KV Cache is the inference memory structure that caches the Key/Value vectors of already-generated tokens during autoregressive decoding, avoiding recomputing attention over the full history at every step. Each decoding step only computes the new token's Q, attends against cached K/V, and appends new K/V to the cache. Memory formula (FP16, 2 bytes/element):
KV Bytes=2⋅2⋅nlayers⋅nkv_heads⋅dhead⋅s⋅b — the first 2 = one K and one V, the second 2 = 2 bytes per FP16 element,
s = sequence length,
b = batch size. Worked example (LLaMA-3 70B: 80 layers, 8 GQA KV heads,
dhead=128, 32K context, batch 8):
2×2×80×8×128×32768×8≈85.9 GB≈86 GB; the same model with MHA (64 KV heads) needs about
687 GB — exactly
64/8=8× more, the direct payoff of GQA. PagedAttention (vLLM): instead of allocating KV as one contiguous array sized for worst case, KV is sliced into fixed-size blocks (default 16 tokens per block, i.e.
16×nkv_heads×dhead elements) and a block table maps logical positions to physical blocks, paging like an OS. This eliminates internal fragmentation (static pre-allocation exceeding actual generated length) and external fragmentation (interleaved sequences of different lengths leaving unusable gaps), pushing effective memory utilization from roughly 60-80% for contiguous allocation toward ~100%.