KV Cache

Definition

The KV cache is the per-sequence store of already-computed key and value tensors for every past token, kept in HBM so autoregressive decode does not recompute them. At decode step the new token attends to all previous tokens’ K/V; caching turns the recompute into reads. It is the central data structure of LLM serving and, at realistic batch sizes, the binding memory constraint — not weights, not FLOPs.

Key math / How it works

For layers, key/value heads, head dim , sequence length , batch , and bytes/element, the cache holds both K and V:

Worked (Llama-3-70B-style): , (GQA), , FP16 ().

  • Per token, all layers: B KiB/token.
  • One 8192-token sequence: GiB.
  • Batch of 32: GiB — an entire H100, on top of 140 GB of FP16 weights. Full MHA () would be 8× worse.

GQA/MQA reduction. The formula scales linearly in , so the cheapest lever is fewer KV heads. MQA (, arXiv:1911.02150) shares one K/V head across all query heads; GQA (, arXiv:2305.13245) interpolates, e.g. 64 query heads → 8 KV groups = 8× smaller cache with negligible quality loss. This is why every modern LLM ships GQA.

Why it matters

Decode reads the whole cache every step, so cache size sets both the memory ceiling (how many concurrent sequences fit → decode batch → throughput) and a bandwidth floor on decode latency. It grows with every concurrent sequence and every generated token, so managing it well (paged-attention, KV quantization, GQA) is the highest-leverage serving optimization. See the roofline: decode’s arithmetic intensity is tiny, so the cache — not compute — is the wall.

Taught in

See also