All courses

Direct Preference Optimization

Derive the optimal policy of the KL-regularized objective and substitute it into Bradley-Terry to get a classification loss on preference pairs. Explain what DPO gains and loses compared with RLHF.

Builds on: RLHF with a KL penalty

▶ Watch this lesson Start the whole course

What the animation says

Too many moving parts

RLHF trains with PPO: maximize reward, minus a KL penalty for drifting from the reference model. That means a reward model, fresh sampled responses, a value baseline, and tuned clipping. Yet the data underneath is just pairs: a prompt, a preferred answer, and a rejected one. And the KL-penalized objective has an exact optimal policy. Can we fit it to the pairs directly, with one supervised loss?

The optimum: reference × boost

Take one prompt and three candidate answers. Grey bars are the reference model's probabilities. Rearranged, the objective is a constant minus beta times the KL divergence from one special policy, pi star. KL is zero only when you match pi star, so pi star is the optimum. It's the reference probabilities, each boosted by e to the reward over beta, then renormalized by Z. With beta 0.1, the top-reward answer climbs from 0.2 to 0.53. Now halve beta, to 0.05. What happens to the bars?

Invert it, and Z cancels

Halving beta sharpens them: the top answer now holds 0.80. Now run it backwards. Take logs and solve for the reward: beta log of pi star over the reference, plus beta log Z. Bradley-Terry says the winner beats the loser with probability sigmoid of the reward difference. But Z sums over every possible response. We can't compute it. Tap the term that drops out of the difference.

One pair, real numbers

It cancels. Put the trainable policy in place of pi star, and the loss is minus log sigmoid of the margin. Beta times each log ratio is the implicit reward. Use beta 0.1. Winner: policy minus 19, reference minus 20. Implicit reward 0.1. Loser: policy minus 21, reference minus 18. Implicit reward minus 0.3. Margin 0.4, sigmoid 0.599, loss 0.513. Untrained, the margin is zero and the loss is log 2, 0.693. Training pushes margins up. Which pair gets the hardest push?

The weights, then the code

Misranked pushes hardest: each pair is weighted by sigmoid of minus its margin. Our pair gets 0.40. In numpy, inputs are summed token log-probs of whole responses, under the policy and the frozen reference. This line builds the margin. Reference log-probs are computed once, with no gradient. This line is minus log sigmoid, written with logaddexp so it stays numerically stable. No generation, no reward model, no value baseline: just forward passes on given text.

What DPO buys, what it gives up

The policy acts as its own reward model, so a preference pair becomes a classification example. Gains: no reward model, no sampling, no PPO. Training is simpler, more stable, and cheaper. The cost: it's offline. It only sees fixed pairs, and never gets feedback on its own new outputs. And it only constrains the margin, so both answers' probabilities can fall together, as long as the gap grows.

Can we skip the RL in RLHF?

RLHF maximizes $\mathbb E[r(x,y)]-\beta\,\mathrm{KL}(\pi_\theta\|\pi_{ref})$ with PPO. That means training a reward model, sampling responses, keeping a value baseline and tuning clipping: many moving parts. Yet the data is just **preference pairs** $(x, y_w, y_l)$: a prompt, a preferred (winner) response and a rejected (loser) response. The KL-regularized objective has an exact optimal policy. Could we use it to fit the policy to the pairs directly, with one supervised-style loss?

The optimum: $\pi_{\text{ref}}$ reweighted by $e^{r/\beta}$

For one prompt, write the objective as a sum over responses $y$: $\sum_y \pi(y)r(y)-\beta\sum_y \pi(y)\log\frac{\pi(y)}{\pi_{ref}(y)}$. Folding $r$ into the log rewrites it as $\beta\log Z-\beta\,\mathrm{KL}(\pi\|\pi^*)$, where $$\pi^*(y)=\frac{\pi_{ref}(y)\,e^{r(y)/\beta}}{Z},\quad Z=\sum_y\pi_{ref}(y)e^{r(y)/\beta}.$$ KL is ≥ 0 and is zero only at $\pi=\pi^*$, so $\pi^*$ is optimal. It is the SFT probabilities, each boosted by $e^{r/\beta}$. A smaller β gives a sharper boost.

Invert, plug into Bradley-Terry, Z cancels

Take logs and solve for the reward: $r(x,y)=\beta\log\frac{\pi^*(y|x)}{\pi_{ref}(y|x)}+\beta\log Z(x)$. Bradley-Terry says $P(y_w\succ y_l\mid x)=\sigma(r(x,y_w)-r(x,y_l))$. The normalizer term $\beta\log Z(x)$ cannot be computed, but it appears in both rewards and cancels. Put $\pi_\theta$ in place of $\pi^*$ and maximize the likelihood of the human labels: $$\mathcal L_{\text{DPO}}=-\mathbb E\log\sigma\Big(\beta\log\tfrac{\pi_\theta(y_w|x)}{\pi_{ref}(y_w|x)}-\beta\log\tfrac{\pi_\theta(y_l|x)}{\pi_{ref}(y_l|x)}\Big)$$ The quantity $\beta\log\frac{\pi_\theta}{\pi_{ref}}$ is the **implicit reward**.

One pair, β = 0.1

Sequence log-probs (sums over tokens): $\log\pi_{ref}(y_w)=-20$, $\log\pi_{ref}(y_l)=-18$; $\log\pi_\theta(y_w)=-19$, $\log\pi_\theta(y_l)=-21$. - Implicit rewards: $0.1(-19+20)=0.1$ and $0.1(-21+18)=-0.3$. - Margin: $0.1-(-0.3)=0.4$, so $\sigma(0.4)=0.599$. - Loss: $-\ln 0.599=0.513$. At the start ($\pi_\theta=\pi_{ref}$) the margin is 0 and the loss is $\ln 2=0.693$. The loss's derivative with respect to the margin $m$ is $-\sigma(-m)$, so each pair's push is weighted by $\sigma(-m)$. Here that weight is $\sigma(-0.4)=0.401$. It is below 0.5 for correctly ranked pairs and approaches 1 as $m$ goes negative, so misranked pairs push hardest.

DPO loss in numpy

The inputs are the summed token log-probs of each full response, under the policy and under the frozen reference. The reference values are computed once, with no gradient. There is no generation, no reward model and no value baseline, just forward passes on given text. Since $-\log\sigma(m)=\log(1+e^{-m})$, `logaddexp` computes the loss stably.
import numpy as np
def dpo_loss(lp_w, lp_l, ref_w, ref_l, beta=0.1):
    # each arg: summed token log-probs per response, shape [B]
    margin = beta * ((lp_w - ref_w) - (lp_l - ref_l))
    return np.mean(np.logaddexp(0.0, -margin))  # -log sigmoid(margin)
a = lambda v: np.array([v])
print(dpo_loss(a(-19.), a(-21.), a(-20.), a(-18.)))  # 0.513
print(dpo_loss(a(-20.), a(-18.), a(-20.), a(-18.)))  # 0.693 = ln 2

What DPO buys and what it gives up

The KL-regularized optimum $\pi^*\propto\pi_{ref}e^{r/\beta}$ lets the policy act as its own reward, $\beta\log\frac{\pi_\theta}{\pi_{ref}}$. That turns Bradley-Terry into a classification loss on preference pairs. **Gains:** no reward model, no sampling and no PPO. Training is simpler, more stable and cheaper. **Losses:** it is **offline**. It learns only from fixed pairs and never gets fresh feedback on its own new outputs, as RLHF's reward model gives. It constrains only margins, so both responses' probabilities can fall.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.