Sparse Attention Indexing at 10 Million Tokens: The Bottleneck and Latent-Space Optimization
As long-context models scale from millions to tens of millions of tokens, the bottleneck of sparse attention shifts from attention computation itself to candidate indexing: the router that decides which tokens to attend to can still grow quadratically with context length. This article explains why indexers become the dominant cost in ultra-long-context prefill, how Latent Sparse Attention (LSA) moves routing into a low-dimensional latent space to avoid materializing full n×n score matrices, and how to balance complexity, recall, and accuracy with practical engineering optimizations such as fused projections, cached latent keys, and block-wise top-k selection.
Sparse Attention Indexing at 10 Million Tokens: The Bottleneck and Latent-Space Optimization
The capability frontier of long-context models is shifting from “can the model ingest a million tokens” to “can it keep inference costs acceptable at ten million tokens.” At million-scale contexts, sparse attention has already proven to be an effective approach: instead of computing exact attention between every query and the full history, the model first selects a small set of the most relevant historical segments and then computes attention only over that candidate set. This reduces exact attention computation from quadratic growth in context length to roughly linear growth in the number of candidates.
But as contexts keep growing, a new bottleneck emerges: the indexer that decides “which tokens to look at” can itself still grow quadratically with context length. During the prefill phase at ten-million-token scale, index-related overhead can account for the majority of time in a single global attention layer. The nature of the problem has changed: sparse attention solves the precision and computation problem of “attending to only a small part,” but it does not automatically solve the problem of “how to find that small part cheaply.”
1. From Millions to Tens of Millions: The Bottleneck Shifts from Attention to Candidate Indexing
A typical sparse attention layer can be broken into two stages:
- Routing or indexing stage: for each query, evaluate the relevance of historical tokens or blocks and select the top-k candidates;
- Sparse attention stage: compute QK scores, softmax, and the weighted sum only over the candidate tokens.
At million-scale contexts, the first stage exists but is usually masked by the second stage and overall throughput. At ten-million scale, if there are n queries and n historical tokens, and the indexer scores every query against all historical tokens, the number of score pairs is n×n—quadratic growth. Meanwhile, the number of candidates k in the actual sparse attention part is usually fixed or kept small, so its cost is approximately n×k. As n grows, the indexer’s share of total cost rises rapidly.
More specifically, indexer overhead is not just floating-point computation. It also includes candidate scoring, top-k selection, candidate reordering, reads of the KV cache or key representations, memory bandwidth consumption, and the materialization of intermediate results introduced for parallelism. Even if a single scoring operation is cheap, when n reaches ten million, an implicit or explicit n×n matrix puts heavy pressure on memory and bandwidth. Therefore, the optimization focus for ultra-long-context inference is shifting from “how to compute less attention” to “how to find candidates at low cost.”
2. Why the Indexer Still Grows Quadratically
The root causes of quadratic indexer growth can be summarized in three points.
First, the structural cost of full relevance scoring. If every query must be compared against all historical tokens or blocks, the number of comparisons equals the number of queries times the number of historical units. Blocking only reduces the constant factor; it does not change the multiplicative structure. The number of blocks grows linearly with context, the number of queries also grows linearly, and their product remains quadratic.
Second, the extra overhead of candidate selection and reordering. Top-k selection itself requires scanning the scores, and a large score matrix brings sorting, threshold filtering, and memory read/write costs. In multi-stage retrieval, the combination of coarse filtering, re-ranking, and exact attention can make the index path heavier than expected.
Third, the difference between prefill and decode. During prefill, a large number of input tokens are processed at once, so the query count is large and the indexer easily becomes the dominant cost. During decode, tokens are generated one at a time, so the per-query index cost is low, but an incrementally updatable index structure must be maintained. If the index cannot be reused, long-context generation will still be slowed down.
Therefore, the optimization direction is not simply to reduce the number of candidates, but to lower the cost of comparing each query against historical units and avoid materializing the full score matrix. Latent Sparse Attention (LSA) is designed around exactly this goal.
3. The Core of LSA: Moving Routing into a Low-Dimensional Latent Space
The basic idea of LSA is: instead of performing candidate selection in the full high-dimensional QK space, first project queries and keys into a low-dimensional latent space, compute routing scores or build a retrievable structure in that space, generate candidate sets at lower cost, and finally run full-dimensional exact attention only on the small set of candidates.
The pipeline can be summarized as:
- Apply lightweight linear projections to Q and K to obtain low-dimensional representations;
- Perform blocking, clustering, approximate nearest neighbor search, or hierarchical retrieval on the low-dimensional representations, avoiding explicit construction of an n×n score matrix;
- Generate top-k candidates for each query;
- Optionally re-rank the candidates once in high dimension to improve recall;
- Run exact attention only on the final candidates.
This brings two direct benefits. First, the routing dimension drops from d to r, where r is much smaller than d, reducing the compute and bandwidth of each comparison. Second, candidate generation can leverage blocking and approximate retrieval, pushing actual growth from full quadratic comparison toward approximately linear or sub-quadratic behavior. Note that low-dimensional projection alone does not automatically eliminate the quadratic term; the key is replacing “full exact scoring” with a combination of “low-dimensional coarse filtering + hierarchical candidates + a small amount of exact re-ranking.”
Illustrative pseudocode:
def lsa_attention(Q, K, V, proj_q, proj_k, top_k):# Q, K, V: [n, d]q_lat = Q @ proj_q # [n, r], r << dk_lat = K @ proj_k # [n, r]# Generate candidates via blocking / hierarchical / approximate retrieval,# avoiding an explicit n×n matrixcandidates = retrieve_candidates(q_lat, k_lat, top_k)# Optional: re-rank candidates in high dimensioncandidates = rerank_candidates(Q, K, candidates, top_k)# Exact attention only over the candidate setscores = Q @ K[candidates].Tweights = softmax(scores / sqrt(d))return weights @ V[candidates]
Here, retrieve_candidates can use general techniques such as block-wise max pooling, hierarchical clustering, locality-sensitive hashing, or approximate nearest neighbor search. In engineering practice, candidate recall should be ensured first, and constant-factor optimizations applied afterward.
4. Balancing Complexity and Accuracy
In terms of complexity, conventional full attention is roughly O(n²d). Sparse attention with k candidates is roughly O(nkd), but if the indexer still performs full-dimensional, full-coverage scoring, the indexing stage remains O(n²d_idx). LSA reduces the indexing dimension to r, making the indexing stage O(n²r), or, with hierarchical retrieval, approximately O(n log n·r + nk d). When r is much smaller than d, both constant factors and bandwidth pressure drop significantly; when candidate generation uses blocking and approximate retrieval, practical scalability improves further.
The key to maintaining accuracy is recall, not simply compressing the candidate count. Useful measures include:
- Multi-path candidates: parallel recall from local windows, latent-space global routing, and linear attention branches;
- Candidate re-ranking: after low-dimensional coarse filtering, re-rank with high-dimensional scores or a lightweight scorer;
- Score calibration: distill or calibrate routing scores against full-dimensional attention scores to reduce distribution drift;
- Training consistency: train the router and the main model in stages or jointly, so that the candidate distribution at inference matches training;
- End-to-end evaluation: cover tasks such as long-document QA, codebase retrieval, log anomaly analysis, multi-hop reasoning, and summarization, while tracking candidate recall@k, sparsity, and accuracy regressions.
5. Engineering Implementation and Monitoring Checklist
For engineering implementation, the following areas deserve priority:
- Fused projections: fuse the latent-space projection into the QKV generation path to reduce extra reads and writes;
- Cache low-dimensional key representations: cache k_lat for long contexts and update it incrementally during decode;
- Block-wise top-k: perform block-level coarse filtering first, then fine selection within blocks, avoiding materialization of the full score matrix;
- Batching and parallelism: parallelize by blocks during prefill and reuse the index structure during decode;
- Monitoring metrics: index time share, candidate recall@k, end-to-end time-to-first-token, throughput, memory usage, and long-text accuracy regressions.
For experimentation and validation, teams can build a reproducible environment on general-purpose cloud services such as compute, object storage, and log services offered by providers like Baidu AI Cloud; the specific selection should be based on actual product capabilities and the team’s existing infrastructure.
6. Applicability and Summary
LSA-style methods are well suited to scenarios that require selecting a few relevant segments from a large history, such as long-document understanding, codebase question answering, log analysis, and multi-turn long conversations. However, for strongly retrieval-dependent tasks, insufficient candidate recall directly harms accuracy; and for very short contexts, index optimization yields limited benefit. Adoption should therefore be based on end-to-end evaluation rather than per-layer speedups alone.
Overall, sparse attention optimization at the ten-million-token scale has evolved from “compute less attention” to “find candidates accurately and cheaply.” Only by combining latent-space routing, hierarchical candidate generation, exact re-ranking, and engineering-grade caching can the advantages of sparse attention truly extend to the ten-million-token regime.
