Long-Context Inference at 10M Tokens: How Latent-Space Sparse Attention Breaks the Indexing Bottleneck for 22x Speedups
As context windows scale from millions to tens of millions of tokens, the dominant cost of long-context inference shifts away from attention itself and toward the retrieval step that decides which history fragments to attend to. This article explains why the indexer becomes the quadratic bottleneck during prefill, introduces the general approach known as latent-space sparse attention, and walks through pseudocode, complexity analysis, accuracy safeguards, and a practical engineering checklist for measuring and tuning block size, candidate redundancy, and caching.
When the context window grows from millions to tens of millions of tokens, the cost structure of long-context inference changes fundamentally. The sparse attention approach widely used across the industry has already shown that having each query attend to only a few relevant history fragments is enough to preserve accuracy. What actually spirals out of control is not attention itself, but the retrieval stage that decides which fragments to look at. This article takes a neutral view of the root cause of that bottleneck, describes a general technique known as latent-space sparse attention, and lays out an engineering design and validation method you can put into practice.
1. Background: As Contexts Get Longer, the Cost Center Shifts
Over the past two years, mainstream large model services have gradually made million-token context a default specification, and architectures that mix sparse attention with linear attention have been widely adopted. These approaches share one idea: instead of having every query scan the entire history, they select a small number of the most relevant fragments to participate in the computation.
At the million-token scale, this works well. But as the context keeps growing toward ten million tokens, an overhead that once seemed negligible begins to dominate total latency. Take a single global attention layer as an example: at ten million tokens, roughly 98% of prefill time is not spent on attention matrix computation at all, but is consumed by the “indexer” — the process of scoring, filtering, and locating candidate tokens.
The nature of the problem therefore changes. Sparsification solved the question of “how much to look at,” but it did not solve the question of “how to find what to look at.” As long as the indexing stage still grows quadratically with context length, end-to-end latency stays locked in place.
2. Locating the Bottleneck: Why the Indexer Carries the Quadratic Complexity
A long-context prefill can be broken into three cost segments:
- Similarity scoring between queries and keys: the candidate set is the full history, which grows linearly with length, and the number of queries grows with length as well; multiplying the two yields quadratic cost.
- Candidate filtering and ranking: keeping the top few fragments requires full comparison and partial sorting.
- Fragment aggregation and attention computation: this involves only the small number of selected fragments, so the cost is roughly linear.
The first two segments together make up the indexing overhead. At the million-token scale, the third segment still accounts for a meaningful share, so optimizing attention computation itself pays off. At ten million tokens, the first two segments balloon into the absolute majority, and any approach that only optimizes the third segment yields limited returns. This is also why “a faster attention kernel” struggles to deliver order-of-magnitude gains at this scale.
3. The Core Idea: Move Retrieval into Latent Space
One class of methods, known as latent-space sparse attention, answers the problem this way: rather than doing an exhaustive comparison in the original token space, first compress the long sequence into low-dimensional, searchable latent representations, then perform coarse filtering in latent space, and finally return to the original space for fine-grained computation.
The logic chain can be summarized in four steps:
- Compress: aggregate history tokens by block into a small number of latent vectors, where each block carries learnable summary information and the number of blocks is far smaller than the number of tokens.
- Coarse filtering: the query computes similarity against block-level representations in latent space and keeps only a few high-scoring blocks, reducing the scoring scale from “exhaustive at the token level” to “a small set at the block level.”
- Fine localization: perform fine-grained scoring inside the selected blocks to pick the tokens that will actually participate in the computation.
- Sparse computation: run attention only on the finally selected tokens, preserving a numerical path consistent with the original model.
The key point is that quadratic growth is interrupted by the compression ratio: the candidate scale drops from N to N/k, indexing cost falls by roughly a factor of k, and the extra overhead introduced by the growth in block count is a controllable, near-linear term.
Illustrative pseudocode:
# History side: build block-level latent representations (offline or incremental)blocks = pool(hidden_states, block_size=k) # [N/k, d]latent = compress(blocks) # low-dimensional latent vectors# Query side: coarse filtering in latent space + fine localization within blocksscore_block = query @ latent.T # [B, N/k]top_blocks = topk(score_block, m) # keep only m blockscand_idx = refine(query, blocks[top_blocks]) # fine-grained scoring within blocksout = sparse_attention(query, keys[cand_idx], values[cand_idx])
In engineering terms, the latent representations can be built once during prefill and cached, then updated incrementally during the decoding stage, avoiding repeated compression.
4. Complexity and Gains: Why Tens-of-Times Speedups Are Possible
Let the sequence length be N, the block size k, the number of blocks kept per query m, and the number of tokens kept per block r. Then:
- Original indexing cost: on the order of O(N²)
- Latent-space indexing cost: on the order of O(N·N/k + N·m·r), which is close to linear when k is large and m is small
- Attention computation cost: O(N·m·r), roughly linear in N
Published research results show that at the ten-million-token scale, prefill for a single attention layer can achieve more than twenty times speedup, and under some model architectures the figure reaches on the order of seventy times, while accuracy stays close to the original model across a range of long-context tasks. It is worth stressing that these numbers depend heavily on model architecture, block size, retention ratio, and hardware conditions. For real deployments, re-measure against your own baseline rather than applying them directly.
5. Why Accuracy Holds Up
Sparse attention has been validated repeatedly: attention distributions are themselves highly concentrated, with the vast majority of weight falling on very few fragments. The value of latent-space retrieval is that it replaces “token-by-token comparison” with a “learnable summary.” As long as the compression process preserves discriminative power, coarse filtering will not systematically miss high-weight fragments.
In practice, two safeguards are recommended:
- Local window fallback: always retain the most recent tokens so that nearby information is not missed.
- Redundant candidates: fetch more blocks during coarse filtering (raise m), trading a small amount of extra compute for recall.
6. Engineering Deployment Checklist
- Baseline measurement: break down prefill latency first and confirm whether indexing has become the dominant share, so you do not optimize in the wrong direction.
- Block size tuning: if k is too small, the compression gain is insufficient; if too large, the cost of fine localization within blocks rises. Scanning the range from 32 to 128 is recommended.
- Caching strategy: cache latent representations and block summaries per session, and use paging to reduce peak memory usage.
- Compatibility with decoding: each decoding step adds only one new query, so indexing cost is minimal there and the optimization focus remains on prefill.
- Accuracy regression: run comparative evaluations on tasks such as long-document question answering, multi-hop retrieval, and code base comprehension, and monitor recall-oriented metrics.
- Observability: bring candidate hit rate and block selection distribution into logs and monitoring alerts to make accuracy regressions easier to trace.
7. Conclusion
For ten-million-token contexts, the core tension has moved from “can we compute it” to “can we find it.” Migrating retrieval from the original token space into latent space, trading compression for the removal of quadratic complexity, is currently the most cost-effective general solution. For developers, the focus of implementation is not chasing a specific speedup multiple, but first quantifying your own indexing share, then using block size, candidate redundancy, and caching strategy to reach a balance between speed and accuracy. Combined with elastic scaling and full-chain observability built on general-purpose cloud container platforms, object storage, and monitoring and alerting capabilities, ultra-long-context services can be delivered reliably with costs kept under control.
