Sparse Attention at 10 Million Tokens: Why the Bottleneck Shifts to Token Selection and How Latent-Space Retrieval Delivers Up to 22x Speedups
As context windows scale from millions to tens of millions of tokens, the cost structure of long-context inference inverts: the slowest step is no longer computing attention but deciding which tokens to look at. This article explains why the indexer becomes the dominant cost, introduces latent sparse attention, which moves relevance retrieval from the raw token space into a compressed latent space, and provides complexity analysis, pseudocode, accuracy validation methods, and an engineering checklist for evaluating the trade-offs of ultra-long context deployments.
When the context length grows from millions to tens of millions of tokens, the cost structure of long-text inference undergoes a fundamental reversal: what slows the system down is no longer attention itself, but the step that decides which tokens to look at. This article takes a neutral view of the causes of that bottleneck and introduces a family of approaches known as latent sparse attention, which moves relevance retrieval out of the raw token space and into a compressed latent space. It includes complexity analysis, pseudocode, methods for validating accuracy, and an engineering checklist, so developers can judge where the gains end and where the risks begin in ultra-long context scenarios.
1. The reversal: the bottleneck moves from computing attention to finding tokens
Over the past two years, long context has quickly become a default specification for large model serving. Million-token context has moved from an experimental feature to a standard configuration, and ten-million-token context is coming into view. The key design behind this progress is that each query no longer scans every historical token; instead, it selects a few of the most relevant segments to participate in the computation, which is sparse attention. This strategy has been validated repeatedly at the million-token scale: on most tasks, attending to only a small portion of the history keeps accuracy loss manageable.
But when the length grows by another order of magnitude, an overhead that once seemed negligible starts to spiral. Take a global attention layer as an example: performing prefill at ten million tokens, most of the time is not spent computing the attention matrix, but on the indexer, meaning the score-filter-locate pipeline. Put differently, sparsification saves computation; what it does not save is retrieval.
The nature of the problem therefore changes. Sparse attention has already shown that attending to only a small portion is enough; what actually blocks ultra-long context is that finding that small portion still grows quadratically with length. Any optimization that only subtracts on the compute side will hit a ceiling at the ten-million-token scale.
2. Why indexing grows quadratically
Breaking a single global attention pass into three steps makes it easier to see:
- Scoring: compute similarity between the query and all historical representations, roughly O(N*d);
- Selection: keep the top-k, O(N log k) or O(N);
- Aggregation: run attention only over the selected k positions, O(k*d).
The first two steps both depend linearly on N, but once layers and heads stack up, the end-to-end cost on long sequences is dominated by retrieval. And if you also account for insufficient cross-layer reuse, repeated scoring, and the enlarged candidate sets used to protect recall, the real overhead clearly exceeds the theoretical linear term. Common amplifying factors in practice include:
- Each attention head retrieves independently, so indexing is repeated h times;
- Candidate sets are expanded from k to several times k to protect recall;
- Index results cannot be shared across layers, so every layer recomputes them;
- Non-contiguous memory access leads to low bandwidth utilization and idle compute.
An illustrative complexity comparison (d is the hidden dimension, k is the number of selected positions, m is the latent-space length, m << N):
Raw token-space retrieval: O(N*d) once per head per layerLatent-space retrieval: O(m*d) m decoupled from NAggregation stage: O(k*d) same for both
The key is decoupling m from N: as long as the latent-space length does not grow linearly with the raw length, retrieval cost changes from growing with context to being roughly constant.
3. Latent sparse attention: moving retrieval onto compressed representations
One class of methods, referred to in the industry as latent sparse attention, comes down to a single idea: do not make relevance judgments on raw tokens, make them on compressed latent representations.
The structure typically has three components:
- Compressor: compresses a continuous run of historical tokens into a shorter sequence of latent states of length m, far smaller than N. Common approaches include block pooling, low-rank projection, and learnable slot aggregation;
- Latent-space indexer: performs scoring and top-k selection over the m latent states, at a cost determined by m;
- Back-mapping and aggregation: maps the selected latent states back to intervals of raw positions, and runs attention only over the small number of tokens in those intervals.
Pseudocode:
# N: raw length, m: latent-space length (m << N), k: number of selected latent slotsdef lsa_attention(q, K, V, compress, indexer, expand, k):z, z_to_span = compress(K) # compress: N -> m, also record the token span each slot coversscores = indexer(q, z) # score in latent space, complexity O(m*d)top_slots = scores.topk(k).indices # select a few latent slotsspans = expand(top_slots, z_to_span)# latent slots -> raw token intervalsidx = merge_and_dedup(spans) # merge overlapping intervals, deduplicatereturn softmax(q @ K[idx].T) @ V[idx]
Three details that are easy to overlook but decide success or failure:
- Coverage completeness: every raw token must be covered by at least one latent slot, otherwise regions that are permanently invisible will appear;
- Interval merging: when multiple latent slots map to adjacent intervals, merge and deduplicate them to avoid repeated computation;
- Forced retention window: the most recent tokens and the task instruction region should unconditionally enter the candidate set, to prevent retrieval drift.
4. Why accuracy holds up
Sparse attention works because the attention distribution is itself highly concentrated: most of the mass falls on very few positions. The latent-space approach adds a layer of compression on top of that, so it has to answer whether compression loses information. The industry generally relies on three safeguards:
- Training alignment: align the indexer’s score distribution with the true distribution of the original attention, typically using distillation or distribution-matching losses;
- Recall fallback: keep a local window plus a small number of randomly sampled slots to reduce the probability of misses;
- Layered strategy: use a more aggressive compression ratio in shallow layers and relax it progressively in deeper layers, balancing early feature aggregation against later semantic retrieval.
Perplexity alone is not enough for evaluation. It is advisable to cover at least four task types: single-point retrieval (needle-in-a-haystack localization), multi-hop reasoning, long-document summarization, and long-range code or structured-data understanding. The first two test recall; the latter two test whether compression has damaged fine-grained information.
5. Engineering checklist
- Make the compression ratio configurable: sensitivity to m varies widely across tasks, so it is best exposed as a parameter tunable per layer and per head;
- Reuse index results as much as possible: share or cache latent states across layers to avoid recomputing at every layer;
- Prioritize memory access: put contiguous interval reads first in the design to reduce the bandwidth waste caused by gather operations;
- Decouple from the decode stage: prefill sees the largest gains, while decode needs a separate path for incrementally updating the compressed state;
- Gradual rollout and fallback: keep the original full path as a switch, and switch automatically based on a length threshold;
- Observability: bring retrieval time share, average candidate length, and recall hit rate into monitoring, alerting, and logging, run stress tests on a container platform, and archive long-text evaluation sets in object storage.
6. Where the gains end and what the risks are
These methods are not free. Compression introduces extra parameters and state management; tasks that depend heavily on exact long-range matching (such as locating a unique identifier in extremely long logs) are more sensitive to the compression ratio; implementation complexity rises and the debugging chain gets longer. A reasonable judgment is that the gains are most pronounced once the context reaches several million to ten million tokens and retrieval overhead has become dominant; below a few hundred thousand tokens, conventional sparse schemes are usually sufficient.
7. Conclusion
In the next stage of ultra-long context, the competition is not about how fast you compute, but about how accurately and how cheaply you find. Moving relevance retrieval from the raw token space to a latent space that is decoupled from length is a currently validated technical path. For developers, what matters more in practice is designing the compression ratio, the recall fallback, and the observability metrics together, so that the performance improvement rests on verifiable accuracy.
