Long-Context LLM Inference Architecture: KV Cache Compression, Sparse Attention, and Cross-Layer Index Sharing
This article breaks down where the cost of long-context LLM inference actually comes from, and how two mainstream techniques work together to address it. Multi-head latent attention compresses the KV cache and reduces memory bandwidth pressure during decoding, while sparse attention shrinks the number of positions each query attends to at the cost of an extra indexing step. The article then explains a key optimization, sharing sparse indices across a group of layers, including pseudocode, design trade-offs, why grouping beats a single global index, and the boundaries between gains and costs. It closes with practical deployment advice on layered evaluation, joint parameter sweeps, capacity planning, observability, and architecture decoupling.
Long-Context LLM Inference Architecture: KV Cache Compression, Sparse Attention, and Cross-Layer Index Sharing
1. Background: Where the Cost Goes as Context Grows
In long-context inference, attention computation grows quadratically with sequence length, while the memory footprint of the key-value (KV) cache grows linearly. When the context expands from a few thousand tokens to the million-token range, what actually slows the system down is usually not the raw size of the matrix multiplications, but three things stacking up:
- KV cache capacity pressure, which directly determines the concurrency batch a single device can hold;
- Memory bandwidth pressure from attention reads, since every generated token during decoding requires scanning the entire history cache again;
- The added “index computation” overhead introduced by sparsification, i.e., deciding which historical tokens are worth attending to.
The third point is often overlooked. Sparse attention is not free: a lightweight scorer must first evaluate all historical positions, and then the top-scoring few are selected to participate in the real attention computation. The longer the sequence, the less negligible the cost of this scoring and selection process becomes, and in small-batch, single-request decoding it can even become the dominant term.
2. How Two General-Purpose Techniques Work Together
2.1 Multi-Head Latent Attention: Compress the Cache, Not the Computation
The core idea of multi-head latent attention is to project keys and values into a low-dimensional latent space, keep only that low-dimensional representation in the cache, and up-project it back to the multi-head dimensions when it is used. It delivers two direct benefits: first, the KV cache size drops significantly, so the same memory supports a longer context or higher concurrency; second, bandwidth pressure during decoding decreases, because fewer bytes need to be moved for each historical position.
It is worth stressing that this optimizes “storage and movement” and does not reduce the number of positions that attention itself has to cover. So at the million-token scale, cache compression alone is not enough.
2.2 Sparse Attention: Fewer Participating Positions, but an Indexing Cost
Sparse attention selects only the most relevant subset of historical positions for each query, reducing the participation scale from “the full sequence” to a fixed budget. It addresses the scale of computation and bandwidth participation, at the price of maintaining an additional indexer: score all historical positions and take the top-k index set.
This creates a clear division of labor: latent attention makes each position “cheaper,” sparse attention makes the participating positions “fewer,” and the indexer is the scheduling hub that connects the two, as well as the new cost center.
3. Key Optimization: Sharing Sparse Indices Across Layers
3.1 The Waste in the Naive Approach
The most straightforward implementation runs the indexer independently at every layer: each layer scores on its own and takes its own top-k. The problem is that adjacent layers face the same historical context and are highly correlated semantically, so the important position sets they select tend to overlap heavily. Repeating the scoring layer by layer amounts to performing the same “context importance judgment” dozens of times.
3.2 How the Sharing Mechanism Works
A compromise adopted in the industry is to group a fixed number of layers together: run the full indexer only once per group to produce one token index set, and let the following layers in that group reuse this index without re-scoring. A sketch:
# Pseudocode: group-wise shared sparse indexINDEX_GROUP = 4 # share one index every 4 layerscached_index = Nonefor layer_id, layer in enumerate(layers):if layer_id % INDEX_GROUP == 0:# Run full scoring and top-k selection only at the first layer of the groupscores = indexer.score(hidden_states, key_cache) # [B, H, L]cached_index = topk(scores, k=budget) # [B, H, k]# The remaining layers in the group reuse it directly, no recomputationattn_out = sparse_attention(q, k_cache, v_cache, cached_index)hidden_states = layer(attn_out, hidden_states)
Three design points stand out: the group granularity is a tunable hyperparameter, where a larger group saves more compute but matches the semantics of the current layer less closely; the index budget stays unchanged, so the attention computation per layer is not reduced; and sharing happens at the index level rather than the attention output level, so each layer still uses its own query and key-value projections.
3.3 Why Group Instead of a Single Global Share
If the model computes the index only once, the deviation between the index and deeper-layer features is amplified layer by layer, and recall quality degrades noticeably under long context. Group-wise sharing is the balance point between “saving index overhead” and “keeping the index current.” It is a typical engineering compromise, not a lossless optimization.
4. The Boundary Between Gains and Costs
On the gains side, the benefits show up mainly in long-context, decode-heavy workloads: the number of index scoring passes drops to a fraction of the original, end-to-end latency and throughput improve markedly, and the KV cache strategy is unaffected.
The costs deserve an honest look as well: the prefill phase is itself large-matrix computation, so index overhead is a small share and the optimization yields limited benefit there; the index lags the current layer semantically, so in theory it may miss the few positions that matter only at a specific layer; and both group size and index budget need validation against the specific task rather than being copied wholesale.
5. Practical Deployment Recommendations
- Evaluate in layers: first align baseline accuracy with short contexts, then gradually lengthen the context and watch for metric drift, instead of validating only on long sequences.
- Sweep parameters jointly: treat group granularity and index budget as one combined hyperparameter sweep rather than tuning either in isolation.
- Plan capacity: factor in the memory savings from cache compression, then recalculate concurrency batch and instance sizing, with elastic scaling on a container platform.
- Build observability: bring index hit overlap rate, cache hit rate, and per-step decoding latency into logging and monitoring alerts, so it is easier to tell whether the issue is indexing or bandwidth.
- Decouple the architecture: make the indexer and the attention kernel replaceable modules, so a more suitable scoring strategy can be swapped in later.
6. Conclusion
Optimizing long-context inference is essentially a structured trade-off among cache capacity, the number of participating positions, and scheduling overhead. Cache compression lowers the per-position cost, sparsification lowers the participation scale, and cross-layer index sharing further cuts the duplicated work in the scheduling layer. Understanding these three layers is more valuable than memorizing the name of any single mechanism, and it better helps teams make sound choices under real business workloads.
