Sparse Attention at Tens of Millions of Tokens: Why Indexing Still Scales with N²

    Sparse attention reduces attention computation by letting each query attend to only a small set of historical tokens, but the indexing step that selects those tokens still tends to scan the full context. This article explains why indexing remains O(N²) at tens of millions of tokens, how Latent Sparse Attention (LSA) reduces per-match cost without changing the growth order, and which additional structures can lower that order. It also provides selection criteria, implementation steps, and evaluation and monitoring practices for deploying sparse attention at this scale.

    1. What Sparse Attention Solves—and What It Leaves Out

    Sparse attention lets each query compute attention only with a small number of historical tokens, reducing the cost of attention itself. At the million-token scale, the accuracy of this approach has already been validated.

    At the tens-of-millions-token scale, another part of the pipeline becomes expensive: the indexing process that decides which tokens to look at. Sparse attention saves computation, but it does not save search. Latent Sparse Attention (LSA) is an improvement aimed at the indexing stage. It addresses the cost of high-dimensional similarity search in indexing, but it does not address the order in which indexing grows with sequence length. The following sections explain why, then provide selection and deployment guidance.

    2. Why Indexing Grows Quickly with Context Length

    A typical sparse attention layer runs in two steps:

    1. Indexing: select a candidate subset from all historical tokens for each query.
    2. Computation: perform attention only on the candidate tokens.

    In mainstream implementations, the indexer usually computes relevance scores between the query and all historical tokens before it can pick the highest-scoring tokens. Therefore, even if only a few tokens are retained in the end, scoring still covers the entire context.

    The cost is clearer with notation. Let the sequence length be N, the original head dimension be D, the dimension used for indexing scores be d, and the number of tokens retained per query be k. If the prefill phase scores every query against all tokens, the scoring cost is O(N²·d). Selecting top-k for each row also requires scanning N scores, which likewise grows with N².

    At the million-token scale, this overhead is often acceptable. At the tens-of-millions scale, the growth from N² can become the main bottleneck before other costs do. The original analysis suggests that under some global attention configurations, indexing accounts for most of prefill time. However, that figure does not specify model size, batch size, hardware environment, or whether KV Cache writes are included. You should measure it in your own environment.

    3. The LSA Approach: Search in a Low-Dimensional Space First

    The core assumption of LSA is that indexing only needs to find relevant tokens; it does not need to perform exact scoring in the high-dimensional representation. LSA has two components.

    • Lightweight latent representation: generate a d-dimensional latent vector for each token, where d is much smaller than D. This vector is produced by a lightweight projection and can be reused after generation, without being recomputed for every query.
    • Two-level filtering: first use the latent vectors to coarsely screen all tokens and obtain m candidates (m is usually much larger than k); then return to the original representation space to finely rank those m candidates and select the final k tokens for attention computation.

    With this structure, the cost of each stage is as follows. Coarse screening is O(N²·d), because each query still scans all tokens. Fine ranking processes only the m candidates per query, at a cost of O(N·m·D). The final attention is O(N·k·D).

    To be clear, coarse screening reduces the cost of a single match from D to d, which changes only the constant factor. As long as coarse screening remains a full scan, the growth order of total cost remains N². LSA can therefore significantly reduce absolute latency, but it cannot eliminate quadratic growth on its own.

    Lowering the growth order requires additional structure. Three common approaches are:

    • Blocking: compute summary scores for each block first, then search in detail only within selected blocks. The scale of block-level scoring can drop from N to N/b, where b is the block size.
    • Clustering or approximate nearest-neighbor retrieval: restrict the search scope to a small number of clusters or neighbors, which can usually make the cost of a single search much lower than N.
    • Hierarchical indexing: use a multi-level structure to narrow the candidate range layer by layer.

    These methods introduce approximation error and engineering complexity. Their benefits depend on data distribution and implementation quality, and conclusions from other scenarios cannot be applied directly.

    4. Choosing Sparse Attention at Tens of Millions of Tokens

    The table below compares four types of approaches. “Indexing complexity” refers to the prefill phase, where N is the sequence length.

    Approach Indexing complexity Extra memory Main recall risk Migration cost
    Dense attention No indexing; computation is O(N²·D) KV Cache only None None
    Block sparse (block-level scoring to select blocks) Block-level scoring is about O(N²·d/b), still growing with N² One summary vector per block, small footprint If the block containing an important token receives a low score, the whole block is missed Low to medium
    LSA-style two-level indexing Coarse screening O(N²·d), fine ranking O(N·m·D), still growing with N² One d-dimensional latent vector per token Coarse screening misses relevant tokens; candidate set m is insufficient Medium; requires projection parameters and accuracy validation
    Hierarchical or approximate indexing Depends on implementation; can be below N² The index structure itself occupies memory Approximation error compounds High

    Use the following order when selecting an approach. If the indexing share is low, dense attention or block sparse attention is already sufficient, and LSA is unnecessary. If the indexing share is high and the per-match cost is the main issue, LSA’s low-dimensional coarse screening is effective. If N² growth itself is no longer acceptable, blocking or approximate retrieval must be added on top of LSA.

    5. Implementation Steps

    1. Profile at fine granularity. Measure the time spent on indexing, attention computation, and KV Cache writes separately, and calculate each part’s share of prefill. When the indexing share is low, the benefit of LSA is limited.
    2. Define recall. Use the top-k of full attention scores as ground truth, and calculate the proportion of ground truth covered by the candidates selected by indexing. Use this metric when tuning d, m, and k.
    3. Determine the latent dimension d. In general, a smaller d makes coarse screening faster but lowers recall. Sweep several values under the target accuracy and choose the smallest d that meets the requirement.
    4. Set the ratio of m to k. A larger m makes recall more stable but increases fine-ranking cost. Balance the latency budget and recall target together.
    5. Plan memory. Each token’s latent vector occupies d elements and must be included in the memory budget. Allocate and release latent vectors in sync with the KV Cache, and use paged management to reduce fragmentation.

    6. Evaluation and Monitoring

    Offline evaluation should cover edge cases, not only common long-text benchmarks. The typical failure mode is missed detection: key evidence does not enter the candidate set. Add the following tests:

    • Multi-hop retrieval, where the model must combine information from multiple dispersed positions to answer.
    • Needle-in-a-haystack tests that place the target information at the beginning, middle, and end of the document.
    • Long documents with low target-information density, to observe whether recall changes with position.

    Online serving should continuously monitor the following metrics:

    • P50, P95, and P99 prefill latency.
    • Indexing time as a proportion of total prefill time.
    • Candidate recall, i.e., the overlap ratio with the full top-k.
    • Needle-in-a-haystack success rate or online evidence hit rate.
    • Peak memory and fragmentation rate of the paged cache.
    • The actual number of candidates m and retained tokens k used per request.

    7. Conclusion

    The accuracy assumptions of sparse attention already hold at the million-token scale. At the tens-of-millions scale, the challenge shifts to indexing. LSA uses a low-dimensional latent space to reduce the cost of a single match, but full coarse screening still grows with N². Changing the growth order requires combining it with blocking or approximate retrieval. When selecting an approach, first measure indexing’s share of prefill, then use recall to determine d, m, and k. Only then can you judge whether this approach is worth the investment.