Sparse Attention at 10M Tokens: 22x Speedup via Hierarchical Index Routing
Sparse attention’s final stage may be linear in k, but its indexer can remain quadratic because every query still scores every key. This article explains how block summaries, hierarchical routing, and coarse-to-fine reranking can make candidate selection near-linear for 10M-token prefilling, compares the complexity with common sparse methods, and outlines implementation and accuracy safeguards.
1. The Bottleneck Is Not “Attention Computes Only k Keys” but “the Indexer Still Scans All Keys”
The cost of long-context inference is concentrated mainly in the prefilling stage. In standard full attention, every query computes relevance against all keys, so time and memory costs grow quadratically with context length. The basic idea of sparse attention is to divide the work: a lightweight indexer first selects the k most relevant keys for each query, and then the actual attention computation runs only on those k keys. This can reduce the final attention cost to O(Tk), which looks very attractive.
However, this idea depends on a precondition: the model really needs only a small number of keys. Existing experimental observations show that, with a 128K context and a medium-sized model, letting each query attend to only its 512 most relevant keys—about 0.8% of all keys—can still retain about 98% of full-attention accuracy on long-context evaluations. This indicates that “a small number of critical keys is sufficient” holds for many tasks, so sparse attention is not an unrealistic idea.
The real paradox lies in the indexer. For the indexer to know which 512 keys are most relevant, it must first score every key. Common industry approaches usually reduce the indexer’s burden by lowering precision, reducing dimensionality, compressing multiple keys into one block, or using block sparsity. But most of these improvements only divide the constant factor by a few times: the indexer’s workload still grows linearly with context length, and every query must do this once, so the total prefilling cost remains quadratic. When the context reaches 10M tokens, the quadratic term swallows all the gains again.
Therefore, discussing “another 22x speedup” cannot focus only on the final attention’s O(Tk). What really needs to change is the indexer’s working paradigm: from “each query scores every key exhaustively” to “first perform hierarchical routing, then perform fine-grained scoring within a small number of candidate blocks.” Only by removing the quadratic complexity of the indexer can 10M-token long context become engineering-feasible.
2. The Complexity Trap of Traditional Sparse Approaches
Common sparse attention can be split into two stages:
- Indexing stage: for each query, select k candidates from T keys;
- Attention stage: perform exact attention only on the k candidates.
The final attention stage is O(Tk d), which is linear when k is much smaller than T. But if the indexing stage still scans all keys for every query, the total complexity is O(T² d’). Here d’ can be very small—low precision, low-dimensional projection, block-level summary, and so on—but as long as T² remains, it is unacceptably large at 10M tokens.
Block-sparse approaches are often considered a way to alleviate the problem: split keys into blocks of size b, and each query scores only blocks. The complexity drops from O(T² d’) to O(T² d’/b). This can indeed provide several-fold to tens-fold improvements, but it is still quadratic—just divided by the block size. As the context expands from 128K to 1M and then to 10M, T²/b still grows rapidly. Low precision and dimensionality reduction only reduce the cost of each scoring operation; they do not change the fact that every query visits all candidate units.
So, if the goal is to achieve roughly 22x speedup at 10M tokens compared with common sparse approaches that optimize only constant factors, the design must focus on this: each query should no longer visit all keys or all blocks. Instead, through a prebuilt hierarchical index, it should visit only logarithmically many or constant many candidate units.
3. Core Idea: Block Summaries + Hierarchical Routing + Coarse-to-Fine Reranking
A more practical general approach is “hierarchical block-indexed sparse attention.” It turns the indexer from a per-key scanner into a multi-level router. The flow is as follows.
3.1 Precompute Block Summaries Once and Reuse Them
Split the context into fixed-size blocks, for example, each block containing a number of tokens. Compute a compact summary for each block. The summary can be a cluster center of tokens within the block, a low-rank projection, an aggregate representation of sampled tokens, or a learnable block-level summary vector. The key point is that summary computation is only linear in context length and can be completed once before prefilling or during sharded prefilling.
The role of the block summary is to “represent the block in coarse-grained routing.” It does not need to be perfectly accurate, but it should preserve the main semantic direction within the block. The summary vector dimension is much smaller than the original key set, so the cost of subsequent query-to-block-summary scoring is much lower than per-key scoring.
3.2 Use a Tree or Cluster Structure for Routing to Avoid Linear Block Scanning
After building block summaries, a hierarchical index can be further constructed: the bottom layer contains block summaries, the upper layer contains cluster centers, and higher layers contain coarser cluster centers, forming a routing tree. Each query starts from the root node, scores only a small number of child nodes, and selects top-m candidate paths layer by layer.
If the number of blocks is B, tree routing visits only a constant number of nodes per layer, and the depth is O(log B). Therefore, the routing cost per query is O(log B), not O(B). In a 10M-token scenario, B may reach tens of thousands or more, and log B is an order-of-magnitude difference relative to B.
3.3 Fine-Grained Scoring Within Candidate Blocks, Then Select Top-k Tokens
After routing selects m candidate blocks, fine-grained scoring is performed on the original keys only inside these blocks to select the final k tokens. The number of tokens within a block is usually fixed and small, so this part costs O(m b d), where b is the block size. m and b are controllable engineering parameters and do not grow linearly with total context length.
Exact attention is then computed only on the final k tokens, at a cost of O(T k d). Overall prefilling changes from “each query scans the full set” to “each query traverses the tree + scans a small number of candidate blocks + exactly computes k tokens.”
3.4 Incremental Updates and Caching
Long-context inference often includes incremental decoding. When a new token arrives, only the summary of its block needs to be updated, and possibly a small number of cluster centers need to be updated upward; most existing block summaries and the routing tree can be reused. For repeated prefixes or stable contexts, routing results can also be cached to further reduce online overhead.
4. Complexity Comparison: From Quadratic Indexing to Near-Linear Prefilling
| Approach | Total indexing-stage cost | Final attention | Main bottleneck at 10M tokens |
|---|---|---|---|
| Full attention | O(T² d) | O(T² d) | Quadratic attention matrix |
| Per-key sparse | O(T² d’) | O(T k d) | Full scoring by the indexer |
| Block sparse | O(T² d’/b) | O(T k d) | Still quadratic, only divided by block size |
| Hierarchical routing sparse | O(T d + T(logB + m b + k d)) | O(T k d) | Summary construction and routing quality control |
In the hierarchical routing scheme, precomputing block summaries costs O(T d), routing costs O(logB + m b) per query, and final attention costs O(T k d). When block size b and candidate-block count m are engineering constants, overall cost grows approximately linearly with T rather than quadratically. This is the source of order-of-magnitude speedup at 10M tokens: not dividing the indexer constant by a few times, but changing the indexer complexity from O(T²) to near O(T logT).
5. Pseudocode: Turning the Indexer into a Router
build_index(tokens):blocks = split_into_blocks(tokens, block_size)summaries = []for block in blocks:summary = summarize(block) # cluster center / low-rank projection / learnable summarysummaries.append(summary)tree = build_route_tree(summaries)return tree, blocksprefill(queries, tree, blocks):outputs = []for q in queries:candidate_blocks = route_top_m(tree, q, m)candidates = []for block_id in candidate_blocks:scores = dot(q, blocks[block_id].keys)candidates.extend(top_r(scores, r))selected = top_k(candidates, k)out = exact_attention(q, selected.keys, selected.values)outputs.append(out)return outputs
The key to this pseudocode is not the specific implementation but the two-level selection: the first level uses tree routing to reduce the candidate range from all blocks to m blocks; the second level performs fine-grained top-k selection only within the m blocks. The final attention still uses full-precision keys and values, so accuracy loss mainly comes from candidate recall rather than the final computation.
6. Engineering Implementation Considerations
6.1 Avoid Materializing the Full Score Matrix
After redesigning the indexer, engineering work should also avoid generating a full query-key score matrix. Routing, intra-block scoring, and top-k selection should be fused into batched kernels as much as possible to reduce intermediate tensor writeback. At 10M tokens, memory bandwidth and intermediate matrix materialization are often more critical than arithmetic operations.
6.2 Block Size and Candidate Count Need Joint Tuning
If blocks are too large, intra-block fine-grained scoring cost increases; if blocks are too small, the number of blocks increases, the routing tree becomes deeper, and block summary quality degrades. If the number of candidate blocks m is too small, recall decreases; if it is too large, the routing benefit is offset. In practice, tune based on the task’s long-context evidence distribution: when evidence is concentrated, use a smaller m; when evidence is dispersed, increase m or add multi-stage reranking.
6.3 Separate Routing Precision from Final Precision
The indexer can use low-precision, low-dimensional, or quantized representations to reduce routing cost, while final attention should retain higher precision. This decouples “routing recall” from “attention computation”: routing is responsible only for not missing critical candidates, and final computation is responsible for numerical precision.
6.4 Load Balancing and Sharded Prefilling
After routing, different blocks may be hit with uneven frequency, and hot blocks can cause parallel load imbalance. In engineering, candidate blocks need to be scheduled in batches, hot blocks split for parallelism, and cold blocks merged. Ultra-long-context prefilling should also build summaries and the routing tree in shards to avoid processing all tokens at once.
6.5 Accuracy Safeguards and Fallback Mechanisms
Before deployment, candidate recall should be monitored: use sampled queries to compare the overlap between full-attention top-k and routed top-k. For layers or heads with low recall, increase m, add reranking stages, or fall back to a more conservative block-sparse path. Long-context evaluation should cover retrieval, aggregation, multi-hop, and other tasks rather than relying on a single metric.
7. Applicable Boundaries and Risks
Hierarchical routing sparse attention is not unconditionally faster. If a task requires a large amount of dispersed evidence and each query truly depends on a wide distribution of keys, the routing tree may miss critical blocks; if block-summary training and inference are inconsistent, routing quality can drift; if incremental updates are frequent, summary maintenance also adds extra cost. Therefore, the solution should retain learnable routing objectives, multi-stage reranking, and fallback paths, and use recall monitoring to determine when to expand the candidate range.
For 10M-token long context, however, the direction is clear: having final attention compute only k keys solves only half the problem; the indexer must be upgraded from “per-key full scanning” to “hierarchical candidate routing.” Only by removing the quadratic indexing term in prefilling can sparse attention move from constant-factor optimization to order-of-magnitude speedup. This is the engineering basis on which “22x speedup at 10M tokens” truly stands.
