People pick the better of two answers. RLHF learns a reward from the picks, then runs RL on a leash. DPO reaches the same model with one loss. In the toy, both routes end where the tuned answers win 70% of match-ups.
Learn how human picks become a reward, why RL needs a KL leash to the starting model, and how DPO folds both stages into one supervised loss. Every equation is read aloud.
Press Train and watch the two-stage route: the reward model learns its scores, then the policy moves. Switch to One loss (DPO) and train again. Drag β to tighten or loosen the leash. Then we build each piece: pairs, Bradley-Terry, the reward model, the KL penalty, the best policy and the DPO loss.
You need a little Python, what a probability is and what a logarithm does. The policy gradient helps in Chapter 4. We build the rest from zero.
Re-taught from Lecture 9, RLHF and DPO, by Archit Sharma, in Stanford CS 224R: Deep Reinforcement Learning (slides on the course site). Main papers: Christiano et al. (2017), Ouyang et al. (2022, InstructGPT) and Rafailov et al. (2023, DPO). The toys and their numbers are our own.
Illustrative toy. One prompt, five answers, a reference model with fixed chances, and 100 human picks (10 per pair) drawn from a hidden human score. Both routes use exact gradients, no sampling. We tuned the step sizes so each route settles in about 200 steps. The dashed tick is the best policy for this β (Chapter 5). "Win" is how often a human would prefer the tuned model's answer to the reference model's answer.
Chapter 0
Follow one prompt through the training stages and find the gap that preferences fill
Type "Explain the moon landing to a 6 year old" into a model trained only on web text. GPT-3 answered with more prompts: "Explain the theory of gravity to a 6 year old. Explain the theory of relativity to a 6 year old." On the web, more questions usually follow a list of questions.
The model is not stupid. Its training made web text likely. Nobody asked it to help. That mismatch is the alignment gap: the distance between "predict the next word" and "give the answer a person wants". A modern model closes it in four training stages. Each stage uses less data of higher quality.
Bars are the data each stage uses, on a log scale. Pick a stage and read its answer.
The pretrained answer is GPT-3's reply from OpenAI's InstructGPT work (Ouyang et al. 2022), as quoted in the lecture. The other three answers are illustrative. Data sizes are rough orders of magnitude, not counts from one model.
Instruction tuning, also called SFT (supervised fine-tuning), trains on prompts paired with good answers written by people. It teaches the model to answer. But you can only teach what someone can write down. "Be brief for easy questions, thorough for hard ones" is hard to write as one gold answer.
A person can still say "this answer is better than that one". The rest of this lesson turns those comparisons into training. Take made-up timings: a gold answer takes 10 minutes to write, and a comparison takes 1. One hour buys 6 written answers or 60 comparisons.
The failure. The symptom is an SFT model that follows instructions but rambles, hedges or invents citations. To measure it, show people its answers beside the SFT model's own earlier answers and count the wins. Near 50% means SFT has stalled. The fix is preference data. In the InstructGPT study, people preferred a 1.3 billion parameter model tuned this way over the 175 billion parameter GPT-3.
Chapter 1
Record a human pick as a triple, and see how one ranking becomes many pairs
The model writes two answers to one prompt. A person reads both and picks one. That is the whole act of labeling. Call the prompt x, the picked answer y-w (w for "winner", also called the chosen answer) and the other y-l (l for "loser", the rejected answer).
One pick is one preference triple (x, y-w, y-l). A dataset of triples is D. Below, the prompt is the moon landing, and five answers compete. Be the labeler.
Click the better answer. Warm bars count wins, pink bars count losses, over 100 crowd picks plus yours.
The five answers and the 100 crowd picks (10 for each of the 10 pairs) are illustrative. The same picks train the hero.
Five answers make 10 pairs, because each answer meets the other four and each pair counts once: 5 × 4 ÷ 2 = 10. InstructGPT asked labelers to rank 4 to 9 answers at once. A ranking of 9 answers gives 9 × 8 ÷ 2 = 36 pairs from one read.
Picks disagree. In the crowd data, the facts answer beats the lecture 4 times out of 10, and the lecture wins the other 6. That is not noise to delete. It says the two answers are close.
The failure. The symptom is labelers who disagree on most pairs, so the data says little. Measure it by giving the same pair to two labelers and counting how often they agree. If agreement is near 50%, the guidelines are unclear. The fix is sharper guidelines and examples, before you collect more.
Chapter 2
Give each answer a score and turn the gap between two scores into the chance of a pick
The story answer beats the hedge 9 times in 10. The facts answer beats the hedge 7 times in 10. Can one number per answer explain all ten pair rates at once?
Give each answer a reward, a score for how good it is for this prompt. Call it r(x, y). A bigger gap between two rewards should mean a more lopsided pick. The sigmoid σ turns any gap into a chance between 0 and 1: σ(z) = 1 ÷ (1 + e−z). Bradley and Terry proposed this model in 1952.
P of y-w beats y-l given x equals sigma of r of x, y-w, minus r of x, y-l.
Subtract the rejected answer's reward from the chosen answer's reward. Put the gap through the sigmoid. The result is the chance that a person picks y-w.
With made-up rewards 2.5 and 1.0: the gap is 1.5, and σ(1.5) = 1 ÷ (1 + 0.223) = 0.818. About 82 people in 100 pick the first answer.
The curve is the sigmoid of the gap. The dots are 20 raters: warm ones pick the first answer. Drag both rewards up together and watch what stays the same.
The raters are a fixed illustrative draw: rater k picks the first answer when the chance is above (k + 0.5) / 20.
Only the gap enters. Add 5 to every reward and every chance stays the same. So a reward model learns a ranking with spacing, not an absolute grade. Where does the sigmoid come from? If each person's sense of quality is the reward plus random noise of a type called Gumbel, the chance of a pick is exactly this sigmoid.
The failure. Some preferences go in a circle. Say A beats B, B beats C and C beats A, each 8 times in 10. No three scores can do that. The best fit gives all three the same score and predicts 50% for every pair.
The symptom is a reward model stuck at chance on part of the data. Measure it by fitting and checking each pair's predicted rate against its real rate. The fix is to split the prompts, or to accept that one score cannot hold that preference.
Chapter 3
Fit the scores so the recorded picks become as likely as possible
Real answers are not five fixed strings. So the reward is a network. A reward model takes the prompt and an answer as tokens and returns one number. It usually starts as a copy of the SFT model. A small linear layer maps the last token’s final hidden state to one number. Its weights are φ (phi), and its reward is r-phi(x, y).
Training asks one question of every triple: how likely does the model make the pick that happened? Take the log of each likelihood, average over D, and flip the sign so that lower is better. That is the reward-model loss.
L-RM of phi equals minus the average, over triples x, y-w, y-l from D, of log sigma of r-phi of y-w minus r-phi of y-l.
For each triple, score both answers with r-phi. Put the gap through the sigmoid and take the log. Average over D, flip the sign, and step phi downhill.
With made-up scores 2.5 for y-w and 1.0 for y-l: σ(1.5) = 0.818 and the loss is −log 0.818 = 0.201. Swap the scores: σ(−1.5) = 0.182 and the loss is 1.70, more than 8 times larger.
Purple bars are the five scores, centred on 0. The line is the loss. Press Fit. Then flip 30% of the picks and fit again.
A tabular toy: one score per answer stands in for the network. "Flip" mixes each pair's pick rate s into 0.7 × s + 0.3 × (1 − s).
At the start every score is 0, every chance is 0.5, and the loss is −log 0.5 = 0.693. Training stops near 0.453, not 0. The picks disagree, so no scores make every pick certain. The fitted scores rank the answers: story 1.61, lecture 0.65, facts 0.23, hedge −0.73, questions −1.76.
The failure. Flip 30% of the picks and the scores shrink toward each other. The ranking survives, but the gaps fall, so the policy later gets a weaker signal. The symptom is a reward model that is right on held-out pairs only a little more than half the time. Measure that held-out accuracy before you use the model. The fix is cleaner labels, or more of them.
Chapter 4
Run RL against the reward model, and charge the policy for every step away from the reference
RLHF (Christiano et al. 2017; Ouyang et al. 2022) has three stages:
Stage 3 alone goes wrong. The reward model saw only answers like the SFT model's. Far from them it can be badly wrong, and RL will find those places. So RLHF keeps a frozen copy of the SFT model, the reference π-ref. The KL divergence measures how far the policy has moved from it.
D-KL of pi-theta from pi-ref equals the average, over answers y drawn from pi-theta, of log pi-theta of y given x minus log pi-ref of y given x.
Let the policy write answers. For each, subtract the reference's log-chance from the policy's log-chance. Average the differences. That is how far pi-theta has moved.
With made-up chances over two answers: reference 0.6 and 0.4, policy 0.2 and 0.8. KL = 0.2 × log(0.2/0.6) + 0.8 × log(0.8/0.4) = −0.220 + 0.555 = 0.335 nats.
Now the full stage 3 goal. The policy earns reward and pays β (beta), a fixed price, for each nat of distance.
Maximize over theta the average, over prompts from D and answers from pi-theta, of r-phi of x, y, minus beta times D-KL of pi-theta from pi-ref.
Let the policy answer the prompts. Score each answer with r-phi. Subtract beta times the KL distance. Change theta to make that total larger.
With the made-up policy above, rewards 1 and 3, and beta 2: the average reward is 0.2 × 1 + 0.8 × 3 = 2.6. The charge is 2 × 0.335 = 0.67. The goal is 2.6 − 0.67 = 1.93, better than the reference's 1.8.
In practice PPO charges the penalty token by token. Each token's reward is minus β times its log-ratio. The reward model's score comes at the last token.
A sixth answer, a wall of bullet points, never appeared in the picks. Purple is what the reward model reports; warm is what people would say. Drag β down.
Illustrative. Each point is the policy that the KL-penalized objective reaches at that β (Chapter 5 shows how to compute it). The wall has reference chance 0.02, reward-model score 2.5 and a true human score of −1.
The failure is reward hacking. At β = 1 the true score is 0.69. At β = 0.1 the reward model reports 2.5, its maximum, while the true score falls to −1.0: the policy writes the wall almost every time. The symptom is a reward that climbs while human ratings fall. Measure the KL and a small human or held-out check at every evaluation. The fix is a larger β, early stopping, or a better reward model.
Chapter 5
Solve the KL-penalized goal exactly and find the reference reweighted by its rewards
Forget the network for a moment. Suppose the policy could put any chance on any answer. Which chances make the Chapter 4 goal largest? There is an exact answer, and it is the key to DPO. Fix one prompt x and follow five steps.
Pi-star of y given x equals pi-ref of y given x, times e to the r of x, y over beta, divided by Z of x.
Start from the reference chances. Multiply each by e to its reward over beta. Divide every result by their total Z of x.
With made-up values: reference 0.6 and 0.4, rewards 1 and 3, beta 2. The boosted weights are 0.6 × e0.5 = 0.989 and 0.4 × e1.5 = 1.793, so Z = 2.782. Pi-star is 0.356 and 0.644. The better answer rose from 40% to 64%, not to 100%.
Left: blue outlines are the reference, teal bars are pi-star. Right: the goal J for every chance of answer 2; drag the dot or the β slider.
The two-answer example from the worked numbers: reference 0.6 and 0.4, rewards 1 and 3.
Beta sets the temperature. As beta falls toward 0, the boost of the best answer swamps the rest and pi-star puts all its chance there. As beta grows, every boost goes to 1 and pi-star returns to the reference. At beta 2 the peak is J = β log Z = 2 × log 2.782 = 2.046. Going all in on answer 2 scores only 1.17, because the KL charge is 2 × log(1/0.4) = 1.83.
The failure. You cannot compute Z(x) for a real model. It sums over every possible answer, and a 100-token answer from a 50,000-word vocabulary has 50,000100 versions. So RLHF cannot write pi-star down; it must reach it by RL. The next chapter finds a way around Z.
Chapter 6
Solve the best policy for the reward, put it into Bradley-Terry, and watch Z cancel
RLHF runs two trainings and keeps four networks in memory. Rafailov et al. (2023) asked: we know the form of the best policy, so can we skip the reward model and the RL? Their answer is DPO, direct preference optimization, in four steps.
Step 1. Take the log of the Chapter 5 result and solve for the reward. Pi-star is the best policy and Z(x) the partition function.
r of x, y equals beta times log of pi-star of y given x over pi-ref of y given x, plus beta log Z of x.
Divide the best policy's chance of y by the reference's chance. Take the log and multiply by beta. Add beta log Z of x. The result is the reward of y.
Use the Chapter 5 example: pi-star 0.356 and 0.644, reference 0.6 and 0.4, beta 2, β log Z = 2.046. Answer 2: 2 × log(0.644/0.4) + 2.046 = 0.954 + 2.046 = 3.0. Answer 1: −1.046 + 2.046 = 1.0. These are the rewards we started from.
Step 2. Bradley-Terry needs only the gap r(x, y-w) − r(x, y-l). Write both rewards with Step 1 and subtract. Both answer the same prompt, so both carry the same β log Z(x).
Step 3. Z(x) is gone. The one quantity we could never compute cancels.
Each reward is a teal log-ratio part plus a grey β log Z part. Drag β log Z to any value. The gap on the right never moves.
The Chapter 5 example. The true β log Z is 2.046; the slider asks what happens for any other value.
Step 4. Put the gap into the Chapter 3 loss, and train a policy π-theta in place of pi-star.
L-DPO of theta equals minus the average over triples of log sigma of: beta log of pi-theta of y-w over pi-ref of y-w, minus beta log of pi-theta of y-l over pi-ref of y-l.
For each triple, compute the policy's log-ratio to the reference for y-w and for y-l. Subtract, multiply by beta, put through the sigmoid and take the log. Average, flip the sign, and step theta downhill.
At step 0, pi-theta equals pi-ref. Both log-ratios are 0, σ(0) = 0.5, and the loss is log 2 = 0.693.
The reward r-phi became β log(π-theta ÷ π-ref). The policy is its own reward model, as the DPO paper's title says: "Your language model is secretly a reward model."
The failure. Step 4 assumes that Bradley-Terry fits the picks and that the network can reach pi-star. If not, the loss stalls high. Compare it with a reward model's loss on the same held-out triples.
Chapter 7
Read the implicit reward, follow the gradient, and write the loss in five lines
Call β log(π-theta(y|x) ÷ π-ref(y|x)) the implicit reward of answer y, written r-hat-theta(x, y). It is the reward the policy behaves as if it believes. With made-up log-chances and beta 0.1:
| Quantity | Chosen y-w | Rejected y-l |
|---|---|---|
| log π-theta(y|x) | −15.2 | −14.8 |
| log π-ref(y|x) | −16.0 | −14.5 |
| log-ratio | +0.8 | −0.3 |
| implicit reward (× 0.1) | +0.08 | −0.03 |
The gap is 0.11. σ(0.11) = 0.527, so the loss is −log 0.527 = 0.640, a little below the starting 0.693. The rejected answer is more likely than the chosen one under the policy (−14.8 against −15.2). DPO does not care. It compares each answer with the reference, not with each other.
How does one step change the policy? Differentiate the loss. The derivative of −log σ(z) is −σ(−z), and the gap z is beta times the difference of two log-chances.
Nabla-theta of L-DPO equals minus beta times the average of: sigma of r-hat of y-l minus r-hat of y-w, times the gradient of log pi-theta of y-w minus the gradient of log pi-theta of y-l.
For each triple, push the chosen answer up and the rejected answer down. Weight the push by how wrong the implicit rewards are, and scale it by beta.
In the table, the weight is σ(−0.03 − 0.08) = σ(−0.11) = 0.473, so each push has strength 0.1 × 0.473 = 0.047. At a margin of 3 the weight is σ(−3) = 0.047, ten times smaller.
Teal is the loss, purple dashes are the weight, both against the gap z. Drag the two log-ratios, or change beta.
A log-ratio is log π-theta(y|x) minus log π-ref(y|x), each summed over the answer's tokens. The starting values are the table's.
In code, each log-chance is a sum over the answer's tokens, with the prompt tokens masked out. The reference runs without gradients.
pythonimport torch.nn.functional as F def dpo_loss(pi_w, pi_l, ref_w, ref_l, beta=0.1): # each input: [batch], log p(answer | prompt) summed over answer tokens # ref_w, ref_l come from the frozen reference under torch.no_grad() z = beta * ((pi_w - ref_w) - (pi_l - ref_l)) # [batch], the implicit reward gap return -F.logsigmoid(z).mean() # logsigmoid is stable for large |z|
The failure. If the code averages log-chances over tokens instead of summing, the log-ratios shrink by the answer length and the loss no longer matches the derivation. The symptom is a loss that barely moves. Measure it by checking that log π-theta equals log π-ref on step 0, so the loss is 0.693. The fix is a masked sum over answer tokens.
Chapter 8
Race RLHF and DPO on the same picks and count what each one costs
Both routes chase the same pi-star. RLHF fits r-phi, then climbs the KL-penalized goal by RL. DPO fits the policy directly, so its implicit reward equals the fitted r-phi up to a constant per prompt. Race them on the hero's 100 picks.
Left: RLHF. Right: DPO. Dashed ticks are pi-star. Press Race, then change β and race again.
Same toy as the hero. RLHF spends 60 steps on the reward model, then 200 RL steps; DPO takes 200 steps. Step counts are not comparable across routes in cost: one RLHF step also samples answers.
At beta 1 both routes end at story 0.44, lecture 0.28, facts 0.22: the same pi-star, at KL 0.33. The cost is not the same.
| Property | RLHF with PPO | DPO |
|---|---|---|
| Networks in memory | 4: policy, reference, reward model, value network | 2: policy, reference |
| Trainings | 2: reward model, then RL | 1 |
| Data during training | New answers sampled from the policy (online) | Fixed triples only (offline) |
| Knobs | beta, PPO clip, advantage settings, learning rates | beta, learning rate, epochs |
| Loss code | A full PPO loop | Five lines |
| Reward model kept | Yes: reusable for scoring and filtering | No explicit one |
With illustrative arithmetic: a 7-billion-parameter network in 16-bit numbers takes 7 × 2 = 14 GB of weights. Four such networks take 56 GB before any optimizer state; two take 28 GB. The value network is the critic that PPO uses to judge each token; DPO needs none.
The failure. The race is fair only with infinite, well-spread data. DPO learns only from answers in D. If D came from a different model, the policy's own likely answers get almost no signal. The symptom is a DPO model that fits held-out triples but loses to RLHF on fresh prompts. Measure the policy's log-chance of the dataset answers: a low value means D is off its distribution.
Chapter 9
Watch DPO overfit a unanimous pick, and map the methods built to fix each weakness
In the crowd data, the story beat "more questions" 10 times out of 10. What does DPO do with a unanimous pick? The loss −log σ(z) reaches 0 only as the gap z goes to infinity. So the gradient never stops. It keeps pushing the rejected answer's chance toward 0, whatever beta is.
Azar et al. (2023) proposed IPO. It replaces the log-sigmoid with a squared error that aims at a finite margin. Call the difference of the two log-ratios h; IPO minimizes (h − 1 ÷ (2β))2, so h stops at 1 ÷ (2β). With beta 0.1 that target is 5: the winner's chance rises relative to the loser's by e5 ≈ 148 times, and no further.
The line is the margin h over training steps. Pick a loss and press Train. The dashed line is IPO's target.
Illustrative: beta 0.1, one pair, plain gradient steps on the margin. We chose the two step sizes so each run is easy to watch.
DPO has one more weak spot: its data is fixed. The triples came from an older model, so they drift away from what the policy now writes. Each weakness led to a new method. The table names the main ones from the lecture.
| Weakness | Method | The change |
|---|---|---|
| DPO margin runs away | IPO (Azar et al. 2023) | Squared loss toward a finite margin |
| Reference model costs memory | SimPO (Meng et al. 2024) | Length-averaged log-chance as the reward, a target margin, no reference |
| No paired data | KTO (Ethayarajh et al. 2024) | Learns from single answers marked good or bad |
| SFT and preference tuning are two runs | ORPO (Hong et al. 2024) | SFT loss plus an odds-ratio penalty on the rejected answer, no reference |
| Offline data goes stale | Online or iterative DPO | Sample from the current policy, score, run DPO, repeat |
| People are slow and costly | RLAIF, Constitutional AI (Bai et al. 2022) | A model judges pairs against written principles |
| One score for a long solution | Process reward models (Lightman et al. 2023) | Score each reasoning step, not only the answer |
The failure, as a checklist. Runaway margins show as a DPO training loss near 0 with falling held-out accuracy. Stale data shows as a low policy log-chance on the dataset answers. Reward hacking shows as a rising reward with falling human ratings. Measure all three every evaluation.
Chapter 10
Keep the equations, the numbers, a checklist and the core code on one page
People compare two answers. Bradley-Terry turns a reward gap into a pick chance, and the reward-model loss fits the rewards. RLHF climbs that reward by RL while it pays beta per nat of KL from the reference. The best policy is the reference reweighted by e to the reward over beta. Solve it for the reward, and Z cancels inside Bradley-Terry: that is the DPO loss.
| Name | Equation | Use |
|---|---|---|
| Bradley-Terry | P(y-w ≻ y-l) = σ(r-w − r-l) | Scores to pick chances |
| Reward-model loss | −E[log σ(r-phi(y-w) − r-phi(y-l))] | Fit the scores |
| KL distance | Ey∼π[log π − log π-ref] | Distance from the reference |
| RLHF goal | E[r-phi] − β KL | What PPO climbs |
| Best policy | π-ref er/β ÷ Z(x) | Where both routes end |
| Reward from policy | β log(π* ÷ π-ref) + β log Z | The DPO substitution |
| DPO loss | −E[log σ(β ratio-w − β ratio-l)] | One supervised loss |
| DPO gradient | weight σ(r-hat-l − r-hat-w) | Push wrong pairs hardest |
| What | Number | Why it matters |
|---|---|---|
| σ(2.5 − 1.0) | 0.818; loss 0.201 | A right ranking costs little |
| Scores swapped | 0.182; loss 1.70 | A wrong ranking costs 8 times more |
| Untrained loss (RM or DPO) | log 2 = 0.693 | Check this on step 0 |
| Toy reward model floor | 0.453 | Disagreement keeps the loss above 0 |
| Best policy, ref 0.6/0.4, r 1/3, β 2 | 0.356 / 0.644 | Boosted, not winner takes all |
| Goal at the peak vs all in | 2.046 vs 1.17 | The KL charge punishes greed |
| DPO table example | gap 0.11; loss 0.640; weight 0.473 | A small step from the start |
| IPO target at β 0.1 | margin 5, ratio e5 ≈ 148 | Where IPO stops |
| Hero at β 0.5 | win 70%, KL 0.93 | Both routes, same end point |
pythonimport torch import torch.nn.functional as F def answer_logp(model, ids, answer_mask): # ids: [B, T] prompt + answer tokens; answer_mask: [B, T], 1 on answer tokens logits = model(ids).logits[:, :-1] # [B, T-1, V] tok = torch.gather(logits.log_softmax(-1), 2, ids[:, 1:].unsqueeze(-1)).squeeze(-1) return (tok * answer_mask[:, 1:]).sum(-1) # [B], a sum, not a mean def reward_model_loss(r_w, r_l): # [B] scalar scores return -F.logsigmoid(r_w - r_l).mean() def dpo_step(policy, ref, batch, beta=0.1): pi_w = answer_logp(policy, batch.ids_w, batch.mask_w) pi_l = answer_logp(policy, batch.ids_l, batch.mask_l) with torch.no_grad(): # the reference is frozen ref_w = answer_logp(ref, batch.ids_w, batch.mask_w) ref_l = answer_logp(ref, batch.ids_l, batch.mask_l) z = beta * ((pi_w - ref_w) - (pi_l - ref_l)) # implicit reward gap return -F.logsigmoid(z).mean()
| Situation | Pick | Why |
|---|---|---|
| A fixed preference set, limited memory | DPO | Two networks, one supervised loss |
| You can sample and score new answers | RLHF, or online DPO | Feedback on the policy's own answers |
| You need a scorer for other jobs | RLHF | The reward model is a product too |
| Many unanimous picks | IPO, or DPO with early stopping | Stops runaway margins |
Now press Present or Teach and derive DPO from memory: the KL-penalized goal, the best policy, the reward solved from it, the Z that cancels and the final loss. Then go back to the hero, train both routes at the same beta, and say why they end at the same bars.
This lesson re-teaches Lecture 9, RLHF and DPO, by Archit Sharma, in Stanford CS 224R: Deep Reinforcement Learning, adapted from CS 224N. The slides are on the course site. The papers behind it: Bradley and Terry (1952); Christiano et al., Deep RL from Human Preferences (2017); Ouyang et al., InstructGPT (2022); Schulman et al., PPO (2017); Rafailov et al., DPO (2023); Azar et al., IPO (2023). The toys and numbers here are our own.