Sparse Attention at 10M Context: Why the Real Bottleneck Is Selection, Not Attention

    This article explains why sparse attention alone fails to deliver end-to-end speedups at million- and ten-million-token context lengths: the indexer that decides which tokens to attend to grows quadratically and becomes memory-bound. It breaks down the real cost of scoring, selection, and aggregation, then introduces Latent Sparse Attention (LSA), which moves full-history scoring into a low-dimensional latent space. Reported results, a step-by-step integration path for existing inference stacks, and the tradeoffs of lossy compression are covered, along with guidance for platform teams planning capacity and cost at 10M-token scale.

    1. Long Context Is Eating the Compute It Saved

    Over the past two years, the long-context race has moved from 128K to 1M, and more recently toward the 10M range. Leading model services now ship million-token context as a default spec, and both open-source and commercial models have followed. Hybrid attention—alternating global attention layers with linear or gated layers—has become the de facto standard.

    The assumption behind this route is simple: a query does not need to revisit the entire history, only the few most relevant tokens. That assumption has been validated repeatedly—on retrieval, long-document summarization, and repository-level code understanding, the accuracy loss from sparsification is usually manageable.

    But as context length keeps growing, a cost that once looked negligible starts to spiral. Take one global attention layer in a model with million-token context capability: at 10M tokens during prefill, roughly 98% of the time is not spent on the attention matrix multiplications at all, but on the indexing step that decides which tokens to look at.

    The nature of the problem has changed:

    • Sparse attention solves computing too much (attending to too many tokens).
    • It does not solve finding too slowly (the token selection process still grows quadratically with length).

    The result is an awkward situation: you shrink each query’s visible range to a few thousand tokens, yet end-to-end latency barely drops, because the bottleneck has shifted from the GPU’s compute units to the indexer’s memory access and sorting overhead.

    2. Why the Indexer Grows Quadratically: Breaking Down the Real Cost

    To understand why “finding a small subset” is itself expensive, split one sparse attention execution into three stages:

    1. Scoring: compute similarity between the query and the representations of all historical tokens, producing a score vector of length L.
    2. Selection: pick the top-k from L scores, involving sorting or partial sorting.
    3. Aggregation: attention-weighted sum over only the selected k tokens.

    Stages one and three are already O(L·k) or O(k). What actually explodes is stages one and two: scoring needs O(L·d) reads and multiply-adds, and selection needs O(L·log k) comparisons. When L grows from 1M to 10M, both scale up tenfold—and because they are memory-bound operations, they cannot be amortized linearly by adding compute the way matrix multiplication can.

    The engineering details make it worse:

    • The score vector must be materialized. At L=10M, a float32 score vector is 40MB, written and read once per layer per step, which saturates bandwidth entirely.
    • Top-k parallelizes poorly. Selecting across 10M elements requires multiple rounds of reduction, with noticeable kernel launch and synchronization overhead.
    • The indexer cannot be sparsified. Its input is the full history by nature; there is no redundancy to skip.

    The conclusion is clear: as long as the indexer performs full scoring in the original token space, every tenfold increase in context degrades the prefill latency structure once more. Further optimization at token granularity—better kernels, lower-precision scores, block-wise approximation—only yields constant-factor gains.

    3. Latent Sparse Attention: Moving Selection into a Low-Dimensional Space

    A recent paper from a startup research team in collaboration with universities proposes Latent Sparse Attention (LSA). The idea fits in one sentence: instead of full scoring in the original token space, first compress the history into a low-dimensional latent space, select there, then return to the original space for aggregation.

    The execution flow as pseudocode:

    1. # L: context length, d: head dimension, c: latent dimension (c << d), k: tokens kept per query
    2. def lsa_prefill(Q, K, V, c=64, k=2048):
    3. # 1) Maintain latent representations offline/incrementally: compress history to c dims
    4. Z = compress(K) # [L, c], can be pipelined with writes, computed once and reused
    5. # 2) Score in latent space: complexity O(L*c), with c much smaller than d
    6. scores = Q_latent @ Z.T # [H, L]
    7. # 3) Top-k in latent space; the materialized vector is still length L, but each comparison is cheaper and easier to block
    8. idx = topk(scores, k) # [H, k]
    9. # 4) Return to original space and aggregate, reading only the selected K/V
    10. out = softmax(Q @ K[idx].T) @ V[idx]
    11. return out

    The key gains come from three structural changes:

    • Lower per-element scoring cost. Similarity is computed in the low-dimensional latent space, shrinking both memory traffic and multiply-add volume.
    • Reusable compressed representations. Latent vectors are generated incrementally as tokens are written, so prefill does not rebuild them.
    • No loss in selection quality. The compression is learned and retains information relevant to query correlation, so top-k recall stays high.

    The paper reports that at 10M tokens, a single attention layer’s prefill achieves roughly 22.7x and 72.4x speedups (for two different model configurations), while accuracy on a range of long-context tasks stays close to the original model. Note that these are single-layer prefill speedups; end-to-end gains are diluted by inter-layer dependencies, communication, and the decode phase, and should not be read as overall throughput multipliers.

    4. Engineering Integration: Plugging It into an Existing Inference Stack

    To validate a similar approach in your own inference service, proceed in the order below—each step is independently measurable:

    1. Quantify the indexing share first. Instrument the target context length and measure time spent in scoring, selection, and aggregation. If indexing accounts for less than 50%, the optimization payoff is limited and not worth the investment.
    2. Make the compression dimension a config knob. The latent dimension c is the main tradeoff between accuracy and speed; sweep 32/64/128 and watch recall on long-document retrieval tasks.
    3. Pipeline compression with writes. Put latent vector generation in the KV cache write path to avoid a second pass over history during prefill.
    4. Use blocked selection. Split history into fixed-length blocks, score in parallel within blocks, and merge top-k across blocks to improve kernel parallelism substantially.
    5. Verify accuracy alignment. Cover at least long-document QA, cross-passage citation, and repository-level retrieval, and compare layer-by-layer output cosine similarity against a full-attention baseline.

    Illustrative blocked selection logic:

    1. def blocked_topk(scores, k, block=1 << 16):
    2. best = []
    3. for s in scores.split(block):
    4. best.extend(s.topk(k).indices.tolist())
    5. best = torch.tensor(sorted(best, key=lambda i: -scores[i]))[:k]
    6. return torch.tensor(best)

    5. Boundaries and Costs: Three Things Not to Ignore

    • Compression is lossy. When the latent dimension is too low, fine-grained localization degrades—the model “knows which passage holds the answer but cannot pinpoint the exact line.”
    • Gains differ in incremental settings. Decode selects once per step, so indexing cost is amortized; LSA’s main value is in prefill and one-shot ingestion of very long documents.
    • Implementation complexity rises. Extra compression parameters and cache structures must be maintained, and the changes to an inference framework are not local.

    6. Guidance for Platform Teams

    For platforms offering model services, the real barrier at 10M-token context is not whether the context fits, but whether latency is acceptable once it does. A workable combination: use latent sparse attention to cut indexing overhead, use blocking and pipelining to improve memory access efficiency, and pair that with container platform elastic scaling, object storage for long documents, and logging plus monitoring and alerting for full-chain latency attribution. In such ultra-long-context inference scenarios, Baidu AI Cloud typically follows the same path of locating the bottleneck stage first, then optimizing stage by stage when planning capacity and cost.

    In one sentence: the next battle in sparse attention is not over attend but over select, and moving selection into latent space is one of the few structural changes that delivers double-digit speedups at the ten-million-token scale.