Cutting Long-Context Inference Cost: Sparse Attention and Cross-Layer Index Reuse
Long-context inference hurts on three fronts at once: attention compute grows quadratically, the KV cache grows linearly, and memory bandwidth, not compute, starts to set decode speed. This article shows how three complementary techniques address them — low-rank KV compression with Multi-head Latent Attention (MLA), block-level sparse attention driven by a lightweight indexing path, and cross-layer index reuse. It covers how each layer works, the trade-offs behind the key knobs (latent rank, share period, sliding window, top-k), a simplified per-layer cost comparison, and a practical rollout plan with evaluation and observability guidance.
1. The Starting Point: Long-Context Cost Comes in Three Forms
When teams discuss long-context inference, they often focus only on FLOPs — that’s the first misconception. Extending the context window from 8K to 1M actually makes three things worse at the same time:
- Compute grows quadratically with sequence length. In standard multi-head attention, every query dot-products against all keys from the entire history. Across a single layer, the two matmuls in
QK^TandAVamount to roughly4 · L · N² · d, whereLis the number of layers,Nis the sequence length, anddis the model dimension. ScalingNby 125x blows up this term by 15625x. - KV cache size grows linearly. During autoregressive decoding, the K and V tensors of every token must stay in GPU memory. Each token occupies
2 · n_h · d_h · bytes, wheren_his the number of heads andd_his the head dimension. This is the real memory hog in long-context serving and directly determines how many concurrent requests a single GPU can handle. - Memory bandwidth becomes the bottleneck. During decoding, every token generated requires the entire KV cache to be streamed from GPU memory into the compute units. Once the cache reaches tens of gigabytes, inference speed is dictated by memory bandwidth rather than compute throughput — leaving compute units idle while memory bandwidth is saturated.
So a viable long-context solution has to rein in all three costs; tackling only one usually yields limited gains. The three-layer design below targets different objectives: low-rank compression addresses memory capacity and bandwidth, sparsification addresses compute, and index reuse addresses the new overhead that sparsification itself introduces.
2. Layer 1: Compressing the KV Cache with Low-Rank Latents
The core idea of Multi-head Latent Attention (MLA) is not to store the full K and V tensors for every head in the cache, but to store a single compressed low-rank latent vector instead.
Concretely, K and V are projected through a down-projection matrix into a latent variable c_t of dimension d_c. Only c_t is kept in the cache, and the up-projection matrix reconstructs the full tensors on demand when they’re needed. To keep rotary positional embeddings working, a separate decoupled key path of small dimension (typically a few dozen dimensions) is retained solely to carry positional information.
# Write pathc_t = W_down_kv @ h_t # Latent vector, dimension d_c, typically much smaller than n_h * d_hk_rope_t = W_rope @ h_t # Decoupled position-aware key, dimension d_r# Cache stores only (d_c + d_r) elements per token instead of 2 * n_h * d_h
The payoff is straightforward: per-token cache footprint drops from 2 · n_h · d_h to d_c + d_r. With n_h = 128 and d_h = 128, the original cache holds 32768 elements per token, whereas a typical d_c + d_r totals only a few hundred — a compression ratio of roughly two orders of magnitude.
There’s a more important decoding trick. Since the query Q can also be projected into the latent space, matrix multiplications can be reordered via associativity (commonly called “weight absorption”), so the actual computation happens in the low-rank space without materializing full K and V tensors first. This means MLA saves memory bandwidth as well as memory capacity — and bandwidth is exactly the long-context decoding bottleneck.
There’s an engineering cost to note: low-rank compression is a lossy information bottleneck. If d_c is set too small, the model’s ability to retrieve fine-grained information precisely will degrade. When tuning, treat d_c as the “width of the information channel” and evaluate it jointly with the model’s retrieval-heavy task performance, rather than picking a number in isolation as if it were just a memory parameter.
3. Layer 2: From Attending to Everything to Attending Selectively
Even with a compressed KV cache, the N² compute cost of attention remains. The idea behind sparse attention is not to interact with every token in history, but only with the k tokens most worth attending to.
The hard part is deciding what’s “worth attending to” cheaply. A scoring function with the same dimensionality as main attention would consume most of the potential savings on its own. A practical approach is to design a lightweight path dedicated to indexing:
- A separate indexing query/key pair with a small dimension
d_idx(on the order of 128); - Shared indexing heads to further reduce scoring cost;
- Block-level selection — assign one score to each block of 64 or 128 tokens instead of scoring every token individually, avoiding a full per-token sort.
# Indexing path: tiny dimension, roughly d_idx / d the cost of exact attentionq_idx = W_idx_q @ h_t # [d_idx]scores = q_idx @ K_idx_cache.T # [N], with blockwise max reductionblocks = blockwise_topk(scores, k_blocks=k) # Select k token blocks
A few channels must remain “never sparse” in practice, or sparsification will undermine local modeling ability:
- Sliding window: the most recent W tokens (e.g., 1024–4096) always participate in exact attention;
- Attention sinks: the first few tokens in the sequence often act as aggregation points for global information and should be permanently retained;
- The current token itself and required positional terms, to avoid breaking the semantics of positional encoding.
With this setup, the compute cost of exact attention per layer drops from O(N²) to O(N · k). With N = 1,000,000 and k = 2048, the number of attention interactions falls by roughly 500x. This is a back-of-the-envelope order-of-magnitude estimate, not a benchmark result, meant only to illustrate the scale of the effect.
4. Layer 3: Cross-Layer Index Reuse to Amortize Indexing Overhead
Sparsification introduces a new cost: the indexer has to score the entire sequence on every layer, costing O(L · N² · d_idx). Even though d_idx is much smaller than d, the N² factor is still substantial at million-token context lengths and becomes a new bottleneck.
Cross-layer index reuse (Index Sharing) offers an optimization that’s quite intuitive: the regions that adjacent layers attend to are highly correlated. Rather than re-running an expensive selection on every layer, run the full indexer once every few layers and let the layers in between reuse the previous selection.
INDEX_SHARE_PERIOD = 4 # Refresh the index every 4 layersdef attn_layer(h, layer_id, index_state):if index_state is None or layer_id % INDEX_SHARE_PERIOD == 0:# Anchor layer: run the full indexer and produce token indicesidx = full_indexer(h)index_state = {"layer": layer_id, "idx": idx, "scores": ...}else:idx = index_state["idx"] # The next 3 layers reuse them directlyk_sel = gather(kv_cache.K, idx)v_sel = gather(kv_cache.V, idx)return softmax(Q(h) @ k_sel.T / sqrt(d)) @ v_sel, index_state
The benefit is that indexing overhead drops by the share period. With a period of 4, indexing cost falls to one quarter of the original, while the bulk of exact attention is unaffected.
How should the share period be chosen? There’s a clear trade-off curve here:
- Too short (e.g., 1, meaning no sharing): indexing cost consumes the entire budget and the design degenerates into dense computation;
- Too long (e.g., 8 or more): the index starts to “drift” from what the current layer actually needs, and the model is forced to attend over an outdated token set, causing a noticeable drop in long-document retrieval tasks;
- In practice, treat the period as an explicit hyperparameter to evaluate. Look for the turning point across perplexity, long-context retrieval accuracy, and per-token inference latency, rather than fixing it at 4 a priori.
Two implementation details also deserve attention. First, prefill and decode should be handled differently. During prefill, the full sequence is visible, so indexing can be made more aggressively sparse to boost throughput. During decode, each step produces only one new query, making reuse more natural and the payoff higher. Second, index state must be managed with paging and rolling updates alongside the KV cache, keeping consistent reference lifetimes with KV blocks. Otherwise, pointer misalignment becomes highly likely under paged-attention implementations (such as PagedAttention-style systems).
5. Cost Model: Tallying All Three Layers Together
Use a simplified per-layer cost model for illustration, with L = 60, d = 6144, d_idx = 128, N = 10⁶, k = 2048, and share period P = 4:
| Scheme | Main attention | Indexing overhead | Relative total compute |
|---|---|---|---|
| Dense full attention | O(N²·d) |
None | 1.00 (baseline) |
| Sparsification only (no low-rank) | O(N·k·d) |
O(L·N²·d_idx) |
Indexing becomes the dominant term |
| Low-rank compression only | O(N²·d) |
None | Compute unchanged; memory and bandwidth drop substantially |
| Low-rank + sparsification + index reuse | O(N·k·d) |
O(L·N²·d_idx / P) |
Indexing amortized down to 1/4 |
Three conclusions follow. Low-rank compression and sparsification solve different dimensions of the problem and cannot substitute for each other. The net gain from sparsification depends heavily on keeping the indexing path cheap enough. And index reuse is what makes sparsification truly cost-effective at very long context windows. The table reflects order-of-magnitude reasoning, not benchmark results; always measure with your own workloads before drawing conclusions.
6. Rollout Plan and Observability Recommendations
Move forward in stages. The recommended order is to start with low-rank compression (low risk, high-certainty gains), then add block-level sparsification (requires evaluation tooling), and finally introduce cross-layer index reuse (requires careful tuning). Jumping straight to index reuse, skipping the intermediate steps, is likely to introduce quality swings on long-text tasks that are hard to attribute.
Don’t evaluate on perplexity alone. Perplexity is relatively insensitive to sparsification and can create a false impression that “nothing was lost.” Add at least three categories of metrics: multi-granularity retrieval (single-needle, multi-needle, and cross-segment multi-hop), factual consistency for long-document summarization and structured extraction, and robustness when perturbations are inserted at key positions. Also measure index recall separately — the overlap between the selected token set and the top attention weights under full attention. This is the fastest probe for diagnosing sparsification quality issues.
Observability in production. The stability of long-context serving depends largely on capacity planning, not on the model itself. A common approach is to use container orchestration platforms for elastic autoscaling and canary (gradual rollout) releases, and log services to collect metrics such as actual input-length distribution, KV cache utilization, index refresh hit rate, and per-request latency percentiles, with monitoring and alerting thresholds set on cache watermark levels and tail latency. On a platform like Baidu AI Cloud, these capabilities are typically delivered through combinations of general-purpose products such as object storage, container platforms, log services, and monitoring and alerting.
Finally, know the limits. Sparse attention and index reuse are approximation techniques that trade acceptable accuracy loss for lower cost — they are not lossless acceleration. For tasks that depend heavily on the full context, such as exact numerical computation, per-token copying, or extremely long chain-of-thought reasoning, any index drift gets amplified. Before going live, run targeted regression tests on real long-text samples from your own business, and treat the share period, top-k size, and sliding-window size as configuration items that need ongoing maintenance, not constants tuned once and forgotten.
