Ten-Million-Token Contexts: How Sparse Attention Can Break the Indexing Bottleneck

    Long-context models still face a hidden indexing bottleneck: sparse attention reduces how many keys each query attends to, but it may still require scanning all history first. This article breaks down the cost structure of dynamic sparse attention, examines latent-space retrieval and hierarchical routing, and outlines the conditions, accuracy risks, measurement caveats, and deployment checks needed to make ten-million-token inference practical.

    1. Why “Looking at Less” Is Not Enough as Context Grows

    The value of ultra-long-context models lies in processing large code repositories, long documents, and cross-period business records at once, reducing the cost of manually splitting materials and stitching together multiple rounds. But a larger context window does not mean the model can complete inference within acceptable time and cost.

    In standard full attention, every query vector must compute relevance against key vectors within the visible range. Let input length be T and attention head dimension be d. The attention computation in the prefill stage is typically O(T²d). A causal mask limits visible positions to history, but it does not change the quadratic growth trend.

    When input length grows from one million tokens to ten million tokens, with other conditions unchanged, the computation involving all queries and historical keys approaches roughly 100 times the original scale. Even with heavily optimized low-level computation, this growth can make latency, memory, and resource costs unacceptable.

    Sparse attention tries to change this: each query focuses only on a small number of important positions instead of traversing all history.

    However, the real difficulty then appears:

    If all history must be scanned first to know which positions are worth attending to, then sparsification only reduces the latter part of the computation; it does not eliminate the quadratic growth in the earlier part.

    Therefore, when discussing ten-million-token inference, it is not enough to ask “how many keys does each query finally attend to?” We also need to ask “how are those keys found?”

    2. Breaking Down the Cost of Sparse Attention

    A typical dynamic sparse attention pipeline can be divided into four steps:

    1. Generate retrieval representations for queries and historical keys.
    2. Find candidate positions that may be relevant for each query.
    3. Filter important positions within a fixed budget from the candidates.
    4. Perform attention computation on selected positions and aggregate the corresponding value vectors.

    If each query finally selects k keys, the computation in the last step can be reduced to O(Tkd). When k is much smaller than T, this part is indeed significantly lower than full attention.

    But if the retriever still needs to traverse T keys for each query, and the retrieval representation dimension is r, the retrieval cost can still reach O(T²r).

    In this case, the main prefill cost can be roughly expressed as:

    Total cost ≈ representation construction cost + full retrieval cost + candidate selection cost + sparse attention cost.

    Lowering the retrieval representation dimension, using lower precision, or merging multiple adjacent positions into one retrieval unit can reduce constant overhead. But as long as queries and retrieval units are still paired exhaustively, quadratic growth is not automatically eliminated.

    This distinction is important for engineering decisions:

    • Reducing constants mainly improves runtime efficiency at an existing scale.
    • Changing the growth order is what creates the possibility of keeping longer contexts scalable.
    • Reducing the amount of data actually accessed determines whether theoretical advantages translate into hardware gains.

    The three are related, but they cannot substitute for one another.

    3. Latent-Space Retrieval: Narrow the Search First, Then Judge Fine-Grained

    For the indexing bottleneck, one feasible approach is to route in a more compact representation space: instead of letting every query directly access all historical keys, first find a small number of relevant regions, then select specific positions within those regions.

    Here, “latent space” can be understood as an internal representation space built for the retrieval task. It does not necessarily preserve all details of the original attention vectors; instead, it tries to preserve the information needed for deciding “which queries should access which historical positions.”

    It is important to emphasize that mapping vectors into a low-dimensional space does not by itself produce sub-quadratic complexity. Only by further limiting the search range and avoiding one-by-one comparison between all queries and all keys is it possible to truly change the cost structure.

    The following is a generic design framework used to explain the core logic of this type of optimization. It does not represent the complete structure of any specific implementation.

    1. Build Retrieval Representations for Historical Information

    The system first generates representations for historical keys that are better suited to retrieval, and organizes them by time blocks, semantic regions, or learned groups.

    Each region can maintain one or more representative vectors. Queries first match against these representative vectors instead of directly matching all keys within the region.

    This stage must solve two problems: representation generation itself cannot be too expensive, and the compressed representation cannot lose critical relevance information.

    For example, if only a very small number of positions in a region are relevant to the current query, simple averaging may dilute those signals. Therefore, how region summaries are constructed directly affects the recall capability of subsequent retrieval.

    2. Select Candidate Regions Through Coarse-Grained Routing

    A query uses its own retrieval representation to select a small number of potentially relevant regions.

    If there are M regions in total, each query selects b regions, and b is much smaller than M, then subsequent fine-grained search can be limited to a local range.

    But this step still has hidden costs: if M grows linearly with context length and every query scans all M regions, the overall complexity may still contain a quadratic term. To further reduce cost, hierarchical routing or other approximate retrieval structures can be considered.

    The benefits of these structures depend on data distribution, access patterns, and implementation. One cannot assume a certain complexity guarantee simply because “an index is used.”

    3. Fine-Rank Within Candidates

    Coarse-grained routing narrows the range, while fine ranking improves selection quality.

    Suppose each query obtains C candidate positions and then selects k positions from them. The cost of candidate scoring can be approximated as O(TCr). When C is significantly smaller than T, this has an advantage over full scoring.

    However, candidate quality has an unavoidable upper bound:

    If a critical position does not enter the candidate set, no amount of subsequent fine-ranking accuracy can bring it back.

    Therefore, candidate recall is often more worth validating first than final ranking. In engineering practice, it is often necessary to balance speed and recall by increasing the number of routing regions or setting additional candidate budgets for edge cases.

    4. Complete Final Attention with Higher Fidelity

    The task of the retrieval space is to determine access positions, not necessarily to replace the representations used in final attention.

    A common design is to use compact representations for routing, then perform attention computation on the selected original keys and values. This mainly confines approximation error to the “which positions to select” stage.

    Final accuracy still depends on candidate coverage, sparse budget, and whether the model is adapted to this access pattern.

    4. What Conditions Are Needed to Reduce Complexity

    To illustrate the cost structure, define:

    • T: number of input tokens;
    • r: retrieval representation dimension;
    • C: number of candidates entering fine ranking for each query;
    • k: number of positions finally participating in attention;
    • d: attention head dimension.

    After omitting some constants and auxiliary operations, the total cost can be illustrated as:

    Total cost ≈ index construction cost + routing cost + O(TCr) + O(Tkd).

    For this structure to grow more gently with context, at least the following conditions must be met.

    First, index construction cannot hide a complete full pairwise comparison.

    Second, routing cannot rescan all historical positions in another form.

    Third, the growth rates of C and k must be controlled. If candidate count has to grow proportionally with T to maintain accuracy, theoretical gains will shrink significantly.

    Fourth, region load should be as balanced as possible. If a large number of keys are concentrated in a few popular regions, some queries may still degrade into large-range scans.

    Fifth, data organization and hardware access patterns must work together. When candidate positions are too scattered, computation may decrease, but data reads may become the new bottleneck.

    Therefore, evaluating an ultra-long-context solution requires more than checking whether a formula contains a quadratic term. It also requires observing average latency, tail latency, and degradation behavior under real workloads.

    5. Preserving Accuracy Requires More Than “Attention Is Naturally Sparse”

    Attention distributions on many inputs are indeed concentrated, but this does not mean all tasks can be handled with the same sparse budget.

    Different tasks have clearly different requirements for historical access:

    • Exact fact retrieval may depend on a distant position that appears very rarely.
    • Cross-document comparison requires access to multiple scattered pieces of evidence.
    • Long code analysis may need to combine definitions, references, configurations, and call chains.
    • Global statistics tasks may depend on broadly distributed information rather than a few high-scoring positions.

    Therefore, sparse strategies usually need to support multiple access paths. For example, they can retain a recent local window, allocate retrieval budget for distant content, and add a coarser global information channel when necessary.

    It is also necessary to distinguish two types of experiments:

    One uses a high-cost method to first find the ideal important positions and then verifies whether “looking only at these positions is sufficient.” The other lets the actual retriever find those positions by itself.

    The former shows that sparsification has potential; the latter shows that a solution can be deployed. The gap between them is retrieval approximation error.

    For models originally using full attention, directly replacing it with a sparse mechanism may also change the distribution of attention outputs. One cannot assume that capabilities will be preserved without training. Whether calibration, continued training, or other adaptation is needed should be determined by actual experiments.

    6. Why Local Speedups Do Not Equal End-to-End Speedups

    When discussing results such as “more than 20x speedup,” the measurement scope must first be clarified:

    • Is it a certain attention layer or the entire model?
    • Is it the indexer or the complete attention pipeline including data movement?
    • Is it prefill or token-by-token decode?
    • Are input length, batch size, and precision the same?
    • Are index construction and extra memory usage included?

    Suppose an optimized module originally accounts for a proportion p of end-to-end latency and the module is accelerated by a factor of s. Then the overall speedup is:

    Overall speedup = 1 ÷ [(1 − p) + p ÷ s].

    As a pure calculation example, if a module accounts for half of total latency, even if it is accelerated to 22 times its original speed, the overall speedup is only about 1.9x. This example does not represent test results from any actual system; it illustrates the upper bound of local optimization.

    Specific multipliers without full experimental settings and verifiable context should not be treated as general performance promises. For developers, it is more valuable to confirm where the main time of the target workload is actually spent and whether the bottleneck shifts to other modules after optimization.

    7. Validation Checklist for Real Deployment

    1. Measure Prefill and Decode Separately

    Prefill needs to process the entire input, while decode mainly involves interaction between newly added queries and existing history. Their computation patterns and bottlenecks differ. Time to first token, subsequent generation speed, and total request latency should be reported separately.

    2. Measure Both Quality and Candidate Recall

    In addition to final task scores, check whether the candidate set covers key evidence. Pay particular attention to low-frequency information, interference from similar content, cross-region evidence, and long-distance dependencies, so that average scores do not hide important failure modes.

    3. Count Complete Memory Costs

    Sparse access does not necessarily mean the historical key-value cache can be reduced proportionally. If any historical position may still be retrieved, the system usually still needs to retain the corresponding data or bear the cost of reading from another storage layer.

    Therefore, memory usage should be counted together for model weights, historical key-values, retrieval representations, index structures, and temporary buffers.

    4. Check Concurrency and Tail Latency

    Improved single-request performance does not mean high-concurrency throughput will necessarily improve. Index construction, candidate collection, and irregular memory access may all contend for resources. Production evaluation should cover different input lengths, batch sizes, and concurrency levels, and observe high-percentile latency.

    5. Design Quality Fallback Paths

    When input distribution changes, routing becomes too concentrated, or retrieval quality is unstable, fallback options can include expanding the candidate range or increasing the local access budget. Fallback strategies themselves also need evaluation to prevent uncontrollable resource spikes under extreme inputs.

    8. Conclusion: The Next Stage Is Finding Useful Information at Low Cost

    Ultra-long-context optimization is shifting from “reducing attention computation” to “reducing the cost of finding attention targets.”

    Latent representations, hierarchical routing, and candidate fine-ranking provide a path worth studying: first narrow the search range at lower cost, then concentrate expensive computation on positions more likely to be valuable.

    But a truly effective solution must pass three tests at the same time: the retrieval process is scalable, key evidence has sufficient recall, and the end-to-end system obtains reproducible gains.

    For developers, the most reliable basis for judgment is not an isolated speedup multiplier but a complete cost bill: under the same quality target, how much has the total cost of indexing, computation, memory, and data movement actually been reduced?