How to Further Speed Up Attention for Ten-Million-Token Contexts

    This article explains why the token indexer, rather than the attention computation itself, becomes the bottleneck at ten-million-token context lengths. It introduces latent-space sparse attention, which replaces per-token scoring with coarse routing over compressed clusters, followed by exact reranking within the candidates. The article covers complexity, recall-focused accuracy safeguards, engineering considerations for indexing, KV caching, and load balancing, and evaluation metrics for long-context performance.

    1. A Shift in the Problem: From Expensive Attention to Expensive Indexing

    The first instinct for very long contexts is usually to compress the attention computation. With full attention at context length T, the prefill stage requires every query to compute relevance against all historical keys, so the cost grows with T². During decoding, each generated token must access the entire historical KV cache, so the cost grows linearly with T. As contexts grow from the million-token scale to the ten-million-token scale, the quadratic term in prefill quickly becomes the dominant cost.

    Sparse attention divides the work as follows. A lightweight indexer first selects the k most relevant keys for each query, and the actual attention is then computed only over those k keys. This reduces the main attention cost to O(Tk), which appears to bypass quadratic complexity. However, there is a hidden cost that is easy to overlook. The indexer still has to decide which keys are relevant, so it must score a large number of keys first. Even if the indexer uses low dimensions and low precision, or merges multiple keys into blocks, the indexing stage keeps a T² asymptotic form as long as it scans all keys for each query.

    At the million-token scale, this cost can still be masked by the constant-factor advantages of low-dimensional projection and block sparsity. At the ten-million-token scale, those constant factors no longer offset the growth. In the global attention layers of some long-context hybrid architectures, more than 90% of prefill time may not go to the main attention computation. It may instead go to indexing and routing, which decide which tokens to look at. The nature of the problem has therefore changed. Sparse attention has already shown that attending to a small subset can preserve accuracy. What now limits very long contexts is that finding that small subset is still too slow.

    2. Core Idea: Replacing Per-Token Scoring with Latent-Space Routing

    The key to latent-space sparse attention is not to keep optimizing how quickly each key is scored. It is to change the granularity of indexing. Instead of scanning query-key relevance across every raw token, the method performs coarse routing in a compressed latent space, then performs precise reranking within a small number of candidate regions.

    The approach works as a three-stage pipeline:

    1. Latent-space construction: Apply low-dimensional projection, block clustering, or hierarchical indexing to the keys to form several candidate regions. The index structure can be updated incrementally, which avoids a full rebuild during every prefill.
    2. Query routing: Each query compares itself only with a small number of cluster centroids or routing nodes in the latent space, and selects several candidate clusters. Routing can be multi-level, which further reduces the cost of checking all clusters.
    3. Exact reranking and attention within candidates: Compute precise relevance scores over the keys covered by the candidate clusters, select the top-k, and then run standard attention.

    This design changes the cost structure from “each query scores each key” to “each query scores a small number of routing nodes, then reranks the candidate keys.” With a fixed number of candidate clusters, a fixed probe count, and a fixed top-k in the engineering configuration, the indexing stage can shift from quadratic growth to approximately linear growth. Even when the number of clusters grows with scale, multi-level routing can keep the growth below quadratic.

    Pseudocode for the approach:

    1. def latent_sparse_prefill(Q, K, V, index, top_k, probes):
    2. # index is maintained by low-dimensional projection, clustering, or a hierarchical routing structure
    3. # 1. Perform coarse routing in latent space to obtain a small set of candidate regions
    4. candidate_regions = index.route(Q, probes=probes)
    5. # 2. Compute exact scores only within candidate regions to avoid a full query-key scan
    6. candidate_keys = index.gather(K, candidate_regions)
    7. scores = exact_score(Q, candidate_keys)
    8. # 3. Select top-k, then perform the actual attention
    9. topk_idx = select_topk(scores, top_k)
    10. return softmax_attention(Q, gather(K, topk_idx), gather(V, topk_idx))

    Latent-space routing is not free compression. It trades a small recall risk for scale advantages in the indexing stage, so engineering work must center on recall. Whether candidate regions cover the true top-k, whether routing stays stable, whether cluster updates cause drift, and whether layers or heads should share an index all affect final accuracy.

    3. Complexity and Benefits: Moving the Quadratic Term Off the Main Path

    Full-attention prefill cost can be roughly expressed as O(T²d). The main sparse attention cost is O(Tkd). A traditional indexer, however, may still include per-token scoring at O(T²d_i). Latent-space sparse attention splits the main path into the following parts:

    • Index maintenance: about O(T·C·d_c), or O(T log C) with hierarchical routing, where C is the number of routing nodes or clusters;
    • Query routing: O(T·r·C_r), where r is the number of probes and C_r is the number of routing nodes per level;
    • Candidate reranking: O(T·m·d), where m is the number of candidate keys;
    • Main attention: O(T·k·d).

    When C, r, m, and k grow slowly relative to T, the total cost grows approximately linearly with T and is no longer dominated by the T² term. The benefit is most visible at the ten-million-token scale. Traditional approaches slow down because the number of query-key pairs explodes, even when the indexer dimension is very low. Latent-space routing compresses most comparisons to the cluster level and limits precise comparisons to a small number of candidates.

    Complexity analysis, however, should not rely only on asymptotic notation. Constants and hardware behavior matter too. The block size in the routing structure, the memory contiguity of candidate regions, the batching efficiency of the reranking stage, and the paging layout of the KV cache all affect real throughput. A theoretically superior index can lose its advantage if it causes random memory access or uneven load. For this reason, latent-space sparse attention must be co-designed with block sparsity, paged KV caches, fused operators, and other engineering techniques.

    4. Accuracy Assurance: Routing Recall Matters More Than Scoring Precision

    The accuracy of sparse attention depends on a premise: the model needs only a small number of key tokens. Existing long-context experiments show that, on some tasks, retaining less than 1% of the key tokens can approach full-attention accuracy. Whether this premise holds depends on whether the indexer places the truly important keys into the candidate set. The risk of latent-space routing is that once the true top-k falls outside the candidate regions, even a precise reranking stage cannot recover it.

    Accuracy assurance should therefore focus on recall:

    • Multi-probe routing: Each query selects multiple adjacent or complementary candidates instead of a single cluster, which lowers the probability of missed recall.
    • Hierarchical indexing: Coarse routing comes first, then fine routing. This prevents oversized single-level clusters from turning candidate reranking into a near-full scan.
    • Joint optimization of routing and main attention: Align the indexing objective with the final attention distribution, rather than relying only on an independent clustering objective.
    • Protection of critical tokens: Guarantee candidate slots for high-salience tokens, recent tokens, and structural markers.
    • Layered monitoring: During offline evaluation, track candidate-set recall, top-k overlap, and end-to-end task accuracy, not just average latency.

    The method suits some tasks better than others. Retrieval-intensive tasks, long-range code dependencies, multi-hop reasoning, and precise citation tasks are more sensitive to the recall of critical tokens. Summarization and topic clustering tolerate the loss of a few key tokens better. Latent-space sparse attention is not unconditionally equivalent to full attention on every task. It trades controllable recall risk for the ability to run very long contexts.

    5. Engineering Implementation: Coordinating Indexing, Caching, and Batching

    Implementing latent-space sparse attention requires attention to four areas:

    1. Index construction and updates: During prefill, cluster centroids can be built in batches. During decoding, they should be maintained incrementally. Avoid rebuilding the global index for every incoming token, and control cluster drift.
    2. Candidate set management: Set an upper bound on candidate regions so that candidate sets do not grow without limit in long contexts. Also handle the batching fragmentation caused by inconsistent candidate sets across queries.
    3. KV cache layout: Candidate keys are often non-contiguous, so paged caches or block-level indexes help reduce random memory access. Fuse the reranking and attention operators where possible to avoid writing intermediate results to memory repeatedly.
    4. Load balancing: Routing can create hot clusters. Possible measures include cluster size constraints, adaptive probe counts, and request-level scheduling, which keep a few clusters from becoming throughput bottlenecks.

    A practical set of principles follows. First guarantee candidate recall, then optimize candidate size. First perform block-level routing, then token-level reranking. First validate accuracy on small long-context workloads, then scale to ten million tokens. Do not sacrifice observability in pursuit of a theoretical speedup. Per-stage timing of the indexing phase, candidate coverage, and reranking hit rate should all be monitored.

    6. Evaluation: Measuring Speed, Accuracy, and Stability Together

    Evaluating such a method should cover at least three categories of metrics:

    • Efficiency: prefill latency, decoding throughput, the share of time spent in indexing for each layer, memory usage, and KV cache hit rate;
    • Accuracy: scores on