NLP & Transformers

The KV Cache

Trading GPU VRAM memory for compute by caching historical Key and Value tensors during autoregressive generation.

🔴 advanced5 min readinferencemust-know
The Key-Value (KV) Cache avoids redundant self-attention re-computation during autoregressive LLM token generation. Because historical tokens do not change during causal generation, their Key (KK) and Value (VV) projection matrices are computed once and stored in GPU VRAM. At step tt, the LLM computes Q,K,VQ, K, V for token tt only, appends Kt,VtK_t, V_t to the KV cache, and evaluates attention over cached keys and values. This reduces generation time complexity per token from O(N2)O(N^2) to O(N)O(N), but creates a massive GPU VRAM memory bottleneck.

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