Cross-Layer Index Reuse for Sparse Attention in Long Contexts

    This article explains how cross-layer index reuse reduces the cost of sparse attention in million-token contexts. It covers how multi-head latent attention and sparse attention work together, why adjacent layers can share the same selected token indices, where the savings come from, the invariants and edge cases to test during implementation, quality risks and fallback strategies, and a staged rollout plan. The goal is to keep latency, cost, and correctness under control at long sequence lengths.

    Where the Problem Comes From

    Million-token contexts have become a normal requirement for code repository understanding, long-document review, and multi-turn agent memory. With full attention, both the compute and the key-value cache grow roughly quadratically or linearly with sequence length, so simply throwing more compute at it rarely brings single-inference cost into an acceptable range. As a result, the industry has adopted “first select a small set of relevant tokens, then run attention only over the selected positions” as a main path: sparse attention shrinks the set that participates in computation, while latent compression shrinks the storage and projection cost per token.

    What is actually expensive is usually not the final small attention pass, but “re-deciding which positions to look at in every layer.” The indexer has to scan a long history and produce scores, sorting, and top-k selection. When there are many layers, this cost recurs and can even outweigh the compute that sparse attention itself saves. Cross-layer index reuse addresses exactly this: the conclusion of a sparse selection is often highly correlated between adjacent layers, so there is no need to retrieve from scratch at every layer.

    How the Two Mechanisms Work Together

    The long-context module can be understood as a pipeline with two clearly separated responsibilities.

    The first stage is multi-head latent attention. Instead of caching every head’s keys and values at the full hidden dimension as-is, it first compresses historical information into a lower-dimensional latent representation and then restores or projects per head when attention is computed. The benefit is a smaller key-value cache and lower memory-bandwidth pressure during both prefill and incremental decoding; the cost is an extra transform between latent space and head space, and an overly aggressive compression ratio loses fine-grained matching ability. In practice, the latent dimension, number of heads, and head dimension should be tuned together rather than chasing the smallest possible cache.

    The second stage is sparse attention. The model maintains a lightweight indexer that scores the correlation between the current position and historical positions, keeping only the top-k (sometimes plus a sliding window, global tokens, or special markers). Attention is computed only over this subset. The idea is unchanged: important positions get fine-grained computation, and the rest never enter the main attention matrix.

    Stacked together, the cache becomes smaller and the matrix becomes thinner, but if the indexer runs in full at every layer, the sorting and memory access on long sequences become a new hotspot.

    What Cross-Layer Reuse Does

    Cross-layer index reuse is a scheduling optimization for sparse retrieval; it does not change the principle of “only looking at selected tokens.” A typical approach runs the full indexer once every few layers, caches the selected token indices, and lets the following layers reuse the same set of indices directly, recomputing only the attention weights and outputs at those positions.

    A clear, easy-to-implement cadence is “run a full retrieval once every four layers”:

    • Layer 4n+1 runs the full indexer to obtain the top-k historical indices for the current position, optionally with a local window and a few always-retained global positions.
    • The next three layers no longer scan the full history; they only read this index and perform sparse attention over the latent keys and values.
    • On reaching the next retrieval layer, the indices are updated to absorb the changes that have already occurred in the representation space.

    An interval of four is an engineering compromise, not the only valid value. A shorter interval keeps the selection closer to the current layer’s representation but costs more retrieval; a longer interval yields more reuse benefit, but stale indices may miss positions that only become important in later layers. The interval should be chosen based on the task distribution rather than a fixed slogan.

    Why Adjacent Layers Can Share Indices

    The hidden states of adjacent layers are connected through residual connections, and attention patterns usually change smoothly rather than fully reordering “who to look at” at every layer. The indexer outputs a discrete set and is not sensitive to small fluctuations in scores: as long as the truly relevant positions stay near the top-k boundary, reuse will not immediately break the information path.

    This does not mean the indices are valid forever. As layers go deeper and the task shifts from “finding the source text” to “composing reasoning,” relevant positions may migrate. So reuse must come with an invalidation strategy rather than using one index all the way to the end of the model. In practice, at least three kinds of positions should be retained to avoid overly aggressive discrete selection:

    1. Local window: the most recent tokens are almost always relevant to the current generation and should be retained by a fixed rule, without competing in the indexer.
    2. Structural anchors: a small number of global positions such as section starts, headings, and system constraints can be force-selected.
    3. Retrieval set: the remaining budget goes to top-k, with the retrieval layer periodically refreshing.

    Where the Cost Savings Roughly Come From

    Qualitatively, the complexity of full indexing depends on both history length and number of layers. If a full retrieval runs only every four layers, the indexer’s main scan becomes roughly one quarter of the original; sparse attention, the feed-forward network, and latent projection still run per layer. So the end-to-end time will not become one quarter, but in the prefill stage with million-token inputs where the indexer dominates, the savings are usually most visible.

    Memory access also matters. Long-sequence inference is often bandwidth-bound: repeatedly reading the full history of keys and repeatedly writing sort buffers hurts throughput more than a few extra small matrix multiplications. After reusing indices, non-retrieval layers only gather keys and values by the sparse indices, reducing the number of gather accesses and improving cache hits. Latent compression further reduces the bytes per gather, so the two benefits multiply rather than simply add.

    Do not write a “theoretical multiplier” as an acceptance metric. Real speedup depends on the indexer implementation, the sequence-length distribution, batch size, whether chunked prefill is enabled, and how efficiently the hardware handles irregular gathers. Before launch, you must compare “per-layer retrieval” against “interval-based reuse” on a fixed dataset in terms of latency, throughput, peak memory, and answer quality.

    Invariants to Hold During Implementation

    Cross-layer reuse is easy to get wrong at boundary conditions. It is worth writing the following as tests rather than only in a design document.

    Index lifecycle. Indices are stored per request, per sequence, and per head or head group, and must follow the same paging rules as the key-value cache. When a sequence is truncated, a prefix cache hits, or only part of the history is reused, stale indices pointing to freed pages will cause silent misreads. After a retrieval layer updates, the snapshot visible to subsequent layers should be replaced atomically, to avoid a layer reading a half-new, half-old set.

    Causality and deduplication. During generation, only tokens before the current position can be seen. Reused indices must likewise not include future positions. After merging the window, anchors, and top-k, deduplicate; otherwise the effective context is shorter than configured, and attention normalization is distorted by duplicate positions.

    Variable length and padding. When sequence lengths differ within a batch, the effective k of top-k may be smaller than the configured value. Use a mask to mark invalid slots, and never treat padding positions as real history. Incremental decoding appends only new tokens each step, and the retrieval layer can update scores only for the newly added positions; but if the implementation chooses to “re-rank the whole segment,” it must stay aligned with the training or reference implementation, otherwise the latter half of long text will drift.

    Numerical path. Skipping the indexer in non-retrieval layers does not mean you can skip the normalization or scaling related to the index. The denominator of sparse attention should include only the actually selected positions. A missing mask lets probability mass flow into invalid indices, which shows up as gibberish or repetition in the later part of long text.

    The scheduling logic can be sketched as:

    1. interval = 4
    2. for layer in layers:
    3. if layer.id % interval == 0:
    4. index = indexer.topk(query, latent_keys, k, window, anchors)
    5. cache.store(seq_id, layer.group, index)
    6. else:
    7. index = cache.load(seq_id, layer.group)
    8. out = sparse_attention(query, latent_kv, index)

    This only describes the control flow. A real system must also fuse indexer scoring, paged gathering, and the attention kernel to avoid materializing a huge intermediate tensor and then gathering, which would eat up the gains.

    Quality Risks and Fallback

    The error introduced by reuse is discrete: either a key position is still in the set, or it is pushed out. It rarely shows up as uniform small noise, and more often as a certain class of evidence suddenly disappearing, such as citing the wrong section in the latter half or mixing up tool arguments. Evaluation cannot look only at average loss; it should also cover:

    • Needle-in-a-haystack retrieval: the answer appears only once in the text, checking whether it can still be hit at different depths.
    • Multi-hop composition: requiring two or more distant pieces of evidence at the same time.
    • Recent-instruction following: when the system constraint is at the beginning and task details are at the end, checking whether anchors and window are sufficient.
    • Short decoding after ultra-long prefill: confirming that when reuse mainly optimizes prefill, decoding correctness is not broken.

    If quality degradation concentrates in a certain layer group, first shorten that group’s reuse interval, or raise k and the window, rather than globally disabling sparsification. Training and inference must use the same selection rule; only reusing lazily at inference while retrieving per layer during training will amplify the distribution gap. If the model was not trained with this schedule and you treat reuse as a pure inference-time approximation, you must set up quality guards and, when necessary, fall back to per-layer retrieval for high-risk requests.

    Integration With the Rest of the System

    Long-context optimization rarely works in isolation. The paged key-value cache determines whether indices are stable; the prefix cache determines whether repeated system prompts can skip retrieval; chunked prefill determines whether the indexer can score in a streaming, block-by-block fashion without putting the entire history into memory at once. For observability, record retrieval-layer time, sparse-attention time, gathered bytes, and the invalid-index ratio separately; otherwise you cannot tell whether the bottleneck is still in indexing or has shifted to the feed-forward network or communication.

    For capacity planning, changing “one index buffer per layer” to “one per layer group” reduces the number of buffers as the interval grows, but each buffer serves multiple subsequent layers and lives longer, so the eviction policy should be per group rather than per layer. With multi-replica inference, indices belong to request state and cannot be synchronized by only syncing the token cache while omitting the index snapshot.

    Rollout Order

    It is best to proceed from low to high risk. First, implement correct sparse attention with per-layer retrieval in offline replay and align with short-context results. Then enable latent compression and confirm the cache-byte and accuracy curves. Then reuse indices only in deep layers or every four layers, comparing needle retrieval and business samples. Finally, make the interval, k, and window configurable, and select automatically by request length: short sequences gain little from reuse and can retrieve per layer directly; only enable cross-layer reuse beyond a set threshold.

    What this yields is not a proprietary trick for a specific model, but a transferable principle for long-context inference: selective attention decides where to look, the latent representation decides the cost of looking, and cross-layer reuse decides how many times the selection itself must be computed. Only by measuring these three things separately and guarding each one can you hold latency, cost, and correctness together in million-token scenarios.