7 routes42 sections324 units

Unit 5.3 · about 4 h

320 / 324

Proving the cache correct

A cache that is fast but subtly wrong poisons every measurement after it. Equivalence across shapes, offsets and messy batches is what lets you trust the rest of the section.

  • implement

You can now

  • Write equivalence tests comparing full-sequence logits with token-by-token cached logits across MHA and GQA, batch sizes and position offsets.
  • Handle variable lengths with padding masks, EOS compaction and cache cleanup without breaking equivalence.
  • Diagnose truncation, fork and stale-cache failures from a failing equivalence test.

Covers

  • Full-prefix versus cached-logit equivalence
  • Variable-length batches and padding state
  • Finished-sequence compaction and EOS handling
  • Cancellation cleanup, truncation, forks and stale-cache hazards

Study, in this order

3 steps

  1. Raschka `tests.py` and optimized cache: equivalence, chunking and overflow
    LLMs from Scratch companion - KV cache and GQA

    test_gpt_model_equivalence_cached and not_cached (30 tokens with torch.equal), test_prefill_chunking_basic (kv_window_size 4 over 10 tokens in 3 chunks, 12 total with input preserved) and test_context_overflow_bug (context_length 10 with 5 plus 10 tokens hitting the position-embedding assert)

  2. CS336 Lecture 10: selective batching and paged sharing
    Stanford CS336 - Lecture 10 Inference

    continuous_batching (ragged lengths [3,9,5] with attention per sequence and non-attention concatenated) and paged_attention (blocks, sharing the system prompt and parallel samples, copy-on-write at block level)

    Depth · Read the two functions only. Keep kernels, distributed serving and expensive performance experiments for the later tracks.

  3. JAX scaling book inference: ragged reads and the EOS loop
    How to Scale Your Model - inference chapter

    Tricks section (ragged HBM reads and Paged Attention that read only the non-padding part) and The Basics (Generation repeats until EOS or a maximum length)

Focus on

  • Generated tokens must match exactly at a fixed seed; logits must match within a small tolerance, such as 1e-5 in float32, because different matmul shapes round differently. Check both before trusting any timing.
  • Variable lengths need per-row lengths and padding masks. Reading the padded tail as real tokens breaks both equivalence and the batch.
  • Finished sequences need compaction: free or clear their rows, compact the batch, and stop them at EOS plus a length cap. Reused slots must be cleared first.
  • Truncation, forks and reuse without reset are stale-cache hazards. Chunked prefill and windowed caches must preserve order and positions.

Reproduce closed-book

Write the equivalence harness: exact token match and per-step logits within tolerance for full-prefix versus token-by-token cached decoding, plus the chunked-prefill case (4-token window over 10 tokens) and the position-overflow assert case.

Traps

  • Testing equivalence on one prompt length and head count. Offset, GQA grouping and batch bugs hide until adversarial shapes and longer contexts.
  • Freeing a finished row without clearing it. The next request inherits old \(K\) and \(V\) and attends to another sequence, which looks like a model bug.
  • Truncating the cache but keeping old position ids. Tokens shift left while positions stay high, so RoPE and absolute embeddings disagree with the full prefix.

Practice

Raschka `ch04/03_kv-cache` tests: chunking and overflow

test_prefill_chunking_basic and test_context_overflow_bug (windowed chunking with input preservation, plus the position-embedding overflow assert)

Then extend in your own repository to variable-length batches with padding masks, EOS compaction and a stale-cache reuse test. The mini-project checks the full matrix across MHA and GQA.

Self-test

  1. Cached and full-prefix logits differ from position 0 onward. What class of bug is it?

  2. With kv_window_size 4, a 10-token prompt prefills in 3 chunks and generates 2 tokens. What total length and input check must hold?

  3. Batch lengths are [3,9,5]. Why does CS336 run attention per sequence but concatenate to [17,H] for the MLP?

  4. A finished sequence is freed without clearing and a new request reuses the slot. What hazard and what fix?

Completion criterion

Stop when

Your harness shows identical tokens and per-step logits within tolerance on adversarial MHA and GQA shapes with offsets, and your chunking, overflow and slot-reuse tests all pass.

Mark passed, then open 5.4 Only mark this when you can do it without notes.

Leads to

Comes after

Resources for this unit

  • LLMs from Scratch companion - KV cache and GQA
    Sebastian Raschkaprimaryimplementation
    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.
  • Stanford CS336 - Lecture 10 Inference
    Stanford Universityrequiredtheory
    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 chapter
    JAX MLdepththeory
    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.

Also in this section

  • Modern LLM Notebook - KV cache and inference acceleration
    Walking Labsrequiredimplementation
    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.
  • AI Performance Engineering - inference-engine bridge
    Waferdepthreference
    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 simulation
    No Magicoptionalpractice
    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.

Quick find

Search Michi

Type to search every route, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels