10-Million-Token Context: Solving the Indexing Bottleneck in Sparse Attention
This article explains why token selection, rather than the attention computation itself, becomes the main bottleneck in sparse attention at ten-million-token context lengths. It describes Latent Sparse Attention (LSA), which runs top-k selection in a compressed latent space and keeps the original-dimension keys and values for the final attention step. It also covers how to profile prefill time, compare speed at equal accuracy, and weigh memory and deployment trade-offs.
1. The Evolution of Long Context and the Rise of Sparse Attention
Context windows of one million tokens have gradually become a common specification for mainstream models. The key to this capability lies in how attention is computed. Standard attention has every query compute relevance against all historical tokens, so the cost grows with the square of the context length. When context grows from a few thousand tokens to one million, this cost becomes difficult to bear.
Sparse attention reduces the set of tokens involved in the computation. Each query interacts with only a small number of the most relevant keys, and the remaining tokens are skipped. Many experiments show that model accuracy stays largely intact as long as the right tokens are selected. As a result, sparsification has become a common technique in long-context inference.
2. The Core Problem: Selection Itself Becomes the Bottleneck
Sparse attention depends on quickly finding the relevant small subset of tokens. The selection process usually runs a rough scoring pass over all historical keys first, then takes the highest-scoring ones. This step still requires each query to scan every key, so its cost also grows quadratically with context length.
Consider a concrete estimate. Assume a context of 10 million tokens. For a single head in a single layer, each query must compute inner products with 10 million keys. Across all queries, this totals roughly 10^14 dot-product operations. With a vector dimension of 128, each dot product involves 128 multiply-add operations, so the total reaches the order of 10^16. This is far larger than the cost of the sparse attention computation itself.
This changes the priority of optimization. Earlier efforts focused on reducing the cost of actually performing attention. In ultra-long contexts, the main constraint has shifted to the indexing stage, which decides where to look. During prefill, if indexing takes up most of the time, optimizing the attention kernel alone yields limited gains.
3. The Basic Idea of Latent Sparse Attention
Latent Sparse Attention (LSA, referred to below as LSA) targets the indexing stage. Its core idea rests on two points.
First, selection and computation are decoupled. The representations used to score and choose tokens can differ from the representations used in the final attention computation. The scoring stage uses compressed, low-dimensional latent representations, so its cost falls as the dimension decreases. The final attention computation still uses the original representations, which preserves output accuracy.
Second, compression applies only to the selection process. The latent representation only needs to keep the ranking roughly correct, not retain all of the information. This keeps the accuracy loss from compression within an acceptable range.
The code below shows the structure of this process. The exact form of the low-dimensional projection depends on the implementation. The snippet only illustrates the data flow:
import torchdef select_topk_latent(q_latent, k_latent_cache, topk):"""Select the top-k key tokens for each query in the low-dimensional latent space.q_latent: [num_queries, r] Latent representations of queries, where r is much smaller than the original dimension dk_latent_cache: [num_keys, r] Cached latent representations of historical keysReturns: [num_queries, topk] Indices of the selected tokens"""scores = q_latent @ k_latent_cache.T # Low-dimensional scoring, cost proportional to rreturn scores.topk(topk, dim=-1).indicesdef sparse_attention(q, k, v, indices):"""Run standard attention only on the selected tokens, using the original-dimension k and v."""k_sel = k[indices] # [num_queries, topk, d]v_sel = v[indices]attn = torch.softmax((q.unsqueeze(1) * k_sel).sum(-1) / q.shape[-1] ** 0.5, dim=-1)return (attn.unsqueeze(-1) * v_sel).sum(1)
This design does not remove the scan over all keys. It lowers the constant cost of each scoring operation and concentrates the accuracy risk on whether the ranking is correct. The compressed dimension r is therefore a trade-off that must be measured. If r is too small, the ranking quality degrades. If r is too large, the gains shrink.
4. How to Evaluate Performance
When evaluating this kind of approach, measure both speed and accuracy, and measure both across multiple context lengths.
1. Break Down the Time First
Before optimizing, time the prefill stage in segments. Distinguish at least the following parts: index scoring, token selection, sparse attention computation, and other modules such as projections and normalization. If the indexing share is lower than expected, the room for speedup is limited. The judgment should rest on each stage’s share of total time, not on a single end-to-end latency figure.
2. Compare Speed at Fixed Accuracy
A speedup only means something when accuracy is comparable. Fix the model and the evaluation set, then compare the throughput of the original sparse approach and the improved approach at the same accuracy. Common evaluations include long-document question answering, cross-passage information retrieval, and multi-hop reasoning. These tasks expose cases where the indexing stage misses critical tokens.
3. Cover Multiple Length Ranges
Indexing cost grows faster with length than other parts of the computation, so conclusions drawn at short lengths do not transfer directly to longer ones. Cover at least three ranges: hundreds of thousands, millions, and tens of millions of tokens. Observe how the speedup changes with length.
According to publicly reported experiments, at the scale of 10 million tokens, single-layer attention prefill achieved speedups of about 20-plus times and 70-plus times on two different models, with accuracy close to the original models. These figures serve as a reference only. Actual gains depend heavily on model architecture, hardware, and implementation details, so readers should reproduce the results in their own environment.
5. Practical Considerations for Deployment
1. Memory Overhead of the Latent Cache
Latent representations must be stored alongside the KV cache. If the compressed dimension is large, the extra memory use can offset part of the gain. Before deployment, estimate the additional storage per token, then determine the context limit based on the available memory.
2. Interaction with Other Optimizations
Sparsification, quantization, and chunked prefill can be combined, but the order of application affects results. For example, low-precision quantization changes the numerical distribution of scores, which can affect the stability of top-k selection. Introduce one change at a time and record the accuracy impact of each.
3. Regression Testing
Regression tests for long-context capability should cover needle-in-a-haystack retrieval tasks and tasks that require integrating information across large spans of text. Short-text benchmarks alone cannot reveal indexing omissions.
4. Deciding Whether the Approach Fits
If a business workload consistently stays below a few hundred thousand tokens, indexing cost usually is not the main bottleneck. In that case, the latent approach offers limited benefit and adds maintenance cost. Invest in this engineering work only when ultra-long context is a real business requirement.
6. Future Directions
Long-context inference is shifting its focus from how to compute attention to how to decide efficiently which parts to compute. Indexing optimization will likely integrate more closely with model architecture design. For example, training may learn compact selection representations from the start, rather than relying only on approximation at inference time. For engineering teams, building the ability to profile performance by stage early is more useful for long-term decisions than chasing a single point of speedup.
