How LLMs Are Trained: Pretraining, SFT & RLHF
Generative & Agentic AI · AI Foundations · Intermediate · 22 min
Explain the three training stages that turn random numbers into a helpful assistant, and why each stage is needed.
A newborn mind reads a whole library by covering every next word and guessing it. Then a tutor shows it how to answer questions. Then a panel of judges keeps saying 'this answer is better than that one' until its manners match what people want.
The idea in everyday words
Training a chef. First they spend years eating and reading every recipe ever written (pretraining): they know food, but if you ask for dinner they might recite a cookbook. Then a mentor shows them hundreds of 'order → perfect dish' examples (supervised fine-tuning). Finally diners taste two versions of each dish and say which they prefer, and the chef adjusts to the crowd's taste (RLHF).
Stage 1, pretraining: guess the next token, trillions of times
An LLM is trained on one simple game: given the text so far, predict the next token (a token is a word or a piece of a word).
The pipeline for every guess:
- Tokenizer: text → token IDs (
"the cat sat"→ three numbers). - Embeddings: each ID → a vector of numbers that captures meaning.
- Transformer layers: attention mixes information between tokens, many layers deep.
- Softmax: one probability for every token in the vocabulary (often 30k to 200k+ tokens).
- Loss:
-log(probability given to the real next token). Confident and right = small loss; confident and wrong = huge loss.
Then backprop nudges billions of weights, and the game repeats on the next chunk.
Why this is so powerful: the labels are free. Every sentence on the internet is its own answer key. "The cat sat on the mat" gives five training examples: the → cat, the cat → sat, and so on. This is called self-supervised learning.
import math
from collections import Counter, defaultdict
corpus = "the cat sat on the mat . the cat ate the fish . the dog sat on the rug ."
tokens = corpus.split()
counts = defaultdict(Counter)
for prev, nxt in zip(tokens, tokens[1:]):
counts[prev][nxt] += 1 # "training" = counting what follows what
def prob(prev, nxt):
return counts[prev][nxt] / sum(counts[prev].values())
print("after 'the':", {w: round(prob("the", w), 2) for w in counts["the"]})
sentence = "the cat sat on the rug".split()
losses = [math.log(1 / prob(a, b)) for a, b in zip(sentence, sentence[1:])] # = -log(p)
print("loss per token:", [round(l, 2) for l in losses])
print("average loss:", round(sum(losses) / len(losses), 3))
This toy counts pairs. A real LLM learns the same kind of probabilities, but conditioned on thousands of previous tokens instead of one.
Scaling laws and compute-optimal training
Researchers found that loss falls smoothly and predictably as you increase three things: model size (parameters, N), data (training tokens, D) and compute. Double the right one and you can roughly predict the new loss before you train. These are scaling laws.
A handy rule: training compute ≈ 6 × N × D floating-point operations.
N = 7e9 # 7 billion parameters
D = 140e9 # 140 billion tokens (20 per parameter)
print(f"training FLOPs ~ {6 * N * D:.2e}")
Compute-optimal (the "Chinchilla" result, 2022): for a fixed compute budget, grow parameters and tokens together. Roughly 20 training tokens per parameter. Many earlier models were too big for the data they saw.
But inference matters too. A model is trained once and served billions of times. So labs now often train smaller models on far more tokens than "optimal" (Meta's Llama 3 8B saw over 15 trillion tokens). The extra training cost buys a model that is cheaper and faster to run forever after.
| Lever | What it buys | What it costs |
|---|---|---|
| More parameters | more capacity | more memory and slower inference |
| More tokens | better use of capacity | longer training, needs good data |
| Better data | often the biggest win | cleaning, deduplication, filtering |
Stage 2, supervised fine-tuning (SFT): learn to answer
After pretraining you have a base model. It knows language and many facts, but it was trained to continue documents. Ask "What is the capital of France?" and it might continue with "What is the capital of Spain? What is the capital of…" because that is what quiz pages look like.
Supervised fine-tuning (also called instruction tuning) trains on prompt → ideal response pairs written or checked by people:
### Instruction: Summarise this email in one line.
### Input: Hi team, the 2pm meeting is moved to 3pm in room B...
### Response: The meeting moved to 3pm in room B.
- Same next-token loss as pretraining, but usually computed only on the response tokens.
- Thousands to hundreds of thousands of examples: tiny compared with pretraining, so it is fast and cheap.
- Mixing many task types (summarise, classify, translate, code) gives a model that follows new instructions too. FLAN was an early, famous example of this multitask mix.
What SFT does not teach: judgement. It imitates the form of good answers, so it may cheerfully help with something harmful or invent a confident answer to a question it cannot know.
Stage 3, preference tuning: RLHF and DPO
People find it hard to write the perfect answer, but easy to say which of two answers is better. Preference tuning uses that.
RLHF (reinforcement learning from human feedback):
- The SFT model writes two or more answers to each prompt. People rank them.
- Train a reward model: a network that reads (prompt, answer) and outputs a score predicting what people would prefer.
- Optimise the SFT model to earn higher reward, usually with an algorithm called PPO. A KL penalty keeps it close to the SFT model so it does not "game" the reward model with weird text that scores high but reads badly (reward hacking).
DPO (direct preference optimisation) skips the separate reward model and the RL loop. It trains directly on (prompt, preferred answer, rejected answer) triples with a simple loss that raises the preferred answer's probability relative to the rejected one. It is simpler and more stable, so it is very popular.
Variants: RLAIF uses an AI model (guided by a written set of principles, as in Anthropic's Constitutional AI) to produce some of the preference labels, which scales better than people alone.
The target is often summed up as HHH: helpful (actually solves the task), honest (does not make things up, admits uncertainty) and harmless (refuses dangerous requests, avoids toxic output).
Step by step
- Tokenise:
"the cat sat on" → 4 token IDs. The training target at the last position is the next real token, "the".
- Predict:
Embeddings → transformer → softmax gives p("the") = 0.40, p("a") = 0.25, p("my") = 0.10, …
- Loss:
loss = −ln(0.40) ≈ 0.92. If the model had said 0.90, loss would be 0.11. Backprop nudges weights to raise p("the").
- Repeat at scale:
Do this for every position of trillions of tokens. Result: a base model that continues text well.
- SFT:
Train on ~10k-100k+ instruction → answer pairs. Now "What is 2+2?" gets "4" instead of more quiz questions.
- Collect preferences:
For "Write a fake doctor's note", raters prefer "I can't forge that, but I can help you ask for a day off" over the forged note.
- Optimise:
A reward model learns those preferences; PPO (or DPO directly) shifts the model toward preferred answers while staying close to the SFT model.
Code example
# A bigram "language model": train by counting, then generate greedily.
from collections import Counter, defaultdict
corpus = "the cat sat on the mat . the cat ate the fish . the dog sat on the rug ."
tokens = corpus.split()
model = defaultdict(Counter)
for prev, nxt in zip(tokens, tokens[1:]):
model[prev][nxt] += 1
print("training pairs:", len(tokens) - 1)
print("after 'the':", dict(model["the"]))
word, out = "the", ["the"]
for _ in range(8):
word = model[word].most_common(1)[0][0] # greedy: always the top token
out.append(word)
print("generated:", " ".join(out))
print("It loops because it only remembers ONE previous token. Real LLMs see thousands.")Interview tips
Walk through the three stages (pretraining, SFT, RLHF/DPO): the data each uses, roughly how much, and the failure each one fixes.
Explain the reward model and why PPO uses a KL penalty against the SFT model (to prevent reward hacking).
Compare RLHF with DPO: DPO removes the separate reward model and the RL loop, which makes it simpler and more stable.
Scaling laws: loss falls predictably with parameters, data and compute; Chinchilla suggests about 20 tokens per parameter for compute-optimal training, but inference cost pushes teams to train smaller models longer.
Be ready for: "Would you pretrain your own model?" Almost always no. Start from a foundation model (for example on Amazon Bedrock) and adapt it.
Challenge: Next-Token Training Pairs
A language model learns from (context → next token) pairs. Write make_training_pairs(tokens, context) that returns every pair as [context_tokens, target].
- Every token except the first is a target, in order.
- Its context is the tokens right before it, but at most
contexttokens (the model's window). - Return a list of lists.
Example:
make_training_pairs(["a", "b", "c", "d"], 2)
→ [[["a"], "b"], [["a", "b"], "c"], [["b", "c"], "d"]]
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- Hugging Face blog: Illustrating RLHF
- InstructGPT paper: Training language models to follow instructions with human feedback
- Chinchilla paper: Training Compute-Optimal Large Language Models
- DPO paper: Direct Preference Optimization
More in AI Foundations
- Machine Learning in 15 Minutes
- Neural Networks from Scratch
- What Is GenAI? LLMs & Tokens
- Tokenization & Byte-Pair Encoding
- Transformers & Attention
- Reasoning Models & RL Post-Training
Previous: Transformers & Attention · Next: Reasoning Models & RL Post-Training