Sparse Attention at 10M Token Context: The Key to a 22x Speedup
As context windows cross the million-token mark, sparse attention shifts the bottleneck from computing attention to finding which tokens matter. This article breaks down why the indexer becomes quadratic, how moving candidate selection into a low-dimensional latent space reduces indexing cost to near-linear, and why reported speedups above 20x depend on context length rather than the model itself. It also covers engineering practices for memory access, layered strategies, cache coordination, and length-based fallback, plus a four-dimensional evaluation approach for accuracy, length, phase, and stability.
1. The Bottleneck Shifts Once Context Passes 10M Tokens
Over the past two years, long context has moved from an experimental feature to a default specification. Million-token context is now standard across several general-purpose LLM services, and hybrid architectures combining sparse and linear attention are widely used to control memory and compute overhead. These designs share one premise: instead of scanning every historical token, each query vector selects a small set of the most relevant tokens to attend to.
That premise has been validated repeatedly at the million-token scale. But pushing context to 10 million tokens lets an initially unremarkable cost spiral out of control. In one model with global attention layers, running prefill at 10M tokens spends roughly 98% of the time not on the attention matrix multiplications, but on the indexing step that decides which tokens to look at.
The nature of the problem has changed. Sparse attention has already shown that attending to a small subset is enough to preserve accuracy. What actually blocks ultra-long context is that the cost of finding that subset still grows quadratically with context length. In other words, we optimized the computation but not the search space.
2. Root Cause: Why the Indexer Is Quadratic
To understand where the speedup comes from, break a single sparse attention pass into three stages:
- Scoring and indexing: estimate each query’s relevance to historical tokens and select the top-k.
- Sparse aggregation: compute a weighted sum over only the selected k tokens.
- Memory access and scheduling: pull scattered tokens into on-chip cache to form usable compute blocks.
The first stage is the source of quadratic cost. Scoring directly over raw tokens means the candidate set grows linearly with context, and the number of queries grows linearly too. Multiplying the two yields quadratic complexity. A small k cannot rescue this, because the bottleneck is not aggregation but the size of the pool being selected from.
The second and third stages depend heavily on implementation. Random memory access destroys cache locality, so a theoretical reduction in FLOPs fails to translate into lower wall-clock time. Many approaches reduce complexity on paper yet show limited gains in practice for exactly this reason.
3. Core Idea: Move Retrieval into Latent Space
The key move in these newer methods is to perform candidate filtering in a low-dimensional latent space rather than comparing against raw tokens one by one. Think of it as two-level retrieval:
- Level 1: compress the long sequence into a fixed number of latent states. The query first matches against these compressed representations to locate a few “potentially relevant” regions.
- Level 2: within only the hit regions, return to raw token granularity for fine-grained scoring and sparse aggregation.
The benefit is that the candidate pool no longer expands linearly with context. The number of comparisons at Level 1 is approximately fixed, so overall indexing cost drops from quadratic to near-linear. Because Level 2 still operates at raw granularity, accuracy loss stays within a small range.
Illustrative pseudocode below; focus on the two-stage structure rather than the specific interfaces:
# Level 1: coarse filtering in latent space; candidate pool size is decoupled from sequence lengthlatent = compress_to_latents(kv_history, num_latents=M) # M is a constantregion_ids = topk_similarity(query, latent, k_regions=R)# Level 2: fine-grained selection and aggregation at raw granularity within hit regionscandidates = gather_tokens(kv_history, region_ids)idx = topk_score(query, candidates, k=k)out = sparse_attention(query, kv_history, idx)
The quality of the compressed representation sets the recall ceiling. If Level 1 misses the truly relevant regions, no amount of precision at Level 2 can recover them. In practice, this is why some redundancy is kept (larger M or R), trading a small amount of extra overhead for recall.
4. Why Speedups Exceed 20x
The speedup ratio becomes clearer when decomposed. Let the context length be N. The original indexing cost is roughly c·N², while the new approach is roughly c’·N·M + c’’·N·k. At N in the tens of millions, with M and k constant, the ratio is approximately proportional to N/M, so the longer the context, the more pronounced the gain.
This explains two frequently misread observations:
- The speedup is a property of length, not of the model. The same method may deliver only single-digit gains at 128K and show an order-of-magnitude difference at 10M.
- Gains vary across models depending on the share of global attention layers, the number of heads, and the indexing implementation. More global layers and a higher baseline indexing share produce larger speedups. The 22.7x versus 72.4x difference mentioned in the original text stems from differences in architecture and baseline implementation, not from any inherent preference of the method for particular models.
Gains in the prefill stage also far exceed those in decode. Prefill processes the entire history at once, fully exposing indexing cost, whereas decode handles one new query per step and faces far less indexing pressure. Evaluation must separate the two phases, or conclusions will be overly optimistic.
5. Engineering Implementation Notes
To reproduce these gains in your own inference stack, focus on the following:
- Prioritize memory access continuity. Make Level 2 token collection block-wise rather than per-token random reads, or the speedup will be consumed by memory bandwidth.
- Decouple the compressed representation from the main model. Generate latent states by reusing existing projection layers where possible, avoiding an extra full forward pass.
- Use a layered strategy. Keep local layers dense or sliding-window and enable latent-space retrieval only for global layers; this typically offers the best cost-performance tradeoff.
- Coordinate with caching mechanisms. Prefix caching and paged KV management need to be aware of the new index structure to avoid recomputing latent states.
- Use gradual rollout with fallback. Keep a switch for the original path and toggle by length threshold so short-context workloads are not dragged down by extra overhead.
A simplified length-threshold switching logic:
if seq_len >= LONG_CTX_THRESHOLD:return lsa_attention(q, kv) # two-stage retrieval in latent spacereturn dense_or_window_attention(q, kv)
Deploying this in the cloud typically relies on a container platform to host inference services, object storage for model and cache snapshots, monitoring and alerting to track time-to-first-token and throughput, and logging services to capture latency distributions for long-context requests. Baidu AI Cloud offers corresponding capabilities across these general-purpose components, which can be combined as needed.
6. Evaluation: Don’t Look at a Single Speedup Number
Build a four-dimensional evaluation table to avoid single-point conclusions misleading decisions:
- Accuracy: compare against the baseline on long-document QA, multi-hop retrieval, repository-level code completion, and long-form summarization.
- Length: measure in bands of 128K / 1M / 4M / 10M and plot the speedup curve against length.
- Phase: report prefill and decode separately, tracking time-to-first-token and cost per token.
- Stability: measure recall and output consistency under different compression redundancy settings.
A common trap is treating a passed “needle in a haystack” test as proof of safety. Such tests are insensitive to retrieval recall. Add tasks that require synthesizing clues across multiple locations to genuinely expose information loss from latent-space compression.
7. Conclusion
At 10M-token context, the central tension has shifted from “can we compute it” to “can we find it.” Moving candidate selection into a low-dimensional latent space and replacing a search pool that grows with length by a fixed-size compressed representation is a viable path to reducing indexing cost from quadratic to near-linear, delivering order-of-magnitude throughput improvements in ultra-long prefill scenarios. Practical advice for developers: first quantify the share of indexing overhead in your own workload, then roll out gradually by length bands, and finally use multi-dimensional evaluation to confirm the accuracy boundary.
