A KV cache stores the attention keys and values of every token already processed, so an autoregressive transformer computes them once, not at every step. Each new token adds one row to the cache and attends over the stored rows. The price is memory that grows with context length and batch size.
Origins and the memory formula
Caching keys and values is standard in incremental decoding. Shazeer's 2019 paper named the bottleneck: repeatedly loading the large key and value tensors costs memory bandwidth.
Per token the cache holds 2 x layers x KV heads x head dim x bytes. Take the 8B model in the Llama 3.1 config. It lists 32 layers and 8 KV heads. Head dim is 128 and the dtype is bfloat16. That gives 131,072 bytes per token. A full 131,072-token context then needs 16 gigabytes.
Methods that shrink and manage it
Multi-query attention shares one KV head across all query heads. GQA in 2023 keeps a middle number of KV heads. Llama 3.1 gives each group of four query heads one KV head.
PagedAttention in vLLM stores the cache in fixed blocks like virtual memory pages. It reports 2-4x throughput. Prefix caching reuses blocks when requests share a prompt start. RadixAttention does this with a tree.
KIVI quantizes keys per channel and values per token to 2 bits, for 2.6x less peak memory. DeepSeek-V2 packs keys and values into one latent vector and cuts the cache by 93.3 percent.
In image and video models
Most image generators refine patches in parallel via diffusion transformers, so they keep no such store. Step reuse is a separate idea. KV caches appear where output comes token by token or frame by frame.
LlamaGen applies next-token prediction to image tokens. VAR predicts whole scales, each attending to cached coarser ones. Among video models, CausVid makes a diffusion transformer causal and streams at 9.4 FPS using KV caching.
Sources
- Shazeer, multi-query attention, 2019: origin of the bandwidth argument.
- GQA paper, 2023 and PagedAttention paper, 2023: head sharing and block paging.
- KIVI, DeepSeek-V2 and CausVid: quantization, latent compression, streaming video.