4.6 Training a GPT
1. Learn
Section titled “1. Learn”- Karpathy, Let's build GPTwhole video (1:56:20); for training, 00:07:52–00:38:00 (data, batches, the bigram baseline) and 01:19:11–01:42:39 (multi-head attention, feed-forward, residuals, layernorm, scaling up)
- Karpathy, Let's reproduce GPT-2 (124M)00:13:47–01:22:18 (the GPT-2 module, loss, overfitting one batch, data loader, weight tying, initialization) and 02:14:55–02:46:52 (AdamW, gradient clipping, warmup + cosine schedule, gradient accumulation); 01:22:18–02:14:55 on speed is for 5.1
2. Bridge
Section titled “2. Bridge”The model. A GPT is a token embedding, a stack of the blocks from 4.5, a final norm and a linear layer that turns each position’s vector into logits over the vocabulary (Karpathy, Let’s build GPT). The output layer can reuse the embedding matrix: tying the two saves vocabulary × d parameters and often helps, since a token’s input and output vectors should be similar (Press & Wolf 2017). With RoPE there is no learned position table.
Training. Every window of the text is a training example. Take ctx + 1 consecutive tokens; the first ctx are the input, and the same window shifted by one gives the target at every position. The causal mask lets one forward pass train all ctx predictions at once. The loss is the mean cross-entropy; at initialisation it should be close to log(vocabulary size). Small initial weights, output projections scaled down by , AdamW, warmup and cosine decay, and gradient clipping keep training stable. The scaled output projections come from GPT-2 (Radford et al. 2019, §2.3); the optimizer, schedule and clipping settings follow GPT-3 (Brown et al. 2020, Appendix B); Karpathy’s GPT-2 video in Learn walks through the 0.02 initialisation and all of them in code.
Decoding. Generation feeds the model its own samples, one token at a time. Greedy decoding, always picking the most likely token, quickly falls into loops. Sampling from the full distribution eventually picks something from the long tail of unlikely tokens and derails. Temperature divides the logits before the softmax: below 1 it sharpens the distribution, above 1 it flattens it. Top-k keeps only the k most likely tokens; top-p (nucleus) sampling keeps the smallest set whose probability reaches p, so the cut adapts to how confident the model is (Holtzman et al. 2020).
3. Explore
Section titled “3. Explore”A convention change. Until now a layer stored W as (inputs, outputs) and computed x @ W (module 3.1). PyTorch’s nn.Linear stores its weight as (outputs, inputs) and computes x @ W.T, and from here on the code follows PyTorch. The maths is the same; only the stored matrix is transposed.
Build the model, batching and decoding in PyTorch and pass the tests locally on a CPU: shapes, causality, initial loss near log(vocab), tied weights, overfitting one batch, and top-k / top-p.
Training a GPT: edit exercises/stubs/m4_6_gpt.py on your own machine. This task needs PyTorch, which the in-page runner does not have.
pip install torch # CPU build is enough for the tests
mlc check 4.6Then train it on Shakespeare (locally, CPU; a few minutes):
cd exercises && python projects/gpt_shakespeare.pyA 0.8 M-parameter model with a 128-character context reaches a validation loss of about 1.5 nats per character in 2,000 steps, well below the RNN of 4.3. It then prints samples with greedy decoding, temperature with top-k, and top-p.
Finally, TinyStories on a GPU. Open notebooks/4.6-tiny-gpt.ipynb on Kaggle as in module 0.3, paste in your finished file, turn on the GPU and internet access, and run everything. It trains a 10.7 M-parameter, six-layer model on TinyStories with mixed precision; the target is a validation loss below 1.1 nats per character in under 30 minutes, and stories that mostly make sense. Without a GPU it runs a short smoke test on Shakespeare instead.
5. Check
Section titled “5. Check”- not yet: All tests pass (0/?)
- not yet: Checkpoint quiz ≥ 80%
Learner log: time spent and points of confusion
Every confusion you note becomes a fix before the module is marked stable. Export it from the progress page and attach it to an issue.