Skip to content

KV Cache Management — Context Length Trade-Offs

The KV cache is the term people forget, and it is the reason a model that loaded fine OOMs twenty minutes into a long conversation.

The KV cache is the term people forget, and it is the reason a model that loaded fine OOMs twenty minutes into a long conversation. It grows linearly with context length and can rival the weights themselves (codingprotocols.com). Measured BF16 KV cache sizes (localaimaster.com):

Context Llama 3.1 8B Llama 3.1 70B Llama 3.1 405B
4K 0.5 GB 1.3 GB 3.0 GB
32K 4 GB 10.7 GB 24 GB
128K 16 GB 43 GB 96 GB
200K 25 GB 67 GB 150 GB

For Llama 3.1 70B at 131K the KV cache alone is 43 GB per request — bigger than the model weights at FP8 (localaimaster.com). Per-token cost: 2 × 80 layers × 8 KV heads × 128 head_dim × 2 bytes = ~320 KB/token for Llama 3.1 70B with GQA; without GQA (full MHA) that is 8× larger, 86 GB at 32K — which is why GQA is effectively mandatory on modern models.

Practical consequence: raising OLLAMA_CONTEXT_LENGTH from 4096 to 32768 is not free. A 7B at Q4_K_M is only ~4.7 GB of weights, but a 32K window adds ~4 GB of KV (promptquorum.com).

Architectural KV reduction (localaimaster.com):

Technique Reduction Quality loss Examples
MHA (baseline) 1× 0% GPT-2, original Llama
MQA up to num_heads (e.g. 32×) 1–2% PaLM, Falcon
GQA num_heads / num_kv_heads (~8×) <0.5% Llama 3, Qwen 2.5, Mistral
MLA (low-rank K/V) 5–10× (~50 KB/token) <0.5% DeepSeek V2/V3
CLA (cross-layer) 2–3× <0.5% Hunyuan-Large

DeepSeek V3's MLA compresses KV to ~50 KB/token (1.6 GB at 32K), which is what makes 671B at 128K context viable at all.

Options that exist in 2026: PagedAttention (vLLM/SGLang/TensorRT-LLM allocate KV in fixed-size pages instead of a contiguous block, killing fragmentation and allowing sharing), prefix/radix caching (reuse KV for shared system prompts), and quantized KV cache (FP8/INT8/INT4). llama.cpp now supports cache-type quantization such as asymmetric q8/q4 KV specifically to keep VRAM in check at long context (llama.cpp discussion #23470), and a paged KV cache + scheduler is in active design for the same engine (llama.cpp discussion #21961). Quality impact of KV quantization is small but measurable — test q8 before dropping to q4.

Sources

Date: 2026-10-09