Skip to content
Post-training and alignment Advanced 33 min read

DPO and direct preference optimisation

The RLHF objective has a closed-form optimum, and inverting it expresses the reward in terms of the policy. Substitute that into the Bradley–Terry loss and the reward model, the sampling and the RL loop all disappear: what is left is a logistic-regression loss on how much more the model has raised the chosen answer's probability than the rejected one's, relative to a frozen reference. That is Direct Preference Optimisation. The idea to keep: DPO optimises the same target as PPO, but only on the answers in your dataset, and most of its failure modes come from that "only".

10,000 ft

By 2023 the RLHF recipe worked but was expensive and fragile: four models, generation inside the training loop, and dozens of implementation details. Rafailov et al. showed that the same KL-regularised objective can be optimised with a single supervised loss on preference pairs (Rafailov et al., 2023), and the paper's subtitle, Your Language Model is Secretly a Reward Model, names the trick. DPO made preference tuning accessible to anyone who could run SFT. It produced Zephyr and Tülu 2 within months, and Meta used it for Llama 3 (Llama 3, 2024). A family of variants followed (IPO, KTO, ORPO, SimPO), each fixing one weakness. It sits between reward models, whose loss it borrows, and PPO, whose objective it solves. For reasoning, where answers can be checked, the field moved on to online RL with verifiable rewards.

2,000 ft

Start from an SFT model and freeze a copy as the reference. For each preference pair \((x, y_w, y_l)\), compute four log-probabilities: chosen and rejected, under the policy and the reference. The implicit reward of an answer is \(\beta\) times how much the policy has raised its log-probability above the reference. Train with \(-\log\sigma(\text{implicit reward of } y_w - \text{implicit reward of } y_l)\): exactly the reward-model loss, with the policy playing the reward model. Each step pushes the chosen answer up and the rejected one down, weighted by how wrongly the pair is currently ranked. One to three epochs, a learning rate typically \(10^{-7}\) to \(10^{-6}\) in open recipes, \(\beta\) around 0.1.

DPO: one loss, two models, no sampling
DPO: one loss, two models, no sampling. Preference pairs (x, y_w, y_l), Policy π_θ (trained, starts as SFT), Reference π_ref (frozen SFT), Log-ratios log π_θ/π_ref for y_w and y_l, Logistic loss -log σ(β·(ratio_w - ratio_l)), gradientDPO: one loss, two models, no sampling. Preference pairs (x, y_w, y_l), Policy π_θ (trained, starts as SFT), Reference π_ref (frozen SFT), Log-ratios log π_θ/π_ref for y_w and y_l, Logistic loss -log σ(β·(ratio_w - ratio_l)), gradient

Ground level

The trick in one paragraph

The RLHF page showed that maximising \(\mathbb{E}[r] - \beta\,\mathrm{KL}(\pi\,\|\,\pi_{\text{ref}})\) has the solution \(\pi^*(y\mid x) = \pi_{\text{ref}}(y\mid x)\,e^{r(x,y)/\beta}/Z(x)\). Read it backwards: if you knew the optimal policy, you could recover the reward, \(r(x,y) = \beta\log\frac{\pi^*(y\mid x)}{\pi_{\text{ref}}(y\mid x)} + \beta\log Z(x)\). The awkward term \(Z(x)\), a sum over every possible response, depends only on the prompt. The Bradley–Terry model only ever uses the difference of two rewards for the same prompt, so \(Z(x)\) cancels. Therefore you can parameterise the reward by the policy itself and fit it to the comparisons by maximum likelihood. Whatever policy fits the data best is, by construction, the optimal policy for the reward that best explains the data.

The DPO derivation in four moves
The DPO derivation in four moves. KL-regularised RLHF objective, Closed-form optimum π* ∝ π_ref·exp(r/β), Invert it r = β log π*/π_ref + β log Z, Plug into Bradley-Terry Z cancels in r_w - r_l, DPO loss on π_θ logistic regressionThe DPO derivation in four moves. KL-regularised RLHF objective, Closed-form optimum π* ∝ π_ref·exp(r/β), Invert it r = β log π*/π_ref + β log Z, Plug into Bradley-Terry Z cancels in r_w - r_l, DPO loss on π_θ logistic regression

The loss:

\[ \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]. \]

What the gradient does, with numbers

Define the implicit reward \(\hat r_\theta(x,y) = \beta\log\frac{\pi_\theta(y\mid x)}{\pi_{\text{ref}}(y\mid x)}\) and the margin \(m = \hat r_\theta(x,y_w) - \hat r_\theta(x,y_l)\). The gradient is

\[ \nabla_\theta\mathcal{L}_{\text{DPO}} = -\beta\,\mathbb{E}\Big[\underbrace{\sigma(-m)}_{\text{how wrong}}\big(\underbrace{\nabla_\theta\log\pi_\theta(y_w\mid x)}_{\text{raise chosen}} - \underbrace{\nabla_\theta\log\pi_\theta(y_l\mid x)}_{\text{lower rejected}}\big)\Big]. \]

The weight \(\sigma(-m)\) is the model's current probability of ranking the pair wrongly. Rafailov et al. found it essential: "a naïve version of this method without the weighting coefficient can cause the language model to degenerate". Without it, every pair is pushed apart forever, including pairs already ranked correctly by a wide margin.

A worked example with \(\beta = 0.1\). Sequence log-probabilities are sums over tokens, so they are large negative numbers:

\(\log\pi_\theta\) \(\log\pi_{\text{ref}}\) log-ratio implicit reward
chosen \(y_w\) −42.0 −43.0 +1.0 +0.10
rejected \(y_l\) −50.5 −50.0 −0.5 −0.05

The margin is \(m = 0.15\), the loss \(-\log\sigma(0.15) = 0.621\), and the pair's gradient weight \(\sigma(-0.15) = 0.463\): nearly half strength, because a margin of 0.15 is barely a decision. Had the model ranked the pair the wrong way with \(m = -0.30\), the loss would be 0.854 and the weight 0.574. At \(m = 2\) the loss is 0.127 and the weight 0.119: well-separated pairs stop contributing.

Notice what the numbers do not say: the absolute log-probability of the chosen answer. Only its change relative to the reference, and only relative to the rejected answer's change. Both could go down. That is the root of DPO's most surprising failure mode, below.

What β does

In RLHF, \(\beta\) is the price of KL. In DPO it plays the same role, seen differently: it is the scale that converts log-ratios into rewards. A small \(\beta\) means a large log-ratio is needed for a given reward margin, so the policy moves further from the reference to fit the same data; a large \(\beta\) keeps it close. The original paper used \(\beta = 0.1\) for dialogue and 0.5 for TL;DR summarisation, with RMSprop, a learning rate of \(10^{-6}\), batch size 64 and 150 warm-up steps. Llama 3 used \(\beta = 0.1\). Tülu 3 used a length-normalised variant (below) for which the equivalent setting is \(\beta = 5\), with learning rates of \(5\times10^{-7}\) (8B) and \(2\times10^{-7}\) (70B), batch size 128 and one epoch (Lambert et al., 2024, table 20). Most open recipes use learning rates one to two orders of magnitude below SFT's; Llama 3, which reports \(10^{-5}\) together with an NLL term, is an exception.

Does it work?

On the paper's own tasks, DPO matched or beat PPO. On TL;DR summarisation, with GPT-4 as judge, "DPO has a win rate of approximately 61% at a temperature of 0.0, exceeding the performance of PPO at 57%"; on Anthropic's helpful-harmless dialogue, DPO was the only method in their comparison to improve over the dataset's chosen responses. In practice it made open preference tuning routine:

  • Zephyr-7B (October 2023) applied DPO to UltraFeedback's GPT-4-ranked pairs and, on MT-Bench, surpassed Llama 2-Chat-70B, "the best open-access RLHF-based model", with no human annotation (Tunstall et al., 2023).
  • Tülu 2+DPO 70B (November 2023) was described as "the largest DPO-trained model to date" (Ivison et al., 2023).
  • Llama 3 (2024) used SFT, rejection sampling and DPO, after finding that PPO needed more compute at scale and that DPO "performed better, especially on instruction following benchmarks like IFEval".
  • Tülu 3 (2024) used length-normalised DPO in its SFT → DPO → RLVR pipeline.

But controlled comparisons that tune both methods well tend to favour online RL: PPO beat DPO "by up to 2.5% in math and 1.2% in general domains" in Ivison et al.'s study (2024), and Xu et al. found PPO ahead in all their benchmarks and traced DPO's weakness to distribution shift (2024). The reasons are the failure modes that follow.

Failure mode 1: it only sees the data

PPO samples from the current policy and the reward model scores whatever comes out. DPO only ever evaluates the answers in the dataset. Its loss says nothing about responses that are in neither the chosen nor the rejected set, so probability mass can flow to them freely, including to responses nobody would prefer. Xu et al. showed that DPO "might find biased solutions that exploit out-of-distribution responses", and that its performance depends strongly on the gap between the model's own outputs and the preference data.

The fix is to make the data look like the policy. Tajwar et al. found that "approaches that use on-policy sampling or attempt to push down the likelihood on certain responses … outperform offline and maximum likelihood objectives" (Tajwar et al., 2024). Tülu 3 found that including on-policy pairs (one response from its own SFT model) improved DPO over a purely off-policy dataset. Which leads to:

Online and iterative DPO. Sample pairs from the current model, label them (with people, a reward model, or an LLM judge), train with DPO, and repeat. Online AI feedback does it every iteration (Guo et al., 2024); iterative DPO under a KL constraint has a theoretical analysis (Xiong et al., 2023); Llama 3 trained each round's DPO on "the most recent batches of preference data collected using the best performing models from the previous alignment rounds"; Self-Rewarding Language Models had the model judge its own samples via LLM-as-a-judge prompting across three rounds of iterative DPO (Yuan et al., 2024). Iterative DPO is a slow-motion, batched version of online RL.

Failure mode 2: deterministic preferences, unbounded margins

Bradley–Terry turns a preference probability into a reward gap: 80% becomes a gap of \(\log 4 = 1.39\). But if every label in the data says A beats B, the maximum-likelihood gap is infinite. Azar et al. pointed out that with the explicit RLHF pipeline the reward model is in practice underfitted and regularised, which keeps the gap finite, while DPO, fitting the policy directly, drives \(\pi(y_l) \to 0\) "irrespective of what constant τ is used for the KL-regularisation" (Azar et al., 2023). The KL leash, which is the whole point of the objective, stops working on exactly the pairs where the data is most confident, and with small datasets almost every pair looks confident.

Two fixes, both simple:

  • IPO replaces the logistic loss with a squared loss that regresses the log-ratio gap to a finite target, \(1/(2\tau)\). The optimum stays a bounded distance from the reference however deterministic the data.
  • Conservative DPO (cDPO) assumes labels are flipped with probability \(\varepsilon\) and uses label smoothing: the target probability is \(1-\varepsilon\) instead of 1, so the optimal margin is \(\log\frac{1-\varepsilon}{\varepsilon}\), finite (Mitchell, 2023).

The second program in Build it shows all three on a single pair: DPO sends the loser's probability to zero at any \(\beta\), cDPO stops at 0.10 and IPO at 0.38.

Failure mode 3: the chosen answer gets less likely

Because DPO only constrains the difference of two log-ratios, it is satisfied when both fall, as long as the rejected one falls faster. This happens routinely. Pal et al. showed theoretically that "the standard DPO loss can lead to a reduction of the model's likelihood of the preferred examples", especially when the two responses differ by only a few tokens, and proposed DPO-Positive, which adds a penalty whenever the chosen log-probability drops below the reference (Pal et al., 2024).

Where does the mass go? To other responses, sometimes ones nobody wanted. Razin et al. call this likelihood displacement: training a model to prefer "No" over "Never" can sharply increase the probability of "Yes", because "No" and "Never" have nearly identical hidden representations and the gradient that separates them points somewhere else entirely. In a safety experiment, DPO on refusal preferences reduced Llama-3-8B-Instruct's refusal rate on unsafe prompts "from 74.4% to 33.4%"; their centred hidden-embedding similarity (CHES) score identifies the training pairs responsible, and filtering them out fixed it (Razin et al., 2024). The third program in Build it reproduces the mechanism in two dimensions.

The standard practical defence is to add the SFT loss on the chosen answer. Iterative Reasoning Preference Optimisation found the extra negative log-likelihood term "crucial" (Pang et al., 2024), and Llama 3 adds it with coefficient 0.2 "to stabilize DPO training by maintaining desired formatting for generation and preventing the decrease of log probability of chosen responses".

Failure mode 4: length

The DPO margin is a difference of sequence log-probabilities, which scale with length, and preference data usually favours longer answers. DPO models therefore lengthen their outputs. Park et al. showed "significant exploitation" of length in DPO and a regulariser that gave "up to 20% improvement in win rates when controlling for length" (Park et al., 2024). The popular fix is to normalise by length: SimPO and Tülu 3's length-normalised DPO both divide each log-probability by the number of tokens.

Failure mode 5: shared tokens

Llama 3 reported that chat-template tokens appearing in both chosen and rejected answers (headers, end-of-turn) destabilised DPO, causing "tail repetition or abruptly generating termination tokens", because "the model needs to increase and reduce the likelihood of these tokens simultaneously". They masked those tokens out of the loss. The general lesson: a contrastive loss on near-identical sequences spends its gradient on the few tokens that differ and does unpredictable things to the ones that do not.

The family

The direct-alignment family, by the problem each variant fixes
The direct-alignment family, by the problem each variant fixes. DPO (2023) Bradley-Terry on log-ratios, IPO squared loss, bounded margin, cDPO label smoothing, KTO unpaired good/bad labels, SimPO, length-normalised DPO average log-probability, ORPO SFT + odds ratio, no reference, DPO + NLL (RPO, Llama 3), Online / iterative DPO fresh on-policy pairs, overfitting, noisy labels, data format, length,The direct-alignment family, by the problem each variant fixes. DPO (2023) Bradley-Terry on log-ratios, IPO squared loss, bounded margin, cDPO label smoothing, KTO unpaired good/bad labels, SimPO, length-normalised DPO average log-probability, ORPO SFT + odds ratio, no reference, DPO + NLL (RPO, Llama 3), Online / iterative DPO fresh on-policy pairs, overfitting, noisy labels, data format, length,
Method Loss on a pair (or a single answer) What it changes Reference model?
DPO (2023) \(-\log\sigma(\beta\,\Delta)\), with \(\Delta\) the difference of log-ratios — Yes
cDPO (2023) \(-(1-\varepsilon)\log\sigma(\beta\Delta) - \varepsilon\log\sigma(-\beta\Delta)\) Finite optimum under label noise Yes
IPO (2023) \(\big(\Delta - \tfrac{1}{2\tau}\big)^2\) Bounded margin; no overfitting to deterministic labels Yes
KTO (2024) \(\lambda_y - v(x,y)\), \(v = \lambda\,\sigma(\pm\beta(\hat r - z_0))\) per answer Needs only "good"/"bad" labels, not pairs; prospect-theory value Yes
SimPO (2024) \(-\log\sigma\big(\tfrac{\beta}{\lvert y_w\rvert}\log\pi_\theta(y_w) - \tfrac{\beta}{\lvert y_l\rvert}\log\pi_\theta(y_l) - \gamma\big)\) Average log-probability as reward; target margin \(\gamma\) No
Length-normalised DPO (Tülu 3) DPO with each log-ratio divided by its length Removes length incentive Yes
ORPO (2024) \(\mathcal{L}_{\text{SFT}} + \lambda\big(-\log\sigma(\log\tfrac{\text{odds}(y_w)}{\text{odds}(y_l)})\big)\) SFT and preference in one stage No
DPO + NLL (RPO, Llama 3) DPO \(+\ \alpha\cdot(-\log\pi_\theta(y_w))\) Keeps the chosen answer likely Yes
SLiC-HF (2023) Hinge loss on sequence log-likelihoods, plus a regulariser Calibration view; predates DPO Optional

Notes on the claims that come with them. KTO "matches or exceeds the performance of preference-based methods at scales from 1B to 30B", and its authors also found it could match DPO "while using up to 90% fewer desirable examples". SimPO reported gains of "up to 6.4 points on AlpacaEval 2 and … up to 7.5 points on Arena-Hard" over DPO, recommending \(\beta\) between 2.0 and 2.5 and \(\gamma\) between 0.5 and 1.5. ORPO trains from a base model in one stage with no reference model. The Tülu 3 team, testing on their own pipeline, found only length-normalised DPO beat their baseline, with SimPO and plain DPO behind it. The pattern across papers is consistent: every variant wins in its own paper, gains shrink in independent comparisons, and data quality moves results more than the choice of loss.

History

  • May 2023. SLiC-HF (Zhao et al.) and DPO (Rafailov et al.) both propose learning from preferences without RL. DPO's derivation, and its "secretly a reward model" framing, win the field's attention.
  • October 2023. Zephyr-7B shows DPO on AI-ranked data can beat a 70B RLHF model on MT-Bench. IPO diagnoses DPO's overfitting to deterministic preferences.
  • November 2023. Tülu 2+DPO 70B; cDPO note on noisy labels.
  • 2024. KTO, ORPO, SimPO, DPO-Positive, R-DPO; likelihood displacement is characterised; iterative and online DPO become standard; Llama 3 ships with DPO; From r to Q* shows DPO can be derived in the token-level MDP, so its log-ratios carry per-token credit (Rafailov et al., 2024). Careful comparisons (Ivison et al., Xu et al.) find well-tuned online RL ahead of DPO.
  • 2025–2026. With reasoning models trained by RL on verifiable rewards, DPO settles into its niche: a cheap, stable stage for style, chat quality and safety preferences, often run before or between online RL stages, as in Tülu 3's SFT → DPO → RLVR pipeline.

In practice

  • Start from a good SFT model and use it as the reference. DPO assumes the reference produced (or could have produced) the data. If the pairs come from a very different model, run SFT on the chosen answers first, as the DPO paper recommends when no reference is available.
  • Prefer on-policy pairs. Sample two or more answers from your SFT model and have them ranked; mix in off-policy pairs for coverage. Iterate if you can afford it.
  • Watch four numbers, as TRL and most libraries log them: the chosen and rejected implicit rewards, the margin, and pair accuracy. Accuracy that climbs to near 100% early means overfitting; a falling chosen reward means displacement, so add an NLL term or check for near-duplicate pairs.
  • Clean the pairs. Drop pairs whose answers are near-identical (they drive displacement) and pairs where the label is a coin flip (they are noise). Cap or normalise length.
  • Mask what both answers share: template tokens, and shared prefixes if the pair diverges late.
  • Precompute reference log-probabilities once; then DPO costs about as much as SFT on the same tokens, twice (chosen and rejected).
  • Evaluate with generations, not the training loss: a judge model or people, with length controlled (for example AlpacaEval's length-controlled win rate).

How this shows up in Jarvis

In a product like Jarvis, an assistant over a financial-planning engine, preference tuning is the natural tool for how things are said: preferring an answer that states the engine's number and its assumptions over one that hedges or lectures, or a clear "here are your options" over a recommendation. DPO fits that kind of stylistic preference well, because the pairs can be built from the model's own drafts. What it must not be asked to do is make numbers right; in Jarvis the engine computes and the model explains, which is the same division of labour as RLVR's "use a checker where one exists". See the Jarvis case study.

Common misconceptions

  • "DPO doesn't use a reward model." It uses an implicit one, \(\beta\log\frac{\pi_\theta}{\pi_{\text{ref}}}\), trained with the reward-model loss. You can read rewards out of a DPO model, and RewardBench evaluates DPO models as reward models.
  • "DPO is RL-free, so it can't overoptimise." It overfits instead: to deterministic labels, to length, and to out-of-distribution responses the data never covered. Different symptoms, same root: a finite, biased preference dataset.
  • "Lower DPO loss means a better model." The loss can fall while the chosen answer's probability falls too. Track generations.
  • "DPO and PPO find the same policy." Only in the limit of complete data covering everything the policy might say. With finite data DPO's optimum is a policy that fits the observed pairs; outside them it is unconstrained, while PPO's samples keep testing the whole policy against the reward model.
  • "The reference model is optional." For DPO it is the leash and the baseline; removing it (ORPO, SimPO) needs a replacement: an SFT term, length normalisation and a margin.

First principles

What DPO assumes. Three things, each of which can fail. (1) Preferences follow Bradley–Terry with some reward. (2) The optimal policy for that reward is the KL-regularised one with this reference. (3) The data covers the responses that matter. Under (1) and (2), any reward function can be written as \(\beta\log\frac{\pi(y\mid x)}{\pi_{\text{ref}}(y\mid x)}\) plus a function of \(x\) alone; Rafailov et al. prove that this reparameterisation loses no generality (their theorem 1), because the per-prompt term is exactly the freedom Bradley–Terry cannot see. So DPO does not restrict which rewards can be learned. What it restricts is where the reward is checked: only on the answers in the dataset. (3) is the assumption that fails in practice.

Why the softmax normaliser cancels. In the tabular case of Build it, the gradient of \(\log\pi_\theta(y_w) - \log\pi_\theta(y_l)\) with respect to the logits is \(e_{y_w} - e_{y_l}\): the log-sum-exp terms are identical for both answers and cancel. DPO does not directly push probability anywhere except onto \(y_w\) and off \(y_l\). In a real network, though, the logits of all answers share parameters, so moving those two moves everything else too, in directions set by the geometry of the representations. That is why likelihood displacement exists, and why it is governed by how similar the chosen and rejected representations are.

Offline versus online, as an information argument. A preference pair carries at most one bit about two specific answers. PPO and online DPO spend their compute generating new answers and asking about those, so information arrives where the policy is currently putting its mass. Offline DPO's information is fixed at data-collection time, so as the policy moves, a growing share of its probability lies on answers the data says nothing about. The longer you train offline, the more the policy's behaviour is determined by the inductive biases of the network rather than by the preferences. Short training, low learning rates and on-policy data are all ways of keeping the policy where the data is.

Is DPO secretly doing RL? In a sense. Rafailov et al. later showed DPO can be derived in the token-level MDP as "a general inverse Q-learning algorithm", so the per-token log-ratios of a DPO model behave like an optimal advantage function and can assign credit within a response (Rafailov et al., 2024). What DPO lacks is not the RL objective but RL's data collection.

The maths

Notation. Prompt \(x\); chosen and rejected answers \(y_w, y_l\); policy \(\pi_\theta\); reference \(\pi_{\text{ref}}\); implicit reward \(\hat r_\theta(x,y) = \beta\log\frac{\pi_\theta(y\mid x)}{\pi_{\text{ref}}(y\mid x)}\); log-ratio difference \(h_\theta = \log\frac{\pi_\theta(y_w)}{\pi_{\text{ref}}(y_w)} - \log\frac{\pi_\theta(y_l)}{\pi_{\text{ref}}(y_l)}\), so the DPO margin is \(\beta h_\theta\).

Derivation: the DPO loss from the RLHF objective

Step 1, the optimum. For each \(x\), \(\max_\pi \mathbb{E}_{y\sim\pi}[r(x,y)] - \beta\,\mathrm{KL}(\pi\|\pi_{\text{ref}})\) is solved by \(\pi_r(y\mid x) = \pi_{\text{ref}}(y\mid x)\exp(r(x,y)/\beta)/Z(x)\), with \(Z(x) = \sum_y \pi_{\text{ref}}(y\mid x)\exp(r(x,y)/\beta)\) (derived on the RLHF page).

Step 2, invert. Take logs and rearrange:

\[ r(x,y) = \beta\log\frac{\pi_r(y\mid x)}{\pi_{\text{ref}}(y\mid x)} + \beta\log Z(x). \]

Step 3, substitute into Bradley–Terry. \(P(y_w\succ y_l\mid x) = \sigma(r(x,y_w) - r(x,y_l))\), and the \(\beta\log Z(x)\) terms cancel:

\[ P(y_w\succ y_l\mid x) = \sigma\Big(\beta\log\frac{\pi_r(y_w\mid x)}{\pi_{\text{ref}}(y_w\mid x)} - \beta\log\frac{\pi_r(y_l\mid x)}{\pi_{\text{ref}}(y_l\mid x)}\Big). \]

Step 4, maximum likelihood over policies. Replace \(\pi_r\) by a parameterised \(\pi_\theta\) and minimise the negative log-likelihood of the observed preferences: that is \(\mathcal{L}_{\text{DPO}}\). If \(\pi_\theta\) is the maximiser, the reward \(\hat r_\theta = \beta\log\frac{\pi_\theta}{\pi_{\text{ref}}}\) is the maximum-likelihood reward (within the equivalence class Bradley–Terry can identify) and \(\pi_\theta\) is its KL-regularised optimal policy, by step 1 read forwards.

Derivation: the DPO gradient

With \(m = \beta h_\theta\) and \(\frac{d}{dm}\big[-\log\sigma(m)\big] = -\sigma(-m)\),

\[ \nabla_\theta\mathcal{L}_{\text{DPO}} = -\,\mathbb{E}\big[\sigma(-m)\,\beta\,\nabla_\theta h_\theta\big] = -\beta\,\mathbb{E}\Big[\sigma(-m)\big(\nabla_\theta\log\pi_\theta(y_w\mid x) - \nabla_\theta\log\pi_\theta(y_l\mid x)\big)\Big], \]

because \(\pi_{\text{ref}}\) does not depend on \(\theta\). Since \(\log\pi_\theta(y\mid x) = \sum_t\log\pi_\theta(y_t\mid x, y_{<t})\), each gradient is a sum of per-token gradients, so DPO is "SFT on the chosen answer minus SFT on the rejected answer, each weighted by \(\beta\sigma(-m)\)". Compare the reward-model gradient on the reward model page: identical, with \(\hat r_\theta\) in place of \(r_\phi\).

Derivation: why IPO's target is 1/(2τ), and cDPO's optimum

Azar et al. define \(\Psi\)PO: maximise \(\mathbb{E}[\Psi(p(y\succ y'))] - \tau\,\mathrm{KL}\) for a non-decreasing \(\Psi\). With \(\Psi(q) = \log\frac{q}{1-q}\) (the logit) you recover RLHF/DPO; with \(\Psi\) the identity you get IPO. Its empirical loss, for a pair where \(y_w\) won, reduces to

\[ \mathcal{L}_{\text{IPO}} = \Big(h_\theta - \frac{1}{2\tau}\Big)^2 , \]

a regression of the log-ratio gap \(h_\theta\) onto \(1/(2\tau)\). When the same pair appears with both labels, the targets average, giving a gap proportional to the empirical preference difference. A finite target means a finite departure from the reference, however deterministic the labels. Note \(\tau\) multiplies the KL; there is no separate \(\beta\).

For cDPO with smoothing \(\varepsilon\), the loss \(-(1-\varepsilon)\log\sigma(m) - \varepsilon\log\sigma(-m)\) has derivative \(\sigma(m) - (1-\varepsilon)\) in \(m\), zero at \(\sigma(m) = 1-\varepsilon\), i.e. \(m^* = \log\frac{1-\varepsilon}{\varepsilon}\): 2.197 for \(\varepsilon = 0.1\).

Plackett–Luce DPO. For a ranking of \(K\) answers \(y_{\tau(1)}\succ\dots\succ y_{\tau(K)}\), the same substitution in the Plackett–Luce model gives

\[ \mathcal{L} = -\,\mathbb{E}\Big[\sum_{k=1}^{K}\log\frac{\exp\big(\hat r_\theta(x, y_{\tau(k)})\big)}{\sum_{j=k}^{K}\exp\big(\hat r_\theta(x, y_{\tau(j)})\big)}\Big], \]

and again the partition function cancels within each prompt.

SimPO (no reference): with \(|y|\) the length in tokens and target margin \(\gamma\),

\[ \mathcal{L}_{\text{SimPO}} = -\log\sigma\Big(\frac{\beta}{|y_w|}\log\pi_\theta(y_w\mid x) - \frac{\beta}{|y_l|}\log\pi_\theta(y_l\mid x) - \gamma\Big). \]

KTO (single answers labelled desirable or undesirable): with \(\hat r = \log\frac{\pi_\theta(y\mid x)}{\pi_{\text{ref}}(y\mid x)}\) and a reference point \(z_0 = \mathrm{KL}(\pi_\theta(y'\mid x)\,\|\,\pi_{\text{ref}}(y'\mid x))\) estimated from the batch (and not differentiated through),

\[ \mathcal{L}_{\text{KTO}} = \mathbb{E}\big[\lambda_y - v(x,y)\big],\qquad v(x,y) = \begin{cases}\lambda_D\,\sigma\big(\beta(\hat r - z_0)\big) & y \text{ desirable}\\ \lambda_U\,\sigma\big(\beta(z_0 - \hat r)\big) & y\text{ undesirable.}\end{cases} \]

Build it

First, DPO on the five-answer toy from the RLHF page. Labellers follow Bradley–Terry with exactly the reward the reward model learned there. DPO never sees that reward; it sees only 40,000 labelled pairs sampled from the SFT model. Does it land on the same \(\pi^*\) that PPO did? (NumPy):

import numpy as np
rng = np.random.default_rng(0)
# Same five styles as the RLHF page. Labellers are Bradley-Terry with utility r_true,
# which is exactly what the reward model learned there. DPO never sees r_true.
styles = ["concise", "rambling", "wrong", "refuses", "flatters"]
r_true = np.array([0.549, 0.440, -3.322, -2.041, 1.2])
pi_ref = np.array([0.54, 0.30, 0.10, 0.05, 0.01])
beta = 0.5

a, b = rng.choice(5, 40000, p=pi_ref), rng.choice(5, 40000, p=pi_ref)   # pairs from SFT
keep = a != b; a, b = a[keep], b[keep]
a_wins = rng.random(len(a)) < 1 / (1 + np.exp(-(r_true[a] - r_true[b])))
w, l = np.where(a_wins, a, b), np.where(a_wins, b, a)                    # chosen, rejected

theta = np.log(pi_ref).copy()                     # policy logits, start at the reference
log_pi = lambda th: th - np.log(np.exp(th).sum())
for step in range(4000):
    lr_ratio = log_pi(theta) - np.log(pi_ref)     # log pi/pi_ref for every answer
    h = beta * (lr_ratio[w] - lr_ratio[l])        # implicit reward margin
    coef = beta * (1 - 1 / (1 + np.exp(-h)))      # sigma(-h) * beta: weight of each pair
    g = np.zeros(5)                               # dLoss/dtheta (log-sum-exp terms cancel)
    np.add.at(g, w, -coef); np.add.at(g, l, coef)
    theta -= 2.0 * g / len(w)
    if step in (0, 99, 999, 3999):
        h = beta * (lr_ratio[w] - lr_ratio[l])
        print(f"step {step+1:4d}  loss {np.mean(np.log1p(np.exp(-h))):.4f}"
              f"  pair accuracy {np.mean(h > 0):.3f}")
pi = np.exp(log_pi(theta))
target = pi_ref * np.exp(r_true / beta); target /= target.sum()
print("DPO policy       ", np.round(pi, 3))
print("RLHF optimum pi* ", np.round(target, 3))
implicit = beta * (log_pi(theta) - np.log(pi_ref))
print("implicit reward  ", np.round(implicit - implicit[0], 3))
print("true reward      ", np.round(r_true - r_true[0], 3))
step    1  loss 0.6931  pair accuracy 0.000
step  100  loss 0.4771  pair accuracy 0.708
step 1000  loss 0.4654  pair accuracy 0.717
step 4000  loss 0.4654  pair accuracy 0.717
DPO policy        [0.67  0.292 0.    0.    0.038]
RLHF optimum pi*  [0.66  0.295 0.    0.    0.045]
implicit reward   [ 0.    -0.12  -3.79  -2.62   0.556]
true reward       [ 0.    -0.109 -3.871 -2.59   0.651]

(Accuracy is 0 at step 1 because every margin is exactly zero: policy equals reference.) DPO recovers the RLHF optimum up to sampling noise, and its implicit reward recovers the labellers' utility, up to a constant, without ever training a reward model: the paper's title, in five numbers. The noisiest estimate is the rare "flatters" answer (0.556 against 0.651), because only about 2% of pairs contain it. That is failure mode 1 in miniature: DPO knows least where the data is thinnest.

Second, deterministic preferences. One pair, A always beats B, reference 50/50 (NumPy):

import numpy as np
# Two answers, reference 50/50, and a dataset where A beat B every time it was compared
# (true preference might be 0.8; with few labels the empirical one is 1.0).
sig = lambda z: 1 / (1 + np.exp(-z))
def train(loss, steps, lr=0.5):
    d = 0.0                                   # d = log pi(A)/pi(B) - log ref(A)/ref(B)
    for _ in range(steps):
        d -= lr * loss(d)                     # loss(d) returns dLoss/dd
    return d
losses = {
    "DPO  beta=0.1":            lambda d: -0.1 * sig(-0.1 * d),
    "DPO  beta=1.0":            lambda d: -1.0 * sig(-1.0 * d),
    "cDPO beta=1, eps=0.1":     lambda d: -1.0 * (0.9 - sig(1.0 * d)),   # label smoothing
    "IPO  tau=1":               lambda d: 2 * (d - 1 / (2 * 1.0)),        # (d - 1/(2 tau))^2
}
print(f"{'':24s}" + "".join(f"{n:>12d}" for n in [10, 100, 1000, 10000, 100000]))
for name, f in losses.items():
    row = [1 / (1 + np.exp(train(f, n))) for n in [10, 100, 1000, 10000, 100000]]
    print(f"{name:24s}" + "".join(f"{p:12.4f}" for p in row))
print("(table entries: probability of the losing answer B after n gradient steps)")
                                  10         100        1000       10000      100000
DPO  beta=0.1                 0.4382      0.0869      0.0000      0.0000      0.0000
DPO  beta=1.0                 0.1749      0.0204      0.0020      0.0002      0.0000
cDPO beta=1, eps=0.1          0.2280      0.1010      0.1000      0.1000      0.1000
IPO  tau=1                    0.3775      0.3775      0.3775      0.3775      0.3775
(table entries: probability of the losing answer B after n gradient steps)

DPO drives B to zero whatever \(\beta\) is; \(\beta\) changes only the speed (and a smaller \(\beta\) gets there faster, because a bigger log-ratio is needed for the same loss). cDPO stops at \(1-\varepsilon\) odds and IPO at a gap of \(1/(2\tau) = 0.5\), i.e. \(\pi(B) = 1/(1+e^{0.5}) = 0.378\).

Third, likelihood displacement, after Razin et al. The trainable thing is the prompt's final hidden state \(h\); each answer's logit is a fixed output embedding dotted with \(h\). "No" and "Never" have nearly the same embedding (NumPy):

import numpy as np
# Likelihood displacement in miniature (after Razin et al., 2024). The model's last hidden
# state h (2-D here) is trained; each answer's logit is phi(y) . h with FIXED output
# embeddings. "No" and "Never" have almost the same embedding; "Yes" is different.
names = ["Yes", "No", "Never"]
phi = np.array([[0.0, 1.0],     # Yes
                [1.0, 0.2],     # No     (preferred)
                [1.0, 0.0]])    # Never  (rejected): cosine with No = 0.98
beta, lr = 0.1, 1.0
h = np.array([2.0, -1.0])                         # the prompt's hidden state, trainable
log_pi = lambda h: phi @ h - np.log(np.exp(phi @ h).sum())
log_ref = log_pi(h).copy()
print("step    P(Yes)   P(No)  P(Never)   DPO loss")
for step in range(1001):
    lp = log_pi(h)
    m = beta * ((lp[1] - log_ref[1]) - (lp[2] - log_ref[2]))     # implicit reward margin
    if step in (0, 50, 100, 200, 400, 1000):
        p = np.exp(lp)
        print(f"{step:4d}   {p[0]:7.3f} {p[1]:7.3f} {p[2]:8.3f}   {np.log1p(np.exp(-m)):8.4f}")
    # d(-log sigmoid(m))/dh = -sigma(-m) * beta * (phi[No] - phi[Never]); softmax terms cancel
    h -= lr * (-(1 / (1 + np.exp(m))) * beta * (phi[1] - phi[2]))
step    P(Yes)   P(No)  P(Never)   DPO loss
   0     0.027   0.438    0.535     0.6931
  50     0.041   0.455    0.503     0.6882
 100     0.063   0.468    0.469     0.6832
 200     0.140   0.472    0.388     0.6735
 400     0.474   0.338    0.188     0.6547
1000     0.990   0.008    0.001     0.6025

The loss falls monotonically and the preferred-over-rejected margin grows, exactly as DPO intends. But the direction that separates "No" from "Never" is the difference of their embeddings, \((0, 0.2)\), and "Yes" lies almost entirely along it. So every step raises the logit of "Yes" five times as fast as the logit of "No". "No" rises briefly, then collapses; at step 1000 the model says "Yes", which no one preferred, 99% of the time. Add an NLL term on "No", or remove such near-duplicate pairs, and it does not happen.

Finally, the DPO loss in PyTorch for a batch (standard code; not run here). Sequence log-probabilities are sums of token log-probabilities over the response tokens only:

import torch.nn.functional as F

def seq_logprob(logits, labels, mask):
    """logits (B, T, V), labels (B, T), mask (B, T) = 1 on response tokens."""
    logp = F.log_softmax(logits[:, :-1], dim=-1)
    tok = logp.gather(-1, labels[:, 1:].unsqueeze(-1)).squeeze(-1)
    return (tok * mask[:, 1:]).sum(-1)                         # (B,)

def dpo_loss(pol_w, pol_l, ref_w, ref_l, beta=0.1, label_smoothing=0.0):
    margin = beta * ((pol_w - ref_w) - (pol_l - ref_l))
    loss = -(1 - label_smoothing) * F.logsigmoid(margin) - label_smoothing * F.logsigmoid(-margin)
    return loss.mean(), {"reward_chosen": beta * (pol_w - ref_w).detach().mean(),
                         "reward_rejected": beta * (pol_l - ref_l).detach().mean(),
                         "accuracy": (margin > 0).float().mean()}

Things to try

  • In the first program, sample pairs from a different policy (say uniform over the five answers) while keeping \(\pi_{\text{ref}}\) as the SFT model. Does DPO still find \(\pi^*\)? Now make the data cover only the first three answers. What happens to "flatters"?
  • In the third program, add an NLL term \(-\alpha\log\pi(\text{No})\) to the loss with \(\alpha = 0.2\). At step 1000, which answer wins?
  • Train a 0.5B model with TRL's DPOTrainer on a public preference set; plot rewards/chosen and rewards/rejected over training. Does the chosen reward go negative? Repeat with rpo_alpha or an SFT term.
  • Compare DPO and length-normalised DPO on the same data: measure average response length before and after.

Check yourself

Why does the partition function Z(x) cancel in DPO, and why is that the whole trick?

The reward expressed through the optimal policy is \(\beta\log\frac{\pi^*}{\pi_{\text{ref}}} + \beta\log Z(x)\), and \(Z(x)\) depends only on the prompt. Bradley–Terry uses only the difference of two rewards for the same prompt, so \(\beta\log Z(x)\) cancels. Computing \(Z(x)\) would require summing over every possible response, which is what forces RLHF to sample; without it, the loss needs only four log-probabilities per pair.

Compute the DPO loss and gradient weight for a pair with policy log-probs −30 (chosen) and −35 (rejected), reference log-probs −31 and −34, and β = 0.1.

Log-ratios: chosen \(-30-(-31) = +1\), rejected \(-35-(-34) = -1\). Margin \(m = 0.1\times(1-(-1)) = 0.2\). Loss \(-\log\sigma(0.2) = 0.598\); weight \(\sigma(-0.2) = 0.450\).

A colleague says DPO cannot overoptimise because it has no reward model to hack. What do you say?

DPO has an implicit reward model and fits it to finite, biased data. It cannot exploit a separate reward model, but it can overfit deterministic labels (driving rejected answers to zero probability whatever \(\beta\) is), exploit length correlations in the data, and move mass onto responses outside the dataset. Online and iterative DPO, IPO or label smoothing, length normalisation and NLL terms address these.

During DPO training, both the chosen and rejected implicit rewards become negative while accuracy climbs. Is this a bug?

Not a bug, but a warning. The loss only needs the rejected log-ratio to fall faster than the chosen one, so both can fall: the probability mass is going to other responses. If generations degrade (or a safety behaviour weakens), add an NLL term on the chosen answers, filter near-duplicate pairs (they cause likelihood displacement), lower the learning rate, or stop earlier.

Why did Llama 3 mask template tokens out of the DPO loss?

Header and end-of-turn tokens appear in both the chosen and rejected answers. The contrastive loss asks for their probability to go up (in \(y_w\)) and down (in \(y_l\)) at once; the net gradient on them is noise that Llama 3 observed as tail repetition or premature termination. Masking them removes the conflict.

Hard: show that with tabular logits the DPO gradient touches only the logits of y_w and y_l, and explain why that stops being true in a real network.

With logits \(\theta\), \(\log\pi_\theta(y) = \theta_y - \log\sum_{y'}e^{\theta_{y'}}\). The difference \(\log\pi_\theta(y_w) - \log\pi_\theta(y_l) = \theta_{y_w} - \theta_{y_l}\), because the log-sum-exp term is shared, so its gradient is \(e_{y_w} - e_{y_l}\). In a network, \(\log\pi_\theta(y)\) depends on shared parameters (embeddings, hidden states), so the update that separates \(y_w\) from \(y_l\) also changes every other response's probability, in proportion to how its representation aligns with the separating direction. When \(y_w\) and \(y_l\) are similar, that direction is small and dominated by whatever else it correlates with, which is likelihood displacement.

Hard: under what conditions do DPO and PPO with a Bradley–Terry reward model reach the same policy, and which condition fails first in practice?

If preferences follow Bradley–Terry, the reward model and DPO's implicit reward are both maximum likelihood fits in the same function class, the data covers every response the optimal policy puts mass on, both use the same reference and \(\beta\), and both optimisations converge, then both reach \(\pi_{\text{ref}}e^{r/\beta}/Z\) for the fitted \(r\). Coverage fails first: preference datasets contain a tiny fraction of possible responses, PPO evaluates its own new samples with a reward model that generalises (imperfectly) to them, while DPO's policy is unconstrained off the data. Iterative DPO restores coverage gradually.

Go deeper

Papers

Videos and lectures

Articles

Books

Code

Where this leads