Sparse Attention at 10 Million Tokens: Solving the Quadratic Indexing Bottleneck with Latent Sparse Attention
As context windows scale from millions to tens of millions of tokens, sparse attention faces a hidden cost: the real bottleneck is not attention computation but the indexing step that decides which tokens to attend to. This article breaks down why indexer overhead grows quadratically with context length, introduces Latent Sparse Attention (LSA), which moves relevance retrieval into a low-dimensional latent space to bring overall complexity below quadratic, and covers engineering implementation details, sample code, the accuracy-versus-performance trade-off, and general architecture guidance for cloud deployment.
1. Background: The Context Length Race Is Shifting the Cost
Over the past two years, long context has moved from an optional feature to a default specification. Million-token context is becoming standard in mainstream model services, and some vendors have made one million tokens the default input limit for their official offerings. Meanwhile, newly released model families have begun supporting the same scale, some for the first time combining sparse attention with linear attention in a hybrid architecture.
These designs share one consistent choice: instead of having each query scan every historical token, the model selects only a few of the most relevant keys for computation. This approach has been repeatedly validated at the million-token scale. But as context pushes toward ten million tokens, an initially unremarkable cost starts to spiral.
Consider a typical global attention layer running the prefill stage at ten million tokens. Most of the time is not spent on attention itself, but on the indexer 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 blocks ultra-long context is that finding that subset still grows quadratically with context length.
2. Cost Breakdown: Attention Is Cheap, Indexing Is Expensive
2.1 The Baseline Cost of Full Attention
In standard full attention, every query computes relevance against all previous keys. With context length T, the prefill compute is roughly O(T²), and the incremental cost of decoding one token is roughly O(T). Going from one million to ten million tokens increases prefill attention compute by about 100x in theory.
2.2 The Division of Labor in Sparse Attention
The core idea of sparse attention is a division of labor: a lightweight indexer first picks the k most relevant keys for each query, and the actual attention runs only over those k keys. This pushes the main attention cost down to O(Tk), a huge win when k is much smaller than T.
This works under one premise: the model really does need only a few keys. The industry has validated this at medium lengths. At around a hundred thousand tokens, letting each query attend to only its 512 most relevant keys, a tiny fraction of all keys, still preserved roughly 98% of full-attention accuracy on long-context benchmarks. So “sparse is sufficient” largely holds at the accuracy level.
2.3 The Overlooked Quadratic Term
Here lies a paradox. To know which 512 keys are most relevant, the indexer must first score every key. If scoring requires the query to interact with all keys, the indexing stage degrades to O(T²), eating up the compute saved by the attention body. Existing engineering tricks, such as lowering scoring precision, compressing dimensions, or aggregating multiple keys into a block, only shrink the constant factor. They do not change the order of magnitude.
Total cost ≈ indexing cost O(T²) + attention cost O(Tk)When T goes from 1M → 10M with k fixed, the indexing term grows 100×, while the attention term grows only 10×Conclusion: the larger T is, the more indexing dominates
3. Latent Sparse Attention: Moving Retrieval into a Low-Dimensional Space
Recently, an overseas startup research team and a European technical university jointly proposed Latent Sparse Attention (LSA), targeting sub-quadratic attention for ultra-long context. Its central claim can be summarized in one sentence: do not perform full scoring in the original token space; instead, project both query and key into a low-dimensional latent space and complete relevance retrieval there.
The reported gains are substantial: at ten million tokens, a single attention layer’s prefill can be sped up by more than an order of magnitude, with speedups ranging from about 20x to 70x across different model sizes, while maintaining accuracy close to the original model on multiple long-context tasks.
3.1 Why the Latent Space Reduces Complexity
In the original space, query and key vectors are high-dimensional and dispersed, making full scoring unavoidable. The latent space helps in three ways:
- Dimensionality reduction: compressing high-dimensional representations into a low-dimensional space sharply lowers the constant cost of scoring;
- Better separability: relevance structure is more concentrated in the low-dimensional space, improving the recall of approximate retrieval;
- Indexability: low-dimensional vectors are well suited to approximate nearest-neighbor structures, turning “find top-k” from a linear scan into sublinear retrieval.
When retrieval complexity drops from O(T) to roughly O(log T) or O(√T), the overall indexing cost falls from O(T²) to sub-quadratic, which is where the LSA name comes from.
3.2 How It Differs from Existing Approaches
- Versus block sparsity: block sparsity uses aggregation to reduce the number of scorings, but comparisons within a block still happen in the original space; LSA moves the comparison into the latent space, changing the order of magnitude rather than the constant.
- Versus linear attention: linear attention approximates softmax with kernel functions, sacrificing exact retrieval; LSA preserves exact top-k retrieval semantics and applies approximation only in the retrieval space.
- Versus full attention: full attention is infeasible at ten million tokens; LSA brings prefill back into a usable range while preserving accuracy.
4. Engineering Implementation
4.1 Decoupling the Indexer from the Attention Body
In implementation, treat the indexer as an independent module: it takes the query latent vector and the set of key latent vectors as input and outputs top-k indices; the attention body receives only the index results. Decoupling the two through a clear interface makes it easy to optimize and replace each separately.
# Sample: latent retrieval + sparse attentiondef latent_sparse_attention(q, k, v, proj_q, proj_k, topk):q_lat = proj_q(q) # project into the low-dimensional latent spacek_lat = proj_k(k)idx = approx_topk(q_lat, k_lat, topk) # sublinear retrievalk_sel = gather(k, idx)v_sel = gather(v, idx)return softmax(q @ k_sel.T / scale) @ v_sel
4.2 Initializing and Training the Projection Matrices
The projection matrices do not have to be trained from scratch. A common approach is to initialize them from the low-rank structure already present in the original model, then apply lightweight fine-tuning on long-context data so the latent space aligns with the attention distribution. Freezing the projections entirely may leave recall insufficient; training everything raises cost. A middle ground between the two is recommended.
4.3 Adaptive top-k
A fixed k wastes budget on short contexts and may be insufficient on long ones. You can set k in segments by context length, or adjust it dynamically based on attention entropy: high entropy indicates a flat distribution, so increase k; low entropy indicates concentration, so reduce k.
4.4 Working with the KV Cache
During decoding, retrieval happens at every step, so the index structure should support incremental updates. Cache the latent vectors alongside the original KV, read only the latent vectors during retrieval, and fetch the original KV after a hit. This can significantly reduce bandwidth pressure.
5. Balancing Accuracy and Performance
Evaluating this kind of solution requires more than prefill speed. A three-dimensional evaluation is recommended:
- Accuracy: compare against a full-attention baseline on long-context benchmarks, focusing on mid-context information recall and multi-hop reasoning;
- Latency: measure prefill and decode separately, focusing on time to first token and throughput;
- Resources: GPU memory usage, bandwidth consumption, and index structure build time.
A practical tuning order is: first fix k at an empirical value and verify accuracy, then adjust the projection dimension and observe recall, and finally tune retrieval structure parameters for throughput. In most scenarios, accuracy is more sensitive to k than to the projection dimension.
6. General Architecture Guidance for Cloud Deployment
To deploy ultra-long context services in the cloud, you can combine general-purpose capabilities:
- Use a container platform to host inference services, scheduling by context length into separate pools;
- Use object storage to keep long documents and index snapshots, loading them quickly on cold start;
- Use a message queue to smooth traffic spikes and make long prefill requests asynchronous;
- Use logging services and monitoring alerts to track time to first token, recall, and GPU memory levels.
Baidu AI Cloud can provide the general-purpose capabilities above in these scenarios, helping teams combine algorithm optimization with engineering stability.
7. Conclusion
The real enemy of ten-million-token context is not attention computation but the quadratic growth of indexing. The value of Latent Sparse Attention is that it changes the space in which comparison happens, rewriting the order-of-magnitude problem at its root. For developers, the path to adoption is clear: decouple the indexer from attention, use a low-dimensional latent space for retrieval, make top-k adaptive, and coordinate with the KV cache. Only when indexing cost is pushed to sub-quadratic does ultra-long context truly move from demo to production.
