Scaling to Tens of Millions of Tokens: The Indexing Bottleneck in Sparse Attention

    Sparse attention can reduce the cost of processing extremely long contexts, but only when relevant positions can be found efficiently. This article examines why candidate indexing may become the dominant bottleneck, how compact representations and hierarchical retrieval can reduce search overhead, how to interpret reported speedups, and how to evaluate quality, memory usage, irregular access, and end-to-end performance.

    1. From Millions to Tens of Millions of Tokens: The Problem Is Not Only How Much to Read, but How to Find It

    The value of long-context models lies in their ability to process more complete information at once, including large code repositories, long-running business records, technical documents spanning multiple chapters, and accumulated task history. However, supporting longer inputs does not mean that the information can be understood at low cost.

    Traditional full attention requires each query to match against a large number of historical keys. For a sequence of length (N), with query and key dimension (d), the attention-matching cost is generally expressed as (O(N^2d)). Causal masking reduces the number of positions that actually participate in computation, but it does not change the overall quadratic growth rate.

    Sparse attention takes a different approach: each query attends only to a small set of candidate positions. If the number of candidates is (k), and (k) is much smaller than (N), the attention computation after candidate selection can be reduced to approximately (O(Nkd)).

    This reduction depends on one important assumption: the candidate positions must be found efficiently.

    If selecting (k) positions still requires every query to scan all historical keys, the attention operation may be sparse while the candidate-discovery process retains a potentially quadratic cost. At sufficiently long context lengths, candidate discovery can become more expensive than the attention computation itself.

    The central challenge in optimizing contexts with tens of millions of tokens is therefore shifting from “How can we compute less attention?” to “How can we avoid performing an expensive full search merely to compute less attention?”

    2. Why the Indexer Can Become the New Performance Limit

    An indexer is the candidate-filtering component that runs before attention. It estimates the relevance between a query and historical information, then determines which tokens should enter the more expensive attention computation.

    The indexer does not necessarily use a conventional database index. In some designs, it is essentially a low-cost scoring module. It uses lower-dimensional representations to calculate relevance between a query and many historical positions, then selects the highest-ranked candidates.

    This design can reduce the cost of each individual match, but it does not necessarily reduce the number of matches.

    Assume that the index representation has dimension (d_i), while the final attention dimension is (d), with (d_i < d). If the indexing stage still performs a full comparison, its main costs are approximately:

    • Indexing cost: (O(N^2d_i))
    • Attention cost after candidate selection: (O(Nkd))

    When (k) remains relatively fixed while (N) continues to grow, the gap between indexing cost and sparse-attention cost becomes increasingly significant. Reducing the representation dimension lowers the constant factor, but it does not automatically remove quadratic growth.

    Real-world overhead also includes candidate sorting, indirect address reads, intermediate-result writes, and device synchronization. These operations may not require much arithmetic, but they can be constrained by memory bandwidth, access locality, and scheduling efficiency.

    For this reason, theoretical operation counts alone can significantly underestimate the actual cost of candidate filtering.

    3. How to Interpret “More Than 20x” Speedups

    The source material describes a specific result: in a particular prefill test involving tens of millions of tokens, the indexer accounted for approximately 98% of the runtime of one attention layer. Optimizing this bottleneck produced more than a 20x layer-level speedup under a specific configuration.

    These figures are useful reference points, but they should not be interpreted as a 20x end-to-end model speedup. Nor do they imply that all long-context workloads will achieve similar gains. Because the full experimental conditions were not provided, the result should be treated as a measurement from a specific test rather than a general performance guarantee.

    Amdahl’s law provides a useful framework:

    [
    \text{Overall speedup} = \frac{1}{(1-p)+p/s}
    ]

    Here, (p) is the fraction of the original runtime spent in the optimized component, and (s) is the speedup achieved by that component.

    If a module consumes most of the runtime, optimizing it can indeed produce a substantial improvement. However, a complete model also includes projection layers, feed-forward networks, normalization, cross-device communication, and other attention layers. The value of (p) in a layer-level test cannot be directly used as the value of (p) for the entire model.

    Similarly, prefill speedup does not imply the same speedup during token-by-token generation. The two phases have different computational patterns and must be measured separately.

    4. The Core of Latent-Space Filtering: Compress Representations and Reduce the Search Space

    A general latent-space filtering strategy first searches for potentially relevant candidates in a compact representation, then applies more detailed attention to those candidates.

    However, the name of a method alone does not reveal its exact network architecture, training procedure, or retrieval implementation. The following discussion describes general technical paths for understanding this class of optimization, rather than reproducing the implementation details of any particular study.

    4.1 Use Compact Representations for Coarse Filtering

    Original key vectors may contain extensive information, but coarse filtering does not necessarily require all of it. A lower-dimensional retrieval representation can be constructed so that the filtering module first identifies positions worth examining in greater detail.

    The objective is different from that of the final representation: a retrieval representation does not need to reconstruct the full original semantics. It must, however, preserve the distinctions that matter for candidate selection.

    Excessive dimensionality reduction can cause different types of information to map to similar regions, eliminating fine-grained distinctions. A variable name in code, an identifier in a log, or an exception clause in a contract may be overlooked if the representation is too coarse.

    4.2 Reduce Full Comparisons Through Hierarchical Filtering

    A more valuable improvement is to prevent each query from visiting every historical position individually.

    One general design organizes historical tokens into blocks and maintains a compact representation for each block. A query first selects a small number of relevant blocks, then searches for token-level candidates within those blocks.

    The process can be summarized as:

    Historical tokens → block-level summaries → block-level coarse filtering → within-block fine filtering → sparse attention

    If there are (B) blocks, each query selects (r) blocks, and each block contains (m) tokens, the filtering cost may depend on (B) and (rm), rather than directly scanning all (N) tokens.

    This does not automatically make the overall complexity linear. If the number of blocks grows with (N), and every query still scans all blocks, the coarse-filtering stage may retain a high growth rate. Complexity must be analyzed across the entire computation path, not only at the final stage.

    4.3 Combine Candidate Types to Cover Different Dependencies

    Relying entirely on semantic retrieval can miss information that lacks obvious semantic features but remains critical to the task. In practice, multiple candidate types can be combined:

    • Local candidates: Preserve nearby tokens to maintain continuity and local structure.
    • Global candidates: Retain task instructions, section boundaries, and other important positions.
    • Retrieval candidates: Dynamically locate relevant information at distant positions.
    • Fallback candidates: Expand coverage when the filtering decision is uncertain.

    Before entering the attention computation, these candidates must be merged, deduplicated, and subjected to causal masking. A larger candidate budget generally improves coverage, but it also increases computation and cache-read costs.

    5. Accuracy Evaluation Must Go Beyond “The Answer Is Roughly the Same”

    Sparse filtering introduces an important risk: information that is not included in the candidate set is usually unavailable to subsequent attention computation.

    Evaluation should therefore examine not only average task scores, but also failure types and their distribution.

    5.1 Evaluate Single-Fact Retrieval Separately from Multi-Evidence Reasoning

    Finding one explicit fact is a different problem from integrating evidence distributed across multiple positions. A system may be effective at retrieving a single passage while failing to preserve several related conditions required for reasoning.

    Tests should cover cross-section constraints, relationships among multiple entities, and conclusions that require joint evaluation of several pieces of evidence.

    5.2 Focus on Long-Tail Information and Exact Matching

    Rare words, identifiers, function signatures, and unusual contractual clauses may not be sufficiently prominent in a compressed representation.

    In addition to semantic question answering, evaluations should include exact-string localization, discrimination between similar identifiers, and detail-consistency checks. Otherwise, average scores may conceal high-risk omissions.

    5.3 Vary the Position of Critical Information

    The same evidence should be placed at the beginning, middle, and end of the context, with similar but irrelevant distractors added. This can reveal positional preferences and show whether candidate filtering is attracted to repeated or redundant information.

    5.4 Prevent Future-Information Leakage

    For causal models, a query may use only information at or before its current position. If a block summary or index representation is generated from an entire block, it is necessary to verify that information from future positions is not exposed to the current query.

    Otherwise, offline evaluations may show an artificial quality improvement that cannot be achieved during causal inference.

    6. Four Engineering Costs Beyond the Algorithm

    6.1 Index Construction and Update Costs

    Indexes are not free. The cost of representation generation, structure construction, incremental insertion, and state maintenance must all be measured.

    This is particularly important during token-by-token generation, when new information is continuously appended. If every append operation requires rebuilding a large portion of the structure, the savings achieved during prefill may be offset by maintenance costs later.

    6.2 GPU Memory and Cache Costs

    Reducing attention computation does not necessarily reduce key-value cache usage. Some designs still store the complete historical key and value states while reducing the number of positions accessed per query.

    Total memory usage should include at least model weights, the key-value cache, index representations, structural metadata, and temporary workspace. If additional representations are stored for retrieval, the index itself may become a capacity bottleneck.

    6.3 Irregular Memory Access

    The more widely scattered the candidate positions are, the less contiguous their reads are likely to be. After theoretical computation is reduced, the system may instead become limited by random access, data movement, and the scheduling of many small tasks.

    As a result, organizing candidates by block, batching reads, and reducing intermediate writes can be as important as the filtering algorithm itself.

    6.4 Multi-Device Communication

    When the context is distributed across multiple devices, candidate discovery and key-value reads may cross device boundaries. The gains from reduced local computation can be partially offset by candidate aggregation, remote reads, and synchronization.

    Evaluations must specify how data is partitioned and whether communication time is included in the reported results.

    7. How to Design a Credible Validation Plan

    Validation should proceed in three layers rather than relying on a single speedup number.

    The first layer is operator-level analysis. Measure index-representation generation, candidate scoring, candidate selection, key-value reads, and attention computation separately to identify the actual hotspots.

    The second layer is single-layer validation. Under the same precision, hardware, and candidate budget, compare runtime and memory usage across different context lengths. This helps determine whether the benefits continue to grow consistently as the context expands.

    The third layer is full-model testing. Record prefill latency, time to first output token, subsequent generation throughput, peak memory usage, and task quality. Tests should cover different concurrency levels and input-length distributions.

    Two additional principles should guide comparisons:

    1. Compare performance at equivalent quality. Apparent speedups should not be obtained by significantly degrading task quality.
    2. Compare costs under equivalent resources. If one approach uses more devices or a larger memory budget, that difference must be disclosed rather than reporting runtime alone.

    8. Conclusion: The Real Breakthrough Is Scalable Candidate Discovery

    Sparse attention demonstrates an important direction: a model may not need to inspect its entire history at every step. At the scale of tens of millions of tokens, however, “attend to only a few positions” is merely the outcome. The critical question is how to locate those positions at low cost.

    Latent-space representations, hierarchical filtering, and hybrid candidate strategies offer viable approaches for reducing candidate-discovery overhead. Still, a lower-dimensional representation does not necessarily mean lower complexity. A layer-level speedup does not equal an end-to-end speedup, and reducing attention computation does not automatically reduce memory or synchronization costs.

    For developers and enterprises, deciding whether a long-context technique is worth adopting ultimately comes down to three questions:

    • Does it reliably preserve the information required by the task?
    • Does it improve the real latency of complete requests?
    • Does it reduce resource cost at equivalent quality?

    Only when all three conditions are satisfied can a local algorithmic advantage become sustainable engineering value.