The KV Cache

Why chatbots stay fast as they write, and why they eat so much GPU memory.

🔴 advanced5 min readinferencemust-know
When a model writes text one word at a time, each new word needs to look back at all the words before it. Without a cache, the model would recompute the same information for those earlier words at every single step. The KV cache stores each word's keys and values the first time they are calculated and reuses them, so each step only does the work for the newest word. Generation becomes much faster, but the cache grows with every word and can fill the GPU's memory.

The Autoregressive Bottleneck Without KV Cache

In Causal Self-Attention:

Attention(Q,K,V)=Softmax(QKTdk)V\text{Attention}(Q, K, V) = \text{Softmax}\left( \frac{Q K^T}{\sqrt{d_k}} \right) V

At step t=100t = 100, we generate token 100. To compute attention for token 100, we need Key vectors K1..100K_{1..100} and Value vectors V1..100V_{1..100}.

  WITHOUT KV CACHE (Redundant Matrix Re-computation)
  Step 1: Compute [T1]
  Step 2: Re-compute [T1], Compute [T2]
  Step 3: Re-compute [T1], Re-compute [T2], Compute [T3]  <-- O(N³) Waste!

  WITH KV CACHE (Append to VRAM Memory)
  Step 1: Compute [T1] -> Store K1, V1 in VRAM
  Step 2: Fetch K1, V1 -> Compute [T2] -> Append K2, V2 to VRAM
  Step 3: Fetch K1..2, V1..2 -> Compute [T3] -> Append K3, V3 to VRAM  <-- O(N²) Efficient!

KV Cache VRAM Formula

For a batch of BB sequences, sequence length LL, LlayersL_{\text{layers}} layers, HkvH_{\text{kv}} Key-Value heads, and head dimension DheadD_{\text{head}}:

KV Cache Memory (Bytes)=2×B×L×Llayers×Hkv×Dhead×BytesPerElement\text{KV Cache Memory (Bytes)} = 2 \times B \times L \times L_{\text{layers}} \times H_{\text{kv}} \times D_{\text{head}} \times \text{BytesPerElement}

Concrete Example (LLaMA-3 70B FP16)

KV Cache VRAM=32×8192×328 KB≈86.0 GB of VRAM!\text{KV Cache VRAM} = 32 \times 8192 \times 328\text{ KB} \approx \mathbf{86.0\text{ GB of VRAM!}}

The KV Cache size quickly exceeds the base model weights size at high batch sizes and long contexts!

Architectural Mitigations

  Multi-Head Attention (MHA)            Grouped-Query Attention (GQA)           Multi-Query Attention (MQA)
  N_q Query Heads, N_kv = N_q KV Heads   N_q Query Heads, N_kv = 8 KV Heads      N_q Query Heads, N_kv = 1 KV Head
  [Q1 Q2 Q3 Q4] [K1 K2 K3 K4]            [Q1 Q2 Q3 Q4] ──► [K1]                 [Q1 Q2 Q3 Q4] ──► [K1]
  (Large KV Cache)                       (8x Memory Reduction! - LLaMA-3)       (32x Memory Reduction!)

Say this out loud

"The KV Cache stores Key and Value projection tensors of past tokens in GPU VRAM during autoregressive generation. This eliminates redundant self-attention re-computations, reducing generation complexity per token from O(N²) to O(N). However, KV cache VRAM footprint scales linearly with context length and batch size, requiring Grouped-Query Attention (GQA) and PagedAttention to fit long context serving in GPU memory."

Follow-ups to expect

Check yourself

Question 1 of 3

Why does autoregressive token generation require re-computing attention scores over historical tokens if KV Cache is NOT used?

More in NLP & Transformers

See all →
The Attention Mechanism5 minTransformer Architecture5 minTokenization & BPE5 min