KV Cache Explained

Volume III, Chapter 15 — Part I. Autoregressive inference optimization: prefill vs. decode phases, KV cache memory analysis, MQA/GQA, and complexity reduction from quadratic to linear per generated token.

Intermediate

Prerequisites

Table of Contents

  1. Learning Objectives
  2. Prerequisites
  3. Notation
  4. Core Intuition
  5. Autoregressive Generation
  6. The Redundancy Problem
  7. KV Cache Mechanism
  8. Prefill vs. Decode Phases
  9. Memory Analysis
  10. Multi-Query and Grouped-Query Attention
  11. Worked Examples
  12. Connection to the Broader Curriculum
  13. Common Pitfalls and Misconceptions
  14. Research Perspective
  15. Summary of Takeaways
  16. Exercises

Learning Objectives

After reading this chapter, you should be able to:

  1. Describe autoregressive generation as iterative Self-Attention over growing sequences.
  2. Explain why naive recomputation costs O(t2)O(t^2) per step tt.
  3. Define the KV cache and reduce per-token cost to O(t)O(t) attention over cached keys/values.
  4. Compute KV cache memory: 2×B×L×H×n×dk×bytes2 \times B \times L \times H \times n \times d_k \times \text{bytes}.
  5. Compare MHA, MQA, and GQA cache requirements.

Prerequisites


Notation

  • t,nt, n — Current decode step and total sequence length
  • Kcache,Vcache\mathbf{K}_{\mathrm{cache}}, \mathbf{V}_{\mathrm{cache}} — Cached key and value tensors
  • L,H,dkL, H, d_k — Layers, heads, and key dimension
  • BB — Batch size
  • MKVM_{\mathrm{KV}} — Total KV cache memory
  • pp — Prompt (prefill) length

Core Intuition

LLMs generate text one token at a time. At step tt, Self-Attention needs all previous keys and values. Without caching, recomputing K/V for tokens 1,,t1, \ldots, t at every step wastes O(t2)O(t^2) work across generation.

The KV cache stores computed ki,vi\mathbf{k}_i, \mathbf{v}_i for i<ti < t; each new step computes only the new token's Q, K, V and attends over the cache. This is essential for practical inference latency.

Series context. Volume III, Chapter 15 (Inference).

KV-Cache in Autoregressive Generation

ThecatsatonthematK/V Cache (grows each step)K1V1K2V2K3V3Step 4: attend to 4 keys (not 4²)~83% compute saved vs re-computing all K,V
Position
3
Explore: KV-cache stores key/value projections from prior tokens. Each new token only computes its own Q,K,V and attends to cached K,V — reducing per-step cost from O(n²) to O(n).

Autoregressive Generation

Definition 1 (Autoregressive Model).

p(x1,,xn)=t=1npθ(xtx<t).(1)p(x_1, \ldots, x_n) = \prod_{t=1}^{n} p_\theta(x_t \mid x_{<t}). \tag{1}

Definition 2 (Generation Step). At step tt, compute logits from x1:tx_{1:t}, sample xt+1x_{t+1}.

Each step runs full Transformer forward pass on sequence of length tt.


The Redundancy Problem

Proposition 1 (Naive Cost). At decode step tt, computing K,VRt×dk\mathbf{K}, \mathbf{V} \in \mathbb{R}^{t \times d_k} for all positions costs O(td)O(t \cdot d) per layer. Summing over generation steps t=1,,nt = 1, \ldots, n yields total attention-related work O(n2d)O(n^2 d) per layer.

Proof. At step tt, a full forward pass processes a sequence of length tt. Key and value projections require O(tddk)=O(td)O(t \cdot d \cdot d_k) = O(t d) operations per layer (with dk=O(d)d_k = O(d)). Summing:

t=1nO(td)=O(dn(n+1)/2)=O(n2d).(2)\sum_{t=1}^{n} O(t d) = O(d \cdot n(n+1)/2) = O(n^2 d). \quad \blacksquare \tag{2}

Observation. Keys and values for positions 1,,t11, \ldots, t-1 are identical to their values at step t1t-1 — weights are frozen during inference and prior token representations do not change. Recomputing them at every step is pure redundancy.


KV Cache Mechanism

Definition 3 (KV Cache). Store per layer:

Kcache=[k1;;kt]Rt×dk,Vcache=[v1;;vt]Rt×dv.(2)\mathbf{K}_{\text{cache}} = [\mathbf{k}_1; \ldots; \mathbf{k}_t] \in \mathbb{R}^{t \times d_k}, \quad \mathbf{V}_{\text{cache}} = [\mathbf{v}_1; \ldots; \mathbf{v}_t] \in \mathbb{R}^{t \times d_v}. \tag{2}

Decode step for new token xt+1x_{t+1}:

  1. Compute qt+1,kt+1,vt+1\mathbf{q}_{t+1}, \mathbf{k}_{t+1}, \mathbf{v}_{t+1} (single token only)
  2. Append: Kcache[Kcache;kt+1]\mathbf{K}_{\text{cache}} \leftarrow [\mathbf{K}_{\text{cache}}; \mathbf{k}_{t+1}]
  3. Attention: softmax(qt+1KcacheT/dk)Vcache\text{softmax}(\mathbf{q}_{t+1} \mathbf{K}_{\text{cache}}^T / \sqrt{d_k}) \mathbf{V}_{\text{cache}}

Theorem 1. Per decode step: O(tdk)O(t \cdot d_k) attention vs. O(t2)O(t^2) for full recomputation matrix operations at length tt.


Prefill vs. Decode Phases

Definition 4 (Prefill). Process prompt x1:px_{1:p} in parallel — compute and fill entire cache at once. Cost: O(p2d)O(p^2 d) — one-time.

Definition 5 (Decode). Generate tokens p+1,,np+1, \ldots, n one at a time using cache. Cost per token: O(td)O(t \cdot d) where tt grows.

Proposition 2. Prefill is compute-bound (parallel); decode is memory-bandwidth-bound (sequential, cache-heavy).


Memory Analysis

Definition 6 (KV Cache Memory).

MKV=2×B×L×H×n×dk×bytes,(3)M_{\text{KV}} = 2 \times B \times L \times H \times n \times d_k \times \text{bytes}, \tag{3}

where BB = batch size, LL = layers, HH = heads, nn = sequence length, factor 2 for K and V.

Example. Llama 70B: L=80L=80, H=64H=64, dk=128d_k=128, n=4096n=4096, FP16:

MKV=2×80×64×4096×128×210.7 GB.(4)M_{\text{KV}} = 2 \times 80 \times 64 \times 4096 \times 128 \times 2 \approx 10.7 \text{ GB}. \tag{4}

Often exceeds weight memory for long contexts.


Multi-Query and Grouped-Query Attention

Definition 7 (MQA). Share single K,V\mathbf{K}, \mathbf{V} across all heads; only Q is per-head. Cache reduced by factor HH.

Definition 8 (GQA). GG KV head groups; each group of H/GH/G query heads shares KV. Interpolates MHA ↔ MQA.

Used in Llama 2/3, PaLM — critical for long-context inference with Flash Attention.


Worked Examples

Example 1: Cache Growth

After 1000 tokens, cache stores 1000 key vectors per head per layer.

Example 2: MQA Savings

64-head MHA → MQA: 64× KV memory reduction.


Connection to the Broader Curriculum


Common Pitfalls and Misconceptions

Pitfall 1: KV cache memory scales linearly with context — limits long sequences.

Pitfall 2: RoPE position must be correct when reading cached K.

Pitfall 3: Prefill and decode have different bottlenecks.

Pitfall 4: Batch inference multiplies cache by BB.


Research Perspective

The KV cache is implicit in any efficient autoregressive implementation but was formalized in the context of transformer inference scaling. Multi-Query Attention (Shazeer, 2019) demonstrated that sharing key and value heads across query heads reduces cache bandwidth with minimal quality loss. Grouped-Query Attention (Ainslie et al., 2023) interpolates between MHA and MQA and is now standard in Llama 2/3 and related architectures. PagedAttention (Kwon et al., 2023) applies virtual-memory paging to KV storage, eliminating fragmentation in batched serving. Quantized and compressed KV caches (INT8, FP8) remain active research for extending context length under fixed memory budgets.


Summary of Takeaways

  • Cache — Store K, V per layer
  • DecodeO(t)O(t) per step vs. O(t2)O(t^2) naive
  • Memory — (3)
  • MQA/GQA — Reduce cache by grouping

Next: RAG


Exercises

Exercise 1. Derive total naive cost O(n2d)O(n^2 d) over nn generation steps by summing per-step costs as in equation (2).

Exercise 2. Compute (4) for given model config.

Exercise 3. MQA vs. MHA memory for Llama 7B.

Exercise 4. Prefill vs. decode bottleneck analysis.

Exercise 5. RoPE indexing with cache at position tt.

Exercise 6. PagedAttention conceptually.

Exercise 7. Batch size effect on (3).

Exercise 8. Connect to Flash Attention memory complexity.