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.

Runs on a CPU or in the browser✦ Interactive~25 min

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 tt, 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:

KVtoken  =  2⏟K, V×nlayers×nkv-heads×dhead×b⏟bytes/value\text{KV}_{\text{token}} \;=\; \underbrace{2}_{K,\,V} \times n_{\text{layers}} \times n_{\text{kv-heads}} \times d_{\text{head}} \times \underbrace{b}_{\text{bytes/value}}

For Mistral 7B (32 layers, 8 KV heads, head dimension 128, FP16):

2×32×8×128×2  =  131,072 bytes  ≈  131 KB per token2 \times 32 \times 8 \times 128 \times 2 \;=\; 131{,}072 \text{ bytes} \;\approx\; \mathbf{131\ KB\ per\ token}

131 KB doesn’t sound like much. Multiply it by the context length, though:

Context (tokens)KV per user
1K0.13 GB
4K0.54 GB
16K2.15 GB
32K4.29 GB
128K17.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:

max users  =  ⌊MGPU−Mweights−MoverheadKVtoken×Lcontext⌋\text{max users} \;=\; \left\lfloor \frac{M_{\text{GPU}} - M_{\text{weights}} - M_{\text{overhead}}}{\text{KV}_{\text{token}} \times L_{\text{context}}} \right\rfloor
  • At 4K context: 57.5 GB / 0.54 GB≈57.5 \text{ GB} \,/\, 0.54 \text{ GB} \approx 107 users
  • At 16K context: 57.5 GB / 2.15 GB≈57.5 \text{ GB} \,/\, 2.15 \text{ GB} \approx 26 users

Quadrupling the context cuts concurrency by four. Nothing about the model changed.

Play with it

Model
GPU
Weights
KV cache
KV / token = 2 (K,V) × 32 layers × 8 kv-heads × 128 dim × 2 B = 131 KB · per user @ 4K = 0.54 GB
GPU memory: A100-80GBused 65.4 GB / 80 GB
weights
weights 14.5 GB overhead 8.00 GB KV cache 42.9 GB (80 × 0.54 GB)┆ capacity 80 GB
Max users at this context
107
Memory left for KV
57.5 GB
Status
Fits
fig. 9.1The capacity equation, live. Each stripe in the blue segment is one user's KV cache. Push past the red line and the GPU runs out of memory.

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:

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.

labs/m09/9.1/kv_cache.py
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)
Terminal window
pip install numpy
python labs/m09/9.1/kv_cache.py
output
Mistral 7B: KV per token = 131,072 B ≈ 131 KB
NumPy check: 256 tokens -> 33,554,432 B (matches formula)
...
Mistral 7B @ 4K -> 107 users
Mistral 7B @ 16K -> 26 users

Sources

Check your understanding

0 / 4 answered
  1. 1.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. 2.You double the context length you serve. With everything else fixed, the maximum number of concurrent users…

  3. 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. 4.Why does a bigger KV cache also make each decode step slower, not only reduce capacity?