Optimizing KV Cache for Million-Token Context Inference
This article explores the challenges and solutions for KV Cache optimization in large language model inference with million-token contexts. It covers memory estimation, architectural approaches like shared heads and low-rank representations, and details a hierarchical attention design including compressed sparse attention and sliding windows. Additional techniques such as Partial RoPE, Attention Sinks, and QK normalization are also discussed to ensure stability and performance in long-context scenarios.
1. The First Hurdle of Million-Token Contexts: KV Cache
During autoregressive generation, each time the model generates a new token, it must compute attention using the current Query against the Keys and Values of all historical tokens. To avoid recalculating historical data at every step, the inference system caches the Keys and Values for each layer and token. This stored data is known as the KV Cache.
As the context length increases, the cache size grows proportionally. The memory footprint of the KV Cache for a single request can be estimated using the following formula:
KV Cache Bytes = L_ctx × N_layers × N_kv_heads × (d_k + d_v) × bytes_per_element
Where L_ctx is the context length, N_kv_heads is the number of key-value heads, and d_k and d_v are the dimensions of the Key and Value for each head, respectively. Under BF16 or FP16, each element occupies 2 bytes.
1.1 Quick Estimation with Code
def kv_cache_gb(ctx_len, n_layers, n_kv_heads, d_k, d_v, bytes_per_elem=2):"""Returns the KV Cache footprint for a single request in GB (decimal)."""total_bytes = ctx_len * n_layers * n_kv_heads * (d_k + d_v) * bytes_per_elemreturn total_bytes / 1e9print(kv_cache_gb(1_000_000, 60, 8, 128, 128)) # Approximately 245.76
1.2 Comparison Under Different Architectural Assumptions
The table below provides estimates based on assumed parameters, with a Batch size of 1, a context of 1,000,000 tokens, and BF16 storage. These numbers illustrate the scale of memory usage and do not represent empirical data from any specific model.
| Architectural Assumption | Layers | KV Heads | Head Dimension | 1M Context KV Cache |
|---|---|---|---|---|
| Full Multi-Head Attention (independent KV sets per query head) | 60 | 64 | 128 | ~1966 GB |
| Grouped-Query Attention (multiple query heads share one KV set) | 60 | 8 | 128 | ~246 GB |
| GQA + Low-Dimensional Representation (assuming effective dimension reduced to 1/4) | 60 | 8 | 32 | ~61 GB |
Two key observations can be drawn from the table. First, reducing the number of KV heads decreases memory usage proportionally. Second, even when compressed to a minimal size, memory usage still scales linearly with context length. Therefore, handling million-token contexts requires simultaneously compressing the “storage per token” and reducing the “number of tokens involved in computation per step.”
2. Four Approaches to Reducing KV Cache
- Shared Key-Value Heads: Multiple query heads share the same set of Keys and Values, directly reducing the number of cache entries.
- Low-Dimensional Representation: Projecting Keys and Values into a lower-dimensional latent space for storage, and restoring them during computation, or absorbing the restoration matrix into other projections.
- Historical Compression: Merging the KV of several consecutive tokens into a single compressed entry. The further away from the current position, the higher the compression rate.
- Sparse Selection and Windowing: Each query focuses only on a few relevant entries, or retains full KV only within a recent sliding window.
These four methods can be combined. A common practice is hierarchical processing: retaining full details for recent context, applying sparse selection for mid-distance context, and applying coarse-grained compression for distant context.
3. Design Considerations for Hierarchical Attention
3.1 Compressed Sparse Attention
The system first segments the historical sequence into chunks of a fixed block length. Each chunk passes through a learnable pooling mapping to generate a compressed KV entry. The query vector then passes through a lightweight indexer to score all compressed entries, selecting only the top-k scoring chunks for exact attention.
The computational cost of this design depends primarily on k, rather than the total historical length. Below is a pseudo-code illustration:
def sparse_compressed_attention(q, comp_kv, index_scores, k_top):# index_scores: relevance score of each compressed block, given by a lightweight indexertop_idx = topk(index_scores, k_top)selected = comp_kv[top_idx]return attention(q, selected.keys, selected.values)
3.2 Highly Compressed Attention
For distant historical context, larger block lengths can be used to generate a small number of global summary entries. These entries always participate in the computation to retain coarse-grained information from the entire text. Unlike the sparse branch, it does not perform selection, resulting in a stable computation path but lower resolution. The outputs of the two branches usually need to be fused, with the fusion method determined experimentally.
3.3 Sliding Window and Local Retention
The KV for the most recent w tokens is kept fully intact. Fine-grained information such as local syntax, coreference resolution, and code indentation relies on this precise data. The window size represents an engineering trade-off: a larger window provides more stable performance but consumes more memory.
4. Local Adjustments for Positional Encoding and Normalization
4.1 Partial Rotary Position Embedding (Partial RoPE)
Partial RoPE applies rotary position encoding only to a portion of the head dimensions, leaving the remaining dimensions position-independent. This ensures that semantic matching does not rely entirely on positional information, reducing the impact of phase errors on content matching over long distances. The trade-off is that these non-positional dimensions must be sufficiently learned during training, meaning their effectiveness needs to be validated at the target context length.
4.2 Attention Sinks
During training, it is commonly observed that the model allocates a large amount of attention to a few tokens at the very beginning of the sequence, even if these tokens are not semantically critical. These positions are often referred to as Attention Sinks. If their KV is compressed or evicted, output quality may degrade significantly. In implementation, the full KV of the first few tokens of the sequence should always be retained and excluded from sliding window eviction.
4.3 Query and Key Normalization
Applying RMSNorm to Query and Key before the dot product can constrain the scale of the logits. As the context grows longer, the numerical range of the dot product expands, and normalization helps maintain numerical stability. Whether this step is necessary, and where it should be placed, should be determined based on validation set results.
5. Data and Training Paradigms
Long-context capability relies heavily on the training process. The following aspects require focused design:
- Staged Length Extension: Gradually expanding the context length during training to help the model adapt to longer sequences efficiently.
