10-Million-Token Inference Optimization: Breaking the Sparse Attention Indexing Bottleneck

    This article explores the computational bottlenecks in ultra-long context LLM inference, specifically shifting the focus from memory capacity to the inefficiencies in sparse attention indexing. It breaks down the costs of prefill stages, highlights the limitations of naive latent space sparsification, and analyzes how to interpret single-layer speedups using Amdahl's Law. Additionally, it provides practical strategies for balancing retrieval efficiency with critical information recall, optimizing hardware memory access, and establishing a comprehensive verification process for end-to-end performance.

    1. The New Bottleneck of Ultra-Long Context: Not Seeing More, but Finding Slower

    The tasks that long-context models need to handle are expanding from single-document Q&A to scenarios like codebase comprehension, multi-document analysis, and long-term record summarization. As the input grows from one million to ten million tokens, the system faces not only memory capacity issues but also a more fundamental computational problem: for each query position, which historical information should it access?

    Standard global attention allows each query to match against all visible keys. Assuming a sequence length of N and a single attention head dimension of d, the primary computational load of full attention typically grows with N²d. Causal masking reduces some matches but does not change the quadratic growth trend relative to sequence length.

    The starting point of sparse attention is that not all historical positions are equally important. By filtering out a sufficiently effective candidate set, it is possible to reduce computation while preserving task capabilities.

    However, “calculating fewer positions” does not mean “paying less cost.” If the filtering stage still requires scanning all historical positions for each query, the system simply moves the full matching from the formal attention computation into the indexer.

    This is the critical shift in the 10-million-token scenario: attention aggregation has become sparse, but candidate retrieval may still maintain an approximate full scan.

    2. Break Down Costs to Locate the Real Optimization Target

    When analyzing sparse attention, the prefill time of a single input can be broken down into:

    T_total = T_representation_transform + T_index_building + T_candidate_filtering + T_data_access + T_attention_aggregation + T_other_computation

    Prefilling refers to the phase where the model processes the entire input and builds the state required for subsequent generation. It differs from the token-by-token generation phase: prefilling requires processing a large number of queries simultaneously, making the scale of index computation more likely to be exposed.

    Assuming each query ultimately accesses only k positions, and k is much smaller than N, the formal attention computation can approach O(Nkd).

    However, if the indexer first computes low-dimensional relevance for all queries against all keys, its computational load may still approach O(N²r), where r is the dimension of the index representation. Even if r is much smaller than d, it only reduces the constant of the quadratic term and does not change the growth order.

    As N continues to expand, this suppressed quadratic term can still become the primary overhead. Therefore, to determine whether a sparse scheme is suitable for ultra-long contexts, at least the following must be examined separately:

    • How many positions the formal attention accesses;
    • How many extra candidates were compared to determine these positions;
    • How much discontinuous memory access the filtering results introduce;
    • Whether index building, maintenance, and updating are included in the total time.

    Reporting only the sparsity ratio cannot answer these questions.

    3. The Key to Latent Space Sparsification: Making Candidate Discovery Itself Cheaper

    The latent space can be understood as an intermediate representation space used for retrieval or routing. It does not necessarily have to be identical to the representation used in formal attention; instead, it attempts to use lower-cost features to determine “which regions are worth further inspection.”

    A boundary must be clarified here: merely mapping queries and keys to a lower-dimensional space does not necessarily eliminate quadratic complexity. If all queries are still compared against all keys, the complexity still grows with N².

    The truly valuable optimization combines latent space representations with candidate organizational structures to avoid per-query full scanning. General approaches include blocking, hierarchical retrieval, clustering routing, and shared candidate discovery. These are common ways to explain the design space and should not be understood as a complete implementation necessarily adopted by specific research.

    Taking hierarchical blocking as an example, the historical sequence can be divided into multiple regions, saving representative features for each region. The query first matches against regional features, and then performs fine-grained filtering on tokens within a few selected regions.

    Assuming each block contains B tokens and each query selects s blocks, the coarse and fine candidate scale for a single query, in a simplified model, is approximately:

    N / B + sB

    Correspondingly, the filtering overhead for all queries is approximately:

    O(N × (N / B + sB))

    This expression illustrates an important fact: blocking can significantly reduce the search volume, but whether it achieves near-linear growth depends on the block size, the number of selected blocks, the number of index layers, and how they scale with sequence length. A scheme with a fixed block size that scores all blocks one by one may still retain quadratic growth terms.

    Therefore, you cannot judge algorithmic complexity based solely on names like “latent space” or “hierarchical”; you must examine the actual access path.

    4. How to Interpret a 20x+ Speedup

    Reference materials report that under a 10-million-token input condition, the prefilling of a single attention layer in a certain type of model achieved an approximate 22.7x speedup, and an even higher speedup under another configuration. The reasonable use of this data is to suggest that there may be massive optimization space in the indexer, rather than directly inferring that the entire model can achieve the same speedup ratio.

    The reference material also provides a key observation: in specific global attention layer tests, the indexing phase accounts for about 98% of the time. Since the original material does not provide a complete test configuration, this ratio should be viewed as an observation under specific conditions and cannot be generalized to all models and hardware.

    However, it can be used to explain the mathematical boundary of the speedup.

    If the indexing time proportion is p, the indexer achieves an r-fold speedup, and the rest remains unchanged, the overall speedup ratio for this layer is:

    S = 1 / ((1 - p) + p / r)

    When p is 0.98, even if the indexing time is ideally reduced to zero, the speedup upper limit for this layer is only 50x. This indicates that when the index proportion is very high, improving the filtering path can indeed yield order-of-magnitude benefits; meanwhile, the remaining computation will quickly become the new bottleneck.

    It is also necessary to further distinguish between three metrics:

    1. Indexer speedup ratio: only measures the candidate discovery module.
    2. Single-layer prefill speedup ratio: includes the related computations of that layer.
    3. End-to-end speedup ratio: includes all model layers, input processing, state management, and subsequent generation.

    These three cannot be mixed. The more significant the local optimization, the more necessary it is to re-measure the proportion of other modules.

    5. With Fewer Candidates, How to Avoid Missing Key Information

    The core risk faced by sparse attention is not just a decrease in average accuracy, but rather that critical evidence fails to enter the candidate set.

    For example, among a large number of ordinary records, a low-frequency anomaly log might determine the final diagnosis; in a long document, a constraint far from the question might change the answer; in a code understanding task, an inconspicuous definition might affect cross-file reasoning.

    If the indexer misses these positions, subsequent attention, even if computed perfectly accurately, cannot recover the unaccessed information.

    Therefore, candidate design usually needs to establish constraints between efficiency and coverage. Evaluable general strategies include:

    • Retaining a certain range of local windows to reduce losses in neighboring grammar and short-range dependencies;
    • Setting an independent budget for long-distance retrieval to prevent all candidates from concentrating locally;
    • Performing more refined secondary scoring on coarse-filtered candidates;
    • Expanding the candidate set when routing scores are close and confidence is insufficient;
    • Adjusting access budgets based on task type and input length, rather than mechanically adopting a fixed ratio.

    All these strategies have costs. Retaining more candidates may improve recall, but it may also offset speed gains. The reasonable goal is not to compress the candidate count to the absolute minimum, but to reduce total execution costs under acceptable task quality constraints.

    6. Lower Complexity Does Not Guarantee Faster Hardware Execution

    The engineering performance of ultra-long context depends not only on the number of multiply-accumulate operations but also highly on memory access patterns.

    A scheme might significantly reduce comparison times but generate a large number of discrete, small-scale reads. In this case, the device struggles to form contiguous accesses, and compute units may idle while waiting for data.

    Actual optimization should simultaneously focus on:

    First, the organization of candidate positions.
    If candidates can be organized into contiguous blocks, it is generally more conducive to batch reading; if candidates are highly discrete, the extra cost of organizing, rearranging, and transferring must be evaluated.

    Second, the lifecycle of the index structure.
    Is the index built independently for each layer, or reused under specific conditions? After new tokens are added, does it require a full rebuild or an incremental update? These factors directly impact long-term operating costs. Any reuse must verify whether the representation remains valid; it cannot be assumed that different layers or stages can share losslessly by default.

    Third, temporary memory.
    Even if the full attention matrix is not saved, intermediate candidate scores, sorting buffers, and data rearrangement spaces may occupy a large amount of memory. Counting only model states while ignoring temporary space will underestimate deployment thresholds.

    Fourth, runtime stability.
    Beyond average latency, tail latency under uneven candidate distribution, input structure changes, and mixed batch lengths should also be checked. A theoretically identical candidate budget does not guarantee consistent execution time for every run.

    7. Establishing a Reliable Verification Process

    For developers, verification should start with correctness before discussing performance.

    1. Fix comparison conditions first

    Keep model weights, numerical precision, input content, hardware resources, and batch conditions consistent. Clarify whether the comparison is for the attention operator, a single layer, or the complete inference flow, and state whether index building and data arrangement are included in the timing.

    2. Measure across lengths, not just one extreme

    Gradually expand from shorter inputs to the target length, plotting the curves for time consumption, peak memory, and candidate count. Single-point speedups may stem from implementation differences at a specific scale; growth curves better reflect whether the algorithm has truly broken free from the main bottleneck.

    3. Measure prefilling and generation simultaneously

    Faster prefilling usually helps reduce first-token latency, but it may not improve subsequent generation speed by the same margin. Input processing time, first-token latency, token-by-token generation latency, and end-to-end completion time should be recorded separately.

    4. Check accuracy with multiple task types

    Evaluations should not only include retrieval for a single target position but also cover multi-evidence synthesis, cross-segment constraints, sequential relationships, long-range dependencies, and massive interference information. It is also necessary to tally results across different positions and input lengths to prevent averages from masking localized failures.

    5. Perform a joint sweep of budget and accuracy

    Gradually adjust the candidate budget and observe the relationship between speed gains and task quality. The final choice should fall in a region where quality requirements are stably met, rather than just selecting the fastest configuration.

    8. From Local Sparsity to Full-Chain Sparsity

    The key takeaway for 10-million-token inference is not simply “look at less history,” but rather making the entire path of finding, reading, and utilizing history efficient together.

    If formal attention is already sparse but the indexer still performs full matching, the system will re-encounter quadratic growth under longer inputs. If the search volume drops but introduces too much random access, the gains may be swallowed by data transfers. If you only pursue speed without verifying long-range evidence recall, you may end up with a faster but unreliable system.

    Therefore, the most noteworthy direction for latent space sparsification is transforming candidate discovery from expensive full matching to low-cost routing with quality constraints. The judgment of its value should be based simultaneously on complexity analysis, real execution profiling, and task quality evaluation.

    A 20x+ single-layer speedup can reveal a significant opportunity, but whether it translates into stable business value ultimately depends on end-to-end latency, memory peaks, long-range information recall, and reliability under different input distributions.