Reducing Long-Context Inference Costs: How Cross-Layer Index Reuse Works with Sparse Attention

    This article explains how to cut the cost of long-context LLM inference by combining Multi-head Latent Attention (MLA), sparse attention, and cross-layer index reuse (the IndexShare idea). It covers why standard self-attention becomes a compute and memory bottleneck as context grows, how low-rank KV compression and top-k sparse attention each reduce cost, and how reusing the same top-k index across a group of N layers amortizes indexer overhead. It also includes pseudocode, guidance on choosing the group size N, deployment considerations, quality validation methods, and the practical limits of the approach.

    Reducing Long-Context Inference Costs: Cross-Layer Index Reuse for Sparse Attention

    1. Background: The Compute Wall as Context Length Grows

    As LLM applications move from short question answering toward long-document understanding, repository-level code analysis, and multi-turn long conversations, context windows have expanded from a few thousand tokens to hundreds of thousands or even millions. The benefits of longer context are clear: you can fit an entire manual, a whole code repository, or a long conversation history into the model’s view at once, reducing the information loss caused by retrieval and chunking.

    The costs are equally clear. In standard self-attention, every query interacts with all historical keys and values, so computation and memory usage grow quadratically with sequence length. When sequence length increases by an order of magnitude, the time and bandwidth pressure of the attention portion quickly become the main bottleneck, sometimes exceeding the feed-forward network itself. This has led the industry to two main optimization paths:

    • Compressed representations: reduce the storage and read cost of the key-value cache;
    • Sparse computation: let each query interact with only a subset of candidate tokens, reducing quadratic complexity to near-linear.

    The technique discussed here belongs to the second path and goes further by reusing work across the layer dimension.

    2. Two Building Blocks: Latent Attention and Sparse Attention

    2.1 Multi-head Latent Attention (MLA)

    The core idea of Multi-head Latent Attention is “low-rank compression plus cache sharing.” Instead of caching the full keys and values for every head, it projects keys and values into a low-dimensional latent space, caches only that low-dimensional representation during inference, and up-projects it back when needed. The benefits are threefold:

    1. Lower memory usage: the key-value cache becomes significantly smaller, allowing larger batches or longer sequences under long context;
    2. Reduced bandwidth pressure: the cache is read at every decoding step, so a smaller cache directly lowers memory access overhead;
    3. Preserved expressiveness: because the compression is low-rank rather than simple truncation, the compressed representation retains strong information reconstruction ability.

    Illustrative pseudocode (structure only, not any specific implementation):

    1. # Write phase: compress into a latent representation and cache it
    2. c_kv = x @ W_dkv # low-dimensional latent vector
    3. k_pe = x @ W_kpe # position-related component
    4. cache.append(c_kv, k_pe)
    5. # Read phase: reconstruct per-head keys and values from the latent representation
    6. k_c = c_kv @ W_uk # up-project to each head
    7. v_c = c_kv @ W_uv
    8. scores = (q_c @ k_c.T + q_pe @ k_pe.T) / sqrt(d)

    2.2 Sparse Attention (DSA)

    Sparse attention no longer scans the entire history for each query. Instead, a lightweight “indexer” scores candidates first and selects a small group of tokens most relevant to the current query (the top-k indices); attention is then computed only at those k positions. Its key properties are:

    • Complexity drops from quadratic to near-linear: the main cost becomes “index scoring plus attention over k positions”;
    • Quality depends on index quality: if the top-k selection is wrong, no amount of precision in the subsequent attention can recover it;
    • The indexer itself has a cost: scoring typically requires a lightweight projection and a comparison over the full sequence, which is not negligible at very long sequence lengths.

    This leads to the core question of this article: can the indexer’s cost be amortized?

    3. Core Mechanism: Cross-Layer Index Reuse (the IndexShare Idea)

    3.1 Observation: Attention Choices in Adjacent Layers Are Highly Similar

    A repeatedly observed phenomenon is that the attention distributions of adjacent Transformer layers at the same position are often highly correlated, especially in deeper layers, where the “importance ranking” of tokens changes gradually. This means recomputing the top-k index at every layer involves a large amount of duplicated work.

    3.2 Approach: Run the Full Indexer Once Every N Layers

    The strategy for cross-layer index reuse is straightforward:

    • Run the full indexer every N layers (for example, every four layers) to obtain the set of candidate token indices for that position;
    • The next N-1 layers do not re-score; they directly reuse this index to perform sparse attention;
    • The index set is refreshed periodically as layers advance, preventing errors from accumulating indefinitely.

    The control flow in pseudocode:

    1. for layer_idx, layer in enumerate(layers):
    2. if layer_idx % N == 0:
    3. topk_idx = indexer(hidden) # full index: the only overhead point
    4. shared_idx = topk_idx
    5. out = sparse_attention(layer, hidden, shared_idx)
    6. hidden = layer.feed_forward(out)

    3.3 Why It Reduces Cost

    Let the number of layers be L, the sequence length be S, the number of candidates be k, and the index group size be N. The index-related overhead drops from roughly L × O(S·d) to roughly (L/N) × O(S·d), which at N=4 theoretically removes about three quarters of the index computation. Meanwhile, the cost structure of the main sparse attention body is unchanged, so the overall benefit grows with context length: the longer the sequence, the larger the absolute cost that gets amortized.

    It is worth emphasizing that this is an engineering trade-off: it does not raise the upper bound of theoretical expressiveness; it makes long context usable within acceptable latency by lowering the “selection cost.”

    4. Implementation Notes

    4.1 Choosing the Group Size N

    • Too small N: limited benefit, close to per-layer indexing;
    • Too large N: the index becomes stale, and attention may focus on tokens that are no longer relevant, degrading quality;
    • Practical advice: start from 2 to 4, and make decisions based on downstream task metrics rather than perplexity alone.

    4.2 Working with Key-Value Compression

    Latent attention handles “storing less,” sparse attention handles “computing less,” and index reuse handles “selecting for less.” The three are orthogonal and can be stacked; however, the memory budget must simultaneously cover the latent cache, the intermediate tensors for index scoring, and activations.

    4.3 Supporting Infrastructure on the Inference Serving Side

    • Batching and paged cache: long-context scenarios should be paired with paged key-value management and continuous batching to improve throughput;
    • Monitoring and alerting: set up monitoring and alerts for time-to-first-token, per-token latency, and cache hit rate to pinpoint whether the bottleneck is in indexing or attention;
    • Logging and tracing: record the share of time spent at index refresh points to evaluate the actual benefit of N;
    • Elastic resources: long-context workloads can run on an elastic resource pool in a container platform and scale automatically based on queue length.

    4.4 Quality Validation Methods

    A three-layer validation is recommended:

    1. Retrieval-style probes: construct tasks where key information is buried in the middle of a long document, and check whether top-k still hits it;
    2. Long-document comparison: compare task accuracy of the same model under “per-layer indexing” versus “cross-layer reuse”;
    3. Stress testing: observe whether the latency curve stays near-linear at gradient lengths such as 32K/128K/1M.

    5. Applicability Boundaries and Common Pitfalls

    • Not a universal speedup: if the task is extremely sensitive to local details, stale indices may cause visible loss;
    • Not a replacement for retrieval augmentation: very long context and external knowledge retrieval are complementary; the former solves “fitting it in,” the latter solves “finding it accurately”;
    • Do not rely on theoretical complexity alone: real benefits are affected by memory access, kernel efficiency, and batch size, so end-to-end stress testing is the standard;
    • Configuration must be revertible: keep a switch to disable reuse, making canary rollout and fault localization easier.

    6. Conclusion

    Reducing the cost of long-context inference is essentially about turning “indiscriminate full computation” into “selective, minimal computation,” and further turning “selection” itself into a reusable asset. Latent attention compresses representations, sparse attention trims computation, and cross-layer index reuse amortizes selection cost; layered progressively, they form a clear engineering path. For teams that need to balance quality and cost at million-token context, understanding the combined logic of these mechanisms and the boundaries of tuning is more valuable than chasing a single metric.