Skip to content

4.6 Training a GPT

ready≈ 13 hoursNeeds: 4.5, 4.1Unlocks: 5.1, 5.4, 5.7, 5.8, 5.11, 7.1, 7.2, 7.3
  1. 1 Learn
  2. 2 Bridge & derive
  3. 3 Explore (Decoding playground, Attention head viewer)
  4. 4 Do
  5. 5 Check
  • 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

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 1/2L1/\sqrt{2L}, 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).

Decoding playground

How sampling shapes output

Static view on small screens. Open this page on a laptop to interact.

␣40.8%s15.6%,13.1%l5.7%.5.6%;2.5%i2.4%:2.0%e2.0%y1.7%n1.3%a1.3%↵1.2%!1.2%?1.0%-0.6%pale: softmax(logits / T) · solid: after top-k / top-p, renormalized · click a row to append it
characters kept 65 of 65 entropy 2.07 nats context used 27 of 64

A 0.1 M-parameter GPT with the 4.6 architecture (2 layers, d = 64, 4 heads), trained on Tiny Shakespeare and stored in int8, runs in your browser. Temperature 0 always picks the top character and soon repeats itself. High temperatures flatten the distribution until unlikely characters break the words apart. Top-k and top-p cut off that unreliable tail: top-k keeps a fixed number of characters; top-p keeps the smallest set whose probability reaches p, so it keeps few after "Bu" and many after a space.

A two-layer character-level GPT trained on Tiny Shakespeare runs in the page. After the prompt, the 16 most likely next characters are listed with two bars: the probability after temperature, and the probability after top-k and top-p filtering and renormalisation; removed characters are greyed out. Sliders set the temperature (0 for greedy), top-k and top-p. A button generates 200 characters with the chosen settings; another draws a new sample. Keyboard: Tab to the prompt, the sliders and the probability rows; press Enter on a row to append that character.

Attention head viewer

What heads attend to

Static view on small screens. Open this page on a laptop to interact.

keys →queries →
query 41: “o” strongest key 41: “o” at 45% (itself) this head's top key is the previous character for 7% of queries, itself for 17%

The same tiny GPT as the decoding playground: 2 layers of 4 heads. Click a character to make it the query; the strip and the outlined matrix row show where it looks. Nothing after the query is visible, because of the causal mask. On Shakespeare most of these heads look one or two characters back: with 64 dimensions and a character vocabulary, the first job is to read the current word. Layer 1 head 4 is close to a pure previous-character head. Layer 2 head 4 is the most spread out and often lands on the last space or newline, the start of the current word or line. Heads in large models do more varied things; reading them is the subject of 7.3.

The same tiny model reads a line of text. Buttons pick one of its 8 heads (2 layers × 4). Each character is a button: the selected one is the query, and the earlier characters are shaded by how much attention it gives them. A matrix shows the whole causal attention pattern of the head, rows for queries and columns for keys. A readout names the strongest key and how often this head’s strongest key is the previous character. Keyboard: Tab to the layer and head buttons and the characters; press Enter to select.

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.6
Hints · CausalSelfAttention.forward 0/3 revealed
Hints · GPT 0/3 revealed
Hints · top_k_top_p 0/3 revealed

Then train it on Shakespeare (locally, CPU; a few minutes):

Terminal window
cd exercises && python projects/gpt_shakespeare.py

A 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.

1. What does tying the output layer to the embedding save?
2. A freshly initialised model over a 65-character vocabulary should have a loss of about…
3. How many next-token predictions does one training window of ctx tokens give?
4. After the model is almost certain of the next token, what does top-p = 0.9 keep, and top-k = 20?
5. Raising the temperature from 1 to 2…
  • not yet: All tests pass (0/?)
  • not yet: Checkpoint quiz ≥ 80%
Finish the items above first.
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.