L3 Advanced · Module 9: KV cache engineering
9.1How big is the KV cache? The capacity equation
Every token a model has seen leaves keys and values behind in GPU memory. This chapter counts those bytes and turns the count into the number of users one GPU can serve.
By the end you will be able to
- ✓Derive KV-cache bytes per token from a model's config
- ✓Write the capacity equation and use it to size a deployment
- ✓Explain why GQA, FP8 KV and long contexts move the answer so much
To generate token , attention needs the key and value vectors of every earlier token, in every layer. Recomputing them at each step would make generation quadratic, so the engine computes them once and keeps them in GPU memory. That stored state is the KV cache, and it is usually the thing that decides how many people one GPU can serve at once.
Where the bytes come from
At each layer, a token contributes one key and one value vector for every KV head. Count them up:
For Mistral 7B (32 layers, 8 KV heads, head dimension 128, FP16):
131 KB doesn’t sound like much. Multiply it by the context length, though:
| Context (tokens) | KV per user |
|---|---|
| 1K | 0.13 GB |
| 4K | 0.54 GB |
| 16K | 2.15 GB |
| 32K | 4.29 GB |
| 128K | 17.18 GB |
The GPU memory budget
An A100-80GB serving Mistral 7B in FP16 splits its memory three ways:
- Weights: 7.24 B parameters × 2 bytes ≈ 14.5 GB. This is fixed.
- Overhead: activations, the CUDA context, allocator fragmentation. Roughly 8 GB here.
- KV cache: everything left, about 57.5 GB. This is the pool that concurrent requests share.
The capacity equation
Divide the leftover memory by what one user costs:
- At 4K context: 107 users
- At 16K context: 26 users
Quadrupling the context cuts concurrency by four. Nothing about the model changed.
Play with it
Why this decides speed too, not only capacity
During decode, every step reads the whole KV cache of every sequence in the batch, plus all the weights, to produce one token per sequence. Decode is memory-bandwidth-bound (see 3.3 The roofline model), so every extra KV byte is an extra byte of HBM traffic on every step.
That is why so many later chapters attack the KV cache:
- Store fewer heads: 9.2 MQA, GQA and MLA
- Waste less of it: 9.3 PagedAttention (naive engines reserve the maximum context for every request)
- Use fewer bits: 9.6 KV-cache quantization
- Keep fewer tokens: 9.7 attention sinks and eviction
- Share it: 10.4 prefix caching
Lab: count the bytes yourself 🟢
The lab computes the formula, then allocates a real FP16 KV cache in NumPy and checks that the byte count matches.
def kv_bytes_per_token(m: Model, kv_bytes: float = 2) -> float: # 2 tensors (K and V) per layer, each kv_heads x head_dim values return 2 * m.layers * m.kv_heads * m.head_dim * kv_bytes
def max_users(m: Model, gpu_gb: float, context: int, weight_bytes: float = 2, kv_bytes: float = 2, overhead_gb: float = 8) -> int: weights = m.params_b * 1e9 * weight_bytes free = gpu_gb * GB - weights - overhead_gb * GB if free <= 0: return 0 return int(free // (kv_bytes_per_token(m, kv_bytes) * context))
def measure_with_numpy(m: Model, tokens: int) -> int: """Allocate a real FP16 KV cache (one sequence) and count its bytes.""" cache = [ (np.zeros((m.kv_heads, tokens, m.head_dim), dtype=np.float16), # K np.zeros((m.kv_heads, tokens, m.head_dim), dtype=np.float16)) # V for _ in range(m.layers) ] return sum(k.nbytes + v.nbytes for k, v in cache)pip install numpypython labs/m09/9.1/kv_cache.pyMistral 7B: KV per token = 131,072 B ≈ 131 KBNumPy check: 256 tokens -> 33,554,432 B (matches formula)... Mistral 7B @ 4K -> 107 users Mistral 7B @ 16K -> 26 usersSources
Check your understanding
0 / 4 answered1.A model has 40 layers, 8 KV heads, head dimension 128, and stores its KV cache in FP16. How many bytes of KV does one token take?
2.You double the context length you serve. With everything else fixed, the maximum number of concurrent users…
3.Why does a model with grouped-query attention (8 KV heads, 32 query heads) fit about 4× more users than its multi-head-attention twin?
4.Why does a bigger KV cache also make each decode step slower, not only reduce capacity?