Unit 2 of 7 · about 5 hours · implement

Building a KV cache

A cache that shares layers, mixes sequences or misplaces positions returns fluent garbage with matching shapes. Ownership, layout and offsets are what make it correct.

You'll be able to

  • Implement per-layer KV allocation, append and single-token cached decode with absolute position offsets for the tiny transformer.
  • Explain MHA, MQA and GQA head mappings and the repeat_interleave rule for shared KV heads.
  • Explain KV tensor shapes and why each layer owns its cache for its own sequence.

Covers

Per-layer KV ownership and sequence identityKV tensor shapes, layout, capacity and append statePosition offsets and RoPE consistency under cached decodeMHA, MQA and GQA KV head mapping
1

Read

In this order, only the parts listed

0 of 3 done

  1. Raschka gpt_with_kv_cache.py: per-layer cache with positionsLLMs from Scratch companion - KV cache and GQA

    MultiHeadAttention (cache_k and cache_v buffers, use_cache append by torch.cat on dim 1, ptr_current_pos mask slice, reset_cache), GPTModel (current_pos with pos_ids arange, ModuleList loop, reset_kv_cache) and generate_text_simple_cached (full-prompt prefill then single-token loop)

  2. Raschka ch04/04_gqa: GQA head mapping and memoryLLMs from Scratch companion - KV cache and GQA

    GroupedQueryAttention (num_kv_groups with group_size, and cache on dim 2, repeat_interleave mapping with the repeat versus repeat_interleave comment, q_positions versus k_positions mask) plus the README bytes formula with n_kv_heads and the 4096/32/32/32768 example

  3. Modern LLM Notebook 21 Sections 2 and 4: shapes and head sharingModern LLM Notebook - KV cache and inference acceleration

    Section 2 shape evolution ([batch, num_heads, cached_seq_len, d_k] from [1,4,1,8] to [1,4,5,8]) and Section 4 MHA/MQA/GQA (32 heads with 32, 8 and 1 KV heads at 8K, the 8 with 2 KV repeat_interleave demo, savings ratio 32/8 = 4x)

    Skip Sections 5 to 8 and 10 (quantization, GGUF, PagedAttention, FlashAttention, batching) until their own units.

2

Focus on

  • Each layer owns its and tensors and each batch row owns its positions. Sharing a cache across layers or sequences mixes unrelated spaces.
  • Append grows the sequence dim by the new chunk only. Prefill appends the whole prompt at once, decode appends one token per step.
  • Positions are absolute. pos_ids and the mask pointer advance by the chunk length, so decode step uses position current_pos plus .
  • GQA stores fewer KV heads and expands them with repeat_interleave. With 8 heads and 2 KV heads, heads 0 to 3 share KV head 0.
Common mistakes · 3
  • Forgetting reset_kv_cache between independent generations. Stale , and pointers leak the old sequence into the new one.
  • Using repeat instead of repeat_interleave for grouped heads. Tiling maps the wrong KV head to each query group while shapes still match.
  • Restarting positions at 0 on every decode step. Absolute embeddings repeat and RoPE rotations reuse early angles, so logits diverge from the full prefix.
3

Try it yourself

Closed-book, before checking anything

Write the cache-owning attention forward from scratch: buffers, append, pointer-based mask slice, absolute pos_ids, reset, and the GQA repeat_interleave mapping for 8 heads with 2 KV heads.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.After a 4-token prefill, the first decode step feeds 1 token. What are the and lengths and which mask row applies?Answer

    has 1 token and has 5 (4 cached plus 1 new). The pointer is 4, so the slice is row 4 over 5 columns, which lets the new query attend to all 5 positions.

  2. 2.With 32 heads and 8 KV heads, which heads share KV head 0, and why repeat_interleave?Answer

    heads 0 to 3 share KV head 0 in contiguous groups of 4. repeat_interleave gives [K1,K1,K2,K2], while repeat would tile as [K1,K2,K1,K2] and map the wrong heads.

  3. 3.Why must decode pos_ids use current_pos, and what breaks for RoPE if they restart at 0?Answer

    Positions are absolute. Restarting at 0 reuses early embeddings and early RoPE angles for late tokens, so relative distances are wrong and logits diverge from the full prefix.

  4. 4.Two layers share one cache object to save memory. What fails?Answer

    Each layer has its own projections, so its and live in different spaces. Sharing mixes them and equivalence fails; each layer needs its own cache just as each sequence needs its own rows.

5

Practice

  • Raschka ch04/03_kv-cache tests: cached equivalence

    test_gpt_model_equivalence_cached and test_gpt_model_equivalence_not_cached (30 new tokens from Hello, I am across base, cached and optimized models with torch.equal)

    Run against the reference files, then re-run against your own per-layer cache in your own repository.

You're done when

Your own cache passes both equivalence tests with torch.equal and you can state the cache shape after each step.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 4 more in the section
  • LLMs from Scratch companion - KV cache and GQASebastian Raschka · primary

    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 · required

    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.

Also in this section

  • Stanford CS336 - Lecture 10 InferenceStanford University · required

    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 · depth

    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 · depth

    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 · optional

    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.