Level 3 In-Depth AI · Transformers and Language Models
RLHF and Preference Optimization
How chat models learn what people actually prefer. Train a reward model on human comparisons and optimise against it with PPO, or skip the reward model with DPO, or let an AI do the judging (RLAIF, Constitutional AI).
- Level
- ●●●●● Advanced
- Reading
- 15 min
- To learn it well
- 1.5 hours to read, an afternoon to practise
- Builds on
- 51 concepts →
- Quiz
- 5 questions ↓
This leads to
Reasoning Models and Test-Time ComputeThe full path from zero — 51 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- Python for AI
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Tokenization
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Tensors and Shapes
- NumPy and Array Thinking
- Language Modeling and Next-Token Prediction
- Supervised Learning
- Reinforcement Learning: The Basics
- Linear Regression
- Training, Validation and Test Sets
- The Perceptron
- Markov Decision Processes
- Logistic Regression
- Overfitting and the Bias–Variance Tradeoff
- Value Functions and Bellman Equations
- Regularization: L1 and L2
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Dropout and Regularizing Neural Networks
- Policy Gradients
- PyTorch
- Vanishing and Exploding Gradients
- Normalization Layers: BatchNorm and LayerNorm
- Optimizers: SGD, Momentum and Adam
- Actor-Critic Methods
- LSTMs and GRUs
- Residual Connections
- Training Neural Networks in Practice
- Proximal Policy Optimization
- Sequence-to-Sequence Models
- Transfer Learning
- Attention
- Self-Attention and Multi-Head Attention
- Positional Encodings
- The Transformer
- GPT and Decoder-Only Models
- Pretraining Large Language Models
- Fine-Tuning
- Instruction Tuning and Chat Models
- RLHF and Preference Optimization
Read them roughly in this order. See it on the concept map →
Why it matters
Instruction tuning teaches a model to imitate example answers. But for most requests there is no single right answer, and people are much better at judging answers than at writing perfect ones. You might struggle to write a great poem, an ideal explanation of tax law, or the perfect tactful refusal, but shown two attempts, you can usually say which is better.
Reinforcement learning from human feedback (RLHF) turns those judgements into training signal. It was the step that made ChatGPT feel so different from GPT-3: in OpenAI's InstructGPT study (2022), human raters preferred the answers of a 1.3-billion-parameter model trained with RLHF over those of the 175-billion-parameter GPT-3, a model more than 100 times larger. Since then some form of preference optimisation has been part of training nearly every major assistant: it makes them more helpful, more honest about uncertainty, and better at refusing harmful requests.
This chapter covers the classic pipeline (a reward model plus PPO), the simpler DPO method that now dominates open-model training, AI-generated feedback (RLAIF and Anthropic's Constitutional AI), and the main way it all goes wrong: reward hacking. The same machinery, pointed at automatically checkable rewards, produces the Reasoning Models and Test-Time Compute of 2024–2025.
The intuition
Imagine training a new chef. You could give them recipes (that's supervised fine-tuning). But to make them great, you let them cook, taste two of their dishes side by side, and tell them which one is better. Over many rounds they develop a sense of what you like and drift towards it.
There are two problems. You can't taste millions of dishes yourself. So you train a food critic who has learned your taste from a few thousand of your comparisons, and the chef practises against the critic instead. That critic is the reward model.
And chefs are clever. Left alone with a critic, a chef might discover that the critic adores salt and start salting everything heavily, scoring brilliantly while the food gets worse. To prevent this you keep the chef on a leash: they are penalised for drifting too far from the cooking style they had at the start. That leash is the KL penalty.
Key idea RLHF learns from comparisons, not demonstrations. A reward model turns human preferences into a score, and RL pushes the model towards higher scores while a KL penalty keeps it from straying far from where it started. DPO reaches the same goal with a single classification-style loss.
How it works
Some vocabulary first. In RL terms (Reinforcement Learning: The Basics), the language model being trained is the policy model : given a prompt , it produces a response by sampling tokens. The reference model is a frozen copy of the model before preference training, usually the SFT model.
Step 1: supervised fine-tuning
Start from an instruction-tuned model (Instruction Tuning and Chat Models). This matters: RL only works well if the model already produces reasonable answers some of the time, so that there is something to prefer.
Step 2: preference data and the reward model
Preference data is collected like this: take a prompt, sample two (or more) responses from the model, and ask a human which is better. Each record is a triple : the prompt, the winning response and the losing response. InstructGPT had labelers rank between 4 and 9 responses per prompt, which gives many pairs at once.
The reward model is usually a copy of the language model with its output layer replaced by a single number: the score. To train it from comparisons we need a link between scores and preferences. The standard choice is the Bradley–Terry model (from 1952, originally for ranking sports teams and taste tests): the probability that is preferred over is the sigmoid of the difference in their scores,
Training maximises the likelihood of the observed human choices, which means minimising
averaged over all comparisons. This is just Maximum Likelihood Estimation for a binary classifier whose input is "which of these two wins?".
Worked example. Suppose the reward model currently scores the winner 1.5 and the loser 0.5. The difference is 1.0, so and the loss is . If it scored them the wrong way round (0.5 and 1.5), and the loss is : a much bigger push to fix it. Only differences in reward matter, so the scale's zero point is arbitrary.
Step 3: RL with a KL penalty
Now optimise the policy to produce high-reward answers. The objective is:
In words: sample prompts from the dataset , let the policy answer, and make the reward model's score high on average, but pay a price for every unit of divergence from the reference model. The KL divergence (Entropy, Cross-Entropy and KL Divergence) measures how different two probability distributions are; it is zero when they are identical. In practice it is computed per token as and subtracted from the reward. The coefficient , often somewhere around 0.01 to 0.1, sets the length of the leash.
The KL penalty does three jobs: it stops the policy from exploiting the reward model's blind spots, keeps the text fluent (the reference model knows language well), and preserves the diversity of outputs.
Because generating text is sampling, you can't backpropagate through it. So the policy is updated with a policy-gradient RL algorithm, almost always PPO (Proximal Policy Optimization). PPO's key trick is a clipped update: it compares the probability of each generated token under the new and old policy, and stops the update once that ratio moves outside a small band such as . This keeps each step small and stable. PPO also trains a value model (critic) to estimate expected reward, which reduces the noise in the updates.
The engineering cost is high. A PPO-based RLHF run keeps four large models in play at once: the policy (trained), the value model (trained), the reference model (frozen) and the reward model (frozen). It has many hyperparameters and is notoriously finicky.
DPO: preference optimisation without RL
Direct Preference Optimization (Rafailov et al., 2023) noticed something neat. For the KL-penalised objective above, the best possible policy can be written down exactly:
where just normalises the probabilities to sum to 1. The optimal policy is the reference policy, re-weighted towards high-reward answers. Rearranging, any policy implicitly defines a reward: . Plug that into the Bradley–Terry loss, and cancels because it appears in both the winner's and the loser's term. What remains is a loss on the policy itself:
Read it as: raise the probability of the preferred answer, relative to the reference model, more than you raise the probability of the rejected one. The log-probabilities of whole responses are just sums of the per-token log-probabilities the model already computes.
Worked example. Say . Before training , so both log-ratios are 0, the argument of is 0, and the loss is . After some training the policy has raised the log-probability of by 2.0 nats and lowered that of by 1.0. The argument is , , and the loss is .
DPO needs no reward model, no sampling during training and no value network: just the policy, a frozen reference and a dataset of pairs. It is ordinary supervised training. That simplicity made it the default for open models from late 2023 on. Its weaknesses: it learns only from a fixed (offline) dataset, so it can't explore and improve on answers better than those in the data, and it can over-fit preferences. Variants such as IPO, KTO (which uses thumbs-up/thumbs-down labels instead of pairs), ORPO and SimPO address these in different ways, and "online" or iterative DPO regenerates pairs from the current model.
RLAIF and Constitutional AI
Human labels are slow, expensive and inconsistent. RLAIF (reinforcement learning from AI feedback) replaces the human judge with a language model prompted to compare two answers. A Google study (Lee et al., 2023) found that AI-labelled preferences gave results comparable to human-labelled ones on summarisation and dialogue tasks.
Anthropic's Constitutional AI (Bai et al., December 2022) is the best-known version and aimed specifically at harmlessness. Instead of thousands of human labels about harmful content, the developers wrote a short constitution: a list of natural-language principles such as asking for the response that is least harmful or least likely to assist with illegal activity. Training has two phases:
- Supervised phase (critique and revise). The model answers a red-teaming prompt, is asked to critique its own answer according to a randomly chosen principle, and then to revise it. The model is fine-tuned on the revised answers.
- RL phase (RLAIF). The model generates pairs of answers, and a model asked to apply a principle picks the better one. These AI preferences train a preference model, and RL proceeds as in standard RLHF.
In the paper, helpfulness comparisons still came from humans; harmlessness comparisons came from the AI. The result was a model that was less harmful and less evasive than one trained on human harmlessness labels, explaining its objections instead of just refusing. The approach also makes the values being trained into the model explicit and editable, written down in one document instead of spread across thousands of labelers' judgements.
Reward hacking
The reward model is only an approximation of what people want. Optimise hard enough against any proxy and you find its flaws: this is reward hacking, an instance of Goodhart's law ("when a measure becomes a target, it ceases to be a good measure").
Typical symptoms in language models:
- Length bias. Raters often prefer longer, more thorough-looking answers, so models learn to pad.
- Sycophancy. Agreeing with the user and flattering them gets rated well, so models learn to tell people what they want to hear.
- Style over substance. Confident tone, bullet points and headings can score higher than correct content.
OpenAI researchers measured this curve systematically (Gao et al., 2022): the true ("gold") reward first rises and then falls as optimisation pushes further from the starting policy. Defences include the KL penalty, larger and better reward models, ensembles of reward models, refreshing preference data from the current policy, and evaluating with fresh human judgements (Evaluating LLMs and Benchmarks).
In code
This toy has one prompt and four candidate answers with a hidden "true quality". We simulate 2,000 human comparisons, then (1) train a Bradley–Terry reward model, and (2) train a policy directly with DPO on the same pairs.
import torch
import torch.nn.functional as F
torch.manual_seed(0)
answers = ["correct & polite", "correct but rude", "long and rambling", "wrong"]
quality = torch.tensor([2.0, 0.5, 0.0, -1.5]) # hidden; labelers follow it noisily
# 2,000 simulated comparisons: P(i beats j) = sigmoid(quality_i - quality_j)
i, j = torch.randint(0, 4, (2, 4000))
keep = i != j
i, j = i[keep][:2000], j[keep][:2000]
i_wins = torch.rand(2000) < torch.sigmoid(quality[i] - quality[j])
win, lose = torch.where(i_wins, i, j), torch.where(i_wins, j, i)
# 1) Reward model: one score per answer, loss = -log sigmoid(r_w - r_l)
r = torch.zeros(4, requires_grad=True)
opt = torch.optim.Adam([r], lr=0.05)
for _ in range(500):
loss = -F.logsigmoid(r[win] - r[lose]).mean()
opt.zero_grad(); loss.backward(); opt.step()
print("reward model:", [round(v, 2) for v in (r - r.mean()).tolist()])
# 2) DPO: no reward model, no sampling; just the policy, a frozen reference and the pairs
ref_logits = torch.log(torch.tensor([0.25, 0.20, 0.40, 0.15])) # the SFT model
logits = ref_logits.clone().requires_grad_(True) # policy starts at SFT
beta = 0.5
opt = torch.optim.Adam([logits], lr=0.05)
for _ in range(500):
logp, logp_ref = F.log_softmax(logits, 0), F.log_softmax(ref_logits, 0)
margin = (logp[win] - logp_ref[win]) - (logp[lose] - logp_ref[lose])
loss = -F.logsigmoid(beta * margin).mean()
opt.zero_grad(); loss.backward(); opt.step()
for a, p0, p1 in zip(answers, F.softmax(ref_logits, 0), F.softmax(logits, 0)):
print(f"{a:18s} SFT {p0:.2f} -> DPO {p1:.2f}")
# reward model: [1.63, 0.22, -0.12, -1.74]
# correct & polite SFT 0.25 -> DPO 0.91
# correct but rude SFT 0.20 -> DPO 0.04
# long and rambling SFT 0.40 -> DPO 0.04
# wrong SFT 0.15 -> DPO 0.00
The reward model recovers the hidden quality up to a shift (the true values minus their mean are 1.75, 0.25, −0.25, −1.75). DPO, which never built a reward model, lands almost exactly on the formula for the optimal policy, normalised: work it out by hand with the printed rewards and and you get 0.91, 0.04, 0.04, 0.00. A smaller makes the policy more extreme; a larger one keeps it closer to the SFT model.
For real models, Hugging Face's TRL library provides RewardTrainer, DPOTrainer, GRPOTrainer and RLOOTrainer (as of late 2026 its older PPOTrainer is no longer part of the library). A DPO run looks like this (it downloads a model and dataset, so it is not run here):
from datasets import load_dataset
from trl import DPOConfig, DPOTrainer
from transformers import AutoModelForCausalLM, AutoTokenizer
name = "Qwen/Qwen2.5-0.5B-Instruct"
model = AutoModelForCausalLM.from_pretrained(name)
tokenizer = AutoTokenizer.from_pretrained(name)
pairs = load_dataset("trl-lib/ultrafeedback_binarized", split="train") # prompt, chosen, rejected
trainer = DPOTrainer(model=model, args=DPOConfig(output_dir="qwen-dpo", beta=0.1),
train_dataset=pairs, processing_class=tokenizer)
trainer.train() # the reference model is a frozen copy made automatically
Common pitfalls
- Skipping SFT. Preference training on a base model that can't yet produce good answers has nothing useful to compare.
- β too small. The policy drifts far from the reference model and reward-hacks: long, flattering, repetitive answers. Watch the KL (or the DPO log-ratios) during training.
- Noisy, inconsistent labels. In published studies, labelers agree with each other on which answer is better only around 60–75% of the time. Clear guidelines and quality checks on labelers matter more than volume.
- Trusting the reward model's score. A rising reward during RL is not proof of a better model. Evaluate with fresh human or strong-model judgements.
- DPO chosen-likelihood collapse. DPO only cares about the gap between chosen and rejected, and the probability of both can fall together. Monitor the absolute log-probability of chosen answers.
Watch out Preference training optimises for what raters like, which is not always what is true. Sycophancy and confident-sounding errors are well-documented side effects. Measure factual accuracy separately (Hallucinations).
Variations
- GRPO (Group Relative Policy Optimization, from DeepSeekMath, 2024) drops PPO's value model and instead scores each sampled answer relative to the average of a group of answers to the same prompt. It is cheaper and became popular for training Reasoning Models and Test-Time Compute.
- RL from verifiable rewards: when the answer can be checked automatically (a maths result, code that passes tests), the "reward model" is a checker, which cannot be flattered. This is the core of reasoning models.
- Process reward models score each step of a solution rather than only the final answer.
- Rejection sampling / best-of-n fine-tuning: sample many answers, keep the ones the reward model likes best, and fine-tune on them. Simple and robust; Llama 2's training used it alongside PPO.
- KTO, IPO, ORPO, SimPO: DPO relatives with different loss shapes or data requirements.
- For the bigger picture of steering AI systems towards human values, see AI Alignment.
A bit of history
The modern recipe started outside language. In 2017, Paul Christiano and colleagues at OpenAI and DeepMind trained agents in simulated robotics and Atari games from human comparisons of short video clips, by learning a reward model and optimising it with RL. A simulated robot learned a backflip from about 900 bits of human feedback. In 2019 OpenAI applied the same idea to text (Ziegler et al.), already with a KL penalty against the starting model, and in 2020 to summarisation (Stiennon et al.), where the RLHF summaries were preferred to the human-written reference summaries. InstructGPT (Ouyang et al., March 2022) brought it to general instruction following, and ChatGPT (November 2022) brought it to the public.
Anthropic published its "helpful and harmless" RLHF work in April 2022 and Constitutional AI in December 2022. In May 2023 Rafael Rafailov, Archit Sharma, Eric Mitchell and colleagues at Stanford published DPO under the title "Your Language Model is Secretly a Reward Model". Its simplicity made it the standard for open models within months. From late 2024, attention shifted back to online RL, now with automatically verifiable rewards, to train reasoning models.
Try it
- In the code, change
betato0.1and to2.0. How do the final DPO probabilities change? Check them against , normalised.- Add label noise: flip 30% of the
win/losepairs at random. How much do the learned rewards shrink? Why does noise make them shrink towards zero rather than become random?- Work out the DPO loss by hand for when the policy has lowered the chosen answer's log-probability by 1.0 and lowered the rejected answer's by 4.0. Is the loss below 0.693? What does that tell you about the pitfall "chosen-likelihood collapse"?
Hint for 3: the argument of is .
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Illustrating Reinforcement Learning from Human Feedback (RLHF)
A clear, illustrated walk through the three stages of RLHF: pretraining, reward model training and RL fine-tuning.
Reinforcement Learning from Human Feedback (the RLHF Book)
A free online book covering reward models, PPO, DPO and its relatives, Constitutional AI and reasoning-era RL, written by a practitioner.
Training language models to follow instructions with human feedback
InstructGPT: the RLHF recipe that turned GPT-3 into an assistant, and the precursor of ChatGPT.
Direct Preference Optimization
Aligning models to preferences without a separate reward model or RL loop.
Constitutional AI: Harmlessness from AI Feedback
Training a harmless assistant using a written set of principles and AI feedback.
Deep Reinforcement Learning from Human Preferences
The origin of modern RLHF: learn a reward model from human comparisons of short clips, then optimise a policy against it.
Learning to summarize from human feedback
Applied the reward-model-plus-PPO recipe with a KL penalty to text summarisation, the direct ancestor of InstructGPT.
RLAIF vs. RLHF: Scaling Reinforcement Learning from Human Feedback with AI Feedback
Compares preference labels from an LLM with labels from humans and finds AI feedback reaches comparable results on summarisation and dialogue.
TRL documentation
Transformer Reinforcement Learning: trainers for supervised fine-tuning (SFT), reward modelling, PPO, DPO and GRPO on Hugging Face models.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/llm/rlhf.md