Sparse Attention at 10 Million Tokens: Why the Indexer Becomes the Bottleneck and How Latent Selection Delivers 22x Speedups
As context windows cross the million-token mark, sparse attention solves the cost of computation but not the cost of selection. This article breaks down why the indexer that decides which tokens to attend to scales quadratically, explains how latent sparse attention moves selection into a compressed low-dimensional space to bring complexity back to near-linear, and provides pseudocode, an evaluation framework covering efficiency, recall, accuracy, and stability, plus practical guidance on slot count, block alignment, positional encoding, training-inference consistency, and fallback paths. Readers will learn where the reported 20x-plus prefill speedups come from and how to validate them in their own systems.
1. The Background: Once Context Passes 10 Million Tokens, the Bottleneck Shifts
Over the past two years, long context has moved from an optional feature to a default specification for flagship models. Million-token context is already standard in many cloud services, and the industry has widely adopted hybrid architectures that mix sparse and linear attention: not every query scans the entire history, but only a few of the most relevant segments take part in the computation. This approach has been repeatedly validated at the million-token scale, with controllable accuracy loss.
But as context pushes toward 10 million tokens, an originally unremarkable cost begins to spiral out of control. Take a global attention layer as an example: at the 10-million-token scale, prefill spends most of its time not on the attention matrix multiplications, but on the indexer that “decides which tokens to look at.”
The nature of the problem has therefore changed. Sparse attention has long proven that “looking at only a small part” is enough to preserve accuracy; what really blocks ultra-long context is that the cost of “finding that small part” still grows quadratically with context length. In other words, sparsification solves the amount of computation, but not the amount of selection.
2. Root Cause: Why the Indexer Is Quadratic
The naive approach scores every historical key for relevance at each query position, then takes the Top-K. Let the sequence length be N; this step costs O(N²), the same order as full attention. When N grows from 10^6 to 10^7, the computation and memory access of the indexing part grow by roughly 100x, while the K that is actually retained is usually only a few hundred to a few thousand and barely grows with N.
This leads to three engineering consequences:
- Compute mismatch: expensive compute is spent on candidates that get discarded;
- Memory bandwidth bottleneck: scoring repeatedly reads the massive key cache, so bandwidth saturates before compute does;
- Scheduling difficulty: within a prefill batch, load is uneven, making operator fusion and pipeline partitioning hard.
3. The Core Idea: Move “Selection” into Latent Space
One validated direction is latent sparse attention. Its key insight is that selection does not have to happen at the original token granularity; it can happen on a compressed low-dimensional latent representation, and the selection result can then be mapped back to the original sequence.
It can be summarized in four steps:
- Compression: aggregate the keys and values of the long sequence by block or by slot into a small number of latent vectors, reducing the scale from N to M (M far smaller than N);
- Latent-space scoring: the query computes similarity only against these M latent vectors, reducing the cost to O(N·M);
- Coarse selection and backfilling: pick a few latent slots, then do fine-grained Top-K within the original blocks corresponding to those slots;
- Sparse computation: run attention only on the finally selected original tokens.
Complexity goes from O(N²) to O(N·M + N·K), which is approximately linear in the sense that M and K are constants. Illustrative code:
# Pseudocode: two-level (latent coarse selection + intra-block fine selection) sparse attentiondef latent_sparse_attention(q, k, v, M=256, top_slots=8, k_per_slot=64):# 1) Aggregate K/V into M latent slots (mean pooling or a learnable projection)latent_k, slot_map = compress_to_slots(k, num_slots=M) # [M, d], [N]# 2) Latent-space scoring, O(N*M) but only M times per query blockslot_scores = einsum('nd,md->nm', q, latent_k) # coarse-grainedchosen = topk(slot_scores, top_slots) # select slots# 3) Fine selection within the original blocks covered by the chosen slotsidx = gather_block_indices(slot_map, chosen, k_per_slot)# 4) Run attention only on the final indicesreturn sparse_attn(q, k[idx], v[idx])
In engineering terms, the compression in step 1 can work together with chunked prefill and cache quantization; the scoring in step 2 is well suited to batched processing by query block and naturally aligns with tensor and sequence parallel partitioning.
4. Where the Gains Come From: A Reproducible Evaluation Framework
Public reports show that at the 10-million-token scale, this class of methods achieves more than 20x speedup on the prefill of a single attention layer, with even higher speedups on another model architecture, while maintaining accuracy close to the original model across a range of tasks. Understanding where the gains come from matters more than memorizing the numbers:
- Lower complexity order: the quadratic term is replaced by a near-linear term, and the larger N is, the more significant the gain;
- Reduced memory access: only the selected cache segments are read, easing the bandwidth wall;
- Near-lossless accuracy: the two-level selection provides tolerance room for “coarse filtering plus fine filtering,” with controllable recall.
Recommended evaluation dimensions:
| Dimension | Metrics to observe | Notes |
|---|---|---|
| Efficiency | Prefill latency, throughput, peak memory | Separate indexing time from computation time |
| Recall | Coverage of the selected blocks against full-attention Top-K | Measures the reliability of the approximation |
| Accuracy | Long-document retrieval, multi-hop QA, code completion | Covers tasks with different information density |
| Stability | Latency curves across different length tiers | Watch for latency spikes at certain lengths |
5. Implementation Notes and Common Pitfalls
- Choosing the number of slots M: too small hurts recall, too large degrades back to quadratic; it is recommended to grow logarithmically with length rather than linearly.
- Block boundary alignment: align compression blocks and fine-selection blocks with memory pages and cache blocks to reduce fragmented reads.
- Coordination with positional encoding: latent aggregation dilutes positional information, so position or segment identifiers must be explicitly preserved in the compression projection.
- Training-inference consistency: if sparse selection is enabled at inference, the training stage should apply corresponding sparsity-aware fine-tuning to avoid distribution drift.
- Fallback path: keep a switchable full-attention fallback for online issue diagnosis and accuracy safety.
6. Cloud Engineering Practice
To support 10-million-token context in your own workload, you can build a validation environment on general cloud capabilities: use a container platform to host inference services and elastic scaling, object storage to archive long-text corpora and checkpoints, a message queue to smooth request peaks, and logging and monitoring with alerting to observe the time share of the indexing and computation stages. Baidu AI Cloud typically provides the general capability categories above for such scenarios, making it easier to move algorithm validation quickly into an observable, rollback-capable engineering loop.
7. Conclusion
In the era of 10-million-token context, the core tension has shifted from “being able to compute” to “selecting accurately and cheaply.” Pushing the selection process down into a low-dimensional latent space and replacing global scoring with two-level filtering is currently a clear path to bring complexity back from quadratic to near-linear. For developers, the real value lies not in a particular speedup figure, but in mastering a transferable methodology: first locate the quadratic term, then break it down with compression and hierarchical selection, and finally use recall and a fallback switch to hold the accuracy baseline.
