Sparse Attention at 10M Token Context: Key Practices Behind a 22x Speedup

    As context windows scale from millions to tens of millions of tokens, the bottleneck in sparse attention shifts from the attention computation itself to the indexing step that decides which tokens to attend to. This article breaks down the three-part cost of the prefill stage, explains why indexing grows quadratically with sequence length, and shows how moving retrieval into a compressed latent space can cut that cost dramatically. It also covers why different models see different speedups, how accuracy is preserved, and a practical checklist for evaluating these optimizations in your own inference stack.

    1. Long Contexts Are Giving Back the Compute They Saved

    Over the past two years, long-context capabilities have evolved faster than most people expected. Million-token windows are already becoming a default spec for some model services, and 10M-token contexts are moving from experimental setups in papers to real engineering problems. On the surface, this looks like a pure capability expansion curve: longer windows, larger codebases that fit in a single pass, and more documents you can feed in at once.

    On the engineering side, though, the problem is not so linear. The core intuition behind attention is that attending to a small fraction of history is enough to preserve accuracy, and this has been validated repeatedly at the million-token scale. The real trouble is that finding that small fraction becomes increasingly expensive as context length grows. When sequence length goes from 1M to 10M, the overhead of filtering, scoring, and ranking candidate tokens gradually exceeds the attention computation itself.

    Take a certain class of global attention layers as an example. During the prefill stage at 10M-token scale, most of the time is not spent on the actual attention matrix operations, but on the indexing step that decides which tokens to look at. In other words, the compute savings from sparsification get eaten back by indexing overhead, and can even invert.

    The nature of the problem has therefore shifted: from “should we sparsify” to “how do we keep the addressing cost of sparsity from growing with length”.

    2. Locating the Bottleneck: A Three-Part Cost That Grows Quadratically

    To understand where the optimization headroom is, break down the cost of the prefill stage. It usually splits into three parts:

    1. Indexing/scoring cost: computing each query’s relevance to historical tokens and selecting the top-k candidates. A naive implementation evaluates similarity against the full history, with complexity growing quadratically with length.
    2. Attention computation cost: weighted aggregation over only the selected k positions. Since k is usually far smaller than the sequence length, this part is “cheap”.
    3. Memory access and scheduling cost: gather/scatter of candidate positions, KV cache reads, chunked scheduling, and parallel partitioning. The longer the sequence, the less friendly random access becomes.

    At the 10M-token scale, the first part becomes the dominant term by far. This also explains why a speedup on the order of “22x faster” is possible: what gets optimized is not the already-cheap attention computation, but the indexing component that has run out of control.

    Looking closer, there are three drivers behind the indexing cost blowing up:

    • The candidate space grows linearly with length, and every query has to scan it, making the overall cost quadratic;
    • Scoring precision requirements are high: to avoid missing key tokens, full comparisons are often done with higher-precision representations;
    • Memory access patterns are fragmented: scattered candidate positions lead to low cache hit rates and poor bandwidth utilization.

    3. The Core Idea: Move Addressing into Latent Space

    The key abstraction in this line of work is: do not perform full retrieval in the original token space; perform approximate retrieval in a compressed latent space instead.

    You can think of it as a three-stage funnel:

    • Stage one compresses the long sequence into a small number of “summary representations” (latent vectors), reducing the length from tens of millions to thousands or even hundreds;
    • Stage two does coarse filtering in latent space, locking onto a few candidate blocks at very low cost;
    • Stage three does fine-grained scoring and attention computation only within the candidate blocks.

    The pseudocode below is illustrative; the point is the hierarchy, not the specific interfaces:

    1. # Conceptual illustration: coarse filtering in latent space + fine computation within blocks
    2. latent = compress(kv_history, block_size=B) # 10M -> thousands
    3. coarse = score(query_latent, latent, topk=M) # low-cost coarse filtering
    4. blocks = gather_blocks(coarse, block_size=B) # fetch candidate blocks only
    5. fine = score(query, blocks, topk=k) # fine scoring within blocks
    6. out = attend(query, fine) # the actual attention

    This structure works because it replaces the step that grows quadratically with length with a low-dimensional retrieval over compressed representations. The more reasonable the compression ratio, the more the indexing cost drops; meanwhile, fine computation within blocks ensures accuracy is not hurt by coarse filtering.

    4. Why Speedups on the Order of 20x and 70x Are Both Possible

    Different model architectures have different sensitivity to indexing overhead, which directly determines the difference in speedup. An intuitive explanation:

    • If the original implementation’s indexing overhead is extremely high (for example, close to all of the time), then after optimization only fine computation within blocks remains, and the speedup can naturally reach a very dramatic level;
    • If attention computation itself accounts for a non-trivial share in the original implementation, then even if indexing is optimized to the extreme, the overall speedup is capped by the “incompressible part”.

    This matches the intuition of Amdahl’s law: the ceiling on optimization gains depends on the share of the optimized part in total time. So when evaluating this kind of approach, you cannot just look at “how many times faster”; you have to look at the cost breakdown for the target model, target length, and target stage (prefill or decode).

    Three variables worth attention in engineering:

    • Compression block size: too large, and coarse filtering gains shrink; too small, and scheduling and memory access overhead rise;
    • Number of coarse-filter candidates M: larger M gives more stable accuracy, but cost goes back up;
    • Fine-grained top-k: k sets the accuracy floor and usually needs sensitivity analysis combined with the task.

    5. Why Accuracy Holds Up: Sparsity Assumes Approximability

    The essential assumption that makes sparse attention work is that the attention distribution has strong locality and low rank: a few positions contribute the vast majority of the weight. As long as the coarse filtering stage does not miss the high-weight regions, the subsequent fine computation can reconstruct an approximate result.

    Common stability techniques in practice include:

    • Hierarchical verification: a second confirmation pass on the candidate blocks from coarse filtering, avoiding accumulation of compression error;
    • Fallback window: keeping the most recent tokens and fixed sink positions to prevent long-range information from being lost entirely;
    • Hybrid structure: alternating global sparse layers with linear/local layers so different layers take on different responsibilities;
    • Length extrapolation calibration: letting the model see longer samples during training or fine-tuning to reduce distribution drift at inference time.

    It is worth stressing that any compression introduces error, so “maintaining comparable accuracy” is an engineering conclusion that needs to be validated per task, not a theorem that holds unconditionally. Evaluation should cover different types such as long-document retrieval, multi-hop QA, codebase-level understanding, and long-conversation memory.

    6. Implementation Advice: How to Evaluate This Kind of Optimization in Your Own Inference Stack

    If you are doing inference optimization for very long contexts, you can proceed in the following order:

    1. Quantify the cost breakdown first. Instrument at the target length to make clear the respective shares of indexing, attention, and memory access. Without this data, the optimization direction can easily go off track.
    2. Replace the indexer first. If indexing accounts for more than half, the gains are the most certain; if its share is very low, you should turn to memory access and scheduling optimization.
    3. Align chunking with parallelism. Align the compression block size with the underlying parallel partitioning and memory layout to reduce random access.
    4. Build an accuracy regression set. Use a fixed evaluation set to monitor accuracy drift caused by compression, and set an acceptable threshold.
    5. Roll out in stages. Enable it in the prefill stage first, observe changes in time-to-first-token and throughput, then evaluate the decode-stage strategy.

    When deploying in the cloud, this kind of optimization is usually combined with general capabilities such as containerized inference services, elastic scaling, and logging with monitoring and alerting: use the monitoring system to observe latency distributions across different length ranges, use the logging service to accumulate failure samples, and use elastic resources to handle peak pressure from long requests.

    7. Conclusion

    The core tension of 10M-token context has shifted from “can we afford to compute it” to “can we find it”. When indexing cost grows quadratically with length and dominates total time, the optimization focus must move forward from the attention formula itself to the addressing mechanism. Latent-space sparsification offers a clear path: use compressed representations for low-cost coarse filtering, and use fine computation within blocks to preserve accuracy, thereby pushing the out-of-control indexing overhead back into a manageable range. For engineering teams, the real work lies in quantifying cost, calibrating parameters, building accuracy regression, and making the optimization integrate smoothly with the existing inference stack and observability system.