How LLMs are trained
About this lesson
A large language model is trained in stages. Pretraining turns raw text into its own labelled examples and teaches the model to predict the next token: predict, score the guess with cross-entropy loss, follow the gradient, update the weights, and repeat billions of times. Fine-tuning on demonstrations and then on human preferences turns the text predictor into a helpful assistant. Watch one training step happen in real numbers on a six-token sentence, then watch it repeat until the model learns that "the" is followed by cat or mat, 50-50.
Start with lots of text
Pretraining starts with a huge pile of text: GPT-3 learned from 300 billion tokens. Ours is one sentence, "the cat sat on the mat": 6 tokens. To keep it simple, each word is one token here.
text "the cat sat on the mat" tokens the | cat | sat | on | the | mat vocab cat mat on sat the (5 different tokens) GPT-3 300 billion tokens of training text stage 1 of 3: pretraining
Read the lesson step by step
Start with lots of text
Pretraining starts with a huge pile of text: GPT-3 learned from 300 billion tokens. Ours is one sentence, "the cat sat on the mat": 6 tokens. To keep it simple, each word is one token here.
text "the cat sat on the mat" tokens the | cat | sat | on | the | mat vocab cat mat on sat the (5 different tokens) GPT-3 300 billion tokens of training text stage 1 of 3: pretrainingThe text labels itself
Every token is the right answer for the token before it. 6 tokens give 5 examples: the→cat, cat→sat, sat→on, on→the, the→mat. Nobody writes labels: the text supplies them. This is called self-supervised learning.
pairs = list(zip(text, text[1:])) example 1 input "the" right answer "cat" example 2 input "cat" right answer "sat" example 3 input "sat" right answer "on" example 4 input "on" right answer "the" example 5 input "the" right answer "mat" no human labels: the next token IS the labelPredict the next token
The model's weights hold a score (a logit) for every possible next token. Given "the", softmax turns its 5 scores into probabilities that add up to 1. Our untrained toy starts every score at 0, so each token gets 0.20: a blind guess.
p = softmax(W[a]) scores W["the"] = [0, 0, 0, 0, 0] softmax p_j = e^(z_j) / sum of e^(z_k) p cat 0.20 mat 0.20 on 0.20 sat 0.20 the 0.20Score the guess
The right answer was "cat". Cross-entropy loss is minus the log of the probability given to the right token: −ln 0.20 = 1.61. A sure, correct guess (probability 1) would score 0. Lower is better.
loss = -math.log(p[b]) p["cat"] = 0.20 loss = -ln(0.20) = 1.61 p = 1.00 -> loss 0; p = 0.01 -> loss 4.61Which way to nudge
The gradient says how the loss changes as each score moves: p − 1 for the right token, p for the rest. "the → cat" alone gives cat −0.8. Both "the" examples add up: cat (−0.8 + 0.2) = −0.6, mat −0.6, others +0.4.
G[a][j] += p[j] - (j == b) the→cat cat −0.8 mat +0.2 on +0.2 sat +0.2 the +0.2 the→mat cat +0.2 mat −0.8 on +0.2 sat +0.2 the +0.2 sum G cat −0.6 mat −0.6 on +0.4 sat +0.4 the +0.4 negative = raise this score; positive = lower itUpdate the weights
Gradient descent steps against the gradient: W −= lr × G, learning rate 1. The cat and mat scores rise to 0.6; the rest fall to −0.4. Now cat and mat get 0.32 each; the loss for "the → cat" drops to 1.13.
W[a][j] -= lr * G[a][j] lr = 1 scores W["the"] = [0.6, 0.6, -0.4, -0.4, -0.4] p cat 0.32 mat 0.32 on 0.12 sat 0.12 the 0.12 loss 1.61 -> 1.13Repeat, many times
Repeat: predict, score, nudge, update. After 100 steps, "the" is followed by cat 0.497 and mat 0.497. The loss heads to ln 2 ≈ 0.69, not 0: in our text, cat and mat really are 50-50. The model learned probabilities.
steps p(cat) p(mat) loss "the→cat" 1 0.322 0.322 1.133 2 0.383 0.383 0.959 3 0.414 0.414 0.881 5 0.445 0.445 0.810 10 0.471 0.471 0.753 20 0.485 0.485 0.723 50 0.494 0.494 0.705 100 0.497 0.497 0.699 mean loss over the text: 1.61 -> 0.28Same loop, giant scale
Real LLMs run this same loop, but a transformer reads all the earlier tokens, not just one. GPT-3 has 175 billion weights. Chinchilla, 70 billion weights, read 1.4 trillion tokens: about 20 tokens per weight.
weights training tokens ours 25 5 examples GPT-3 (2020) 175 billion 300 billion Chinchilla 70 billion 1.4 trillion same loss, same gradient descent; batches of millions of tokens, many GPUs, and Adam: gradient descent with its own step size for each weightFine-tune on examples
A pretrained model only continues text. Supervised fine-tuning trains it on prompts paired with answers people wrote, using the same next-token loss, usually counted only on the answer tokens. InstructGPT used about 13,000 such demonstrations.
stage 2: supervised fine-tuning (SFT) prompt Q: Capital of France? answer A: Paris. loss on answer tokens only (the prompt is masked) same loop as before, far less dataLearn from preferences
People compare two answers and pick the better one. A reward model learns to score answers the way people ranked them; reinforcement learning (PPO, Proximal Policy Optimization) then nudges the LLM toward higher scores. Labellers preferred a 1.3-billion-weight InstructGPT to the 175-billion-weight GPT-3.
stage 3: RLHF answers "Paris." > "No idea." (people pick) reward model trained on those rankings PPO raise the reward, with a penalty for drifting far from the fine-tuned model DPO a newer shortcut: no separate reward model
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01Pretraining on "the cat sat" needs which labels?
Pretraining is self-supervised. Each token is the right answer for the tokens before it, so any text supplies its own labels.
02The model gives the right next token a probability of 0.5. What is its cross-entropy loss for that example?
Cross-entropy loss is minus the natural log of the probability given to the right token: −ln 0.5 ≈ 0.69. Only a probability of 1 gives a loss of 0.
03With softmax and cross-entropy, the probabilities are cat 0.2, mat 0.2, on 0.2, sat 0.2, the 0.2 and the right answer is cat. What is the gradient for the cat score?
The gradient is p minus 1 for the right token (0.2 − 1 = −0.8) and p for the others (+0.2). Gradient descent subtracts it, so the cat score goes up and the others go down.
04In "the cat sat on the mat", "the" is followed once by cat and once by mat. After long training, why does the loss for "the → cat" stay near 0.69 and not reach 0?
The model learns the probabilities in its training text. When the text itself is uncertain, the lowest possible loss is above zero.
05After pretraining, what do supervised fine-tuning (SFT) and then RLHF each add?
SFT keeps the next-token loss but zeroes it on the prompt, so the model learns to write the answer (Llama 2, §3.1). RLHF then has people rank answers, a reward model learns those rankings, and PPO tunes the model toward higher reward while keeping it close to the SFT model.
Glossary
- Pretraining
- The first and largest stage: train a model to predict the next token on a huge amount of unlabelled text. It is self-supervised: the next token is the label, so no person has to write labels.
- Logit
- A raw score the model gives each possible next token before softmax turns the scores into probabilities.
- Softmax
- Turns a list of scores into probabilities that are all positive and add up to 1: e to the power of each score, divided by the sum.
- Cross-entropy loss
- Minus the log of the probability the model gave the right answer. It is 0 for a sure, correct guess and grows as that probability shrinks.
- Gradient descent
- Change each weight a small step in the direction that lowers the loss: weight minus learning rate times gradient.
- Supervised fine-tuning (SFT)
- Further training on prompts paired with answers people wrote, using the same next-token loss.
- PPO (Proximal Policy Optimization)
- A reinforcement-learning method that changes the model in small, limited steps toward answers with a higher reward, so one update cannot change it too much.
- RLHF
- Reinforcement learning from human feedback: a reward model learns from people's rankings of answers, and reinforcement learning tunes the model to score higher.
Notes and sources
- Our model is a bigram model: it looks only at the previous token, with one row of scores per token. A real LLM is a transformer that looks at every earlier token, with billions of weights, but it is trained with the same loss and the same gradient descent.
- We take full-batch steps (all five examples, gradients added) with learning rate 1. Real training uses random mini-batches of millions of tokens, a tuned learning-rate schedule and the Adam optimiser (gradient descent that adapts the step size for each weight from its recent gradients).
- Real tokenizers split text into word pieces, so a word can be several tokens. Here each word is one token to keep the numbers small.
- Real LLMs start from small random weights, not zeros. Our toy starts every score at 0 so the first guess is exactly even and the numbers are easy to follow.
- The Python program in the lesson is real: run it and it prints "1.61 0.28" and then the probabilities after "the".
- Vaswani et al., Attention Is All You Need (2017): the transformer
- Radford et al., Improving Language Understanding by Generative Pre-Training (2018)
- Brown et al., Language Models are Few-Shot Learners (GPT-3, 2020): 175B parameters, 300B training tokens
- Hoffmann et al., Training Compute-Optimal Large Language Models (Chinchilla, 2022): 70B parameters, 1.4T tokens
- Ouyang et al., Training language models to follow instructions with human feedback (InstructGPT, 2022)
- Christiano et al., Deep reinforcement learning from human preferences (2017)
- Schulman et al., Proximal Policy Optimization Algorithms (2017)
- Rafailov et al., Direct Preference Optimization (2023)
- Touvron et al., Llama 2: Open Foundation and Fine-Tuned Chat Models (2023): loss on answer tokens only in SFT
- Goodfellow, Bengio & Courville, Deep Learning (MIT Press, 2016): softmax, cross-entropy, gradient-based learning
- Stanford CS224N: Natural Language Processing with Deep Learning
- Python documentation: math.exp and math.log
Quiz Unlocks after the last step.