Sparse Attention at 10M Context: The Key to a 22x Speedup
As context windows grow from millions to tens of millions of tokens, the bottleneck in sparse attention shifts from computing attention to finding which tokens to attend to. This article breaks down why the indexing overhead scales quadratically, and how moving retrieval into a compressed latent space reduces that cost to near-linear. It covers the three-stage architecture, why accuracy is largely preserved, an engineering deployment checklist, and guidance on when this approach is—and isn't—worthwhile.
1. The Background: When Context Grows, the Bottleneck Moves
Over the past two years, long-context capability has shifted from an experimental feature to a baseline specification. Million-token context is becoming a default configuration for many model services, and architectures that mix sparse attention with linear attention are entering mainstream design. These approaches share a common premise: instead of having every query vector scan the entire history of tokens, each query selects a small number of the most relevant positions to participate in the computation.
At the million-token scale, this trade-off has been repeatedly validated as worthwhile. But as context pushes toward ten million tokens, an overhead that once seemed negligible starts to spiral out of control. Take a single global attention layer as an example: at ten million tokens, roughly 98% of the prefill time is not spent on the matrix operations of attention itself, but on the indexing step that “decides which tokens to look at.”
This means the nature of the problem has changed. Sparse attention has long proven that “looking at only a small fraction” is enough to preserve accuracy. What actually blocks ultra-long context is the act of “finding that small fraction”—and its cost still grows quadratically with context length.
2. Root Cause: Why Indexing Overhead Is Quadratic
Splitting a single global attention layer into two stages makes the cost structure clearer:
- Scoring and selection: evaluate the relevance of candidate keys for each query position, then pick the top-k.
- Aggregation: compute a weighted sum over only the selected k positions.
The second stage has a complexity of O(n·k), which grows linearly with n when k is fixed—very manageable. A naive implementation of the first stage requires scanning all n keys for every query, giving a complexity of O(n²) that cannot be avoided even when k is small. When n grows from 10⁶ to 10⁷, the theoretical cost of this stage rises by roughly 100x, while compute and memory bandwidth do not grow in step.
Common engineering mitigations—blocked scanning, quantized scoring, caching index results—can reduce the constant factors but do not change the order of magnitude. As long as “selection” depends on pairwise comparison across all raw tokens, the quadratic term remains.
3. The Core Idea: Move Retrieval into Latent Space
One class of new approaches offers an answer: rather than doing a full comparison in the raw token space, first compress the long sequence into a much smaller latent space, complete candidate filtering there, and then return to the original space for exact aggregation. You can think of it as “build a table of contents first, then flip through the book,” instead of reading from the first page to the last every time.
The structure typically consists of three components:
- Compressor: maps contiguous blocks of historical tokens into a small number of latent states; block size and the number of latent states together determine the compression ratio.
- Latent-space scorer: computes a dot product or lightweight similarity between the query vector and the latent states to select candidate blocks, then locates specific tokens within those blocks.
- Exact aggregator: applies standard attention weighting only to the finally selected tokens, keeping the numerical path identical to the original implementation.
The schematic pseudocode below emphasizes the stage division rather than specific interfaces:
# Stage 1: Build the latent-space index (parallelizable and incremental during prefill)latent = compressor(blocks) # [n_blocks, d_latent]# Stage 2: Filter candidate blocks in latent space, complexity O(n_blocks * d_latent)scores = query @ latent.T # [n_q, n_blocks]block_ids = topk(scores, k_blocks)# Stage 3: Intra-block localization + exact aggregation, complexity O(n_q * k_tokens)out = exact_attention(query, keys[block_ids], values[block_ids])
The key is that n_blocks is far smaller than n, and latent-space scoring is a single matrix multiplication rather than a pairwise comparison. As a result, the first stage degrades from quadratic to near-linear.
4. Why the Speedup Materializes
Summing the three stages reveals where the gains come from: total overhead is roughly the compression cost plus the latent-space retrieval cost plus the exact aggregation cost, and none of the three contains an n² term. Reported figures in public discussions indicate that at the ten-million-token scale, prefill for a single attention layer can be sped up by more than twentyfold, with some model configurations seeing speedups of several tens of times.
It is worth stressing that these multipliers are measured at the “single operator, single stage” level, not end-to-end throughput. In a real service, you also need to account for the cost of building the compressor, storing and updating the index, and scheduling overhead across different layers. Evaluations should stick to an apples-to-apples comparison: the same batch, the same sequence length, and the same accuracy metrics.
5. Why Accuracy Barely Drops
The key to preserving accuracy is the “separation of retrieval and computation.” Candidate filtering is allowed to be noisy; as long as recall is high enough, the keys and values that ultimately participate in aggregation are still the original ones, and the numerical path is not approximated. This is fundamentally different from the route of “replacing the attention output with a low-rank approximation,” where the error enters the result directly.
In practice, three main factors affect recall: block granularity that is too coarse leads to imprecise candidate localization; insufficient latent-state dimensionality distorts similarity; and query distribution drift causes index mismatch. The corresponding routine practices are to moderately reduce block granularity, increase the latent dimension, and periodically rebuild the index during incremental generation over long sequences.
6. Engineering Deployment Checklist
- Layered strategy: enable latent-space retrieval only in some global layers, and keep windowed attention in local layers to balance cost and quality.
- Incremental updates: build the index in batches during prefill and append per block during decode, avoiding a full rebuild at every step.
- Memory and bandwidth: latent-state storage is far smaller than raw KV, but the compressor’s temporary footprint and memory access patterns still need evaluation.
- Observability: bring index build time, candidate recall, and block hit rate into logging and monitoring alerts so you can pinpoint where the bottleneck has moved.
- Elastic scaling: long-context inference is sensitive to memory, so consider combining elastic scheduling from a container platform with object storage to hold long-session state.
7. Applicability and Selection Guidance
Latent-space sparse attention is not a universal accelerator. When context is short, the fixed cost of compression and indexing may outweigh the benefit; for exact-retrieval tasks (which require word-by-word comparison over the full history), recall requirements are extremely high and warrant careful validation; and if the index-building logic differs between training and inference, it introduces distribution shift.
The recommended path is to first align the accuracy baseline on small-scale sequences, then gradually scale up to the target length while observing whether the index-stage share drops as expected, and finally stress-test end-to-end latency and cost. If you are running this kind of long-context inference on Baidu AI Cloud’s compute and storage capabilities, it is likewise advisable to record data on both tracks—“single-operator measure” and “end-to-end measure”—to avoid distorted conclusions.
Overall, the next stretch of optimization for ultra-long context has shifted from “computing a bit less attention” to “more intelligently finding the part that needs computing.” Moving retrieval into latent space is currently a viable path for genuinely driving down the quadratic term.
