During generation, each new token needs the keys and values of all previous tokens. The cache stores them per layer so they are computed once instead of recomputed at every step, turning each step's cost from recomputing everything into one new token's work.
Memory estimate: 2 (K and V) x layers x sequence length x model dimension x batch size x bytes per element. Example: 32 layers, dimension 4096, 4,096 tokens, batch 1, FP16 comes to about 2 GB.
It grows linearly with context length and batch size, so for long contexts it, not the weights, often exhausts GPU memory.
Reduce it with multi-query or grouped-query attention (share K and V across heads), KV-cache quantization, paged attention (vLLM), and cache eviction.
Loading…