ACT 1
Build one transformer
Parts 0–11. One block, the thing every modern LLM repeats.
00 THE JOB
A machine that guesses the next word
- WHAT
- Give it some text. It returns one guess for what comes next.
- WHY
- That's the whole job. Every part below exists to make that one guess better.
- HOW
- Run it again on its own output, and one guess at a time becomes an answer, an essay, or code.
THE EXAMPLEWe'll push one sentence through every part: "The cat sat on the". A good model should say " mat".
01 PART 1
Tokenizer
- WHAT
- Cuts text into pieces called tokens, and swaps each piece for its number in a fixed list.
- WHY
- The model can only do maths on numbers. Pieces smaller than words keep the list short (50,257 entries) and still let it spell anything, even a word it has never seen.
- HOW
- Byte-pair encoding: start from single characters, and keep merging the pair that shows up most often in the training text. Common words end up as one token; rare words become a few.
NOTE THE SPACEThe space belongs to the token: " cat" with a space is a different token from "cat" without one.
02 PART 2
Token embedding
- WHAT
- A big table with one row per token. Each id picks its row: a list of 768 numbers.
- WHY
- An id is just a label: 3797 isn't "closer" to dog than 3796. A list of numbers is a position in space, so similar words can sit close together.
- HOW
- The table starts random. Training slowly moves the rows until words used in similar ways end up near each other.
BIGGEST PARTThis one table is 50,257 × 768 = 38.6 million numbers, almost a third of GPT-2 small.
03 PART 3
Position embedding
- WHAT
- A second table, one row per position (0, 1, 2 … 1023). Each token's position row is added to its vector.
- WHY
- Attention, coming up next, looks at all tokens at once and has no sense of order. Without this, "dog bites man" and "man bites dog" look the same.
- HOW
- Add the two lists number by number. Now each vector says both which word and where.
LIMIT1,024 rows means GPT-2 can read at most 1,024 tokens at a time. That's its context window.
04 PART 4 · INSIDE THE BLOCK
LayerNorm
- WHAT
- Re-centres each token's vector to an average of 0, and re-scales it to a spread of 1.
- WHY
- Numbers passing through dozens of layers drift: some blow up, some shrink to nothing. Normalising keeps every layer working on the same scale, so training stays stable.
- HOW
- Subtract the mean, divide by the standard deviation, then apply two learned knobs (scale and shift) per number.
YOU ARE NOWinside the transformer block. The next six parts are the block.
05 PART 5 · ATTENTION, 1 OF 4
Query, key, value
- WHAT
- Each token makes three new vectors by multiplying with three learned matrices.
- WHY
- A question (what I need), a label (what I am) and a message (what I give). For "it" in "the animal was tired because it…", the query asks for a noun to refer to; "animal"'s key says "noun, living thing". Splitting the roles lets a token be found for one reason and deliver something else.
- HOW
- Like a search: the query is the search box, keys are the titles, values are the pages. The next part matches queries to keys.
CAREFUL"Question, label, message" is an aid. Training decides what the vectors actually hold.
06 PART 6 · ATTENTION, 2 OF 4
Scores, and no peeking
- WHAT
- Every token's query is compared with every earlier token's key. Each comparison is one number: the score.
- WHY
- A dot product is big when two vectors point the same way, so a high score means "this one has what I'm looking for". Future tokens are masked out: in training the next word is the answer, so a token must not see it.
- HOW
- score = q · k ÷ √d. Dividing by √d (here √8) keeps scores from getting too large as vectors get longer.
07 PART 7 · ATTENTION, 3 OF 4
Softmax, then mix
- WHAT
- Each row of scores becomes weights that add up to 1. Each token's output is the weighted mix of the values.
- WHY
- This is how information moves between tokens. The last "the" can pull in "something was sat on" from sat on, which is what it needs to guess mat.
- HOW
- softmax turns any numbers into positive weights: eˢ ÷ (sum of all eˢ). Then output = w₁v₁ + w₂v₂ + … Hover a row on the right.
VS LSTMAn LSTM reads one word at a time and squeezes everything so far into one memory vector, so early words fade. Attention looks straight back at every earlier token, however far.
HONEST NUMBERSThese weights come from random, untrained matrices, so the pattern is noise. Training is what turns it into something useful (next part).
08 PART 8 · ATTENTION, 4 OF 4
Many heads
- WHAT
- GPT-2 runs 12 attention heads side by side, each with its own Q, K and V matrices on a 64-number slice.
- WHY
- One pattern can't track everything. Trained heads specialise: one looks at the previous word, one finds the subject, one copies repeated words.
- HOW
- 12 heads × 64 numbers = 768. Glue the outputs end to end, then one more matrix (the projection) mixes them back into one vector per token.
ILLUSTRATEDThe patterns on the right are the kinds researchers find in trained models, drawn by hand, not read from GPT-2.
09 PART 9
Residual connection
- WHAT
- Add attention's output back onto its input, instead of replacing it.
- WHY
- Think of a stream running through the whole model. Each part reads the stream and adds a small edit. Nothing gets lost, and in training the error signal has a straight road back to the first layers, so deep models can learn at all.
- HOW
- x = x + attention(LayerNorm(x)). One plus sign, zero parameters.
CHEAPEST PART0 parameters. Probably the reason models can be 96 blocks deep.
10 PART 10
MLP
- WHAT
- Another LayerNorm, then a small two-layer network applied to each token on its own: widen 768 → 3,072, bend, narrow back to 768. Then add to the stream again.
- WHY
- Attention moves information between tokens. The MLP works on what each token now holds. Much of what the model "knows" (Paris is in France) seems to be stored in these weights.
- HOW
- The bend is GELU: let positive numbers through, squash negatives toward 0. Without a bend, two layers of multiplying would collapse into one.
WHERE THE WEIGHT ISThe MLP is two-thirds of each block's parameters: 4.7M of 7.1M.
11 CHECKPOINT
That's one transformer block
- WHAT
- LayerNorm → attention → add → LayerNorm → MLP → add. Vectors go in, vectors of the same size come out.
- WHY
- Same size in and out means blocks can be stacked like bricks. That's the trick the whole field runs on.
- HOW
- 7,087,872 parameters per block in GPT-2 small.
NOTHING NEW BUT ONEDot products, dense layers, skip connections, normalising: all older than this block. The only new part is attention (2017, "Attention Is All You Need").
ACT 2
Turn it into an LLM
Parts 12–21. Stack it, read out a word, pick one, loop, train, scale, tune.
12 PART 12
Stack it ×12
- WHAT
- Twelve copies of the block in a row, each with its own weights. The stream flows through all of them.
- WHY
- Each block can build on the last. Roughly: early blocks handle grammar and nearby words; later blocks handle meaning and what should come next.
- HOW
- Same block, different numbers. Watch the counter.
FOR SCALEGPT-3 stacks 96 blocks, with 12,288 numbers per token instead of 768.
13 PART 13
Unembedding
- WHAT
- One last LayerNorm. Then the last token's vector is scored against every row of the token table: 50,257 scores, called logits.
- WHY
- We only need the last position: it has read the whole sentence, and its job is "what comes after me?"
- HOW
- GPT-2 reuses the embedding table from part 2, run backwards. A vector that ends up near the row for " mat" gives " mat" a high score.
FREEReusing the table saves 38.6M parameters. Only the final LayerNorm adds any: 1,536.
14 PART 14
Softmax
- WHAT
- Turn the 50,257 scores into probabilities that add up to 100%.
- WHY
- Scores can be any size and sign. Probabilities can be compared, sampled from, and graded in training.
- HOW
- The same softmax as inside attention: eˢ for each, divided by the total. It's an ordinary classifier, with 50,257 classes.
15 PART 15
Sampler
- WHAT
- Pick one token from the probabilities.
- WHY
- Always taking the top choice (greedy) gives flat, repetitive text that can loop. A little randomness reads more human.
- HOW
- Temperature divides the scores before softmax: below 1 sharpens toward the top choice, above 1 flattens toward chaos. Top-p keeps only the most likely tokens that add up to p, then picks among them. Try the slider.
WHY ANSWERS DIFFERAsk the same question twice and get two answers: that's the sampler, not the model changing its mind.
16 PART 16
The loop
- WHAT
- Stick the chosen token on the end and run the whole machine again. Repeat until a stop token.
- WHY
- One pass gives one token. This is why chat answers stream out word by word.
- HOW
- The KV cache keeps every earlier token's keys and values, so each new pass only computes one new row instead of redoing the whole sentence.
VS LSTMBoth generate one token at a time. The difference is training: an LSTM must read a sentence step by step, while a transformer learns from every position of a sentence at once. That's what made huge training runs practical.
17 PART 17
Training
- WHAT
- Start with all 124 million numbers random. Guess. Measure how wrong. Nudge every knob the helpful way. Repeat, billions of times. That is all of training.
- WHY
- Nobody writes these numbers by hand, and no labels are needed: the text is its own answer key. Predicting the next token, over enough text, forces the model to pick up grammar, facts and some reasoning on the way.
- HOW
- Loss = −log(probability given to the true next token). Backpropagation works out which way to nudge each number; the optimiser takes a small step.
STARTING POINTA random model spreads its bets evenly: 1 in 50,257. Its loss is ln(50,257) ≈ 10.8. That's where every training run starts.
18 PART 18
Scale
- WHAT
- Same recipe, much bigger: more parameters, more text, more compute.
- WHY
- Loss keeps falling smoothly as all three grow together (the scaling laws), and new skills show up along the way.
- HOW
- GPT-2 → GPT-3 changed almost nothing in the design. Mostly it was 100× more parameters and far more data.
VS LSTMThe big jump from LSTMs to LLMs wasn't one clever trick. It was data and compute, which the transformer could finally use.
GPT-3175 billion parameters, trained on about 300 billion tokens. The counter just jumped.
19 PART 19
Post-training
- WHAT
- Turn the base model into an assistant: first train on example conversations (supervised fine-tuning), then on human preferences (RLHF).
- WHY
- A base model only continues documents. Ask it a question and it may continue with more questions, because that's what quiz pages look like. A chat is a script the model completes: fine-tuning teaches it to play the assistant's part.
- HOW
- People rate pairs of answers. A reward model learns their taste, and the LLM is trained to score well with it.
20 PART 20
The context window
- WHAT
- Everything the model sees is the tokens in the window: your prompt, the chat so far, its own answer. Nothing else.
- WHY
- It has two memories. The weights are something it read months ago: vague, fixed. The window is a page in front of it: exact, but only what fits. Outside the window, it has never heard of you.
- HOW
- Attention compares every pair of tokens: twice the input, four times the work. Long windows also spread attention thin: models often miss things in the middle of a long prompt.
21 DONE
You built GPT-2
- WHAT
- Tokenizer → embeddings → 12 blocks of attention and MLP → unembedding → softmax → sampler, in a loop.
- WHY
- Every part serves one goal: a better guess at the next token.
- HOW
- 124,439,808 numbers, all learned from text.