KV Cache Explained: How LLMs Remember What They've Already Read
KV Cache Explained: How LLMs Remember What They've Already Read
You're chatting with an AI and ask it a long, detailed question. The model reads every single word — and then, to reply, it has to somehow "remember" everything it just processed while generating each new word one at a time.
Here's the thing: without a clever trick, the model would have to re-read and re-process your entire message from scratch for every single word it generates. That's like a writer re-reading a whole novel before typing each new sentence.
That clever trick is called the KV Cache.
The Problem It Solves
To understand KV Cache, you first need a one-minute crash course on how transformers "pay attention."
Inside every transformer layer, there's a mechanism called self-attention. For each token (word or word-piece) in the input, the model creates three vectors:
- Q (Query): "What am I looking for?"
- K (Key): "What do I offer?"
- V (Value): "What's my actual content?"
The model then computes attention scores by comparing the current token's Q against every other token's K. Those scores determine how much attention to pay to each V.
Here's the critical insight: when generating token #42, tokens #1 through #41 are already in the past. Their Keys and Values will never change. They're done. Fixed. Frozen.
Without any caching, the model re-computes all those K and V tensors from scratch at every generation step. For a 4,000-token context, that means 4,000 redundant computations per new token — multiplied across every layer.
What KV Cache Actually Does
KV Cache is dead simple in concept: store the K and V tensors for every past token, and reuse them.
Instead of recomputing:
Step 1: compute K, V for tokens 1–1 → generate token 2
Step 2: compute K, V for tokens 1–2 → generate token 3
Step 3: compute K, V for tokens 1–3 → generate token 4
...
With KV Cache:
Step 1: compute K, V for token 1 → cache it → generate token 2
Step 2: load cached K, V for 1, compute K, V for token 2 → cache it → generate token 3
Step 3: load cached K, V for 1–2, compute K, V for token 3 → cache it → generate token 4
...
Each step only does one new K, V computation instead of all previous ones. The speedup is massive — especially for long contexts.
Think of it like a conversation with a friend. You don't re-read all previous texts every time you send a new one. You pick up where you left off.
The Memory Tradeoff
Nothing in engineering is free. KV Cache trades compute for memory.
The memory cost of storing a KV Cache is roughly:
Memory = 2 × num_layers × num_heads × head_dim × seq_len × batch_size × bytes_per_element
Break that down for a typical model like LLaMA-2 7B (32 layers, 32 heads, head_dim=128, fp16):
- For a single request with 4K tokens: ~2 GB of VRAM just for the KV cache
- For a batch of 8 requests at 4K tokens each: ~16 GB — your entire GPU for some cards
This is why:
- Running longer context windows gets dramatically more expensive
- Serving many concurrent users is hard — each user occupies a chunk of VRAM
- Engineers constantly balance batch size vs context length
Optimizations That Make KV Cache Practical
Engineers have invented several clever tricks to reduce KV cache memory without sacrificing too much quality.
1. Multi-Query Attention (MQA)
Instead of each attention head having its own K and V, all heads share a single K and V. Only Q stays per-head.
Result: memory drops by a factor equal to the number of heads. The tradeoff? Slightly reduced model quality.
2. Grouped-Query Attention (GQA)
A middle ground: groups of heads share a K and V. Used in LLaMA-3, Mistral, Gemma, and most modern models.
If you have 32 query heads and 8 KV heads (groups of 4), memory is 4× smaller than standard multi-head attention, with minimal quality loss.
MHA: Q1 K1 V1 | Q2 K2 V2 | Q3 K3 V3 | Q4 K4 V4
GQA: Q1 Q2 K1 V1 | Q3 Q4 K2 V2
MQA: Q1 Q2 Q3 Q4 K V
3. KV Cache Quantization
Instead of storing each value in 16-bit float (fp16), compress to int8 or int4.
- INT8 → 2× memory reduction
- INT4 → 4× memory reduction
Libraries like bitsandbytes and llama.cpp support this natively. Quality barely degrades — the KV cache values are intermediate activations, and they're surprisingly resilient to quantization noise.
PagedAttention: Solving Fragmentation (vLLM)
Here's another problem nobody talks about enough: memory fragmentation.
Traditional KV cache allocates memory contiguously upfront — like reserving a full conference room before you know how many people will show up. If a request ends early, that memory sits wasted. If a request grows longer than expected, it can't use freed-up memory elsewhere.
PagedAttention, introduced by the vLLM project, solves this by borrowing a page from operating systems.
Your OS doesn't give programs one giant contiguous block of RAM. It gives them pages — small fixed-size chunks scattered across physical memory, mapped together logically.
PagedAttention does the same for KV cache:
- Allocate KV cache in fixed-size blocks (pages), not giant contiguous chunks
- Requests can use non-contiguous pages in GPU VRAM
- When a request finishes, its pages are freed and immediately reusable by other requests
- Multiple requests can even share pages for identical prompt prefixes (like a system prompt)
The result: dramatically better GPU utilization, higher throughput, and no wasted VRAM due to fragmentation.
Real-World Impact
Here's what KV Cache means in practice:
| Without KV Cache | With KV Cache |
|---|---|
| O(n²) compute per token generated | O(n) compute per token generated |
| Unusable for long contexts | Practical for 128K+ token contexts |
| Generation speed degrades with context | Near-constant generation speed |
For developers building LLM-powered apps:
- Streaming responses feel fast because each new token only costs one forward pass through the new token's K, V — not the full context
- Long system prompts are expensive — they permanently occupy KV cache VRAM for the duration of the request
- Context window ≠ free — every token in context uses VRAM, even tokens you "forgot about" pages ago
- Batching has limits — more concurrent users = more KV cache = less VRAM left for model weights
Putting It All Together
KV Cache is one of those optimizations that sounds simple but unlocks everything:
- Why is streaming fast? KV Cache — only the new token is computed fresh.
- Why do long conversations cost more? KV Cache — more tokens = more VRAM consumed.
- Why do models like LLaMA-3 use GQA? KV Cache — to cut VRAM usage without killing quality.
- Why is vLLM 10–24× faster than naive HuggingFace serving? PagedAttention — no wasted VRAM, no fragmentation.
The next time you chat with an LLM and it responds word-by-word almost instantly, that's the KV Cache quietly doing its job — remembering everything it's already read, so it never has to re-read it again.
Key Takeaways
- KV Cache stores Key and Value tensors from past tokens so they don't need to be recomputed at every generation step
- Without it, inference cost grows quadratically with context length; with it, it's linear
- The tradeoff: VRAM usage scales linearly with sequence length and batch size
- MQA and GQA reduce KV cache size by sharing K/V across attention heads
- KV quantization (INT8/INT4) further cuts memory at minimal quality cost
- PagedAttention (vLLM) eliminates fragmentation by treating VRAM like OS virtual memory pages
- Understanding KV cache is essential for anyone running, fine-tuning, or serving LLMs at scale
Understanding the internals of LLMs helps you build better AI applications — not just use them. Want to go deeper? Check out our tutorials on transformer architecture and attention mechanisms.