Alignment I: SFT and RLHF

A reward model scores answers. RLHF moves the model toward high scores, on a leash called β. In this toy, β = 1 lifts human-judged quality from 0.36 to 0.57. At β = 0.1 the score reaches 2.00 and quality falls to −0.50: the model pads every answer.

Loosen the leash and watch where the probability goes. Then we build each part from zero: instruction data, the masked fine-tuning loss, preference pairs, the reward model, the leashed objective, PPO and DPO.

You need a probability, the log and the training loss of a language model. We build the rest from zero.

Lecture 15 of Stanford CS336, Language Modeling from Scratch (Spring 2025, Percy Liang and Tatsunori Hashimoto). Previous: Lecture 14, Data II. Next: Lecture 16, Alignment II: RLVR.

Pull the leash on the policy

1

Illustrative toy: six answers to one prompt, with made-up SFT probabilities, reward-model scores and human scores. The tuned policy is the exact optimum of the leashed objective (Chapter 5), computed live. Drag right to loosen the leash.

Chapter 0

A Base Model Completes; an Assistant Answers

See what pretraining leaves out, and the two stages that add it

Type "Explain why the sky is blue to a 10-year-old" into a freshly pretrained model. Pretraining taught it to continue web text. Often the likeliest continuation is more of a forum page: another question, a list of links, a quiz. The model knows the physics. It does not know you want an answer.

The lecture frames this as control. Pretraining data is not the behaviour we want, but it scales. So we collect a small amount of data that shows the behaviour, and train on it. Three questions follow: what does that data look like, how do we use it, and how much do we need?

The standard recipe comes from InstructGPT (Ouyang et al., 2022), and has two stages:

  1. Supervised fine-tuning (SFT). People write good answers to prompts. The model learns to imitate them. InstructGPT used about 13,000 training prompts.
  2. Reinforcement learning from human feedback (RLHF). People compare two answers and pick the better one: 33,000 prompts. A reward model learns their taste. Then PPO tunes the model to score well, on 31,000 more prompts.

Train one stage at a time

The bars show what 100 samples of the model do with the sky prompt. Pick a stage. The strip below lights each stage you paid for.

Illustrative outcome shares. The SFT and RLHF rows sum the hero's six answers. The dollar figures are the lecture's rough estimate for a 7B model.

Worked number, from the lecture's cost table for a small 7B model. Pretraining costs about $300k of compute. SFT costs $25k of writing and $100 of compute. Preference labels cost $4k, and RL $100 of compute. All of post-training together is about $29k, a tenth of pretraining. Yet labelers preferred the 1.3B InstructGPT model's outputs to those of the 175B GPT-3, a model with more than 100 times the parameters.

Symptom: asked a question, the model writes more questions or the rest of a web page.

Measure: sample 20 completions of a few instructions and count the ones that answer.

Fix: fine-tune on demonstrations (Chapter 2). Prompting with examples helps a little; SFT helps more.

The road

  1. SFT data: what instruction data holds, and how little you need.
  2. SFT loss: next-token loss, graded only on the answer.
  3. Preferences: compare two answers; Bradley-Terry turns scores into odds.
  4. Reward model: learn a score from pairs, and see it learn length.
  5. KL leash: the objective the hero solves, and its exact optimum.
  6. PPO: reach that optimum by sampling, one clipped step at a time.
  7. DPO: skip the reward model with one line of algebra.
  8. Showcase: RLHF and DPO on the same pairs.
  9. Goodhart: why the score keeps rising after quality falls.
  10. Field guide: the table, the code, the links.
Asked "What is the capital of France?", a base model writes "What is the capital of Germany? What is the capital of Italy?" What is the problem?

Chapter 1

What Instruction Data Teaches

Read three datasets the lecture opens, and see that style travels further than facts

SFT data is a list of prompts with answers we would like the model to give. The lecture opens three public sets. FLAN turns old NLP benchmarks into instructions. Alpaca has 52,000 instructions with answers that a language model wrote. OpenAssistant has conversations that volunteers wrote.

Open three datasets

Each is a random example the lecture shows. Each warm chip is one word of the answer. Compare the lengths and the style.

Examples copied from the lecture's slides; the slide cuts part of the OpenAssistant answer, so only its visible words count.

The sets differ in length, in style (bullets or prose), and in knowledge. In evaluations by preference, both people and GPT-4 judges favour longer answers, so a long-answer dataset looks better than it is.

The OpenAssistant answer ends with a citation. What does it teach: that paper, or the habit of citing? If the model never saw that paper in pretraining, it learns to write citations it cannot back. Work by Schulman and by Gekhman et al., shown in the lecture, supports this folklore: fine-tuning on facts the model does not know raises hallucination.

A little data goes far. In a study the lecture shows, about 500 safety examples cut harmful answers sharply. The hard part is over-refusal of safe requests. LIMA (Zhou et al., 2023) fine-tuned a 65B model on 1,000 curated examples, about 750,000 tokens. On 300 test prompts, people rated its answers as good as or better than GPT-4's 43% of the time. The authors call this the superficial alignment hypothesis: knowledge comes from pretraining; SFT teaches the format.

Worked number: OpenAssistant's visible answer is 120 words for a 30-word prompt. FLAN's is 3 words for a 33-word prompt. Fine-tune on one or the other, and you get a terse model or a chatty one.

Symptom: after SFT, the model writes confident citations to papers that do not exist.

Measure: check a sample of its references against a search engine.

Fix: do not fine-tune on tail facts the model lacks. Teach the format; reward correctness later with RL.

LIMA reaches strong instruction following with 1,000 examples. What does that suggest about SFT?

Chapter 2

The SFT Loss: Grade Only the Answer

Train with the pretraining loss, and mask the prompt out of it

The lecture's method slide says "just do gradient descent". SFT uses the same next-token loss as pretraining. Two things change: the data, and which tokens count.

A chat template wraps each example in special tokens, for example <|user|> before the prompt and <|assistant|> before the answer. The model reads the whole sequence. But we grade it only on the answer, because we never want it to write the user's part.

Call the prompt x and the answer's tokens y1 to yT, so the answer has T tokens. Call the model's probability for answer token t, given the prompt and the answer so far, pθ(yt | x, y<t). The loss is the average surprise over the answer only:

Say it aloud

L-S-F-T equals minus one over T, times the sum over t of the log of p-theta of y-t, given x and the answer tokens before t.

LSFT
L-S-F-T the fine-tuning loss: the average surprise per answer token, in nats. Training lowers it.
1/T
one over T divide by the number of answer tokens, so the sum becomes an average.
Σt
the sum over t one term for each answer position, 1 to T. Prompt positions get no term: that is the mask.
ln
the log the natural log; negative for a probability below 1, so the minus sign makes the loss positive.
pθ(yt | x, y<t)
p-theta of y-t given x and the tokens before t the probability the model with weights θ gives the right answer token.
In plain words

Feed the prompt x and the answer. At each answer position t, read the probability of the true token y-t and take its log. Average the T logs over the answer and flip the sign.

With numbers

With made-up numbers: the answer "Blue light scatters most" is 4 tokens with probabilities 0.7, 0.6, 0.9 and 0.8. The logs are −0.357, −0.511, −0.105 and −0.223. LSFT = 1.196 / 4 = 0.299 nats per token.

Mask the prompt

Each chip is a token; the pink bar is its surprise. Turn the mask off and see which tokens take over the loss. Then drag the probability of "most".

0.80

Illustrative probabilities. The answer tokens match the worked example above.

In PyTorch, copy the token ids into a label tensor and set every prompt position to −100. F.cross_entropy skips that label value by default (ignore_index=-100). The device shows why it matters: user text is hard to predict, so unmasked prompt tokens dominate the loss. Their gradient also teaches the model to write questions.

Symptom: after SFT, the model keeps going past its answer and writes the user's next turn.

Measure: print the labels for one batch; prompt and template positions should be −100.

Fix: mask everything before the answer, and keep the end-of-turn token in the answer so the model learns to stop.

Why set prompt labels to −100 instead of training on the full sequence?

Chapter 3

Preferences: Compare, Do Not Write

Ask people which of two answers is better, and turn two scores into the odds of that choice

Picking the better of two answers is quicker than writing a perfect one. Also, people do not always write what they prefer. In a news-summary study the lecture shows (Zhang et al., 2023), one annotator wrote abstractive summaries but preferred the model's extractive ones.

So the next stage collects comparisons. For a prompt x, sample two answers from the SFT model. A labeler picks the winner yw over the loser yl. InstructGPT hired about 40 contractors and showed them 4 to 9 answers at once. Ranking K answers gives K(K − 1)/2 pairs: 36 pairs from one ranking of 9.

Labels are noisy: InstructGPT's labelers agreed with each other 72.6% of the time. The labeler pool also shifts the model's opinions (Santurkar et al., 2023). GPT-4 agrees with people about as often as people agree with each other, so open models like Zephyr and Tulu 3 trained on AI feedback.

To learn from pairs, give each answer a hidden score: rw for the winner, rl for the loser. The Bradley-Terry model (1952) says each answer wins in proportion to e to its score: P = erw / (erw + erl). Divide the top and bottom by erw, and it becomes a function of the gap alone:

Say it aloud

P of y-w preferred to y-l equals sigma of r-w minus r-l.

P(yw ≻ yl)
P of y-w preferred to y-l the chance a labeler picks answer y-w over answer y-l. Read the curly sign as "beats".
σ
sigma the sigmoid, 1 / (1 + e−z). It turns any number into a chance between 0 and 1; σ(0) = 0.5.
rw
r-w the score of y-w. Only gaps between scores matter.
rl
r-l the score of y-l.
In plain words

Subtract r-l from r-w to get the gap. Pass the gap through the sigmoid. A gap of 0 is a coin flip; a large positive gap means y-w almost always wins.

With numbers

With made-up scores r-w = 2.1 and r-l = 0.4: the gap is 1.7, and σ(1.7) = 1 / (1 + 0.183) = 0.846. The long form agrees: 8.166 / (8.166 + 1.492) = 0.846. Labelers pick y-w 85 times in 100.

Ask 40 labelers

Drag the score gap. The dot rides the sigmoid; the grid shows 40 labelers who each vote with that chance.

1.7

We simulate the votes with a fixed seed; each labeler picks A with chance σ(gap).

Worked number on noise. Assume each labeler picks the better answer with the same chance p on every pair. Two labelers then agree with chance p2 + (1 − p)2. Setting that to 72.6% gives p = 0.836, a gap of ln(0.836/0.164) = 1.63. So no reward model can match one labeler more than about 84% of the time.

Symptom: reward-model accuracy stops rising in the low 70s, whatever you try.

Measure: have two labelers label the same pairs, and compute their agreement.

Fix: if agreement is the ceiling, sharpen the guidelines or collect several labels per pair; a bigger model will not help.

Two answers get the same score, rA = rB = 1.5. What is P(A ≻ B)?

Chapter 4

The Reward Model Learns a Score, and Its Shortcuts

Fit a scorer to pairs, and watch it learn that longer looks better

A reward model reads a prompt and an answer and returns one number. InstructGPT built it from the SFT model: remove the last layer that predicts tokens, and add a head that outputs a scalar. Its reward model had 6B parameters.

Train it so the Bradley-Terry odds match the labels. Call the reward model with weights φ rφ(x, y). Over the labeled triples (x, yw, yl), maximize the log chance of each observed choice, which means minimizing:

Say it aloud

L-R-M equals minus the average, over labeled pairs, of the log of sigma of r-phi of x and y-w, minus r-phi of x and y-l.

LRM
L-R-M the reward model's loss. ln 2 = 0.693 when it cannot tell the answers apart; 0 when it is sure and right.
E
the average over pairs the mean over all labeled triples of prompt, winner, loser.
ln
the log of the chance the model gave the choice people made.
σ
sigma the sigmoid from Chapter 3: the Bradley-Terry chance that the winner wins.
rφ(x, yw)
r-phi of x and y-w the score the reward model, with weights φ, gives the winning answer.
rφ(x, yl)
r-phi of x and y-l the score it gives the losing answer.
In plain words

For each pair, score both answers with r-phi and take the margin. Turn the margin into a chance with sigma and take its log. Average over pairs and flip the sign.

With numbers

With made-up scores: a margin of 1.7 gives a loss of −ln 0.846 = 0.168. A margin of −1 (the wrong order) gives 1.313. The gradient on the margin is −(1 − σ): a push of 0.15 for the first pair and 0.73 for the second. Wrongly ranked pairs pull hardest.

This is logistic regression on score differences. InstructGPT keeps all K(K − 1)/2 pairs from one ranking in one batch element. Shuffled apart, these correlated pairs made the reward model overfit in one pass.

Train a reward model on pairs

Each toy answer has a true quality and a length. The reward model sees a noisy reading of quality, plus the length. Press Train, then turn off the link between length and quality.

1,000

Illustrative toy, computed live with a fixed seed. Quality and length are standard normal; when linked, their correlation is 0.6. Labels follow Bradley-Terry on true quality times 2. The model reads quality with noise of standard deviation 1. Accuracy is on 2,000 held-out pairs: does it rank the truly better answer first?

Worked number, from the toy with 1,000 pairs. With length linked to quality, the length weight is 0.51 and held-out accuracy 77.6%; without the link, the weight is about 0 and accuracy 73.4%. Length is a real clue here. It turns into a weakness when a policy can pad without adding quality: 2 units of padding buy 1.02 points.

Stiennon et al. (2020) saw this in a real reward model: it preferred edits that shortened a summary 62.6% of the time, people 76.4%.

Symptom: the reward model's score rises when you pad an answer with filler.

Measure: score answers before and after padding, or split accuracy by length.

Fix: balance lengths within pairs, collect pairs where the shorter answer wins, and report length next to reward.

In the toy, the reward model puts weight on length even though people do not value length. Why?

Chapter 5

The Leash: Reward Minus Drift

Write the RLHF objective, and solve it exactly for one prompt

Now tune the language model, the policy, to earn high reward. Maximizing the reward alone finds the reward model's blind spots, as the hero shows at small β. So RLHF adds a penalty for drifting from the SFT model, the reference policy.

Call the policy π, the reference πref, and the reward r(x, y). Drift is the KL divergence: KL(π ‖ πref) = Σy π(y) ln(π(y) / πref(y)), the average log ratio under π. It is 0 only when the two match. A number β sets its price:

Say it aloud

J of pi equals the expected r of x and y with y drawn from pi, minus beta times the K-L of pi from pi-ref.

J(π)
J of pi the objective RLHF maximizes for prompt x.
Ey~π
the expected value with y drawn from pi the average over answers the policy would write, weighted by their probability.
r(x, y)
r of x and y the reward model's score for answer y.
β
beta the leash: the reward one nat of drift costs. Large β holds the policy near SFT.
KL(π ‖ πref)
K-L of pi from pi-ref how far the policy has drifted from the SFT model, in nats.
In plain words

Average the reward r over the answers the policy π writes. Measure its drift from π-ref with the KL. Subtract beta times the drift. Find the π with the highest J.

With numbers

From the hero at β = 1: the best policy averages a reward of 1.056 at a drift of 0.265 nats. J = 1.056 − 1 × 0.265 = 0.791. The SFT model itself scores J = 0.455, with no drift.

For one prompt, this has an exact answer. Rewrite J by folding the reward into the log:

J(π) = −β Σy π(y) ln[ π(y) / (πref(y) er(y)/β) ] = −β KL(π ‖ π*) + β ln Z

Here Z = Σy πref(y) er(y)/β is the total that makes π* sum to 1. The term β ln Z does not depend on π. A KL is never negative and is 0 only at a match, so J is largest exactly when π = π*:

Say it aloud

Pi-star of y equals pi-ref of y, times e to the r of y over beta, divided by Z.

π*(y)
pi-star of y the best policy's probability of answer y: the policy the hero draws in purple.
πref(y)
pi-ref of y the SFT model's probability of y: the yellow outline.
er(y)/β
e to the r of y over beta the reward's boost. Small β makes the boost explode for the top answer.
Z
Z the partition function: the sum of π-ref times the boost over all answers, so the result sums to 1.
In plain words

Start from the SFT probabilities. Multiply each by e to its reward over beta. Divide everything by the total Z.

With numbers

From the hero at β = 0.5: the padded answer has π-ref = 0.05 and reward 2.0, so its boost is e4 = 54.6 and its weight 2.730. All six weights sum to Z = 7.562. So π*(padded) = 2.730 / 7.562 = 0.361, up from 0.05.

Build the best policy in three steps

Step through the formula for the hero's six answers. Then change β and step again.

0.5

Same toy as the hero; exact arithmetic.

The KL term does two jobs, as Stiennon et al. put it. It acts as an entropy bonus, so the policy does not collapse onto one answer. And it keeps the policy near the answers the reward model saw in training, where its scores mean something.

Symptom: the reward keeps rising and the KL from the reference grows without bound.

Measure: log the KL to πref next to the reward at every step.

Fix: raise β, or stop at the checkpoint where held-out human preference peaks (Chapter 9).

In J(π) = E[r] − β KL(π ‖ πref), what happens as β goes to 0?

Chapter 6

PPO: Small, Clipped Steps Toward the Optimum

Reach the leashed optimum by sampling, and stop each update from going too far

A real model can write more answers than there are atoms, so it cannot compute Z. It must sample answers, score them, and nudge its weights. InstructGPT did this with PPO (Schulman et al., 2017), following Stiennon et al.

The leash becomes a per-token reward. At every generated token, the policy pays β times ln(π/πref) for that token. At the last token it also receives the reward model's score. InstructGPT used β = 0.02 and trained for 256,000 episodes on about 31,000 prompts. PPO keeps four models busy: the policy, the frozen reference, the reward model and a value model that predicts future reward. InstructGPT used a 6B reward model and a 6B value model.

The lecture tells the story in three attempts. Plain policy gradients have high variance (see Policy Gradients). TRPO limits each update with a KL constraint, which needs a more complex constrained solver. PPO keeps the limit and drops the solver: it clips. Call the advantage A, how much better a token did than expected. Call the ratio of new to old probability ρ, and the clip width ε:

Say it aloud

L-clip equals the expected minimum of rho times A, and rho clipped to between one minus epsilon and one plus epsilon, times A.

LCLIP
L-clip PPO's surrogate objective, which it maximizes for several gradient steps on one batch of samples.
E
the expected value the average over the sampled tokens in the batch.
min
the minimum take the smaller of the two terms: the cautious one.
ρ
rho π-new(token) / π-old(token): 1 before any update.
A
A the advantage: positive if the token beat the value model's forecast.
clip(ρ, 1−ε, 1+ε)
rho clipped to one minus epsilon, one plus epsilon rho held inside the band; ε = 0.2 in the PPO paper.
In plain words

Multiply the ratio rho by the advantage A. Also multiply the clipped ratio by A. Keep the smaller. Once rho leaves the band in the helpful direction, the term goes flat and stops pushing.

With numbers

With made-up numbers, ε = 0.2: a token with A = 2 whose probability rose by half has ρ = 1.5. The unclipped term is 3.0; the clipped one is 1.2 × 2 = 2.4. The min is 2.4, a flat spot: no more push. With A = −1 and ρ = 0.6, the terms are −0.6 and −0.8; the min, −0.8, is flat too.

Clip one token's update

The dashed line is the unclipped term ρA; the solid line is what PPO keeps. Drag ρ, then flip the sign of A.

1.50
0.20

Exact formula; one token, made-up advantage.

The clip and the KL leash do different jobs. The clip limits how far one update moves from the policy that sampled the batch. The leash limits how far all of training moves from SFT. Lecture 17 derives policy gradients and PPO in full; the PPO paper walkthrough covers the rest.

Symptom: reward climbs, then collapses after a few batches.

Measure: the KL between old and new policy per batch, and the fraction of tokens clipped.

Fix: lower the learning rate or the epochs per batch. Many tokens clipped means steps are too big.

A token has A = +3 and its probability already doubled (ρ = 2), with ε = 0.2. How hard does PPO keep pushing it up?

Chapter 7

DPO: The Policy Is Its Own Reward Model

Invert the exact optimum, put it into Bradley-Terry, and train on pairs with no sampling

PPO needs four models, a sampling loop and careful tuning. DPO (Rafailov et al., 2023) asks: can we train on the pairs directly? The lecture lists the key steps. Assume the policy can be any distribution, so the optimum from Chapter 5 is reachable. Then write the reward as a function of the policy, and fit it with the Bradley-Terry loss.

Take the log of π* = πref er/β / Z and solve for r. This is the implied reward:

r(x, y) = β ln[ π*(y | x) / πref(y | x) ] + β ln Z(x)

Put it into Bradley-Terry for a pair. The term β ln Z(x) depends only on the prompt, so it appears in both rewards and cancels in the difference. Swap π* for the policy we train, πθ. Call its log ratio on the winner Δw = ln πθ(yw | x) − ln πref(yw | x), and on the loser Δl. The loss is the reward-model loss, with the policy as the reward model:

Say it aloud

L-D-P-O equals minus the average over pairs of the log of sigma of beta, times delta-w minus delta-l.

LDPO
L-D-P-O the DPO loss; minimizing it trains the policy directly.
E
the average over pairs the mean over labeled triples of prompt, winner, loser.
ln
the log of the Bradley-Terry chance of the observed choice.
σ
sigma the sigmoid.
β
beta the same leash as in RLHF; it scales log ratios into rewards.
Δw
delta-w how much more log probability the policy gives the winner than the SFT model does.
Δl
delta-l the same log ratio for the loser.
In plain words

Score both answers under the policy and the frozen SFT model. Take each log ratio, delta-w and delta-l. Multiply their difference by beta, pass it through sigma, take the log, and flip the sign.

With numbers

With made-up numbers, β = 0.1: the policy has raised the winner by Δw = +1.0 and lowered the loser by Δl = −1.0. The margin is 0.1 × 2 = 0.2, and the loss is −ln σ(0.2) = 0.598. At the start, both deltas are 0 and the loss is ln 2 = 0.693.

The gradient raises ln π(yw) and lowers ln π(yl), with weight β σ(β(Δl − Δw)). The lecture calls this "positive gradient on good, negative gradient on bad", scaled by the prediction error of the implied reward model. Pairs the policy already ranks right get a small push.

Weigh one DPO update

Drag how far the policy has moved the winner and the loser from the SFT model. The bars show the push each gets next.

+1.0
−1.0
0.10

Exact formula; one pair, made-up log ratios.

Symptom: the margin grows, but the winner's own probability falls during training.

Measure: log Δw and Δl separately, not only their difference.

Fix: the loss sees only the difference, so both can sink. Lower the learning rate, stop earlier, or add an SFT loss on the winners.

Why does the partition function Z(x) vanish from the DPO loss?

Chapter 8

Showcase: RLHF and DPO on the Same Pairs

Train both from one set of labels, and watch them land on the same policy

Both methods solve the objective of Chapter 5. RLHF fits a reward model, then optimizes the policy against it: two stages. DPO fits the policy to the pairs: one stage. Labelers compare pairs of the hero's six answers, drawn from the SFT model, and pick by Bradley-Terry on human quality.

Race RLHF against DPO

Press Train. RLHF fits its reward model, then its policy; DPO trains its policy from the start. The yellow tick is the leashed optimum computed from true human quality, the target.

300
0.5

Illustrative toy, computed live with a fixed seed. The reward model has one score per answer. RLHF's second stage takes exact policy steps with no sampling noise; PPO estimates such steps from samples. Both fits use the same small penalty on centred rewards, so both share one optimum.

Things to try. Train at 300 pairs and β = 0.5. Both policies match to three decimals, and both land near the target: human quality 0.818 against the target's 0.859. Raise the pairs to 2,000: both reach 0.828 together. Drop to 40 pairs: both land on the same, worse policy (0.773), because they share the same data. DPO saves a stage, not labels.

Real comparisons agree, with caveats. In the AlpacaFarm table the lecture shows, PPO and DPO both reach a simulated win rate of 46.8% (±1.8 and ±1.7). In the DPO paper, with GPT-4 as the judge, DPO's summaries beat the human-written ones 61% of the time, PPO's 57%. In Ivison et al. (2024), on the same better preference data, PPO edges DPO, 62.2 against 61.0 on an average of evaluations. The lecture's verdict: RL results are highly contingent on the setup.

The lecture also names two DPO variants from Tulu 3. SimPO drops the reference model; length-normalized DPO divides each log probability by the answer's length.

FeatureRLHF with PPODPO
Models in memory4: policy, reference, reward, value2: policy, reference
Training datapairs, then fresh samples from the policyfixed pairs only
Stagesfit reward model, then RL loopone supervised loss
Explores new answersyes, during samplingno
Main riskinstability; reward hackingover-fitting the pairs; length drift

Check yourself. Why do the two policies match exactly in this toy? Which assumption from Chapter 7 makes that true, and where does a real network break it?

Chapter 9

Over-Optimization: The Score Rises, Quality Falls

Optimize a proxy hard enough and it stops tracking the goal

Goodhart's law: when a measure becomes a target, it stops being a good measure. The reward model is a measure of human taste, fit on finite noisy pairs. Push the policy far enough, and it finds answers the reward model overrates, like the padded answer in the hero.

Stiennon et al. saw it in summarization. Light optimization improved summaries. Further on, the reward model's prediction kept rising while human preference fell, until the two were anti-correlated.

Gao et al. (2022) measured it with a large "gold" reward model in the role of the human. They tracked gold score against d, the square root of the KL from the starting policy. With fitted coefficients a and b (the paper's α and β; we keep β for the leash), gold reward R under RL follows:

Say it aloud

R of d equals d times a minus b log d.

R(d)
R of d the gold reward gained, measured from the starting policy, so R(0) = 0.
d
d the square root of the KL from the starting policy: how far optimization has moved it.
a
a the early slope: how fast real quality rises at first.
b
b the over-optimization rate; it shrinks as the proxy reward model grows.
ln d
log d the natural log of d: it grows slowly, so the fall comes late and does not stop.
In plain words

Early on, real reward grows like a times d. The b ln d term eats into it more as d grows. Past the peak, every extra nat of drift costs real quality.

With numbers

With made-up a = 1 and b = 0.5: the peak is at d = ea/b − 1 = e = 2.72, a KL of 7.39 nats. There R = b × d = 1.36. At d = e2 = 7.39 the gain is back to 0.

Loosen the leash all the way

Each point is the hero's best policy at one β, placed by its drift. Drag β along the curve, then change how much the reward model overrates length.

1
1.00

Same toy as the hero. The reward-model score is human quality plus the bias times each answer's length (0 is a perfect reward model). Exact optimum at each β.

Worked number, from the toy with bias 1: human quality peaks at 0.57 near β = 1.15, a drift of 0.21 nats. At β = 0.05 the score is 2.00 and quality −0.50. With bias 0 there is no peak. For comparison, best-of-n sampling has an exact drift of ln n − (n − 1)/n: n = 16 costs 1.84 nats.

The lecture adds two warnings. Over-optimization appears with human labels and noisy simulated labels, but not with noiseless ones. And RLHF tends to remove calibration, part of mode collapse: the policy piles onto a few favoured answers.

InstructGPT paid an alignment tax too: RLHF lowered scores on some public datasets, such as SQuAD, DROP, HellaSwag and WMT French to English. Mixing pretraining updates into PPO (their PPO-ptx) shrank the loss.

Symptom: the reward-model score keeps rising while human or gold win rate falls.

Measure: evaluate checkpoints on held-out human or gold preferences, plotted against √KL.

Fix: keep the checkpoint at the peak. A larger proxy reward model peaks later and higher (Gao et al.).

After 10,000 PPO steps the reward-model score is at its highest, but people rate the model below the SFT checkpoint. What happened?

Chapter 10

Field Guide

Keep the table, the code and the warnings for the next post-training run

Post-training turns a text predictor into an assistant in two stages. SFT imitates demonstrations, graded only on the answer. RLHF learns a reward from pairs, then raises it on a KL leash, with PPO or, in one supervised step, with DPO. The leash exists because the reward model is wrong far from its data.

ToolFormula and numberMain caveat
SFT loss−(1/T) Σ ln p(yt); 0.7, 0.6, 0.9, 0.8 gives 0.299mask the prompt; teach format, not new facts
Bradley-TerryP = σ(rw − rl); gap 1.7 gives 0.846labelers agree only 72.6% of the time
Reward model−ln σ(margin); 1.7 gives 0.168learns shortcuts such as length
Leashed optimumπ* = πref er/β/Z; padded 0.05 to 0.361 at β = 0.5small β chases reward-model errors
PPO clipmin(ρA, clip(ρ)A); ρ 1.5, A 2 gives 2.44 models; finicky tuning
DPO−ln σ(β(Δw − Δl)); 0.1, +1, −1 gives 0.598no exploration; both log probs can sink
Over-optimizationR = d(a − b ln d); a 1, b 0.5 peaks at KL 7.39a KL penalty acts like early stopping

The core, as Python we ran:

python
import numpy as np
sig = lambda z: 1 / (1 + np.exp(-z))

def sft_loss(token_probs, is_answer):          # mask: grade the answer only
    lp = np.log(np.asarray(token_probs))[np.asarray(is_answer)]
    return -lp.mean()

def bt_loss(r_w, r_l):                         # reward model on one pair
    return -np.log(sig(r_w - r_l))

def best_policy(pi_ref, r, beta):              # exact optimum of E[r] - beta KL
    w = pi_ref * np.exp(r / beta)
    return w / w.sum()

def ppo_clip(rho, adv, eps=0.2):
    return np.minimum(rho * adv, np.clip(rho, 1 - eps, 1 + eps) * adv)

def dpo_loss(lp_w, lp_l, ref_w, ref_l, beta=0.1):   # summed log probs of each answer
    return -np.log(sig(beta * ((lp_w - ref_w) - (lp_l - ref_l))))

sft_loss([.9, .02, .7, .6, .9, .8], [False, False, True, True, True, True])   # 0.299
bt_loss(2.1, 0.4)                                     # 0.168
pi_ref = np.array([.25, .30, .15, .05, .15, .10])
r = np.array([.4, 1.0, 1.3, 2.0, -.8, -1.2])
best_policy(pi_ref, r, 0.5)[3]                        # 0.361, the padded answer
ppo_clip(1.5, 2.0)                                    # 2.4
dpo_loss(-9.0, -12.0, -10.0, -11.0)                   # 0.598: deltas +1 and -1

The lecture's recap has three points. RLHF data collection is hard, with many confounders. RLHF algorithms are more complex than SFT, PPO most of all. And over-optimizing a reward has costs.

Keep going

Read next

The habit. Next to every reward curve, plot the KL from the reference and a held-out human or gold score. When the two curves part, stop.
Which stage of the InstructGPT recipe trains directly on comparisons between two answers?

Now teach it: press Present or Teach. Derive π* from the leashed objective, then DPO from π*, and explain why the padded answer wins at small β. Then go back to the leash and predict the β where human quality peaks before you drag.

Alignment I: SFT and RLHF · Stanford CS336, Lecture 15
Previous: Data II · Next: Alignment II, RLVR · Course site · Back to Gleams