Sparse Attention for Million-Token Contexts: The Critical Path to a 22x Speedup

    Long-context inference is bottlenecked by attention's quadratic cost, and sparse attention only shifts the problem to the indexer that must score every key. This article explains why sparsity holds up in practice, why scoring still keeps prefill quadratic, and the four techniques that bring indexing down to near-linear: hierarchical indexing, low-rank projection, block-level pruning with budget allocation, and caching with incremental reuse. It also covers two-stage training and evaluation practices to protect accuracy, plus notes on running these workloads in the cloud.

    1. Where the Problem Starts: Sparse but Not Cheap

    The core tension in long-context inference is that attention’s compute and memory footprint grow quadratically with sequence length. The mainstream response is a division of labor: a lightweight indexer first selects the k most relevant keys for each query, and the actual attention is computed only over those k keys. This reduces the complexity of attention itself to O(T·k), where T is the sequence length and k is the number of keys retained per query.

    The approach rests on a premise that is often overlooked: the model genuinely needs only a tiny fraction of the keys. Validation supports this. At a scale of 128k tokens, forcing each query to attend to only its 512 most relevant keys (roughly 0.8% of all keys) still preserves about 98% of full-attention accuracy on long-context retrieval benchmarks. Sparsity, in other words, is not a compromise; it is a structural fact that matches model behavior.

    2. The Paradox: The Indexer Is Still Linear or Even Quadratic

    The catch is that deciding which 512 keys are most relevant requires scoring every key first. The scoring stage therefore still grows linearly with context length, and since every query needs scoring, overall prefill remains quadratic.

    Common ways to cut the cost in the industry include lowering the numerical precision of scores, compressing the scoring dimension, and merging every 4 adjacent keys into 1 before scoring (block sparsity). These help, but they only divide the constant factor by a few times without changing the order of complexity. As context grows from 128k toward the millions, constant-factor optimizations get swallowed by scale.

    3. The Breakthrough: Taking Scoring from O(T²) to Hierarchical and Near-Linear

    Real speedup requires the indexer to stop scoring every key one by one. Four types of techniques can be combined:

    1. Hierarchical indexing (coarse-to-fine): Cluster or bucket the keys first, let the query score only the buckets, then do fine-grained scoring within the few selected buckets. Complexity drops from T² to T·(T/B + B·k); with B≈√T it approaches T^1.5, and a two-level scheme can push it closer to near-linear.
    2. Low-rank/projection approximation: Use a shared low-dimensional projection to map queries and keys into a space of d’≪d for the inner product. Scoring cost falls linearly with d’, and matrix multiplication can absorb the work as batched throughput.
    3. Block-level pruning and budget allocation: Estimate upper bounds per block (such as the maximum or mean similarity within a block), prune blocks that cannot make the top-k, then concentrate the scoring budget on the candidate blocks.
    4. Caching and incremental reuse: Cache bucket assignments and projection results for historical keys, and score only incrementally during decode to avoid recomputation.

    Illustrative pseudocode (hierarchical indexing):

    1. # T: sequence length, B: number of buckets, k: keys retained per query
    2. def sparse_attention(Q, K, V, B, k):
    3. buckets = build_buckets(K, B) # precomputed, cacheable
    4. scores = coarse_score(Q, buckets) # O(T * B)
    5. cand = topk_buckets(scores, budget=B//4)
    6. idx = fine_score_and_select(Q, K, cand, k) # only within candidates
    7. return attention(Q, K[idx], V[idx]) # O(T * k)

    4. Protecting Accuracy: Two-Stage Training and a Closed Evaluation Loop

    The risk with sparsification is selecting the wrong keys. The engineering recommendation is to first align with full attention on short contexts, then gradually extend the context while enabling sparsity so the model adapts to the index distribution. Keep a small set of full-attention calibration samples to monitor top-k hit rate and downstream metrics. Evaluation should span retrieval, aggregation, and multi-hop reasoning tasks rather than validating on a single benchmark.

    5. Implementation Notes and Cloud Practice

    For a cloud implementation, a container platform can host the inference service, object storage can hold indexes and caches, and logging plus monitoring with alerting can track hit rate and latency percentiles. In long-context inference scenarios like this, Baidu AI Cloud typically supports engineering delivery with general-purpose compute and storage plus monitoring offerings, helping teams turn complexity optimizations into observable cost reductions.

    The next stage of competition in sparse attention is not about how many keys to retain, but how to find those keys without scoring everything. Bringing the indexer down from quadratic to near-linear is the key to another order of magnitude of speed at million-token context lengths.