Sub topic 6
The KV cache and why context length costs memory
This chapter assumes you can estimate weight memory from parameter count and bits per weight, and that you know what a layer and an attention head are at a high level. It covers the second large memory cost of a local model: the KV cache.
What the cache stores
A transformer model generates text one token at a time. For each new token, every attention layer compares that token against all earlier tokens. Each earlier token produces two vectors in each layer: a key (K) and a value (V). These vectors do not change once computed, so the runtime stores them instead of recomputing them. That store is the KV cache.
The weights are fixed in size for a given file. The KV cache starts empty and grows with every token in the context, both your prompt and the model's output.
The formula
Per token, each layer stores one K and one V vector for every KV head. So:
KV cache bytes = 2 × layers × KV heads × head size × context tokens × bytes per value
The leading 2 stands for K plus V. A 16-bit cache uses 2 bytes per value. The cost grows linearly with context length: double the context and the cache doubles.
Many recent models use grouped-query attention (GQA). They have fewer KV heads than attention heads, which shrinks the cache. Always use the KV head count from the model's metadata, not the attention head count.
def kv_cache_gib(layers, kv_heads, head_dim, context, bytes_per_value=2):
# 2 = one K tensor and one V tensor per layer
return 2 * layers * kv_heads * head_dim * context * bytes_per_value / 2**30
# 32 layers, 8 KV heads, head size 128, 16-bit cache
for ctx in (2048, 8192, 32768, 131072):
print(f"{ctx:>6} tokens: {kv_cache_gib(32, 8, 128, ctx):.2f} GiB")This prints 0.25, 1.00, 4.00 and 16.00 GiB. An 8B model at Q4KM has weights of about 4.5 GiB. At 8192 tokens the cache is small next to that. At 131072 tokens it is more than three times the size of the weights.
Combining with the weights
Add the cache to the weight estimate:
def weights_gib(params_billion, bits_per_weight):
return params_billion * 1e9 * bits_per_weight / 8 / 2**30
def kv_cache_gib(layers, kv_heads, head_dim, context, bytes_per_value=2):
return 2 * layers * kv_heads * head_dim * context * bytes_per_value / 2**30
w = weights_gib(8.0, 4.85)
kv = kv_cache_gib(layers=32, kv_heads=8, head_dim=128, context=8192)
print(f"weights {w:.1f} GiB + KV cache {kv:.1f} GiB = {w + kv:.1f} GiB before runtime overhead")The result is about 4.5 GiB plus 1.0 GiB, or 5.5 GiB. The runtime also needs working buffers for computation, so leave some headroom beyond this figure.
Common errors
- Using the model's maximum context in the estimate by accident. A model may advertise 128k tokens, but the memory cost applies to the context size you configure, not the advertised limit. Check the context setting in your runtime.
- Using attention heads instead of KV heads. This overstates the cache, sometimes by a factor of four or eight.
- Forgetting that the cache scales with context, not with the weights' quantisation. A 4-bit weight file still has a 16-bit cache by default.
- Treating the cache as optional. Without it, generation would recompute every earlier token at each step and become far slower.
Exercise
A model has 40 layers, 8 KV heads and a head size of 128. The cache uses 16-bit values. How large is the KV cache at a 16384-token context?
Show answer
2 × 40 × 8 × 128 × 16384 × 2 bytes = 2,684,354,560 bytes, which is 2.5 GiB. Doubling the context to 32768 tokens would double this to 5 GiB.
Exercise
Your model weights take 9 GiB and your GPU has 12 GiB of VRAM. The KV cache for your planned context is 4 GiB. Does it fit?
Show answer
No. The total is 13 GiB, which already exceeds 12 GiB before runtime overhead. You could shorten the context, use an 8-bit cache, or choose a smaller quantisation.