Million-Token Context in Practice: Attention Mechanisms and System-Level Optimizations
This article explores the technical challenges and optimization practices for implementing million-token context windows in large language models. It covers the core bottlenecks of long context—attention computation, KV cache size, and memory bandwidth—and examines the evolution of attention mechanisms including MHA, MQA, GQA, and MLA. Finally, it discusses system-level collaborative optimizations such as paged KV cache, prefix caching, sparsification, and scheduling strategies to maximize throughput and reduce latency.
1. Why Long Context is Challenging
Expanding the context window from tens of thousands of tokens to the million level may appear to be a simple parameter adjustment, but it simultaneously amplifies three types of pressure.
First, attention computation grows rapidly with sequence length. The computational complexity of standard self-attention scales quadratically with the sequence length. The longer the input, the faster the time and energy consumption of a single forward pass increase.
Second, the KV cache grows linearly with sequence length. During autoregressive generation, the model must save the Keys and Values of all processed tokens for each layer. The memory footprint of this KV cache is directly proportional to the context length, number of layers, number of KV heads, and the dimension per head.
Third, the decoding phase is limited by memory bandwidth. Every time a new token is generated, a massive amount of historical KV data must be read from memory. Even with sufficient compute power, memory bandwidth becomes the upper limit for throughput and latency.
The size of the KV cache can be estimated using the following formula:
def kv_cache_bytes(layers, kv_heads, head_dim, seq_len, dtype_bytes=2, batch=1):# Coefficient 2 means Key and Value are stored separatelyreturn 2 * layers * kv_heads * head_dim * seq_len * dtype_bytes * batch# Example config: 60 layers, 8 KV heads, head dim 128, 1 million tokens, FP16 storagesize = kv_cache_bytes(60, 8, 128, 1_000_000)print(f"{size / 1e9:.1f} GB") # Approx 245.8 GB
If each query head stores an independent set of KV (assuming 64 heads), the cache size for the same configuration would grow to approximately 1966 GB, an 8x increase. The values above are solely for illustrating the order of magnitude and do not represent the exact configuration of any specific model.
2. Evolution of Attention Mechanisms
The choice of architecture directly dictates the scale of the KV cache, making it the first decision point in long-context design.
2.1 Multi-Head Attention (MHA)
Each query head has its own independent K and V heads. This structure offers the strongest expressive power but also results in the largest KV cache, creating the most obvious memory pressure in long-context scenarios.
2.2 Multi-Query Attention (MQA)
All query heads share the same set of K and V. The KV cache is reduced to 1/H of the original (where H is the number of query heads), significantly lowering memory and bandwidth usage. The trade-off is that it becomes difficult for different heads to learn differentiated attention patterns, which may affect model quality and requires validation through training and evaluation.
2.3 Grouped-Query Attention (GQA)
Query heads are divided into G groups, with each group sharing a set of K and V. GQA strikes a balance between MHA and MQA: the more groups there are, the closer the expressive power is to MHA; the fewer groups, the more cache is saved. The number of groups is a hyperparameter that must be determined through empirical testing based on business needs.
2.4 Multi-Head Latent Attention (MLA)
MLA does not directly cache the complete K and V. Instead, it compresses them into low-dimensional latent vectors for storage and restores them via projection when needed. Because it caches the compressed representation, memory usage is significantly reduced while still preserving the expressive space of the multi-head structure. The trade-off is the addition of projection computations, requiring a balance between compute power and memory.
A comparison of the four structures is as follows:
| Structure | Relative KV Cache Size | Expression Capacity | Main Trade-off |
|---|---|---|---|
| MHA | 1x (Baseline) | Strongest | Highest memory and bandwidth pressure |
| MQA | Approx. 1/H | Weaker | Potential quality degradation |
| GQA | Approx. G/H | Moderate | Requires determining the optimal number of groups |
| MLA | Low-dimensional compression | Relatively strong | Additional projection computation |
For a period, the industry generally believed that mainstream architectures had stabilized and that subsequent improvements would mainly consist of minor tweaks. However, attention structures are still being re-evaluated, indicating that the space for architectural exploration is not exhausted. When selecting an architecture, one should not only look at the cache size but also comprehensively consider training stability, the degree of support from inference frameworks, and compatibility with existing parallelization strategies.
3. System-Level Collaborative Optimization
The benefits of single-point innovation can easily be offset by other bottlenecks. For example, if the scheduler cannot proportionally increase the batch size after the KV cache is halved, overall throughput will not see a corresponding increase. Similarly, if the parallel partitioning method does not match the model structure, cross-device communication overhead may consume most of the gains. Therefore, a long-context system must be designed holistically, integrating model structure, memory management, scheduling strategies, and hardware topology.
3.1 Paged KV Cache
The traditional approach reserves a large, contiguous block of memory for each request. When request lengths are uncertain, this easily leads to fragmentation and waste. Paged management splits the KV cache into fixed-size blocks, allocating and reclaiming them on demand. This improves memory utilization and makes it easier to serve more requests concurrently.
3.2 Prefix Caching
When multiple requests share the same system prompt or document prefix, the already computed KV can be reused to reduce redundant calculations and lower the time-to-first-token (TTFT) latency. The hit rate depends on how requests are organized, a point that will be expanded upon in Section 5.
def prefill(tokens, prefix_len, cache):# Pseudocode: omits cache eviction, concurrency control, and hash collision handlingprefix_key = hash(tuple(tokens[:prefix_len]))if prefix_key in cache:past_kv = cache[prefix_key] # Reuse computed prefix KVstart = prefix_lenelse:past_kv = Nonestart = 0kv = compute_kv(tokens[start:], past=past_kv)cache[prefix_key] = kv[:prefix_len]return kv
3.3 Sparsification and Mixture of Experts
Sparse attention (such as sliding windows or importance-based block selection) can reduce the number of tokens involved in computation. The Mixture of Experts (MoE) architecture ensures that each token only activates a portion of the experts, meaning the total parameter count is no longer directly proportional to the computation per pass. Both approaches require extra attention to load balancing and communication overhead between experts; otherwise, theoretical gains are difficult to realize.
3.4 Scheduling and Batching
Continuous Batching
