AI from scratch · Chapter 10
A tiny transformer, trained here
Chapter 7 drew attention as pictures. This chapter builds the real thing: a GPT, the same design as the models behind chatbots, shrunk to one block and about 36,000 numbers so it trains in your browser in a minute. It reads every subway station name in New York, one character at a time, learning to guess the next one. Then it makes up stations that don't exist, but sound like they should.
1. The task: guess the next letter
Language models do one thing: given the text so far, give a probability for every possible next piece. Chatbots predict word-pieces; ours predicts single characters, from an alphabet of 68 (letters, digits, a few symbols, and a "the name ends here" mark). Here's everything it will learn from:
Before training, the model knows nothing, so it gives all 68 characters the same chance. Its loss is −ln(the chance it gave the right one). What's that loss?
A language model does one thing: give every possible next character a probability. Any loss below ln 68 ≈ 4.22 is learning.
2. The model
Each character becomes a vector of 48 numbers (its embedding, plus one for its position). Attention lets every position gather information from the positions before it, weighted by how relevant they are; the MLP then thinks about what it gathered. The residual connections ("+") add each step's result to its input, so information can flow straight through. Big models stack this block 50–100 times, with thousands of numbers per vector and dozens of attention heads; ours has one of each.
\[ \text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d}} + \text{mask}\right) V, \qquad Q = XW_q,\; K = XW_k,\; V = XW_v \]
The mask sets every "look at a later position" score to −∞ before the softmax, so a letter can't peek at the answer it's supposed to predict.
Why does training need the mask, but a model that only ever generates left to right could seem not to?
- It makes training faster
- In training, all positions are predicted at once from a known text; without the mask, each could just read the next letter from its neighbor
- Softmax needs it
One block: each letter looks back and gathers (attention), then thinks about what it gathered (the MLP), each step adding to what was there.
3. Train it
Each step takes 8 random 32-character windows of the station list, predicts every next character, measures the loss, and nudges all 36,000 numbers downhill (backpropagation through the attention and the MLP, then the Adam optimizer: chapters 2 and 4). Every 50 steps it makes up a few new names.
Green: a name that isn't a real station. Gray: one it memorized from the list.
Turn the temperature down to 0.2 and generate. Why does it start repeating real stations?
Training nudges 36,000 numbers so the right next letter gets more probability; temperature decides how boldly the model samples.
Why temperature works the way it does
- The probability of character \(i\) is \(e^{s_i / T}\) divided by the sum over all characters, where \(s_i\) are the model's scores.
- The ratio between two characters is \(e^{(s_i - s_j)/T}\): only the gap between their scores matters, divided by \(T\).
- Scores 2 and 1: at \(T = 1\) the first is \(e \approx 2.7\) times as likely; at \(T = 0.5\), \(e^2 \approx 7.4\) times; at \(T = 2\), only \(e^{0.5} \approx 1.6\) times.
- As \(T \to 0\) the ratio grows without limit: the model always takes the top character (greedy). As \(T\) grows large every ratio goes to 1: uniform noise.
- \(T = 1\) is the distribution the model was trained to produce. Anything else is a deliberate distortion: below 1 for safer, above 1 for more surprising.
4. Look inside
Type the start of a name. The bars are the model's guesses for the next character; the colored letters show where the last position's attention went (darker: more weight).
That's one row of the attention table. Here is all of it: every letter of your text is a row, and its squares show where that letter looked while guessing the one after it. Everything above the diagonal is empty: that's the mask. Train a few hundred steps and watch the pattern form. Hover a row to read it.
The top row (the start mark ⏎) is always one fully lit square. Why?
- It's learned that the start matters most
- Its position embedding is special
- The mask leaves it only itself to look at, and softmax over one score gives it weight 1
Each row of the attention table is one letter's view of the past, and the mask keeps the future dark.
Where it breaks: memorizing, short sight and no undo
- Memorizing. 36,000 numbers for 379 names is about 95 numbers per name: enough to learn the list by heart. Trained long, most "new" names come out gray, real stations. That's chapter 11's overfitting; big models face the same pull on text they've seen many times.
- Short sight. The model sees 32 characters, about five words. Real models read word-pieces of about 4 characters each, so the same window holds four times as much text, and their windows are thousands of pieces long.
- No undo. Generation picks one character at a time and never goes back. One unlucky low-probability letter, and every later guess is conditioned on it. That's why low temperature looks "safer", and why tricks like beam search keep several candidates alive.
That's the whole idea, at toy scale. The GPTs behind chatbots are this block, repeated dozens of times, about a million times wider, trained on trillions of word-pieces instead of 379 station names. Same arithmetic.
All chapters: AI from scratch.
Last updated