Sparse Attention at 10M-Token Contexts: The Indexing Bottleneck and How to Overcome It

    As context windows scale to millions and even tens of millions of tokens, sparse attention has become the standard approach for keeping inference costs manageable. However, the indexer that selects which keys each query attends to has quietly become the dominant bottleneck—on one long-context attention layer at 10M tokens, indexing accounted for nearly 98% of prefill time. This article breaks down why this happens, examines practical techniques for reducing indexing costs, and outlines how to validate both speed and accuracy when deploying sparse attention at extreme context lengths.

    Sparse Attention at 10M-Token Contexts: The Indexing Bottleneck and How to Overcome It

    1. Background: Context Lengths Enter the Tens of Millions

    Million-token contexts have evolved from a differentiating feature into a mainstream specification. Longer contexts clearly improve model performance on long-document analysis, codebase understanding, and long-running conversations—but they also drive up inference costs.

    The attention layer is one of the primary cost drivers in long-context inference. In standard full attention, every query must compute relevance against every historical key. With a context length of T, the prefill stage costs roughly O(T²), and decoding costs O(T) per generated token. Scaling from 1M to 10M tokens theoretically increases prefill attention compute by about 100x.

    To mitigate this, the industry has widely adopted sparse attention. The core idea is to have each query attend to only a small set of the most relevant keys, reducing attention overhead to O(Tk), where k is the number of keys each query actually computes against.

    2. The Hidden Cost of Sparse Attention

    The key to sparse attention lies in the step that “selects k keys.” The common approach introduces a lightweight indexer: first, each query scores all keys, then the top k are selected. The workflow looks like this in pseudocode:

    1. function sparse_attention(query, keys, values, k):
    2. # Stage 1: the indexer scores all keys
    3. scores = indexer_score(query, keys) # shape [T]
    4. selected = topk(scores, k) # pick the k most relevant keys
    5. # Stage 2: attend only over the selected keys
    6. return attention(query, keys[selected], values[selected])

    The problem is that stage 1 still scores all T keys. Even if stage 2 drops to O(k), the indexer itself scales with T. During prefill, every query must run the indexing step, so total cost remains on the order of T².

    To put concrete numbers on it: with T = 10M and k = 512, full attention requires roughly 10¹⁴ query-key pair computations, while stage 2 needs only about 5.12 × 10⁹. But if the indexer scans all keys for every query, its scoring cost is still close to 10¹⁴. In other words, sparsity savings mostly come from stage 2, while the real bottleneck is left in stage 1.

    Measurements confirm this. On a global attention layer in a large language model, prefill with 10M tokens spent nearly 98% of the time in the indexer rather than in attention computation itself.

    3. The Essence of the Problem: From “How Much to Compute” to “What to Find”

    Sparse attention research has shown that models typically need to attend to only a small fraction of tokens to maintain high accuracy. The hard problem for ultra-long contexts has therefore shifted from “how much to compute” to “which tokens to find.”

    The cost of finding the right tokens depends on two factors: the per-pair scoring cost, and the number of pairs that need scoring. The former can be compressed by reducing the dimensionality of the scoring representation; the latter can be reduced through hierarchical or block-based methods. These map to the following categories of approaches.

    4. Common Approaches to Reducing Indexing Cost

    1. Latent-Space (Low-Dimensional) Scoring

    The indexer does not have to score in the original high-dimensional representation. A projection matrix can first map queries and keys into a lower-dimensional latent space, where similarity is then computed. Per-pair scoring cost drops from O(d) to O(r), where r < d.

    The following pseudocode illustrates this idea and is for demonstrating the computation structure only:

    1. function latent_indexer_topk(Q, K, W_proj, k):
    2. # Q: [Tq, d], K: [Tk, d], W_proj: [d, r]
    3. Q_lat = matmul(Q, W_proj) # [Tq, r]
    4. K_lat = matmul(K, W_proj) # [Tk, r]
    5. scores = matmul(Q_lat, transpose(K_lat)) # [Tq, Tk]
    6. return topk(scores, k, axis=-1)

    Note that this code still materializes the full [Tq, Tk] score matrix, which is infeasible in both memory and time at the 10M-token scale. Real systems need to combine this with chunked computation or approximate retrieval to avoid materializing the entire matrix at once. Projection also loses some information, so the choice of r requires balancing speed against recall.

    2. Block-Based and Hierarchical Indexing

    Keys can be divided into fixed-length blocks, with a summary vector computed for each block. A query first compares against block summaries to select candidate blocks, then performs fine-grained scoring within those blocks. This coarse-to-fine approach turns a scan over all keys into a scan over blocks plus a small amount of in-block scanning.

    The trade-off is that block summaries may miss important tokens. Block size and the number of candidate blocks need to be tuned according to the retrieval difficulty of the task.

    3. Index Reuse During Decoding

    During decoding, queries in adjacent steps usually change little, and the selected key sets often overlap substantially. By caching the previous step’s candidate set and applying incremental updates only for newly added tokens, redundant computation can be reduced. This approach is especially effective for long conversations and long-output scenarios.

    4. Hybrid Architectures

    Another common practice is to keep full attention in some layers while using sparse or linear attention in others. Full attention layers preserve critical global information, while the remaining layers control overall cost. The layer allocation ratio must be determined experimentally—there is no universally optimal split.

    5. Validation Methods for Engineering Deployment

    After optimizing indexing cost, both speed and accuracy must be validated—neither can be skipped.

    1. Measure latency stage by stage. Time prefill and decoding separately, and track indexer, attention computation, and memory access time individually. Looking only at end-to-end latency can easily mask the true bottleneck.

    2. Measure at multiple lengths. Set multiple length points from 128k to 10M tokens and observe how latency scales with length. If the curve is still close to quadratic, indexing optimization is not yet effective.

    3. Compare recall. Using full attention as the ground truth, compute the overlap between the keys selected by the sparse method and the truly most relevant keys. The more recall drops, the higher the risk to downstream task accuracy.

    4. Evaluate accuracy on long-context tasks. Use long-context benchmarks covering retrieval, question answering, and multi-hop reasoning, and compare scores before and after optimization. Accuracy degradation should stay within business-acceptable limits.

    5. Track GPU memory usage. Latent-space projection and block summaries both introduce additional storage. At the 10M-token scale, memory can become the new limiting factor.

    6. Applicability and Selection Guidance

    • With context lengths under a few hundred thousand tokens, indexing is usually not the main bottleneck; full attention or simple sparse schemes are sufficient.
    • At the 10M-token scale, with workloads dominated by long-document retrieval and codebase analysis, indexing optimization delivers the clearest gains.
    • For accuracy-critical scenarios, validate recall first, then decide how aggressively to compress.
    • For latency-sensitive online services, decoding-stage index reuse is often a better investment than simply reducing prefill cost.

    Engineering optimization for ultra-long contexts has shifted from “reducing attention computation” to “reducing the cost of selecting the right information.” Treating the indexing stage as an independent performance target—to be measured, optimized, and validated—is the prerequisite for maintaining usable performance at the 10M-token scale.