Cross-Layer Index Reuse in Sparse Attention for Ultra-Long Contexts

    This article explains a cross-layer index reuse architecture for sparse attention in million-token context inference. It covers why per-layer indexers become a bottleneck at long context lengths, how full indexers can run every N layers while intermediate layers reuse shared top-k indices, the cost model, training and accuracy trade-offs, and the engineering requirements for index caching, incremental decoding, and observability in production inference systems.

    Cross-Layer Index Reuse in Sparse Attention for Ultra-Long Contexts

    1. Background: The Cost Structure of Million-Token Inference

    As large model applications expand from short Q&A to long document understanding, code repository analysis, multi-turn conversational memory, and complex retrieval-augmented generation, context lengths are moving from thousands of tokens toward the million-token range. Longer contexts do not mean computation scales linearly: in standard full attention, the attention matrix grows quadratically with sequence length, and KV cache usage rises rapidly as well. Even with chunked computation, cache reuse, and parallel scheduling, long-context inference still faces triple pressure from memory capacity, memory bandwidth, and latency.

    Sparse attention is a common approach to relieving this pressure. Its core idea is that not every query needs to attend to all historical tokens. Instead, an indexer or scorer selects the most relevant top-k tokens, and attention is computed only over that subset. This reduces attention from a “full set” computation to a “sparse subset” computation, significantly cutting FLOPs. However, sparse attention does not eliminate cost entirely: the indexer itself must still score, sort, or approximately retrieve candidate keys against each query. At million-token scale, if every layer independently runs a full indexer, index selection itself becomes a non-trivial overhead—especially with deep models, large batches, and very long sequences, where the indexer’s memory access and sorting costs accumulate across layers.

    This motivates a design direction worth attention: while preserving the fundamental idea of sparse attention, reduce redundant indexer computation. Cross-layer index reuse is one such approach: rather than having every layer recompute top-k indices, a full indexer runs once every N layers, and subsequent layers reuse the already-selected token indices. With a reuse stride of four, only one full indexer call is executed per four layers, and the remaining layers read the shared indices directly. This design does not change the “compute over a subset of tokens” path of sparse attention, but it substantially reduces the repeated indexing overhead in long-context inference.

    2. Foundational Mechanisms: Combining Latent Representations with Sparse Selection

    To understand cross-layer index reuse, it helps to distinguish two levels of optimization.

    The first level is compression of attention representations. Methods in the family of multi-head latent attention compress keys and values through low-rank latent variables, reducing KV cache storage and memory access overhead. Their value lies in the fact that in long-context inference, cache reads and writes are often more expensive than raw computation, and compressed representations reduce per-layer cache bandwidth pressure. The second level is sparse selection. Sparse attention uses an indexer to select a small set of key tokens per query and computes attention weights only over those tokens. Its value is shrinking the attention computation from the full candidate set down to a top-k subset.

    These two mechanisms compose naturally: latent representations handle “fits in memory, reads fast,” while sparse selection handles “computes less.” But in deep models, sparse selection is not a one-time operation—it happens layer by layer. Each layer has different query representations and, in theory, requires different top-k indices. If every layer runs a full indexer, the number of indexer calls grows linearly with depth. The observation behind cross-layer index reuse is that query representations in adjacent or nearby layers are often strongly correlated, so their index selection results do not necessarily need to be fully independent. Sharing top-k indices within a bounded reuse window can trade a controllable accuracy loss for a significant reduction in indexing overhead.

    3. Core Design of Cross-Layer Index Reuse

    The basic rule of cross-layer index reuse can be summarized as follows: set a reuse stride N, run a full indexer every N layers to generate top-k token indices, and let the remaining layers skip scoring and sorting, instead reading the most recently generated indices to perform sparse attention. Taking N=4 as an example, layer 0 runs the full indexer, and layers 1, 2, and 3 reuse layer 0’s indices; layer 4 reruns the indexer, and layers 5, 6, and 7 reuse layer 4’s indices, and so on.

    From a cost-model perspective, if the total number of layers is L, the per-layer full indexer cost is C_idx, the per-layer sparse attention cost is C_sparse, and the index read-and-reuse cost is C_reuse, then the approximate cost of per-layer indexing is:

    C_total ≈ L × C_idx + L × C_sparse

    The approximate cost after cross-layer reuse becomes:

    C_total ≈ ceil(L / N) × C_idx + L × C_sparse + L × C_reuse

    When C_idx accounts for a significant share of total cost in long-context scenarios, reducing the number of indexer calls directly lowers total cost. A larger stride N means fewer indexer calls, but also higher accuracy risk from diverging layer representations. Choosing N therefore requires balancing cost against quality. A stride of four is a reasonable compromise: it cuts indexer calls to roughly one quarter of the original count without forcing too many layers to share the same indices and accumulate selection bias.

    It is important to emphasize that cross-layer reuse is not simply “copying indices.” When later layers reuse indices, they still compute attention based on their own query representations against the keys and values corresponding to the shared indices. What is shared is the candidate token set, not the attention weights. The index cache must stay consistent with sequence positions, batches, cache paging, and request lifecycles, so that indices are never leaked across different requests or decoding steps.

    The following pseudocode illustrates the scheduling logic only; it is not a real interface:

    1. REUSE_STRIDE = 4
    2. index_cache = {}
    3. def sparse_attention_forward(layer_id, query, kv_cache):
    4. group_id = layer_id // REUSE_STRIDE
    5. if layer_id % REUSE_STRIDE == 0:
    6. topk_indices = run_full_indexer(query, kv_cache)
    7. index_cache[group_id] = topk_indices
    8. else:
    9. topk_indices = index_cache[group_id]
    10. selected_kv = gather_kv(kv_cache, topk_indices)
    11. return attention(query, selected_kv)

    This example highlights two key points: the indexer is scheduled in layer groups, and subsequent layers read shared indices via the group identifier. A production implementation must additionally handle variable-length sequences, batched requests, incremental decoding, and cache eviction.

    4. Training and Accuracy Trade-offs

    The biggest risk of cross-layer index reuse is index quality. Query representations differ across layers—lower layers may focus more on local syntactic information, while higher layers may focus more on semantic associations. If later layers fully reuse earlier layers’ indices, they may miss tokens that are genuinely important for the current layer, weakening long-range dependency modeling. To mitigate this risk, training should let the model adapt to the shared-index pattern—for example, by fixing or randomly sampling the reuse stride during training so later layers learn to perform effective attention within a given candidate set. A lightweight calibration module can also be introduced to re-rank shared indices or supplement them with a small number of additional candidates.

    For evaluation, average perplexity alone is insufficient. Long-document retrieval, multi-hop question answering, cross-file code references, and long-dialogue coreference resolution should also be examined. Useful monitoring metrics include index recall, cross-layer index consistency, quality variation under different reuse strides, and the share of end-to-end time spent in the indexer. If certain layers prove sensitive to index changes, a non-uniform reuse strategy can be adopted: shallow or critical layers keep independent indices while the rest reuse; the stride can also be adjusted dynamically based on input length. Note that the specific stride and its benefits must be validated empirically on the actual hardware and model scale—fixed conclusions should not be applied blindly.

    5. Engineering Implementation and Observability

    Deploying cross-layer index reuse in an inference system requires treating the index cache as a first-class resource. First, the index cache should align with the paged layout of the KV cache, organized by request, layer group, and sequence block, to avoid isolation problems caused by global sharing. Second, during incremental decoding, new tokens may change the top-k selection, so a refresh policy must be defined: whether to refresh per decoding step or per layer group is a trade-off against latency targets. Third, in batched inference, request lengths vary widely, so the index cache must support variable lengths and eviction to prevent long requests from crowding out resources for short ones.

    At the deployment level, inference services can be packaged on general container platforms, with monitoring and alerting for indexer latency, cache hit rate, memory usage, and tail latency; logging can record reuse strides and anomalous requests; and object storage can hold offline evaluation data and model artifacts. In general cloud environments such as Baidu AI Cloud, these categories of services can be used to build elastic scheduling and observability systems, but the actual benefits still depend on model architecture, batching strategy, and hardware configuration.

    6. Conclusion

    The value of cross-layer index reuse lies in pushing “sparse attention” one step further into “sparse index scheduling”: it reduces not only attention computation but also repeated indexer execution. Its design logic is straightforward—run a full indexer every N layers and let subsequent layers reuse the top-k indices, trading a controllable accuracy risk for lower inference cost at million-token contexts. Engineering challenges include index cache consistency, variable-length batching, refresh policies for incremental decoding, and accuracy evaluation. For large-model systems targeting ultra-long contexts, this type of cross-layer reuse is an orthogonal optimization direction worth attention: it composes with latent representation compression, sparse attention, cache paging, and parallel scheduling, together enabling usable inference services at longer context lengths.