Speeding Up Sparse Attention Indexing for Ten-Million-Token Contexts

    Sparse attention reduces computation but not the cost of finding relevant tokens. At ten-million-token scale, the indexing step—selecting candidates before attention—can dominate prefill time, growing quadratically with sequence length. This article explains why indexing becomes the bottleneck, introduces a latent-space sparse attention approach with two-stage candidate selection (block-level coarse filtering in a low-dimensional space, then token-level fine selection in the original space), provides a simplified algorithm outline, analyzes complexity and engineering trade-offs, and discusses precision risks and practical deployment guidance.

    1. Background: Sparse Attention Solves “Less Computation” but Not “Faster Search”

    As context length grows from one million to ten million tokens, the core challenge for sparse attention shifts. The traditional idea is to avoid having every query attend to all historical tokens, instead selecting a small number of most relevant keys and values for attention computation. This direction has been validated repeatedly at million-token scale: if candidate selection is accurate enough, attention computation itself can be greatly reduced while maintaining acceptable precision.

    However, “attending to only a small part” involves two actions: first, deciding which tokens to look at; second, computing attention over the chosen tokens. Much discussion focuses on the second action, overlooking the cost of the first. In very long contexts, the truly expensive operation is often not the attention dot product but the indexing process that finds the candidate set for each query. If the indexer still scores query–key pairs in the original high-dimensional space, its cost grows quadratically with context length.

    Thus, sparse attention does not inherently eliminate all overhead of long contexts. It shifts part of the computation from “full attention” to “candidate selection.” When sequences are short, this overhead is negligible; at ten-million-token scale, the indexer can become the dominant prefill bottleneck. Public experiments on certain global-attention layers at ten-million-token scale report that the indexer can consume over 90% of prefill time, and in extreme configurations approaches nearly all of it. The nature of the problem changes: the bottleneck moves from “how to compute attention” to “how to find candidates.”

    2. Bottleneck Shift: Why the Indexer Becomes Unmanageable at Ten-Million-Token Scale

    Let the sequence length be N, the original attention dimension be d, and the number of tokens retained per query be k. Standard sparse attention has a computation cost of approximately O(N·k·d) for attention itself, which is controllable when k is much smaller than N. But if the indexer scores every query against all historical keys, its cost is roughly O(N²·d). When N grows from one million to ten million, N² grows far faster than the linear term, so the indexer quickly dominates total time.

    More specifically, the indexer typically involves projection, scoring, sorting or Top-k selection, and candidate gathering. Projection and scoring can be matrix-based but still process a large number of query–key combinations; Top-k retains only a few results but requires comparisons over many scores; candidate gathering often leads to irregular memory access. Even if attention is computed only on a small candidate set, the matrix multiplications, memory bandwidth, and sorting overhead during indexing still scale with N².

    This also explains why simply reducing the number of attention candidates provides limited benefit. Reducing k from 64 to 32 only lowers the attention computation part; it does not lower the cost of “finding 32 positions out of N.” To break through ten-million-token contexts, the indexer itself must be freed from quadratic complexity or high constant overhead. A viable direction is to avoid exact full indexing in the original high-dimensional space, and instead perform coarse filtering in a low-dimensional latent space, followed by exact selection within the candidate set.

    3. Core Idea: Latent-Space Sparse Attention

    The key point of latent-space sparse attention is not simply replacing a brand or model, but changing where candidate selection happens. It projects queries and keys into a lower-dimensional latent space, computes approximate relevance there, and completes a first round of screening at lower cost. It then returns to the original dimension for exact scoring and attention computation on only a small number of candidate blocks or tokens.

    This approach typically involves two-stage screening. The first stage is block-level coarse filtering: divide the key sequence into fixed-size blocks, generate a summary vector for each block—for example, mean pooling, max pooling, or learnable pooling over latent-space key vectors. The query scores against block summaries in latent space and selects the Top-b candidate blocks. The second stage is token-level fine filtering: gather tokens inside the candidate blocks, return to the original dimension for exact relevance scoring, and then select the Top-k tokens for attention. Since the number of candidate blocks is much smaller than the number of tokens, the coarse-filtering cost drops significantly; and since fine filtering occurs only on a small candidate set, exact scoring does not explode.

    There are two important design points here. First, the latent dimension r should be much smaller than the original dimension d—for example, r from a fraction to one-tenth of d—to obtain practical benefits during coarse filtering. Second, the block size B needs a trade-off: too small makes block summaries unstable and increases the number of blocks; too large increases the number of tokens inside candidate blocks and raises fine-filtering cost. Real systems often use multi-level indexing—for example, coarse blocks, then sub-blocks, then tokens—to balance recall and cost.

    4. Algorithm Flow and Illustrative Code

    Below is a simplified pseudocode for a causal autoregressive scenario, intended only to illustrate the two-stage filtering logic, not as a real interface or parameter set. A real implementation must also handle masks, boundaries, numerical stability, variable-length sequences, and parallel load balancing.

    1. def latent_index_sparse_attention(q, k, v, Wq, Wk, block_size, top_b, top_k):
    2. # q/k/v: [N, d], Wq/Wk: [d, r], r << d
    3. q_lat = q @ Wq
    4. k_lat = k @ Wk
    5. # Block-level summary: pool latent-space keys by block_size
    6. k_blk = pool_blocks(k_lat, block_size) # [N / B, r]
    7. blk_score = q_lat @ k_blk.T # [N, N / B]
    8. blk_score = apply_causal_block_mask(blk_score, block_size)
    9. blk_idx = topk(blk_score, top_b, dim=-1) # Select Top-b blocks per query
    10. # Gather candidate tokens and score exactly in original dimension
    11. cand_idx = expand_blocks(blk_idx, block_size)
    12. cand_k = gather(k, cand_idx)
    13. exact_score = exact_dot(q, cand_k)
    14. tok_idx = topk(exact_score, top_k, dim=-1)
    15. # Only compute softmax and weighted sum over final Top-k
    16. selected_score = gather_score(exact_score, tok_idx)
    17. selected_v = gather(v, tok_idx)
    18. out = softmax(selected_score) @ selected_v
    19. return out

    This flow emphasizes a principle: the “coarse” indexing and the “fine” attention are separated. Coarse filtering happens in latent space at the block level, reducing the candidate range from N to a manageable number. Fine filtering happens in the original dimension at the token level, preserving precision. In causal scenarios, candidate blocks must only come from the current and previous positions; block boundaries and masks must stay consistent with training.

    5. Complexity and Benefit Analysis

    Assume sequence length N, original dimension d, latent dimension r, block size B, number of candidate blocks b, and final token count k. Original pairwise indexing is about O(N²·d). With latent-space block-level coarse filtering, the coarse stage is roughly O(N·(N/B)·r), which reduces the cost by the dimension factor r/d and the block factor 1/B compared to original indexing. The fine stage only performs exact scoring on tokens inside b blocks, approximately O(N·b·B·d) or O(N·k·d), depending on candidate gathering. When b·B is much smaller than N, the total cost is mostly controlled by the coarse stage, which no longer expands over every token in the original high-dimensional space.

    Public experiments at ten-million-token scale in global-attention-layer prefill report speedups of tens of times—roughly 20× to 70× for a single layer depending on model size, dimension, configuration, hardware, block size, candidate count, precision mode, and implementation quality. These numbers cannot be simply extrapolated to end-to-end training or inference speedups.

    There are also costs. Projection matrices add extra computation and storage; block summaries require caching; Top-k sorting and irregular candidate gathering may stress memory bandwidth; insufficient candidate-block recall can hurt precision. Therefore, latent-space indexing is not a “free speedup” but an engineering trade-off that replaces expensive full high-dimensional indexing with “low-dimensional coarse filtering plus a small amount of exact fine filtering.”

    6. Key Engineering Considerations

    First, block partitioning and hierarchical indexing should be designed together. Single-level block indexing is simple to implement but sensitive to block size; two- or three-level indexing—coarse blocks, then sub-blocks, then token-level scoring—makes it easier to balance recall and cost. Second, projection matrices can be learned, or initialized with fixed orthogonal or random projections and then calibrated on a small scale. In any case, monitor the consistency between latent-space scores and original scores.

    Third, prefill and decode should be optimized separately. During prefill, both query and key counts are large, well-suited for matrix-based block summaries, batched Top-k, and kernel fusion. During decode, tokens are generated one by one; block summaries and candidate caches should be updated incrementally, avoiding rebuilding the full index at each step. Fourth, try to fuse projection, scoring, Top-k, and candidate gathering to reduce intermediate tensor writes; otherwise the indexer may shift from a compute bottleneck to a memory-bandwidth bottleneck.

    Fifth, adopt a hybrid attention-layer strategy. Not every layer needs global sparse indexing. Most layers can use local windows or linear attention to reduce overhead, while a few global layers use latent-space indexing for long-range information aggregation, with periodic full-attention layers kept for calibration. Sixth, precision and stability should be observable: record candidate-block recall, final Top-k recall, end-to-end task metrics, perplexity, latency, and memory usage. Low-precision scoring should be calibrated separately to avoid Top-k instability near decision boundaries.

    7. Precision Evaluation and Risk Control

    The main risk of latent-space indexing is approximation error. Low-dimensional projection and block summaries may miss tokens that are relevant but semantically scattered, leading to insufficient candidate recall. Evaluation should not rely only on end-to-end average scores; intermediate metrics matter, such as candidate-block recall, candidate-token recall, Top-k stability, and performance on long-tail retrieval, multi-hop question answering, codebase understanding, long-document summarization, and similar tasks.

    If the original model has not been adequately trained on long contexts, directly replacing the indexer may cause distribution shift. A safer approach is to calibrate on small-scale long-context data first, comparing ordering correlation between latent-space and original scores, then gradually increase the proportion of sparse layers. For precision-sensitive tasks, increase the number of candidate blocks or keep a few full-attention layers as fallback. When short-context scenarios yield limited benefits, set a threshold to switch back to dense attention, avoiding unnecessary projection and sorting overhead for small sequences.

    8. Applicable Scenarios and Best Practices

    Latent-space sparse attention is suitable for prefill-intensive scenarios at ten-million-token scale: very long document analysis, enterprise knowledge-base concatenation, code-repository-level understanding, multi-turn conversation history compression, and log or audit record retrieval. These scenarios share a common trait: historical context far exceeds a single attention window, and truly relevant information occupies only a small proportion. For short-context tasks, high-precision token-by-token alignment, or tasks that strongly depend on full interactions, use it cautiously or only as an auxiliary layer in a hybrid architecture.

    Best practices can be summarized as: first use block-level coarse filtering to reduce the candidate range, then token-level fine filtering to preserve precision; tune latent dimension and block size through actual measurement; batch and matrixify prefill, use incremental caching for decode; fuse the indexer with attention kernels as much as possible; validate jointly with recall metrics and end-to-end metrics; and in a hybrid layer architecture, keep both global and local layers so that not all long-range modeling pressure falls on a single sparse index.

    9. Conclusion

    At ten-million-token scale, the difficulty of sparse attention shifts from “computing less attention” to “cheaply finding the attention you need to compute.” When the indexer still grows quadratically with context length, simply reducing the Top-k count does not solve the root problem. Latent-space sparse attention decouples the indexing stage from full high-dimensional scoring by combining low-dimensional coarse filtering with candidate fine filtering. Public experiments show tens-of-times speedups for single-layer prefill and offer an engineering path for very long-context systems. In practice, achieving stable, usable long-context capability requires attention to complexity, candidate recall, caching strategies, kernel fusion, and precision monitoring.