The KV cache
Decode makes one token per step. The KV cache keeps each step cheap.
Redoing old work
To make a new token, attention looks back at every earlier token's keys and values. Without help, each step would work out those keys and values again, for all earlier tokens. Old tokens never change, so this work is wasted, and it grows with the answer.
Caching keys and values
The KV cache saves each token's keys and values, in every layer, the first time they are made. Each step then computes Q, K and V only for the newest token and reads the rest. Queries are not kept, because an old query is never used again. The output is the same; you spend memory to save math.
How the cache grows
Every token adds an entry in every layer, for every request that is running. Entries stay in GPU memory until the request finishes, so long chats and many users fill it.
Cache size per token
Attention runs as several heads (not the same as the head at the end of the model); each head's key or value is a list of numbers (the head size, often 128). The heads that keep a key and value are the KV heads; in a plain model, that is every head. Bytes per token = 2 (K and V) × layers × KV heads × head size × bytes per number. With 32 layers, 32 heads, size 128 and 2 bytes, that's about 0.5 MB per token, so a 2,000-token chat needs about 1 GB.
Sharing K/V heads (GQA and MQA)
With grouped-query attention (GQA), a group of query heads shares one K/V head. 32 query heads with 8 K/V heads means a cache 4 times smaller. Multi-query attention (MQA) shares a single K/V head across all of them: smallest cache, with a bit more risk to quality. It is part of the model's design.
Remember
- The cache keeps old tokens' K and V, so each step only does the new token.
- It grows with every token, every layer, every running request.
- Bytes per token = 2 × layers × KV heads × head size × bytes.
- Fewer K/V heads (GQA, MQA) means a smaller cache.