Reducing Long-Context Inference Cost: How Cross-Layer Index Reuse Works
This article explains why long-context inference becomes bottlenecked by attention compute and memory access, and how cross-layer index reuse (IndexShare) cuts the cost of sparse attention. It breaks down the three stages of sparse attention, shows where the indexing overhead comes from, and explains how sharing indexes across a group of layers works alongside low-rank latent caches and sparse attention. It also covers practical guidance on group size, first and last layer handling, decoding behavior, fallback strategies, observability, and evaluation dimensions.
1. Background: The Cost Structure of Long-Context Inference Has Changed
When the context grows from a few thousand tokens to the million-token range, the inference bottleneck shifts quickly from parameter count to attention compute and memory access. The reason is straightforward: standard attention scales quadratically with sequence length, and during decoding it repeatedly reads a key-value cache that keeps growing. Memory bandwidth is often saturated before compute is.
The industry has responded along two main lines. One is to compress the representation of the key-value cache, using low-rank latent vectors to carry multi-head information and reduce cache size. The other is to let each query attend to only a small set of the most relevant tokens, turning quadratic complexity into near-linear complexity. The first approach is commonly associated with multi-head latent attention (MLA); the second with sparse attention (DSA). Only when the two are combined does million-token context become practically feasible.
Sparsification, however, introduces a hidden cost: you must first select which tokens to look at. That selection step requires scoring, sorting, and taking the top-k, which is not cheap over very long sequences, and it has to be redone at every layer. The result is counterintuitive: attention has been sparsified, but end-to-end latency does not drop as expected.
2. Breaking Down the Mechanism: Why Index Computation Dominates
A single sparse attention operation is easier to reason about in three steps:
- Index scoring: compute a relevance score for every candidate token;
- Selection: take the k highest-scoring positions to form the index set;
- Aggregation: perform the attention-weighted sum only over the selected positions.
The cost of step 3 has already been pushed down by sparsification. The expensive parts are steps 1 and 2. They must cover the full sequence and are triggered repeatedly under large batches and long contexts. With L layers and sequence length n, index-related overhead is on the order of L times n, while aggregation overhead is on the order of L times k, where k is far smaller than n.
Illustrative pseudocode (structure only, not a specific implementation):
# Naive approach: recompute the sparse index at every layerfor layer in layers:idx = topk(score(q[layer], k_cache), k) # full-sequence scoring + selectionout[layer] = sparse_attend(q[layer], k_cache, idx)
The key observation is that adjacent layers have highly correlated attention preferences over the same set of tokens. Representations in a language model evolve progressively from shallow to deep layers, so the ranking of token importance changes slowly within a local range. This means recomputing indexes layer by layer involves a large amount of duplicated work.
3. The Core Idea: Cross-Layer Index Reuse
Cross-layer index reuse (IndexShare) works like this: instead of running the full indexer at every layer, run full scoring and selection once every few layers (for example, every four layers), and let the following layers reuse the previous index set directly.
GROUP = 4shared_idx = Nonefor i, layer in enumerate(layers):if i % GROUP == 0:shared_idx = topk(score(q[layer], k_cache), k) # full indexerout = sparse_attend(q[layer], k_cache, shared_idx) # reuse the index
This keeps the core premise of sparse attention intact: each query still looks at only k tokens and aggregation complexity is unchanged, while index-related overhead drops from L times to roughly L/GROUP times. At million-token context lengths this term usually dominates end-to-end latency and memory traffic, so the gain is amplified. The indexer’s own parameters and intermediate activations no longer need to stay resident at every layer, which reduces memory pressure as well.
It is worth stressing that this does not approximate away part of the computation; it shares out the computation that is highly redundant. The approximation comes from a verifiable assumption: the optimal token set within a group is close enough across layers. In practice, it is usually enough to ensure recall does not collapse in order to preserve accuracy.
4. How It Works With Latent Attention and Sparse Attention
The three techniques address different dimensions of the problem and are meaningful only in combination:
- Latent attention: compresses the storage representation of the key-value cache, solving “the cache is too large”;
- Sparse attention: limits each query’s visible range, solving “too much is computed”;
- Cross-layer index reuse: eliminates repeated index computation across layers, solving “selection happens too often”.
Chained together, the data flow is: a compact cache built from low-rank latent vectors → token indexes generated periodically → aggregation over the shared index at each layer in the group. The cache is smaller, the visible range is narrower, and the index frequency is lower. All three multipliers are below 1, so end-to-end cost falls.
5. Implementation Notes
Choosing the group size G. If G is too small, the reuse benefit is limited; if it is too large, semantic drift within the group lowers recall. In practice, start at 4 and configure it per depth segment: shallow representations are general-purpose and can tolerate a larger G, while deeper layers are more task-specific and warrant a smaller G.
Handling the first and last layers. The first layer’s index quality sets the baseline for subsequent reuse, and the last layer directly affects the output distribution. Both usually keep full index computation and are excluded from reuse.
Working with the decoding stage. During prefill the sequence is long and highly parallel, index overhead is a large share, and the reuse benefit is clear. During decoding each step adds only one query, so the incremental index must stay consistent with the cached index version to avoid reading a stale selection.
Fault tolerance and fallback. When an abnormal in-group recall metric is detected (for example, a clear shift in the score distribution of selected tokens), a layer can temporarily trigger one full index computation, forming a hybrid strategy of “periodic reuse plus on-demand refresh”.
Observability. Instrument index hit rate, in-group recall, per-step index latency, and cache bandwidth usage separately, and track long-tail latency in long-context scenarios with a monitoring and alerting system.
6. Evaluation Recommendations
Evaluating this kind of optimization on throughput alone is not enough. Cover at least four dimensions: accuracy on long-context understanding tasks (multi-document retrieval, cross-passage reasoning); first-token latency and per-token latency curves at different context lengths; peak memory and bandwidth; and the accuracy-cost tradeoff curve across different G values. Missing any one of these can lead you to mistake “lower cost” for “lower quality”.
7. Summary
The focus of cost reduction in long-context inference has moved from cache compression alone to eliminating repeated computation. The value of cross-layer index reuse lies in capturing a structural redundancy: adjacent layers judge token importance in highly similar ways. Trading a controlled recall risk for a multiplicative reduction in index frequency pulls the cost curve back into a usable range for million-token contexts. If you are building long-text capabilities, validate in-group recall stability in offline evaluation first, then roll out gradually with solid observability in place. General-purpose capabilities from Baidu AI Cloud, such as container platforms, log services, and monitoring and alerting, can serve as the hosting and observability foundation.
