Build your own GPT-2 inference engine (no HuggingFace)
CPU · your Mac~8 hLoad the real GPT-2 small weights into a decoder you wrote yourself (embeddings, RoPE-free learned positions, attention, MLP, layer norm, tied unembedding), add a KV cache and greedy/top-k sampling, and prove it matches the Hugging Face output. This is the whole of Phase 1 in one file you understand completely.
Scope
- A single model.py with the decoder block, under 400 lines, no transformers import except to download weights once.
- A weight loader that maps the HF state_dict names onto your modules (and checks every tensor was consumed).
- A tokenizer wrapper using the GPT-2 BPE vocab files (you may use tiktoken for the BPE itself).
- A generate() with a KV cache, greedy and top-k, temperature, and a stop token.
- A bench.py that times prefill and per-token decode for prompts of 16, 128 and 512 tokens.
Out of scope
- Training or fine-tuning.
- Any GPU code; this is CPU fp32.
What to measure
- Logit agreement with Hugging Face GPT-2
- How · torch.allclose on logits for 5 prompts, atol 1e-3
- Target · all pass
- Parameter accounting
- How · sum(p.numel()) versus config formula
- Target · 124,439,808 exactly, zero unconsumed HF tensors
- Prefill vs decode time
- How · wall-clock with torch.set_num_threads fixed, 5 repeats, median
- Target · prefill grows roughly linearly with prompt length; decode per-token is flat within 20 percent across 16/128/512
- Tokens per second at batch 1
- How · 128 greedy tokens after a 32-token prompt
- Target · report the number; typical Apple M-series CPU lands 10-40 tok/s
Pay attention to
- Pre-norm order and the residual stream; most "almost right" outputs come from applying layer norm in the wrong place.
- GPT-2 uses Conv1D-named linear layers with transposed weights; the loader must transpose.
- Causal mask must be applied before softmax in fp32; check with a prompt whose later tokens would otherwise leak.
- Position ids for the one-token decode step must equal the current cache length, not zero.
- Do not compare argmax tokens only; compare logits, then tokens.
Acceptance (all must pass)
- ☐pytest passes the logit-agreement test on 5 prompts.
- ☐Greedy generation of 64 tokens is identical to HF generate(do_sample=False) for 3 prompts.
- ☐KV-cached decode produces identical tokens to the uncached path and is at least 2x faster at 128 tokens.
- ☐README contains the bench table and a one-paragraph explanation of why decode is memory-bound even on CPU.