Hierarchical Sparse Attention Architecture and Cross-Layer KV Cache Reuse Mechanism Explained

    This article explores an advanced attention architecture designed to optimize long-context inference in Large Language Models. By decoupling historical content states from historical position selection states, the architecture combines Sliding Window Attention for local context with Compressed Sparse Attention for global retrieval. It categorizes attention layers into Full, Reuse, Reindex, and SWA operations to maximize cross-layer KV cache reuse and reduce redundant computation. The article details the hierarchical sparse indexing process, dimensional computation paths, differences between encoding and decoding phases, and key engineering challenges in cache consistency and index storage, offering a flexible balance between local precision and global coverage.

    1. Why Redesign the Attention Architecture?

    In the standard Transformer, each attention layer must process the relationship between the current token and historical tokens. As the context length increases, the overhead of attention computation, the Key-Value (KV) cache, and memory access grows rapidly.

    For autoregressive generation, the current token usually only needs to access previously generated historical content. However, traditional implementations often maintain a complete history of Keys and Values at every layer and repeat similar global selection processes. This approach presents three obvious problems:

    1. Saving the full historical KV at every layer causes memory usage to grow linearly with the number of layers.
    2. Recomputing global attention candidates at every layer leads to redundant computation.
    3. The simultaneous increase in computation and memory access causes throughput to drop in long-context scenarios.

    A more scalable approach is to split “historical content” and “historical position selection” into two distinct types of states:

    • Historical content state: Represented by Keys and Values, providing the actual information at the attended positions.
    • Historical selection state: Represented by sparse indices or Top-K positions, determining which historical tokens the current Query should access.

    These two states do not need to be synchronized and updated at every layer. The content cache can be reused across layers, while indices can be recomputed on demand, forming a more flexible attention architecture.

    2. Overall Structure: Collaboration Between Local and Global Sparse Attention

    This architecture can be understood as consisting of two paths:

    • SWA (Sliding Window Attention): Handles local continuous context.
    • CSA2 (Compressed Sparse Attention): Selects a small number of important positions from longer history.

    SWA only accesses the most recent segment of tokens. For example, with a window size of 128, the current token only interacts with the nearest 128 historical positions. Its advantages are regular computation, continuous memory access, and the stable capture of local semantics, short-distance dependencies, and formatting information.

    However, the windowing mechanism cannot cover distant positions, so a sparse global path is needed for supplementation. Sparse attention does not access all historical tokens; instead, it selects a fixed number of candidate positions from the global history via an indexer. For instance, a Top-K of 512 means each Query ultimately only accesses a few of the most relevant historical positions.

    This way, the model maintains high-density modeling locally and employs low-cost retrieval globally, forming a combined structure of “local completeness, global sparsity.”

    3. Layer-Level Operations: Full, Reindex, Reuse, and SWA

    To reduce redundant work, attention layers can be divided into four types of operations.

    3.1 SWA: Sliding Window Attention Only

    This layer only retains its own local KV, does not generate global KV, and does not recompute global Top-K indices.

    It is suitable for local information modeling tasks, and its computation path is relatively simple. Because the window length is fixed, its computational and memory access scale do not grow infinitely with the full context.

    3.2 Full: Regenerate Global KV and Build Indexes

    The Full layer performs a complete global state update, mainly including:

    1. Generating a new set of global KV based on the current hidden state.
    2. Using the indexer to compute the global candidate positions for each Query.
    3. Passing the global KV and Top-K indices to subsequent layers for reuse.

    The role of the Full layer is similar to establishing a new “snapshot of historical information.” Since hidden states at different depths contain semantic information at different levels, multiple Full layers are not simple repetitions but provide the model with global representations at different abstraction levels.

    3.3 Reuse: Reuse KV and Indexes

    The Reuse layer simultaneously reuses existing global KV and Top-K indices, only needing to use the current layer’s Query to perform attention computation on the cached content.

    This approach significantly reduces the overhead of global cache construction and candidate filtering, but its expressive power depends on whether the previously generated shared state is still suitable for the current layer.

    3.4 Reindex: Reuse KV, but Reselect Positions

    The Reindex layer does not regenerate the global KV. Instead, it uses the existing global content cache while recomputing Top-K positions based on the current layer’s Query.

    It solves a key contradiction: different layers may need to access different historical positions, but they do not necessarily need to re-encode all historical content.

    Therefore, the cost of Reindex mainly comes from index selection rather than full KV construction. For stages requiring stronger inter-layer adaptability, this design is more flexible than simple Reuse.

    4. Significance of Cross-Layer KV Reuse

    Assume a model has 40 layers, but only a few are responsible for creating new global KV, while the rest directly reuse existing results. In this case, global historical information is no longer maintained independently by each layer but is carried by a few shared states.

    The global KV established at different depths can be viewed as historical summaries at different semantic levels:

    • Shallower layers lean more towards lexical, local structural, and basic pattern information;
    • Middle layers lean more towards entities, events, and semantic relationships;
    • Deeper layers may contain task-related abstract information.

    These KVs are not simple compressed copies but multiple sets of representations projected from different hidden states. Subsequent layers can choose one set or combine them based on their own needs.

    It is important to note that cross-layer reuse does not mean all layers completely share parameters. Typically, each layer still retains its own Query projection, output projection, and local window KV. What is shared is the specific global historical content state, not the entire attention module.

    5. Computation Paths Under Given Dimensions

    Based on the original material, the following example dimensions can be used for illustration:

    • Model hidden dimension: 5120
    • Main attention Query heads: 64
    • Main attention head dimension: 512
    • Query latent dimension: 1280
    • Indexer Query heads: 32
    • Indexer head dimension: 128
    • Sparse attention Top-K: 512
    • Sliding window length: 128
    • Encoding phase compression rate: 2
    • Decoding phase compression rate: 1

    Assuming a batch size of 1 and a sequence length of 1024, the input hidden state is:

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

    Some architectures also maintain multi-stream residual flows, such as:

    [ X_{\mathrm{res}}\in\mathbb{R}^{1\times1024\times4\times5120} ]

    After mixing, the multi-stream residuals still need to be mapped back to the model’s main dimension, so the main input shape received by the attention module remains:

    [ [1,1024,5120] ]

    Low-Rank Generation of Query

    Query can adopt a two-stage projection.

    The first stage compresses the high-dimensional hidden state into a lower-dimensional latent variable space:

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

    The dimension change is:

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

    The second stage maps the latent variables to the multi-head Query space:

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

    If the main attention contains 64 heads with a dimension of 512 each, the final Query can be organized as:

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

    The main purpose of this low-rank path is to reduce the computation and parameter overhead of generating all Query parameters directly from the high-dimensional hidden state while preserving the expressive power required for multi-head attention.

    6. How the Hierarchical Sparse Indexer Works

    The task of the hierarchical sparse indexer is not to directly perform the final attention, but to answer one question:

    Which historical positions are most worth visiting for the current Query?

    It can first project the Query into a lower-dimensional index space and then match it against the index representation of historical tokens.

    Assuming the indexer Query shape is:

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

    The historical positions also have corresponding low-dimensional index vectors. Through a dot product or other similarity function, candidate scores between the Query and historical positions can be obtained:

    [ S{i,j}=\langle Q{\mathrm{idx},i},K_{\mathrm{idx},j}\rangle ]

    Subsequently, Top-K selection is performed to obtain the candidate index set:

    [ \mathcal{I}i=\operatorname{TopK}(S{i,:},K) ]

    In actual systems, the indexer can adopt a hierarchical filtering strategy:

    1. First, filter candidate regions at a coarser granularity.
    2. Then, perform fine-grained sorting within the candidate regions.
    3. Finally, retain a fixed number of historical positions.

    This avoids performing high-cost exact sorting on the full historical sequence, making the indexing process itself sparse.

    7. Differences Between Encoding and Decoding Phases

    The encoding phase typically processes longer sequences at once, so it focuses more on parallel computing efficiency, index construction cost, and intermediate cache compression.

    If the encoding compression rate is 2, it can be understood that in certain stages, the historical information or index computation is aggregated, so the indexer does not have to perform the exact same operation for every fine-grained position.

    The decoding phase generates tokens one by one. The single-step sequence length is short, but the historical length continuously increases. At this point, the most important things are:

    • Avoiding regenerating the global KV whenever possible;
    • Reusing existing historical content caches;
    • Recomputing Top-K indices only when necessary;
    • Controlling the bandwidth pressure caused by random memory access.

    Therefore, the decoding part is more suitable for heavy use of Reuse, and Reindex when the Query distribution changes. Setting the compression rate to 1 also implies that the decoding phase usually needs to maintain a more direct positional correspondence to reduce the complexity of incremental updates.

    8. Typical Computation Flow for a Single Token

    Taking a new token in the decoding phase as an example, the computation process can be abstracted as follows:

    1. Input the current hidden state.
    2. Generate the main Query via low-rank projection.
    3. Generate the local sliding window Query, Key, and Value for the current layer.
    4. Access the local KV within the recent window.
    5. Select the global path based on the current layer type:
      • Full: Build new global KV and compute indices.
      • Reuse: Directly use old KV and old indices.
      • Reindex: Use old KV but recompute indices.
    6. Read the sparse global KV based on the Top-K indices.
    7. Merge the local attention results with the global attention results.
    8. Pass through the output projection, residual connection, and subsequent feed-forward network.

    This flow shows that the model does not simply replace full attention with sparse attention, but rather separates historical information of different ranges and update frequencies for separate processing.

    9. Key Issues in Engineering Implementation

    9.1 Consistency of KV Reuse

    When different layers reuse the same set of global KV, it is necessary to clearly define the hidden state version, layer source, and layout information corresponding to the cache. Otherwise, cache mismatch can easily occur, leading to abnormal attention results.

    9.2 Storage Format of Top-K Indices

    Indices usually need to be saved in a compact integer format, and the access order should be as mergeable as possible. If the indices are too discrete, even if the theoretical computation is reduced, actual gains may not be realized due to random memory access.

    9.3 Fusion of Local and Global Results

    The results from SWA and sparse global attention need to be stably fused. The fusion method can be projection after concatenation, weighted summation, or dynamic adjustment through a gating structure. The specific choice should consider numerical stability, hardware characteristics, and training objectives.

    9.4 Consistency Between Training and Inference Paths

    If full attention is used during training and sparse indexing is suddenly switched to during inference, obvious distribution shifts may occur. Therefore, during the training process, the model must be allowed to adapt to the approximation errors brought by index errors, missing candidates, and cache reuse.

    9.5 Cache Eviction Under Long Context

    As the context continues to grow, even with sparse mechanisms, it is necessary to manage local KV, global KV, and index caches. Eviction strategies can be designed based on layer level, time, access frequency, or semantic importance, but it must be ensured that critical historical information is not prematurely deleted.

    10. Conclusion

    The core of this architecture is not simply “reducing attention computation,” but redefining how historical information is organized within the model.

    It splits the attention state into:

    • Local window KV maintained independently by each layer;
    • Global KV generated by a few layers and shared across multiple layers;
    • Top-K position indices that can be updated independently.

    Here, Full is responsible for establishing new global information snapshots, Reuse is responsible for maximizing cross-layer reuse, and Reindex restores inter-layer selection capability without rebuilding historical content. SWA ensures complete modeling of local information, while the sparse global path handles long-distance dependency modeling.

    From a system perspective, this design simultaneously optimizes computation volume, cache capacity, and historical information access methods; from a model perspective, it achieves a more flexible balance between local precision and global coverage. For long-context inference, incremental generation, and resource-constrained deployment scenarios, this concept of “decoupling content cache from position indices” holds strong universal research value.