Cross-Layer Index Reuse Architecture for Long-Context Sparse Attention
This article examines the inference cost structure of large models with million-token context windows and describes an architecture that combines multi-head latent attention, sparse attention, and cross-layer index reuse. It explains how latent key-value compression reduces cache size and read bandwidth, why the sparse-attention indexer becomes a bottleneck at long sequence lengths, and how a full top-k indexer can run at fixed layer intervals while subsequent layers reuse cached token indices or sparse masks. The article also covers a typical anchor-layer workflow with pseudocode, cost-benefit trade-offs, engineering considerations such as cache granularity and variable-length batching, and suitable use cases and limitations. Readers will gain a system-level view of how to reduce indexer calls while managing accuracy, cache overhead, and training-inference consistency.
1. Problem Background: Where Do Long-Context Inference Costs Come From?
After large-model context windows expand to the million-token level, inference cost is no longer determined only by parameter scale. It is increasingly affected by attention computation, key-value cache access, and sparse index selection. Standard full attention requires every query to compute relevance against all historical tokens, so computation and memory access grow rapidly with sequence length. Even with a key-value cache, cache capacity and memory bandwidth become bottlenecks at long sequence lengths.
Long-context architectures therefore usually adopt two types of optimization. One compresses key-value representations to reduce cache size and read cost. The other uses sparse attention, in which each query attends only to a small number of the most relevant tokens, reducing attention computation. Furthermore, when sparse attention must recompute token indices at every layer, the indexer itself becomes a non-negligible overhead. Cross-layer index reuse targets this step: instead of running a full top-k index selection at every layer, it runs a full indexer at fixed layer intervals and lets subsequent layers reuse the selected token indices.
2. Architecture Overview: Compressed Representation, Sparse Selection, and Cross-Layer Reuse
From publicly described architecture designs, three optimization components can be abstracted:
- Multi-head latent attention: Low-rank latent variables compress key-value representations, reducing key-value cache size and read bandwidth in long contexts. The core idea is not simply to reduce the number of heads. Instead, keys and values are projected into a lower-dimensional latent space and then restored or projected to the required dimensions before attention computation, trading representation compression for efficiency.
- Sparse attention: An indexer scores the relevance between queries and candidate tokens, selects the top-k tokens, and forms a sparse mask. Subsequent attention is computed only on those tokens. This narrows the attention scope from the full history to a small set of candidates and significantly reduces attention kernel computation.
- Cross-layer index reuse: Transformer layers are grouped at fixed intervals. Each group has an anchor layer that runs the full indexer, and subsequent layers directly reuse the token indices or sparse masks produced by the anchor layer. A typical configuration runs the full indexer every four layers, while the other layers reuse the most recent index result.
The overall idea is to use latent representations to reduce the storage cost per token, use sparse attention to reduce the number of tokens involved in computation, and use cross-layer reuse to reduce the decision cost of selecting which tokens to use. These three components act on representation, computation, and index decision respectively, forming a relatively complete cost-optimization chain for long context.
3. The Role and Boundaries of Multi-Head Latent Attention
Multi-head latent attention compresses the key-value cache through low-rank projection. In conventional multi-head attention, each head maintains independent key and value representations, and cache usage at long sequence lengths grows with the product of layers, heads, head dimension, and sequence length. Latent attention maps keys and values into a shared or lower-dimensional latent space and projects them to the dimensions required for attention computation when needed, thereby reducing cache usage and memory access.
It is important to note that compressed representation is not lossless. Low-rank latent variables introduce some representation error, so they must match the model training process to ensure that projection matrices and attention distributions are properly adapted. Latent attention also does not directly reduce the number of scoring operations between queries and all tokens, so it usually needs to be combined with sparse attention. With the two combined, sparse attention reads only the selected top-k key-value latent representations, reducing both the number of reads and the size of each read.
4. Why the Sparse Attention Indexer Becomes a Bottleneck
The key component of sparse attention is the indexer. Its task is to estimate the relevance between the current query and candidate keys, select the top-k tokens, and generate a sparse mask. The indexer usually needs to perform scoring, sorting, or approximate selection. The longer the sequence, the larger the candidate set, and the more obvious the indexer’s computation and sorting costs become. The more layers there are, the greater the cumulative overhead of running the indexer repeatedly at every layer.
In short-sequence scenarios, indexer cost may be hidden by attention computation. In million-token scenarios, however, the indexer must repeatedly select from a large number of candidates, and sorting and mask generation can take significant time. More importantly, adjacent layers often have correlated attention patterns over the same context, so independently recomputing indices at every layer involves redundant work. Cross-layer index reuse exploits this inter-layer correlation and reduces index computation from once per layer to once per group.
5. Workflow of the Cross-Layer Index Reuse Mechanism
A typical workflow is as follows:
- Divide consecutive layers into a layer group, for example, one group every four layers.
- Run the full indexer at the first layer of the group or at a designated anchor layer: compute relevance scores between queries and candidate tokens, select top-k tokens, and generate an index set or sparse mask.
- Cache the index result in a layer-group-level cache. The cache granularity can be per-head independent indices, head-group shared indices, or all-layer shared indices.
- Subsequent layers in the group no longer run the full indexer. Instead, they read the cached index and perform only lightweight validation or shape alignment.
- When the next anchor layer is reached, refresh the index and recompute top-k to avoid long-term index staleness.
- Sparse attention computes attention weights on the tokens specified by the cached index and combines them with the compressed key-value representations from multi-head latent attention to produce the output.
The pseudocode can be abstracted as follows:
def forward_with_cross_layer_index_reuse(x, layers, index_interval=4):cached_index = Nonecached_mask = Nonefor layer_id, layer in enumerate(layers):is_anchor = (layer_id % index_interval == 0)if is_anchor or cached_index is None:# Anchor layer: full indexer computes top-k token indicesscores = layer.indexer.score(x)cached_index = layer.indexer.topk(scores, k=layer.top_k)cached_mask = layer.indexer.build_mask(cached_index, seq_len=x.seq_len)else:# Subsequent layers: reuse the latest index with optional lightweight validationcached_index = layer.indexer.maybe_refine(cached_index, x)cached_mask = layer.indexer.build_mask(cached_index, seq_len=x.seq_len)# Multi-head latent attention: read compressed key-value latent representationskv_latent = layer.latent_kv.project(x)# Sparse attention: compute only on tokens specified by the cached indexx = layer.sparse_attention(query=x,kv_latent=kv_latent,sparse_mask=cached_mask,)return x
The pseudocode above expresses only the structure and is not tied to specific interfaces. Engineering implementations need to handle variable-length sequences, in-batch padding, multi-head index alignment, cache layout, and multi-GPU synchronization.
6. Cost Benefits and Design Trade-Offs
The direct benefit of cross-layer index reuse is fewer indexer calls. With a full indexer every four layers, indexer-related computation and sorting overhead can ideally be reduced to approximately one quarter of the original. However, end-to-end benefit depends on attention kernel efficiency, key-value cache bandwidth, batch size, top-k ratio, and sequence length. If the indexer accounts for only a small share of total cost, the benefit will be limited. If sorting and mask generation account for a high share at long sequence lengths, the benefit will be more obvious.
Index reuse also introduces extra cache overhead: token indices, masks, or head-level index sets need to be stored. Compared with the key-value cache, the index cache is usually smaller, but layout and access efficiency still need attention when many batches, heads, and layer groups run in parallel. Another trade-off is accuracy: attention distributions are not completely identical across layers, and reusing an index may miss tokens that later layers actually need. A smaller layer interval lowers accuracy risk but reduces benefit. A larger layer interval increases benefit but requires stronger validation and fallback mechanisms.
7. Engineering Implementation Considerations
1. Layer interval and anchor layer selection. Fixed intervals are easy to implement, but attention patterns differ considerably across depth. Anchors can be placed preferentially in shallow layers or layers with large semantic changes, with deeper layers reusing shallow-layer indices. Offline analysis can also be used to select positions with high inter-layer index overlap as reuse groups.
2. Index cache granularity. Indices can be cached per layer group with all heads sharing one index, or cached independently per head or head group. Coarser sharing saves cache and simplifies implementation but may lose multi-head differences. Finer granularity improves accuracy but increases cache and synchronization costs.
3. Variable-length sequences and batching. When sequences within a batch have different lengths, indices need to carry sequence offsets and valid-length information, and mask generation must avoid cross-sample contamination. In paged key-value cache scenarios, token indices should be mappable to page tables or contiguous block offsets.
4. Lightweight validation and fallback. Subsequent layers can perform low-cost confidence checks on reused indices, for example by comparing a small number of candidate scores, checking attention entropy, or checking mask coverage. If significant drift is detected, indices can be recomputed locally rather than fully recomputed for the entire layer.
5. Training and inference consistency. If the indexer participates in training, the sparse pattern during training must be consistent with the inference reuse strategy, so that the model does not become overly dependent on independent per-layer indices. Whether reused indices participate in gradients and whether straight-through estimation is used should be designed according to the training objective.
6. Monitoring metrics. Useful metrics include index hit rate, inter-layer index overlap, sparse attention recall, attention entropy, long-document question-answering accuracy, and inference throughput. Before deploying a reuse strategy, ablation tests should be run on target tasks to confirm that accuracy loss is within an acceptable range.
8. Suitable Scenarios and Limitations
Cross-layer index reuse is suitable for long-context tasks such as long-document summarization, retrieval-augmented generation, repository-level code understanding, and log and audit analysis. In these scenarios, sequences are long, indexer overhead is high, and attention patterns in adjacent layers usually have some continuity, so reuse benefits are relatively clear. For short-sequence tasks, indexer cost accounts for a low share, reuse benefit is limited, and implementation complexity increases instead.
This mechanism is not suitable for all accuracy-sensitive scenarios. If a task requires each layer to precisely capture different fine-grained token relationships, cross-layer reuse may cause recall loss. In such cases, the reuse interval should be shortened, more anchor layers should be added, or independent indices should be retained for critical layers. Overall, cross-layer index reuse is a system-level optimization based on the premise of inter-layer correlation. It must be designed together with multi-head latent attention, sparse attention kernels, key-value cache management, and evaluation systems to achieve stable cost benefits at million-token context lengths.
