KV Cache Optimization: How to Extend Your LLM Context Window
The KV cache is what makes long-context LLM inference possible — and what limits it. Understanding and optimizing it is essential for anyone running LLMs locally with large contexts.
What Is the KV Cache?
During inference, the transformer computes Key and Value matrices for every token in the context. To avoid recomputing these for past tokens at each step, they're cached in VRAM — the KV cache. It grows linearly with context length and can consume more memory than the model itself at long contexts.
KV Cache Size Formula
For Llama 3 8B at 128K context (fp16):
= 2 × 32 × 8 × 128 × 131072 × 2 = ~17 GB
This is why 128K context requires so much VRAM. LLMHardware.io's context length calculator helps you find the max context your hardware supports for any model.
Reducing KV Cache Memory
1. KV Cache Quantization
# llama.cpp: quantize KV cache to int8 (half the memory, minimal quality loss)
./llama-server -m model.gguf --ctx-size 131072 --cache-type-k q8_0 --cache-type-v q8_0
Q8 KV cache cuts memory by 50% with negligible quality impact. Q4 cuts by 75% with slight degradation on very long contexts.
2. Grouped Query Attention (GQA)
Models using GQA (Llama 3, Mistral, Qwen2) share KV heads across multiple query heads, reducing KV cache size by the GQA ratio (typically 4–8x). When choosing models, prefer GQA architectures for long-context work.
3. Flash Attention
# vLLM (enabled by default)
python -m vllm.entrypoints.openai.api_server --model Qwen/Qwen2.5-7B-Instruct --enable-chunked-prefill --max-num-batched-tokens 8192
Flash Attention reduces peak VRAM usage during prefill by computing attention in chunks without materializing the full attention matrix.
Practical Context Length vs Hardware
| GPU | Max Context (7B, Q4) | Max Context (7B, Q8 KV) |
|---|---|---|
| RTX 3060 12GB | 32K | 64K |
| RTX 4090 24GB | 96K | 128K+ |
| Mac Studio M4 Ultra 192GB | 512K+ | 1M+ |
Comments
Post a Comment