The key-value, or KV, vectors are used to calculate attention scores, and for autoregressive models they are calculated every time because the model predicts one token at a time. A KV cache stores these calculations so they can be reused without recomputing them, which makes generation faster, but the cache grows with every token and can occupy a significant portion of memory. Work out the size before you start a long conversation, so you know whether the cache will fit or whether you need a quantized or offloaded cache.
What you need
- The model config: layers, attention heads and head size
- The context length you plan to use, in tokens
- The precision of the cache, usually 2 bytes per value in FP16
Step 1: Count the numbers per token
For each layer, the cache stores one key and one value vector per attention head. Multiply layers by heads by head size by 2, for keys and values, to get the numbers stored per token.
Step 2: Multiply by tokens and bytes
Multiply the per-token numbers by the context length and by the bytes per value, 2 for FP16. That is the cache size in bytes; divide by a billion for gigabytes.
Step 3: Compare with free GPU memory
Subtract the model weights and a margin for activations from your GPU memory, and check the cache fits in what remains. If it does not, shorten the context, quantize the cache, or offload it.
Worked example: synthetic KV cache size for one model
The table below is a synthetic example. It shows the expected result of sizing a KV cache; no model was run.
| Setting | Value | Cache size |
|---|---|---|
| Layers x heads x head size | 32 x 32 x 128 | 131,072 numbers per token |
| Context | 32,768 tokens | About 8.6 GB in FP16 |
| GPU free after weights | 10 GB | Fits |
| Context 131,072 tokens | 4x longer | About 34 GB – does not fit |
Expected result (UNTESTED). the cache fits at 32k tokens but not at 131k tokens, so the longer context needs a quantized or offloaded cache. This check was not run live; the table shows the expected result for the synthetic example.
Limits
- The cache grows with every generated token, so a conversation that fits at the start can run out of memory later.
- Models with sliding window attention stop the cache growing once the window is full, which caps the size.
- Offloading the cache to CPU saves GPU memory but costs some generation throughput.
- The default dynamic cache grows as generation progresses; a fixed-size static cache pre-allocates its maximum size instead.
