What is stored, and deriving the size formula
Build the formula up rather than memorising it. For one token, at one layer, in one attention head, you store:
- a key vector of
head_dimnumbers, - a value vector of
head_dimnumbers.
That is 2 × head_dim numbers. The leading 2 is K and V — nothing more mysterious than that.
Now multiply out the dimensions you have:
x kv_heads each KV head has its own K and V (this is n_kv_heads, NOT n_heads)
x layers every layer attends independently and keeps its own cache
x seq_len one entry per position, and it only ever grows
x batch no sharing between sequences
x dtype_bytes 2 for fp16/bf16, 1 for fp8/int8
Giving:
kv_bytes = 2 * n_layers * n_kv_heads * head_dim * seq_len * batch * dtype_bytes
The term people get wrong is n_kv_heads. On a GQA model this is much smaller than n_heads, and using the wrong one inflates your estimate by the GQA ratio — 4× on Llama-3-8B, 8× on Llama-3-70B. Check the config, not the head count.
The most useful form is bytes per token per sequence, because it strips out the two things that vary at runtime:
bytes_per_token = 2 * n_layers * n_kv_heads * head_dim * dtype_bytes
For Llama-3-8B at fp16: 2 × 32 × 8 × 128 × 2 = 131,072 bytes = 128 KiB per token. For Llama-3-70B at fp16: 2 × 80 × 8 × 128 × 2 = 327,680 bytes = 320 KiB per token.
Commit those two numbers. From them everything else is one multiplication: an 8k-context 70B sequence is 320 KiB × 8192 = 2.5 GiB, and thirty-two of them is 80 GiB — an entire H100, holding nothing but cache.
Note what is not in the formula: n_heads, d_model, and vocab_size are all absent. The KV cache is governed by the KV side of attention alone, which is precisely why architectural attacks on it (MQA, GQA, MLA in Module 6) are so effective — they change one term in a product.
per token, per layer:
K [n_kv_heads=8, head_dim=128] ─┐
├─ 2 x 8 x 128 x 2 bytes = 4 KiB
V [n_kv_heads=8, head_dim=128] ─┘
x 80 layers = 320 KiB per token (Llama-3-70B)
x 8192 tokens = 2.5 GiB per sequence
x 32 sequences = 80 GiB <- one entire H100
REMEMBERkv_bytes = 2 × layers × kv_heads × head_dim × seq_len × batch × dtype_bytes, and every term is there for a reason you can name.