Accelerating Ten-Million-Token LLM Contexts with Latent-Space Sparse Attention

    This article explains why sparse attention becomes bottlenecked by candidate retrieval at ten-million-token context scales, and how latent-space sparse attention addresses the problem by separating low-cost coarse retrieval from high-precision local attention. It covers the core architecture, sources of speedup, accuracy tradeoffs, differences between prefill and decode, engineering considerations, suitable use cases, and how to interpret reported acceleration numbers.

    As large language models continue to expand their context windows, “letting the model read more historical information” has moved from a capability demonstration to a real engineering requirement. Long-document question answering, code repository analysis, cross-chapter information retrieval, audit material summarization, and multi-turn task memory all require the model to process millions or even tens of millions of tokens in a single computation.

    However, traditional full attention cannot directly handle input at this scale. For a sequence of length (N), standard self-attention computes the relevance between every query and all keys, and its computation and intermediate data typically grow with (N^2). Even as hardware performance continues to improve, when context expands from the million-token level to the ten-million-token level, simply stacking more compute resources quickly runs into limits in bandwidth, memory capacity, and scheduling efficiency.

    Sparse attention has therefore become an important technical route for ultra-long contexts. Its basic idea is not complicated: each query does not need to access all historical tokens, but only a small number of the most relevant positions. This can compress the number of candidates that actually participate in exact attention computation from millions or even tens of millions into a much smaller range, significantly reducing the cost of subsequent matrix operations.

    But at ten-million-token contexts, a new bottleneck appears. The system must first answer a question: which tokens are actually worth reading?

    1. The Sparse Attention Bottleneck Shifts from “Computation” to “Retrieval”

    A typical sparse attention pipeline usually includes three stages:

    1. Build some comparable representation for the query and historical tokens.
    2. Compute relevance between the query and historical positions.
    3. Select the top-ranked positions and perform exact attention.

    The computation in the third stage is relatively small, but the first two stages may still need to scan a large amount of historical information. If the indexer requires every query to be compared with all historical tokens, then even if only a small number of candidates are ultimately retained, the candidate screening process itself may still approach full computation.

    At the million-token context level, this overhead may not yet be decisive. But at the ten-million-token level, both the number of queries and the number of historical positions that the indexer must process increase at the same time, and the cost of the screening stage rises rapidly. At this point, although sparse attention reduces “the number of tokens that are exactly read,” it does not fully solve “how to find those tokens.”

    From a system perspective, overall prefill time can be roughly decomposed as:

    [
    T{\text{prefill}} =
    T
    {\text{representation building}}+
    T{\text{candidate screening}}+
    T
    {\text{exact attention}}+
    T{\text{data movement}}+
    T
    {\text{scheduling and synchronization}}
    ]

    When the context size is small, exact attention may account for the main share. When the context enters the ten-million-token range, candidate screening, index access, and memory movement may instead become dominant factors. The optimization objective therefore shifts from “reducing attention computation” to “lowering the cost of global search.”

    2. The Core Idea of Latent-Space Sparse Attention

    The key to latent-space sparse attention is that it does not perform large-scale candidate search directly on original token representations. Instead, it first compresses historical information into a smaller latent space that is better suited for retrieval.

    It can be understood as a two-layer computation structure.

    The first layer is low-cost coarse-grained retrieval. The model maps historical tokens, local fragments, or continuous positions into low-dimensional latent vectors and organizes these vectors hierarchically or in blocks. When a query arrives, the system first looks for potentially relevant regions in the latent space rather than comparing every original token one by one.

    The second layer is high-precision local attention. After the coarse retrieval stage produces candidate regions, the system returns to the original key/value representations and performs full attention computation on a small number of candidate positions, aiming to preserve the model’s original expressive capability as much as possible.

    Its computation path can be summarized as:

    1. Historical tokens
    2. │
    3. ├─ Generate original key/value for exact attention
    4. │
    5. └─ Project into low-dimensional latent space for fast retrieval
    6. │
    7. query ──> latent-space matching ──> candidate blocks or positions
    8. │
    9. └─> exact attention on original representations

    The value of this approach is that it separates “global search” from “high-precision computation.” Global search uses a more compact representation, thereby reducing computation and memory access costs. Exact attention operates only on a small number of candidates, avoiding expensive operations over all historical tokens just to maintain accuracy.

    It is important to emphasize that the latent space is not simply truncating the context, nor is it crudely discarding historical information. It is closer to a learnable index structure: the system attempts to retain retrieval-relevant information so that a query can quickly locate potentially useful historical regions.

    3. Why Latent Space Can Deliver Higher Speedup

    The benefit of traditional sparse attention mainly comes from reducing the number of candidates, while latent-space methods further reduce the complexity of candidate search itself. Sources of speedup usually include the following.

    3.1 Lower Comparison Dimensionality

    Original keys often have high dimensionality, and direct large-scale similarity computation brings significant arithmetic and memory overhead. Latent-space retrieval uses more compact vectors, reducing the cost of each comparison.

    The system can first divide continuous history into blocks and use block-level representations for coarse filtering. Only top-ranked blocks are further expanded to the token level. In this way, the search target is reduced from tens of millions of tokens to a smaller number of blocks.

    3.3 Fewer Invalid Memory Accesses

    In long-context tasks, memory bandwidth is often more likely to become a bottleneck than compute units. A latent-space index can make accesses more concentrated, avoiding irregular scans over the entire KV cache and thereby reducing cache misses and cross-device data movement.

    3.4 Easier Batch Execution on Hardware

    If candidate positions are organized into continuous regions or structured blocks, low-level operators are easier to vectorize, batch, and schedule in parallel. Compared with a large number of discrete position accesses, a regularized data layout is usually better suited to accelerator execution.

    Related research has reported significant gains at the ten-million-token scale: for some large model structures, prefill latency of a single attention layer can achieve order-of-magnitude improvement, with speedups exceeding twenty times in some test scenarios and even higher levels for other structures. However, such results usually depend on hardware configuration, candidate retention ratio, sequence content, and operator implementation, and should not be simply understood as meaning that all tasks will obtain the same acceleration.

    4. Why Accuracy Does Not Drop Noticeably

    The biggest risk of sparsification is that the model may miss genuinely important historical information. For example, an entity definition required for the answer may appear very early, a key constraint may be hidden in the middle of a long document, or a variable declaration in code may be far away from its final call site.

    To maintain accuracy, latent-space methods usually need to address three issues.

    4.1 Preserve Sufficient Recall

    The most important metric in the candidate screening stage is not “how fast the filtering is,” but whether it can recall genuinely useful positions. If key tokens do not enter the candidate set, even the strongest subsequent exact attention cannot recover the information.

    Therefore, systems usually need to trade off candidate scale against recall. Too few candidates lead to high speed but easy information loss; too many candidates lead to more stable accuracy but reduced acceleration.

    4.2 Use Both Local and Global Information

    Many tasks have obvious local relevance, such as adjacent code lines or definitions and explanations in the same paragraph. But long-context tasks also contain long-distance dependencies, so local windows alone are not enough.

    A more robust strategy is to combine local windows, global candidates, and special positions: local windows are responsible for stable modeling of nearby relationships, global latent-space retrieval is responsible for discovering long-distance associations, and a small number of retained positions are used to reduce the risk of information loss in extreme cases.

    4.3 Retain Some Redundancy

    In practical systems, the candidate set should not rely entirely on a single retrieval result. Robustness can be increased through multi-path retrieval, hierarchical candidates, dynamic candidate expansion, and similar methods. When query uncertainty is high or retrieval scores are close, the system can automatically increase the number of candidates.

    Therefore, latent-space sparse attention is not unconditionally “looking only at the few most relevant positions.” Instead, it establishes an adjustable balance among speed, recall, and model accuracy.

    5. Different Impacts on Prefill and Decode

    Ultra-long-context scenarios need to distinguish between the prefill and decode phases.

    The prefill phase must process a large number of input tokens at once, with high computation and memory access pressure, so the benefits of latent-space retrieval are usually most obvious. Especially when a long document is first fed into the model, candidate screening overhead may account for a large proportion of total latency.

    The decode phase generates only a small number of tokens each time, but it needs to continuously access the historical KV cache. At this point, the bottleneck often shifts from large-scale matrix computation to cache reads, random memory access, and cross-device communication. Latent-space indexing still helps, but the optimization focus shifts to index reuse, cache residency, and low-latency candidate updates.

    Engineering implementations can adopt different strategies:

    • Use block-based construction and batched retrieval during prefill.
    • Reuse the already-built latent-space index during decode.
    • Cache indexes for stable, unchanging historical intervals.
    • Use a local window for fast processing of recently generated tokens.
    • Update indexes for long-term history at a lower frequency.

    This avoids rescanning the entire context every time a token is generated.

    6. Engineering Issues to Watch During Deployment

    6.1 Index Construction Cost

    A latent-space index is not free. The system needs to additionally generate compressed representations, build block structures, and maintain metadata. If index construction itself is too complex, it may offset the time saved by subsequent attention computation.

    Therefore, index construction should be made as streaming as possible, so that part of the processing can be completed as historical tokens arrive, rather than performing a centralized build only after all context has been input.

    6.2 Dynamic Length and Dynamic Candidate Count

    Different queries have different information needs. A simple question may require only a small number of candidates, while complex reasoning may require a broader historical range. A fixed candidate count is easy to implement, but it does not necessarily achieve the best balance between speed and accuracy.

    More flexible systems can dynamically determine candidate scale based on retrieval score distribution, candidate spacing, query type, or the importance of context regions.

    6.3 Data Layout and Operator Fusion

    If latent-space retrieval, candidate reordering, and exact attention are each completed by separate independent operators, frequent write-back of intermediate results may introduce significant overhead. In actual deployment, attention should be paid to operator fusion, memory layout, batching methods, and inter-device communication.

    Especially in multi-GPU or heterogeneous hardware environments, candidate indexes should minimize cross-device transmission, avoiding large communication waits caused by retrieving a small amount of KV data.

    6.4 Long-Context Evaluation Cannot Rely Only on Average Accuracy

    Ordinary short-text evaluations cannot fully reflect the strengths and weaknesses of ultra-long-context sparse mechanisms. Testing should cover at least:

    • Key facts located at the beginning, middle, and end.
    • Multiple similar entities appearing at the same time.
    • Cross-chapter references and long-distance coreference.
    • Variable tracking in long code files.
    • Recovery of old constraints in multi-turn conversations.
    • Cases with a high proportion of noisy documents.
    • Degradation behavior after candidate recall failure.

    In addition to final task accuracy, systems should also record candidate recall, average candidate count, index construction time, peak memory usage, memory bandwidth utilization, and p95 and p99 latency.

    7. Scenarios Suitable for This Technology

    Latent-space sparse attention is better suited to tasks where “the context is very long, but the truly relevant information is relatively sparse.” Examples include:

    • Question answering over ultra-long technical documents.
    • Retrieval-augmented internal enterprise knowledge bases.
    • Understanding large code repositories.
    • Analysis of contracts, audit materials, and policy documents.
    • Long-span conversational memory.
    • Fact checking across multiple documents.
    • Long-sequence log diagnosis.

    If a task requires the model to precisely aggregate almost all tokens, such as complete statistics, verbatim transformation, or high-density global computation, excessive sparsification may not be suitable. In such cases, consider approaches that combine segmentation, hierarchical summarization, external retrieval, and exact computation.

    8. How to Interpret “More Than Twenty Times Speedup”

    High acceleration numbers appearing in papers usually represent relative improvements in a specific computation stage or a specific attention layer under specific experimental conditions, not a guarantee that end-to-end model latency will necessarily decrease by the same factor.

    End-to-end performance is also affected by other model layers, input/output processing, KV cache management, data transmission, and scheduling overhead. According to Amdahl’s law, if the attention part accounts for only a portion of total time, then even if attention itself achieves extremely high acceleration, the overall gain will be limited by other components.

    Therefore, when evaluating a solution, one should also note:

    [
    \text{End-to-end gain}
    \neq
    \text{Single-operator speedup}
    ]

    A more reasonable evaluation method is to report single-layer performance, attention module performance, total prefill latency, decode throughput, memory usage, and task accuracy separately, while clearly specifying context length, hardware environment, and candidate configuration.

    Conclusion

    When context size enters the ten-million-token level, the core problem of long-context optimization has shifted from “how to compute all attention” to “how to efficiently find the attention that actually needs to be computed.” Traditional sparse attention solves the candidate count problem, but may leave a new global search overhead in the candidate screening stage.

    Latent-space sparse attention separates global search from high-precision modeling through low-dimensional representations, block-based retrieval, and local exact computation, potentially reducing computation, memory access, and system latency at the same time. Its real value is not only a higher single-layer speedup, but also a scalable computation organization method for ultra-long-context models.

    For engineering teams, deploying such a solution cannot focus only on theoretical complexity. It must also be validated across multiple dimensions, including recall, dynamic candidates, index reuse, hardware memory access, end-to-end latency, and task accuracy. Only when “finding accurately, finding quickly, and computing stably” hold at the same time does sparse attention truly have practical value for supporting ten-million-token contexts.