Part III · RL for LLMs · Chapter 13

Direct preference optimization

Skip the reward model: derive DPO from the KL-regularized objective, and meet its variants.

~150 minBefore this: The wider landscape, LLM as a policy, RLHFUpdated 2026-10

Chapter 12 built the RLHF pipeline. You collected preference pairs, fit a Bradley–Terry reward model, and ran PPO against it, with four networks in memory (policy, reference, reward model, value function), a sampling loop, per-token KL penalties, GAE, and a long list of implementation details. It works, but it’s a lot of machinery for a simple goal: make the model produce more of what people prefer.

In 2023, Rafailov and colleagues pointed out that most of the machinery is unnecessary, at least on paper. The RL step in RLHF has a known answer, a closed-form formula you met in Chapter 10 and Chapter 11. If you know the answer’s form, you can turn the problem around: instead of learning a reward and then searching for the policy that maximizes it, write the reward in terms of the policy, and fit the policy to the preferences directly. The result is direct preference optimization (DPO): one loss, computed from four log-probabilities per preference pair, trained like supervised learning. No reward model, no sampling, no PPO. The paper’s subtitle says what is going on: your language model is secretly a reward model.

This chapter derives DPO slowly, with numbers you can check, then looks hard at what it gives up. DPO is offline, so it never sees its own mistakes. It can push the probability of the preferred answers down. With few labels it ignores its own leash. Then come the variants people built to fix these problems (IPO, KTO, ORPO, SimPO, online DPO), and the contested question of whether DPO or PPO works better.

Two facts you already have

DPO is built from two results from earlier chapters. Here they are side by side.

Fact 1: the KL-regularized optimum (Chapter 10 derived it, Chapter 11 applied it to language models). For a prompt xx, the RLHF objective is

max⁡π  Ey∼π(⋅∣x)[r(x,y)]  −  β KL(π(⋅∣x) ∥ πref(⋅∣x)),\max_{\pi}\; \mathbb{E}_{y \sim \pi(\cdot\mid x)}\big[r(x, y)\big] \;-\; \beta\, \mathrm{KL}\big(\pi(\cdot\mid x) \,\Vert\, \pi_\text{ref}(\cdot\mid x)\big),

and its maximizer is the reference policy tilted by the exponentiated reward:

π∗(y∣x)  =  1Z(x) πref(y∣x) er(x,y)/β,Z(x)=∑yπref(y∣x) er(x,y)/β.\pi^*(y\mid x) \;=\; \frac{1}{Z(x)}\, \pi_\text{ref}(y\mid x)\, e^{r(x,y)/\beta}, \qquad Z(x) = \sum_{y} \pi_\text{ref}(y\mid x)\, e^{r(x,y)/\beta}.

Z(x)Z(x) is a partition function: a sum over every possible response, astronomically many for a language model. Nobody can compute it. That’s why RLHF doesn’t just write down π∗\pi^* and stop; it runs PPO to approximate it by sampling.

Fact 2: the Bradley–Terry model (Chapter 12). The probability that an annotator prefers ywy_w to yly_l for prompt xx is

P(yw≻yl∣x)  =  σ(r(x,yw)−r(x,yl)),P(y_w \succ y_l \mid x) \;=\; \sigma\big(r(x, y_w) - r(x, y_l)\big),

with σ\sigma the logistic sigmoid. A reward model is fit by maximizing this likelihood on the preference data, which is the loss −log⁡σ(rϕ(x,yw)−rϕ(x,yl))-\log\sigma(r_\phi(x, y_w) - r_\phi(x, y_l)). Notice that only reward differences between two responses to the same prompt enter.

RLHF uses these facts in sequence: fit rr with Fact 2, then chase the π∗\pi^* of Fact 1 with RL. DPO’s idea is to use Fact 1 backwards.

The trick, with numbers

Take Chapter 10’s worked example and pretend it’s a language model with a single prompt and only three possible responses A, B, C. The reference policy is πref=(0.5,0.3,0.2)\pi_\text{ref} = (0.5, 0.3, 0.2), the rewards are r=(0,1,2)r = (0, 1, 2), and β=1\beta = 1. Chapter 10 computed the tilted optimum: the weights πref er\pi_\text{ref}\,e^{r} are (0.500,0.816,1.478)(0.500, 0.816, 1.478), so Z=2.793Z = 2.793, log⁡Z=1.027\log Z = 1.027, and π∗=(0.179,0.292,0.529)\pi^* = (0.179, 0.292, 0.529).

Now go the other way. Suppose someone hands you π∗\pi^* and πref\pi_\text{ref} but not the reward. Compute βlog⁡π∗πref\beta \log\frac{\pi^*}{\pi_\text{ref}} for each response:

Responseπref\pi_\text{ref}π∗\pi^*βlog⁡π∗πref\beta\log\dfrac{\pi^*}{\pi_\text{ref}}true rrr−βlog⁡Zr - \beta\log Z
A0.50.179ln⁡(0.358)=−1.027\ln(0.358) = -1.0270−1.027-1.027
B0.30.292ln⁡(0.973)=−0.027\ln(0.973) = -0.0271−0.027-0.027
C0.20.529ln⁡(2.645)=0.973\ln(2.645) = 0.97320.9730.973

The log-ratio column is the reward minus one constant, βlog⁡Z=1.027\beta \log Z = 1.027, the same for every response. So you don’t recover the reward exactly, but you recover every reward difference exactly: B − A =1= 1, C − A =2= 2, C − B =1= 1.

And reward differences are all Bradley–Terry needs. The probability an annotator prefers C to A is σ(2−0)=0.881\sigma(2 - 0) = 0.881, and you get the same number from the policy alone: σ(0.973−(−1.027))=σ(2)=0.881\sigma(0.973 - (-1.027)) = \sigma(2) = 0.881. The unknowable ZZ never came into it, because it cancelled in the subtraction.

So here is DPO in one sentence. If the policy is the tilted optimum for some reward, that reward is βlog⁡ππref\beta \log\frac{\pi}{\pi_\text{ref}} (up to a per-prompt constant), so fit the policy so that this implied reward explains the preference data under Bradley–Terry.

Deriving the DPO loss

Now the general version, in four steps.

Step 1: invert the optimum. Take the log of Fact 1 and solve for the reward:

r(x,y)  =  βlog⁡π∗(y∣x)πref(y∣x)  +  βlog⁡Z(x).r(x, y) \;=\; \beta \log \frac{\pi^*(y\mid x)}{\pi_\text{ref}(y\mid x)} \;+\; \beta \log Z(x).

Step 2: substitute into Bradley–Terry. For two responses to the same prompt, the βlog⁡Z(x)\beta \log Z(x) terms are identical and cancel:

P(yw≻yl∣x)  =  σ(βlog⁡π∗(yw∣x)πref(yw∣x)  −  βlog⁡π∗(yl∣x)πref(yl∣x)).P(y_w \succ y_l \mid x) \;=\; \sigma\Big(\beta \log \frac{\pi^*(y_w\mid x)}{\pi_\text{ref}(y_w\mid x)} \;-\; \beta \log \frac{\pi^*(y_l\mid x)}{\pi_\text{ref}(y_l\mid x)}\Big).

The preference probability is now written entirely in terms of the optimal policy and the reference. No reward function appears.

Step 3: make the policy the thing you learn. Replace π∗\pi^* by the trainable model πθ\pi_\theta. Each policy now defines a reward model, its implicit reward

r^θ(x,y)  =  βlog⁡πθ(y∣x)πref(y∣x),\hat r_\theta(x, y) \;=\; \beta \log \frac{\pi_\theta(y\mid x)}{\pi_\text{ref}(y\mid x)},

and πθ\pi_\theta is exactly the KL-regularized optimum for r^θ\hat r_\theta (plug r^θ\hat r_\theta into Fact 1 and you get Z=1Z = 1 and π∗=πθ\pi^* = \pi_\theta).

Step 4: maximum likelihood. Fit r^θ\hat r_\theta to the preference data with the ordinary Bradley–Terry loss, as you would fit a reward model in Chapter 12. That’s the DPO loss:

LDPO(θ)  =  − E(x,yw,yl)∼D[log⁡σ(βlog⁡πθ(yw∣x)πref(yw∣x)  −  βlog⁡πθ(yl∣x)πref(yl∣x))].\mathcal{L}_\text{DPO}(\theta) \;=\; -\,\mathbb{E}_{(x, y_w, y_l) \sim \mathcal{D}}\Big[\log \sigma\Big(\beta \log \frac{\pi_\theta(y_w\mid x)}{\pi_\text{ref}(y_w\mid x)} \;-\; \beta \log \frac{\pi_\theta(y_l\mid x)}{\pi_\text{ref}(y_l\mid x)}\Big)\Big].

Each term is a sequence log-probability, and (Chapter 11) a sequence log-probability is a sum of token log-probs: log⁡πθ(y∣x)=∑tlog⁡πθ(yt∣x,y<t)\log \pi_\theta(y\mid x) = \sum_t \log \pi_\theta(y_t \mid x, y_{\lt t}). So for each pair you need exactly four numbers: log⁡πθ(yw∣x)\log\pi_\theta(y_w\mid x), log⁡πθ(yl∣x)\log\pi_\theta(y_l\mid x), log⁡πref(yw∣x)\log\pi_\text{ref}(y_w\mid x), log⁡πref(yl∣x)\log\pi_\text{ref}(y_l\mid x). That takes one forward pass through each model for each of the two responses. The reference numbers don’t change during training, so you can compute them once in advance.

∂ The fine print: is fitting the policy really the same as fitting a reward and then optimizing it?

Step 3 quietly swapped “learn a reward, then find its optimal policy” for “learn a policy”. Here is why nothing is lost, in an idealized setting where both rr and π\pi can be any function.

Rewards come in equivalence classes. Call two rewards equivalent if they differ by a function of the prompt only: r′(x,y)=r(x,y)+f(x)r'(x, y) = r(x, y) + f(x). Equivalent rewards

  • give the same Bradley–Terry probabilities, because f(x)f(x) cancels in r′(x,yw)−r′(x,yl)r'(x, y_w) - r'(x, y_l) (this is the shift invariance of Chapter 12), and
  • give the same optimal policy, because er′/β=ef(x)/βer/βe^{r'/\beta} = e^{f(x)/\beta} e^{r/\beta} and the factor ef(x)/βe^{f(x)/\beta} cancels when you normalize over yy.

(The DPO paper states these two facts as its Lemmas 1 and 2.)

Each class corresponds to exactly one policy, and vice versa. Going from rewards to policies, each class maps to one optimal policy πr∝πrefer/β\pi_r \propto \pi_\text{ref} e^{r/\beta}, by the second bullet. Going back, take any policy π\pi that is positive wherever πref\pi_\text{ref} is. The reward rπ=βlog⁡ππrefr_\pi = \beta \log\frac{\pi}{\pi_\text{ref}} has Z(x)=∑yπref ππref=1Z(x) = \sum_y \pi_\text{ref}\,\frac{\pi}{\pi_\text{ref}} = 1, so its optimal policy is π\pi itself. And any reward whose optimal policy is π\pi satisfies r=βlog⁡ππref+βlog⁡Z(x)r = \beta\log\frac{\pi}{\pi_\text{ref}} + \beta\log Z(x), so it is in the class of rπr_\pi. Classes and policies are in one-to-one correspondence.

So the two problems are the same problem. RLHF solves max⁡r(BT log-likelihood of r)\max_r \text{(BT log-likelihood of } r) and then outputs πr\pi_r. DPO solves max⁡π(BT log-likelihood of rπ)\max_\pi \text{(BT log-likelihood of } r_\pi). Because the map between classes and policies is a bijection, and the likelihood depends only on the class, the DPO optimum is πr^\pi_{\hat r}, where r^\hat r is the maximum-likelihood reward. That is exactly what RLHF would return if its RL step found the exact optimum. (The DPO paper’s Theorem 1 states the representation result.)

Where the idealization breaks. In practice the reward model and the policy are different neural networks trained by different procedures on finite data. The Bradley–Terry maximum-likelihood solution is not unique on responses the data never mentions, and the two pipelines fill in that gap differently: PPO’s KL penalty is measured on responses the policy actually samples, while DPO’s loss says nothing at all about responses outside the pairs. “Equivalent in the limit” does not mean “equivalent in practice”. The section on what DPO gives up returns to this.

Why the pair must share a prompt

The cancellation in Step 2 is the whole trick, and it needs both responses to be answers to the same xx. Suppose you tried to compare y1y_1 for prompt x1x_1 with y2y_2 for prompt x2x_2. Then

r(x1,y1)−r(x2,y2)=βlog⁡π∗(y1∣x1)πref(y1∣x1)−βlog⁡π∗(y2∣x2)πref(y2∣x2)+βlog⁡Z(x1)Z(x2),r(x_1, y_1) - r(x_2, y_2) = \beta \log \frac{\pi^*(y_1\mid x_1)}{\pi_\text{ref}(y_1\mid x_1)} - \beta \log \frac{\pi^*(y_2\mid x_2)}{\pi_\text{ref}(y_2\mid x_2)} + \beta\log\frac{Z(x_1)}{Z(x_2)},

and the last term, a ratio of two intractable sums, refuses to go away. DPO can only learn from comparisons within a prompt. That matches how preference data is collected anyway: annotators see one prompt and two answers.

A worked example of the loss

Take β=0.1\beta = 0.1 and one pair with these sequence log-probs:

log⁡πθ\log \pi_\thetalog⁡πref\log \pi_\text{ref}log-ratioimplicit reward r^=β×\hat r = \beta \times log-ratio
chosen ywy_w−12.0-12.0−13.0-13.0+1.0+1.0+0.1+0.1
rejected yly_l−15.0-15.0−14.0-14.0−1.0-1.0−0.1-0.1

The policy has made the chosen response e1≈2.7e^{1} \approx 2.7 times more likely than the reference does, and the rejected one ee times less likely. The implicit reward margin is r^w−r^l=0.2\hat r_w - \hat r_l = 0.2, the implicit reward model says P(yw≻yl)=σ(0.2)=0.550P(y_w \succ y_l) = \sigma(0.2) = 0.550, and the loss is −log⁡σ(0.2)=log⁡(1+e−0.2)=0.598-\log\sigma(0.2) = \log(1 + e^{-0.2}) = 0.598.

Two numbers to remember. At the start of training πθ=πref\pi_\theta = \pi_\text{ref}, every log-ratio is 0, every margin is 0, and the loss is log⁡2=0.693\log 2 = 0.693 for every pair. Any other value at step 0 means a bug. And notice that the raw log-probs (−12-12, −15-15) are large and negative, as they are for any real response of a few dozen tokens, but only the differences from the reference matter.

Quick check At the very first DPO step (policy initialized to the reference), what is the DPO loss on every pair, and what is the implicit reward of every response?

What the gradient does

The DPO loss looks like a classification loss. To see what it does to the policy, differentiate it. Write u=r^θ(x,yw)−r^θ(x,yl)u = \hat r_\theta(x, y_w) - \hat r_\theta(x, y_l) for the margin. Since ddu[−log⁡σ(u)]=−(1−σ(u))=−σ(−u)\frac{d}{du}\big[-\log\sigma(u)\big] = -(1 - \sigma(u)) = -\sigma(-u) and ∇θu=β(∇θlog⁡πθ(yw∣x)−∇θlog⁡πθ(yl∣x))\nabla_\theta u = \beta\big(\nabla_\theta \log\pi_\theta(y_w\mid x) - \nabla_\theta \log\pi_\theta(y_l\mid x)\big) (the reference terms are constants),

∇θLDPO  =  − β  E[σ(r^θ(x,yl)−r^θ(x,yw))⏟weight: how wrong is the implicit RM?(∇θlog⁡πθ(yw∣x)⏟raise the winner  −  ∇θlog⁡πθ(yl∣x)⏟lower the loser)].\nabla_\theta \mathcal{L}_\text{DPO} \;=\; -\,\beta\; \mathbb{E}\Big[\underbrace{\sigma\big(\hat r_\theta(x, y_l) - \hat r_\theta(x, y_w)\big)}_{\text{weight: how wrong is the implicit RM?}} \Big(\underbrace{\nabla_\theta \log \pi_\theta(y_w\mid x)}_{\text{raise the winner}} \;-\; \underbrace{\nabla_\theta \log \pi_\theta(y_l\mid x)}_{\text{lower the loser}}\Big)\Big].

Gradient descent on the loss moves θ\theta along the negative of this, so each pair does three things:

  1. Raise the winner. +∇log⁡πθ(yw∣x)+\nabla\log\pi_\theta(y_w\mid x) is the supervised fine-tuning gradient on ywy_w.
  2. Lower the loser. −∇log⁡πθ(yl∣x)-\nabla\log\pi_\theta(y_l\mid x) pushes the rejected response down. This “negative gradient” is something SFT can’t do: SFT only ever learns from good examples.
  3. Weight by surprise. The factor σ(r^l−r^w)\sigma(\hat r_l - \hat r_w) is the probability the implicit reward model assigns to the wrong ordering. Pairs it already ranks confidently get almost no weight; pairs it gets wrong get almost full weight.

Here is the weight as the margin grows:

implicit margin u=r^w−r^lu = \hat r_w - \hat r_l−2-2−1-100112244
loss −log⁡σ(u)-\log\sigma(u)2.1271.3130.6930.3130.1270.018
weight σ(−u)\sigma(-u)0.8810.7310.5000.2690.1190.018

The weight is what keeps DPO from running away. Without it, “push the winner up and the loser down with equal force forever” has no stopping point. The DPO paper reports that a naive version without the weighting coefficient can make the language model degenerate. With it, each pair contributes less and less once the implicit reward model is confident about it. (Less and less, but never zero: with labels that never disagree, the push fades without stopping, which is the problem the section on deterministic preferences takes up.)

Quick check Two pairs in a batch: for pair 1 the implicit reward margin is +3 (ranked confidently right), for pair 2 it is −1 (ranked wrong). Roughly how do their gradient weights compare?

The algorithm in practice

DPO
input: preference pairs D = {(x, y_w, y_l)}, SFT model π_SFT, β (e.g. 0.1)
1. π_ref ← copy of π_SFT, frozen;   π_θ ← π_SFT, trainable
2. (optional) precompute log π_ref(y_w|x) and log π_ref(y_l|x) for every pair
3. for each minibatch of pairs:
4.     lw ← Σ_t log π_θ(y_w,t | x, y_w,<t)          # masked sum over response tokens
5.     ll ← Σ_t log π_θ(y_l,t | x, y_l,<t)
6.     u  ← β·[(lw − log π_ref(y_w|x)) − (ll − log π_ref(y_l|x))]
7.     loss ← mean(−log σ(u))                         # use a stable log-sigmoid
8.     gradient step on loss
9.     log: reward accuracy mean(u > 0), mean margin, mean lw and ll

Some practical points, all of which you will meet in the lab:

  • The reference is the SFT model. DPO assumes πref\pi_\text{ref} is a reasonable model of the distribution the preference data came from. The DPO paper recommends, when no SFT model is available, first fine-tuning on the preferred responses to get one.
  • Masking. Prompt tokens and padding are excluded from the sums, exactly as in Chapter 11. Llama 3’s DPO also masked out special formatting tokens (headers and end-of-turn tokens) that appear in both responses.
  • Hyperparameters. β\beta around 0.1 is the common default; Llama 3 reports β=0.1\beta = 0.1 with learning rate 10−510^{-5}. Learning rates are small and training is short, usually one to a few epochs over the pairs, because DPO overfits (more below).
  • What to watch. The reward accuracy (fraction of pairs with r^w>r^l\hat r_w > \hat r_l) and the margin tell you whether the implicit reward model is learning. The chosen and rejected log-probs, log⁡πθ(yw∣x)\log\pi_\theta(y_w\mid x) and log⁡πθ(yl∣x)\log\pi_\theta(y_l\mid x), tell you how it is learning. You would hope the chosen one goes up. Often it doesn’t.

Here is how this compares with the pipeline of Chapter 12:

RLHF with PPO (Chapter 12)DPO
Stages after SFTtrain a reward model, then run RLone training run
Networks in memorypolicy, reference, reward model, value functionpolicy and reference (reference log-probs can be precomputed)
Generation during trainingevery step: sample responses, score themnone
Datapreference pairs (for the RM) plus prompts (for RL)preference pairs only
Where the KL leash actsexplicit penalty, on responses the policy samplesbuilt into the loss through the derivation
Learns from its own outputs?yes: on-policyno: offline
Typical failurethe policy exploits reward-model errorsoverfitting the pairs, likelihood displacement, drift on unseen responses

DPO is cheaper and simpler. The last two rows are the price.

Watch DPO train

The demo below is a whole “language model” for a single prompt with a handful of possible responses, small enough to see everything. Each scenario fixes πref\pi_\text{ref}, a hidden true reward rr (used only to draw the RLHF target π∗\pi^*, the thick horizontal ticks on the bars), and a preference dataset. A pair that annotators label "yi≻yjy_i \succ y_j" with probability pp contributes its average loss, pp times the loss with yiy_i as winner plus 1−p1-p times the loss with yjy_j as winner. The demo minimizes this with Adam on all pairs at once (no sampling), so the curves are smooth and repeatable. The readout below the table shows the step, the loss, the mean implicit-reward margin on the pairs, and two KL divergences: how far πθ\pi_\theta has moved from πref\pi_\text{ref}, and how far it still is from π∗\pi^*.

In scenarios 1 and 2 the policy is tabular: one free logit per response. In scenario 3 the four responses are described by 2-dimensional feature vectors and the policy is πθ(y)∝πref(y) eϕ(y)⋅θ\pi_\theta(y) \propto \pi_\text{ref}(y)\,e^{\phi(y)\cdot\theta}. That is a cartoon of a real network, where similar responses have similar internal representations and therefore move together.

Interactive DPO on a tiny enumerable language model
Policy over responses

πref  πθ (trained)  π* (RLHF optimum)

log πθ(y) vs. training step

solid: log πθ(y)   dashed: log π*(y)

responsein the datatrue rπrefπθπ*implicit reward β·log(πθ/πref)

What to try: (1) Scenario 1, DPO, β = 1: press Train. π_θ converges onto the π* ticks (the thick horizontal lines), (0.179, 0.292, 0.529) as in the worked example, the implicit rewards become (−1.027, −0.027, 0.973), and KL(π_θ ‖ π*) goes to 0. Change β to 0.3 and train again: π* changes, but the implicit rewards still differ by exactly 1 and 2, the true reward gaps. (2) Scenario 2: response B is the winner of one pair, yet its log-probability falls (the curve labeled B). D, the best response, appears in no pair and is never learned. The margin grows without limit, and the final policy is the same for β = 0.1 and β = 1. Switch the loss to IPO: the margin stops at 0.5. (3) Scenario 3: the data says only 'No.' ≻ 'Never.', yet 'Yes.' takes over and 'No.' first rises, then collapses. Switch to DPO + NLL and train again.

Scenario 1 confirms the derivation: when every pair is labeled according to Bradley–Terry with the true reward (think: infinitely many annotators per pair), DPO’s minimizer is exactly the RLHF optimum π∗\pi^*, without ever seeing the reward or ZZ. Scenarios 2 and 3 are what happens with realistic data, and they lead straight to the next section.

What DPO gives up

It’s offline

DPO trains on a fixed dataset of pairs that some other policy generated (often a mixture of older models, or the SFT model before training). It never samples from πθ\pi_\theta, so it never finds out what πθ\pi_\theta actually does. This is Chapter 10’s offline RL problem in a new form.

Look at what the loss constrains. It involves πθ\pi_\theta only through the log-probabilities of the responses in the pairs. Every other response, which is nearly all of them, is unconstrained, except that probabilities must sum to one. If raising ywy_w relative to yly_l happens to also raise some response y′y' that appears nowhere in the data, the loss doesn’t notice, and nothing in DPO will ever sample y′y' to find out it’s bad.

Xu et al. (2024) make this precise. They prove that every policy PPO-based RLHF can produce also minimizes the DPO loss, but not the reverse: DPO’s set of solutions is strictly larger. Their toy example has three responses with πref=(0.5,0.5,0)\pi_\text{ref} = (0.5, 0.5, 0) and one preference, y1≻y2y_1 \succ y_2. The policy (0.1,0,0.9)(0.1, 0, 0.9) minimizes the DPO loss (the loss only needs π(y2)=0\pi(y_2) = 0) while putting 90% of its mass on y3y_3, a response the reference never produces and no annotator ever saw. A KL-penalized RL policy can’t do this, because y3y_3 would have infinite KL from the reference. Scenario 2 in the demo shows the milder version: the best response D gets nothing, because nobody ever compared it with anything.

PPO-based RLHF has the opposite profile. It samples from the current policy, so it finds out what the policy does, and the reward model judges those very samples. Its weakness is that the reward model may be wrong about them (reward hacking, Chapter 19). DPO trades “a wrong judge of new samples” for “no judge of new samples”.

Deterministic preferences: the leash goes slack

In the derivation, β\beta is the strength of the KL leash: large β\beta keeps πθ\pi_\theta near πref\pi_\text{ref}. But look at what the loss does with a pair whose label is always the same. If a fraction pp of annotators prefer ywy_w, the expected loss on that pair, as a function of the margin uu, is −plog⁡σ(u)−(1−p)log⁡σ(−u)-p\log\sigma(u) - (1-p)\log\sigma(-u). It is minimized where σ(u)=p\sigma(u) = p, at

u∗=log⁡p1−p.u^* = \log\frac{p}{1-p}.

(The second term is there because a fraction 1−p1-p of the time the label is flipped, and then the margin enters the loss with the opposite sign.) With p=0.9p = 0.9 that’s a finite margin, u∗=ln⁡9=2.2u^* = \ln 9 = 2.2. With p=1p = 1 there is no minimum: the loss keeps decreasing as u→∞u \to \infty. Since πθ(yw∣x)≤1\pi_\theta(y_w\mid x) \le 1, the chosen log-ratio can never exceed log⁡1πref(yw∣x)\log\frac{1}{\pi_\text{ref}(y_w\mid x)}, so the only way to make uu infinite is πθ(yl∣x)→0\pi_\theta(y_l\mid x) \to 0: the rejected response is driven out completely. Whatever β\beta is, the optimizer drives the log-ratios to infinity. β\beta only sets the speed, not the destination, and the KL regularization that the derivation promised has no effect.

And p=1p = 1 is the normal case, not an edge case. In a real dataset each pair is labeled once, so the empirical preference probability of every pair is exactly 1, even when the true probability is 0.6. Azar et al. (2023) used this argument to motivate IPO (identity preference optimization), which replaces the log-sigmoid with a squared loss that has a finite target. Scenario 2 in the demo shows both behaviors: DPO’s margin grows without limit, while IPO’s stops at a fixed value.

In practice the damage is limited by early stopping: DPO is trained for one or a few epochs with a small learning rate, so it never gets close to the infinite optimum. That works, but it means the real regularizer is the training schedule, not β\beta.

Likelihood displacement: the chosen response can go down

The DPO loss depends on the difference of two log-ratios. Nothing in it says log⁡πθ(yw∣x)\log\pi_\theta(y_w\mid x) has to go up. If pushing yly_l down is “cheaper” than pushing ywy_w up, the optimizer can widen the margin while both log-probabilities fall, as long as yly_l falls faster. The probability mass has to go somewhere, and it goes to responses outside the pair.

This is observed in real training runs, not only in toys. Pal et al. (2024) reported that DPO can lower the likelihood of preferred responses, especially when the two responses in a pair differ by only a few tokens. Razin et al. (2025) studied it under the name likelihood displacement. Their examples are striking. Training a model to prefer “No” over “Never” sharply raised the probability of “Yes”. In a safety setting, DPO on refusal data lowered Llama-3-8B-Instruct’s refusal rate from 74.4% to 33.4%. They trace the effect to pairs whose two responses have very similar hidden representations.

Why similarity matters is easy to see in the demo’s feature model. With πθ(y)∝πref(y)eϕ(y)⋅θ\pi_\theta(y) \propto \pi_\text{ref}(y)e^{\phi(y)\cdot\theta} and one pair, the gradient of the margin is

∇θ[log⁡πθ(yw)−log⁡πθ(yl)]=ϕ(yw)−ϕ(yl),\nabla_\theta\big[\log\pi_\theta(y_w) - \log\pi_\theta(y_l)\big] = \phi(y_w) - \phi(y_l),

because the normalizer’s gradient cancels in the difference. So θ\theta moves along d=ϕ(yw)−ϕ(yl)d = \phi(y_w) - \phi(y_l). When ywy_w and yly_l are nearly identical (“No.” and “Never.”), dd is a short vector that encodes only the small way they differ, and it can point anywhere, including toward a response with the opposite meaning. Each response’s logit changes by ϕ(y)⋅d\phi(y)\cdot d per unit step. If “Yes.” has a larger ϕ⋅d\phi\cdot d than “No.” does, “Yes.” grows fastest and eventually takes mass from everything, including the “chosen” “No.”. That’s scenario 3. A real network’s representations aren’t 2-D, but the mechanism (the update direction is a difference of two similar representations) is the one Razin et al. describe.

You’ll see the same thing in the lab with a real (tiny) transformer. On correct-versus-wrong arithmetic answers, plain DPO with β=0.1\beta = 0.1 separates chosen from rejected on more than 90% of training pairs, while the held-out log-probability of the correct answers falls from −0.67-0.67 to about −2.5-2.5 and the model gets fewer problems right than before training. The fixes are simple:

  • Add a likelihood term on the chosen response. L=LDPO−α 1∣yw∣log⁡πθ(yw∣x)\mathcal{L} = \mathcal{L}_\text{DPO} - \alpha\,\frac{1}{\lvert y_w\rvert}\log\pi_\theta(y_w\mid x). Llama 3 used this with α=0.2\alpha = 0.2. Pang et al. (2024), training reasoning with iterated DPO on correct versus incorrect chains of thought, found the NLL term crucial.
  • Penalize any drop of the chosen log-ratio below zero (DPOP, the “DPO-Positive” loss of Pal et al.).
  • Clean the data: Razin et al. filter out pairs whose responses are too similar.
  • Sample from the policy (online DPO, below), so the mass that leaks to unexpected responses gets noticed and pushed back.

Quick check During DPO training you see reward accuracy rise to 95% and the margin grow, while the average log π_θ(chosen) falls steadily. What is the best reading?

Length and other shortcuts

Because the implicit reward is a sum of per-token log-ratios, DPO can be influenced by response length. Preference datasets often favor longer answers (annotators and LLM judges have a verbosity bias, Chapter 14), and Park et al. (2024) found that DPO strongly exploits this, producing longer responses without more quality. They tie it to the same out-of-distribution problem: DPO extrapolates the “longer is preferred” pattern beyond the data. Their fix adds a length regularizer. Length-normalized variants (SimPO, and the length-normalized DPO of Tülu 3, below) attack the same issue.

The variant family

DPO started a flood of “direct alignment” losses. They differ in four choices: what data they need (pairs, or single responses labeled good or bad), whether they need a reference model, how they normalize for length, and what shape of loss they put on the margin. Here are the ones you will see named in papers, in our notation, with hθ(x,y)=log⁡πθ(y∣x)πref(y∣x)h_\theta(x, y) = \log\frac{\pi_\theta(y\mid x)}{\pi_\text{ref}(y\mid x)} for the raw log-ratio.

MethodDataReference?Loss, per exampleMain idea
DPO (Rafailov et al. 2023)pairsyes−log⁡σ(βhθ(x,yw)−βhθ(x,yl))-\log\sigma\big(\beta h_\theta(x,y_w) - \beta h_\theta(x,y_l)\big)Bradley–Terry on the implicit reward
IPO (Azar et al. 2023)pairsyes(hθ(x,yw)−hθ(x,yl)−12β)2\big(h_\theta(x,y_w) - h_\theta(x,y_l) - \tfrac{1}{2\beta}\big)^2finite target margin, so deterministic labels can’t push it to infinity
KTO (Ethayarajh et al. 2024)single responses labeled desirable / undesirableyesλy−v(x,y)\lambda_y - v(x,y), see belowno pairs needed; loss shaped by prospect theory
ORPO (Hong et al. 2024)pairsno−log⁡pθ(yw)−λlog⁡σ(log⁡oddsθ(yw)oddsθ(yl))-\log p_\theta(y_w) - \lambda\log\sigma\Big(\log\frac{\text{odds}_\theta(y_w)}{\text{odds}_\theta(y_l)}\Big)SFT and preference learning in one stage
SimPO (Meng et al. 2024)pairsno−log⁡σ(β∣yw∣log⁡πθ(yw∣x)−β∣yl∣log⁡πθ(yl∣x)−m0)-\log\sigma\Big(\frac{\beta}{\lvert y_w\rvert}\log\pi_\theta(y_w\mid x) - \frac{\beta}{\lvert y_l\rvert}\log\pi_\theta(y_l\mid x) - m_0\Big)length-normalized reward, target margin m0m_0
DPO + NLL (Pang et al. 2024; used in Llama 3)pairsyesLDPO−α 1∣yw∣log⁡πθ(yw∣x)\mathcal{L}_\text{DPO} - \alpha\,\frac{1}{\lvert y_w\rvert}\log\pi_\theta(y_w\mid x)keep the chosen response likely
Online / iterative DPO (e.g. Guo et al. 2024)pairs sampled from the current policyyesDPOfresh on-policy data each round

A few words on each.

IPO. Azar et al. show that DPO and RLHF both rest on the Bradley–Terry assumption, which turns a preference probability pp into a reward difference through the logit function log⁡p1−p\log\frac{p}{1-p}. That function is infinite at p=1p = 1, and that’s the source of the infinite margins. IPO optimizes preference probabilities directly (their Ψ\Psi is the identity) and arrives at a squared loss that regresses the log-ratio margin to 1/(2β)1/(2\beta). With label probability pp the expected IPO loss is minimized at margin (2p−1)/(2β)(2p-1)/(2\beta): finite even at p=1p = 1. Notice that IPO’s β\beta (the paper writes τ\tau) is a different knob from DPO’s: the target is a margin in raw log-ratio units, and the optimum is not the RLHF π∗\pi^* (the demo’s scenario 1 with IPO shows this).

KTO. Pairs are expensive. Often you only have thumbs up or thumbs down on single responses. KTO (named for Kahneman and Tversky’s prospect theory, a model of how people value gains and losses relative to a reference point) works with that. With the implicit log-ratio hθ(x,y)h_\theta(x,y) and a reference point z0z_0 (an estimate of KL(πθ∥πref)\mathrm{KL}(\pi_\theta \Vert \pi_\text{ref}) computed from the batch and not backpropagated through), the “value” of a response is v=λD σ(β(hθ−z0))v = \lambda_D\,\sigma\big(\beta(h_\theta - z_0)\big) if it is desirable and v=λU σ(β(z0−hθ))v = \lambda_U\,\sigma\big(\beta(z_0 - h_\theta)\big) if not, and the loss is λy−v\lambda_y - v. A desirable response is pushed up until it beats the reference point, an undesirable one down until it is below it. The weights λD\lambda_D, λU\lambda_U (default 1) let you correct for unbalanced numbers of good and bad examples. The paper reports matching or exceeding pair-based methods from 1B to 30B parameters.

ORPO. It removes the reference model and the separate SFT stage. Training is SFT on ywy_w plus a penalty on the odds ratio, where pθ(y)p_\theta(y) is the per-token geometric mean probability exp⁡(1∣y∣∑tlog⁡πθ(yt∣x,y<t))\exp\big(\frac{1}{\lvert y\rvert}\sum_t\log\pi_\theta(y_t\mid x, y_{\lt t})\big) and oddsθ(y)=pθ(y)1−pθ(y)\text{odds}_\theta(y) = \frac{p_\theta(y)}{1-p_\theta(y)}. With no πref\pi_\text{ref} there is no explicit leash; the SFT term keeps the model anchored to the chosen responses. The paper used λ\lambda between 0.1 and 0.25 for its main models.

SimPO. The implicit reward is the average per-token log-probability, scaled by β\beta, with no reference model, and the loss asks the chosen to beat the rejected by a margin m0m_0 (the paper’s γ\gamma, renamed here because γ\gamma is our discount factor). The average removes the advantage long responses get from summing more tokens. The paper suggests β\beta around 2–2.5 and m0m_0 between 0.5 and 1.5, finds that removing the length normalization hurts most, and reports gains over DPO on AlpacaEval 2 and Arena-Hard. Tülu 3 used a related length-normalized DPO, which keeps the reference but divides each log-ratio by the response length (with β=5\beta = 5, since per-token log-ratios are small).

Which is best? Each paper reports wins on its own benchmarks, and independent comparisons disagree. In the Tülu 3 report, length-normalized DPO beat both standard DPO and SimPO on their evaluation suite. Treat the table as a menu of fixes for specific failure modes: IPO for overfitting to deterministic labels, KTO for unpaired data, ORPO and SimPO for dropping the reference model’s memory and compute, length normalization for verbosity, NLL for displacement.

Online and iterative DPO

Most of DPO’s problems come from one fact: the pairs were not sampled from the model being trained. The obvious fix is to sample them from it.

Online DPO (Guo et al. 2024, “Direct Language Model Alignment from Online AI Feedback”) samples two responses from the current policy for each prompt, asks an LLM annotator which is better, and takes a DPO step on that fresh pair. The paper reports that this beats offline DPO, IPO and SLiC (another pairwise loss, a hinge on the log-probability margin), and RLHF, in human evaluations. Iterative DPO does the same in a few large rounds instead of every step: train with DPO, sample new responses from the trained model, label them (with humans, a reward model, a judge, or a verifier), train again. Llama 3 ran several such rounds, re-collecting preferences on the latest model each time. Self-rewarding language models (Yuan et al. 2024) let the model judge its own samples between rounds. Iterative reasoning preference optimization (Pang et al. 2024) builds the pairs from correct and incorrect chains of thought checked against the known answer.

Online DPO is no longer offline RL, and it has stopped being “RL-free” in the sense that mattered: you now need a generation loop and a source of labels for new samples, which is most of the machinery DPO set out to remove. What remains different from PPO is the loss: a contrastive loss on pairs, with no value function and no explicit KL penalty.

DPO or PPO? The empirical picture

This is contested, and the honest answer is “it depends on the data, the tuning, and what you measure.” Here are the main data points, with what each one actually claims.

  • Xu et al. (2024), “Is DPO Superior to PPO for LLM Alignment?” Beyond the theorem above, they find that a carefully tuned PPO surpasses the other alignment methods they test in all their settings, from dialogue to competitive programming. They identify three things that made PPO work: advantage normalization, large batches, and an exponential moving average of the reference model.
  • Ivison et al. (2024), “Unpacking DPO and PPO”. A controlled comparison across many preference datasets. Their ranking of what matters: the quality of the preference data first, then the learning algorithm, then reward model quality, then extra unlabeled prompts. PPO beat DPO, by up to 2.5% in math and 1.2% in general domains, while better data was worth up to 8% on instruction following and truthfulness.
  • Llama 3 (Grattafiori et al. 2024). Meta’s post-training used SFT, rejection sampling and DPO over several rounds. The report says the team explored on-policy algorithms such as PPO but found that DPO needed less compute for large models and performed better, especially on instruction-following benchmarks like IFEval.
  • Tülu 3 (Lambert et al. 2024). AI2’s open recipe is SFT, then length-normalized DPO on largely on-policy preference pairs (responses from the SFT model and other models, judged by an LLM), then RL with verifiable rewards. In their controlled comparison, PPO came out comparable to DPO, slightly lower, at a much higher compute cost, so they kept DPO for preference tuning and used PPO-style RL for the verifiable-reward stage.
  • On-policy data matters more than the loss. Tajwar et al. (2024) argue that methods using on-policy samples or a “negative gradient” (pushing some responses down) do better than offline maximum-likelihood objectives, because they move probability mass between responses faster. Online DPO’s results (above) point the same way.

The pattern most practitioners take from this: with a fixed offline dataset and limited compute, DPO is a strong, cheap default. With the ability to sample from the policy and score the samples, on-policy methods tend to win, and online DPO closes much of the gap.

Where things stand in late 2026. DPO remains a standard step in open recipes: Olmo 3 still runs SFT, then DPO, then RL with verifiable rewards, building its preference pairs with the “delta learning” idea of Geng et al. (2025) (pair a stronger model’s response with a weaker model’s; what matters is the quality gap). Qwen2.5 used offline DPO on pairs built from execution feedback and answer matching before its online RL stage. But for reasoning, the center of gravity moved to on-policy RL with verifiable rewards and GRPO-style algorithms (Chapter 15). In a June 2026 Interconnects conversation, Nathan Lambert and Finbarr Timbers described DPO as largely disappearing from leading frontier recipes, while noting it can still be a compute-efficient choice and that the shift may owe something to fashion rather than careful ablations. No published study settles the question.

Quick check Which statement about DPO vs. PPO is best supported by the evidence above?

Summary

  • The trick: the KL-regularized optimum π∗∝πrefer/β\pi^* \propto \pi_\text{ref}e^{r/\beta} can be inverted, r=βlog⁡π∗πref+βlog⁡Z(x)r = \beta\log\frac{\pi^*}{\pi_\text{ref}} + \beta\log Z(x). In Bradley–Terry only reward differences within a prompt appear, so Z(x)Z(x) cancels.
  • The loss: LDPO=−E[log⁡σ(r^θ(x,yw)−r^θ(x,yl))]\mathcal{L}_\text{DPO} = -\mathbb{E}\big[\log\sigma(\hat r_\theta(x,y_w) - \hat r_\theta(x,y_l))\big] with the implicit reward r^θ=βlog⁡πθπref\hat r_\theta = \beta\log\frac{\pi_\theta}{\pi_\text{ref}}. It needs four sequence log-probs per pair and no sampling. At initialization it equals log⁡2\log 2.
  • The gradient raises the winner, lowers the loser, and weights each pair by σ(r^l−r^w)\sigma(\hat r_l - \hat r_w), the implicit reward model’s probability of getting it wrong.
  • In the ideal limit (all pairs, Bradley–Terry labels, an expressive model), DPO’s optimum is exactly the RLHF optimum. In practice it is not.
  • What it gives up: it is offline (no exploration; unseen responses are unconstrained); with deterministic labels the margin is pushed to infinity and β\beta stops acting as a leash (IPO’s motivation); and likelihood displacement can lower the chosen response’s probability and move mass to unrelated, sometimes opposite, responses.
  • Variants fix specific failures: IPO (finite target), KTO (unpaired labels), ORPO and SimPO (no reference model; SimPO length-normalizes), DPO + NLL (displacement), online/iterative DPO (on-policy data).
  • Empirically it’s contested: tuned PPO often wins in controlled studies, DPO is far cheaper and has been used by Llama 3, Tülu 3 and Olmo 3, and on-policy data matters as much as the choice of loss.

Exercises

Exercise 13.1What disappears, and what doesn'tConcept●○○

(a) List everything an RLHF-with-PPO run needs during training that a DPO run does not (models in memory, computation per step, data).

(b) DPO still needs a reference model. What role does it play, and could you drop it? Name a method that does.

(c) A colleague says: “DPO is RL without the RL.” In what sense is that right, and in what important sense is DPO not reinforcement learning as Chapter 1 defined it?

Solution

(a) PPO-based RLHF needs a reward model and a value function in memory (on top of the policy and the reference), a generation step every iteration (sample responses from the current policy, then score them with the reward model), per-token rewards with a KL penalty, GAE advantages, and the PPO clipped update over several epochs. It needs prompts for the RL stage in addition to the preference data used to train the reward model. DPO needs only the preference pairs, the policy, and the reference, and the reference’s log-probs can be computed once before training.

(b) The reference anchors the implicit reward: r^θ=βlog⁡πθπref\hat r_\theta = \beta\log\frac{\pi_\theta}{\pi_\text{ref}} measures how much the policy has changed a response’s probability, and the derivation’s KL leash is a leash to πref\pi_\text{ref}. Without it, the “reward” of a response would be its raw log-probability, which mostly reflects length and fluency rather than quality. You can drop it if you replace the anchor with something else: SimPO uses the length-normalized log-probability with a margin; ORPO adds an SFT term on the chosen response. Both save the memory and compute of the reference model, at the cost of the derivation’s guarantee.

(c) It is right that DPO optimizes, in the ideal limit, the same KL-regularized reward objective as RLHF; that’s the derivation. It is not RL in Chapter 1’s sense because the agent never acts. It never samples a response, never receives evaluative feedback on its own behavior, and its data does not depend on its policy. It is supervised learning on a fixed dataset with a cleverly chosen loss. That is exactly why it is offline, can’t explore, and can’t correct mistakes on responses the dataset doesn’t contain.

Exercise 13.2A DPO step by handPen & paper●○○

Take β=0.2\beta = 0.2 and a pair with log⁡πθ(yw∣x)=−8\log\pi_\theta(y_w\mid x) = -8, log⁡πref(yw∣x)=−9\log\pi_\text{ref}(y_w\mid x) = -9, log⁡πθ(yl∣x)=−10\log\pi_\theta(y_l\mid x) = -10, log⁡πref(yl∣x)=−9.5\log\pi_\text{ref}(y_l\mid x) = -9.5.

(a) Compute both implicit rewards and the margin. Does the implicit reward model rank the pair correctly, and with what probability?

(b) Compute the loss and the gradient weight σ(r^l−r^w)\sigma(\hat r_l - \hat r_w).

(c) Compute ∂L/∂log⁡πθ(yw∣x)\partial\mathcal{L}/\partial\log\pi_\theta(y_w\mid x) and ∂L/∂log⁡πθ(yl∣x)\partial\mathcal{L}/\partial\log\pi_\theta(y_l\mid x). Which way does a gradient-descent step move each log-prob?

Solution

(a) r^w=0.2 (−8−(−9))=0.2\hat r_w = 0.2\,(-8 - (-9)) = 0.2. r^l=0.2 (−10−(−9.5))=−0.1\hat r_l = 0.2\,(-10 - (-9.5)) = -0.1. Margin u=0.3u = 0.3. It ranks the pair correctly, with P(yw≻yl)=σ(0.3)=1/(1+e−0.3)=1/1.7408=0.574P(y_w\succ y_l) = \sigma(0.3) = 1/(1 + e^{-0.3}) = 1/1.7408 = 0.574: correct, but not confident.

(b) Loss =−log⁡σ(0.3)=log⁡(1+e−0.3)=log⁡1.7408=0.554= -\log\sigma(0.3) = \log(1 + e^{-0.3}) = \log 1.7408 = 0.554. Weight σ(−0.3)=0.7408/1.7408=0.426\sigma(-0.3) = 0.7408/1.7408 = 0.426.

(c) L=−log⁡σ(u)\mathcal{L} = -\log\sigma(u) with u=β(log⁡πθ(yw)−log⁡πref(yw))−β(log⁡πθ(yl)−log⁡πref(yl))u = \beta(\log\pi_\theta(y_w) - \log\pi_\text{ref}(y_w)) - \beta(\log\pi_\theta(y_l) - \log\pi_\text{ref}(y_l)). So ∂L/∂log⁡πθ(yw)=−σ(−u) β=−0.426×0.2=−0.0851\partial\mathcal{L}/\partial\log\pi_\theta(y_w) = -\sigma(-u)\,\beta = -0.426 \times 0.2 = -0.0851, and ∂L/∂log⁡πθ(yl)=+0.0851\partial\mathcal{L}/\partial\log\pi_\theta(y_l) = +0.0851. Gradient descent moves opposite to the gradient: log⁡πθ(yw)\log\pi_\theta(y_w) goes up, log⁡πθ(yl)\log\pi_\theta(y_l) goes down, with equal force. (How the parameters change, and so what happens to other responses, depends on the network; see Exercise 13.4.)

Exercise 13.3The full DPO derivationPen & paper●●○

(a) Starting from the objective max⁡πEy∼π(⋅∣x)[r(x,y)]−β KL(π(⋅∣x)∥πref(⋅∣x))\max_\pi \mathbb{E}_{y\sim\pi(\cdot\mid x)}[r(x,y)] - \beta\,\mathrm{KL}(\pi(\cdot\mid x)\Vert\pi_\text{ref}(\cdot\mid x)) and its solution π∗(y∣x)=πref(y∣x)er(x,y)/β/Z(x)\pi^*(y\mid x) = \pi_\text{ref}(y\mid x)e^{r(x,y)/\beta}/Z(x) (take it as given from Chapter 10), derive the DPO loss. Show every step, and say exactly where you use the fact that the two responses share a prompt.

(b) Suppose a dataset also contained comparisons of the form “response y1y_1 to prompt x1x_1 is better than response y2y_2 to prompt x2x_2”. Write the Bradley–Terry probability of such a comparison in terms of π∗\pi^* and πref\pi_\text{ref}, and explain why DPO can’t use it.

(c) Bradley–Terry generalizes to rankings of KK responses (the Plackett–Luce model): the probability of the ranking y1≻y2≻⋯≻yKy_1 \succ y_2 \succ \dots \succ y_K is ∏k=1Ker(x,yk)∑j=kKer(x,yj)\prod_{k=1}^{K}\frac{e^{r(x,y_k)}}{\sum_{j=k}^{K}e^{r(x,y_j)}}. Show that Z(x)Z(x) also cancels here, and write the resulting loss.

Hint
In (a), take logs of the solution to isolate rr. In (c), substitute r=βlog⁡π∗πref+βlog⁡Z(x)r = \beta\log\frac{\pi^*}{\pi_\text{ref}} + \beta\log Z(x) into each factor and factor elog⁡Z(x)e^{\log Z(x)} out of the numerator and the denominator.
Solution

(a) Take the log of the solution: log⁡π∗(y∣x)=log⁡πref(y∣x)+r(x,y)/β−log⁡Z(x)\log\pi^*(y\mid x) = \log\pi_\text{ref}(y\mid x) + r(x,y)/\beta - \log Z(x). Multiply by β\beta and rearrange:

r(x,y)=βlog⁡π∗(y∣x)πref(y∣x)+βlog⁡Z(x).r(x,y) = \beta\log\frac{\pi^*(y\mid x)}{\pi_\text{ref}(y\mid x)} + \beta\log Z(x).

Bradley–Terry says P(yw≻yl∣x)=σ(r(x,yw)−r(x,yl))P(y_w\succ y_l\mid x) = \sigma(r(x,y_w) - r(x,y_l)). Substitute:

r(x,yw)−r(x,yl)=βlog⁡π∗(yw∣x)πref(yw∣x)−βlog⁡π∗(yl∣x)πref(yl∣x)+βlog⁡Z(x)−βlog⁡Z(x).r(x,y_w) - r(x,y_l) = \beta\log\frac{\pi^*(y_w\mid x)}{\pi_\text{ref}(y_w\mid x)} - \beta\log\frac{\pi^*(y_l\mid x)}{\pi_\text{ref}(y_l\mid x)} + \beta\log Z(x) - \beta\log Z(x).

Here we use the shared prompt: both log⁡Z\log Z terms are evaluated at the same xx, so they cancel. Now parameterize the policy, π∗→πθ\pi^* \to \pi_\theta, which makes r^θ=βlog⁡πθπref\hat r_\theta = \beta\log\frac{\pi_\theta}{\pi_\text{ref}} a reward model whose optimal policy is πθ\pi_\theta itself. The log-likelihood of the dataset under Bradley–Terry is ∑(x,yw,yl)log⁡σ(r^θ(x,yw)−r^θ(x,yl))\sum_{(x,y_w,y_l)}\log\sigma(\hat r_\theta(x,y_w) - \hat r_\theta(x,y_l)). Maximizing it is minimizing

LDPO(θ)=−E(x,yw,yl)∼D[log⁡σ(βlog⁡πθ(yw∣x)πref(yw∣x)−βlog⁡πθ(yl∣x)πref(yl∣x))].\mathcal{L}_\text{DPO}(\theta) = -\mathbb{E}_{(x,y_w,y_l)\sim\mathcal{D}}\Big[\log\sigma\Big(\beta\log\frac{\pi_\theta(y_w\mid x)}{\pi_\text{ref}(y_w\mid x)} - \beta\log\frac{\pi_\theta(y_l\mid x)}{\pi_\text{ref}(y_l\mid x)}\Big)\Big].

(b) P=σ(r(x1,y1)−r(x2,y2))=σ(βlog⁡π∗(y1∣x1)πref(y1∣x1)−βlog⁡π∗(y2∣x2)πref(y2∣x2)+βlog⁡Z(x1)Z(x2))P = \sigma\big(r(x_1,y_1) - r(x_2,y_2)\big) = \sigma\Big(\beta\log\frac{\pi^*(y_1\mid x_1)}{\pi_\text{ref}(y_1\mid x_1)} - \beta\log\frac{\pi^*(y_2\mid x_2)}{\pi_\text{ref}(y_2\mid x_2)} + \beta\log\frac{Z(x_1)}{Z(x_2)}\Big). The last term is a ratio of sums over all responses to two different prompts. It is not a function of anything you can compute from the policy’s log-probs on the two given responses, so the loss can’t be evaluated. (A separately trained reward model can in principle use cross-prompt comparisons, although Bradley–Terry rewards are only identified up to a per-prompt shift, so those comparisons carry information the within-prompt model doesn’t even represent.)

(c) Write r^k=βlog⁡π∗(yk∣x)πref(yk∣x)\hat r_k = \beta\log\frac{\pi^*(y_k\mid x)}{\pi_\text{ref}(y_k\mid x)} and r(x,yk)=r^k+cr(x,y_k) = \hat r_k + c, c=βlog⁡Z(x)c = \beta\log Z(x):

er(x,yk)∑j≥ker(x,yj)=ecer^kec∑j≥ker^j=er^k∑j≥ker^j.\frac{e^{r(x,y_k)}}{\sum_{j\ge k}e^{r(x,y_j)}} = \frac{e^{c}e^{\hat r_k}}{e^{c}\sum_{j\ge k}e^{\hat r_j}} = \frac{e^{\hat r_k}}{\sum_{j\ge k}e^{\hat r_j}}.

The common factor ece^c cancels in every term of the product because all KK responses share xx. The loss is −E[∑k=1K(r^θ(x,yk)−log⁡∑j=kKer^θ(x,yj))]-\mathbb{E}\Big[\sum_{k=1}^{K}\Big(\hat r_\theta(x,y_k) - \log\sum_{j=k}^{K}e^{\hat r_\theta(x,y_j)}\Big)\Big] with r^θ=βlog⁡πθπref\hat r_\theta = \beta\log\frac{\pi_\theta}{\pi_\text{ref}}. For K=2K = 2 this is the DPO loss, since r^1−log⁡(er^1+er^2)=log⁡σ(r^1−r^2)\hat r_1 - \log(e^{\hat r_1} + e^{\hat r_2}) = \log\sigma(\hat r_1 - \hat r_2) and the k=2k = 2 term is 00. (The DPO paper derives this Plackett–Luce version in its appendix.)

Exercise 13.4The gradient, down to the logitsPen & paper●●○

(a) Derive ∇θLDPO\nabla_\theta\mathcal{L}_\text{DPO} for one pair and show it equals −β σ(r^l−r^w)(∇θlog⁡πθ(yw∣x)−∇θlog⁡πθ(yl∣x))-\beta\,\sigma(\hat r_l - \hat r_w)\big(\nabla_\theta\log\pi_\theta(y_w\mid x) - \nabla_\theta\log\pi_\theta(y_l\mid x)\big).

(b) Now take a tabular policy over a finite set of responses (the demo’s scenarios 1 and 2): πθ(y)=softmax(z)y\pi_\theta(y) = \mathrm{softmax}(z)_y with one logit zyz_y per response, and πref\pi_\text{ref} fixed. Show that ∂L/∂z=−β σ(r^l−r^w) (ew−el)\partial\mathcal{L}/\partial z = -\beta\,\sigma(\hat r_l - \hat r_w)\,(e_w - e_l), where eye_y is the one-hot vector for response yy. Which logits move under gradient descent?

(c) In that tabular model with a single pair, show that a gradient step always increases πθ(yw)\pi_\theta(y_w), and that the ratio πθ(y)/πθ(y′)\pi_\theta(y)/\pi_\theta(y') of any two responses outside the pair doesn’t change. So in this model, displacement needs something more. What? (Exercise 13.7 and the demo’s scenario 3 give two answers.)

Hint
For (b), use ∇zlog⁡softmax(z)y=ey−π\nabla_z\log\mathrm{softmax}(z)_y = e_y - \pi. For (c), the step changes zwz_w by +δ+\delta and zlz_l by −δ-\delta for some δ>0\delta \gt 0; differentiate log⁡π(yw)\log\pi(y_w) with respect to δ\delta.
Solution

(a) Let u=r^θ(x,yw)−r^θ(x,yl)u = \hat r_\theta(x,y_w) - \hat r_\theta(x,y_l) and L=−log⁡σ(u)\mathcal{L} = -\log\sigma(u). Then dLdu=−σ′(u)σ(u)=−σ(u)(1−σ(u))σ(u)=−(1−σ(u))=−σ(−u)\frac{d\mathcal{L}}{du} = -\frac{\sigma'(u)}{\sigma(u)} = -\frac{\sigma(u)(1-\sigma(u))}{\sigma(u)} = -(1-\sigma(u)) = -\sigma(-u). The reference terms don’t depend on θ\theta, so ∇θu=β(∇θlog⁡πθ(yw∣x)−∇θlog⁡πθ(yl∣x))\nabla_\theta u = \beta\big(\nabla_\theta\log\pi_\theta(y_w\mid x) - \nabla_\theta\log\pi_\theta(y_l\mid x)\big). By the chain rule, ∇θL=−σ(−u) β (… )\nabla_\theta\mathcal{L} = -\sigma(-u)\,\beta\,(\dots), and σ(−u)=σ(r^l−r^w)\sigma(-u) = \sigma(\hat r_l - \hat r_w).

(b) ∇zlog⁡π(yw)−∇zlog⁡π(yl)=(ew−π)−(el−π)=ew−el\nabla_z\log\pi(y_w) - \nabla_z\log\pi(y_l) = (e_w - \pi) - (e_l - \pi) = e_w - e_l: the normalizer’s gradient π\pi cancels in the difference. So ∂L/∂z=−βσ(r^l−r^w)(ew−el)\partial\mathcal{L}/\partial z = -\beta\sigma(\hat r_l - \hat r_w)(e_w - e_l). Only two logits move: zwz_w up and zlz_l down, by equal amounts. All other logits stay put.

(c) After the step, zw→zw+δz_w \to z_w + \delta, zl→zl−δz_l \to z_l - \delta with δ>0\delta \gt 0. Then log⁡π(yw)=zw+δ−log⁡(ezw+δ+ezl−δ+∑y≠w,lezy)\log\pi(y_w) = z_w + \delta - \log\big(e^{z_w+\delta} + e^{z_l-\delta} + \sum_{y\ne w,l}e^{z_y}\big), and

dlog⁡π(yw)dδ=1−(π(yw)−π(yl))>0,\frac{d\log\pi(y_w)}{d\delta} = 1 - \big(\pi(y_w) - \pi(y_l)\big) \gt 0,

since π(yw)−π(yl)<1\pi(y_w) - \pi(y_l) \lt 1. So π(yw)\pi(y_w) always rises. For y,y′y, y' outside the pair, π(y)/π(y′)=ezy−zy′\pi(y)/\pi(y') = e^{z_y - z_{y'}}, and neither logit moves, so the ratio is unchanged (both probabilities shrink by the same factor as ywy_w grows). Displacement needs either several pairs that share responses, so one response is pushed up by one pair and down by another (Exercise 13.7, demo scenario 2), or shared parameters, so moving one response’s logit moves others (demo scenario 3, a real network).

Exercise 13.5Deterministic preferences push the margin to infinityPen & paper●●●

Fix one pair (x,yw,yl)(x, y_w, y_l) and let pp be the fraction of annotators who prefer ywy_w. Write Δ=hθ(x,yw)−hθ(x,yl)\Delta = h_\theta(x,y_w) - h_\theta(x,y_l) for the raw log-ratio margin, where hθ=log⁡πθπrefh_\theta = \log\frac{\pi_\theta}{\pi_\text{ref}}.

(a) Write the expected DPO loss on this pair as a function of Δ\Delta and find its minimizer. What happens as p→1p \to 1? Does β\beta stop this?

(b) If the labels come from Bradley–Terry with true reward rr, so p=σ(r(x,yw)−r(x,yl))p = \sigma(r(x,y_w) - r(x,y_l)), show the minimizer satisfies βΔ=r(x,yw)−r(x,yl)\beta\Delta = r(x,y_w) - r(x,y_l). What does that say about the policy DPO converges to when every pair of responses is labeled this way (demo scenario 1)?

(c) The expected IPO loss is p (Δ−12β)2+(1−p)(−Δ−12β)2p\,\big(\Delta - \tfrac{1}{2\beta}\big)^2 + (1-p)\big(-\Delta - \tfrac{1}{2\beta}\big)^2. Find its minimizer and evaluate it at p=1p = 1.

(d) A real dataset labels each pair once. Explain why (a) is the relevant case, even when annotators disagree a lot.

Hint
Write u=βΔu = \beta\Delta. Use ddulog⁡σ(u)=σ(−u)\frac{d}{du}\log\sigma(u) = \sigma(-u) and ddulog⁡σ(−u)=−σ(u)\frac{d}{du}\log\sigma(-u) = -\sigma(u). For (b), think about which policies have βhθ(y)=r(y)+const\beta h_\theta(y) = r(y) + \text{const}.
Solution

(a) With u=βΔu = \beta\Delta: ℓ(u)=−plog⁡σ(u)−(1−p)log⁡σ(−u)\ell(u) = -p\log\sigma(u) - (1-p)\log\sigma(-u). Then ℓ′(u)=−p σ(−u)+(1−p) σ(u)=−p(1−σ(u))+(1−p)σ(u)=σ(u)−p\ell'(u) = -p\,\sigma(-u) + (1-p)\,\sigma(u) = -p(1 - \sigma(u)) + (1-p)\sigma(u) = \sigma(u) - p. It vanishes at σ(u)=p\sigma(u) = p, i.e. u∗=log⁡p1−pu^* = \log\frac{p}{1-p}, and ℓ′′=σ(u)(1−σ(u))>0\ell'' = \sigma(u)(1-\sigma(u)) \gt 0, so this is the minimum. So Δ∗=1βlog⁡p1−p\Delta^* = \frac{1}{\beta}\log\frac{p}{1-p}. As p→1p \to 1, u∗→∞u^* \to \infty. At p=1p = 1, ℓ′(u)=σ(u)−1<0\ell'(u) = \sigma(u) - 1 \lt 0 for every uu: the loss decreases forever and has no minimizer. β\beta doesn’t help: for any β\beta, Δ\Delta must go to infinity. A larger β\beta makes the loss saturate sooner in Δ\Delta, but the infimum is still only approached as Δ→∞\Delta \to \infty. Because πθ(yw)≤1\pi_\theta(y_w) \le 1, the chosen log-ratio is capped at −log⁡πref(yw)-\log\pi_\text{ref}(y_w), so Δ→∞\Delta \to \infty forces πθ(yl)→0\pi_\theta(y_l) \to 0.

(b) With p=σ(Δr)p = \sigma(\Delta r), where Δr=r(x,yw)−r(x,yl)\Delta r = r(x,y_w) - r(x,y_l), the minimizer is u∗=log⁡σ(Δr)1−σ(Δr)=log⁡σ(Δr)σ(−Δr)=log⁡eΔr=Δru^* = \log\frac{\sigma(\Delta r)}{1-\sigma(\Delta r)} = \log\frac{\sigma(\Delta r)}{\sigma(-\Delta r)} = \log e^{\Delta r} = \Delta r. So βΔ∗=Δr\beta\Delta^* = \Delta r. If this holds for every pair of responses, then βhθ(y)−r(y)\beta h_\theta(y) - r(y) is the same constant for all yy, i.e. πθ(y)∝πref(y)er(y)/β\pi_\theta(y) \propto \pi_\text{ref}(y)e^{r(y)/\beta}: the policy is the RLHF optimum π∗\pi^*. (In a tabular model all pairwise conditions can be met at once, and that’s what the demo’s scenario 1 shows.)

(c) ddΔ\frac{d}{d\Delta}: 2p(Δ−c)−2(1−p)(−Δ−c)=2Δ−2c(2p−1)2p(\Delta - c) - 2(1-p)(-\Delta - c) = 2\Delta - 2c(2p - 1) with c=12βc = \frac{1}{2\beta}. Setting it to zero gives Δ∗=2p−12β\Delta^* = \frac{2p - 1}{2\beta}, a finite value for every pp (the loss is a convex quadratic). At p=1p = 1, Δ∗=12β\Delta^* = \frac{1}{2\beta}: the larger β\beta, the smaller the target margin, so β\beta acts as a leash again. In the demo’s implicit-reward units, βΔ∗=12\beta\Delta^* = \frac12, the value where IPO’s margin stops.

(d) With one label per pair, the empirical pp of every pair is exactly 1 (or 0). Minimizing the empirical loss is minimizing a sum of p=1p = 1 terms, each of which wants an infinite margin, whatever the true annotator agreement was. Only early stopping, a small learning rate, and the model’s limited capacity keep the margins finite. This is Azar et al.’s argument for IPO.

Exercise 13.6The two limits of βPen & paper●●○

(a) For fixed θ\theta, expand the DPO loss of one pair to first order in β\beta around β=0\beta = 0. What does the gradient become, and why might training on it for a long time be dangerous? (The DPO paper reports what happens.)

(b) As β→∞\beta \to \infty, what happens to the gradient weight σ(r^l−r^w)\sigma(\hat r_l - \hat r_w) once the policy has moved even slightly in the right direction, and what policy does training end at?

(c) Connect both answers to the optimum π∗∝πrefer/β\pi^* \propto \pi_\text{ref}e^{r/\beta}: which policy does DPO target in each limit?

Hint
Write the loss as −log⁡σ(βΔ)-\log\sigma(\beta\Delta) with Δ\Delta the raw log-ratio margin, and Taylor-expand log⁡(1+e−u)\log(1 + e^{-u}) around u=0u = 0. For (b), the weight is σ(−βΔ)\sigma(-\beta\Delta): what does it do for a fixed small Δ>0\Delta \gt 0 as β\beta grows?
Solution

(a) With u=βΔu = \beta\Delta and −log⁡σ(u)=log⁡(1+e−u)=log⁡2−u2+O(u2)-\log\sigma(u) = \log(1 + e^{-u}) = \log 2 - \frac{u}{2} + O(u^2), the loss is log⁡2−β2Δ+O(β2)\log 2 - \frac{\beta}{2}\Delta + O(\beta^2). Its gradient is −β2(∇log⁡πθ(yw)−∇log⁡πθ(yl))-\frac{\beta}{2}\big(\nabla\log\pi_\theta(y_w) - \nabla\log\pi_\theta(y_l)\big): every pair gets the same weight 12\frac12, forever, regardless of how well the pair is already ranked. This is the “naive” objective (raise the winner, lower the loser, with no stopping point) that the DPO paper reports can make the model degenerate: the log-probability of the loser can be pushed toward −∞-\infty, dragging shared tokens and probability mass with it.

(b) The weight is σ(−βΔ)\sigma(-\beta\Delta). For any fixed Δ>0\Delta \gt 0, as β→∞\beta\to\infty this goes to 00. So as soon as the policy ranks a pair correctly by any tiny log-ratio margin, the pair stops contributing. Training ends with the policy almost exactly at πref\pi_\text{ref}, just nudged enough to get the orderings right.

(c) In the target π∗∝πrefer/β\pi^* \propto \pi_\text{ref}e^{r/\beta}: β→∞\beta\to\infty gives π∗→πref\pi^*\to\pi_\text{ref} (the leash is infinitely tight), matching (b). β→0\beta\to 0 gives π∗\pi^* concentrated on the highest-reward response (no leash), which requires infinite log-ratios, matching the unbounded push in (a). In both limits, the loss’s behavior and the target’s behavior agree.

Exercise 13.7Likelihood displacement with two pairsPen & paper●●○

A tabular policy over three responses A, B, C starts at the uniform reference, πref=(13,13,13)\pi_\text{ref} = (\frac13, \frac13, \frac13), with logits z=(0,0,0)z = (0,0,0). The dataset has two pairs, each labeled once: B ≻ A and C ≻ B. B is the chosen response in the first pair.

(a) Using Exercise 13.4(b), write the gradient of the total loss (the mean over the two pairs) with respect to zz at the start. Which logits move?

(b) Argue that throughout gradient descent the two margins stay equal, so z=(−δ,0,δ)z = (-\delta, 0, \delta) for some growing δ≥0\delta \ge 0. Write log⁡πθ(B)\log\pi_\theta(B) as a function of δ\delta and evaluate it at δ=0,1,2\delta = 0, 1, 2.

(c) Training reports 100% reward accuracy and growing margins. What happened to the “chosen” response B, and where did its probability go?

Hint
Because πref\pi_\text{ref} is uniform, each log-ratio margin is just a difference of logits, e.g. zB−zAz_B - z_A. Pair 1 pushes zBz_B up and pair 2 pushes it down; when are the two pushes equal? For (b), πθ(B)=ezB/∑yezy\pi_\theta(B) = e^{z_B}/\sum_y e^{z_y}.
Solution

(a) Both margins are 0 at the start, so both weights are βσ(0)=β/2\beta\sigma(0) = \beta/2. The gradient of the mean loss is −12⋅β2[(eB−eA)+(eC−eB)]=−β4(eC−eA)-\frac12\cdot\frac{\beta}{2}\big[(e_B - e_A) + (e_C - e_B)\big] = -\frac{\beta}{4}(e_C - e_A). Gradient descent raises zCz_C, lowers zAz_A by the same amount, and leaves zBz_B unchanged: the push up from pair 1 and the push down from pair 2 cancel.

(b) Suppose z=(−δ,0,δ)z = (-\delta, 0, \delta). The two margins are β(zB−zA)=βδ\beta(z_B - z_A) = \beta\delta and β(zC−zB)=βδ\beta(z_C - z_B) = \beta\delta, equal, so the two weights are equal, and by the same calculation as in (a) the gradient is again proportional to eC−eAe_C - e_A. So the form (−δ,0,δ)(-\delta, 0, \delta) is preserved, with δ\delta increasing. Then

log⁡πθ(B)=0−log⁡(e−δ+1+eδ)=−log⁡(1+2cosh⁡δ).\log\pi_\theta(B) = 0 - \log\big(e^{-\delta} + 1 + e^{\delta}\big) = -\log(1 + 2\cosh\delta).

At δ=0\delta = 0: −log⁡3=−1.099-\log 3 = -1.099. At δ=1\delta = 1: −log⁡(1+3.086)=−1.408-\log(1 + 3.086) = -1.408. At δ=2\delta = 2: −log⁡(1+7.524)=−2.143-\log(1 + 7.524) = -2.143. It decreases monotonically in δ\delta.

(c) Both pairs are ranked correctly, with growing margins, yet B, the winner of the first pair, falls from 13\frac13 to 0.1170.117 at δ=2\delta = 2, and on toward 0. Its probability went to C (and A’s too): π(C)=e2/8.524=0.867\pi(C) = e^{2}/8.524 = 0.867 at δ=2\delta = 2. A response can be “chosen” in the data and still lose probability, because the loss only sees margins. In this example the outcome is reasonable (C beat B, so C is the better answer). With shared parameters the mass can go somewhere unreasonable instead, which is scenario 3 in the demo.

Exercise 13.8Explore the demoExplore the demo●○○

(a) Scenario 1, DPO, β = 1. Train to the end. Check π_θ, the implicit rewards and the mean margin against the worked example in “The trick, with numbers”. Then set β = 0.3 and train again. What changes, and what stays the same?

(b) Scenario 2, DPO. Compare β = 0.1 and β = 1. Where does each end up? Then switch to IPO with β = 1 and compare with π*. Which response is never learned about, and why?

(c) Scenario 3, DPO, β = 1. Describe the curve of log π_θ(“No.”). Which response wins, and how does its true reward compare with the others’? Now try DPO + NLL, then IPO. Which one fixes the problem?

Solution

(a) At β = 1, π_θ converges to (0.179, 0.292, 0.529), exactly the π* ticks. The implicit rewards converge to (−1.027, −0.027, 0.973), which is r−βlog⁡Zr - \beta\log Z with βlog⁡Z=1.027\beta\log Z = 1.027, the table in the text. The mean margin over the three pairs converges to (1 + 1 + 2)/3 = 1.333, the mean true reward gap, and KL(π_θ ‖ π*) goes to 0. At β = 0.3, π* is much sharper (C gets most of the mass), and DPO follows it. But the implicit rewards still differ by 1 and 2, and the mean margin is still 1.333. DPO learns the reward differences, whatever β, and β only decides how strongly the policy acts on them.

(b) Both go to “all mass on C”, with B and D falling too. With deterministic labels, β changes the speed (how long the curves take) but not the destination, as Exercise 13.5 showed. The margin keeps growing. With IPO at β = 1 the margin stops at 0.5 and the policy stays close to the reference: about (0.25, 0.31, 0.34, 0.10). In both cases D, which has the highest true reward, is never learned about: it appears in no pair, so no gradient ever targets its logit, and it only loses probability through normalization. π* gives D the most mass. The data simply never asked about it: this is DPO being offline.

(c) log π_θ(“No.”) first rises for a few dozen steps, then falls steadily, while “Yes.” (true reward −3, by far the worst) rises to over 90% of the mass. DPO + NLL fixes it: “No.” goes toward probability 1, because the NLL term pulls θ toward the chosen response’s features while DPO separates it from “Never.”. IPO limits the damage because the margin target is finite, but at β = 1 “Yes.” still about doubles its probability (0.05 → 0.10): with a feature-based policy, any movement along the direction φ(No.) − φ(Never.) helps “Yes.”.

Exercise 13.9Lab, Tasks 1–3: the lossesCode●●○

In dpo.py, implement sequence_logprob (Task 1), implicit_reward and dpo_loss (Task 2), then ipo_loss and simpo_loss (Task 3). The tests check the worked example from this chapter (β=0.1\beta = 0.1, log-probs −12,−15,−13,−14-12, -15, -13, -14, loss 0.5980.598) and the gradient ∓β σ(r^l−r^w)\mp\beta\,\sigma(\hat r_l - \hat r_w), IPO’s zero at margin 1/(2β)1/(2\beta), and numerical stability at a margin of −500-500.

Hint
Multiply the per-token log-probs by the mask before summing. For the losses use torch.nn.functional.logsigmoid; torch.log(torch.sigmoid(u)) underflows to -inf for very negative u.
Solution

The reference solution (solutions/dpo.py) is a few lines per function:

def sequence_logprob(token_logp, mask, average=False):
    total = (token_logp * mask).sum(dim=-1)
    return total / mask.sum(dim=-1).clamp(min=1.0) if average else total

def implicit_reward(policy_logp, ref_logp, beta):
    return beta * (policy_logp - ref_logp)

def dpo_loss(pw, pl, rw, rl, beta):
    r_w, r_l = implicit_reward(pw, rw, beta), implicit_reward(pl, rl, beta)
    return -F.logsigmoid(r_w - r_l).mean(), r_w.detach(), r_l.detach()

def ipo_loss(pw, pl, rw, rl, beta):
    h = (pw - rw) - (pl - rl)
    return ((h - 1.0 / (2.0 * beta)) ** 2).mean()

def simpo_loss(avg_w, avg_l, beta, margin):
    return -F.logsigmoid(beta * avg_w - beta * avg_l - margin).mean()

Key points: the mask multiplication comes before the sum (padding positions can hold anything); IPO’s hh has no β\beta in front, while its target does; F.logsigmoid is computed stably as min⁡(u,0)−log⁡(1+e−∣u∣)\min(u,0) - \log(1 + e^{-\lvert u\rvert}); and the implicit rewards are returned detached because they are for logging only.

Exercise 13.10Lab, Task 4 and the experiment: when DPO makes the model worseCode●●○

Implement dpo_step (Task 4): policy log-probs with gradients, reference log-probs under torch.no_grad(), the chosen loss, an optional NLL term on the chosen response, one optimizer step, and the diagnostics dict. Then run python run.py, which builds about 2,200 offline pairs (a correct answer preferred to a wrong one, both sampled from the SFT TinyLM) and trains four variants on them.

(a) Which variant lowers answer accuracy? What happens to its held-out log⁡πθ(chosen)\log\pi_\theta(\text{chosen}), and how is that possible when its reward accuracy on training pairs is above 90%?

(b) Explain why β = 1 behaves so differently from β = 0.1 here, using the gradient weight σ(−u)\sigma(-u).

(c) Which of the three fixes in the run correspond to which section of the chapter?

Hint
The loss stops pushing a pair once the implicit-reward margin u=βΔu = \beta\Delta is a few units. How large must the raw log-ratio margin Δ\Delta be for that, at each β?
Solution

The core of the reference dpo_step:

tok_w, mask_w = response_logprobs(policy, prompts, chosen)
tok_l, mask_l = response_logprobs(policy, prompts, rejected)
pi_w, pi_l = sequence_logprob(tok_w, mask_w), sequence_logprob(tok_l, mask_l)
with torch.no_grad():
    ref_w = sequence_logprob(*response_logprobs(ref, prompts, chosen))
    ref_l = sequence_logprob(*response_logprobs(ref, prompts, rejected))
loss, r_w, r_l = dpo_loss(pi_w, pi_l, ref_w, ref_l, cfg.beta)        # or ipo / simpo
if cfg.nll_coef > 0:
    loss = loss - cfg.nll_coef * sequence_logprob(tok_w, mask_w, average=True).mean()
opt.zero_grad(); loss.backward(); opt.step()

followed by the stats: (r_w > r_l).float().mean(), (r_w - r_l).mean(), pi_w.mean(), pi_l.mean() as Python floats.

(a) With the reference solution, DPO β = 0.1 drops greedy accuracy from 0.76 to about 0.38, and its held-out log⁡πθ(chosen)\log\pi_\theta(\text{chosen}) falls from −0.67 to about −2.5, while log⁡πθ(rejected)\log\pi_\theta(\text{rejected}) falls much further (to about −9.8). The margin, which is all the loss sees, keeps growing, so the ranking is right; but both responses lose probability, and the freed mass goes to other wrong answers that appear in no pair (for example, the model starts answering 41+19= with 71). This is likelihood displacement: the right answer is “preferred” and less likely at the same time.

(b) A pair stops contributing once σ(−u)\sigma(-u) is small, say u≈3u \approx 3 (weight 0.05). With β = 1 that needs a raw log-ratio margin Δ≈3\Delta \approx 3 nats (natural-log units), which the model reaches quickly; then the gradients fade and the policy stays near the reference. With β = 0.1 it needs Δ≈30\Delta \approx 30 nats. The optimizer keeps pushing hard on every pair for many epochs over the same small dataset, and the cheapest way to grow Δ\Delta is to crush the rejected answers and everything that shares parameters with them, which includes the correct answers’ neighbors and the correct answers themselves. (On a dataset this small, with this many epochs, a small β is a weak leash, as the “deterministic preferences” section predicts.)

(c) DPO β = 1: a tighter leash, the “deterministic preferences” section (and Exercise 13.6). DPO β = 0.1 + NLL: the likelihood-displacement fix (Llama 3, Pang et al.); it does best here, about 0.91 greedy accuracy, with log⁡πθ(chosen)\log\pi_\theta(\text{chosen}) rising to −0.18. IPO β = 0.1: the finite-target fix from the variants section; about 0.84 greedy accuracy.

Files: README.md, dpo.py, prefs.py, test_dpo.py, run.py

cd 13-dpo
python -m pytest -q          # your code: tests fail until you fill in the TODOs
RL_SOLUTIONS=1 python -m pytest -q   # reference solutions: all pass

First time? See Exercises & setup.

Further reading

Next, Chapter 14 asks where the preferences and rewards come from in the first place: human labelers, AI feedback and constitutions, LLM judges, rubrics, and verifiers.