Training: Pretraining, Fine-tuning, RLHF
A chat assistant is made in stages. First a model learns language and world knowledge from a huge amount of text (pretraining). Then it is taught to follow instructions and hold conversations (fine-tuning). Finally it is shaped by human and AI preferences to be helpful, honest and safe (RLHF and related methods). This lesson explains each stage with small simulations — real training uses thousands of GPUs for weeks, so treat the code as illustrations of the ideas.
Stage 1: pretraining
During pretraining the model reads trillions of tokens of text (web pages, books, code, …) and learns to predict the next token. The training signal comes from the text itself — no human labels are needed, which is why it is called self-supervised.
The loss is cross-entropy: the negative log of the probability the model gave to the token that actually came next. Lower is better. Here we "pretrain" a bigram model by counting and measure its loss on a sentence:
import math
from collections import Counter, defaultdict
corpus = ("the sun rises in the east . the sun sets in the west . "
"the moon rises at night . birds sing in the morning .").split()
vocab = sorted(set(corpus))
counts = defaultdict(Counter)
for a, b in zip(corpus, corpus[1:]):
counts[a][b] += 1
def prob(a, b, smoothing=0.1):
total = sum(counts[a].values()) + smoothing * len(vocab)
return (counts[a][b] + smoothing) / total
def cross_entropy(sentence):
words = sentence.split()
losses = [-math.log(prob(a, b)) for a, b in zip(words, words[1:])]
return sum(losses) / len(losses)
print(f"familiar: {cross_entropy('the sun rises in the east'):.3f}")
print(f"plausible: {cross_entropy('the moon sets in the west'):.3f}")
print(f"scrambled: {cross_entropy('east the in rises sun the'):.3f}")familiar: 1.155
plausible: 1.624
scrambled: 3.664
The model is least "surprised" by text like what it has seen. A pretrained LLM is a powerful text completer, but not yet an assistant: ask it a question and it might continue with more questions, because that is also common on the web.
Stage 2: supervised fine-tuning (SFT)
Next, the model is trained further on a much smaller, carefully curated set of examples: instructions paired with good responses, written or checked by people. The training objective is the same next-token loss, but the data now teaches the format and behaviour of an assistant.
Fine-tuning shifts the model's probabilities towards the new data. In our bigram toy, adding a few domain examples (with more weight) changes what follows "the":
from collections import Counter
def next_word_probs(text, word):
words = text.split()
c = Counter(b for a, b in zip(words, words[1:]) if a == word)
total = sum(c.values())
return {w: round(n / total, 2) for w, n in c.most_common(3)}
base = "the sun rises . the sun sets . the moon rises . the cat sleeps ."
domain = "the patient rests . the patient recovers . the doctor visits ."
print("before fine-tuning:", next_word_probs(base, "the"))
print("after fine-tuning: ", next_word_probs(base + " " + domain * 3, "the"))before fine-tuning: {'sun': 0.5, 'moon': 0.25, 'cat': 0.25}
after fine-tuning: {'patient': 0.36, 'doctor': 0.27, 'sun': 0.18}
Companies also fine-tune models for narrow tasks (a style, a classification task, a domain's vocabulary). Lightweight techniques such as LoRA train only small extra matrices instead of all parameters, making this much cheaper.
Stage 3: learning from preferences (RLHF)
"Good" answers are hard to define with examples alone: they should be helpful, accurate, safe and well-calibrated. Reinforcement learning from human feedback (RLHF) works like this:
- The model produces two or more answers to the same prompt.
- People (or another model, guided by written principles) pick which answer is better.
- A reward model is trained on these comparisons to predict a score for any answer.
- The LLM is optimised to produce answers the reward model scores highly, while staying close to its fine-tuned behaviour.
Below, a tiny reward model learns from preference pairs. Each answer is described by three hand-made features; training adjusts the weights so preferred answers score higher (the Bradley–Terry model used in many RLHF systems):
import numpy as np
# features: [answers the question, polite, contains made-up facts]
pairs = [ # (preferred, rejected)
([1, 1, 0], [0, 1, 0]),
([1, 0, 0], [1, 0, 1]),
([1, 1, 0], [1, 1, 1]),
([0, 1, 0], [0, 0, 1]),
([1, 1, 0], [1, 0, 0]),
]
w = np.zeros(3)
for epoch in range(200):
for good, bad in pairs:
good, bad = np.array(good), np.array(bad)
p_good = 1 / (1 + np.exp(-(w @ good - w @ bad))) # P(good preferred)
w += 0.1 * (1 - p_good) * (good - bad) # gradient ascent
print("learned weights:", np.round(w, 2))
candidates = {"helpful + polite": [1, 1, 0], "helpful but invents facts": [1, 1, 1], "polite non-answer": [0, 1, 0]}
for name, f in candidates.items():
print(f"{name:<26} reward = {w @ np.array(f):.2f}")learned weights: [ 2.9 3.01 -3.71]
helpful + polite reward = 5.91
helpful but invents facts reward = 2.20
polite non-answer reward = 3.01
The reward model discovered, from comparisons alone, that answering helps and invented facts hurt. Related methods such as DPO (direct preference optimisation) skip the separate reward model, and RLAIF / constitutional approaches use AI feedback guided by written principles. Newer reasoning models are additionally trained with reinforcement learning on tasks whose answers can be checked automatically, such as maths and code.
Summary
| Stage | Data | Teaches |
|---|---|---|
| Pretraining | trillions of tokens of raw text | language, facts, patterns, code |
| Supervised fine-tuning | thousands–millions of instruction/response examples | following instructions, chat format |
| Preference tuning (RLHF, DPO, RLAIF) | ranked answers | helpfulness, honesty, safety, style |
Note: A model's knowledge stops at its training cutoff. It can't know about later events unless you provide them in the prompt (for example through retrieval or a search tool).
Go further: Each stage has its own lesson in the Machine Learning track: Pretraining a Tiny GPT, Supervised Fine-Tuning and Loss Masking and Preference Tuning: Reward Models, RLHF and DPO.
Test yourself
Why is pretraining called self-supervised?
- The model labels its own outputs as correct
- The next token in the text itself serves as the training label
- No computers are needed
- Humans supervise each step
What does a reward model in RLHF learn from?
- Raw web text
- Comparisons where people (or an AI) chose the better of two answers
- Token IDs
- The model's parameters
Which statement about fine-tuning is correct?
- It replaces pretraining
- It continues training on a smaller, targeted dataset to change behaviour
- It increases the context window
- It deletes old knowledge on purpose