Hierarchical Attention Architectures for Efficient Long-Context Models

    Explore how hierarchical attention combines sliding-window attention, sparse global retrieval, and cross-layer KV cache reuse to support efficient long-context processing. This article explains Full, Reuse, and Reindex layers, illustrative tensor flows, hierarchical indexing, residual streams, and the engineering trade-offs involved in managing shared attention state.

    1. Why Attention Architectures Need a Redesign

    Standard self-attention matches each query against all eligible keys in the sequence. As context length (S) increases, attention computation and access to intermediate state become increasingly expensive. In long-context inference, matrix multiplication is only part of the cost:

    1. Each layer stores its own historical keys and values.
    2. Each new token must be scored against many historical positions.
    3. Different layers often select similar historical information repeatedly.
    4. KV cache capacity grows linearly with both layer count and sequence length.
    5. Memory access can become a greater bottleneck than computation itself.

    A more efficient design separates historical attention state into two categories and manages queries and retrieval indices independently:

    • Local historical state: Maintained independently by each layer, primarily for short-range dependencies.
    • Global historical state: Generated by selected layers and shared across multiple subsequent layers.
    • Historical position indices: Specify which global historical positions a layer should access.
    • Query representations: Still generated by each layer from its current hidden state for the final attention computation.

    The central idea is not simply to reduce the number of attention heads. It is to decouple cached historical content from historical position selection, allowing them to be reused, updated, and compressed separately.

    2. The Computation Path: Local and Global Attention

    Let the input hidden states be:

    [
    X\in\mathbb{R}^{B\times S\times d_{\text{model}}}
    ]

    where:

    • (B) is the batch size.
    • (S) is the sequence length.
    • (d_{\text{model}}) is the model hidden dimension.

    This architecture divides a layer’s attention computation into two complementary paths.

    Sliding-Window Attention: SWA

    Sliding-window attention accesses only a fixed neighborhood around the current position. With window size (W), the token at position (t) attends to:

    [
    [\max(1,t-W+1),t]
    ]

    This keeps the computation and cache access range relatively stable. SWA is well suited to local syntax, short-range references, and relationships within contiguous text.

    On its own, however, it has limited direct access to distant information. A global attention path supplements it.

    Compressed or Sparse Global Attention: CSA

    The global path does not attend to every historical token. Instead, an indexer selects the top (K) candidate positions, and the current query interacts only with the global keys and values at those positions.

    When (K\ll S), the global attention access set shrinks from the full history to a bounded sparse selection.

    The aggregation still follows the familiar attention formulation:

    [
    \operatorname{Attn}(Q,K,V)
    =
    \operatorname{Softmax}
    \left(
    \frac{QK^\top}{\sqrt{d}}
    \right)V
    ]

    Here, however, the keys and values used in the computation are restricted to:

    [
    K{\mathcal I},V{\mathcal I}
    ]

    where (\mathcal I) is the historical position set produced by the indexer.

    A layer’s attention output can therefore be expressed abstractly as:

    [
    H^{(l)}
    =
    \operatorname{SWA}^{(l)}(X^{(l)})
    +
    \operatorname{CSA}^{(l)}(X^{(l)})
    ]

    The local path handles nearby dependencies, while the global path aggregates selected long-range information.

    3. Layer Scheduling: Full, Reuse, Reindex, and Local-Only Layers

    To control global cache and indexing costs, not every layer rebuilds global state. Instead, different layers take on different responsibilities.

    Full: Generate Global KV and Select Positions

    A Full layer performs both parts of global state construction:

    • Generate new global keys and values from the current hidden states.
    • Use an indexer to select the top (K) historical positions.

    Abstractly:

    [
    (Kg,V_g)=f{\text{kv}}(X)
    ]

    [
    \mathcal I=f{\text{index}}(Q{\text{idx}},K_{\text{idx}})
    ]

    Full layers have the highest computation cost, but they produce new global semantic representations that subsequent layers can share.

    Reuse: Share Global KV and Position Indices

    A Reuse layer neither regenerates global KV nor recomputes position selection. It uses previously cached state:

    [
    (K_g,V_g,\mathcal I)
    \leftarrow
    (K_g^{\text{cached}},V_g^{\text{cached}},\mathcal I^{\text{cached}})
    ]

    This mode is useful when adjacent layers need similar historical information. It can reduce repeated projections, index matching, and memory traffic.

    Reindex: Share Global KV but Select Positions Again

    Reindex is a key part of the architecture. It keeps the global KV cache unchanged but uses the current layer’s indexing query to select a new top-(K) position set:

    [
    \mathcal I^{(l)}
    =
    f{\text{index}}^{(l)}
    \left(
    Q
    {\text{idx}}^{(l)},K_{\text{idx}}^{\text{cached}}
    \right)
    ]

    The layer then accesses the shared global cache using those new indices:

    [
    \operatorname{CSA}^{(l)}
    =
    \operatorname{Attn}
    \left(
    Q^{(l)},
    K_g[\mathcal I^{(l)}],
    V_g[\mathcal I^{(l)}]
    \right)
    ]

    Content updates and position selection are therefore independent. Global historical content can remain unchanged while different layers retrieve different positions according to their own queries.

    S: Sliding-Window-Only Layers

    An S layer performs only SWA. It does not generate global KV or run global indexing.

    These lower-cost layers provide additional local feature extraction and transformations between layers.

    4. Why Generate Global KV at Multiple Depths?

    If the entire network shares only one global KV cache, every layer must rely on historical representations from the same depth. Yet layers at different depths tend to represent information at different levels:

    • Shallow layers are generally closer to lexical information, local structure, and positional relationships.
    • Middle layers are better suited to representing entities, events, and paragraph-level relationships.
    • Deep layers often encode more abstract task semantics and reasoning information.

    Generating independent global KV caches at selected depths gives later layers access to historical representations at different semantic levels.

    This creates a hierarchical memory system:

    [
    \mathcal M=
    {
    (K_g^{(1)},V_g^{(1)}),
    (K_g^{(2)},V_g^{(2)}),
    (K_g^{(3)},V_g^{(3)})
    }
    ]

    These caches are not simple copies. They originate from different hidden states and therefore contain different information distributions.

    5. Why Decoding Favors Reindexing

    During autoregressive decoding, each step adds only one or a few tokens. Reconstructing the entire historical global KV state usually offers limited benefit because most historical content is already cached.

    A more suitable strategy is to:

    1. Retain the existing global KV cache.
    2. Update candidate positions using the latest query.
    3. Access only the top (K) historical positions relevant to the current token.
    4. Continue maintaining each layer’s independent sliding-window KV cache.

    The distinction can be summarized as:

    [
    \text{Cached content updates}
    \approx
    \text{low-frequency updates}
    ]

    [
    \text{Historical position selection}
    \approx
    \text{per-layer or per-step updates}
    ]

    This lets retrieval adapt to the current token’s semantics without repeatedly reconstructing the full historical state.

    A full update primarily changes stored content. Reindexing primarily changes the access plan. For long-form generation, updating the access plan often aligns better with incremental decoding.

    6. Illustrative Dimensions and Tensor Flow

    The following configuration illustrates the architecture:

    Parameter Illustrative value
    Model hidden dimension (d_{\text{model}}=5120)
    Attention heads 64
    Main attention head dimension 512
    Low-rank query dimension 1280
    Indexer query heads 32
    Indexer head dimension 128
    Sparse attention top-(K) 512
    Sliding-window size 128
    Encoding-stage compression ratio 2
    Decoding-stage compression ratio 1

    These values describe an example structure, not a mandatory configuration for every implementation.

    Assume:

    [
    B=1,\quad S=1024
    ]

    The input tensor is:

    [
    X\in\mathbb{R}^{1\times1024\times5120}
    ]

    Query Generation

    A low-rank projection first produces a latent query representation:

    [
    Q_{\text{latent}}=XW_q^A
    ]

    The shape changes as follows:

    [
    [1,1024,5120]
    \rightarrow
    [1,1024,1280]
    ]

    The latent query is then projected into the multi-head attention space:

    [
    Q=Q_{\text{latent}}W_q^B
    ]

    After reshaping:

    [
    Q\in\mathbb{R}^{1\times1024\times64\times512}
    ]

    The low-rank factorization performs an intermediate query transformation in a smaller space before expanding into the multi-head representation. This reduces part of the projection parameter count and computation.

    Indexer Queries

    The indexer does not necessarily use the full-dimensional main query. Instead, it constructs a more compact representation:

    [
    Q{\text{idx}}
    \in
    \mathbb{R}^{B\times S\times h
    {\text{idx}}\times d_{\text{idx}}}
    ]

    For the illustrative configuration:

    [
    Q_{\text{idx}}
    \in
    \mathbb{R}^{1\times1024\times32\times128}
    ]

    The indexer estimates the importance of historical positions rather than performing the final value aggregation. A simplified position-scoring expression is:

    [
    s{t,j}
    =
    \left\langle
    q
    {\text{idx},t},
    k_{\text{idx},j}
    \right\rangle
    ]

    It then selects the (K) highest-scoring positions:

    [
    \mathcal It=\operatorname{TopK}_j(s{t,j})
    ]

    The main attention computation reads only the global KV entries associated with (\mathcal I_t).

    7. Benefits and Costs of Cross-Layer Cache Reuse

    Cross-layer KV reuse offers several direct benefits:

    1. Lower KV cache capacity requirements: A complete global history does not need to be stored separately for every layer.
    2. Fewer repeated projections: Some layers can skip global key and value generation.
    3. Less full-history attention work: Final sparse attention operates on a small candidate set.
    4. Potentially higher decoding throughput: Incremental processing emphasizes index updates rather than repeated content writes.
    5. Opportunities for better hardware utilization: Bounded candidate sets can support batching and kernel optimization.

    These benefits introduce engineering trade-offs:

    • Shared cache lifecycles are more complex to manage.
    • Layers depend on caches produced by other layers.
    • Reindexing can become a new bottleneck.
    • Sparse reads can suffer from noncontiguous memory access.
    • Multiple global caches require careful memory layout.
    • Cache invalidation, sequence truncation, and dynamic batch merging need explicit handling.

    Reducing attention aggregation work does not automatically make retrieval inexpensive or guarantee higher end-to-end throughput. Implementations still need suitable memory layouts, batched indexing, asynchronous prefetching, and cache reclamation strategies.

    8. The Role of a Hierarchical Sparse Indexer

    A hierarchical sparse indexer is a subsystem dedicated to retrieving historical positions. Its operation can be understood in three stages.

    Stage 1: Generate Compact Queries and Keys

    Hidden states are mapped into a lower-dimensional space to produce indexing queries and keys.

    Because retrieval only needs to estimate relevance, rather than carry the complete value representation, it can use smaller representations.

    Stage 2: Filter Candidates Hierarchically

    A low-cost representation first filters out many irrelevant positions. More precise scoring is then applied to the remaining candidates.

    This avoids performing high-dimensional matching against the entire context at every retrieval step.

    Stage 3: Return Top-(K) Indices

    The indexer returns a bounded set of positions:

    [
    \mathcal I_t={i_1,i_2,\ldots,i_K}
    ]

    Main attention then reads the fuller KV representations at those positions.

    The resulting two-stage design combines lightweight retrieval with precise aggregation.

    9. CED and Compressed Residual Streams

    Beyond attention caching, these models may also use multi-branch residual streams. Such a stream can be represented as:

    [
    X{\mathrm{mHC}}
    \in
    \mathbb{R}^{B\times S\times r\times d
    {\text{model}}}
    ]

    where (r) is the number of residual branches.

    Different branches can carry information from different levels or computation paths. A mixing operation returns the representation to the main model dimension:

    [
    X{\text{out}}
    =
    \operatorname{Mix}(X
    {\mathrm{mHC}})
    \in
    \mathbb{R}^{B\times S\times d_{\text{model}}}
    ]

    CED-style mechanisms should not be understood simply as adding channels. Their emphasis is on compression, branching, and fusion to make information flow between layers more controllable.

    They may help establish more stable paths between local features, global memory, and deeper semantic representations. However, additional residual branches also complicate normalization, fusion, and memory management, making numerical stability and training efficiency important considerations.

    10. How Work Is Distributed Across the Network

    An illustrative 40-layer network can divide attention responsibilities as follows:

    • A small number of layers generate new global KV.
    • Some layers recompute top-(K) position indices.
    • Many layers reuse existing global state.
    • Every layer maintains its own local-window KV.
    • Every layer generates a main query from its own hidden state.

    The architecture does not simply remove attention layers. It assigns different update frequencies to work that would otherwise be repeated at every layer.

    State type Update frequency Primary role
    Local-window KV Continuously, in every layer Model short-range dependencies
    Global KV At selected layers or less frequently Store long-range historical content
    Top-(K) indices On demand Determine which historical positions to access
    Main query In every layer Express the current layer’s retrieval needs
    Residual stream Propagated through every layer Fuse features from multiple paths

    The governing pattern is less frequent content updates, on-demand position selection, and continuous local-state updates.

    11. Key Implementation Considerations

    Separate Cache Owners from Cache Consumers

    Only designated layers should write global KV. Other layers should read the cache or update retrieval indices without allocating duplicate global state.

    Keep Index and KV Lifecycles Consistent

    When a global KV cache is replaced, indices referencing the old cache must not remain in use. Conversely, reindexing alone should not delete the underlying KV state.

    Define Training and Inference Paths Explicitly

    Training usually operates on complete sequences and can use batched indexing. Inference must handle incremental token updates. These paths may require different implementation strategies.

    Optimize Sparse Memory Access

    Top-(K) selection reduces the size of the final attention computation, but scattered reads can still limit throughput.

    Index sorting, blocked access, and cache layout therefore deserve attention alongside arithmetic cost.

    Add Observability

    Useful metrics include:

    • Index hit rate.
    • Cache reuse rate across layers.
    • Average candidate count.
    • Cache read and write volume.
    • End-to-end latency.

    Theoretical complexity alone is not enough to assess system efficiency.

    Conclusion

    Hierarchical attention redefines what long-context models share across layers. Rather than sharing complete attention outputs, layers share reusable historical content representations. Each layer retains an independent query and can select historical positions according to its current semantic needs.

    Sliding-window attention handles local dependencies. Global KV provides long-range memory. Reindexing adapts the retrieval scope, while hierarchical indexing reduces retrieval cost. Multi-branch residual streams can help information move between these paths.

    Together, these components form a design built around dense local attention, sparse global attention, and cross-layer cache reuse.

    The main architectural opportunity is not any single attention variant. It is the coordinated design of caches, indices, hierarchical representations, and residual paths to balance context capability, memory consumption, and inference efficiency.