◆ AI All-in-One

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
↗ Plan a path here

Read first

Instruction Tuning and Chat ModelsProximal Policy Optimization

This leads to

Reasoning Models and Test-Time Compute
The full path from zero — 51 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. Python for AI
  6. How Machines Learn
  7. Partial Derivatives and Gradients
  8. Matrices and Matrix Multiplication
  9. The Chain Rule
  10. Dot Product, Norms and Similarity
  11. Tokenization
  12. Supervised, Unsupervised and Reinforcement Learning
  13. Gradient Descent
  14. Tensors and Shapes
  15. NumPy and Array Thinking
  16. Language Modeling and Next-Token Prediction
  17. Supervised Learning
  18. Reinforcement Learning: The Basics
  19. Linear Regression
  20. Training, Validation and Test Sets
  21. The Perceptron
  22. Markov Decision Processes
  23. Logistic Regression
  24. Overfitting and the Bias–Variance Tradeoff
  25. Value Functions and Bellman Equations
  26. Regularization: L1 and L2
  27. Neural Networks
  28. Recurrent Neural Networks
  29. Backpropagation
  30. Activation Functions
  31. Dropout and Regularizing Neural Networks
  32. Policy Gradients
  33. PyTorch
  34. Vanishing and Exploding Gradients
  35. Normalization Layers: BatchNorm and LayerNorm
  36. Optimizers: SGD, Momentum and Adam
  37. Actor-Critic Methods
  38. LSTMs and GRUs
  39. Residual Connections
  40. Training Neural Networks in Practice
  41. Proximal Policy Optimization
  42. Sequence-to-Sequence Models
  43. Transfer Learning
  44. Attention
  45. Self-Attention and Multi-Head Attention
  46. Positional Encodings
  47. The Transformer
  48. GPT and Decoder-Only Models
  49. Pretraining Large Language Models
  50. Fine-Tuning
  51. Instruction Tuning and Chat Models
  52. 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.

1 · Supervised fine-tuning 2 · Train a reward model 3 · RL against it (PPO) human-writtendemonstrations pretrained base model SFT model next-token loss onthe ideal answers prompt x → two answers answer Aanswer B a human picks: A ≻ B reward model r(x, y) loss = −log σ(r_A − r_B)(Bradley–Terry) policy π_θstarts as SFT model samples y reward model scores y PPO update of π_θ reference π_ref (frozen) KL penalty: stay near π_ref copy of the SFT model starts the policy and becomes π_ref DPO shortcut: replaces steps 2 + 3 train the policy directly on the pairs (x, A, B) with one loss, no reward model, no sampling, no PPO
Fig. 1 The classic RLHF pipeline. Step 1: supervised fine-tuning on demonstrations. Step 2: humans compare pairs of answers, and a reward model learns to score answers the way they would. Step 3: the policy generates answers, the reward model scores them, and PPO updates the policy, with a KL penalty keeping it close to the SFT model. DPO collapses steps 2 and 3 into a single supervised loss on the comparisons.

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 πθ\pi_\theta: given a prompt xx, it produces a response yy by sampling tokens. The reference model πref\pi_{\text{ref}} 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 (x,yw,yl)(x, y_w, y_l): 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 rϕ(x,y)r_\phi(x, y) 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 ywy_w is preferred over yly_l is the sigmoid of the difference in their scores,

P(yw≻yl∣x)=σ(rϕ(x,yw)−rϕ(x,yl)),σ(z)=11+e−zP(y_w \succ y_l \mid x) = \sigma\big(r_\phi(x, y_w) - r_\phi(x, y_l)\big), \qquad \sigma(z) = \frac{1}{1 + e^{-z}}

Training maximises the likelihood of the observed human choices, which means minimising

LRM=−log⁡σ(rϕ(x,yw)−rϕ(x,yl))L_{\text{RM}} = -\log \sigma\big(r_\phi(x, y_w) - r_\phi(x, y_l)\big)

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 P=σ(1.0)=0.731P = \sigma(1.0) = 0.731 and the loss is −ln⁡0.731=0.313-\ln 0.731 = 0.313. If it scored them the wrong way round (0.5 and 1.5), P=σ(−1.0)=0.269P = \sigma(-1.0) = 0.269 and the loss is 1.3131.313: 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:

max⁡θ  Ex∼D, y∼πθ(⋅∣x)[rϕ(x,y)]  −  β KL(πθ(⋅∣x) ∥ πref(⋅∣x))\max_\theta \; \mathbb{E}_{x \sim \mathcal{D},\, y \sim \pi_\theta(\cdot \mid x)} \Big[ r_\phi(x, y) \Big] \;-\; \beta \, \mathrm{KL}\big(\pi_\theta(\cdot \mid x) \,\Vert\, \pi_{\text{ref}}(\cdot \mid x)\big)

In words: sample prompts from the dataset D\mathcal{D}, let the policy answer, and make the reward model's score high on average, but pay a price β\beta 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 log⁡πθ(yt)−log⁡πref(yt)\log \pi_\theta(y_t) - \log \pi_{\text{ref}}(y_t) and subtracted from the reward. The coefficient β\beta, 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 [0.8,1.2][0.8, 1.2]. 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:

π∗(y∣x)=1Z(x) πref(y∣x) exp⁡ ⁣(r(x,y)/β)\pi^*(y \mid x) = \frac{1}{Z(x)} \, \pi_{\text{ref}}(y \mid x) \, \exp\!\big(r(x, y) / \beta\big)

where Z(x)Z(x) 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: r(x,y)=βlog⁡π(y∣x)πref(y∣x)+βlog⁡Z(x)r(x, y) = \beta \log \frac{\pi(y \mid x)}{\pi_{\text{ref}}(y \mid x)} + \beta \log Z(x). Plug that into the Bradley–Terry loss, and Z(x)Z(x) cancels because it appears in both the winner's and the loser's term. What remains is a loss on the policy itself:

LDPO=−log⁡σ ⁣(βlog⁡πθ(yw∣x)πref(yw∣x)  −  βlog⁡πθ(yl∣x)πref(yl∣x))L_{\text{DPO}} = -\log \sigma\!\left( \beta \log \frac{\pi_\theta(y_w \mid x)}{\pi_{\text{ref}}(y_w \mid x)} \;-\; \beta \log \frac{\pi_\theta(y_l \mid x)}{\pi_{\text{ref}}(y_l \mid x)} \right)

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 β=0.1\beta = 0.1. Before training πθ=πref\pi_\theta = \pi_{\text{ref}}, so both log-ratios are 0, the argument of σ\sigma is 0, and the loss is −ln⁡0.5=0.693-\ln 0.5 = 0.693. After some training the policy has raised the log-probability of ywy_w by 2.0 nats and lowered that of yly_l by 1.0. The argument is 0.1×(2.0−(−1.0))=0.30.1 \times (2.0 - (-1.0)) = 0.3, σ(0.3)=0.574\sigma(0.3) = 0.574, and the loss is 0.5540.554.

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:

  1. 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.
  2. 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").

distance of the policy from π_ref (KL) → reward proxy reward (reward model) keeps rising: the policy learns its quirks true quality (people) peaks, then falls: reward hacking best stopping point SFT schematic of the shape reported by Gao et al. (2022), not real data
Fig. 2 A schematic of reward over-optimisation. As the policy moves further from the reference model (larger KL), the proxy reward from the reward model keeps rising, but the true quality judged by people rises, peaks, then falls.

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, πref⋅exp⁡(r/β)\pi_{\text{ref}} \cdot \exp(r/\beta) normalised: work it out by hand with the printed rewards and β=0.5\beta = 0.5 and you get 0.91, 0.04, 0.04, 0.00. A smaller β\beta 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

  1. In the code, change beta to 0.1 and to 2.0. How do the final DPO probabilities change? Check them against πref⋅exp⁡(r/β)\pi_{\text{ref}} \cdot \exp(r/\beta), normalised.
  2. Add label noise: flip 30% of the win/lose pairs at random. How much do the learned rewards shrink? Why does noise make them shrink towards zero rather than become random?
  3. Work out the DPO loss by hand for β=0.1\beta = 0.1 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 σ\sigma is 0.1×(−1.0−(−4.0))0.1 \times (-1.0 - (-4.0)).

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Why does RLHF train on comparisons of two answers rather than only on ideal written answers?

  2. A reward model scores the preferred answer 1.5 and the rejected one 0.5. Under the Bradley–Terry model, what probability does it give that the preferred one wins?

  3. During RL the reward model's score keeps rising, but the answers are getting longer, more flattering and less useful. What is happening?

  4. What is the main practical advantage of DPO over PPO-based RLHF?

  5. In Constitutional AI, where did the harmlessness comparisons come from?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Paper

Direct Preference Optimization

Rafailov et al. · 2023 · Advanced · Free

Aligning models to preferences without a separate reward model or RL loop.

Paper

Learning to summarize from human feedback

Stiennon et al. (OpenAI) · 2020 · Advanced · Free

Applied the reward-model-plus-PPO recipe with a KL penalty to text summarisation, the direct ancestor of InstructGPT.

Docs

TRL documentation

Hugging Face · Intermediate · Free

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