During autoregressive generation, the model produces one token at a time. Naively, you'd run the whole sequence through every layer for each new token — O(n²) compute per token, prohibitively slow. The KV-cache avoids this. The idea is mechanical and beautiful: K and V vectors for past tokens never change once computed, so cache them.
How it works
At step t, you only need to compute Q for the new token. K and V for the new token are computed and appended to the cache. Attention for the new token is then a single matmul against the cached K and V — Q has shape (1, d_head), K_cache has shape (t, d_head), so the score is shape (1, t) and the output is (1, d_v). Per-token compute drops from O(n²) to O(n).
The cost: memory
The cache stores 2 × n_layers × n_kv_heads × seq_len × d_head × bytes_per_param bytes. For Llama 3.3 (70B, 80 layers, 8 KV heads, d_head=128) at 128K context in FP16: roughly 32 GB. This is huge — often comparable to or larger than the model weights. It's the main reason inference at long context is hard, and the main reason GQA exists.