03A GPT from scratch (PyTorch)

hardtorch
65:00

03 A GPT from scratch (PyTorch)

Four levels in solution.py. Read one level at a time and run only its tests until they pass: pytest problems/03_tiny_gpt -k level1. Earlier levels must keep passing.

Write GPT(vocab_size, block_size, n_embd, n_head, n_layer), a decoder-only transformer. forward(idx, targets=None) returns (logits, loss): logits (B, T, vocab_size), and the loss, or None without targets.

Level 1. The ends. self.tok_emb (token embedding) plus self.pos_emb (learned positions, block_size of them), a final self.ln_f, then self.lm_head to vocab logits, with its weight tied to self.tok_emb. Raise ValueError when T > block_size.

Level 2. The blocks. n_layer pre-LayerNorm blocks in self.blocks (an nn.ModuleList, a new block each time): x = x + attn(ln1(x)), then x = x + mlp(ln2(x)). The tests reach into a block by these names: ln1, attn, ln2 and mlp. attn is problem 02's causal multi-head attention, with the fused attn.qkv (q, then k, then v) and attn.proj, and a scale of 1 / sqrt(n_embd // n_head). mlp is Linear(n_embd, 4 * n_embd), GELU, Linear(4 * n_embd, n_embd). forward adds the two embeddings, runs the blocks, then ln_f, then lm_head. Earlier tokens must reach later positions, and later tokens must never reach earlier ones.

Level 3. The loss: the mean cross-entropy over every position, a 0-d tensor. The caller passes targets already shifted by one (targets[:, t] is the token after idx[:, t]), so don't shift them again. A test trains the model for 150 AdamW steps on one short sequence and expects the loss under 0.3.

Level 4. The start. Every nn.Linear and nn.Embedding weight starts with a standard deviation of 0.02 and every bias at 0, so a fresh model's loss on random tokens sits near ln(vocab_size).

Things to get right: pre-LN versus post-LN and why pre-LN trains more stably, why the weights are tied, the parameter count (roughly 12 * n_layer * n_embd^2), initialization scale, and what the loss should be at initialization (about ln(vocab_size)).

solution.py
Run the tests to see which pass.