Sparse Attention at 10M Tokens: Indexing Bottlenecks and Breakthroughs

    Sparse attention reduces exact attention cost by selecting a small set of keys per query, but at 10M-token context lengths the selection step itself becomes the dominant cost. This article analyzes the O(T²) indexing bottleneck, estimates the gap between indexing and exact attention, reviews common approaches to reducing index cost, and discusses latent-space scoring, hierarchical retrieval, and practical deployment validation.

    1. Background: Context Lengths Are Moving from 1M to 10M Tokens

    Large model context windows have expanded rapidly over the past two years. One million tokens has become a default specification for many general-purpose services, and some workloads are beginning to explore inputs at the 10M-token level, such as full code repository analysis, long-cycle log review, and cross-document legal and financial review.

    As context grows longer, the structure of inference cost changes. For short text, computation over model parameters and memory movement are the main costs. For long text, attention gradually becomes the main cost. Understanding this shift is the starting point for designing long-context systems.

    2. Cost Structure of Standard Full Attention

    Full attention requires each query to compute relevance against all previous keys, then use those relevance scores to compute a weighted sum of values. Let context length be T:

    • Prefill phase: Process T input tokens at once; attention computation is O(T²).
    • Decode phase: Each newly generated token must be compared with T historical keys; per-step cost is O(T).

    Under this pattern, when context grows from 1M to 10M tokens, prefill attention computation increases by roughly 100x. This means that each doubling of length increases attention cost by about four times.

    3. Basic Division of Work in Sparse Attention

    The core idea of sparse attention is to split the work into two steps:

    1. Indexing: Use a lightweight module to select the k most relevant keys for each query.
    2. Sparse attention: Perform standard attention computation only over these k keys.

    The cost of attention itself therefore drops to O(Tk). When k is much smaller than T, this gain is substantial.

    This idea depends on an empirical premise: the model needs only a small amount of critical information at most positions. Prior research on long-text evaluation at the 128k-token level has observed that retaining only about one percent of critical keys per query can still preserve performance close to full attention. This suggests that the accuracy risk of sparsification mainly comes from “selecting the wrong keys,” not from “selecting too few keys.”

    4. The Hidden Bill: Why the Indexer Also Grows Quadratically

    To know which k keys are most relevant, the indexer must score every key. For T queries in the prefill phase, each query must scan all T keys, so the computation of indexing itself remains O(T²).

    In a 10M-token prefill, the indexing stage may account for more than 90% of the time in a single attention layer. Attention computation, by contrast, may account for only a small fraction. The problem therefore shifts from “how to look at only a subset” to “how to find that subset at low cost.”

    The following estimate uses a set of hypothetical parameters to illustrate the gap between the two. Assume a single head, head dimension d=128, indexing score dimension d’=64, T=10^7, and k=512:

    1. Exact attention (only selected keys):
    2. T × k × d = 10^7 × 512 × 128 ≈ 6.6 × 10^11
    3. Full indexing score (each query scans all keys):
    4. T × T × d' = 10^7 × 10^7 × 64 ≈ 6.4 × 10^15
    5. Indexing cost / exact attention cost ≈ 10^4

    These numbers show that at the 10M-token level, the cost of indexing far exceeds the attention computation it saves. Even if scoring each token is cheap, multiplying it by T² becomes unmanageable.

    5. Trade-offs of Existing Indexing Approaches

    Common industry approaches to reducing indexing cost fall into roughly three categories. All of them can reduce constant factors, but none changes the O(T²) growth trend.

    Approach Method Benefit Cost
    Low-precision scoring Compute index scores using lower-bit numeric formats Faster per computation and lower memory usage Ranking is sensitive to numerical error, making mistakes more likely near boundaries
    Dimensionality-reduced scoring Project keys and queries into lower dimensions before comparison Fewer multiply-add operations per score Dimension compression loses some semantic information
    Block-level scoring Merge adjacent keys into blocks and score each block Number of scoring targets drops to T/b Coarse granularity may miss a small number of critical tokens within a block

    The common limitation of these three approaches is that the candidate set still needs to be fully scanned. As long as every query must be compared with all candidates, total cost remains quadratic.

    6. Changing the Computation Space of Indexing

    To truly break through quadratic growth, two problems need to be solved at the same time: reducing the cost of each score computation, and reducing the number of candidates each query must compare against.

    6.1 Scoring in Latent Space

    One approach is to learn a shared low-dimensional latent representation. The model compresses each key into a compact vector, maps the query into the same space, and then computes relevance in that space. Compressed keys can be cached and reused during generation to avoid repeated computation.

    The key to this approach is that the compression process needs training so that the compressed space still preserves the ranking information of “which keys are relevant,” rather than merely reconstructing the original vectors.

    6.2 Hierarchical Retrieval to Reduce Candidate Count

    A second approach organizes indexing into a multi-level structure. The first level uses coarse-grained summaries to quickly filter a batch of candidate blocks, and the second level performs fine-grained scoring only within those candidate blocks. The number of candidates drops from T to a constant order related to k, and total cost then approaches linear or sub-quadratic growth.

    6.3 Two-Stage Flow Illustration

    1. # Illustrative code only; shows the data flow, not a real API from a specific library
    2. def sparse_attention_with_latent_index(q, keys, values, k_top):
    3. # Stage 1: compress all keys into latent space (cacheable)
    4. latent_keys = project_to_latent(keys) # shape [T, d_latent]
    5. latent_q = project_to_latent(q) # shape [d_latent]
    6. # Stage 2: score in latent space and select top-k
    7. scores = latent_keys @ latent_q # shape [T]
    8. idx = topk_indices(scores, k_top)
    9. # Stage 3: perform exact attention only on selected keys
    10. selected_k = keys[idx]
    11. selected_v = values[idx]
    12. return softmax_attention(q, selected_k, selected_v)

    The key points of this flow are that scoring happens in a smaller space, and exact computation covers only a small number of tokens. Real systems also need to consider batching, multi-head shared indexing, memory layout, and hardware parallelism.

    7. Engineering Deployment Considerations

    7.1 Define Evaluation Metrics First

    Long-context optimization can easily produce “faster speed, lower quality.” Before deployment, monitor the following metrics together:

    • Time to first token (TTFT): reflects prefill-phase efficiency.
    • Decode throughput (tokens/s): reflects sustained generation capability under long context.
    • Task accuracy: includes retrieval tasks, such as locating information in long documents, and reasoning tasks, such as summarizing across paragraphs.
    • Memory usage: includes both KV cache and index cache.

    7.2 Validate by Length Segment

    Bottlenecks differ across length ranges. Test separately at multiple levels such as 32k, 128k, 1M, and 10M, and observe the time ratio between indexing and exact attention. If the indexing share rises sharply in a certain range, it usually indicates that candidate scanning scale has become the dominant factor.

    7.3 Watch for Accumulation of Indexing Errors

    Once an incorrectly selected key is missed by indexing, later layers cannot recover it. Validation should cover scenarios such as critical information located in the middle of a document, long-distance spans, and multi-hop reasoning, rather than only looking at average scores.

    7.4 Keep a Fallback Path

    In online services, a full-attention path can be retained for shorter requests or requests with extremely high accuracy requirements, while the sparse path is enabled only for very long requests. This on-demand switching approach controls risk and makes gradual rollout easier.

    8. Summary and Next Steps

    Sparse attention solves the problem of “looking at only a subset,” but the 10M-token scenario exposes the cost of “finding that subset.” Moving indexing from full scanning to latent-space scoring and hierarchical retrieval is a relatively clear direction of evolution.

    In engineering practice, first use complexity estimates to confirm the bottleneck, then use measured data across length segments to choose an approach. Theoretical speedup ratios need to be validated on the target hardware and real tasks before they can translate into reliable gains.