Sparse Attention in Latent Space: 22x Prefill Speedup for 10M-Token Contexts
As context windows scale from millions to tens of millions of tokens, the bottleneck in sparse attention shifts from computing attention to selecting which keys to attend to. This article breaks down that cost structure and explains how latent-space sparse attention projects queries and keys into a low-dimensional space for near-linear candidate retrieval, decoupling candidate generation from the main attention computation. It covers why the approach delivers order-of-magnitude prefill speedups while preserving accuracy, the design constraints behind recall, and a practical rollout checklist covering layer selection, block size tuning, caching, regression testing, observability, and cost.
1. The Problem: Longer Contexts Move the Bill
Over the past two years, long context has gone from an optional feature to a baseline specification. Million-token windows are now a default configuration for many model services, and hybrid attention architectures (stacking global attention layers alternately with linear or gated layers) are widely adopted to trade off throughput and memory on long sequences. These designs share the same premise: instead of having every query scan the entire history, only a small set of the most relevant keys participates in the computation.
That premise has been validated repeatedly at the million-token scale. But as contexts push toward ten million tokens, an overhead that once looked negligible starts to spiral. Take a single global attention layer doing prefill at ten million tokens: most of the time is not spent on the attention matrix multiplications at all, but on the indexing step 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 actually blocks ultra-long contexts is that the cost of finding that subset still grows quadratically with context length.
2. Cost Breakdown: Attention Is Cheap, Selection Is Expensive
The cost of standard full attention is well understood: with sequence length T, prefill compute is roughly O(T²), and decoding each token costs O(T). Going from one million to ten million tokens inflates attention compute by about two orders of magnitude.
Sparse attention splits the work: a lightweight indexer first picks the k most relevant keys for each query, then the real attention computes over only those k keys, pushing the main compute down to O(T·k). This works under one condition — the model genuinely needs very few keys. Ablation studies at moderate lengths support this: at around a hundred thousand tokens, letting each query attend only to the few hundred keys it is “truly” most relevant to (typically less than one percent of the total) still retains roughly 98% of full-attention accuracy on long-context benchmarks.
But this hides a paradox: for the indexer to know which few hundred keys matter, it must first score every key. The common engineering compromise is to lighten the indexer’s load — lower scoring precision, compress dimensions, or aggregate several adjacent keys into a block before scoring. These tricks shrink the constant but do not change the order of magnitude: index scoring is still a T×T pairwise comparison, so doubling the length quadruples the selection cost. At ten million tokens, selection cost completely dwarfs attention itself.
Schematically, the logic looks like this:
# Naive block sparsity: selection cost grows quadratically with length# scores: [num_queries, num_key_blocks]scores = query_index @ key_index.transpose(-1, -2) # O(T^2 / block)topk_idx = scores.topk(k, dim=-1).indices # still full pairwise comparisonattn_out = sparse_attention(q, k, v, topk_idx) # O(T * k)
3. The Core Idea: Move Relevance Search into Latent Space
A class of methods known as latent-space sparse attention changes what the indexing stage operates on. Instead of pairwise scoring in the original token dimension, queries and keys are each projected into a low-dimensional latent space, similarity retrieval and candidate filtering happen there, and the sparse attention is then computed back in the original space.
Three things change:
- Retrieval dimension drops sharply. Scoring goes from pairwise inner products over hidden dimension d to pairwise inner products over latent dimension r, where r is far smaller than d, shrinking the constant significantly.
- Candidate generation decouples from the main compute. Latent-space retrieval only needs to produce a candidate set, so it does not have to be tightly bound to the numerical precision of attention; it can use lower precision, more aggressive quantization, and approximate nearest-neighbor structures.
- The complexity class moves down. Combined with blocking and hierarchical retrieval, the selection stage drops from quadratic to near-linear (roughly O(T·log T) or O(T·k)), bringing the overall attention pipeline into the sub-quadratic regime.
In pseudocode, the shape is roughly:
# Latent-space retrieval: low-dimensional projection + hierarchical candidate filteringq_lat = proj_q(q) # [T, r], r << dk_lat = proj_k(k) # [T, r]block_centroids = pool(k_lat, block_size) # hierarchical clustering centroidscand = search(block_centroids, q_lat, topk=k) # near-linear candidate retrievalattn_out = sparse_attention(q, k, v, cand) # compute only over candidates
4. Why You Get Both Speed and Accuracy
The speedup can be attributed item by item: the projection itself is a cheap linear transform; low-dimensional retrieval reduces the memory traffic for scoring and ranking by an order of magnitude; hierarchical candidates replace “global pairwise comparison” with “coarse localization, then fine ranking”; and the sparse main attention only handles a fixed-size candidate set, keeping both memory and compute bounded. With these factors stacking up, a speedup of more than twenty times over the naive sparse approach on single-layer prefill at ten million tokens is not surprising; the exact figure varies considerably across model architectures, and speedups in the tens of times are within a reasonable range.
Accuracy retention depends on three design constraints:
- Prioritize candidate recall. The indexing stage optimizes for “don’t miss the truly relevant keys” rather than exact ordering, so recall is the primary metric to monitor.
- Layered verification. After coarse filtering, keep a candidate pool slightly larger than k, then do a lightweight rerank in the original space to compensate for the ordering error introduced by latent-space projection.
- Align with training. If the indexer and projection matrices are jointly optimized during pretraining or continued pretraining, distribution drift is smaller; bolting an indexer on at inference time only usually requires compensatory fine-tuning on downstream tasks.
5. Implementation Checklist
- Layer selection: Enable latent-space indexing only on global attention layers and leave linear/gated layers untouched — maximum benefit, minimal change.
- Block size tuning: Larger blocks make retrieval cheaper but recall worse; run a two-dimensional recall-versus-latency sweep at the target length.
- Caching strategy: The latent representations of keys can stay resident alongside the key-value cache and be reused during decoding, avoiding repeated projection.
- Accuracy regression: Run regression on long-context benchmarks (multi-hop retrieval, aggregation, variable tracking) and watch for performance collapse in the middle of the context.
- Observability: Bring candidate recall, average candidate count, and index time share into monitoring and alerting; index time share is the most direct anomaly signal.
- Cost perspective: For ultra-long context scenarios, the maintenance cost of memory and retrieval structures (such as approximate nearest-neighbor indexes) must be counted as well; offload cold data to object storage when necessary.
6. Conclusion
Once contexts enter the ten-million-token range, the focus of long-context optimization has shifted from “compute less attention” to “cheaply find the part that needs computing.” Moving relevance retrieval into a low-dimensional latent space and decoupling candidate generation from the main attention is currently a viable path for pushing selection cost down to near-linear; combined with layered enablement, recall monitoring, and training alignment, it delivers order-of-magnitude prefill speedups while preserving accuracy. For teams planning ultra-long context capabilities, the recommendation is to start with a small-scale validation on global attention layers and use two metrics — candidate recall and index time share — to judge whether the gains hold.
