Long-Context Sparse Attention: The Key Path to 22x Speedups at 10 Million Tokens
This article explains why standard self-attention becomes expensive as context length grows, and why sparse attention alone does not solve the problem when the indexer itself still scales linearly with sequence length. It covers the ideal-sparse upper-bound rationale, the remaining O(T) indexing bottleneck, four composable structural optimizations, and the engineering practices needed to bring indexing close to linear and achieve order-of-magnitude prefill speedups.
1. Where the Problem Starts: Why Attention Gets Expensive in Long Contexts
In very long context scenarios, the compute and memory cost of standard self-attention grows quadratically with sequence length T: every query must compute a similarity score against every key and then perform a weighted aggregation. As T grows from a few thousand to hundreds of thousands or even tens of millions of tokens, this cost quickly becomes the dominant factor in end-to-end latency and cost, especially during the prefill stage.
A common industry approach is to split the work: 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 the attention body to O(Tk), which yields substantial gains when k is much smaller than T.
This approach relies on one premise: the model genuinely needs only a small number of keys. The usual way to validate this is an “ideal sparse upper bound” experiment—at a scale of 128k tokens, forcing each query to keep only its 512 truly most relevant keys (about 0.8% of all keys) still preserves roughly 98% of full-attention accuracy on long-context retrieval and aggregation benchmarks. This shows that sparsification is not an accuracy compromise, but a way to exploit the fact that the attention distribution is highly concentrated.
2. The Paradox: The Indexer Is Also O(T)
The problem is that to decide which 512 keys are most relevant, the indexer must first score every key. The complexity has simply been moved elsewhere rather than truly eliminated.
Different technical approaches reduce this burden by lowering scoring precision, compressing the scoring dimension, or aggregating several adjacent keys into a representative block before scoring. These methods do help, but they essentially divide the constant factor by a few times; the indexer’s scoring volume still grows linearly with context length, and overall prefill remains quadratic. Achieving order-of-magnitude speedups requires a structural change in the algorithm, not further constant-factor tuning.
The bottleneck is clear from this illustrative pseudocode:
# Naive sparse attention: the body is saved, the indexing is notscores = indexer.score(Q, K_all) # O(T^2 * d_index)idx = topk(scores, k) # selection cost on the order of O(T^2)out = sparse_attention(Q, K, V, idx) # O(T * k * d)
3. Four Composable Structural Optimization Paths
1) Hierarchical and coarse-to-fine. First run a coarse pass over the full sequence using a very low-resolution representation (such as block means or low-rank projections) to keep only candidate blocks, then do fine-grained scoring within those candidate blocks. Complexity drops from “fine scoring over everything” to “coarse scoring over everything plus fine scoring on a small subset.”
2) Low-rank and shared scoring. Write the scoring function as a low-dimensional inner product so that the key-side representation can be cached and reused, avoiding repeated reads of all keys for every query; combined with quantized storage, this significantly reduces memory bandwidth pressure.
3) Block-level pruning and dynamic k. Not every query needs the same k: retrieval-type queries need a larger k, while aggregation-type queries can use a very small k. Adapting k based on attention entropy or distribution concentration can reduce average compute with almost no loss in accuracy.
4) Two-stage prefill. The first stage uses the indexer to build a reusable hierarchical index structure (a one-time O(T log T) or near-linear cost); in the second stage, attention at each level performs only local computation. This amortizes repeated scoring across multiple inference requests.
4. Engineering Implementation Notes
- Manage the index structure and the KV cache under the same lifecycle to avoid repeated construction;
- Keep the sparse pattern as consistent as possible between training and inference to reduce distribution shift;
- Use monitoring, alerting, and logging services to observe latency and hit rates across different length ranges and pinpoint degraded ranges;
- Use elastic scaling on a container platform to route long-context requests and short requests to different resource pools.
5. Conclusion
The ceiling on sparse attention gains does not depend on “how aggressively you sparsify,” but on whether the indexing stage can break free from linear scoring. Structurally reducing indexing from O(T²) to near-linear is the key to achieving 22x-level speedups at the 10-million-token scale; in cloud environments such as Baidu AI Cloud, an end-to-end solution can be built by combining general capabilities like object storage, message queues, container platforms, and monitoring and alerting.
