Millions of Tokens of Context: The Key Breakthrough for Speeding Up Sparse Attention
As context windows grow from thousands to millions of tokens, attention computation quickly becomes the most expensive stage of inference. This article breaks down why sparse attention alone does not solve the problem: the indexer that scores every key still keeps prefill at quadratic complexity. It explains how to decompose the total cost, why the index stage itself must become sub-quadratic, and which engineering optimizations still deliver predictable gains. It also outlines how to validate a sparse attention design using accuracy retention, prefill latency curves, and memory usage rather than average throughput alone.
1. The Background: The Cost Wall of Long-Context Inference
When context length grows from a few thousand tokens to millions or even tens of millions, the cost of attention quickly becomes the most expensive part of the inference pipeline. Standard full attention scales quadratically with sequence length in time, and memory consumption grows at the same pace. That makes long-document understanding, ultra-large codebase analysis, and multi-turn conversation memory hard to deploy in practice.
The most common way to cut this cost is sparse attention: instead of every token attending to every token, each token attends to only a few of the most relevant tokens. The core idea is division of labor. A lightweight indexer first selects a handful of the most relevant keys for each query, and the actual attention is then computed only over that small candidate set. This pushes the cost of attention itself down to roughly linear in sequence length.
This approach rests on one key premise: on most tasks, the model really does need only a small number of keys to preserve quality. The usual way to verify this in the industry is an “ideal sparsity” control experiment: on a long-context benchmark, force each query to keep only a tiny fraction of its truly most relevant keys, then measure the accuracy loss. Published research under this setup has reported retaining more than ninety percent of full-attention accuracy, which shows the gains from sparsification are real rather than a pure approximation trade-off.
2. The Overlooked Paradox: The Indexer Becomes the New Bottleneck
The problem hides in the indexing step. To decide which keys are most relevant, the indexer must first score every key. So while the cost of attention itself is reduced, the scoring work does not disappear; it still grows linearly with context length. Combined with the aggregation that follows, the prefill stage as a whole remains quadratic.
Common ways to reduce this burden include lowering the numerical precision of scoring, compressing the dimensions used for scoring, and aggregating several adjacent keys into one representative before scoring (block sparsity). These techniques do help, but their essence is dividing a constant factor by a smaller number. They do not change the growth order of the complexity. When context grows from hundreds of thousands to tens of millions of tokens, both the linear and quadratic terms are amplified, and the benefit from constant-factor optimization is quickly diluted.
The real breakthrough direction, then, is not to keep squeezing the indexer’s constant factor, but to change the complexity profile of scoring itself at the algorithmic level.
3. Breaking Down the Complexity: Accounting for the Total Cost
Splitting a long-context prefill into three parts makes the bottleneck easier to locate:
- Index scoring: for each query, traverse all keys and produce relevance scores, on the order of O(T²) or O(T²/d), where d is the compressed dimension.
- Candidate selection: pick the top k from the scores, on the order of O(T·k), or lower with a block structure.
- Attention itself: computed only over the k candidates, on the order of O(T·k).
Full attention: O(T²)Block sparse + low-precision index: O(T²) / c # c is a constant factorIdeal target: O(T·k) + index cost # index cost must be sub-quadratic
The conclusion is straightforward: as long as index scoring still scans all keys per query, the overall cost cannot escape quadratic growth. To gain another order of magnitude at tens of millions of tokens, the indexing stage itself must become sub-quadratic, for example through hierarchical clustering, learnable coarse-grained buckets, approximate-nearest-neighbor-style retrieval, or merging scoring with state compression into a single linear scan.
4. A Practical Checklist of Engineering Optimizations
Beyond algorithmic structure, there is still plenty of predictable gain on the engineering side:
- Chunking and shared indexes: let adjacent queries share the same coarse-grained candidates to avoid repeated scoring.
- Caching and reuse: keep the computed compressed key representations resident in memory or offload them to higher-tier storage to avoid rebuilding them.
- Batching and operator fusion: fuse scoring, selection, and aggregation into a few kernels to reduce memory access and launch overhead.
- Precision tiering: use low precision for the index and higher precision for attention itself, balancing speed and quality.
- Elastic scaling: use container platforms and scheduling to adjust parallelism and instance sizing dynamically based on context length.
- Observability: track time-to-first-token, prefill time, and peak memory with logging services and monitoring alerts to close the tuning loop.
5. How to Validate the Results: Do Not Look at Average Throughput Alone
When evaluating a sparse approach, cover at least three categories of metrics. First, accuracy retention on long-context benchmarks, especially needle-in-a-haystack retrieval of key information. Second, the prefill latency curve across different context lengths, to see whether it truly shifts from quadratic to near-linear. Third, the combined behavior of memory usage and time-to-first-token. Only when all three improve at once can you conclude the optimization is structural rather than a cost shifted elsewhere.
6. Conclusion
The key to acceleration at the tens-of-millions-of-tokens scale is not shrinking the indexer’s constant factor by a few more times, but accepting that indexing is the bottleneck and replacing full scoring with a sub-quadratic index structure. For developers, the right order is: first break down the complexity to locate the bottleneck, then combine algorithmic structure with engineering techniques, and finally validate the gains across three dimensions: accuracy, latency, and memory. To serve this kind of long-context inference, you can build the deployment and tuning loop on general capabilities such as container platforms, object storage, logging services, and monitoring alerts from Baidu AI Cloud.
