Systems Engineering · Machine Learning

KV Cache

Reference entry · last updated September 11, 2026

KV cache (Key-Value cache) is a memory buffer in autoregressive transformer inference that stores intermediate Key and Value activation vectors across attention layers for past tokens.[1] By retaining these projections in accelerator high-bandwidth memory (HBM), the model evaluates attention for each newly emitted token without recomputing linear projections for preceding context.[2]

1. Prefill Phase (Parallel Write) Input Tokens \(t_1, t_2, \dots, t_L\) Full Projection \(K, V \in \mathbb{R}^{L \times d}\) Parallel GEMM (Compute-Bound) Writes all \(L\) slots to HBM 2. Decode Step \(i\) (Vector Append) Token \(t_i\) Query \(q_i\) Read Past Cache [K<i, V<i] + Append Single [k_i, v_i] GEMV Attention (Memory-Bandwidth Bound) Reads entire cache from HBM per token

1. First Principles: Computational Trade-off

In standard transformer self-attention, the scaled dot-product attention for query tokens \(Q \in \mathbb{R}^{N_q \times d}\), key tokens \(K \in \mathbb{R}^{N_k \times d}\), and value tokens \(V \in \mathbb{R}^{N_k \times d}\) is defined by Vaswani et al.:[3]

\[\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V\]

During the prefill phase, all \(L\) prompt tokens are available at once. The attention mechanism calculates keys and values for all tokens simultaneously via dense matrix-matrix multiplication (GEMM), operating with high arithmetic intensity on GPU tensor cores.[2]

During autoregressive decoding, the model generates output tokens sequentially. Emitting step \(i+1\) requires calculating attention between the current token query \(q_i\) and the representations of all preceding tokens \(t_1, \dots, t_i\). Two operational choices exist:

This efficiency introduces a fundamental systems trade-off: the KV cache eliminates redundant mathematical operations by trading compute for memory storage and memory bandwidth.[1] Because every decoding step loads the full accumulated KV cache from high-bandwidth memory (HBM) into on-chip cache (SRAM) for a single token query vector, autoregressive decoding shifts from being compute-bound to memory-bandwidth bound.[2]

2. Memory Footprint Formulation

The total bytes required to store the KV cache for a transformer model depend on batch size, sequence length, network depth, and attention dimensions.[2]

For standard Multi-Head Attention (MHA), the total memory footprint \(M_{\text{KV}}\) in bytes is:

\[M_{\text{KV}} = 2 \times B \times L \times n_{\text{layers}} \times h_{\text{kv}} \times d_{\text{head}} \times P\]

where:

For a 70-billion-parameter model with \(n_{\text{layers}} = 80\), \(h_{\text{kv}} = 64\), \(d_{\text{head}} = 128\), and 16-bit precision (\(P = 2\)):

\[\text{Memory per token} = 2 \times 80 \times 64 \times 128 \times 2 = 2,621,440 \text{ bytes} \approx 2.5 \text{ MB per token}\]

At a context length of 128,000 tokens for a single user (\(B = 1\)), the KV cache footprint requires:

\[128,000 \times 2.5 \text{ MB} \approx 320 \text{ GB}\]

This single-sequence footprint exceeds the physical 80 GB capacity of an NVIDIA H100 or A100 GPU before accounting for the model parameter weights themselves.[1] Consequently, KV cache memory footprint is the primary bottleneck limiting maximum context length, batch size, and serving concurrency in production AI systems.

3. Architectural Variants: MHA, MQA, GQA, and MLA

To reduce KV cache storage requirements and memory bandwidth pressure during decoding, neural network architectures modify attention head topologies:[4]

Architecture Head Topology KV Cache Footprint (Relative to MHA) Representative Models
Multi-Head Attention (MHA) \(h_{\text{kv}} = h_{\text{q}}\) (One KV head per Query head) \(1\times\) (Baseline, largest footprint) Original Transformer, GPT-3, Llama 1 (65B)
Multi-Query Attention (MQA) \(h_{\text{kv}} = 1\) (All Query heads share one KV head) \(1 / h_{\text{q}}\) (Up to 98% reduction) PaLM, Falcon, StarCoder
Grouped-Query Attention (GQA) \(1 < h_{\text{kv}} < h_{\text{q}}\) (Query heads partitioned into groups) \(h_{\text{kv}} / h_{\text{q}}\) (Typically 75% to 87.5% reduction) Llama 2 (70B), Llama 3/3.1/3.3, Mistral, Qwen
Multi-Head Latent Attention (MLA) Low-rank joint compression into latent vector \(c_t^{KV}\) Compresses KV cache into small latent dimension \(d_c\) DeepSeek-V2, DeepSeek-V3, DeepSeek-R1

Introduced by Shazeer in 2019, Multi-Query Attention collapses all Key and Value heads into a single head per layer.[5] While drastically slashing memory bandwidth demands, MQA can lead to capacity loss and training instability in large models.

Grouped-Query Attention, formulated by Ainslie et al. in 2023, strikes an empirical middle ground.[4] By assigning query heads into \(g\) groups that each share a single KV head (e.g., 8 KV heads serving 64 query heads), GQA recovers nearly all representational expressiveness of MHA while delivering an \(8\times\) reduction in KV cache storage and transfer overhead.

Multi-Head Latent Attention, introduced in DeepSeek-V2, compresses keys and values into a shared low-rank latent vector prior to caching.[6] During generation, only the compressed latent vector and decoupled positional encodings need to reside in the cache, reducing the effective per-token memory footprint to a fraction of standard GQA architectures.

4. Memory Management and PagedAttention

Conventional deep learning frameworks allocate memory for the KV cache as contiguous physical memory blocks sized to the maximum theoretical sequence length (\(L_{\text{max}}\)). This introduces severe memory fragmentation:[1]

In 2023, Kwon et al. introduced PagedAttention in the vLLM serving system, adapting operating system virtual memory concepts to transformer inference.[1]

PagedAttention partitions the KV cache of each sequence into fixed-size physical blocks (e.g., 16 or 32 tokens per block). A centralized block table translates logical token positions to non-contiguous physical pages in GPU VRAM. When a new token is generated, the engine writes to the current block; when the block fills, the system allocates another page from a shared global pool. This design eliminates external fragmentation and reduces internal memory waste to under 4%, multiplying effective serving throughput and concurrency by factors of 2 to 4.[1]

PagedAttention also enables copy-on-write memory sharing across multiple sequences. Parallel sampling, beam search, and multi-turn agent conversations share physical memory blocks for identical token prefixes, laying the foundation for modern prompt caching runtimes such as RadixAttention.[7]

5. Eviction and Compression Strategies

When contexts expand to millions of tokens, physical GPU memory limits require dropping or compressing older activations:[8]

See also

References

  1. W. Kwon, Z. Li, S. Zhuang, S. Kang, Y. Sheng, L. Zheng, C. H. Yu, J. Gonzalez, H. Zhang, and I. Stoica, "Efficient Memory Management for Large Language Model Serving with PagedAttention," in Proceedings of the 29th ACM Symposium on Operating Systems Principles (SOSP), 2023, pp. 611–626. Free full text: https://arxiv.org/abs/2309.06180
  2. R. Pope, S. Douglas, A. Chowdhery, J. Devlin, J. Bradbury, A. Heek, K. Xiao, S. Agrawal, and J. Dean, "Efficiently Scaling Transformer Inference," in Proceedings of Machine Learning and Systems (MLSys), vol. 5, 2023. Free full text: https://arxiv.org/abs/2211.05102
  3. A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, L. Kaiser, and I. Polosukhin, "Attention Is All You Need," in Advances in Neural Information Processing Systems (NeurIPS), vol. 30, 2017, pp. 5998–6008. Free full text: https://arxiv.org/abs/1706.03762
  4. J. Ainslie, J. Lee-Thorp, M. de Jong, Y. Zemlyanskiy, F. Lebrón, and S. Sanghai, "GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints," in Proceedings of the 2023 Conference on Empirical Methods in Natural Language Processing (EMNLP), 2023, pp. 4895–4901. Free full text: https://arxiv.org/abs/2305.13245
  5. N. Shazeer, "Fast Transformer Decoding: One Write-Head is All You Need," arXiv preprint arXiv:1911.02150, 2019. Free full text: https://arxiv.org/abs/1911.02150
  6. DeepSeek-AI, "DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model," arXiv preprint arXiv:2405.04434, 2024. Free full text: https://arxiv.org/abs/2405.04434
  7. L. Zheng, L. Yin, Z. Xie, C. Sun, H. Huang, C. H. Yu, S. Cao, C. Perez, K. Yang, H. Zhu, L. Stoica, and J. E. Gonzalez, "SGLang: Efficient Execution of Structured Language Model Programs," arXiv preprint arXiv:2312.07104, 2023. Free full text: https://arxiv.org/abs/2312.07104
  8. G. Xiao, Y. Tian, B. Chen, S. Han, and M. Lewis, "Efficient Streaming Language Models with Attention Sinks," in International Conference on Learning Representations (ICLR), 2024. Free full text: https://arxiv.org/abs/2309.17453
  9. Z. Zhang, Y. Sheng, T. Zhou, T. Chen, L. Zheng, R. Cai, Z. Song, Y. Tian, C. Re, C. Barrett, K. Wang, and B. Chen, "H2O: Heavy Hitter Oracle for Efficient Generative Inference of Large Language Models," in Advances in Neural Information Processing Systems (NeurIPS), vol. 36, 2023, pp. 34661–34680. Free full text: https://arxiv.org/abs/2306.14048