The Indexing Bottleneck in Million-Token Sparse Attention—and How to Optimize It

    At million- and ten-million-token context lengths, sparse attention reduces the cost of exact attention but does not automatically make candidate selection efficient. This article explains why token-level indexers can become the dominant prefill bottleneck, how latent-space and block-level filtering reduce indexing overhead, the resulting complexity and accuracy trade-offs, and the engineering metrics needed for production evaluation.

    From “How Much to Attend” to “Which Tokens to Find”: Optimizing Indexing for Ten-Million-Token Sparse Attention

    1. Background: Sparse Attention Reduces Computation, but Not Candidate Selection

    The first challenge in ultra-long-context processing is the cost of attention itself. Standard global attention computes relevance between every query and every token in the history, causing time complexity to grow quadratically with sequence length. Sparse attention addresses this by allowing each query to attend only to a small set of the most relevant tokens or token blocks. If the selected subset covers the critical information, model quality can remain close to that of global attention while the cost of exact attention falls from quadratic to approximately linear.

    This approach has been repeatedly validated at million-token context lengths. However, as context windows approach ten million tokens, the cost structure changes. The previously overlooked task of deciding which tokens to select can become the dominant expense. Public analyses indicate that, during prefill at a 10-million-token scale, roughly 98% of the time in some global attention layers is spent on the indexer that determines the candidate set rather than on attention computation itself.

    This changes the nature of the problem. Sparse attention has already demonstrated that looking at only a small portion of the history can preserve accuracy. The real challenge for ultra-long contexts is finding that small portion efficiently. If the indexer still computes high-dimensional relevance scores between every query and every historical token, it continues to carry quadratic cost. Once exact attention is sparsified, the indexer becomes the new bottleneck.

    2. Why the Indexer Becomes the Dominant Cost at Extreme Context Lengths

    2.1 Per-Query, Per-Token Scoring Introduces a Quadratic Term

    Content-routed sparse attention generally has two stages. First, an indexer estimates the relevance between each query and historical tokens and selects the top-k candidates. Second, exact attention is computed only over those candidates.

    If the indexer evaluates every query-token pair, the cost is approximately:

    1. Indexing cost ≈ O(n_q × n_k × d_index)
    2. During prefill, n_q ≈ n_k = n
    3. Indexing cost ≈ O(n² × d_index)

    Here, n is the sequence length and d_index is the dimensionality used for index scoring. Sparse attention reduces the cost of the second stage but does not remove the quadratic term in the first stage. As the context grows, indexing can easily become more expensive than exact attention.

    2.2 Top-k Selection Also Has a Cost

    The indexer must not only calculate scores but also sort or select the top-k candidates. Running top-k over a large candidate set introduces additional memory traffic, reductions, and synchronization overhead. On GPUs and other accelerators, this is often less a pure compute problem than a challenge involving memory bandwidth and parallel reduction efficiency.

    As the candidate set grows, temporary storage for the index matrix and the associated read/write operations also become more significant.

    2.3 Prefill Parallelism Amplifies Indexing Pressure

    During prefill, all queries can be processed in parallel, which appears beneficial for throughput. However, the indexer must generate candidate sets for a large number of queries at the same time. If the implementation is not carefully designed, index matrices, score caches, and intermediate top-k results can consume substantial GPU memory and produce irregular memory access patterns.

    Exact attention can rely on highly optimized matrix multiplication kernels. Indexers, by contrast, often combine projection, scoring, sorting, and mask generation, making kernel fusion more difficult.

    2.4 Prefill and Decode Have Different Bottlenecks

    Decode usually generates one token at a time. The number of queries is small, so indexing cost is relatively manageable. Prefill processes an entire context in one pass, with the number of queries comparable to the history length, making the quadratic indexing term much more visible.

    As a result, time to first token and prefill throughput for ultra-long contexts are often more vulnerable to indexer overhead than decode performance. Optimization must treat the two stages separately rather than relying on a single aggregate metric.

    3. The Core Idea of Latent-Space Sparse Attention: Move Coarse Filtering to a Lower-Dimensional, Coarser Space

    A class of recently proposed latent-space sparse attention methods does not primarily change the number of tokens that ultimately participate in exact attention. Instead, it restructures how candidates are selected.

    The key idea is to perform an initial filter in a lower-dimensional latent space and at a coarser granularity, then return to the original high-dimensional space for exact attention.

    In practice, the indexing stage can work as follows:

    1. Project queries and keys into a lower-dimensional latent space to obtain compact representations.
    2. Aggregate historical tokens into blocks and construct block-level latent representations.
    3. Compute relevance at the block level and select the top-b candidate blocks.
    4. Run exact attention only over tokens inside the selected blocks, optionally followed by token-level reranking within each block.

    The main benefit is not that the quadratic term disappears. Rather, the quadratic comparison is moved from high-dimensional, token-level matching to lower-dimensional, block-level matching. Block size and latent dimension jointly reduce the indexing constant, while exact attention depends only on the selected candidate tokens.

    At ten-million-token context lengths, this can rebalance the dominant cost from a high-dimensional token-level indexer toward a more manageable combination of coarse filtering and exact attention.

    A simplified implementation looks like this:

    1. function latent_sparse_prefill(Q, K, V, block_size, latent_dim, top_blocks):
    2. # Q: [n_query, d_model], K/V: [n_kv, d_model]
    3. q_latent = project_query(Q) # [n_query, latent_dim]
    4. k_latent = project_key(K) # [n_kv, latent_dim]
    5. # Aggregate historical tokens into block-level latent representations
    6. block_k_latent = pool_by_block(k_latent, block_size)
    7. # [n_block, latent_dim]
    8. # Perform coarse block-level filtering in latent space
    9. block_scores = matmul(q_latent, transpose(block_k_latent))
    10. # [n_query, n_block]
    11. selected_blocks = topk(block_scores, top_blocks)
    12. candidate_mask = build_block_mask(selected_blocks, block_size, n_kv)
    13. # Run exact attention only over the selected blocks
    14. output = exact_attention_with_mask(Q, K, V, candidate_mask)
    15. return output

    In production systems, coarse filtering can be hierarchical: first select large blocks, then rerank smaller blocks within them. A local window can also be combined with block selection to reduce the risk of missing nearby information.

    The key requirement is maintaining sufficient candidate recall so that the coarse filter does not discard critical tokens.

    4. Complexity, Benefits, and Accuracy Trade-offs

    The gains from latent-space sparse attention come from three sources:

    • Lower-dimensional index scoring;
    • Coarser-grained candidate comparison;
    • A smaller exact-attention region.

    A rough complexity estimate is:

    1. Coarse filtering cost ≈ O((n / block_size)² × latent_dim)
    2. Exact attention cost ≈ O(n × candidate_tokens × d_model)

    With suitable choices of block_size and latent_dim, coarse filtering can have a substantially lower constant than a high-dimensional, token-level indexer.

    Public experiments report speedups of roughly 20x to more than 70x for single-layer prefill at a 10-million-token scale while maintaining accuracy close to the original model across a range of tasks. The actual benefit depends on model architecture, layer type, block granularity, and hardware. These results should not be interpreted as equivalent end-to-end speedups for an entire system.

    Several boundaries also need to be considered:

    • For shorter contexts, the indexer may not be the primary bottleneck, so the optimization provides limited benefit.
    • If candidate blocks are too large, exact-attention cost increases. If they are too small, the number of blocks to filter grows and indexing cost rises again.
    • An excessively low latent dimension can reduce candidate recall and requires accuracy regression testing.
    • Tasks involving high sparsity, multi-hop retrieval, and codebase understanding are more sensitive to missed candidates and require dedicated evaluation.
    • If indexing kernels are not fused, sorting and mask generation can offset part of the theoretical gain.

    5. Engineering Checklist

    1. Tune block size and candidate count together. Do not tune only top-k. Block size determines filtering granularity and the amount of redundancy in exact attention, while the number of candidate blocks affects recall and cost. Sweep different combinations on realistic long-context distributions and record indexer time share, end-to-end throughput, and task accuracy.

    2. Calibrate the latent-space projection. Projection matrices can be obtained through low-rank decomposition, quantization, or lightweight learning, but they must be calibrated on long-context validation data. Candidate recall is more important than average loss alone.

    3. Optimize kernel fusion and memory layout. Fuse projection, block aggregation, scoring, top-k selection, and mask generation where possible to reduce materialization of intermediate tensors. A block-contiguous KV-cache layout can help coarse filtering and exact attention share data efficiently.

    4. Monitor prefill and decode separately. Track indexing time, exact-attention time, top-k time, and memory usage for both stages. An indexer optimization should not come at the cost of decode regression.

    5. Make accuracy regression tests cover long-range dependencies. In addition to standard perplexity, include long-document retrieval, multi-hop question answering, cross-section references, codebase understanding, and log analysis. Investigate cases where critical tokens are not selected.

    6. Keep a fallback path. Short sequences or accuracy-sensitive layers can fall back to the original indexer or global attention, while ultra-long sequences use latent-space filtering. Dynamic routing by layer, attention head, and sequence length is generally more robust than a one-size-fits-all policy.

    6. Evaluation: Put Speed and Accuracy in the Same Table

    A useful evaluation matrix includes the following dimensions:

    Dimension Metrics Purpose
    Latency Per-layer prefill latency, time to first token Determine whether the indexer remains the bottleneck
    Throughput Tokens per second, end-to-end request throughput Measure system-level gains
    Cost Indexing time share, peak memory usage Locate the balance between coarse filtering and exact attention
    Accuracy Retrieval hit rate, multi-hop QA, long-document summarization Verify that candidate recall is sufficient
    Stability Results across length buckets and block granularities Avoid long-tail degradation

    Comparison experiments should keep hardware, batch size, sequence-length distribution, and numerical precision fixed. Results should be reported separately for short, medium, long, and ultra-long contexts.

    Latent-space sparse attention is suitable for production only when the indexing time share drops substantially without a clear regression on long-range dependency tasks.

    7. Conclusion

    At ten-million-token context lengths, the central challenge of sparse attention shifts from “exact attention is too slow” to “candidate selection is too slow.”

    The value of latent-space sparse attention is not simply that it reduces the number of selected tokens. Instead, it moves candidate selection into a lower-dimensional, coarser latent space: first perform low-cost filtering, then apply high-precision attention to the selected region.

    For systems that must continue expanding their context windows, this provides a composable optimization path. It can be combined with block sparsity, local windows, linear attention, hierarchical routing, and kernel fusion to gradually remove the indexer from the dominant quadratic path.

    Whether the approach is production-ready ultimately depends on meeting the required balance among block size, latent dimension, candidate recall, and end-to-end accuracy.