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 the difference between VRAM and system RAM. It also assumes you know roughly what a transformer layer and an attention head are. By the end you will be able to compute the KV cache size for a model and context length, and explain why the cache can matter as much as the weights.
What the cache stores
A language model generates text one token at a time. To produce each new token, every attention layer compares the new token against all earlier tokens in the conversation. For each earlier token, a layer needs two vectors:
- A key (K), which the new token is matched against.
- A value (V), which supplies the content that is mixed into the result.
These vectors depend only on the tokens before them, so they do not change as generation continues. Recomputing them for every new token would be wasteful. Instead, the runtime stores them in the KV cache and appends one new K and V per layer at each step.
The cache is a trade of memory for compute. Without it, the work per token would grow with the whole history. With it, the runtime computes K and V only for the newest token. In return, the cache grows with every token, and it must stay in fast memory because each generation step reads all of it.
The cache holds activations, not weights. It is allocated at load time for the context length you configure, and it is separate from the model file.
The formula
For each token in the context, the cache stores K and V in every layer:
bytes per token = 2 × layers × kv_heads × head_dim × bytes_per_value
cache bytes = bytes per token × context lengthThe 2 counts the K tensor and the V tensor. The terms mean:
- layers: the number of transformer layers.
- kv_heads: the number of key/value heads. Many modern models use grouped-query attention (GQA), where several query heads share one K/V head. This number can be much smaller than the number of query heads.
- head_dim: the size of each head's vector.
- bytespervalue: 2 for a 16-bit cache, which is the usual default.
You can read these numbers from the model's metadata or config file. In llama.cpp, the startup log prints values such as the layer count and the KV head count.
Worked example
Take an 8B-parameter model with 32 layers, 8 KV heads, and head size 128:
def kv_bytes_per_token(layers, kv_heads, head_dim, bytes_per_value=2):
# 2 = one K tensor and one V tensor per layer
return 2 * layers * kv_heads * head_dim * bytes_per_value
def kv_cache_gib(layers, kv_heads, head_dim, context, bytes_per_value=2):
return kv_bytes_per_token(layers, kv_heads, head_dim, bytes_per_value) * context / 2**30
per_token = kv_bytes_per_token(32, 8, 128)
print(f"{per_token // 1024} KiB per token")
for context in (4096, 8192, 32768, 131072):
gqa = kv_cache_gib(32, 8, 128, context)
mha = kv_cache_gib(32, 32, 128, context) # same model if it had 32 KV heads
print(f"context {context:>6}: {gqa:5.1f} GiB with 8 KV heads, {mha:5.1f} GiB with 32")The output is:
128 KiB per token
context 4096: 0.5 GiB with 8 KV heads, 2.0 GiB with 32
context 8192: 1.0 GiB with 8 KV heads, 4.0 GiB with 32
context 32768: 4.0 GiB with 8 KV heads, 16.0 GiB with 32
context 131072: 16.0 GiB with 8 KV heads, 64.0 GiB with 32Three things stand out:
- The cache is linear in context length. Doubling the context doubles the cache.
- At 8192 tokens, the cache is about 1 GiB. The Q4KM weights of this model are about 4.5 GiB (8 billion parameters at about 4.85 bits per weight). Together they need about 5.5 GiB before runtime overhead.
- At 131072 tokens, the cache is 16 GiB, about 3.5 times the weight file. A long context can cost more than the model itself.
The second column shows why GQA matters. A model with 32 KV heads would need four times as much cache at the same context length.
Where the cache lives
The cache is normally placed in the same memory as the layers it serves. If you offload all layers to the GPU, the cache goes to VRAM with them. If only some layers are offloaded, the cache for each layer follows its layer, so a split model also has a split cache. This is why raising the context length can push a model that fitted in VRAM into partial offload, which slows generation.
A practical budget for a fully offloaded model is:
VRAM needed ≈ weights + KV cache + compute buffers + overheadThe compute buffers hold temporary tensors used during a pass. Their size depends on the runtime and the batch size, and they can reach a few hundred MiB or more. Leave headroom of roughly 1 GiB or more rather than aiming at exactly 100% of VRAM. Your own measurements, from the load log or from a tool such as nvidia-smi, are better than any rule.
Controlling cache size
You have four levers, and each has a cost.
- Lower the context length. In llama.cpp this is the
-c(--ctx-size) option. This is the most direct fix, and it is free if you do not need the long context. A setting such as-c 131072allocates for the full length at load time, even if your prompts are short. - Quantise the cache. llama.cpp can store K and V in lower precision with
--cache-type-kand--cache-type-v(-ctk,-ctv). Aq8_0cache uses about 8.5 bits per value, roughly half of 16-bit. Aq4_0cache uses about 4.5 bits. Quantising the V cache generally requires flash attention to be enabled. Cache quantisation can reduce output quality, especially at 4 bits, and the K cache is usually more sensitive than the V cache. Test on your own prompts. - Choose a model with fewer KV heads. GQA models cost less per token than older full multi-head designs. Compare
kv_headsbefore you compare parameter counts. - Reduce parallel slots. A server that handles several requests at once divides its context among slots. In llama-server, a total context of 16384 with 4 parallel slots gives each request 4096 tokens. The total cache is set by the total context, not by each slot.
llama-server -m model-Q4_K_M.gguf -c 16384 -ngl 99 -ctk q8_0 -ctv q8_0 -fa onOn older llama.cpp builds, -fa is a plain flag without a value. Run llama-server --help to check your version.
Common errors
- Estimating memory from the file size alone. The file size covers the weights only. Add the cache and overhead.
- Using query heads instead of KV heads. If a model has 32 query heads and 8 KV heads, the cache uses 8. Using 32 overestimates by four times.
- Forgetting that the advertised context window is a maximum. A model that supports 128K tokens does not need 128K allocated. Set the context you actually use.
- Assuming the cache is free once allocated. Each generation step reads the whole filled cache, so a long context also slows generation, because more bytes are read per token. Chapter 9 covers why that read cost matters.
- Ignoring architecture variations. Some models use sliding-window attention in some layers, or compressed attention designs, and these store less per token than the formula predicts. The formula is an upper bound for standard attention. Check the runtime's startup log for the actual cache size it allocates.
Summary
The KV cache stores one K and one V vector per layer for every token in the context. Its size is 2 × layers × kv_heads × head_dim × bytes_per_value × context. It grows linearly with context, and for long contexts it can exceed the weights. You control it by setting the context length, using models with fewer KV heads, quantising the cache, and limiting parallel slots.
Exercise
A model has 40 layers, 8 KV heads, and head size 128. The cache is stored in 16-bit values. How large is the KV cache for a 32768-token context? What is it if you use a q8_0 cache, taking 1.0625 bytes per value?
Show answer
Bytes per token at 16-bit = 2 × 40 × 8 × 128 × 2 = 163,840 bytes (160 KiB). For 32768 tokens that is 163,840 × 32,768 = 5,368,709,120 bytes = 5.0 GiB. With q8_0, multiply by 1.0625 / 2 = 0.53125, giving about 2.66 GiB.
Exercise
You have a GPU with 8 GiB of VRAM. Your 8B model (32 layers, 8 KV heads, head size 128) uses 4.5 GiB for weights. You want about 1 GiB of headroom for compute buffers and overhead. What is the largest 16-bit-cache context length that fits fully on the GPU, and what is it with a q8_0 cache?
Show answer
Available for cache = 8 − 4.5 − 1 = 2.5 GiB. At 16-bit the cache costs 128 KiB per token (1 GiB per 8192 tokens), so 2.5 GiB allows 2.5 × 8192 = 20,480 tokens. With q8_0 the cost per token is about 68 KiB (128 × 0.53125), so the limit is roughly 2.5 × 2^30 / 69,632 ≈ 38,600 tokens. In practice, round down and confirm with the load log.