KV Cache, Prefill & Decode

Autoregressive generation has two distinct execution regimes and a stateful cache. This final section proves cache correctness first, then explains capacity and latency without importing an entire serving stack.

Section 5 of 5 · 7 units · about 22 hours

0/7

By the end you can Prove full-prefix and cached logits or tokens agree across adversarial MHA and GQA shapes, offsets and variable lengths. Derive KV capacity and measure prefill and decode separately across at least two context and batch regimes with trustworthy timing.

Units

Build it

Mini project · about 10 to 14 hours

Cached generation, proved and measured

Add a KV cache to the decoder and prove that it changes nothing but cost. Then measure prefill and decode separately, and explain the numbers with the arithmetic from section 4.

  1. 1Add a per-layer cache of unexpanded and to your model, with absolute positions for RoPE, and a forward that takes new tokens, the cache and a start position.
  2. 2Prove equivalence: greedy tokens match and per-step logits agree within tolerance with the uncached model for MHA, GQA and MQA, chunked prefill, a one-token prompt, a variable-length batch with padding, a sequence that stops early at EOS, and a reused cache slot.
  3. 3Derive the KV-cache bytes for your config and for one published model config, and check the formula against the real tensor sizes of your cache.
  4. 4Measure time to first token and inter-token latency on a CPU or a free GPU across two context lengths and two batch sizes, with warm-up, device synchronization and repeated trials.
  5. 5Explain the measurements: which phase is compute-bound, which is memory-bound, and how the cache changes the cost of each decode step.
  6. 6Add a test that fails if a decode step recomputes the prefix, for example by counting the tokens that reach the and projections at each step.
What you hand in
  • The cached model and its equivalence test suite.
  • A KV memory sheet: the formula, your config, one published config and the measured cache size.
  • A latency report: time to first token and inter-token latency per regime, the timing method, and an explanation of each trend.
How to check it
  • Self-grade with the rubric below
How it's graded

Equivalence

Pass: Cached and uncached greedy tokens match on every case in your equivalence tests.

Great: Per-step logits also match within 1e-5 on your own adversarial cases, and a deliberately wrong RoPE offset makes your tests fail.

Memory

Pass: The KV formula matches the measured cache size.

Great: The sheet scales the formula to a published model at long context and large batch, and names what dominates memory there.

Timing method

Pass: Prefill and decode are timed separately with warm-up and repeated trials.

Great: The report gives medians with spread, synchronizes the device and states what the timings exclude.

Explanation

Pass: Each trend is explained in a sentence.

Great: The explanation uses arithmetic intensity from section 4 and predicts one result before measuring it.

Resources

  • LLMs from Scratch companion - KV cache and GQASebastian Raschka

    Use ch04/03_kv-cache and ch04/04_gqa with the chapter model code. Add explicit per-layer ownership, position offsets, variable lengths, EOS compaction and MHA-versus-GQA cache arithmetic to the runnable comparison.

  • Modern LLM Notebook - KV cache and inference accelerationWalking Labs

    Use the KV-cache portions of English notebooks 11-mla-kv-cache and 21-inference-acceleration. Skip MLA and advanced acceleration as core work. Recalculate cache sizes and verify timing after warmup and explicit synchronization.

  • Stanford CS336 - Lecture 10 InferenceStanford University

    Use the Spring 2026 inference lecture to connect KV arithmetic, phase behavior and batching vocabulary. Keep kernels, distributed serving and expensive performance experiments for the later tracks.

  • How to Scale Your Model - inference chapterJAX ML

    After cache equivalence and phase measurement pass, read the inference chapter for arithmetic intensity, parallelism and production-scale reasoning. Treat it as the handoff to inference and performance tracks, not required foundation work.

  • AI Performance Engineering - inference-engine bridgeWafer

    Use Sections 4 and 5 only after this gate to choose the next inference, KV-cache, scheduling, quantization or distributed-serving resource. Do not treat its GPU and kernel material as unfinished LLM Foundations work.

  • No Magic - micro KV or paged-cache simulationNo Magic

    Use one small CPU simulation such as microkv.py or micropaged.py only to visualize state ownership. Do not present Python timing as GPU or serving-performance evidence.