The Key to 22x Faster Sparse Attention at 10 Million Token Contexts

    As context windows grow from millions to tens of millions of tokens, sparse attention shifts the bottleneck from computing attention to finding which tokens to attend to. This article breaks down why the indexer becomes the dominant cost, how latent-space sparse attention moves selection into a low-dimensional space with two-stage retrieval, where the 22x prefill speedup comes from, how accuracy is preserved, and what to consider when applying it in production.

    1. Background: As Contexts Scale from Millions to Tens of Millions, the Bottleneck Shifts

    Over the past two years, long context has quickly become a standard capability in large model serving. Million-token contexts have moved from an optional feature to a default specification, and the exploration of ten-million-token contexts has already appeared on the research horizon. One of the key technologies supporting this trend is sparse attention: instead of having every query vector scan all historical tokens, each query selects only a few of the most relevant tokens to participate in the computation.

    At the million-token scale, this approach has been repeatedly validated. It preserves accuracy while compressing the quadratic cost of attention into an acceptable range. But as contexts push toward ten million tokens, an overhead that once seemed negligible starts to spiral out of control.

    Take a class of models that use a hybrid architecture of global attention layers plus sparse selection. When running the prefill stage at ten million tokens, more than ninety percent of the time is spent not on the matrix operations of attention itself, but on the indexer that decides which tokens to look at. In other words, the real cost center has shifted from computing attention to finding attention.

    The nature of the problem has therefore changed. Sparse attention has long proven that attending to only a small subset is enough to preserve accuracy. What actually blocks ultra-long contexts is that the process of finding that small subset still grows quadratically with context length.

    2. Breaking Down the Bottleneck: Why the Indexer Dominates Cost

    To understand this shift, it helps to split a single sparse attention call into two stages.

    The first stage is the selection stage, also called the indexing stage. The model must compute the relevance strength between each query position and all historical positions, then pick the Top-K positions. In a naive implementation, this requires scoring all candidates, with complexity that scales with the square of the sequence length.

    The second stage is the aggregation stage, which is the actual attention computation. Because only K positions are retained, this step is linear, and K is usually far smaller than the sequence length.

    At one million tokens, the ratio of K to sequence length is still acceptable, and the two stages take comparable time. At ten million tokens, however, the quadratic term in the first stage expands rapidly while the second stage barely changes, so the indexer consumes the vast majority of the time. This explains a seemingly contradictory phenomenon: even though sparsification reduces the amount of computation, the end-to-end speedup is not proportional.

    Looking closer, the cost of the indexing stage consists of three parts:

    • Scoring: computing relevance for each query against each candidate, typically a dot product or a lightweight MLP;
    • Sorting/filtering: extracting Top-K from a massive pool of scores, involving partial sorting or approximate retrieval;
    • Memory access: gathering the key-value tensors of the selected K positions from GPU memory into a contiguous buffer, a step that is clearly bandwidth-bound at long sequence lengths.

    Together, these three make selection itself an engineering burden on the same order of magnitude as full attention.

    3. Core Idea: Moving Selection into Latent Space

    In response to this bottleneck, a class of new methods offers an answer: do not perform selection in the original token space. Instead, first compress the query and history into a low-dimensional latent space, complete scoring and filtering in that latent space, then map back to the original space to fetch the keys and values.

    These methods are usually referred to as latent-space sparse attention. Their key design can be summarized in four points.

    First, low-dimensional projection. Learnable projection matrices are introduced for queries and keys, reducing the dimension from thousands to hundreds or lower. Because scoring depends only on low-dimensional inner products, the number of multiply-accumulate operations in the scoring stage drops by one to two orders of magnitude.

    Second, shared bases and clustering structure. Historical keys are clustered in the latent space or organized into shared bases, so a query only needs to compare against a small number of cluster centers to locate candidate regions, turning a scan over all candidates into a scan over a few representatives.

    Third, two-stage retrieval. A low-dimensional approximate score first coarsely filters a candidate set, then the original dimension is used to score candidates precisely, balancing speed and selection quality.

    Fourth, complementarity with linear attention. Global layers use latent-space sparse selection to guarantee long-range dependencies, while local layers use linear attention to guarantee local smoothness. Mixing the two achieves a balance between accuracy and throughput.

    Expressed as illustrative pseudocode, the structure looks roughly like this:

    1. # Conceptual illustration, not a concrete interface
    2. q_low = proj_q(q) # reduce to low dimension
    3. k_low = proj_k(k) # reduce historical keys to low dimension
    4. scores = q_low @ k_low.T # low-dimensional scoring, cost drops sharply
    5. idx = topk(scores, K) # select candidate positions
    6. kv_sel = gather(kv, idx) # do exact attention only on candidates
    7. out = softmax(q @ kv_sel.T) @ kv_sel

    It is worth emphasizing that the code above only illustrates the data flow. An actual implementation involves engineering details such as chunking, quantization, and cache reuse.

    4. Sources of the Gains: A Double Drop in Complexity and Constant Factors

    The speedup of this kind of solution does not come from a single trick, but from improvements at two levels simultaneously.

    In terms of asymptotic complexity, if the original indexing stage is on the order of the square of the sequence length, latent-space scoring reduces it to sequence length multiplied by the low dimension, which at ten million tokens amounts to replacing a quadratic term with a linear one.

    In terms of constant factors, low-dimensional inner products are friendlier to GPU memory bandwidth, the candidate pool for Top-K filtering is smaller, memory access is more contiguous, and cache hit rates are higher. Only when the two are combined does the prefill stage of a single attention layer achieve a speedup on the order of tens of times.

    From an engineering perspective, this means the cost structure of long-context inference is rewritten: the part that originally expanded with the square of the length is flattened, and end-to-end throughput is no longer locked by the indexer.

    5. Why Accuracy Holds Up

    A natural question is whether low-dimensional scoring might select the wrong positions and thus hurt accuracy. In practice, three safeguards usually address this.

    First, two-stage retrieval. The coarse filtering stage relaxes the number of candidates, and the precise stage rechecks with the original dimension, reducing the probability of missed selections.

    Second, training adaptation. During pre-training or post-training, the model is adapted to the latent-space selection distribution, aligning the projection matrices with the attention distribution.

    Third, a hybrid architecture. Local linear attention handles high-frequency local dependencies, while global sparse layers are responsible only for a small number of critical long-range jumps, spreading the overall error thin.

    In publicly described results, this class of methods achieves more than a twentyfold speedup for the prefill of a single global attention layer at ten million tokens, with even higher speedups for another model architecture, while maintaining accuracy close to the original model across multiple tasks. This shows that selection and computation can be optimized separately without sacrificing expressive power.

    6. Key Points for Engineering Implementation

    To practice similar ideas in your own system, it is worth focusing on the following areas.

    1. Layered design: clarify which layers are global sparse layers and which are local linear layers, avoiding the stacked selection overhead that comes from making every layer sparse.
    2. Chunking and streaming: split long sequences into chunks, and build and reuse latent-space indexes per chunk to lower the cost of a single selection.
    3. Caching strategy: persist a cache of the low-dimensional representations of historical keys to avoid repeated projection.
    4. Monitoring and observability: use general-purpose logging and monitoring/alerting capabilities to separately observe the time share of the indexing stage and the aggregation stage, and locate the real bottleneck.
    5. Elastic resources: scale inference replicas on demand on a container platform, and route long-context tasks and short-context tasks separately to improve overall utilization.
    6. Accuracy regression: build a long-context evaluation set and continuously track miss rates and task metrics to prevent optimization from introducing hidden regressions.

    7. Applicability and Caveats

    Latent-space sparse attention is not universally applicable. It is better suited to scenarios that are prefill-intensive, have extremely long contexts, and are not extremely sensitive to first-token latency, such as long-document understanding, code-base-level retrieval, and long-session memory. For short contexts or latency-sensitive online interactions, the extra projection and index construction may not pay off.

    In addition, low-dimensional projection loses some discriminative power. For tasks that require fine-grained distinction between highly similar tokens, the number of candidates should be increased appropriately or a higher dimension retained. On the engineering side, the combined impact of numerical stability and quantization error also deserves attention.

    8. Conclusion

    The core tension of ten-million-token contexts has shifted from being unable to compute to being unable to find. Moving the selection process into latent space, replacing full scans with low-dimensional scoring plus two-stage retrieval, is currently the most representative optimization path. What it brings is not just a single-point speedup, but a reshaping of the cost structure of long-context inference. For developers, understanding this paradigm is more valuable than memorizing any specific number.