Sparse Attention at 10 Million Tokens: Why Indexing Is the Real Bottleneck and How Latent Sparse Attention Delivers Up to 22x Speedups

    As context windows grow from millions to tens of millions of tokens, the bottleneck in long-context inference shifts from computing attention to finding which tokens to attend to. This article breaks down why scoring and top-k selection remain quadratic even when aggregation is sparsified, and introduces Latent Sparse Attention (LSA), which projects queries and history into a low-dimensional latent space and uses two-stage block filtering to cut indexing costs. It includes complexity analysis, a framework-agnostic pseudocode skeleton, practical tuning guidance, common pitfalls, and the cloud capabilities needed to run long-context inference reliably.

    Over the past two years, the long-context race has largely been about window size. Million-token context is becoming a default configuration for many model services, and hybrid architectures that mix sparse and linear attention are being used to balance accuracy against cost. These approaches share the same premise: each query does not need to scan the entire token history and only attends to a small set of the most relevant positions.

    That premise has been validated repeatedly at the million-token scale. But when the context is pushed to tens of millions of tokens, an overhead that once seemed negligible starts to spiral. In one global attention layer, for example, roughly 98% of prefill time at the 10-million-token scale is spent not on attention computation but on the indexing step that decides which tokens to look at.

    The nature of the problem has changed. Sparse attention has already shown that attending to a small subset is enough to preserve accuracy. What actually blocks extreme-length context is that the cost of finding that subset still grows quadratically with context length.

    2. A Complexity View: Why Indexing Takes Center Stage

    Breaking a single attention operation into three steps makes the structure clearer:

    1. Score: estimate the relevance of every historical position to the current query.
    2. Select: pick the top-k positions from the scores.
    3. Aggregate: compute a weighted sum over only the selected positions.

    Sparsification compresses the third step, but the first two still face the full set of candidates. With sequence length n and k positions selected per query, aggregation costs roughly O(n·k), while scoring and selection remain O(n) or even O(n²) overall, which becomes more pronounced across multiple layers and heads. At the million-token scale, the gap between n·k and n² can still be masked by raw compute. At the tens-of-millions scale, that gap turns into an order-of-magnitude difference, and the indexer goes from a supporting role to the bottleneck.

    Two engineering factors amplify the issue. First, indexing results are data-dependent, which leads to irregular memory access and low cache hit rates. Second, top-k selection is hard to parallelize and tends to create serial segments on accelerators.

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

    A recent paper from a startup research team and university collaborators proposes Latent Sparse Attention (LSA). Instead of scoring at full resolution over the original token dimension, LSA first projects queries and history into a low-dimensional latent space, performs similarity estimation and candidate filtering there, and then returns to the original dimension for aggregation.

    The key design points are:

    • Low-dimensional projection: a shared projection matrix maps queries and historical representations into dimension d′ (d′ is much smaller than the head dimension), so scoring cost drops linearly with d′.
    • Block-level approximation: history is split into blocks, and block-level latent representations are used for coarse filtering; fine-grained selection happens only within the selected blocks, forming a two-stage filter.
    • Cache-friendly design: latent representations and block summaries can be reused, avoiding repeated reads of the full history for every query.
    • Compatibility with existing architectures: LSA replaces the internal implementation of the attention layer without changing the model’s external interface or weight layout.

    The paper reports that at the tens-of-millions-token scale, a single attention layer achieves roughly 22.7x and 72.4x prefill speedups while maintaining accuracy close to the original model across a range of tasks. Note that these are layer-level results on specific hardware and implementations; end-to-end throughput also depends on communication, operator fusion, and scheduling.

    4. A Skeleton Implementation of the Two-Stage Filter

    The pseudocode below expresses only the control flow and does not depend on any specific framework API:

    1. def latent_sparse_attention(q, k, v, block=2048, d_latent=64, topk=512):
    2. # 1) Project into the latent space (weights can be learned or a fixed random projection)
    3. q_l = project(q, d_latent) # [nq, d_latent]
    4. k_l = project(k, d_latent) # [nk, d_latent]
    5. # 2) Block-level coarse filtering: select a few candidate blocks per query
    6. block_scores = block_summary(k_l, block) @ q_l.T # [nblocks, nq]
    7. cand_blocks = topk_indices(block_scores, k=8) # 8 blocks per query
    8. # 3) Fine filtering within blocks + aggregation
    9. out = []
    10. for i in range(q.shape[0]):
    11. idx = gather_within_blocks(cand_blocks[i], k_l, topk - 8 * block)
    12. out.append(softmax(q[i] @ k[idx].T) @ v[idx])
    13. return stack(out)

    In practice, three things determine success: the ratio between block size and top-k, the choice of latent dimension d′, and the recall of the coarse filtering stage. Insufficient recall in coarse filtering shows up directly as accuracy regressions on long-document tasks.

    5. Deployment Notes and Common Pitfalls

    • Profile before optimizing: use per-layer timing to confirm the share of indexing cost, and avoid spending compute on aggregation operators that are already fast.
    • Prioritize recall over speed: measure coarse-filter recall on an offline evaluation set first, then tighten top-k gradually.
    • Keep training and inference consistent: if inference uses latent-space filtering, the model should have seen similar sparse patterns during training; otherwise distribution shift amplifies errors.
    • Use a layered strategy: enable LSA only in the global layers of long sequences and keep dense local windows in local layers, which usually offers better cost-performance.
    • Cover long-range dependency tasks in accuracy regression: short question-answering tests cannot expose coarse-filtering defects, so include retrieval, aggregation, and multi-hop reasoning evaluations.

    6. Combining General Cloud Capabilities for Production

    Turning this kind of optimization into a stable service typically requires several general cloud capabilities: a container platform to host elastically scaling inference instances; object storage for model weights and evaluation sets; a message queue for request peak shaving and batch queuing; and logging, monitoring, and alerting to track time-to-first-token, prefill duration, and recall-related metrics. Baidu AI Cloud offers corresponding capabilities in these general categories and can serve as an engineering foundation for ultra-long-context inference services.

    7. Conclusion

    At the tens-of-millions-token scale, the core tension has shifted from being able to compute to being able to find fast. Through low-dimensional scoring and block-level coarse filtering, Latent Sparse Attention brings the indexing step back from quadratic to near-linear, delivering order-of-magnitude improvements in ultra-long-context prefill. For developers, the reusable methodology is: first locate the share of indexing cost, then use two-stage filtering to reduce the candidate set, and finally set recall and long-range task accuracy as the gate for going live.