Chapter 17 · Section 17.2 · 55 min

DPO derived

The RLHF pipeline of Chapter 16 has two learning stages. First a reward model is fit to human comparisons with the Bradley-Terry loss (§16.3). Then a policy is trained with PPO to maximize that reward minus a KL penalty (§16.4). The second stage is where nearly all of the cost and instability lives.

Section 17.1 showed that the second stage has an exact answer, π⋆(y∣x)∝πref(y∣x) er(x,y)/β\pi^\star(y\mid x) \propto \pi_{\text{ref}}(y\mid x)\,e^{r(x,y)/\beta}, which we cannot use because of its normalizer Z(x)Z(x). Rafailov, Sharma, Mitchell, Ermon, Manning, and Finn (2023) noticed that this is backwards. Instead of fitting a reward and then searching for its optimal policy, choose the form of the reward model so that its optimal policy is known in advance. If the reward model is written as βlog⁡πθ(y∣x)πref(y∣x)\beta\log\frac{\pi_\theta(y\mid x)}{\pi_{\text{ref}}(y\mid x)} for a language model πθ\pi_\theta, then the optimal policy for that reward is πθ\pi_\theta itself. Fitting the reward model by maximum likelihood is training the policy, the RL stage disappears, and the normalizer cancels out of the loss along the way. The title of their paper says it in one line, your language model is secretly a reward model.

This section derives Direct Preference Optimization (DPO) step by step, proves that the change of variables loses nothing, computes the loss and its gradient by hand, and reads the gradient carefully, because what it weights and what it ignores explain most of DPO's behavior in practice, good and bad.

Preferences, one more time

A preference dataset D\mathcal{D} contains triples (x,yw,yl)(x, y_w, y_l), a prompt and two responses to it, where a labeler preferred ywy_w (the "winner", also called chosen) over yly_l (the "loser", or rejected). The Bradley-Terry model of §16.3 assumes the labels come from a latent reward r⋆r^\star,

p⋆(yw≻yl∣x)=er⋆(x,yw)er⋆(x,yw)+er⋆(x,yl)=σ(r⋆(x,yw)−r⋆(x,yl)),p^\star(y_w \succ y_l \mid x) = \frac{e^{r^\star(x, y_w)}}{e^{r^\star(x, y_w)} + e^{r^\star(x, y_l)}} = \sigma\big(r^\star(x, y_w) - r^\star(x, y_l)\big),

with σ(z)=1/(1+e−z)\sigma(z) = 1/(1+e^{-z}) the logistic sigmoid. A reward model rϕr_\phi is fit by maximizing the likelihood of the observed labels, which is the binary cross-entropy of §0.4,

LR(ϕ)=−E(x,yw,yl)∼D[log⁡σ(rϕ(x,yw)−rϕ(x,yl))].\mathcal{L}_R(\phi) = -\mathbb{E}_{(x, y_w, y_l)\sim\mathcal{D}}\Big[\log\sigma\big(r_\phi(x, y_w) - r_\phi(x, y_l)\big)\Big].

In plain words, the probability that ywy_w wins is a logistic function of how much more reward it has, and we fit the rewards so that observed winners get higher scores.

Two facts about this model matter here. It only ever sees reward differences between two responses to the same prompt, so adding any function f(x)f(x) of the prompt to rr changes no prediction. And it says nothing about how to generate a good response, which is why Chapter 16 needed a second stage.

Three steps to DPO

Step 1, solve for the reward. Section 17.1 showed that for any reward function rr, the optimal policy πr\pi_r of the KL-regularized problem satisfies πr(y∣x)=πref(y∣x)er(x,y)/β/Z(x)\pi_r(y\mid x) = \pi_{\text{ref}}(y\mid x)e^{r(x,y)/\beta}/Z(x). Take the log of both sides and solve for rr,

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

This holds for every reward, so in particular for the true reward r⋆r^\star and its optimal policy π⋆\pi^\star. In plain words, a reward is the scaled log-ratio between its optimal policy and the reference, plus a constant for each prompt.

Step 2, substitute into Bradley-Terry. The preference probability depends only on the difference r⋆(x,yw)−r⋆(x,yl)r^\star(x,y_w) - r^\star(x,y_l). Write both rewards with Step 1,

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

Both responses answer the same prompt xx, so they share the same Z(x)Z(x), and it cancels,

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

In plain words, under Bradley-Terry, the probability that a human prefers one response to another can be written using only the optimal policy and the reference policy. The intractable sum over all responses has vanished, because preferences compare two responses to the same prompt.

Step 3, fit by maximum likelihood. We do not know π⋆\pi^\star, so replace it with a parameterized policy πθ\pi_\theta and maximize the likelihood of the observed preferences, exactly as for a reward model. The result is the DPO loss,

  LDPO(θ)=−E(x,yw,yl)∼D[log⁡σ(βlog⁡πθ(yw∣x)πref(yw∣x)−βlog⁡πθ(yl∣x)πref(yl∣x))].  \boxed{\;\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].\;}

In plain words, train the policy so that, relative to the reference, it has raised the probability of the chosen response more than the probability of the rejected one, and score how well it has done with a logistic loss. Everything in the loss is computable. It needs the log-probability of two given responses under two models, one of them frozen, and nothing else. No sampling, no reward model, no value function, no ZZ.

It helps to give the quantity inside the sigmoid a name, because it appears in every formula from here on. The log-ratio difference of a pair is

hθ(x,yw,yl)=log⁡πθ(yw∣x)πref(yw∣x)−log⁡πθ(yl∣x)πref(yl∣x),h_\theta(x, y_w, y_l) = \log\frac{\pi_\theta(y_w\mid x)}{\pi_{\text{ref}}(y_w\mid x)} - \log\frac{\pi_\theta(y_l\mid x)}{\pi_{\text{ref}}(y_l\mid x)},

measured in nats, and the DPO loss is −log⁡σ(βhθ)-\log\sigma(\beta h_\theta) averaged over pairs. When the context is clear we write hh. (This hh is unrelated to the number of attention heads hh of Chapters 4 to 6. In this chapter it always means a pair's log-ratio difference.) Notice where β\beta sits. It multiplies hh, so the sigmoid sees the difference of two scaled log-ratios, while hh itself stays in nats.

Why this is not a trick

It is worth stating plainly why this procedure is legitimate, because the first reaction of many people is that something must have been swept under the rug. Define a reward model by

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

The DPO loss is exactly the Bradley-Terry reward-model loss LR\mathcal{L}_R evaluated at this rθr_\theta. So DPO is reward modeling with an unusual architecture. Now ask what the optimal KL-regularized policy is for this reward. Plug it into the closed form,

πrθ(y∣x)=πref(y∣x) erθ(x,y)/β∑y′πref(y′∣x) erθ(x,y′)/β=πθ(y∣x)∑y′πθ(y′∣x)=πθ(y∣x).\pi_{r_\theta}(y\mid x) = \frac{\pi_{\text{ref}}(y\mid x)\,e^{r_\theta(x,y)/\beta}}{\sum_{y'}\pi_{\text{ref}}(y'\mid x)\,e^{r_\theta(x,y')/\beta}} = \frac{\pi_\theta(y\mid x)}{\sum_{y'}\pi_\theta(y'\mid x)} = \pi_\theta(y\mid x).

The normalizer is a sum of probabilities, which is 1. So whatever reward DPO fits, the policy that RLHF would extract from it is the network we are already holding. Reward modeling and policy optimization have become a single maximum-likelihood problem. The cell checks Steps 1 and 2 with numbers. It picks a random reward on six responses, computes π⋆\pi^\star, recovers the reward from the policy, and compares Bradley-Terry probabilities computed both ways.

Python · cell 1

Every response's reward differs from the policy-derived reward by the same constant, βlog⁡Z=0.7628\beta\log Z = 0.7628, and the 36 preference probabilities agree to machine precision.

Does the change of variables lose anything?

DPO restricts reward models to the form βlog⁡(π/πref)\beta\log(\pi/\pi_{\text{ref}}). A natural worry is that some rewards cannot be written this way, so DPO could be fitting a smaller family than a reward model can. The answer is no, and the proof is short enough to give in full. It is Theorem 1 of the DPO paper.

Call two rewards equivalent if they differ by a function of the prompt alone, r′(x,y)=r(x,y)+f(x)r'(x,y) = r(x,y) + f(x). Two facts follow from what we already know.

Lemma 1. Equivalent rewards give identical preferences. Bradley-Terry depends on r(x,yw)−r(x,yl)r(x,y_w) - r(x,y_l), and f(x)f(x) cancels in the difference.

Lemma 2. Equivalent rewards give the same optimal policy. Adding f(x)f(x) multiplies every weight πrefer/β\pi_{\text{ref}}e^{r/\beta} by ef(x)/βe^{f(x)/\beta}, and the normalizer absorbs it (§17.1).

So the data can only ever identify a reward up to its equivalence class, and the policy only depends on the class. It is therefore enough to show that every class contains a reward of DPO's form.

Theorem. Assume πref(y∣x)>0\pi_{\text{ref}}(y\mid x) > 0 for all xx and yy. Every equivalence class contains exactly one reward that can be written as βlog⁡π(y∣x)πref(y∣x)\beta\log\frac{\pi(y\mid x)}{\pi_{\text{ref}}(y\mid x)} for some policy π\pi.

Existence. Given any rr, subtract its own log-partition function, r′(x,y)=r(x,y)−βlog⁡Zr(x)r'(x,y) = r(x,y) - \beta\log Z_r(x). This is in the same class, since we subtracted a function of xx, and by Step 1 it equals βlog⁡πr(y∣x)πref(y∣x)\beta\log\frac{\pi_r(y\mid x)}{\pi_{\text{ref}}(y\mid x)}, which has the required form with π=πr\pi = \pi_r.

Uniqueness. Suppose two members of a class have the form, βlog⁡ππref+f(x)=βlog⁡π′πref\beta\log\frac{\pi}{\pi_{\text{ref}}} + f(x) = \beta\log\frac{\pi'}{\pi_{\text{ref}}}. Exponentiating gives π(y∣x) ef(x)/β=π′(y∣x)\pi(y\mid x)\,e^{f(x)/\beta} = \pi'(y\mid x). Summing over yy, both sides being distributions, gives ef(x)/β=1e^{f(x)/\beta} = 1, so f=0f = 0 and the two rewards are the same.

In plain words, among all rewards that make the same predictions, DPO's form picks out the single one whose partition function is 1, which is the one that is "already normalized". Nothing representable by a reward model is lost, as long as the policy network itself is expressive enough. That last condition is not trivial. A reward model and a policy model of the same size have different strengths, and DPO bets that the policy's representation is a good one for judging responses.

The loss, by hand

Two worked examples fix the scale of the numbers.

Example 1, early in training. Take β=0.1\beta = 0.1 and one pair. The policy assigns the chosen response a sequence log-probability of −12.0-12.0 (the reference gave −12.5-12.5) and the rejected response −15.0-15.0 (the reference gave −14.2-14.2). The policy has raised the chosen response by 0.5 nats and lowered the rejected one by 0.8, so

h=(−12.0+12.5)−(−15.0+14.2)=0.5+0.8=1.3,βh=0.13,h = (-12.0 + 12.5) - (-15.0 + 14.2) = 0.5 + 0.8 = 1.3, \qquad \beta h = 0.13, L=−log⁡σ(0.13)=log⁡(1+e−0.13)=0.6303.\mathcal{L} = -\log\sigma(0.13) = \log(1 + e^{-0.13}) = 0.6303 .

At initialization, when πθ=πref\pi_\theta = \pi_{\text{ref}}, every pair has h=0h = 0 and loss log⁡2=0.6931\log 2 = 0.6931. This is the first number to check in any DPO run, and §17.3 lists the bugs that make it come out differently. After moving 1.3 nats the loss has fallen only to 0.630, because β=0.1\beta = 0.1 shrinks the logit.

Example 2, a pair the model has learned. To bring this pair's loss down to 0.018 we need βh=4\beta h = 4, which means h=40h = 40 nats. With β=0.1\beta = 0.1, "learning" a preference means changing the relative log-probability of the two responses by tens of nats. Spread over two responses of a few hundred tokens each, that is only about a tenth of a nat per token, small enough to look harmless locally. But it is forty nats of relative probability, a factor of e40e^{40}, and it is the first hint that DPO with a small β\beta can wander far from the reference on the pairs it trains on.

Warm-up

The DPO loss

Implement dpo_loss(policy_chosen_logps, policy_rejected_logps, ref_chosen_logps, ref_rejected_logps, beta). Each argument is an array of shape (B,) holding sequence log-probabilities log⁡π(y∣x)\log\pi(y\mid x) for a batch of BB pairs. Return the mean DPO loss over the batch as a float. It must be finite for log-ratio differences in the thousands, positive or negative.

Hidden tests, hints, and AI help, from $1.99 a month.

The implicit reward

The quantity inside the loss deserves a name. The implicit reward of a response is

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)},

so that βhθ=r^θ(x,yw)−r^θ(x,yl)\beta h_\theta = \hat r_\theta(x, y_w) - \hat r_\theta(x, y_l), the implicit reward margin. In Example 1 the implicit rewards are +0.05+0.05 for the chosen response and −0.08-0.08 for the rejected one, with margin 0.13. Every DPO training log reports their averages over a batch as the chosen reward, the rejected reward, and the margin, along with the reward accuracy, the fraction of pairs with a positive margin.

Three properties are worth knowing before reading such a log.

  • It starts at zero. At initialization every implicit reward is exactly 0. A positive implicit reward means the policy has made that response more likely than the reference did, and a negative one means less likely. Nothing more.
  • It is only meaningful within a prompt. The data identify the reward only up to a per-prompt constant, and r^θ\hat r_\theta is the particular member of the class whose partition function is 1. Saying that one prompt's response has a higher implicit reward than another prompt's response compares two numbers that the model was never trained to make comparable.
  • It can serve as a reward model. Since r^θ\hat r_\theta is a Bradley-Terry reward model, a DPO-trained policy can score responses, rank candidates for best-of-nn, or label new preference pairs. Benchmarks of reward models, such as RewardBench (Lambert et al. 2024), evaluate DPO models this way, by comparing the policy's and the reference's log-probabilities.
Core

Implied preferences from a policy

Implement implied_preferences(pi, pi_ref, beta) for 1-D arrays over KK responses to one prompt, returning the K×KK\times K matrix PP with Pij=σ(r^(yi)−r^(yj))P_{ij} = \sigma\big(\hat r(y_i) - \hat r(y_j)\big), the probability under Bradley-Terry that yiy_i beats yjy_j according to the policy's implicit reward r^=βlog⁡(π/πref)\hat r = \beta\log(\pi/\pi_{\text{ref}}). It must be accurate when some probabilities are as small as 10−30010^{-300}, so work with logs and a stable sigmoid.

Hidden tests, hints, and AI help, from $1.99 a month.

The gradient, and what it weights

Now the analysis that every interviewer asks for. Write u=βhθu = \beta h_\theta for one pair, so the per-pair loss is ℓ(u)=−log⁡σ(u)\ell(u) = -\log\sigma(u). Two facts about the sigmoid do all the work, σ′(u)=σ(u)(1−σ(u))\sigma'(u) = \sigma(u)(1 - \sigma(u)) and 1−σ(u)=σ(−u)1 - \sigma(u) = \sigma(-u). So

dℓdu=−σ′(u)σ(u)=−(1−σ(u))=−σ(−u).\frac{d\ell}{du} = -\frac{\sigma'(u)}{\sigma(u)} = -(1 - \sigma(u)) = -\sigma(-u).

The reference log-probabilities do not 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,

∇θLDPO=−β E(x,yw,yl)∼D[σ(r^θ(x,yl)−r^θ(x,yw))⏟weight(∇θlog⁡πθ(yw∣x)⏟raise the chosen−∇θlog⁡πθ(yl∣x)⏟lower the rejected)],\nabla_\theta\mathcal{L}_{\text{DPO}} = -\beta\,\mathbb{E}_{(x,y_w,y_l)\sim\mathcal{D}}\Big[\underbrace{\sigma\big(\hat r_\theta(x, y_l) - \hat r_\theta(x, y_w)\big)}_{\text{weight}}\Big(\underbrace{\nabla_\theta\log\pi_\theta(y_w\mid x)}_{\text{raise the chosen}} - \underbrace{\nabla_\theta\log\pi_\theta(y_l\mid x)}_{\text{lower the rejected}}\Big)\Big],

where we used σ(−u)=σ(r^θ(yl)−r^θ(yw))\sigma(-u) = \sigma(\hat r_\theta(y_l) - \hat r_\theta(y_w)). In plain words, a gradient descent step makes the chosen response more likely and the rejected one less likely, and weights each pair by the probability that the implicit reward model currently ranks the pair the wrong way. It is exactly the weight σ(−Δ)\sigma(-\Delta) that §16.3 found in the gradient of an ordinary reward model, with the implicit margin in place of Δ\Delta, as it must be, since DPO's loss is a reward-model loss. A pair the model gets badly wrong gets a weight near 1. A pair it already ranks correctly by a wide margin gets a weight near 0.

implicit margin βh\beta h−4-4−2-2002244
weight σ(−βh)\sigma(-\beta h)0.9820.8810.5000.1190.018
loss −log⁡σ(βh)-\log\sigma(\beta h)4.0182.1270.6930.1270.018
Which preference pairs does the DPO gradient actually learn from?
The horizontal axis is a pair's log-ratio difference h in nats. The solid curve is the gradient weight sigmoid(−βh), the dashed curve is the loss −log sigmoid(βh). Dots are a batch of 48 pairs, including six with labels the model cannot fit.
Loading interactive figure…

The weight is not a detail. Rafailov et al. report that a naive version of the method without it, which raises log⁡πθ(yw)\log\pi_\theta(y_w) and lowers log⁡πθ(yl)\log\pi_\theta(y_l) with equal force on every pair (essentially an unlikelihood objective), makes the language model degenerate (their Appendix Table 3). The reason is that the unweighted objective log⁡πθ(yw)−log⁡πθ(yl)\log\pi_\theta(y_w) - \log\pi_\theta(y_l) is unbounded. It can always be improved by pushing the rejected responses further toward probability zero, and in a network with shared parameters the cheapest way to do that is to damage the model broadly. The weight acts as a brake. Once a pair is ranked correctly by a margin of a few units of βh\beta h, it stops pulling, and the gradient budget goes to the pairs that are still wrong. This is the KL regularization at work, disguised, because βh\beta h is large exactly when the policy has moved far from the reference on that pair.

The brake never fully engages, though. The weight σ(−βh)\sigma(-\beta h) is positive for every finite hh, so DPO keeps pushing on every pair forever. How fast does a learned pair drift? For one pair and a tabular policy (one free logit per response), only the chosen and rejected logits move, by equal and opposite amounts, and a gradient step of size η\eta updates the log-ratio difference by h←h+2ηβ σ(−βh)h \leftarrow h + 2\eta\beta\,\sigma(-\beta h). When βh\beta h is large, σ(−βh)≈e−βh\sigma(-\beta h)\approx e^{-\beta h}, so eβhe^{\beta h} grows by about 2ηβ22\eta\beta^2 per step, and after tt steps

ht≈1βlog⁡(2ηβ2t).h_t \approx \frac{1}{\beta}\log\big(2\eta\beta^2 t\big).

In plain words, on a pair the model already ranks correctly, the margin keeps growing, but only logarithmically, like the weights of logistic regression on separable data. Without the weight it grows linearly. The cell runs both recurrences.

Python · cell 2

After 10,000 steps DPO's margin is 45.7 nats, matching the logarithmic prediction of 46.1, while the unweighted version has reached 500. (The approximation assumes βh\beta h is already large, which is why it says nothing useful at step 100.) Both are pushing πθ(yl)\pi_\theta(y_l) toward zero, which on a single deterministic pair is what maximum likelihood asks for, and §17.4 returns to why that is a problem when preferences are noisy or rare.

What the gradient looks like inside a softmax

For a policy that is a single softmax over KK responses with logits z∈RK\mathbf{z} \in \R^K (think of one-token responses, or the tabular policy above), the score of a response is ∇zlog⁡π(y)=ey−π\nabla_{\mathbf{z}}\log\pi(y) = \mathbf{e}_y - \boldsymbol\pi (§15.3). The difference of two scores is

∇zlog⁡π(yw)−∇zlog⁡π(yl)=(ew−π)−(el−π)=ew−el.\nabla_{\mathbf{z}}\log\pi(y_w) - \nabla_{\mathbf{z}}\log\pi(y_l) = (\mathbf{e}_w - \boldsymbol\pi) - (\mathbf{e}_l - \boldsymbol\pi) = \mathbf{e}_w - \mathbf{e}_l .

The policy's own probabilities cancel. A DPO step on one pair changes exactly two logits, by equal and opposite amounts, and leaves every other logit alone (the other probabilities still change, through the normalization). Contrast this with a language model, where the parameters are shared. There ∇θlog⁡πθ(yw)\nabla_\theta\log\pi_\theta(y_w) and ∇θlog⁡πθ(yl)\nabla_\theta\log\pi_\theta(y_l) are large vectors that overlap heavily when the two responses are similar, so lowering one drags the other down with it. That overlap is the mechanism behind likelihood displacement, where both log-probabilities fall during training, which §17.5 studies in detail.

There is one more cancellation that matters in practice. A sequence log-probability is a sum over tokens, log⁡πθ(y∣x)=∑tlog⁡πθ(yt∣x,y<t)\log\pi_\theta(y\mid x) = \sum_t\log\pi_\theta(y_t\mid x, y_{<t}). If ywy_w and yly_l begin with the same tokens, those tokens have identical contexts in both responses, so their terms in log⁡πθ(yw)−log⁡πθ(yl)\log\pi_\theta(y_w) - \log\pi_\theta(y_l) cancel exactly, in the loss and in the gradient. DPO learns only from the first point where the responses differ onward. Tokens after the divergence do not cancel even when they match, because their contexts differ. Pal et al. (2024) show that for pairs differing in only a few tokens, this structure can lower the probability of the chosen response's later tokens, one of the first documented forms of likelihood displacement.

Interview

The DPO loss and its gradient, checked numerically

Implement dpo_loss_and_grads(pc, pr, rc, rr, beta) with the same inputs as Exercise 17.2a (policy chosen, policy rejected, reference chosen, reference rejected sequence log-probabilities, each of shape (B,)). Return (loss, d_pc, d_pr), the mean DPO loss over the batch and its gradients with respect to the policy log-probabilities pc and pr, each of shape (B,). Derive the gradients yourself. The tests compare them with central finite differences of your own loss.

Hidden tests, hints, and AI help, from $1.99 a month.
Interview

DPO on a softmax policy, gradient with respect to the logits

A tabular policy over KK responses has logits z of shape (K,), and the reference has logits z_ref. You are given pairs, an integer array of shape (P, 2) whose rows are (w, l) index pairs for one prompt. Implement dpo_logit_grad(z, z_ref, pairs, beta) returning (loss, grad), the mean DPO loss over the pairs and its gradient with respect to z, shape (K,). Use log-softmax for log-probabilities. The same response can appear in many pairs, so accumulate with np.add.at, not fancy-index assignment.

Hidden tests, hints, and AI help, from $1.99 a month.

What beta does in the loss

The loss depends on β\beta and hh only through their product. Suppose we want a pair's loss to fall to some level, say a weight of 0.05, which needs βh≈3\beta h \approx 3. With β=0.5\beta = 0.5 that takes h=6h = 6 nats of change relative to the reference. With β=0.1\beta = 0.1 it takes 30. Smaller β\beta means the policy must move further from the reference to satisfy the same data, which is the same direction as in the closed form, where small β\beta meant a sharper tilt. Typical values are 0.01 to 0.5, with 0.1 the default in the DPO paper (which used 0.5 for summarization) and in many later recipes, including Zephyr and Llama 3.

There is a second, less obvious effect. β\beta also multiplies the gradient, so at initialization the step is β/2\beta/2 times the difference of scores. With plain SGD a smaller β\beta therefore also means smaller steps. With Adam, which divides by a running estimate of the gradient's scale, a constant factor in the gradient mostly cancels, so β\beta acts mainly through where the weight σ(−βh)\sigma(-\beta h) saturates. This is one reason DPO learning rates are tuned together with β\beta, never separately, and §17.3 gives typical values.

Finally, notice what β\beta in DPO does not do. In RLHF with PPO, β\beta penalizes the KL on the policy's own samples at every step. DPO never samples, so nothing directly measures or limits the KL during training. The KL constraint is only present through the parameterization, and it holds exactly only at the optimum of a loss with complete data. On responses that are not in the dataset, nothing in the loss holds the policy near the reference at all. That gap is the subject of §17.5.

From pairs to rankings

Sometimes labelers rank KK responses rather than compare two. The Plackett-Luce model generalizes Bradley-Terry to rankings. The top choice is drawn with probability proportional to ere^{r} among all KK, the second among the remaining K−1K-1, and so on. For a ranking τ\tau (so yτ(1)y_{\tau(1)} is the best),

p⋆(τ∣x)=∏k=1Ker⋆(x,yτ(k))∑j=kKer⋆(x,yτ(j)).p^\star(\tau\mid x) = \prod_{k=1}^{K}\frac{e^{r^\star(x, y_{\tau(k)})}}{\sum_{j=k}^{K}e^{r^\star(x, y_{\tau(j)})}} .

Each factor is a softmax over a subset of responses to the same prompt, so substituting r=βlog⁡(π/πref)+βlog⁡Z(x)r = \beta\log(\pi/\pi_{\text{ref}}) + \beta\log Z(x) multiplies the numerator and every denominator term by the same factor Z(x)βZ(x)^\beta, which cancels again. The DPO loss for rankings is the negative log of this product with the implicit rewards r^θ\hat r_\theta in place of r⋆r^\star. With K=2K = 2 it is exactly the pairwise loss. Exercise 17.2e implements it.

Research

DPO with full rankings (Plackett-Luce)

Implement plackett_luce_dpo_loss(logratios, beta). logratios has shape (B, K), and row bb holds log⁡πθ(y∣x)−log⁡πref(y∣x)\log\pi_\theta(y\mid x) - \log\pi_{\text{ref}}(y\mid x) for the KK responses of prompt bb, already sorted from best to worst. Return the mean over the batch of −log⁡p(τ)-\log p(\tau) with Plackett-Luce probabilities computed from the implicit rewards β⋅\beta\cdotlogratios. It must be stable for log-ratios in the thousands and must equal the pairwise DPO loss when K=2K = 2.

Hidden tests, hints, and AI help, from $1.99 a month.

DPO and RLHF, side by side

RLHF with PPO (Chapter 16)DPO
learning stagesreward model, then RLone supervised stage
models in memory while trainingpolicy, reference, reward model, value modelpolicy, reference (or precomputed reference log-probabilities)
samples from the policy during trainingyes, every stepnone
what is learnedan explicit reward, then a policy that maximizes ita policy whose log-ratio to the reference is the reward
uses prompts without labelsyes, PPO can train on any prompt the reward model can scoreno, only labeled pairs
target at the optimumπ⋆∝πreferϕ/β\pi^\star\propto\pi_{\text{ref}}e^{r_\phi/\beta}the same π⋆\pi^\star, for the Bradley-Terry fit of the data
hyperparametersmany (clip range, KL coefficient or target, GAE, value loss weight, batch sizes)few (β\beta, learning rate, epochs)

The row that says "the same" is true and important, and it is also the most misunderstood line in the table. Both methods target the same policy when the reward model is fit to the same data and the optimization succeeds over all responses. In practice the two differ in what happens off the data. PPO's policy is judged by a reward model on its own samples, so it can be pulled back from (or pushed into) responses the data never covered. DPO's policy is judged only on the responses in the dataset. Whether that makes DPO better (no reward model to exploit) or worse (nothing controls the unseen responses) is an empirical question, and §17.5 reviews the evidence.

In PyTorch

The DPO loss is a few lines in any framework. Below we write it the way the paper's reference code does, as a function of four vectors of sequence log-probabilities, then check the hand-derived gradient on a small policy with shared parameters, a linear softmax over response features, where the gradient of log⁡πθ(y)\log\pi_\theta(y) is no longer a one-hot vector.

🔥 In PyTorchfor a machine with PyTorch

Read more

Watch next

🎬 Direct Preference Optimization (DPO) explained: Bradley-Terry model, log probabilities, math · Umar JamilA careful whiteboard derivation of the reward model loss and the DPO loss, with every algebra step shown.
🎬 Direct Preference Optimization: Your Language Model is Secretly a Reward Model | DPO paper explained · AI Coffee Break with LetitiaA short, clear overview of the paper's idea, good for a first pass or a quick review.
🎬 Direct Preference Optimization (DPO) and Friends | Post-Training Course, Lecture 6 · Nathan Lambert · starts at 19:19Recovering the reward from the policy, the Bradley-Terry substitution, and the loss and gradient.