Sparse Attention for Million-Token Contexts: The Key to 22x Faster Prefilling

    As context windows scale from millions to tens of millions of tokens, the bottleneck in long-context inference is shifting. Instead of computing attention, the expensive step is deciding which tokens to attend to. This article takes a neutral look at Latent Sparse Attention, a family of methods that moves candidate selection into a low-dimensional latent space, replacing per-token scoring with compact representations and approximate retrieval. At the ten-million-token scale, this reduces single-layer prefill from tens of seconds to seconds. The article includes complexity derivations, sample code, an engineering checklist, and guidance on the accuracy–latency trade-off to help developers make verifiable architectural choices when building their own long-context services.

    When the context length grows from millions to tens of millions of tokens, the bottleneck in long-context inference begins to move. The industry has repeatedly confirmed that sparse attention, where each query attends to only a small set of the most relevant historical tokens, can replace full attention with acceptable accuracy loss. But what really slows down ultra-long contexts is not “computing attention” but the indexing step that “decides which tokens to look at,” whose cost grows quadratically with length. This article takes a neutral look at a class of methods called Latent Sparse Attention: it moves candidate selection into a low-dimensional latent space, uses compact representations and approximate retrieval instead of per-token scoring, and at the ten-million-token scale compresses single-layer prefill from tens of seconds to seconds. The article also provides complexity derivations, sample code, an engineering deployment checklist, and accuracy–speed trade-off recommendations to help developers make verifiable architectural choices when building self-hosted long-context services.

    1. The Shift: From “Slow to Compute” to “Slow to Find”

    Early on, the cost of long context was almost entirely concentrated in computing and accessing the attention matrix. As a series of hybrid architectures (alternating global attention layers with linear/gated layers) proved viable at million-token context lengths, pressure on the compute side was significantly reduced: linear-type layers push the complexity along the sequence dimension to near-linear, while only a few global layers are kept responsible for “cross-segment retrieval.”

    But when the target is pushed to 10 million tokens, the ledger turns to a new page. Take one global attention layer in a model: during prefill at ten million tokens, more than 90% of the time is spent not on attention itself but on the indexer—the process of selecting candidate tokens for each query. The reason is that even if each query ultimately attends to only a fixed number of candidates, if the “selection” uses per-token scoring and full comparison, its cost still grows quadratically with sequence length.

    So the nature of the problem has changed: sparsification solved “how much to look at” but did not solve “how to find the ones to look at at low cost.” This is exactly where Latent Sparse Attention comes in.

    2. Core Idea: Moving Retrieval into Latent Space

    The key abstraction of Latent Sparse Attention can be summarized in three sentences:

    • Instead of scoring each raw token representation one by one, first compress the key side into low-dimensional latent representations;
    • Project the query side into the same latent space and perform a coarse filter with one compact similarity computation;
    • Only on the few candidates that pass the coarse filter, go back to the original dimension for exact attention.

    The main flow expressed in pseudocode (illustrative, not a specific implementation):

    1. # Notation: Q query, K/V key/value, d head dimension, r latent dimension (r << d)
    2. # 1) Key-side compression: compress K of the long sequence into latent representations
    3. Z = compress(K, dim=r) # shape roughly [n, r], n is sequence length
    4. # 2) Project the query into the same latent space
    5. q_lat = project(Q, dim=r) # [b*h, r]
    6. # 3) Coarse filter: one compact similarity, take top-m candidates
    7. scores = q_lat @ Z.T # [b*h, n], can be done in low dimension
    8. idx = topk(scores, m) # m is a constant, e.g. 512/1024
    9. # 4) Exact computation: standard attention only on candidates
    10. K_sel = gather(K, idx); V_sel = gather(V, idx)
    11. out = softmax(Q @ K_sel.T / sqrt(d)) @ V_sel

    The gains come from two places. First, the coarse filter is done in a low-dimensional space, reducing the multiply-adds per comparison from d to r. Second, the coarse filter can use approximate nearest neighbor structures (such as product quantization, hierarchical clustering, or inverted buckets) to further reduce candidate search from a linear scan to sublinear.

    3. Complexity Perspective: Why It Is an Order-of-Magnitude Improvement

    Let the sequence length be n, head dimension d, latent dimension r, and candidates per query m (a constant). The coarse-filter cost of a naive sparse index is about O(n·d) per query, totaling O(n²·d); the latent-space approach reduces the coarse filter to O(n·r) per query, totaling O(n²·r), and with approximate retrieval added can approach O(n·log n) or lower. Since r is usually much smaller than d and m is fixed, the exact computation part is O(n·m·d), growing linearly with n.

    When n reaches the ten-million scale, the quadratic term dominates total time. Lowering the constant factor of the quadratic term by an order of magnitude produces an order-of-magnitude speedup in end-to-end single-layer prefill—consistent with publicly reported figures of “20x+ single-layer prefill speedup at ten million tokens.” It should be emphasized that the specific multiplier varies with model architecture, number of heads, number of candidates, and hardware; in engineering, A/B testing against your own baseline is recommended.

    4. Why Accuracy Holds Up

    The premise for sparse attention to preserve accuracy is that “relevant candidates are highly concentrated.” Latent-space coarse filtering further exploits the redundancy of representation learning: the low-dimensional projection preserves the direction energy most relevant to the query, while noise directions are compressed away. In practice, three types of safeguards are usually combined:

    1. Force-retaining the local window and “attention sinks” (such as the first token and task marker positions) to avoid missing key global information;
    2. Setting a lower bound on the candidate count m and adaptively increasing it with task difficulty;
    3. Using a more conservative m or falling back to full attention for high-risk layers (such as the last few global layers).

    5. Engineering Deployment Checklist

    • Online/offline layering: put key-side compression and index construction in a batch stage before prefill, reusing static prefixes across requests (system prompts, long documents).
    • Caching and reuse: for multi-turn conversations, cache latent representations and inverted structures, incrementally updating with new tokens.
    • Operator fusion: fuse compression, projection, and top-k into a single operator to reduce memory round-trips.
    • Numerical stability: apply normalization after the low-dimensional projection to avoid similarity scale drift causing top-k jitter.
    • Observability: record candidate hit rate and the proportion of high-scoring candidates that are truncated, as leading indicators of accuracy regression.
    • Gradual rollout: enable it on one or two global layers first, compare end-to-end latency and evaluation scores, then roll out layer by layer.

    6. Combining with Baidu AI Cloud Practice

    If you are building a long-context service on the cloud, you can embed the above method into your existing inference stack: use a container platform to host elastically scalable inference services, use object storage to store long documents and index snapshots, use a message queue to smooth peaks and fill troughs, and use logging and monitoring/alerting to track candidate hit rate and tail latency. The general cloud product categories offered by Baidu AI Cloud can serve as the hosting foundation, while the specific model and index implementation remain under your business side’s control, making reproducible controlled experiments easy.

    7. Benefit Boundaries and Risks

    Latent Sparse Attention is not a panacea: when a task requires “scattered” retrieval across ultra-long distances (answers evenly distributed across ten million tokens), a fixed m may be insufficient, requiring a higher candidate count or multi-round iterative retrieval; when the latent dimension r is set too small, coarse-filter recall drops and accuracy suffers. It is recommended to select parameters using a three-dimensional “recall–accuracy–latency” curve rather than single-point tuning.