The Key to 22x Faster Sparse Attention at Ten-Million-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 tokens to attend to. This article breaks down why the indexer, not the attention math, dominates prefill time, and explains Latent Sparse Attention (LSA), an approach that moves selection from token space into a compressed latent space. It covers the two-level retrieval design, why the method can deliver roughly 22x to 70x per-layer prefill speedups while preserving accuracy, and the engineering details required to reproduce it: block size tuning, memory access and parallelism, coordination with linear attention layers, accuracy regression testing, and service observability. It closes with practical advice for developers on measuring before optimizing, treating recall as a first-class metric, staged rollout, and handling long-tail request lengths.

    Introduction: The Context Length Race Enters the Ten-Million-Token Stage

    Over the past two years, long context has shifted from an optional feature to a baseline specification. Million-token context is becoming a default configuration for many cloud-hosted model services, and hybrid attention architectures that alternate global and linear attention layers are widely used to control memory and compute overhead. The industry has converged on a shared assumption: attention does not need every query to scan the entire token history. Selecting a small set of the most relevant tokens is enough, with manageable accuracy loss.

    But as context grows from millions to tens of millions of tokens, an initially unremarkable cost starts to spiral: the indexing process that decides which tokens to look at. Its cost grows quadratically with context length, until it takes over as the dominant expense.

    A publicly reported research effort quantified the problem: in a single global attention layer during prefill at ten million tokens, roughly 98% of the time is spent not on the numerical attention computation but on the indexer. In other words, the compute saved by sparsification is consumed by the cost of finding the sparse positions.

    The work proposes Latent Sparse Attention (LSA), which moves selection out of token space and into a compressed latent space. At ten million tokens, a single attention layer’s prefill can be accelerated by roughly 22x to 70x (the exact factor varies by model architecture), while maintaining accuracy close to the original model across multiple tasks. This article takes a neutral view of the underlying problem, the method’s framework, and the key points for engineering deployment.

    1. The Bottleneck Moves: From Slow Compute to Slow Selection

    To understand the value of LSA, it helps to first see the cost structure of sparse attention clearly.

    The prefill cost of standard attention has two main components: scoring and weighted summation, and determining the sparse pattern. Early sparse schemes (sliding window, block sparse, static patterns) turned the second component into a constant, which is why their gains were obvious. Dynamic top-k selection schemes, however, turned the second component into a new quadratic term: every query must run a similarity evaluation against all historical positions, so the complexity remains O(N²), only with a smaller constant and more memory-access-friendly behavior.

    This explains a counterintuitive phenomenon: the longer the context, the weaker the advantage of dynamic sparsity over static sparsity, because the indexing overhead keeps rising as a share of total time. The direct engineering implication is that optimizing ultra-long context should attack the indexing path first, rather than continuing to tune the attention kernel.

    2. The Core Idea of LSA: Retrieval in Latent Space

    The key abstraction of LSA is to change “find relevant tokens in token space” into “find relevant blocks in compressed latent space.”

    The logic can be summarized in four steps:

    1. Compression: encode the historical token sequence into a small number of latent vectors (latent codes) block by block. Information within a block is aggregated, and the sequence length drops from N to N/B.
    2. Retrieval: the query is matched against the latent vectors in latent space to select a small number of candidate blocks, reducing complexity to roughly O(N·N/B).
    3. Restoration: within the candidate blocks, finer-grained localization turns the block-level selection back into a token-level sparse set.
    4. Computation: attention is computed only over the finally selected tokens.

    Illustrative pseudocode (expressing structure only, not any specific interface):

    1. # Prefill stage: build the latent-space index
    2. latent = block_encode(kv_history, block_size=B) # shape: [N/B, d]
    3. # Decode stage: each query first coarsely filters blocks, then finely selects tokens
    4. blocks = topk(sim(q, latent), k_blocks) # coarse filter, cost O(N/B)
    5. idx = refine(q, kv_history, blocks) # fine selection, cost O(k_blocks * B)
    6. out = sparse_attention(q, kv_history, idx) # compute only the selected part

    Two easily overlooked design points matter here. First, the compression must be “retrievable”: the latent vectors need to retain the discriminative information required to match against the query, rather than being produced by unsupervised average pooling. Second, the coarse filter and fine selection must form a two-level structure with controllable error: the coarse filter handles recall, the fine selection handles precision, and together they determine the final approximation quality.

    3. Why It Delivers Both Speed and Accuracy

    LSA’s gains come from reducing the order of the quadratic term; its accuracy comes from two-level approximation plus training alignment.

    On the speed side: the indexing cost drops from being on the order of N to being on the order of N/B. When B is in the tens to hundreds, the indexing overhead falls by one to two orders of magnitude, and the time that once accounted for 98% is compressed to a single-digit percentage, so end-to-end prefill naturally sees tens-of-times speedup.

    On the accuracy side: compression alone loses information, so common practices include keeping representative tokens within each block, applying normalization and temperature adjustment to the latent vectors, and training the model to complete predictions using the results of latent-space retrieval, so that the approximation error is absorbed by downstream tasks. This is also why LSA emphasizes accuracy close to the original model: it is not a pure inference-time trick, but an architecture-level change that works in concert with the training objective.

    It is worth stressing that the specific speedup factor is strongly tied to model architecture, layer distribution, block size, and batching strategy. The difference between 22x and 70x reflects different attention configurations across models rather than the relative merit of the method.

    4. Engineering Deployment: Five Details That Must Be Handled

    To reproduce a similar approach in your own inference stack, the following areas determine success or failure:

    • The tradeoff in block size B: too small, and indexing stays expensive; too large, and recall is insufficient while fine-selection cost rises. A practical approach is to work backward from the constraint that indexing should stay below 10% of total time.
    • Memory access and parallelism: latent-space retrieval is a memory-access-intensive operation that needs tiled pipelines and operator fusion to avoid the reappearance of quadratic memory access.
    • Coordination with linear attention layers: in a hybrid architecture, the linear layers have already compressed the history, so doing latent-space retrieval in the global layers keeps overall memory and bandwidth more favorable.
    • Accuracy regression evaluation: it must cover long-range dependency tasks such as long-document retrieval, multi-hop question answering, and code repository understanding. Looking at perplexity alone is not enough.
    • Service infrastructure: ultra-long-context inference needs a container platform to host elastic compute, object storage to hold long-text corpora, and logging and monitoring with alerting to track time-to-first-token, throughput, and the share of time spent on indexing, forming an observable tuning loop.

    5. Practical Advice for Developers

    First, measure before optimizing. Use per-layer time breakdowns to locate the indexing share; if indexing exceeds 30% of total time, change the selection mechanism before the operators. Second, treat recall as a first-class metric. The ceiling of sparse attention is set by recall, so it is worth evaluating the recall-accuracy curve offline under different B and k values. Third, roll out in stages. Enable latent-space retrieval on the prefill side first and keep the exact path on the decode side; unify them only after stability is verified. Fourth, watch the long tail of lengths. Ten-million-token requests are often a minority, so pair the approach with request tiering and resource isolation to keep long requests from dragging down the overall SLA.

    Conclusion

    The next wall for long context is not “unable to compute” but “unable to select.” Moving selection into a compressed latent space, trading a two-level approximation for a lower-order indexing complexity, is currently one of the most cost-effective engineering directions. For platforms and toolchains, whoever can turn this kind of approximate retrieval into a standard capability that is observable, tunable, and rollback-able will be able to offer a more stable inference experience in the ten-million-token era. This is also the significance of Baidu AI Cloud’s continued investment in general-purpose capabilities for serving long-context inference.