RLHF and DPO

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.

Tune a model on human picks

0.5

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

The Model Knows, but Does Not Help

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.

Ask the model after each stage

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.

The road

  1. Preferences as data: a prompt, a chosen answer, a rejected answer.
  2. The Bradley-Terry model: scores become pick probabilities.
  3. Training the reward model: the loss that fits the scores.
  4. RLHF with a KL leash: chase reward, pay for distance from the reference.
  5. The best policy in closed form: the hero's dashed ticks.
  6. DPO: solve for the reward, watch Z cancel, get one loss.
  7. Inside the DPO loss: the implicit reward, the gradient and the code.
  8. Two routes, one target: the hero's two buttons, raced side by side.
  9. What breaks: runaway margins, stale data, and the methods that followed.
  10. The field guide: terms, numbers, checklist and code.
Why does instruction tuning alone leave a gap?

Chapter 1

Preferences as Data

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.

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.

A labeler ranks 6 answers to one prompt. How many preference pairs does the ranking give?

Chapter 2

The Bradley-Terry Model

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.

Say it aloud

P of y-w beats y-l given x equals sigma of r of x, y-w, minus r of x, y-l.

P(yw ≻ yl | x)
P of y-w beats y-l given x the chance that a person picks answer y-w over answer y-l for prompt x.
σ
sigma the sigmoid: 1 divided by 1 plus e to the minus z. It maps any number to a chance; σ(0) = 0.5.
r(x, yw)
r of x, y-w the reward of the chosen answer, any real number.
r(x, yl)
r of x, y-l the reward of the rejected answer.
In plain words

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 numbers

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.

Turn two rewards into a pick rate

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.

2.5
1.0

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.

Two answers have rewards 0.3 and 0.3. What chance does Bradley-Terry give that a person picks the first?

Chapter 3

Training the Reward Model

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.

Say it aloud

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.

LRM(φ)
L-RM of phi the reward-model loss for weights phi. Lower is better; 0 is a perfect fit.
E(x, yw, yl)∼D
the average over triples from D one term per recorded pick, averaged.
log σ(…)
log sigma of the gap the log of the Bradley-Terry chance of the real pick. It is 0 or below.
rφ(x, yw)
r-phi of x, y-w the network's reward for the chosen answer.
rφ(x, yl)
r-phi of x, y-l the network's reward for the rejected answer.
In plain words

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 numbers

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.

Fit the reward model

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.

The reward model gives the chosen answer 1.0 and the rejected answer 2.5. What does one gradient step do?

Chapter 4

RLHF: Chase the Reward, Pay for Distance

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:

  1. Collect triples: sample two answers from the SFT model, ask a person to pick.
  2. Fit the reward model r-phi on the triples (Chapter 3).
  3. Tune the policy π-theta, the language model with weights θ, by RL to raise r-phi. The usual RL method is PPO, a policy gradient method.

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.

Say it aloud

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.

DKL(πθ ‖ πref)
D-KL of pi-theta from pi-ref the distance of the policy from the reference, in nats. It is 0 only when the two match.
Ey∼πθ
the average over y drawn from pi-theta over answers the policy itself writes.
log πθ(y|x)
log pi-theta of y given x the log-chance that the policy writes answer y for prompt x: the sum of its tokens' log-chances.
log πref(y|x)
log pi-ref of y given x the same log-chance under the frozen reference.
In plain words

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 numbers

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.

Say it aloud

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.

maxθ
maximize over theta find the policy weights that make the rest largest.
Ex∼D, y∼πθ
the average over prompts x and answers y from pi-theta the policy writes its own answers to the dataset's prompts.
rφ(x, y)
r-phi of x, y the frozen reward model's score for each answer.
β
beta the price of one nat of distance: the leash. A bigger beta keeps the policy closer to the reference.
DKL(πθ ‖ πref)
D-KL the distance from the reference, from the equation above.
In plain words

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 numbers

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.

Loosen the leash on a flawed reward

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.

1

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.

During RLHF the reward-model score keeps rising, but people now rate the answers worse. What is the first knob to turn?

Chapter 5

The Best Policy in Closed Form

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.

  1. Write the goal for one prompt as a sum over answers y. The KL is an average of a log-ratio, so both parts share the weight π(y|x).
    J(π) = Σy π(y|x) [ r(x,y) − β log( π(y|x) ÷ πref(y|x) ) ]
  2. Pull out −β. Write the reward as a log: r = β log er/β. Now one log holds everything.
    J(π) = −β Σy π(y|x) log[ π(y|x) ÷ ( πref(y|x) er(x,y)/β ) ]
  3. The bottom does not add to 1 over y. Call its total Z(x), the partition function, and define π* (pi-star) as the bottom divided by Z(x), which does add to 1.
    Z(x) = Σy πref(y|x) er(x,y)/β
  4. Swap the bottom for Z(x) times π*. Since Σy π(y|x) = 1, the Z(x) comes out of the sum as one term.
    J(π) = −β DKL(π ‖ π*) + β log Z(x)
  5. A KL is never below 0 and is 0 only when the two match. The second term does not depend on π. So J is largest when π = π*, and its best value is β log Z(x).
Say it aloud

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.

π*(y|x)
pi-star of y given x the best policy's chance of answer y: the one that maximizes reward minus beta times KL.
πref(y|x)
pi-ref of y given x the reference model's chance of answer y.
er(x,y)/β
e to the r over beta the boost for answer y. A reward higher by beta multiplies the chance by e, about 2.72.
Z(x)
Z of x the partition function: the sum, over every answer, of pi-ref times the boost. Dividing by it makes the chances add to 1.
In plain words

Start from the reference chances. Multiply each by e to its reward over beta. Divide every result by their total Z of x.

With numbers

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%.

Find the peak of the goal

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.

2
0.80

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.

What happens to pi-star as beta grows very large?

Chapter 6

DPO: From the Best Policy to One Loss

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.

Say it aloud

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.

r(x, y)
r of x, y the reward of answer y, now written through the best policy.
β
beta the leash from Chapter 4. It converts log-ratios into reward units.
log(π* ÷ πref)
log of pi-star over pi-ref the log-ratio: how much more likely the best policy makes y than the reference does.
β log Z(x)
beta log Z of x one number per prompt, the same for every answer to it.
In plain words

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.

With numbers

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).

r(x,yw) − r(x,yl) = β log( π*(yw|x) ÷ πref(yw|x) ) − β log( π*(yl|x) ÷ πref(yl|x) )

Step 3. Z(x) is gone. The one quantity we could never compute cancels.

Watch Z cancel

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.

2.0

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.

Say it aloud

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.

LDPO(θ)
L-DPO of theta the DPO loss for the policy weights theta. Lower is better.
E(x,yw,yl)∼D
the average over triples from D the same fixed preference data as the reward model used.
β log(πθ(yw|x) ÷ πref(yw|x))
beta log-ratio of the chosen answer how much more likely the policy makes y-w than the reference does, times beta.
β log(πθ(yl|x) ÷ πref(yl|x))
beta log-ratio of the rejected answer the same for y-l.
In plain words

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.

With numbers

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.

Why can DPO ignore the partition function Z of x?

Chapter 7

Inside the DPO Loss

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:

QuantityChosen y-wRejected 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.

Say it aloud

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.

∇θLDPO
nabla-theta of L-DPO the direction that raises the loss fastest. The optimizer steps the other way.
β
beta the leash. It scales every step.
σ(r̂l − r̂w)
sigma of r-hat of y-l minus r-hat of y-w the weight: near 1 when the policy ranks the pair wrongly, near 0 when it already ranks it right by a wide margin.
∇θ log πθ(yw|x)
the gradient of log pi-theta of y-w the direction that makes the chosen answer more likely.
∇θ log πθ(yl|x)
the gradient of log pi-theta of y-l the direction that makes the rejected answer more likely.
In plain words

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.

With numbers

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.

Feel the loss and its weight

Teal is the loss, purple dashes are the weight, both against the gap z. Drag the two log-ratios, or change beta.

0.8
−0.3

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.

The policy already gives a pair an implicit reward gap of 5. What is the DPO gradient weight on that pair?

Chapter 8

Two Routes, One Target

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.

Race the two routes

Left: RLHF. Right: DPO. Dashed ticks are pi-star. Press Race, then change β and race again.

1

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.

PropertyRLHF with PPODPO
Networks in memory4: policy, reference, reward model, value network2: policy, reference
Trainings2: reward model, then RL1
Data during trainingNew answers sampled from the policy (online)Fixed triples only (offline)
Knobsbeta, PPO clip, advantage settings, learning ratesbeta, learning rate, epochs
Loss codeA full PPO loopFive lines
Reward model keptYes: reusable for scoring and filteringNo 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.

Which network does RLHF with PPO need that DPO does not?

Chapter 9

What Breaks, and What Came Next

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.

Train on a unanimous pick

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.

WeaknessMethodThe change
DPO margin runs awayIPO (Azar et al. 2023)Squared loss toward a finite margin
Reference model costs memorySimPO (Meng et al. 2024)Length-averaged log-chance as the reward, a target margin, no reference
No paired dataKTO (Ethayarajh et al. 2024)Learns from single answers marked good or bad
SFT and preference tuning are two runsORPO (Hong et al. 2024)SFT loss plus an odds-ratio penalty on the rejected answer, no reference
Offline data goes staleOnline or iterative DPOSample from the current policy, score, run DPO, repeat
People are slow and costlyRLAIF, Constitutional AI (Bai et al. 2022)A model judges pairs against written principles
One score for a long solutionProcess 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.

Why does IPO stop growing the margin while DPO does not?

Chapter 10

The Field Guide

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.

The equations

NameEquationUse
Bradley-TerryP(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 distanceEy∼π[log π − log π-ref]Distance from the reference
RLHF goalE[r-phi] − β KLWhat PPO climbs
Best policyπ-ref er/β ÷ Z(x)Where both routes end
Reward from policyβ log(π* ÷ π-ref) + β log ZThe DPO substitution
DPO loss−E[log σ(β ratio-w − β ratio-l)]One supervised loss
DPO gradientweight σ(r-hat-l − r-hat-w)Push wrong pairs hardest

The numbers from this page

WhatNumberWhy it matters
σ(2.5 − 1.0)0.818; loss 0.201A right ranking costs little
Scores swapped0.182; loss 1.70A wrong ranking costs 8 times more
Untrained loss (RM or DPO)log 2 = 0.693Check this on step 0
Toy reward model floor0.453Disagreement keeps the loss above 0
Best policy, ref 0.6/0.4, r 1/3, β 20.356 / 0.644Boosted, not winner takes all
Goal at the peak vs all in2.046 vs 1.17The KL charge punishes greed
DPO table examplegap 0.11; loss 0.640; weight 0.473A small step from the start
IPO target at β 0.1margin 5, ratio e5 ≈ 148Where IPO stops
Hero at β 0.5win 70%, KL 0.93Both routes, same end point

Before you trust a preference-tuning run

The core code

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()

Which route

SituationPickWhy
A fixed preference set, limited memoryDPOTwo networks, one supervised loss
You can sample and score new answersRLHF, or online DPOFeedback on the policy's own answers
You need a scorer for other jobsRLHFThe reward model is a product too
Many unanimous picksIPO, or DPO with early stoppingStops runaway margins

Keep going

The takeaway. RLHF and DPO solve the same problem: raise the reward people imply while paying beta for every nat away from the reference. RLHF learns the reward and climbs it. DPO notices that the policy already is a reward model, and fits it in one loss.
At step 0 of DPO training your loss is 0.41, not 0.693. What is the most likely bug?

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.

Credit and source

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.

CS 224R: RLHF and DPO
The course site · DPO · InstructGPT · Back to Gleams