Long Context Inference Cost Reduction: How Cross-Layer Index Reuse Works

    This article explains why long context inference costs grow close to quadratically and how two base mechanisms, Multi-head Latent Attention (MLA) and DeepSeek Sparse Attention (DSA), address the problem from different angles. It then breaks down Cross-Layer Index Reuse (IndexShare), which refreshes the top-k index once every four layers and reuses it in between, along with its tunable group_size, quantified savings, memory overhead, and quality risks. Engineering guidance, an evaluation methodology, and the practical limits of the technique are also covered.

    1. Background: Where the Cost of Long Context Inference Comes From

    When a model’s context window grows from a few thousand tokens to the million-token range, inference cost does not scale linearly. It grows close to quadratically. Standard self-attention requires every query position to interact with all historical positions, so both computation and memory usage climb quickly with sequence length. For workloads such as long-document summarization, cross-file code comprehension, and long-conversation memory, inputs routinely reach hundreds of thousands of tokens, and time-to-first-token along with peak memory usage become bottlenecks at the same time.

    The industry has responded along two broad lines. The first narrows the “visible range” of attention, which is sparse attention. The second compresses the storage form of the key-value cache, which is latent attention. The first reduces the number of tokens that participate in computation; the second shrinks the cache footprint of each token. Combining the two is currently the mainstream direction for long context solutions.

    2. Two Base Mechanisms: Latent Attention and Sparse Attention

    The core idea of Multi-head Latent Attention (MLA) is to compress keys and values into a low-dimensional latent space for caching, then project them back up during inference. The benefit is a substantial reduction in key-value cache size, which supports longer sequences or larger batches under the same memory budget. The cost is extra projection computation, so there is a trade-off between saving memory and doing a bit more math.

    DeepSeek Sparse Attention (DSA) introduces a lightweight indexer that selects the top-k most relevant historical tokens for each query position, and attention is computed over those k positions only. This reduces complexity from something tied to the square of the sequence length to something linear in k. The key engineering difficulty is that the indexer itself still has to scan the entire history. Without optimization, the indexing stage becomes a new hotspot.

    3. Core Innovation: Cross-Layer Index Reuse

    Cross-Layer Index Reuse (IndexShare) targets exactly that hotspot. Its premise is that attention distributions in adjacent layers are highly similar, and the same batch of tokens is often judged highly relevant across several consecutive layers. So instead of recomputing top-k at every layer, the full indexer runs once every four layers, and the following three layers directly reuse the already selected token indices.

    This change preserves the original semantics of sparse attention and only reduces the indexing frequency to one quarter. Illustrative pseudocode:

    1. # Refresh the index every group_size layers; reuse it on the others
    2. if layer_idx % group_size == 0:
    3. topk_idx = indexer(query, key_cache) # full scan, select top-k
    4. else:
    5. topk_idx = shared_topk_idx # reuse directly
    6. shared_topk_idx = topk_idx
    7. out = sparse_attention(query, key_cache, topk_idx)

    It is worth stressing that group_size is a tunable hyperparameter. A smaller value keeps the index fresher, which is more stable in accuracy but costs more. A larger value yields more obvious savings, but raises the risk of the index drifting away from the current layer’s distribution. In practice, teams often start from 4 and then run sensitivity checks against the specific task.

    4. Quantifying the Benefits and the Costs

    Let the sequence length be L, the number of layers be N, and the index group size be g. The original approach incurs roughly N full scans for indexing; with reuse this drops to N/g, so the indexing cost falls by about (1 - 1/g). With g=4, indexing computation is reduced by roughly 75%. Since the main attention computation already depends only on k, the overall end-to-end gain depends on how much of total time indexing accounts for: the higher the indexing share, the more pronounced the benefit.

    The costs are equally clear. First, a cross-layer shared index tensor must be maintained in memory, which adds a small amount of extra usage. Second, index staleness may cause some layers to miss locally optimal tokens, showing up as slight quality fluctuation on tasks that require fine-grained retrieval. Evaluation therefore has to look at throughput, peak memory, and task metrics together, not speed alone.

    5. Engineering Implementation Notes

    • Layered deployment: place the indexer and the main attention computation on the same device or within the same communication domain, so that moving the index tensor across nodes does not cancel out the gains.
    • Caching strategy: manage the key-value cache with paging, combined with prefix reuse, so multi-turn question answering over long documents can share the historical prefix.
    • Elastic scaling: long context inference is sensitive to memory, so container platforms can be used to dynamically match instance specifications and batch size.
    • Observability: collect time-to-first-token, per-token latency, peak memory, and index hit rate through logging services and monitoring alerts to form a regression baseline.
    • Data pipeline: large-scale corpora can rely on object storage and message queues to build a closed loop of offline evaluation and online sampling.

    If you use the relevant general-purpose capabilities of Baidu AI Cloud, these stages map to standard categories such as container platforms, object storage, logging services, and monitoring alerts, and the setup can be completed without binding to any proprietary interface.

    6. How to Evaluate the Effect

    Set up three comparison groups: the full-attention baseline, per-layer sparse indexing, and cross-layer reuse sparse indexing. Fix input lengths in tiers (for example 32K/128K/1M), record throughput, peak memory, and time-to-first-token, and compare metrics across three task types: long-document question answering, cross-file code retrieval, and long-text summarization. Also sweep group_size and plot the “speed-quality” curve to find the point that is acceptable for the business.

    7. Applicability Limits and Common Pitfalls

    The technique is not a cure-all. When a task requires layer-by-layer precise localization, such as cell-level references in extremely long tables, the drift introduced by index reuse is more sensitive, so g should be reduced or per-layer indexing restored. Another pitfall is looking only at average latency: long context workloads have a pronounced tail, so P95/P99 must be examined. It also pays to remember that sparsification is not lossless. Any top-k truncation carries a risk of information loss, so thorough regression testing is needed before going live.

    8. Summary

    The cost-reduction path for long context inference is essentially about removing the redundancy of computing at every layer. Latent attention compresses the cache footprint, sparse attention shrinks the computation range, and cross-layer index reuse further amortizes the indexing cost. Only when the three are stacked together can cost at the million-token scale be pushed into a usable range. In deployment, use group size as the tuning knob and multi-dimensional metrics as the acceptance criteria, and only then can a robust balance between performance and quality be achieved.