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.
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
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:
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.
Chapter 1
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.
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.
Chapter 2
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:
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.
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 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.
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".
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.
Chapter 3
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:
P of y-w preferred to y-l equals sigma of r-w minus r-l.
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 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.
Drag the score gap. The dot rides the sigmoid; the grid shows 40 labelers who each vote with that chance.
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.
Chapter 4
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:
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.
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 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.
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.
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.
Chapter 5
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:
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.
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.
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 π = π*:
Pi-star of y equals pi-ref of y, times e to the r of y over beta, divided by Z.
Start from the SFT probabilities. Multiply each by e to its reward over beta. Divide everything by the total Z.
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.
Step through the formula for the hero's six answers. Then change β and step again.
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).
Chapter 6
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 ε:
L-clip equals the expected minimum of rho times A, and rho clipped to between one minus epsilon and one plus epsilon, times A.
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 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.
The dashed line is the unclipped term ρA; the solid line is what PPO keeps. Drag ρ, then flip the sign of A.
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.
Chapter 7
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:
L-D-P-O equals minus the average over pairs of the log of sigma of beta, times delta-w minus delta-l.
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 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.
Drag how far the policy has moved the winner and the loser from the SFT model. The bars show the push each gets next.
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.
Chapter 8
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.
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.
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.
| Feature | RLHF with PPO | DPO |
|---|---|---|
| Models in memory | 4: policy, reference, reward, value | 2: policy, reference |
| Training data | pairs, then fresh samples from the policy | fixed pairs only |
| Stages | fit reward model, then RL loop | one supervised loss |
| Explores new answers | yes, during sampling | no |
| Main risk | instability; reward hacking | over-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
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:
R of d equals d times a minus b log d.
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 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.
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.
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.).
Chapter 10
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.
| Tool | Formula and number | Main caveat |
|---|---|---|
| SFT loss | −(1/T) Σ ln p(yt); 0.7, 0.6, 0.9, 0.8 gives 0.299 | mask the prompt; teach format, not new facts |
| Bradley-Terry | P = σ(rw − rl); gap 1.7 gives 0.846 | labelers agree only 72.6% of the time |
| Reward model | −ln σ(margin); 1.7 gives 0.168 | learns shortcuts such as length |
| Leashed optimum | π* = πref er/β/Z; padded 0.05 to 0.361 at β = 0.5 | small β chases reward-model errors |
| PPO clip | min(ρA, clip(ρ)A); ρ 1.5, A 2 gives 2.4 | 4 models; finicky tuning |
| DPO | −ln σ(β(Δw − Δl)); 0.1, +1, −1 gives 0.598 | no exploration; both log probs can sink |
| Over-optimization | R = d(a − b ln d); a 1, b 0.5 peaks at KL 7.39 | a 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.
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.