Phase 7 · Transformers/
Lesson 7.10advanced3 h 30 min⚡ live demo

Efficient inference: KV cache, GQA, FlashAttention, speculative decoding, quantization

Decode is memory-bound — every trick here does more useful work per byte read

Training a model happens once; serving it happens billions of times, and serving is where most of the money and latency go. The techniques here — the KV cache, grouped-query attention, FlashAttention, continuous batching, speculative decoding and quantization — are why a 7B model runs on a laptop and why frontier APIs can stream hundreds of tokens per second. You will meet them again as 4-bit QLoRA (8.2 Fine-tuning and PEFT), as the latency and cost budgets of RAG and agent systems (9.9 Production: latency, cost, caching, guardrails, security and privacy, 10.11 Building production agents), and in every serving stack you deploy (8.13 Project: fine-tune a small LLM with LoRA and ship a chat app).

You'll be able to

  • Explain why decoding is memory-bandwidth-bound and compute arithmetic intensity for a decode step
  • Derive the KV-cache memory formula and apply it to real models with and without GQA
  • Describe how FlashAttention computes exact attention in O(n) memory using the online softmax
  • Explain speculative decoding's acceptance rule and expected speedup, and the basics of int8/int4 quantization

Key ideas

  1. Prefill is compute-bound and parallel; decode produces one token per step and is bound by memory bandwidth (reading weights + KV cache).
  2. KV cache per token = 2 · L · n_kv · d_head · bytes; Llama 2 7B needs 0.5 MB per token in fp16, Llama 3 8B (GQA, 8 KV heads) 128 KB.
  3. Arithmetic intensity of a decode step ≈ batch size, far below the GPU's ridge point at small batches — hence continuous batching and PagedAttention.
Show 4 more key ideas
  1. GQA shares K/V heads across groups of query heads, shrinking the cache by n_heads / n_kv with little quality loss.
  2. FlashAttention tiles Q, K, V through SRAM and uses the online softmax to compute exact attention with O(n) memory and 2–4× speed.
  3. Speculative decoding verifies γ draft tokens in one target pass; with acceptance rate α it yields (1 − α^(γ+1))/(1 − α) tokens per pass and the exact target distribution.
  4. Quantization to int8/int4 cuts weight bytes 2–4× with small perplexity cost; GPTQ, AWQ and NF4 are the common 4-bit schemes.

Suggested path through this lesson