Sparse Attention for 10-Million-Token Contexts: Acceleration Limits
Sparse attention can speed up long-context inference under specific test conditions, but the results depend on the model, sequence length, GPU, data type, and dense attention baseline. Readers should re-measure in their own environment. This article explains why reducing constant factors does not remove the quadratic cost of attention at very long lengths. It compares ANN indexing, cluster-based routing, and dynamic chunking, and covers engineering issues in operator fusion and paged KV cache, including parameter tuning and memory estimation.
Sparse attention can speed up long-context inference under specific test conditions, but the claim of acceleration at the 10-million-token scale needs qualification. The conclusions in this article assume a particular model, sequence length, GPU model, data type, and dense attention baseline. Readers should measure performance in their own environment.
1. Why constant-factor optimizations struggle to solve the long-context bottleneck
Standard attention computes an N×N relevance matrix over N tokens. The prefill computation costs about O(N²·d), where d is the head dimension. When N reaches the tens of millions, the computation remains quadratic even when block-based algorithms such as FlashAttention reduce memory reads and writes.
Sparse attention changes how many keys each query attends to. If each query attends to only k keys, the attention computation itself drops to O(N·k·d). Selecting those k keys, however, requires an indexing step. If each query scans all keys, the selection cost per query is O(N), and the total selection cost across all queries is O(N²). The total cost can fall to O(N) or lower only when the index is shared across queries, or when candidate results can be reused.
Lower precision, lower dimensionality, and vector compression all reduce the constant factor on top of this. INT8 quantization reduces the number of bytes. Lower key dimensionality reduces the number of multiply-accumulate operations per dot product. Compressing neighboring keys into centroid vectors reduces the number of candidates. These methods typically shrink the indexing cost by a multiple, but they shrink the coefficient, not the growth rate. Each method also carries an accuracy cost. Dimensionality reduction loses directional information. Compression merges tokens with different meanings into the same centroid. Quantization can change the attention ranking in extreme cases.
The table below lists the complexity impact, main risks, and suitable scenarios for each approach.
| Method | Per-query complexity | Impact on total complexity | Main risks | Suitable scenarios |
|---|---|---|---|---|
| Lower precision (e.g., INT8) | Fewer bytes per value | Growth order unchanged | Quantization error affects attention ranking | Bandwidth-bound workloads with enough accuracy margin |
| Lower key dimensionality | Lower cost per dot product | Growth order unchanged | Directional information loss, lower recall | Models with clear dimensional redundancy |
| Vector compression (centroids) | Fewer candidates | Coefficient reduced, growth order unchanged | Different meanings get merged | Neighboring tokens with highly similar meaning |
| ANN indexes (HNSW, IVF-PQ) | Approximately logarithmic candidate lookup | Total cost about O(N log N), provided recall meets the target | Recall loss, graph construction and memory overhead | Large candidate sets where approximate results are acceptable |
| Cluster routing | About m·N/K candidates, plus K centroid comparisons | Total cost still grows with N when K is fixed | Uneven cluster distribution lowers efficiency | Long texts with clear semantic structure |
| Dynamic chunking | Fewer nodes participate, based on semantics | Depends on the reduction in block count | Boundary errors cause information loss | Structured documents and code |
| Operator fusion | Less memory access | Growth order unchanged | Higher debugging cost, numerical differences | Memory access is the main bottleneck |
| Paged KV cache | Does not change the attention computation | Growth order unchanged | Page table overhead, extra latency from preemption | High concurrency, widely varying request lengths |
2. Choosing ANN indexes, cluster routing, and dynamic chunking
Approximate nearest neighbor (ANN) search
Storing key vectors in a graph index (such as HNSW) or a quantized index (such as IVF-PQ) changes each query’s candidate lookup from a linear scan to an approximately logarithmic search. In practice, HNSW query complexity is usually close to O(log N), but this holds only when the recall rate is acceptable. Higher recall requires the graph search to visit more nodes. In high-dimensional spaces, distances become less distinct, and graph navigation becomes less efficient. Building the index takes extra time, and the graph edges consume a significant amount of GPU memory.
Start tuning with the following parameters:
- M: the number of neighbors per node, typically between 16 and 64. A larger M improves recall but increases memory use.
- efConstruction: the length of the candidate queue during graph construction, typically between 100 and 400.
- efSearch: the length of the candidate queue at query time. It is the main control for the trade-off between recall and latency. Derive the value from a target recall rate, such as 0.95.
- Quantization bit width and number of sub-vectors: these affect compression ratio and distance error, and must be evaluated together with recall.
To measure ANN parameters, follow these steps:
- Build an evaluation set using key and query vectors that match production. Use at least several hundred queries.
- Use exact brute-force search to get the true top-K results for each query. These results serve as the recall baseline.
- Sweep efSearch, and record the recall rate and per-query latency at each value.
- Choose the smallest efSearch that meets the target recall rate, and use it in production.
- Record index build time separately, and compare it with the time window available for indexing in production.
Memory can be estimated as follows. Graph edges take about N×2M×4 bytes. This assumes the upper bound of 2M edges per node and 4 bytes per neighbor ID. Vectors take about N×d×(bytes per element). For example, with 10 million keys, M=32, d=128, and FP16, the graph edges take about 2.6 GB and the vectors take about 2.6 GB, for a total of about 5 GB. If each layer and each KV head builds its own index, add the totals across all layers and heads. When planning GPU memory, count the index cost together with the KV cache.
Cluster routing
Clustering keys with K-Means has a training cost of about O(N·K·d·T), where K is the number of clusters and T is the number of iterations. At query time, the query is first compared with the K cluster centroids at a cost of O(K·d). The m most relevant clusters are then selected. If cluster sizes are roughly even, the number of candidate keys is about m·N/K.
The number of candidates per query depends on both m and K. When K is fixed, the number of candidates grows with N. If K grows with N, for example close to sqrt(N), the candidates per query can drop to about m·sqrt(N). However, the cost of comparing against centroids also grows with K, so the total cost across all queries still grows with N. When evaluating this approach, consider total query cost, m, K, and the cluster distribution together. If semantic distribution is uneven, a few large clusters can account for most candidates, and efficiency drops. Start K near sqrt(N), then adjust based on the cluster size distribution and recall results.
Context-aware dynamic chunking
Fixed-length chunks can split complete semantic units. Splitting at periods, paragraph breaks, or grammatical boundaries reduces this problem. Low-information chunks can be aggregated more aggressively, while high-information chunks keep fine-grained keys. The main risk is that boundary detection can be wrong. An incorrect merge can dilute key information in a centroid vector. Compare dynamic chunking against fixed chunking on a validation set, and measure task accuracy, perplexity, and inference latency together. Node reduction ratios in theory do not show whether the method actually helps.
3. Engineering the system and where problems appear
Operator fusion
Fusing the similarity computation, top-K selection, and weighted sum into a single CUDA kernel reduces the number of intermediate writes back to GPU memory. The benefit depends on whether memory access is actually the bottleneck. Before writing a fused kernel, use Nsight Compute to check memory bandwidth usage and compute unit utilization, and confirm the bottleneck first.
Fused kernels are harder to debug, and their numerical results may differ slightly from a reference implementation. Keep a naive implementation as a reference, compare outputs layer by layer in float32, and set absolute and relative error thresholds. Regression tests should cover many random inputs and real long texts. The final judgment on error thresholds should rest on the model’s task metrics, not on the numerical difference of a single operator.
Paged KV cache
Splitting the KV cache into fixed-size pages, often a few dozen tokens each, and allocating them on demand reduces the GPU memory wasted by preallocation. It also allows flexible scheduling across concurrent requests. The risks include page table overhead, internal fragmentation from a poor page size choice, and extra latency from preemption and swapping when GPU memory runs short.
Determine the page size from production measurements:
- Collect the length distribution of production requests.
- For several candidate page sizes (such as 16, 32, and 64 tokens), measure GPU memory utilization and the average internal fragmentation rate. Internal fragmentation is the unused space in the last page of each sequence.
- Record the number of preemptions and the extra latency caused by reloading after preemption.
- Weigh memory utilization against tail latency, and choose the page size with the best overall result.
Infrastructure
Ultra-long-context inference typically requires large-memory GPUs, high-speed interconnects within a node, and
