Sparse Attention at 10 Million Tokens: Moving Relevance Search into Latent Space for a 22x Prefill Speedup
Long-context inference is shifting the bottleneck from computation to retrieval. This article explains why sparse attention still carries a quadratic indexing cost at million- and ten-million-token scales, how Latent Sparse Attention moves top-k selection into a low-dimensional latent space while keeping aggregation in the original space, and why one reported implementation achieved roughly 22.7x faster prefill on a single attention layer. It also covers practical engineering considerations such as tuning the latent dimension, caching projection matrices, combining with blockwise strategies, focusing optimization on prefill, and profiling each stage before choosing any long-context optimization.
1. Long Context Is Moving the Bottleneck from Compute to Search
Over the past two years, long-context capability has gone from an experimental feature to a default specification. Context windows of a million tokens are now standard in many general-purpose LLM services. Beyond that, ten-million-token inference is starting to appear in scenarios such as repository-level code understanding, long-document batch processing, and multi-turn conversations with very long histories.
The mainstream approach to supporting this is to stop having every query scan the entire token history and instead let it attend to only a few of the most relevant tokens. This route has been validated repeatedly at the million-token scale: what actually affects accuracy is whether the model looks in the right place, not how much it looks at.
But as the context grows to ten million tokens, an initially unremarkable cost starts to spiral. Take one global attention layer in a hybrid attention architecture: when running prefill at ten million tokens, most of the time is not spent on the matrix multiplications of attention itself, but on the indexer that decides which tokens to look at.
The nature of the problem has therefore changed. Sparse attention has already shown that attending to a small subset is enough to preserve accuracy. What actually blocks long context is that the process of finding that small subset still grows quadratically with context length.
2. Where the Quadratic Indexing Cost Comes From
To understand this cost, split an attention layer into two stages:
- Scoring and selection: compute each query’s relevance to all historical tokens, then pick the top-k.
- Aggregation: compute a weighted sum over only the selected k tokens.
The first stage has complexity O(n²·d); the second is O(n·k·d). When k is far smaller than n, the second stage is nearly negligible and the n² term in the first stage dominates outright. In other words, sparsification compresses aggregation but not selection.
Schematically, a naive implementation looks roughly like this:
# Naive sparse attention: the selection stage is still quadraticscores = q @ k_all.transpose(-1, -2) # [B, H, n, n] <- compute and memory hotspotidx = scores.topk(k, dim=-1).indices # pick top-kout = gather_and_aggregate(v, idx) # only k tokens, cheap
At n=10^7, the intermediate tensor [B, H, n, n] is unrealistic in both compute and memory. In practice, engineering workarounds rely on blockwise processing and online statistics, but blocking only reduces peak memory usage; the total number of comparisons is still on the order of n².
3. Latent Sparse Attention: Moving the Search into a Low-Dimensional Space
A recent paper from a startup research team working with universities proposes Latent Sparse Attention. Its core idea is not another refinement of the top-k selection strategy, but changing the space in which the relevance metric is computed.
It can be summarized in three points:
- Compressed representation: project keys and queries into a low-dimensional latent space whose dimension is far smaller than the original head dimension.
- Latent-space scoring: perform relevance estimation and top-k selection in the low-dimensional space, where comparison cost drops linearly with dimension.
- Original-space aggregation: after the indices are selected, return to the original space to fetch values for weighted aggregation, avoiding accuracy loss.
Pseudocode:
# Latent-space selection + original-space aggregationq_lat = proj_q(q) # [B, H, n, d_lat], d_lat << dk_lat = proj_k(k) # low-dimensional key representation, cacheable and reusablescores = q_lat @ k_lat.transpose(-1, -2) # low-dimensional scoring, much cheaperidx = scores.topk(k, dim=-1).indicesout = aggregate_in_original_space(v, idx) # accuracy guaranteed by the original space
The key point: selection happens in a low-fidelity space, aggregation happens in a high-fidelity space. The low-dimensional space only needs to get the ranking roughly right, not exact values; the final output is still determined by the original values, so any accuracy loss stays within a controllable range.
4. Why Speedups Above 20x Are Possible
The paper reports that at the ten-million-token scale, prefill for a single attention layer in one hybrid attention model was about 22.7x faster, while another model of similar scale saw about 72.4x, with accuracy on multiple tasks remaining close to the original models.
The reason the speedups differ so much is that the share of total time taken by indexing differs. If indexing already accounted for more than ninety percent of the time in a given model, cutting indexing cost by an order of magnitude yields a speedup close to the theoretical ceiling; if compute takes a larger share, the speedup is naturally more modest. This also gives an important engineering rule of thumb:
Before evaluating any long-context optimization, do a stage-level profile first to confirm whether time is going into selection or aggregation. The share determines the ceiling on the gain.
5. Engineering Considerations
To borrow this idea in your own inference pipeline, keep the following in mind:
- The latent dimension is a tunable knob: lower is faster, but degraded ranking quality drags down accuracy, so run a small sweep per task.
- Projection matrices can be cached: once the low-dimensional key representation is decoupled from positional encoding, it can be precomputed and kept resident, with the clearest gains in prefill.
- It is orthogonal to blockwise strategies: blocking addresses peak memory, latent-space selection addresses comparison count, and the two can be combined.
- Separate prefill from decode: in decode, n is small and only one query is processed per step, so the quadratic problem is not prominent; optimization effort should focus on prefill.
- Accuracy regression must cover long-range dependency tasks: “no visible drop” on short tasks is unreliable, so build retrieval-style evaluations that span long distances.
6. Building Long-Context Inference Services on the Cloud
Productizing this kind of capability typically requires a few categories of general infrastructure: a container platform to host elastic inference instances, object storage for long documents and vectorized intermediate results, a message queue to queue and smooth out long-running tasks, and logging, monitoring, and alerting to observe the time distribution across prefill stages. Baidu AI Cloud offers corresponding capabilities in these general categories and can serve as a reference for the underlying stack of a long-context inference pipeline.
7. Conclusion
In the ten-million-token era, the core tension is not how much the model looks at, but how fast it can find what matters. Moving relevance selection from the original high-dimensional space to a low-dimensional latent space is currently a rare path that improves both complexity and accuracy. For developers, the real first step is not choosing a solution but quantifying how much time the indexing stage takes in your own pipeline, since that determines the ceiling on any optimization.
