Sparse Attention Optimization for Million-Token LLM Context Inference

    This article examines how to make long-context LLM inference practical as context windows grow to millions of tokens. It covers two foundational mechanisms—Multi-head Latent Attention (MLA) for compressing KV cache and sparse attention (DSA) for selecting relevant tokens—then explains why per-layer indexing becomes a bottleneck in deep models. The core proposal is cross-layer index reuse, which runs the indexer every few layers and shares the selected token indices across intermediate layers. The article also details engineering considerations, evaluation methods, and deployment infrastructure, offering a clear path to balancing quality and cost.

    1. Background: Why Long-Context Inference Requires Subtraction

    When the context window expands from a few thousand tokens to millions, the complexity of attention computation grows quadratically with sequence length, while the memory footprint of the key-value (KV) cache grows linearly. Together, these two factors put simultaneous pressure on latency, memory, and throughput for a single inference pass. The industry generally recognizes two directions: compressing representations to reduce the per-token cache size, and sparsifying computation so each query interacts with only a subset of tokens. This article focuses on the latter and discusses how to evolve sparsification from a single-layer optimization into cross-layer coordinated optimization.

    2. Two Foundational Mechanisms: Latent Attention and Sparse Attention

    2.1 Multi-head Latent Attention (MLA)

    The core idea is to project the KV cache into a low-dimensional latent space. During inference, only this low-dimensional representation is cached, and it is up-projected back when needed. The benefits are threefold:

    • Reduced cache size, which alleviates memory pressure for long sequences;
    • Attention scoring performed in the low-dimensional space, which is more memory-access friendly;
    • When combined with positional schemes such as rotary position embeddings (RoPE), a small number of position-related components must be retained additionally.

    Illustrative pseudocode:

    1. # Cache side: store only the low-dimensional latent vectors
    2. kv_latent = x @ W_down_kv # [B, T, d_latent]
    3. # Compute side: up-project on demand
    4. k = kv_latent @ W_up_k # [B, T, d_head * n_head]
    5. v = kv_latent @ W_up_v

    2.2 Sparse Attention (DSA)

    Sparse attention first uses a lightweight “indexer” to score tokens for each query, selects the top-k most relevant tokens, and then performs exact attention only over those k positions. The key point is that the indexer must be cheap enough; otherwise, the compute saved by sparsification is offset by the indexing overhead. In practice, the indexer typically operates at a low-dimensional or block granularity, and k is capped statically to keep memory and latency predictable.

    3. The Key Conflict: Indexing Overhead Becomes the New Bottleneck

    Placing sparse attention in a multi-layer stacked architecture exposes a long-underestimated problem: the indexer must be run again at every layer. If a model has dozens of layers and the sequence reaches a million tokens, the cumulative cost of the indexer can be comparable to—or even higher than—the exact attention itself. At that point, the gains from sparsification are diluted layer by layer.

    4. Cross-Layer Index Reuse (The IndexShare Idea)

    4.1 Basic Approach

    Run the full indexer once every fixed number of layers (for example, every four layers) to obtain a batch of selected token indices. Intermediate layers directly reuse this index and perform only exact attention, without re-scoring. Formal description:

    1. if layer_idx % reuse_interval == 0:
    2. idx = top_k(indexer(q, kv_latent)) # full indexing
    3. else:
    4. idx = shared_idx # reuse the shared result from the previous group
    5. out = sparse_attention(q, k, v, idx)

    4.2 Why Reuse Does Not Significantly Degrade Quality

    • Query representations in adjacent layers are highly correlated, and the ranking of token importance changes gradually within a shallow range of layers;
    • Reuse acts as an implicit smoothing along the layer dimension, reducing noise from index jitter;
    • The reused index still covers global candidates and does not degrade into local window attention.

    4.3 Costs and Boundaries

    • When the reuse interval is too large, semantic drift in deeper layers causes index mismatch, so the interval value needs evaluation;
    • Index sharing requires a consistent k across layers for top-k, or padding/truncation logic for inconsistent cases;
    • When combined with dynamic k (adaptive per layer or per head), additional alignment logic is required.

    5. Engineering Implementation Notes

    1. Layered caching: manage the latent cache and the index cache separately, with the index cache lifecycle bound to the reuse interval.
    2. Batch alignment: when sequence lengths vary widely within a batch, index tensors must be padded to the maximum length and paired with masks.
    3. Numerical stability: normalize the indexer scores before taking top-k to avoid score-scale drift over long sequences.
    4. Observability: instrument metrics such as index hit rate, reuse-layer ratio, and average candidate length to support tuning.
    5. Fallback strategy: under memory pressure, temporarily shorten the reuse interval or lower k to preserve service availability.
    1. shared_idx = None
    2. for layer_idx, layer in enumerate(layers):
    3. if layer_idx % reuse_interval == 0:
    4. shared_idx = layer.indexer_topk(q, kv_latent) # full indexing
    5. out = layer.sparse_attn(q, k, v, shared_idx) # reuse the index

    6. Evaluation Methodology

    • Quality side: compare metrics before and after reuse on tasks such as long-document question answering, multi-hop retrieval, and repository-level code understanding;
    • Efficiency side: measure time-to-first-token, overall latency, peak memory, and throughput separately, focusing on the curve slope at million-token lengths;
    • Ablation studies: tune the reuse interval and top-k independently to observe the quality–cost Pareto frontier;
    • Pre-launch validation: run regression tests on fixed long-text samples to confirm that index reuse introduces no long-tail degradation.

    7. Integration with General Cloud Capabilities

    In real deployments, long-context capabilities typically require supporting general-purpose infrastructure: a container platform to host inference services with elastic scaling, object storage to hold long-text samples and model artifacts, a message queue to smooth request spikes, and logging and monitoring services to track latency and memory metrics. Baidu AI Cloud can provide corresponding support across these general categories, helping teams bring architecture optimizations reliably into production.

    8. Summary

    The focus of long-context inference optimization is shifting from single-layer sparsification to cross-layer coordination. Latent attention compresses representations, sparse attention filters candidates, and cross-layer index reuse amortizes indexing costs; together they form a clear cost-reduction path. In practice, using the reuse interval and top-k as the core tuning knobs, combined with thorough observability and fallback mechanisms, allows a controllable balance between quality and cost.