Highlights

Contents

A HAND-DRAWN FIELD GUIDE / OCTLM UNIT IVInferenceEngineeringFrom a checkpoint on disk to a chat reply you can trust,one verified step at a time.ONE CHAT TURN, BOTTOM TO TOPmessages → chat templatetokenizer → token IDsprefill the promptKV cachedecode one tokensample → detokenize"The capital of France is Paris."repeatread the wholeprompt once,then one tokenat a time.Qwen3-0.6B, rebuilt and provedCHAPTER 4 / PREFILL, CACHE, QUANTIZE, LOAD, PROVE, TEMPLATE
Before we start

How to read this chapter

A checkpoint becomes useful only when the surrounding code reproduces its input contract and computation. This chapter follows loading, cached generation, and the checks that establish correctness.

Follow a chat message through prompt processing, decoding, quantization, weight loading, parity checks, and serialization. Explain the mechanism from its drawing, then use the implementation details to identify what could break. Benchmark only after correctness is established.

Each part ends with an “In one breath” recap. The interview page has questions, graded exercises, and worked solutions; try the reasoning before reading the answer.

The running example

Meet Qwen3-0.6B

Qwen3-0.6B is the checkpoint used for the port. It combines the modern-block components with explicit head dimensions and query/key normalization. The settings below come from its published configuration; the file and tokenizer are inspected in later parts.

Setting Config key Qwen3-0.6B Finch-24
Vocabulary rows vocab_size 151,936 32,000
Width hidden_size 1,024 512
Layers num_hidden_layers 28 8
Query heads num_attention_heads 16 8
Key/value heads num_key_value_heads 8 2
Head size head_dim 128 64
SwiGLU width intermediate_size 3,072 1,536
RoPE base rope_theta 1,000,000 10,000
RMSNorm epsilon rms_norm_eps 10−610^{-6} 10−510^{-5}
Position limit max_position_embeddings 40,960 4,096
Tied embeddings tie_word_embeddings true true
Stored dtype torch_dtype bfloat16
Unique parameters 596,049,920 40,509,952

Finch-24 remains the small teaching example, and Llama 3 8B is the larger reference. Hardware peak rates provide lower bounds on time, not measured latency. The companion scripts are scripts/inference/calc.py and scripts/inference/tokens.py.

The map

What is inside

Ten parts follow one chat message through a real model. The map is the whole inference stack on one page; each part lights up the piece it covers.

YOU ARE HEREmessageschat templatetokenizertoken IDsconfig.jsonmodel.safetensorsint8 / int4 weightsOUR DECODER, REBUILT FROM THE CONFIGprefilldecodeattention kernelKV cacheparity checkvs referenceLM head → logitssamplingdetokenizereply textnext token
  1. 01Prefill and DecodeSections 1 to 4. A prompt is known before generation begins.
  2. 02The KV Cache in PracticeSections 5 to 9. Cached history removes repeated prefix work.
  3. 03Attention Kernels at Inference TimeSections 10 to 15. Prefill and decode expose different attention shapes.
  4. 04QuantizationSections 16 to 23. Weights can be expensive to store and read.
  5. 05Reading a Real Model: Qwen3Sections 24 to 29. A saved checkpoint expects one particular architecture.
  6. 06Checkpoints and LoadingSections 30 to 34. Loading must preserve each tensor's learned role.
  7. 07Proving the Implementation Is CorrectSections 35 to 41. Plausible text can hide an incorrect implementation.
  8. 08Real TokenizersSections 42 to 47. The tokenizer determines which learned rows the model reads.
  9. 09Chat TemplatesSections 48 to 55. Chat roles need a format the model recognizes.
  10. 10End-to-End Real LLM InferenceSections 56 to 62. Every stage contributes to a correct chat reply.
  11. +Interview prepInterview question bank, graded exercises and worked solutions.