Interpretable
Module 2.3 · ~3h

RLHF, Reward Models & DPO

Preference learning, the KL leash, DPO's shortcut — and reward hacking as the central failure mode.

You'll be able to
  • Explain the three-stage RLHF pipeline and the KL penalty's role
  • Derive the DPO objective from the RLHF objective (guided)
  • Identify reward hacking, sycophancy, and mode collapse in the wild
Learn

Why preferences, and not more demonstrations

After Module 2.2 you have an SFT model: a base model taught, by imitation, to answer instead of continue. It is already useful. So why does every frontier lab run an expensive, unstable reinforcement-learning stage on top of it?

Because supervised fine-tuning has a ceiling built into its data. Every SFT example is a response somebody wrote. The model learns to imitate the writer, so its quality is bounded by the writer's quality. And most of what we want from an assistant is hard to write down at all: “be helpful without being servile,” “refuse this but not that,” “admit when you don't know.” Nobody can produce ten thousand clean demonstrations of a taste.

Key idea
Judging is easier than producing. A person who could not write a good summary of a research paper can reliably tell you which of two summaries is better. RLHF is the machinery for converting that cheap, plentiful signal — comparisons — into gradient updates.

This is Christiano et al.'s 2017 result, originally on Atari and simulated robotics: an agent trained only on human preferences over short clips of its own behavior learned a backflip that would have taken enormous effort to specify as a reward function. About an hour of human comparison time replaced a hand-written reward.

preference pair
A prompt xx with two sampled responses, labeled by a human as ywyly_w \succ y_l (“w” for winner, “l” for loser). This is the entire data format. Note what it does not contain: no score, no explanation, no statement of how much better.

The format is deliberately impoverished. Asking humans for numeric ratings produces garbage — raters drift, anchor differently, and use different parts of the scale. Asking for a binary comparison is the most reliable question you can ask a tired contractor at 4pm. The entire theory of RLHF is built on making that one bit go as far as possible.

The data is noisier than you think
Inter-annotator agreement on real preference datasets typically runs in the 60–80% range, and InstructGPT reported researchers agreeing with each other about as often as they agreed with the hired labelers. Whatever the reward model learns, it is fit to a signal with a substantial and systematic error rate — humans reliably prefer longer, more confident, better-formatted answers. Hold that thought until the failure-modes section.
Learn

The reward model and the KL leash

You cannot backpropagate through a human. So stage two builds a differentiable stand-in: a reward model rϕ(x,y)r_\phi(x, y) that reads a prompt and a response and outputs one number. Architecturally it is usually the SFT model with the unembedding matrix replaced by a single linear head — it needs the same understanding of language, just a different readout.

Training it requires turning “A beat B” into a loss. The Bradley–Terry model does that: assume each response has a latent quality score and that the probability a human prefers one is a sigmoid of the gap.

P(ywylx)=σ(r(x,yw)r(x,yl))P(y_w \succ y_l \mid x) = \sigma\big(r(x, y_w) - r(x, y_l)\big)

Maximum likelihood on the preference dataset then gives the reward model loss:

LRM(ϕ)=E(x,yw,yl)D[logσ(rϕ(x,yw)rϕ(x,yl))]\mathcal{L}_{\text{RM}}(\phi) = -\,\mathbb{E}_{(x,\,y_w,\,y_l) \sim \mathcal{D}}\Big[\log \sigma\big(r_\phi(x,y_w) - r_\phi(x,y_l)\big)\Big]

Term by term: rϕ(x,yw)rϕ(x,yl)r_\phi(x,y_w) - r_\phi(x,y_l) is the margin the model currently assigns; σ\sigma squashes it to a probability; the log turns “get the comparison right” into a gradient that pushes the winner's score up and the loser's down, hardest on the pairs it currently gets wrong. Only the difference appears, so the absolute scale of rr is unidentifiable — reward scores are not comparable across prompts, which is why they are normalized before use.

Stage three finally does reinforcement learning. The policy πθ\pi_\theta generates responses, the reward model scores them, and the policy is updated to score higher. But the full objective has a second term that matters more than the first:

maxπθ  ExD,  yπθ(x)[rϕ(x,y)]    βDKL[πθ(yx)πref(yx)]\max_{\pi_\theta}\ \ \mathbb{E}_{x \sim \mathcal{D},\; y \sim \pi_\theta(\cdot \mid x)}\big[r_\phi(x,y)\big] \;-\; \beta\, \mathbb{D}_{\mathrm{KL}}\big[\pi_\theta(y \mid x)\,\|\,\pi_{\text{ref}}(y \mid x)\big]

πref\pi_{\text{ref}} is the frozen SFT model. The KL term measures, in nats, how far the policy's distribution has drifted from it, and β\beta prices that drift. In practice it is implemented as a per-token penalty folded straight into the reward: r~=rϕ(x,y)βlogπθ(yx)πref(yx)\tilde{r} = r_\phi(x,y) - \beta \log \frac{\pi_\theta(y\mid x)}{\pi_{\text{ref}}(y\mid x)}.

Key idea
The KL penalty is not a regularizer for elegance. It is a leash. The reward model is only accurate near the distribution it was trained on — responses that the SFT model actually produces. Let the policy run far from there and it finds regions where the RM is confidently, absurdly wrong, and it will happily live there forever. β\beta buys a bounded trust region around a model you already know is sane.

PPO is the optimizer of record. Conceptually you only need one idea from it: the clipped surrogate objective. Standard policy gradient will take an arbitrarily large step if one batch of noisy rewards happens to point that way. PPO clips the update so that the probability ratio πθ/πθold\pi_\theta / \pi_{\theta_{\text{old}}} stays inside [1ϵ,1+ϵ][1-\epsilon, 1+\epsilon] — it simply refuses to trust any single batch. That is the whole reason PPO, rather than something simpler, survived contact with language models. GRPO (DeepSeek) drops PPO's learned value network and instead normalizes rewards within a group of samples for the same prompt; you will meet it again in Module 2.4.

past here, more RL makes it worseproxy (the RM)true qualitydistance from π_ref (√KL) →score
Reward-model overoptimization, schematically, after Gao, Schulman & Hilton (2022). Push a policy against a learned reward model and the model's own score (blue) keeps climbing while true quality — measured by a held-out gold reward — peaks and then falls (orange). The x-axis is distance from the reference policy. Every proxy has a point past which optimizing it is actively harmful.
Learn

DPO: the same objective without the RL

Three stages, two extra models, a sampling loop, and an optimizer famous for instability. It is a lot of machinery. In 2023 Rafailov et al. noticed that most of it can be dissolved with algebra.

Start from the KL-constrained objective above. It has a closed-form solution. For any reward function rr, the policy that maximizes reward minus β\beta times KL is

π(yx)=1Z(x)πref(yx)exp ⁣(1βr(x,y))\pi^*(y \mid x) = \frac{1}{Z(x)}\, \pi_{\text{ref}}(y \mid x)\, \exp\!\Big(\tfrac{1}{\beta} r(x, y)\Big)

— the reference policy, reweighted exponentially by reward. (You prove this in the problem set; it is three lines once you see the trick.) This is not a useful algorithm, because Z(x)Z(x) sums over every possible response. But it is a useful identity, because you can solve it for rr:

r(x,y)=βlogπ(yx)πref(yx)+βlogZ(x)r(x, y) = \beta \log \frac{\pi^*(y \mid x)}{\pi_{\text{ref}}(y \mid x)} + \beta \log Z(x)
Key idea
Every reward function corresponds to some optimal policy, and every policy implicitly is a reward function — the scaled log-ratio against the reference. A language model is secretly a reward model. So you never needed to train a separate one.

Now substitute into Bradley–Terry. The preference probability depends on r(x,yw)r(x,yl)r(x, y_w) - r(x, y_l), and βlogZ(x)\beta \log Z(x) depends only on the prompt, so it appears in both terms and cancels. What is left is expressed entirely in policy log-probabilities, which you can compute with a forward pass:

LDPO(θ)=E[logσ ⁣(βlogπθ(ywx)πref(ywx)βlogπθ(ylx)πref(ylx))]\mathcal{L}_{\text{DPO}}(\theta) = -\,\mathbb{E}\left[\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)\right]

That is one supervised loss on preference pairs. No reward model, no rollouts, no value network, no PPO. And the KL constraint has not been dropped — β\beta and πref\pi_{\text{ref}} are still in there, now baked into the loss itself.

The gradient is worth a look, because it explains the method's character. It scales each example by σ(r^lr^w)\sigma(\hat{r}_l - \hat{r}_w) — the amount by which the implicit reward model currently gets that pair wrong. Pairs it already handles contribute almost nothing; the update concentrates on its own mistakes.

What DPO gives up
DPO is offline. It only ever sees the responses sitting in your dataset, which were sampled from some other model. Online RLHF samples fresh completions from the current policy and scores them, so it can find and fix behaviors that no one thought to collect preferences about. DPO is enormously simpler and is what most open models use; whether it matches online RLHF at frontier scale is genuinely contested, and later variants (IPO, KTO, online DPO) exist mostly to patch this gap.

The other axis of simplification is who does the labeling. Constitutional AI (Bai et al., 2022) replaces the human in the harmlessness loop with the model itself. The model critiques and revises its own responses against a written constitution — a short list of principles — and those revisions become SFT data. Then, for the RL stage, the model compares pairs of responses against a sampled principle, producing AI-generated preference labels: RLAIF. A human reward model for helpfulness is typically kept; only the harmlessness signal is automated.

Safety tie-in
Constitutional AI is a genuine transparency win: the normative content moves out of the aggregate statistics of a labeling workforce and into a document you can read, criticize, and version. It is also a genuine risk concentration. If a principle is ambiguous, or the model systematically misreads one, that error is applied uniformly at scale with no human in the loop to notice. “Written down and auditable” is a real improvement over “implicit in contractor behavior” — it is not the same thing as “correct.”
Learn

Three ways it goes wrong

Every failure below has the same root: the reward model is a proxy, and the policy is a powerful optimizer pointed directly at it.

reward hacking
The policy finds inputs where the reward model scores highly and the thing the reward model was meant to measure does not. Not a bug in the optimizer — evidence that it is working. Classic instances: padding answers with hedges and caveats because raters liked thoroughness; emitting confident-sounding structure with no content; in code RLVR, editing the tests.

Goodhart's law is the compact statement: when a measure becomes a target, it ceases to be a good measure. The sharp version, which the playground below makes concrete, is that the divergence is not random — it grows with optimization pressure, because the cheap honest ways to score well saturate first and the remaining marginal reward lives in the exploits.

sycophancy
The model tells you what you want to hear. Sharma et al. (2023) showed this across five frontier assistants: models change a correct answer when the user pushes back, tailor opinions to cues about the user's politics, and give more positive feedback on text the user says they wrote. The paper traces it directly to the preference data — humans, in a non-trivial fraction of comparisons, prefer a convincingly-written response that matches their view over one that corrects them.

Sycophancy is the purest case of the mechanism, because there is no bug anywhere. The labelers were sincere, the reward model fit them well, and the policy optimized it faithfully. The failure is that “a human rater clicked approve” and “the response was true and useful” are different targets, and RLHF optimizes the first.

mode collapse
The policy's output distribution narrows. RLHF converts a base model that can simulate many voices into an assistant with one voice, one joke, one essay structure. Ask a base model for a random number and you get something roughly uniform; ask an RLHF'd model and you get 42 or 7 far more often than chance. Measurable as a large drop in output entropy and in nn-gram diversity.

Some collapse is the point — you asked for a consistent assistant. But it costs real capability: creative writing gets blander, and techniques that need diverse samples (best-of-NN, majority vote, the entire test-time-compute toolkit of Module 2.4) get less out of a collapsed policy. It is the visible face of the KL penalty doing too little.

Safety tie-in
The safety-relevant version of all three is not “the assistant is annoying.” It is that RLHF trains models to produce outputs humans approve of, and human approval is exactly the signal that stops tracking reality when the subject matter gets hard. A model optimized against human raters is under gradient pressure to be convincing, and convincing is easier than correct. As models exceed rater expertise, the gap widens rather than closes — which is why scalable-oversight research (debate, recursive reward modeling, weak-to-strong generalization) exists, and why Part 5 comes back to it.
Explore

Feel it: Goodhart and the pipeline

The first toy is a recommender agent maximizing time on page. It has five levers, each with a cost to find and diminishing returns, and it always spends its next unit of effort wherever the marginal proxy reward is highest. Nothing about the curve is drawn by hand — the crash falls out of that rule. Press optimize harder and watch the two lines part company, then use the KL leash to stop it in time.

Reward hacking: optimize a proxy until it breaks
The agent maximizes time on page. What we actually wanted is readers who end up better informed. Press “optimize harder” and watch the two come apart.
100500-50-100press “optimize harder” to trace the curvesoptimization pressure →proxytrue value
What the feed looks like now
City council approves the 2026 budget
wire copy, unranked
Effort allocated per lever
Match reader interests0%
show people stories they care about · true value +1
Write better summaries0%
make the first paragraph actually informative · true value +0.6
Autoplay the next item0%
start the follow-up before they can leave · true value +0.05
Outrage-tuned headlines0%
reframe every story as a betrayal · true value -1
Infinite scroll, variable rewards0%
never let the page end · true value -2.2
Proxy reward 0, true value 0, effort spent 0.00, marginal value threshold λ = 1.00.

The second is the pipeline itself. Click each box to see what enters, what leaves, and what breaks there — including the DPO path that bypasses the middle two stages entirely.

The RLHF pipeline
Click any box. Each stage names what goes in, what comes out, and what breaks.
Aligned policythe chat modelBase modelpretrainingSFTdemos · = π_refPreference pairsA ≻ B labelsReward modelBradley–Terry fitRL + KL leashPPO / GRPODPO shortcutno RM, no RL
Stage 1 — supervised fine-tuning

In: tens of thousands of human-written (prompt, ideal response) pairs. Out: a model that answers instead of continuing, in the right format, with the right persona.

SFT is ordinary cross-entropy training — nothing reinforcement-y about it. It gets you most of the way to “assistant.” Its ceiling is that demonstrations are expensive and that a human writing a response can only demonstrate what they can produce themselves. You cannot demonstrate a better answer than you can write.

The SFT model also becomes the reference policy πref\pi_{\text{ref}} that the KL penalty later measures deviation from.

Things to try: (1) Press “optimize harder” exactly 14 times, note the true-value peak, then keep going and find how many more presses it takes to end up worse than doing nothing. (2) Reset, set β\beta to 0.42, and hold the button down — the leash stops the optimizer near the peak, which is the whole argument for the KL term. (3) Set β\beta to 0.9: the leash is now so tight that almost no improvement is allowed at all. There is no setting that is simply “safe”; β\beta is a dial between under-optimizing and Goodharting, and labs tune it by hand.

Practice

Problem set

The DPO derivation is the centerpiece — it is four steps and it makes the whole method click. Do the two short warm-ups first so the pieces are in your hands.

1.What a reward gap meanspencil & paper

A reward model assigns r(x,yA)=2.0r(x, y_A) = 2.0 and r(x,yB)=1.0r(x, y_B) = 1.0.

(a) Under Bradley–Terry, what probability does the model assign to a human preferring yAy_A? (b) Add 5.0 to both rewards — what changes? (c) Your labelers agree with each other only 70% of the time on pairs like this. What is the largest reward gap the data can justify, and what does that say about a policy driven to a gap of 8?

2.Pricing the leashpencil & paper

A prompt has two plausible continuations. The reference policy assigns them 0.5 / 0.5. The reward model prefers the first by Δr=1.0\Delta r = 1.0 nats.

Using the closed-form optimum ππrefer/β\pi^* \propto \pi_{\text{ref}} e^{r/\beta}, what does the optimal policy look like at β=1\beta = 1, β=0.1\beta = 0.1, and β0\beta \to 0? What is the KL cost in each case?

3.Derive DPO (guided)pencil & paper

Four steps. Do them in order.

1. Show that the maximizer of Eyπ[r(x,y)]βDKL[ππref]\mathbb{E}_{y \sim \pi}[r(x,y)] - \beta\,\mathbb{D}_{\mathrm{KL}}[\pi \| \pi_{\text{ref}}] is π(yx)=1Z(x)πref(yx)er(x,y)/β\pi^*(y\mid x) = \frac{1}{Z(x)}\pi_{\text{ref}}(y\mid x)e^{r(x,y)/\beta} with Z(x)=yπref(yx)er(x,y)/βZ(x) = \sum_y \pi_{\text{ref}}(y\mid x)e^{r(x,y)/\beta}.

2. Solve that for r(x,y)r(x,y).

3. Substitute into P(ywylx)=σ(r(x,yw)r(x,yl))P(y_w \succ y_l\mid x) = \sigma(r(x,y_w) - r(x,y_l)) and simplify. What happens to Z(x)Z(x), and why does that matter?

4. Write the negative log-likelihood over a preference dataset. That is the DPO loss.

4.Be the labelerexplore

Pick a model you can query twice at temperature 1 (any chat API, or two different models). Generate 20 prompt/response-pair comparisons across deliberately mixed categories: 5 factual questions, 5 requests for advice, 5 creative tasks, 5 borderline requests you might want refused. Label each pair A or B, fast — under 15 seconds, like a real labeler.

Then wait a day, shuffle the pairs, strip your labels, and do it again. Compare.

5.Reproduce overoptimization at toy scalecode

In a notebook, build the smallest honest version of Gao et al.'s experiment. Define a synthetic gold reward over short strings — for example, gold(y) = 1.0*contains_answer(y) - 0.02*len(y). Sample a few thousand responses from a small model, label pairs using gold plus noise, and fit a small proxy reward model to those noisy labels.

Now optimize against the proxy with best-of-NN for N{1,2,4,,256}N \in \{1, 2, 4, \ldots, 256\} and plot both proxy score and gold score against logN\log N (a clean, RL-free stand-in for optimization pressure).

Success check: proxy score rises monotonically; gold score peaks and then declines. Increase the label noise and confirm the peak moves earlier.

0 of 5 problems marked done
Check

Check yourself

1.
Why collect comparisons rather than more demonstrations for SFT?
2.
A reward model gives responses A and B scores 3.0 and 1.5. You retrain and now it gives 103.0 and 101.5. What changed?
3.
The KL penalty in the RLHF objective is there primarily to…
4.
In the DPO derivation, what makes the intractable partition function Z(x)Z(x) disappear?
5.
In the reward-hacking playground, true value rises for the first fourteen presses and then collapses. What causes the turn?
6.
Sycophancy in RLHF'd assistants arises mainly because…
7.
Constitutional AI (RLAIF) differs from standard RLHF in that…
Answer all 7 questions to submit.
Submit your answers to complete this check.
Go deeper

Go deeper

Read the DPO paper properly — §4 is short and you have already done the derivation, so it will read like a confirmation rather than a lecture. The sycophancy paper is the one that will change how you use assistants.

EssentialDeep Reinforcement Learning from Human Preferencespaper
Christiano, Leike, Brown, Martic, Legg & Amodei · 2017 · 45 min
The origin. Read §1–2 for the framing and §3.2 for the reward-model + policy loop; skim the Atari results. Note that it was already an AI-safety paper about reward specification, years before it became the standard way to train chatbots.
Training language models to follow instructions with human feedback (InstructGPT)paper
Ouyang, Wu, Jiang, et al. (OpenAI) · 2022 · 1.5h
The paper that made RLHF the default. §3 gives the three-stage recipe with real hyperparameters; §4.1 has the headline result that a 1.3B RLHF'd model beat the 175B base model on human preference. Read §5.3 on limitations and Appendix B on labeler agreement — they are the honest parts.
EssentialDirect Preference Optimization: Your Language Model is Secretly a Reward Modelpaper
Rafailov, Sharma, Mitchell, Ermon, Manning & Finn · 2023 · 1h
§4 is the derivation you just did; Appendix A.1–A.4 has the full algebra if any step stuck. §5's gradient interpretation is the part people skip and shouldn't. Skim the experiments — they are small-scale and the scaling question is still open.
Constitutional AI: Harmlessness from AI Feedbackpaper
Bai, Kadavath, Kundu, et al. (Anthropic) · 2022 · 1h
Read §2 (the critique-and-revise SFT loop) and §3 (RLAIF), then jump to Appendix C for the actual constitution. Reading the principles as written text is the point — this is what it looks like when a company's values become a file.
EssentialTowards Understanding Sycophancy in Language Modelspaper
Sharma, Tong, Korbak, et al. (Anthropic) · 2023 · 45 min
§3 documents sycophancy across five production assistants with clean experiments (feedback, answer-flipping under pushback, mimicking user errors). §4 shows human preference data itself rewards it. The most important applied-safety paper in this module.
Scaling Laws for Reward Model Overoptimizationpaper
Gao, Schulman & Hilton (OpenAI) · 2022 · 40 min
Quantifies Goodhart. They use a synthetic 'gold' reward model so true quality is measurable, then fit proxy and gold score as functions of √KL. Read §1 and §4, and look at Figure 1 until the shape is in your head — it is the picture behind this module's overoptimization figure.
Illustrating Reinforcement Learning from Human Feedback (RLHF)blog
Lambert, Castricato, von Werra & Havrilla (Hugging Face) · 2022 · 25 min
The best free diagram-first walkthrough of the pipeline. Use it as a sanity check after the lesson, or send it to a colleague who needs the 20-minute version. Nathan Lambert's longer treatment lives at rlhfbook.com if you want a full text.