Paper notes

Direct Preference Optimization: Your Language Model is Secretly a Reward Model

DPO replaces 'reward model plus PPO' with one classification-style loss: given only preference pairs and a frozen reference model, it optimizes the same KL-constrained objective as RLHF. This post checks the derivation, runs a toy world for the frontier and training dynamics, and covers limits.

Published Updated 35 min read

On this page
  1. Why it is worth reading
  2. From the objective to the loss in four steps
  3. What the paper reports
  4. Hands-on: a toy world of 256 responses
  5. Checking the derivation
  6. DPO is a Bradley-Terry fit plus the closed form
  7. The frontier: beta and data size
  8. Training dynamics: the chosen probability falls too
  9. Questions the paper left open, and what followed
  10. What to take from this paper
  11. Further reading
  12. FAQ

The paper “Direct Preference Optimization: Your Language Model is Secretly a Reward Model” (Rafailov, Sharma, Mitchell, Ermon, Manning and Finn, Stanford University; arXiv 2305.18290, NeurIPS 2023; called the DPO paper below) points out that the KL-constrained reward maximization at the heart of RLHF has a closed-form optimal policy. The reward can therefore be written as a log-ratio between the policy and a reference model, and the intractable partition function cancels in the Bradley-Terry preference probability, which depends only on a difference of rewards. Preference learning then becomes one classification-style loss on preference pairs (x,yw,yl)(x,y_w,y_l). The method is DPO (Direct Preference Optimization): no separate reward model, and no sampling from the policy inside the training loop.

The paper reports that on controlled sentiment generation with IMDb the reward-KL frontier of DPO lies above that of PPO, even when PPO is given the true reward; on Reddit TL;DR summarization the GPT-4 win rate is about 61% for DPO (temperature 0.0) against about 57% for PPO (its best temperature, also 0.0); and on single-turn Anthropic HH dialogue DPO is the only computationally light method among those compared that beats the chosen answers in the dataset. The largest model is 6B. This post checks the derivation equation by equation (all errors are below 1e-15 except the 4.8e-07 of one numerical optimization), sweeps beta and the data size in a toy world of 256 responses, looks at the training dynamics, and then covers what the paper left open: reward over-optimization, falling chosen probabilities, length bias, and the dispute between DPO and PPO. The experiments run in seconds on a CPU and train no real language model, so they verify the derivation and the mechanisms, not the paper’s experimental numbers.

Why it is worth reading

The standard RLHF recipe (see the InstructGPT breakdown) has four steps: supervised fine-tuning, sampling and labeling preferences, training a reward model, and reinforcement learning with PPO (see the PPO breakdown) under a KL penalty. The DPO paper says up front that this pipeline trains several language models and samples from the policy in the training loop, at significant computational cost. DPO keeps the first two steps and replaces the last two with one loss.

It quickly became the default starting point for open alignment: Zephyr (Tunstall et al., 2023, arXiv 2310.16944, subtitled Direct Distillation of LM Alignment) aligns a 7B model with DPO, and the post-training of Llama 3 is six rounds of SFT, rejection sampling and DPO. But simpler is not the same as better. The paper’s own discussion leaves several questions open: how DPO policies generalize out of distribution, what reward over-optimization looks like under DPO, and what happens with much larger models. Later work answered some of them and opened new disputes; the second half of this post goes through them.

From the objective to the loss in four steps

Notation: prompt xx, answer yy, the policy being trained πθ\pi_\theta, a frozen reference model πref\pi_{\mathrm{ref}} (usually the SFT model), a reward r(x,y)r(x,y), and a preference pair (x,yw,yl)(x,y_w,y_l) in which ywy_w is the chosen and yly_l the rejected answer.

Step 1: the RLHF objective (paper Eq. 3): maximize reward without drifting far from the reference model.

max⁡πθ Ex,  y∼πθ(⋅∣x)[r(x,y)]−β DKL[πθ(y∣x) ∥ πref(y∣x)]\begin{aligned} \max_{\pi_\theta}\ &\mathbb{E}_{x,\;y\sim\pi_\theta(\cdot\mid x)}\big[r(x,y)\big]\\ &-\beta\,\mathbb{D}_{\mathrm{KL}}\big[\pi_\theta(y\mid x)\,\|\,\pi_{\mathrm{ref}}(y\mid x)\big] \end{aligned}

Step 2: its optimal policy has a closed form (Eq. 4):

πr(y∣x)=1Z(x) πref(y∣x) exp⁡ ⁣(1β r(x,y)),Z(x)=∑yπref(y∣x)exp⁡ ⁣(1β r(x,y))\pi_r(y\mid x)=\frac{1}{Z(x)}\,\pi_{\mathrm{ref}}(y\mid x)\,\exp\!\Big(\frac{1}{\beta}\,r(x,y)\Big),\qquad Z(x)=\sum_{y}\pi_{\mathrm{ref}}(y\mid x)\exp\!\Big(\frac{1}{\beta}\,r(x,y)\Big)

Z(x)Z(x) is the partition function, a sum over the whole answer space that cannot be computed directly, so using the closed form as it stands is not practical.

Step 3: solve for the reward as a function of the policy (Eq. 5): take logarithms on both sides,

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_{\mathrm{ref}}(y\mid x)}+\beta\log Z(x)

Step 4: the partition function cancels in the preference probability. The Bradley-Terry model (Eq. 1) says the preference probability depends only on a difference of rewards, p∗(y1≻y2∣x)=σ(r∗(x,y1)−r∗(x,y2))p^*(y_1\succ y_2\mid x)=\sigma\big(r^*(x,y_1)-r^*(x,y_2)\big). Substitute Eq. 5, and the answer-independent term βlog⁡Z(x)\beta\log Z(x) drops out of the difference (Eq. 6):

p∗(y1≻y2∣x)=σ(βlog⁡π∗(y1∣x)πref(y1∣x)−βlog⁡π∗(y2∣x)πref(y2∣x))\begin{aligned} p^*(y_1\succ y_2\mid x)=\sigma\Big(&\beta\log\frac{\pi^*(y_1\mid x)}{\pi_{\mathrm{ref}}(y_1\mid x)}\\ &-\beta\log\frac{\pi^*(y_2\mid x)}{\pi_{\mathrm{ref}}(y_2\mid x)}\Big) \end{aligned}

The preference probability is now expressed with the policy and the reference model only. Replace π∗\pi^* with a trainable πθ\pi_\theta and maximize the likelihood of the preference data, and you have the DPO loss (Eq. 7):

LDPO=−E(x,yw,yl)∼D[log⁡σ(βlog⁡πθ(yw∣x)πref(yw∣x)−βlog⁡πθ(yl∣x)πref(yl∣x))]\begin{aligned} \mathcal{L}_{\mathrm{DPO}}=-\mathbb{E}_{(x,y_w,y_l)\sim\mathcal{D}}\Big[\log\sigma\Big(&\beta\log\frac{\pi_\theta(y_w\mid x)}{\pi_{\mathrm{ref}}(y_w\mid x)}\\ &-\beta\log\frac{\pi_\theta(y_l\mid x)}{\pi_{\mathrm{ref}}(y_l\mid x)}\Big)\Big] \end{aligned}
The RLHF pipeline versus DPO RLHF on the left has four steps: supervised fine-tuning, sampling and labeling preferences, training a reward model, and reinforcement learning with PPO. DPO on the right keeps the first two steps and merges the last two into one classification-style loss: no reward model and no sampling during training. Both optimize the same KL-constrained objective. RLHF (with PPO) DPO 1. Supervised fine-tuning (SFT) gives the reference model π_ref and the starting point 2. Sample and label preferences two answers per prompt, labeled y_w ≻ y_l 3. Train a reward model r_φ minimize the Bradley–Terry negative log-likelihood (Eq. 2) 4. Reinforcement learning (PPO) maximize r_φ − β·KL; sampling from the policy in the loop 1. Supervised fine-tuning (SFT) same as on the left 2. Preference data (x, y_w, y_l) same as on the left; ready-made datasets work too 3. One classification-style loss on the policy −log σ(β · difference of implicit rewards) implicit reward = log π_θ(y|x) − log π_ref(y|x) no reward model, no sampling in the loop Same objective on both sides: max E[r] − β·KL(π‖π_ref); DPO merges steps 3 and 4 by a change of variables
Figure 1: The RLHF and DPO pipelines. DPO keeps supervised fine-tuning and the preference data and merges the reward model and the reinforcement learning step into one loss by a change of variables.

The paper calls r^θ(x,y)=βlog⁡πθ(y∣x)πref(y∣x)\hat r_\theta(x,y)=\beta\log\frac{\pi_\theta(y\mid x)}{\pi_{\mathrm{ref}}(y\mid x)} the implicit reward of the policy; the title’s “your language model is secretly a reward model” refers to exactly this. The paper also proves (Theorem 1) that under mild assumptions every class of reward functions representable by a Plackett-Luce model (Bradley-Terry in particular) can be written in this form, so the reparameterization loses no generality. A “class” means rewards that differ by a function f(x)f(x) of the prompt alone (Lemmas 1 and 2: they induce the same preference distribution and the same optimal policy).

The gradient is the best way in to what DPO does during training:

∇θLDPO=−β E[σ(r^θ(x,yl)−r^θ(x,yw))⋅(∇θlog⁡πθ(yw∣x)−∇θlog⁡πθ(yl∣x))]\begin{aligned} \nabla_\theta\mathcal{L}_{\mathrm{DPO}}=-\beta\,\mathbb{E}\Big[&\sigma\big(\hat r_\theta(x,y_l)-\hat r_\theta(x,y_w)\big)\\ &\cdot\big(\nabla_\theta\log\pi_\theta(y_w\mid x)-\nabla_\theta\log\pi_\theta(y_l\mid x)\big)\Big] \end{aligned}

The bracket is the direction that raises the chosen log-probability and lowers the rejected one. The factor σ(r^θ(x,yl)−r^θ(x,yw))\sigma(\hat r_\theta(x,y_l)-\hat r_\theta(x,y_w)) is a weight: the more wrongly the implicit reward orders the pair, the larger it is, and it fades once the pair is ordered correctly and well separated. The paper says that a naive version without this weight makes the model degenerate (appendix Table 3 shows samples from the Unlikelihood baseline on TL;DR, which has no such weight); the lab below tests this in the toy world.

Three easy misunderstandings:

  • The reference model is frozen, and should come from the same source as the preference data. The paper suggests sampling the preference pairs from the SFT model; when no SFT model is available, first maximize the likelihood of the chosen answers to obtain πref\pi_{\mathrm{ref}}, to reduce the mismatch between the data and the reference.
  • Beta is the strength of the KL constraint, not a learning rate. The paper’s default is β=0.1\beta=0.1 (batch size 64, RMSprop, learning rate 10−610^{-6}, linear warm-up over 150 steps) and TL;DR uses 0.5.
  • DPO is offline. The pairs come from a fixed dataset, not from the current policy. Once the policy moves far, the shift between data and policy grows, which is the common starting point of several of the follow-ups below.

What the paper reports

The largest model in the paper has 6B parameters. The table collects the main experiments of the paper’s body (numbers are the paper’s, from GPT-4 or human evaluation; this post did not reproduce them):

TaskSetupCompared withThe paper’s result
IMDb controlled sentimentGPT-2-large, SFT on IMDb to convergence; preference pairs from a sentiment classifier by the value of p(positive)p(\text{positive})PPO, PPO-GT with the true reward, Unlikelihood, Preferred-FT; 22 runsDPO has the highest reward-KL frontier; even PPO with the true reward falls short
Reddit TL;DR summarizationSFT model of GPT-J; human preferences collected by Stiennon et al.GPT-4 win rate against the human reference summaryDPO about 61% (temperature 0.0), PPO about 57% (its best, 0.0); DPO is more robust to the sampling temperature
Anthropic HH single-turn dialoguePythia-2.8B, first fine-tuned on the chosen answers to get the reference modelGPT-4 win rate against the chosen answer in the datasetDPO is the only computationally light method that beats the chosen answers, on par with or better than the expensive Best of 128
Out of distribution: CNN/DailyMailThe TL;DR policies applied directly to news summarizationGPT-4 win rate against the reference summaryDPO 0.36 (temperature 0) and 0.31 (0.25), PPO 0.26 and 0.23
Is the evaluation trustworthyHuman study on TL;DR (Table 2)Agreement between humans and GPT-4In comparisons with PPO, humans prefer DPO 58%, GPT-4 with the simple prompt 47% and with the concise prompt 54%; GPT-4-human agreement is 70% and 67%, human-human 65%

Three caveats from the authors deserve to travel with these numbers. The IMDb preference pairs are generated by a classifier, so the reward is known and the frontier can be drawn. On TL;DR beta was not tuned meaningfully, which the authors say may underestimate DPO. On HH the paper could not find a prompt or temperature that made a public PPO checkpoint (a 6B model) beat the base Pythia-2.8B, so Best of 128 stands in as a rough proxy for PPO-level performance.

Hands-on: a toy world of 256 responses

Training DPO on a real language model takes tens of GPU hours, which this post cannot do; but the paper’s core claims have versions that can be checked exactly, and a small “world” is enough.

The world. A response is a binary string of length 8, 256 in total; each has 15 features (the 8 bits plus 7 indicators that two neighbouring bits are equal). The policy is log-linear: πθ(y)∝exp⁡(θ⋅ϕ(y))\pi_\theta(y)\propto\exp(\theta\cdot\phi(y)) with θ∈R15\theta\in\mathbb{R}^{15}, and the reference policy is a random θref\theta_{\mathrm{ref}}. The true reward rr is a linear function of the features minus a penalty when there are six or more ones; that term lies outside the feature family, so the policy family cannot represent the true reward, a misspecification like that of real language models; the reward is standardized to a standard deviation of 1.5. A preference pair draws two responses independently from the reference policy and decides the winner by the Bradley-Terry probability σ(r1−r2)\sigma(r_1-r_2) (a deterministic labeling in which the higher reward always wins is tried too). With only 256 responses, KL and expected reward are computed exactly, with no sampling noise.

How this toy differs from real models. There is no sequence structure, no real language model, and no PPO (so the paper’s claim that DPO is more efficient than PPO is not tested); the lab checks the algebra, the roles of beta and the data size, and the mechanisms in the training dynamics. Environment: Apple M2 Max CPU (2 threads), Python 3.14.3, NumPy 2.4.2, PyTorch 2.10.0, float64; all randomness is fixed by seeds, and a last digit may differ in another environment. A full run takes about 15 seconds and all outputs below come from the same run. The first three parts use one world (seed 0), the fourth uses three worlds (seeds 0, 1 and 2).

Full code (about 255 lines)
"""A small DPO lab: a world of 256 responses"""
import itertools

import numpy as np
import torch
import torch.nn.functional as F

torch.set_num_threads(2)
torch.set_default_dtype(torch.float64)
BITS = torch.tensor(list(itertools.product((0, 1), repeat=8))).double()
SAME = (BITS[:, 1:] == BITS[:, :-1]).double()
PHI = torch.cat([BITS, SAME], 1)  # 256 responses x 15 features
BETAS = (0.05, 0.1, 0.2, 0.5, 1.0, 2.0)


def world(seed, extra=True):
    # reference parameters theta_ref, true reward r
    g = torch.Generator().manual_seed(seed)
    theta_ref = 0.5 * torch.randn(15, generator=g)
    w = torch.randn(15, generator=g)
    r = PHI @ w
    if extra:  # a penalty outside the family
        r = r - 1.5 * (BITS.sum(1) >= 6).double()
    return theta_ref, (r - r.mean()) / r.std() * 1.5


def logp(theta):
    return torch.log_softmax(PHI @ theta, 0)


def kl(a, b):
    return (a.exp() * (a - b)).sum().item()


def entropy(a):
    return -(a.exp() * a).sum().item()


def value(a, r):
    return (a.exp() * r).sum().item()


def pairs(lref, r, n, rng, det=False):
    p = lref.exp().numpy()
    a, b = rng.choice(256, (2, 4 * n), p=p)
    keep = a != b
    a, b = a[keep][:n], b[keep][:n]
    ra, rb = r[a].numpy(), r[b].numpy()
    win = ra >= rb if det else rng.random(len(a)) < 1 / (1 + np.exp(rb - ra))
    return torch.tensor(np.where(win, a, b)), torch.tensor(np.where(win, b, a))


def lbfgs(f, x, iters=500):
    x = x.clone().requires_grad_(True)
    opt = torch.optim.LBFGS([x], max_iter=iters, tolerance_grad=1e-12,
                            tolerance_change=1e-15,
                            line_search_fn="strong_wolfe")

    def closure():
        opt.zero_grad()
        loss = f(x)
        loss.backward()
        return loss
    opt.step(closure)
    return x.detach()


def dpo_loss(theta, lref, w, l, beta, weighted=True):
    lq = logp(theta)
    z = beta * ((lq[w] - lref[w]) - (lq[l] - lref[l]))
    return -F.logsigmoid(z).mean() if weighted else -z.mean()


def bt_loss(u, w, l):
    return -F.logsigmoid((PHI[w] - PHI[l]) @ u).mean()


print("== 1. Checking the theory (one world: 256 responses, 15 features)")
theta_ref, r = world(0)
lref = logp(theta_ref)
B = 0.5
star = torch.log_softmax(lref + r / B, 0)  # Eq. (4): closed-form optimum


def neg_objective(z):
    lq = torch.log_softmax(z, 0)
    return -(lq.exp() * r).sum() + B * (lq.exp() * (lq - lref)).sum()


z = lbfgs(neg_objective, lref)
num = torch.log_softmax(z, 0)
print(f"(a) numeric optimum vs closed form: "
      f"max|pi_num - pi*| = {(num.exp() - star.exp()).abs().max():.1e}, "
      f"J(num) = {value(num, r) - B * kl(num, lref):.6f}, "
      f"J(pi*) = {value(star, r) - B * kl(star, lref):.6f}")
imp = B * (star - lref)
sig = torch.sigmoid
d_true = sig(r[:, None] - r[None, :])
d_imp = sig(imp[:, None] - imp[None, :])
logz = torch.logsumexp(lref + r / B, 0)
print(f"(b) partition function cancels: "
      f"max|p(r) - p(implicit)| = {(d_true - d_imp).abs().max():.1e}; "
      f"B*logZ = {B * logz:.4f}, r - implicit in "
      f"[{(r - imp).min():.4f}, {(r - imp).max():.4f}]")
w, l = pairs(lref, r, 50, np.random.default_rng(0))
g = torch.Generator().manual_seed(0)
th = (0.3 * torch.randn(15, generator=g)).requires_grad_(True)
(g_auto,) = torch.autograd.grad(dpo_loss(th, lref, w, l, 0.1), th)
jac = torch.autograd.functional.jacobian(logp, th.detach())  # 256 x 15
rhat = 0.1 * (logp(th.detach()) - lref)
wt = sig(rhat[l] - rhat[w])
g_form = -0.1 * (wt[:, None] * (jac[w] - jac[l])).mean(0)
print(f"(c) gradient formula vs autograd: "
      f"max|diff| = {(g_auto - g_form).abs().max():.1e}, "
      f"max|grad| = {g_auto.abs().max():.3f}")
star2 = torch.log_softmax(lref + (r + 3.7) / B, 0)
print(f"(d) reward + constant: "
      f"max|pi* change| = {(star2.exp() - star.exp()).abs().max():.1e}")
print("(e) the two extremes of beta (closed-form optimum):")
print(f"{'beta':>7} {'KL':>5} {'E[r]':>5} {'entropy':>7} {'max prob':>9}")
print(f"{'ref':>7} {0:5.2f} {value(lref, r):5.2f} {entropy(lref):7.2f} "
      f"{lref.exp().max():9.3f}")
for beta in (100.0, 10.0, 1.0, 0.1, 0.01):
    s = torch.log_softmax(lref + r / beta, 0)
    print(f"{beta:7g} {kl(s, lref):5.2f} {value(s, r):5.2f} "
          f"{entropy(s):7.2f} {s.exp().max():9.3f}")
print(f"    max r = {r.max():.2f}")

print()
print("== 2. DPO is a BT reward fit plus the closed form (1000 pairs)")
w, l = pairs(lref, r, 1000, np.random.default_rng(1))
u = lbfgs(lambda u: bt_loss(u, w, l), torch.zeros(15))
for beta in (0.1, 1.0):
    th = lbfgs(lambda t: dpo_loss(t, lref, w, l, beta), theta_ref)
    p_dpo = logp(th).exp()
    p_rm = torch.log_softmax(lref + PHI @ u / beta, 0).exp()
    print(f"beta={beta}: max|pi_DPO - pi_RM| = "
          f"{(p_dpo - p_rm).abs().max():.1e}, "
          f"loss_DPO = {dpo_loss(th, lref, w, l, beta):.8f}, "
          f"loss_BT = {bt_loss(u, w, l):.8f}")

print()
print("== 3. The reward-KL frontier (true expected reward E[r] and KL)")
print(f"reference: E[r] = {value(lref, r):.2f}, "
      f"max r = {r.max():.2f}")
NS = (100, 1000, 10000)
SEEDS = (0, 1, 2)
opt_row = {}
fam_row = {}
for beta in BETAS:
    s = torch.log_softmax(lref + r / beta, 0)
    opt_row[beta] = (kl(s, lref), value(s, r))

    def neg_j(t, beta=beta):
        lq = logp(t)
        return -(lq.exp() * r).sum() + beta * (lq.exp() * (lq - lref)).sum()

    f = logp(lbfgs(neg_j, theta_ref))
    fam_row[beta] = (kl(f, lref), value(f, r))
res = {}
spread = []
for n in NS:
    for seed in SEEDS:
        w, l = pairs(lref, r, n, np.random.default_rng(100 * n + seed))
        u = lbfgs(lambda u: bt_loss(u, w, l), torch.zeros(15))
        spread.append(u.norm().item())
        for beta in BETAS:
            s = torch.log_softmax(lref + PHI @ u / beta, 0)
            res.setdefault((n, beta), []).append((kl(s, lref), value(s, r)))


def cell(vals):
    a = np.array(vals)
    return f"{a.mean():.2f} ({a.min():.1f}-{a.max():.1f})"


for k, name in ((1, "E[r]"), (0, "KL")):
    print(f"{name}: each cell: mean (min-max) over 3 data seeds")
    print("beta  optimum in-family " + "".join(f"n={n:<14}" for n in NS))
    for beta in BETAS:
        row = "".join(f"{cell([v[k] for v in res[(n, beta)]]):<16}"
                      for n in NS)
        print(f"{beta:<5} {opt_row[beta][k]:7.2f} {fam_row[beta][k]:9.2f} "
              + row)
print(f"norm of the fitted BT parameters: "
      f"{min(spread):.2f} - {max(spread):.2f}")
print("Preferred-FT (max likelihood on chosen only):")
for n in NS:
    pts = []
    for seed in SEEDS:
        w, l = pairs(lref, r, n, np.random.default_rng(100 * n + seed))
        t = lbfgs(lambda t: -logp(t)[w].mean(), theta_ref)
        pts.append((kl(logp(t), lref), value(logp(t), r)))
    print(f"  n={n:<6} KL {cell([p[0] for p in pts])}, "
          f"E[r] {cell([p[1] for p in pts])}")

print("control: n=10000, beta=0.5, reward with or without the outside term")
for extra in (True, False):
    th0, rr = world(0, extra)
    l0 = logp(th0)
    best = value(torch.log_softmax(l0 + rr / 0.5, 0), rr)
    got = []
    for seed in SEEDS:
        w, l = pairs(l0, rr, 10000, np.random.default_rng(100 * 10000 + seed))
        u = lbfgs(lambda u: bt_loss(u, w, l), torch.zeros(15))
        got.append(value(torch.log_softmax(l0 + PHI @ u / 0.5, 0), rr))
    tag = "with the term" if extra else "without the term"
    print(f"  {tag}: optimum {best:.3f}, DPO {np.mean(got):.3f} "
          f"(min {min(got):.3f}, max {max(got):.3f})")

print()
print("== 4. Dynamics (3 worlds, 200 pairs each, beta=0.1, Adam, 3000 steps)")
sizes = []
for wseed in (0, 1, 2):
    th0, rr = world(wseed)
    w, l = pairs(logp(th0), rr, 200, np.random.default_rng(10 + wseed))
    sizes.append(len(torch.unique(torch.cat([w, l]))))
print("distinct responses in the pairs (3 worlds):",
      ", ".join(map(str, sizes)))
REC = (0, 50, 100, 200, 500, 1000, 2000, 3000)
CASES = (("DPO", False, True), ("DPO-det", True, True),
         ("naive", False, False), ("naive-det", True, False))
for name, det, weighted in CASES:
    runs = []
    for wseed in (0, 1, 2):
        th0, rr = world(wseed)
        lr0 = logp(th0)
        w, l = pairs(lr0, rr, 200, np.random.default_rng(10 + wseed), det)
        th = th0.clone().requires_grad_(True)
        opt = torch.optim.Adam([th], lr=0.01)
        rows = []
        for step in range(max(REC) + 1):
            lq = logp(th)
            z = 0.1 * ((lq[w] - lr0[w]) - (lq[l] - lr0[l]))
            loss = -F.logsigmoid(z).mean() if weighted else -z.mean()
            if step in REC:
                rows.append([kl(lq, lr0), value(lq, rr), entropy(lq),
                             (lq[w] - lr0[w]).mean().item(),
                             (lq[l] - lr0[l]).mean().item(), z.mean().item()])
            opt.zero_grad()
            loss.backward()
            opt.step()
        runs.append(np.array(rows))
    runs = np.array(runs)  # 3 x len(REC) x 6
    m = runs.mean(0)
    print(f"{name}:")
    print("   step     KL   E[r] entropy chosen rejected margin")
    for i, step in enumerate(REC):
        print(f"{step:7d} {m[i, 0]:6.2f} {m[i, 1]:6.2f} {m[i, 2]:7.2f} "
              f"{m[i, 3]:7.1f} {m[i, 4]:8.1f} {m[i, 5]:6.2f}")
    fin = runs[:, -1, :]
    last = ", ".join(f"{v:.2f}" for v in fin[:, 1])
    first = ", ".join(f"{v:.2f}" for v in runs[:, 0, 1])
    print(f"   E[r] per world at step 3000: {last}; "
          f"start: {first}")

Checking the derivation

== 1. Checking the theory (one world: 256 responses, 15 features)
(a) numeric optimum vs closed form: max|pi_num - pi*| = 4.8e-07, J(num) = 1.299248, J(pi*) = 1.299248
(b) partition function cancels: max|p(r) - p(implicit)| = 4.4e-16; B*logZ = 1.2992, r - implicit in [1.2992, 1.2992]
(c) gradient formula vs autograd: max|diff| = 6.1e-18, max|grad| = 0.018
(d) reward + constant: max|pi* change| = 7.6e-17
(e) the two extremes of beta (closed-form optimum):
   beta    KL  E[r] entropy  max prob
    ref  0.00  0.04    5.13     0.027
    100  0.00  0.06    5.13     0.027
     10  0.01  0.24    5.13     0.026
      1  0.58  1.42    4.69     0.037
    0.1  5.97  3.23    0.53     0.833
   0.01  6.54  3.27    0.00     1.000
    max r = 3.27
  • (a) The closed form is the optimum. Without using Eq. 4, L-BFGS optimizes the objective of Eq. 3 directly over the probabilities of the 256 responses; the resulting policy differs from the closed form by at most 4.8e-07, and both reach the objective value 1.299248.
  • (b) The partition function does cancel. The implicit reward βlog⁡(π∗/πref)\beta\log(\pi^*/\pi_{\mathrm{ref}}) differs from the true reward rr by a constant, in the range [1.2992,1.2992][1.2992, 1.2992], which is exactly βlog⁡Z=1.2992\beta\log Z=1.2992; the preference probabilities computed from the true reward and from the implicit reward differ by at most 4.4e-16 over all pairs of responses.
  • (c) The gradient formula is right. The paper’s gradient formula and automatic differentiation differ by at most 6.1e-18 (the largest gradient entry is 0.018).
  • (d) Adding a constant to the reward changes nothing. Adding 3.7 to rr changes the closed-form optimal policy by at most 7.6e-17; this is what “reward equivalence class” in the lemmas means.
  • (e) The two extremes of beta. At beta=100 the KL is 0.00 and the expected reward 0.06, almost the reference policy’s 0.04; at beta=0.01 the policy is fully deterministic (maximum probability 1.000, entropy 0.00) and the expected reward 3.27 equals the maximum reward; the paper’s default beta=0.1 sits in between: KL 5.97, expected reward 3.23, entropy 0.53.

DPO is a Bradley-Terry fit plus the closed form

== 2. DPO is a BT reward fit plus the closed form (1000 pairs)
beta=0.1: max|pi_DPO - pi_RM| = 5.6e-16, loss_DPO = 0.43339334, loss_BT = 0.43339334
beta=1.0: max|pi_DPO - pi_RM| = 2.1e-17, loss_DPO = 0.43339334, loss_BT = 0.43339334

Using the same 1000 preference pairs, one side trains the policy under the DPO loss to convergence, the other fits a linear Bradley-Terry reward model r^=ϕ⋅u\hat r=\phi\cdot u and then takes the closed form π∝πrefexp⁡(r^/β)\pi\propto\pi_{\mathrm{ref}}\exp(\hat r/\beta). The two policies differ by at most 5.6e-16 at beta=0.1 and 2.1e-17 at beta=1.0, and both losses are 0.43339334. Note that in this log-linear family the two are one function written in two parameterizations (u=β(θ−θref)u=\beta(\theta-\theta_{\mathrm{ref}})), so this step checks the derivation and the implementation; it is not an empirical finding. Its use comes next: the frontier below does not need one training run per beta; fit Bradley-Terry once and sweep beta through the closed form.

The frontier: beta and data size

== 3. The reward-KL frontier (true expected reward E[r] and KL)
reference: E[r] = 0.04, max r = 3.27
E[r]: each cell: mean (min-max) over 3 data seeds
beta  optimum in-family n=100           n=1000          n=10000         
0.05     3.27      3.27 2.16 (1.5-2.7)  2.78 (2.5-3.1)  3.08 (3.0-3.1)  
0.1      3.23      3.23 2.18 (1.5-2.7)  2.70 (2.4-2.9)  2.99 (2.9-3.1)  
0.2      3.01      3.07 2.21 (1.7-2.6)  2.54 (2.3-2.7)  2.66 (2.6-2.7)  
0.5      2.06      1.98 1.91 (1.5-2.3)  1.98 (1.9-2.1)  1.87 (1.9-1.9)  
1.0      1.42      1.36 1.42 (1.1-1.7)  1.43 (1.3-1.5)  1.33 (1.3-1.4)  
2.0      0.89      0.86 0.91 (0.7-1.1)  0.92 (0.8-1.0)  0.85 (0.8-0.9)  
KL: each cell: mean (min-max) over 3 data seeds
beta  optimum in-family n=100           n=1000          n=10000         
0.05     6.41      6.41 5.40 (5.1-5.7)  4.91 (4.3-5.5)  5.56 (4.9-6.0)  
0.1      5.97      5.99 5.18 (5.0-5.3)  4.36 (3.8-4.7)  4.91 (4.6-5.2)  
0.2      4.56      4.91 4.38 (4.1-4.8)  3.54 (2.9-4.1)  3.45 (3.4-3.5)  
0.5      1.52      1.46 2.39 (1.4-3.5)  1.62 (1.4-1.9)  1.29 (1.3-1.3)  
1.0      0.58      0.55 1.03 (0.5-1.5)  0.66 (0.6-0.7)  0.52 (0.5-0.5)  
2.0      0.20      0.19 0.34 (0.2-0.5)  0.23 (0.2-0.3)  0.18 (0.2-0.2)  
norm of the fitted BT parameters: 2.81 - 4.35
Preferred-FT (max likelihood on chosen only):
  n=100    KL 0.13 (0.1-0.2), E[r] 0.56 (0.5-0.7)
  n=1000   KL 0.12 (0.1-0.1), E[r] 0.67 (0.6-0.7)
  n=10000  KL 0.11 (0.1-0.1), E[r] 0.66 (0.6-0.7)
control: n=10000, beta=0.5, reward with or without the outside term
  with the term: optimum 2.060, DPO 1.874 (min 1.856, max 1.900)
  without the term: optimum 2.163, DPO 2.132 (min 2.126, max 2.138)

In the tables “optimum” is the closed-form optimal policy for the true reward, “in-family” is the best that the log-linear family can do on the same objective (optimized directly with the true reward), and the last three columns are DPO with 100, 1000 and 10000 preference pairs, each cell the mean over 3 data seeds with the minimum to maximum in brackets.

  • More data gets closer to the upper bound, and the gap is largest at small beta. At beta=0.1 the closed-form optimum has an expected reward of 3.23; 100 pairs give only 2.18 (the three seeds range from 1.5 to 2.7, very noisy), 1000 pairs give 2.70 and 10000 pairs 2.99. At large beta (1.0 and above) the columns nearly coincide: the KL budget is small, the policy moves only near the reference, and errors in the reward estimate matter little.
  • Noise pushes the policy farther without buying more true reward. At beta=0.5 the KL with 100 pairs is 2.39, larger than the optimum’s 1.52, while the expected reward is only 1.91, below the optimum’s 2.06. This is a minimal example of reward over-optimization: the KL budget is spent and the true reward does not follow.
  • Preferred-FT stays near the start. Maximum likelihood on the chosen answers alone gives a KL of 0.11 to 0.13 and an expected reward of 0.56 to 0.67: a little above the reference’s 0.04 and far below DPO’s 2.18 to 2.99 at beta=0.1, because the chosen distribution is only slightly better than the reference distribution. In the paper’s Figure 2 Preferred-FT also sits on the low-KL, low-reward side, but that is IMDb with GPT-2-large and the numbers are not comparable.
  • Even with plenty of data a systematic gap remains. With 10000 pairs and beta=0.5 the three seeds are nearly identical (1.856 to 1.900), with mean 1.874, below the closed-form optimum 2.060; the in-family optimum has an expected reward of 1.98, so the policy family can represent better policies and the problem lies in the reward implied by the preference fit. Control: replace the true reward by a purely linear one without the outside term, and DPO reaches 2.132 (2.126 to 2.138) against an optimum of 2.163, a gap that shrinks to little more than noise. So the gap here comes from a function family that cannot represent the true reward, not from the amount of data.
Lab results: the reward-KL frontier and the training dynamics Left: in the toy world of 256 responses, the true expected reward against KL: the closed-form optimum is the upper bound, DPO approaches it as the preference data grows, and maximum likelihood on the chosen answers barely moves. Right: training dynamics: compared with the naive version without the weight, DPO lets the mean log-ratio of chosen and rejected answers fall more slowly. Reward-KL frontier (β from 2 to 0.05) 0 1 2 3 0 1 2 3 4 5 6 7 KL to the reference (nats) True expected reward E[r] closed-form optimum DPO, 10,000 pairs DPO, 1000 pairs DPO, 100 pairs max likelihood on chosen (×) Training: mean log-ratio log π_θ/π_ref -200 -150 -100 -50 0 0 500 1000 1500 2000 2500 3000 training step mean log-ratio (nats) DPO: chosen DPO: rejected naive: chosen naive: rejected
Figure 2: Results of the lab, taken from the full run above (a toy world; 3 worlds for the dynamics). Left: the frontier swept by β from 2 to 0.05, each point the mean over 3 data seeds. Right: the training dynamics, averaged over 3 worlds.

Training dynamics: the chosen probability falls too

== 4. Dynamics (3 worlds, 200 pairs each, beta=0.1, Adam, 3000 steps)
distinct responses in the pairs (3 worlds): 155, 174, 166
DPO:
   step     KL   E[r] entropy chosen rejected margin
      0   0.00   0.07    5.23     0.0      0.0   0.00
     50   0.44   1.12    4.72    -0.1     -0.9   0.08
    100   1.26   1.79    3.88    -0.8     -2.3   0.15
    200   2.47   2.30    2.70    -2.8     -5.6   0.28
    500   3.89   2.63    1.52    -8.2    -13.9   0.57
   1000   4.93   2.76    0.77   -14.8    -24.0   0.92
   2000   5.35   2.78    0.41   -23.3    -36.9   1.36
   3000   5.42   2.77    0.35   -28.7    -45.2   1.65
   E[r] per world at step 3000: 2.23, 3.22, 2.88; start: 0.04, 0.22, -0.06
DPO-det:
   step     KL   E[r] entropy chosen rejected margin
      0   0.00   0.07    5.23     0.0      0.0   0.00
     50   0.51   1.22    4.61    -0.1     -1.0   0.09
    100   1.50   1.99    3.54    -0.9     -2.6   0.17
    200   2.77   2.49    2.27    -3.0     -6.3   0.33
    500   3.82   2.74    1.38    -8.2    -15.2   0.70
   1000   4.43   3.06    1.10   -14.7    -26.4   1.17
   2000   5.23   3.18    0.47   -26.6    -45.8   1.92
   3000   5.44   3.21    0.27   -36.8    -62.3   2.55
   E[r] per world at step 3000: 2.74, 3.36, 3.53; start: 0.04, 0.22, -0.06
naive:
   step     KL   E[r] entropy chosen rejected margin
      0   0.00   0.07    5.23     0.0      0.0   0.00
     50   0.48   1.14    4.67    -0.1     -0.9   0.08
    100   1.45   1.83    3.60    -1.1     -2.7   0.16
    200   2.96   2.26    1.96    -4.4     -7.5   0.31
    500   4.49   2.32    0.37   -16.5    -24.3   0.78
   1000   4.67   2.32    0.19   -37.7    -53.3   1.56
   2000   4.68   2.32    0.19   -80.0   -111.2   3.12
   3000   4.68   2.32    0.19  -122.3   -169.2   4.68
   E[r] per world at step 3000: 1.77, 2.64, 2.55; start: 0.04, 0.22, -0.06
naive-det:
   step     KL   E[r] entropy chosen rejected margin
      0   0.00   0.07    5.23     0.0      0.0   0.00
     50   0.54   1.24    4.57    -0.1     -1.0   0.09
    100   1.79   2.09    3.21    -1.2     -3.0   0.18
    200   3.47   2.57    1.48    -5.0     -8.7   0.37
    500   4.65   2.61    0.32   -18.6    -27.8   0.91
   1000   4.78   2.61    0.19   -42.0    -60.3   1.83
   2000   4.78   2.61    0.19   -88.8   -125.4   3.66
   3000   4.78   2.61    0.19  -135.6   -190.5   5.48
   E[r] per world at step 3000: 1.77, 3.50, 2.55; start: 0.04, 0.22, -0.06

This part trains in 3 different worlds, each with 200 preference pairs, beta=0.1 and Adam (learning rate 0.01) for 3000 steps; the tables show the mean over the 3 worlds. The chosen and rejected columns are the mean of log⁡πθ/πref\log\pi_\theta/\pi_{\mathrm{ref}} over the training pairs, and margin is the mean implicit reward difference β⋅(chosen−rejected)\beta\cdot(\text{chosen}-\text{rejected}). There are four settings: DPO (Bradley-Terry labels), DPO-det (deterministic labels: the higher reward always wins), and naive and naive-det (the naive version without the weight, which just maximizes the difference of log-ratios). The learning rate and step count were not tuned; the preliminary run used this very set.

  • DPO pushes down the log-probabilities of both the chosen and the rejected answers. At step 3000 the mean log-ratio of the chosen answers is -28.7 and of the rejected -45.2: their difference grows (the margin rises from 0 to 1.65) but both are falling, the rejected ones further. The loss constrains only the difference; nothing in it asks the chosen probability to rise.
  • Where the probability mass goes: the policy collapses onto a few responses. Entropy falls from 5.23 to 0.35 (in nats; two equally likely responses have entropy 0.69) and KL rises to 5.42. The training pairs of the three worlds contain 155, 174 and 166 distinct responses; the policy concentrates its mass on very few of them and pushes the rest, including most of the chosen answers, to nearly zero. This is what likelihood displacement looks like in the toy world; the mechanism in real language models has to be analyzed by the later papers, and this experiment cannot replace them.
  • Expected reward rises, then flattens. In the 3 worlds it goes from the starting points 0.04, 0.22 and -0.06 to 2.23, 3.22 and 2.88, and the mean barely increases after step 1000 (2.76, 2.78, 2.77) while KL and the log-ratios keep drifting. DPO-det with deterministic labels climbs higher (2.74, 3.36, 3.53).
  • The weight helps, but not everywhere. The naive version’s log-ratios are far more extreme (chosen -122.3, rejected -169.2) and its margin climbs to 4.68, yet its expected reward stalls at 2.32 and does not move after step 500; DPO has a margin of only 1.65 and an expected reward of 2.77. World by world, the weighted loss has the higher expected reward in 5 of the 6 cases (3 worlds times two labelings); in the remaining one (world 1 with deterministic labels: 3.36 against 3.50) the naive version is higher, so this is consistent evidence, not a verdict. A larger margin does not mean a better policy.

The limits should be clear: three toy worlds and one set of hyperparameters, no sequence structure, and no check of how robust these phenomena are to the learning rate, beta or the data size; the lab shows the direction of mechanisms, not conclusions about the paper’s experiments.

Questions the paper left open, and what followed

QuestionFollow-upGist
What does the DPO objective assumeAzar et al., 2023, IPORLHF rests on two approximations: pairwise preferences can be replaced by pointwise rewards, and a reward model generalizes to out-of-distribution data sampled by the policy; DPO bypasses the second but not the first. It proposes ΨPO, expressed directly in pairwise preferences, which gives IPO when Ψ is the identity
Reward over-optimizationRafailov et al., 2024, over-optimization in direct alignmentDirect alignment algorithms (DPO included) also degrade at higher KL budgets, often before a single epoch is finished
The chosen probability fallsPal et al., 2024, Smaug; Razin et al., 2024, likelihood displacementThe former shows that the DPO loss can lower the likelihood of the chosen examples as long as the relative probability rises, especially on data with a small edit distance, and proposes DPO-Positive; the latter shows that mass can even flow to answers of the opposite meaning, for instance training a model to prefer No over Never can sharply raise the probability of Yes
Length biasPark et al., 2024, length and qualityFirst study of the length problem in DPO: significant length exploitation, plus a regularization that prevents it
DPO or PPOXu et al., 2024, Is DPO Superior to PPO?The authors argue DPO has fundamental limitations and that a well-tuned PPO leads across their dialogue and code benchmarks; a disputed comparison whose conclusion depends on tuning and the evaluation setup
Dropping the reference modelMeng et al., 2024, SimPOUses the average log-probability of a sequence as the implicit reward, needs no reference model, and adds a target margin to the Bradley-Terry objective

Engineering practice has examples too: in the Llama 3 breakdown DPO masks formatting tokens out of the loss and adds a negative log-likelihood term with coefficient 0.2 on the chosen answers; in the Llama 3 paper’s own words this stabilizes training and prevents the log-probability of the chosen answers from decreasing. Methods built on a reward model, such as Learning to Summarize, face the other half of the problem, generalization and over-optimization of the reward model (see the Learning to Summarize breakdown). For tasks that need online exploration, such as the verifiable rewards of math and code, the mainstream is PPO variants and GRPO (see the DeepSeekMath breakdown).

What to take from this paper

  1. One objective, two routes. KL-constrained reward maximization can be solved by first learning a reward and then running reinforcement learning, or by using the closed-form optimal policy to replace the reward by a policy log-ratio and learning the policy directly. Checks (a) to (d) are the links of that chain.
  2. The cancellation of the partition function is the key to the whole paper. Bradley-Terry depends only on a difference of rewards, so the intractable Z(x)Z(x) disappears; that is also why DPO needs only preference pairs, not absolute rewards.
  3. Beta is the knob. It is not a learning rate but the position of the trade-off between reward and KL: a large beta leaves the policy in place, a small one collapses it; in the frontier figure a sweep of beta over one dataset draws the whole curve.
  4. The implicit reward is not a free lunch. DPO removes the reward model but not the problems of a reward model: noise, misspecification, over-optimization and biases in the preference data all carry over. Falling chosen probabilities and a collapsing policy in the dynamics are the questions to carry when reading the DPO paper.
  5. The paper’s experiments are GPT-4 and human evaluations up to 6B. They show that DPO matches or beats PPO on these tasks; larger models, longer training and well-tuned PPO have since given different comparisons, and the conclusions have to be read within their settings.

Further reading

FAQ

What is DPO (Direct Preference Optimization)?
DPO aligns a language model using only preference pairs (a chosen and a rejected answer to the same prompt). It trains the policy directly with a loss similar to binary cross-entropy, relative to a frozen reference model. It optimizes the same objective as RLHF (reward maximization with a KL constraint) but needs neither a separate reward model nor sampling from the policy inside the training loop.
How is DPO different from RLHF with PPO? Is DPO not reinforcement learning?
The objective is the same; the route differs. RLHF first trains a reward model on preference data and then runs PPO under a KL penalty. DPO uses the fact that the KL-constrained objective has a closed-form optimal policy, writes the reward as a log-ratio between the policy and the reference model, and turns preference learning into a supervised loss on a fixed dataset. It therefore drops the sampling and exploration half of reinforcement learning and can only learn from existing preference data; tasks that need online exploration, such as math and code with verifiable rewards, still use PPO, GRPO and similar methods.
How should I choose beta in DPO?
Beta sets how far the policy may move from the reference model: a larger beta keeps it closer, a smaller beta lets it chase reward harder and overfit the preference data more easily. The paper defaults to 0.1 and uses 0.5 for TL;DR summarization. In this post's toy experiment the policy barely moves at beta=100 and collapses to an almost deterministic output at beta=0.01, so start near 0.1 and tune against a held-out evaluation that tracks quality, length and output diversity.
Why does the probability of the chosen answer sometimes fall during DPO training?
The DPO loss only looks at the difference between the chosen and rejected log-probabilities; nothing in it asks the chosen probability to rise. When the two answers are similar, for example when their edit distance is small, probability mass can leave both of them for other answers. Smaug (Pal et al., 2024) and Razin et al. (2024) analyze this; Llama 3 adds a negative log-likelihood term with coefficient 0.2 on the chosen answers to its DPO loss to stabilize it. The toy experiment below shows the same direction.
What data does DPO need, and when is it not enough?
It needs triples of prompt, chosen and rejected answers, plus a reference model that is usually the starting SFT model; the preference data should come from a distribution close to the reference model. DPO is not enough when labels are noisy or vague, when you need an explicit controllable reward signal, or when you need online exploration on verifiable rewards. It also learns biases in the data, such as a preference for long answers, which need countermeasures like length control.