Sparse Attention at 10 Million Tokens: Engineering a 22x Speedup by Fixing the Indexer
As context windows cross the 10-million-token mark, the bottleneck in sparse attention shifts from computing attention to deciding which tokens to attend to. This article breaks down why the indexing step becomes the new quadratic cost center, explains how latent sparse attention moves the lookup into a compressed latent space for coarse-to-fine retrieval, and details five key engineering decisions: block size, latent dimension, train-inference consistency, cache reuse, and numerical stability. It also covers accuracy evaluation with needle-in-a-haystack, multi-hop reasoning, and long-document tasks, plus recall and indexing-time metrics, and how cloud infrastructure can support stable deployment. Readers will learn where the 22x-and-higher speedups come from and what tradeoffs to tune.
1. Background: The Bottleneck Shifts Once Context Passes 10 Million Tokens
Over the past two years, long context has moved from an optional feature to a default specification. Million-token context is becoming a standard configuration for mainstream model serving, and hybrid architectures combining sparse and linear attention are widely adopted. The shared premise of these designs is straightforward: instead of having every query vector scan the entire token history, each query selects only a small set of the most relevant tokens for computation.
At the million-token scale, this approach has been validated repeatedly. But as context pushes toward 10 million tokens, an initially negligible overhead starts to spiral out of control. In one global attention layer at the 10-million-token scale, roughly 98% of the prefill time is not spent on the attention computation itself, but on the indexing step that decides which tokens to look at.
This changes the nature of the problem. Sparse attention has already proven that attending to a small subset is enough to preserve accuracy. What actually blocks ultra-long context is that the cost of finding that small subset still grows quadratically with context length.
2. Root Cause: Why the Indexer Becomes the New Complexity Center
To understand where the speedup comes from, split the attention stage into two steps:
- Selection (indexing): locate a candidate token set for each query.
- Attention compute: perform weighted aggregation over the candidate set.
In dense attention, both steps are fused into a single matrix multiplication with O(N²) complexity. Sparsification only compresses the second step. If the first step still scores or ranks the full history, complexity remains O(N²), just with a smaller constant. As N grows from 10⁶ to 10⁷, the absolute time spent on indexing is amplified into the dominant cost.
Schematically, a naive indexer looks like this:
# Naive approach: score every query against the full history, O(N^2)scores = query @ keys.T # [N, N]topk_idx = scores.topk(k, dim=-1).indicesout = gather_and_aggregate(values, topk_idx)
There are two hidden engineering costs. First, the intermediate [N, N] score matrix puts heavy pressure on GPU memory. Second, top-k sorting itself introduces blocking and synchronization overhead. Combined, these make the indexer both slow and resource-hungry on long sequences.
3. Core Idea: Move the Lookup into Latent Space
One validated direction is latent sparse attention. Rather than scoring the full history directly in the original token dimension, it first compresses keys and values into a lower-dimensional latent representation, performs coarse-grained retrieval in latent space, and then returns to the original space for fine-grained aggregation. The pattern is coarse-to-fine, layered localization:
- Compression: project historical key vectors into a lower-dimensional latent space to form a compact index.
- Coarse retrieval: the query locates a small number of candidate blocks in latent space, sharply reducing complexity.
- Fine aggregation: attention is computed only over the original tokens in the candidate blocks.
The gains come from two sources. The latent dimension is far smaller than the original dimension, significantly reducing the constants in scoring and sorting. Block-level coarse retrieval reduces the O(N²) candidate comparison to roughly O(N·√N) or O(N·logN), depending on the block and index structure. On a single-layer prefill at 10 million tokens, this class of methods can deliver more than 20x speedup, and models with larger architectural differences can reach several tens of times faster.
Note that the speedup ratio is strongly tied to model architecture. The higher the proportion of global attention layers and the more aggressive the latent compression, the more pronounced the gains. If a model is dominated by linear attention, the available headroom narrows accordingly.
4. Engineering Implementation: Five Key Design Points
- Blocking strategy. Block size is the core tradeoff between accuracy and speed. Blocks that are too small create too many index entries; blocks that are too large introduce redundant candidates. In practice, sizes that are friendly to hardware memory access (such as 64/128/256) are common, aligned to memory page size.
- Latent dimension selection. Too low a compression dimension loses retrieval recall; too high degrades back to the original complexity. Start ablations from 1/4 to 1/8 of the original dimension.
- Train-inference consistency. If the model was not trained with latent-space indexing, swapping it in directly causes accuracy drift. A practical approach is index distillation first, making the coarse retrieval distribution approximate the top-k distribution of full scoring.
- Caching and incremental reuse. The latent index built during prefill can be reused in the decode stage, combined with paged caching (similar to KV cache management) to avoid rebuilding.
- Numerical stability. Latent-space scoring needs scaling and normalization to prevent logit overflow on long sequences.
A simplified pseudocode for layered retrieval:
# 1) Build the latent index (once during prefill)latent_keys = proj_k(keys) # [N, d_latent], d_latent << dblocks = chunk(latent_keys, size=128)# 2) Coarse retrieval: query locates candidate blocks in latent spaceq_latent = proj_q(query)block_scores = q_latent @ blocks.mean(dim=1).Tcand_blocks = block_scores.topk(b=8).indices# 3) Fine aggregation: compute only over original tokens in candidate blocksmask = build_mask(cand_blocks)out = sparse_attention(query, keys, values, mask)
5. Accuracy Safeguards and Evaluation
Speedups must not come at the cost of collapsing accuracy. Evaluation should cover three task types:
- Needle-in-a-haystack retrieval: verifies long-range precise localization.
- Multi-hop reasoning and aggregation: verifies whether candidate recall covers key evidence.
- Long-document summarization and code understanding: verifies global semantic completeness.
Beyond task accuracy, record candidate recall (the proportion of true top-k covered by coarse retrieval) and the share of time spent on indexing. If recall falls below roughly 95%, it usually means blocks are too large or the latent dimension is insufficient, and parameters need to be dialed back.
6. Combining with Cloud Engineering Practice
In real workloads, ultra-long context often comes with high concurrency and long-lived connections. General cloud capabilities can provide supporting infrastructure: container platforms to host elastic inference replicas, object storage to hold long-document corpora, message queues to smooth traffic peaks, and logging plus monitoring and alerting to track indexing time and recall drift. Baidu AI Cloud offers standardized support across these general categories, helping teams turn a single-point algorithm optimization into a stable service capability.
7. Conclusion
In the 10-million-token era, the competition in sparse attention has shifted from computing fast to finding accurately and fast. By compressing the index dimension and using layered retrieval, latent sparse attention pulls the dominant cost back from quadratic to near-linear, achieving order-of-magnitude speedups while preserving accuracy. For developers, the key to deployment lies in the tradeoff between block size and latent dimension, train-inference consistency, cache reuse, and an evaluation loop centered on recall.
