Million-Token Context Windows: Sparse Attention and KV Cache Optimization
Million-token context windows are becoming essential for codebase analysis, long-document review, and multi-step AI agent workflows. This article explains why standard attention and KV caching become impractical at this scale, and examines the architectural, data, and engineering techniques used to make ultra-long contexts feasible—including sparse attention, compressed KV representations, long-context training, sequence parallelism, paged KV management, and prefix reuse.
Introduction: Why Million-Token Context Windows Matter
As large language model applications evolve beyond simple question answering into codebase analysis, long-document review, and multi-step agent workflows, context-window length has become a major limit on model capability. Even a model with a very large parameter count may struggle with tasks such as “read an entire code repository and answer a question” if it can process only tens of thousands of tokens.
However, expanding the context window from tens of thousands of tokens to one million is not as simple as extending the training sequence. It introduces challenges at three levels:
- Architecture: The computation and memory cost of attention increases quadratically or linearly with sequence length, requiring redesigned attention structures.
- Data: Naturally occurring long-form text is relatively scarce in pretraining corpora, so high-quality long-sequence data must be constructed deliberately.
- Engineering: Sequence parallelism during training and KV Cache management during inference place significant demands on the underlying infrastructure.
This article examines the main technical approaches used to support million-token contexts from these three perspectives.
1. The First Bottleneck: KV Cache
Understanding the difficulty of long-context inference starts with the memory cost of the KV Cache.
With standard attention, the model stores a Key and a Value vector for every token in the context during inference. This avoids recomputing them at each decoding step. The approximate memory requirement can be expressed as:
KVCache = Lctx × Nlayers × Nkv_heads × (dK + dV) × 2 bytes
Here:
Lctxis the context length;Nlayersis the number of model layers;Nkv_headsis the number of KV heads;dKanddVare the dimensions of each head;2 bytesrepresents the storage cost of each value in BF16 or FP16 precision.
For a batch size of 1 and a context length of one million tokens, several common architectures illustrate the scale of the problem:
- Multi-head attention (MHA): Using a typical 7B-scale model as a reference, the KV Cache can reach hundreds of gigabytes, far beyond the memory capacity of a single accelerator.
- Grouped-query attention (GQA): Multiple query heads share a smaller group of KV heads, significantly reducing memory usage. Even so, a million-token context can still require tens of gigabytes.
- Multi-head latent attention (MLA): Keys and Values are compressed into a lower-dimensional latent space before being cached, reducing the memory requirement further. This has become one of the major approaches in recent model architectures.
The conclusion is straightforward: continuing to use standard attention makes million-token contexts extremely difficult to deploy in practice. As a result, newer architectures generally combine sparsity with aggressive compression.
2. Architecture: Combining Sparse and Highly Compressed Attention
2.1 The Core Idea Behind Sparse Attention
Sparse attention is based on the observation that attention patterns in long documents are often naturally sparse. A token typically has strong relationships with a limited number of important tokens rather than interacting uniformly with the entire context.
A common design allows each token to attend to two types of targets:
- A local window: Sliding Window Attention limits attention to nearby tokens and captures local semantics.
- Global anchors: A selection mechanism, such as lightweight top-k routing, identifies a small number of globally important tokens and creates long-range connections to them.
This changes the computational complexity from O(n²) to approximately O(n·k), where k is the number of targets each token actually attends to and is much smaller than n.
2.2 Highly Compressed Attention: Making Each Cache Entry Smaller
Highly compressed attention takes a different approach. Instead of only reducing the number of attention connections, it reduces the size of each cached Key and Value representation.
Common techniques include:
- Low-rank compression: Project Keys and Values into a latent space with a much smaller dimension than the original representation. The compressed form is cached and decompressed when needed.
- Hierarchical compression: Apply more aggressive compression to earlier context while preserving higher precision for recent tokens. This reflects the practical pattern that attention is usually denser for nearby content and sparser for distant content.
- Quantized caching: Apply low-bit quantization to the KV Cache during inference, potentially combining it with structural compression.
2.3 Important Details That Are Easy to Overlook
Long-context models often include several additional design choices:
- Attention sinks: Experiments have shown that models tend to direct excess attention toward a small number of tokens near the beginning of a sequence. Explicitly preserving or introducing these sink tokens can stabilize output quality in streaming scenarios and prevent sharp changes in probability distributions after context eviction.
- Partial RoPE: Rotary positional encoding is applied only to some dimensions, allowing the remaining dimensions to focus on content matching without being affected by distance. This can help long-range retrieval tasks.
- RMSNorm at selected locations: Adding normalization at key points in the attention branch can stabilize activation distributions during ultra-long-sequence training and reduce the risk of numerical explosions.
None of these techniques is particularly complex in isolation. Together, however, they form a complete architecture capable of stable training and inference at million-token scale.
3. Data: Long-Context Capability Must Be Trained
Architecture defines the upper bound of what a model can support, but its ability to understand long-range relationships depends heavily on the training data.
3.1 Where Long-Sequence Data Comes From
High-quality naturally long documents, such as complete books and extensive technical documentation, represent only a limited portion of most corpora, and their quality can vary. Common ways to supplement them include:
- Document concatenation: Combine multiple semantically related short or medium-length documents into a long sequence. Attention masks may be needed to prevent unwanted cross-document interactions.
- Synthetic tasks: Insert instructions into long documents and ask the model to perform retrieval, summarization, or cross-section reasoning. These tasks explicitly train “needle-in-a-haystack” capabilities.
- Curriculum training: Complete the main pretraining stage at conventional sequence lengths, then gradually extend the target length in multiple stages. The RoPE base frequency can also be adjusted to support the expanded positional range.
3.2 Data Quality Matters More Than Raw Volume
Simply adding more long text does not necessarily produce better long-context reasoning. Low-quality concatenation can even harm model performance. In practice, a small amount of high-quality long-sequence data combined with a carefully designed curriculum is often more effective than a massive collection of roughly constructed long sequences.
4. Engineering: Coordinating Training and Inference Infrastructure
4.1 Training
A million-token sequence cannot fit on a single accelerator. Sequence parallelism distributes one long sequence across multiple devices, with each device holding one segment. Cross-device communication is then used to complete attention and normalization calculations.
Other supporting techniques include:
- Activation recomputation: Trade additional computation for lower memory usage instead of storing intermediate activations for the entire long sequence.
- Mixed precision and numerical stability: Gradient accumulation over extremely long sequences can introduce numerical issues, so loss scaling and normalization strategies must be selected carefully.
4.2 Inference
Several inference optimizations are particularly important:
- Paged KV management: Inspired by operating-system paging, the KV Cache is divided into fixed-size blocks that are allocated on demand. This reduces memory fragmentation and improves concurrency.
- Prefix-cache reuse: In multi-turn conversations or batch document processing, a shared prefix needs to be computed only once.
- Combining speculative decoding with sparse computation: This can further reduce the amortized inference cost of generating each token in long-context scenarios.
For organizations deploying long-context capabilities in the cloud, choosing container platforms, distributed-training frameworks, and inference services that support these mechanisms can substantially reduce the complexity of building infrastructure independently. Cloud providers such as Baidu AI Cloud are also turning long-document processing capabilities into more general-purpose services that developers can invoke as needed.
5. Conclusion
Supporting million-token contexts is ultimately a system-wide effort involving architecture, data, and engineering:
- Architecture: Combine sparse attention with highly compressed caching to bring memory and computation costs within practical limits, while using techniques such as Attention Sink, Partial RoPE, and targeted normalization for stability.
- Data: Use high-quality long-sequence construction and curriculum training so that the model learns to use long-range information rather than merely accept longer inputs.
- Engineering: Rely on sequence parallelism, paged KV management, prefix-cache reuse, and related infrastructure to turn theoretical designs into reliable services.
Understanding these three layers provides a clearer basis for evaluating models and designing long-context applications. The competition around context length is far from over, but the underlying methodology is becoming more consistent: architectures that push sparsity and compression further will be better positioned to help models work with entire books, repositories, and other very large information sources.
