Computation Paths and State Reuse in Efficient Sparse Attention Architectures

    Long-context models face a core tension: attention computation and KV cache grow rapidly with sequence length. This article walks through the token-level computation path of a hierarchical sparse attention architecture, explaining how sliding window attention, global KV generation, Top-K index recomputation and reuse, cross-layer KV sharing, a hierarchical sparse indexer, and conditional execution (CED) split historical information into two independently updatable shared states—content cache and position selection. It covers layer type classification (Full, Reindex, Reuse, sliding-window), example dimension configurations, execution flow pseudocode, and engineering considerations such as cache layout, index consistency, memory footprint, and numerical stability.

    Computation Paths and State Reuse in Efficient Sparse Attention Architectures

    One of the central challenges of long-context models is that attention computation and the KV cache grow rapidly with sequence length. Common efficient attention designs do not simply choose between “full global attention” and “pure local window attention.” Instead, they decompose historical information at different granularities: local windows handle nearby dependencies, global sparse indexing handles long-range recall, and cross-layer sharing reduces duplicated state. This article follows the actual computation path of a single token through the model and analyzes how a class of hierarchical sparse attention architectures turns “historical content caching” and “historical position selection” into two shared states that can be updated independently—via sliding window attention, global KV generation, Top-K index recomputation and reuse, cross-layer KV reuse, a hierarchical sparse indexer, and conditional execution and scheduling.

    1. Background: Regenerating Historical State Is the Main Waste

    In standard Transformer attention, every layer generates Query, Key, and Value from its own hidden state and maintains its own KV cache. For long sequences, this creates two kinds of duplication:

    1. Content duplication: different layers re-express the content of historical tokens with their own projection matrices, producing multiple copies of global KV.
    2. Position-selection duplication: different layers recompute “which historical positions deserve attention,” i.e., Top-K indices or sparse routing results.

    If every layer fully performs both steps, compute and memory grow linearly with the number of layers. A better approach is to split historical information into two states:

    • Historical content cache: the Key/Value representations, describing what the historical tokens are;
    • Historical position selection: the Top-K indices or sparse routing results, describing which historical positions the current token should attend to.

    The two can be updated separately: some layers generate new global KV, some layers reuse existing global KV but re-select indices, and some reuse both. This is the core idea behind dual-state shared attention.

    2. Overall Computation Path and Layer Types

    In a token’s forward path, every layer still keeps its own main Query and sliding window attention KV, but global KV and Top-K indices are no longer generated independently per layer. Layers can be abstracted into four types:

    Type Meaning Global KV Top-K Index
    S Sliding window attention only Not produced Not used or local only
    F Full Generates new global KV Computes new Top-K indices
    R Reuse Reuses existing global KV Reuses existing Top-K indices
    I Reindex Reuses existing global KV Recomputes Top-K indices

    Consider an example configuration with 40 layers: only 4 layers actually generate new global KV; only 8 layers perform new index selection—the 4 Full layers plus 4 Reindex layers; the remaining 30 layers directly reuse earlier index results. Meanwhile, all 40 layers keep their own sliding window KV and main Query. The direct effect is that global KV generation drops from “once per layer” to a handful of times, index selection drops from “once per layer” to a handful of times, while fine-grained modeling of nearby context is preserved in every layer.

    It is worth emphasizing that layers 2, 8, and 14 can each produce three independent global KV sets. They correspond to hidden states at different depths and thus retain historical information at different levels: shallow global KV tends to capture local patterns and lexical information, while deep global KV leans toward semantic and task-relevant information. During cross-layer reuse, different layers can reference global KV pools at different depths, reducing duplicated generation while avoiding a single, overly homogeneous historical representation shared by all layers.

    3. Dual-State Sharing: Decoupling KV Content from Top-K Indices

    The most notable design in this architecture is decoupling the historical content cache from historical position selection. In traditional approaches, KV and indices are bound to the same layer: indices are selected based on the KV generated in that same layer. Dual-state sharing instead allows:

    • Reuse: reuse existing global KV and existing Top-K indices—cheapest computation;
    • Reindex: reuse existing global KV but recompute Top-K indices, suitable when the current layer’s Query distribution disagrees with earlier selections;
    • Full: generate new global KV and compute new Top-K indices, suitable for layers that need fresh historical representations.

    The decoding stage often uses the Reindex mechanism: it recomputes “which configuration of global KV to use” rather than regenerating global KV. In other words, Reindex updates the selection result, not the content cache. This lets the current layer re-decide which historical positions to attend to based on its own Query, without increasing global KV generation cost.

    From a state management perspective, the system must maintain two sets of shared state:

    1. Global KV pool: multiple content caches partitioned by depth or layer group;
    2. Top-K index table: sparse selection results cached per layer, per token, or per sequence block.

    The two states have different lifecycles: the global KV pool is expensive to generate and updated infrequently; the Top-K index table is relatively cheap to compute and its update frequency is tunable. Decoupling them allows finer-grained trade-offs between “content freshness” and “selection freshness.”

    4. Basic Dimensions and the Query Generation Path

    To make the computation path concrete, here is an example dimension configuration. These values illustrate tensor flow and design trade-offs only—they do not represent a fixed interface or performance commitment.

    Parameter Example Value
    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 size 128
    Encoder compression ratio 2
    Decoder compression ratio 1

    With Batch=1 and sequence length S=1024, the input tensor is:

    [
    X \in \mathbb{R}^{1 \times 1024 \times 5120}
    ]

    If there are multiple residual mixing streams, the internal representation can be:

    [
    X_{\mathrm{mix}} \in \mathbb{R}^{1 \times 1024 \times 4 \times 5120}
    ]

    but after mixing, the dimension returns to 5120 before entering the attention sublayer. Query generation typically happens in two steps. The first step performs low-rank compression:

    [
    Q_{\mathrm{latent}} = X W_q^A
    ]

    with the dimension change:

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

    The second step projects into 64 main attention heads:

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

    The point is to first compress the Query representation into a low-rank latent space, then project into the multi-head space, reducing projection parameters and compute. Meanwhile, the indexer uses its own set of Query heads with a smaller head dimension—for example, 32 heads with 128 dimensions each. The indexer does not need to match the main attention dimensions; it only needs to perform coarse filtering of “which historical positions should enter the Top-K” in a lower-dimensional space.

    5. Fusing Sliding Windows with Global Sparse Recall

    Every layer keeps its own sliding window KV and main Query, with an example window size of 128. Sliding window attention handles nearby dependencies; its complexity scales roughly with sequence length times window size rather than quadratically. For local syntax, adjacent token interaction, and positional continuity, window attention is usually sufficient.

    Windows alone cannot cover long-range dependencies, so global sparse recall is needed. The global part does not perform full attention directly; instead, a hierarchical sparse indexer selects the Top-K historical positions, with an example Top-K of 512. The indexer computes relevance between low-dimensional index Queries and compressed global KV representations, then selects the highest-scoring K positions or blocks. Since K is much smaller than the sequence length, actual global attention computation is confined to the sparse candidate set.

    The fusion can be expressed as:

    [
    \mathrm{Out} = \mathrm{Attention}{\mathrm{SWA}}(Q, KV{\mathrm{swa}}) + \mathrm{Attention}{\mathrm{sparse}}(Q, KV{\mathrm{global}}, \mathcal{I}_{\mathrm{topK}})
    ]

    where (\mathcal{I}_{\mathrm{topK}}) is the index set actually used by the current layer. For a Reuse layer, the index set comes directly from cache; for a Reindex layer, it is recomputed from the current layer’s index Query; for a Full layer, both global KV and the index set are updated.

    6. Execution Flow for Full / Reindex / Reuse

    Writing the mechanism as pseudocode makes the state flow clearer:

    1. for layer in range(num_layers):
    2. q = project_query(x) # [B, S, H, D]
    3. q_idx = project_index_query(x) # [B, S, H_idx, D_idx]
    4. swa_kv = update_swa_cache(x, layer) # independent per layer
    5. if layer in FULL_LAYERS:
    6. global_kv = build_global_kv(x) # generate new global KV
    7. topk_idx = sparse_index(q_idx, global_kv, topk=K)
    8. elif layer in REINDEX_LAYERS:
    9. global_kv = select_global_kv(layer) # reuse existing content
    10. topk_idx = sparse_index(q_idx, global_kv, topk=K)
    11. else:
    12. global_kv = select_global_kv(layer)
    13. topk_idx = reuse_index(layer) # reuse existing selection
    14. out = attention(q, swa_kv, global_kv, topk_idx)
    15. x = mix_residual(x, out)

    This pseudocode highlights three key points:

    1. The main Query is generated at every layer: each layer retains its own query perspective—this is not simple layer skipping.
    2. Sliding window KV is kept at every layer: nearby-context modeling does not rely on cross-layer sharing, preventing local information from being over-compressed.
    3. Global KV and Top-K indices are updated according to layer type: content cache and position selection are no longer tightly coupled.

    In the 40-layer example, global KV generation occurs in only 4 layers and index selection in 8 layers; the rest reuse. Actual gains depend on the compression operator, indexer overhead, memory bandwidth, and hardware access patterns, and cannot simply be equated with the “layer reduction ratio.” But the design direction is clear: centralize the generation of expensive, infrequently updated global state, and share cheap, reusable selection results broadly.

    7. Hierarchical Sparse Indexer and Compression Ratio

    The value of a hierarchical sparse indexer lies in “coarse filtering with cheap representations, then precise computation with main attention.” The indexer has fewer Query heads and a smaller head dimension, so indexing is cheaper than main attention. In the example, the indexer uses 32 heads with 128 dimensions each, while main attention uses 64 heads with 512 dimensions each. The indexer only outputs the Top-K position set, not the final attention result.

    The compression ratio affects the cache density of global KV. With an encoder compression ratio of 2 and a decoder compression ratio of 1, the granularity of historical KV compression along the sequence dimension differs: the encoding stage can aggregate historical blocks more aggressively, while decoding is more conservative to preserve autoregressive generation quality. A larger compression ratio yields a more compact cache and less indexer/attention memory traffic, but with a higher risk of detail loss; a smaller ratio preserves more fidelity but increases memory and bandwidth pressure.

    Hierarchical designs typically have two or three levels: first select candidate blocks at the block level, then select tokens or finer-grained positions within blocks. This way, Top-K does not need to score every token in the full sequence but first narrows the candidate range. For long sequences, this two-level filtering significantly reduces indexer overhead while preserving long-range recall.

    8. CED: Conditional Execution and Scheduling

    CED can be understood as a general term for conditional execution and scheduling mechanisms. In this architecture, CED does not simply “skip layers”; it performs conditional branch scheduling over global KV generation, index recomputation, and attention fusion. For example:

    • If the current layer is a Full layer, execute global KV generation and index computation;
    • If the current layer is a Reindex layer, execute only index recomputation;
    • If the current layer is a Reuse layer, read cached indices directly;
    • For certain sequence blocks or token positions, upgrade to Reindex based on index confidence, window coverage, or cache freshness.

    The engineering value of CED is combining “fixed layer types” with “dynamic conditions.” Fixed layer types provide a stable computation graph and cache layout, while dynamic conditions allow extra computation when sequences are long, sparse recall is unstable, or the distribution shifts. The specific scheduling rules depend on the implementation; this article does not assume a fixed policy. But the design principle is clear: expensive branches should trigger rarely, be predictable, and be cache-friendly; cheap branches should be shared as widely as possible.

    9. Engineering Considerations and Risks

    First, cache layout must distinguish content cache from index cache. The global KV pool can be partitioned by depth or layer group; the index table can be stored per layer, per token, or per sequence block. Their update frequencies differ, so they should not be managed under the same lifecycle.

    Second, balance index consistency between Reuse and Reindex. Long-term index reuse may cause the current layer’s Query to mismatch historical selections, weakening long-range recall; frequent reindexing increases indexer overhead. A hybrid policy can be set based on layer depth, sequence position, or index confidence.

    Third, multiple global KV copies increase memory usage. Although generation is reduced, keeping multiple global KV sets at different depths still consumes cache space. Compression ratios, block-based storage, and offloading strategies should be combined to control peak memory.

    Fourth, verify the complementarity of the sliding window and global Top-K. Too small a window increases global recall pressure; too large a window weakens sparsification benefits. Too small a Top-K risks missed recall; too large a Top-K increases attention compute. Ablation experiments should determine the combination of window size, Top-K, and compression ratio.

    Fifth, monitor numerical stability and indexer recall quality. The low-dimensional indexer reduces overhead but may lose ranking precision. During training or inference, monitor index coverage, window hit rates, and the global attention contribution to prevent sparse selection from degenerating into local attention.

    10. Summary

    The core of this class of hierarchical sparse attention architectures is not merely “computing fewer layers.” It splits historical information into two shared states that can be updated independently: global KV content cache and Top-K position selection. Every layer keeps its main Query and sliding window KV to preserve local modeling; a few Full layers generate new global KV, a few Reindex layers recompute indices, and many Reuse layers reuse directly; global KV pools at different depths retain historical information at different levels; the hierarchical sparse indexer and compression ratio control global recall cost; and CED-style conditional execution schedules expensive branches. Understanding this token-level computation path makes it easier to evaluate the benefit boundaries, cache design challenges, and tuning directions of this architecture in long-context scenarios.