Your language model is secretly a reward model. DPO aligns it with one classification loss on preference pairs, where RLHF needed a separate reward model and a PPO loop.
Pick a starting policy, press Train, then drag β. Watch the right answer rise, the wrong one fall, and the update weight shrink as the policy learns. Then we build, piece by piece, why this one loss equals RLHF.
You need the RLHF pipeline, KL divergence and the Bradley-Terry model. We build the rest from zero.
Rafailov, Sharma, Mitchell, Manning, Ermon and Finn, 2023. Read the paper.
Four answers to one prompt. People preferred the plain story to the jargon lecture. Press Train to apply the DPO loss to that one pair.
A toy, not the paper's data: one prompt, four answers, and a table of four numbers as the policy, so the maths is exact. The loss, the implicit reward and the update weight are the paper's formulas. A real language model shares weights across answers, so it moves less cleanly. The step size is divided by β, so β changes where training settles, not how fast it moves.
Chapter 0
See why the standard way to align a language model needs so much machinery, and what we wish we could skip
By 2023, RLHF had become the standard recipe for aligning language models with human preferences. ChatGPT, InstructGPT and Claude all used the same three-stage pipeline:
This pipeline works. But it is a lot of machinery. You need to train and serve a reward model. You need to implement PPO with all its moving parts: a value function, advantage estimation, clipping and multiple epochs. You need to sample from the policy during training, which is expensive for large LMs. You need to tune a KL penalty coefficient. The whole thing is also notoriously brittle. Reward hacking, mode collapse and training instability are constant threats.
The standard three-stage RLHF pipeline versus DPO's simplified approach. Switch between them and count the parts you must build and run.
A schematic of the two pipelines as the paper describes them, not a measurement. The frozen reference model sits in both.
The hero at the top of this page is the answer in miniature. It has no reward model and no RL loop. It has one loss, applied to one pair. Each later chapter explains one part of it:
Chapter 1
Rewrite the reward as a ratio of two policies, and watch the one term that blocks you cancel
Here is the core idea of DPO, in one sentence:
Let us unpack this step by step. The standard RLHF objective is:
This is a constrained optimization problem: maximize reward while staying close to the reference policy. The remarkable fact is that this problem has an analytical solution:
Z(x) is a normalizing constant. This is known from the control-as-inference literature, but nobody had thought to rearrange it. Rearranging for r:
The reward is just β times the log-ratio of the optimal policy to the reference policy, plus a prompt-dependent constant. Now here is the magic: the Bradley-Terry preference model only cares about differences in reward between two completions for the same prompt. And β log Z(x) is the same for both completions. It cancels.
So you can write the probability of preferring yw over yl entirely in terms of policy log-ratios. No reward model is needed. Train the policy directly on preference data with a binary cross-entropy loss.
Chapter 2
Learn what RLHF optimizes, and slide β to see why the KL leash exists
Before we derive DPO, we need to understand precisely what RLHF optimizes. The pipeline has two key components.
Given a dataset of human preferences, we have triples (x, yw, yl) where yw is preferred over yl for prompt x. We fit a reward model rφ(x,y) using the Bradley-Terry model. The probability that y1 is preferred over y2 is:
Here σ is the sigmoid function. The reward model loss is binary cross-entropy:
Once we have a reward model, we optimize the policy to maximize reward while not drifting too far from the reference (SFT) model:
The β parameter controls how much the policy can deviate from πref. A large β means stay very close to the reference (conservative). A small β means chase reward aggressively (risky, and can lead to reward hacking).
The curve is the best reward you can reach at each KL distance. The warm dot is where the policy ends up for your β. Drag β to see how the KL constraint strength moves it.
Illustrative: the curve is a made-up shape that rises and flattens (reward = 1 − exp(−KL/6), scaled to 0 to 100%). The dot is the point where one more unit of KL stops paying for itself, which for this curve is where its slope equals β/3. The shape is a toy. The tension it shows is the real one.
Chapter 3
Derive the best policy in three steps, and reparameterize the reward
This is the mathematical heart of DPO. We will derive the closed-form optimal policy for the KL-constrained reward maximization objective, step by step. The symbols are the ones from Chapter 1.
The objective is:
Expanding the KL term, which is itself an average of a log-ratio:
Both terms average over the same answers, so we merge them:
We can rearrange to recognize this as a KL divergence. Define:
Here Z(x) = Σy πref(y|x) exp(r(x,y)/β) ensures normalization. Then the objective can be rewritten as:
Since DKL ≥ 0 with equality iff π = π*, the maximum is achieved at π = π*. Done.
Now we rearrange the optimal policy equation to express reward in terms of policy ratios. Starting from:
Take the logarithm of both sides:
Solve for r(x,y):
Four answers with a reference probability (blue tick) and a reward. The best policy multiplies each reference probability by exp(r/β), then divides by Z. Drag β and watch the bars rebalance.
Toy numbers: the same four answers as the hero, reference probabilities 25%, 35%, 25%, 15%, and made-up rewards 1.0, 0.2, −0.6 and −0.4 (the plain story is best, the jargon lecture is worst). The formula is the paper's, computed exactly.
Chapter 4
Substitute the new reward into Bradley-Terry, cancel Z(x), and read the loss off
Now we complete the derivation. We have the reward reparameterized as:
We substitute this into the Bradley-Terry preference model. The probability of preferring yw over yl is:
Plugging in the reparameterized reward:
The β log Z(x) terms cancel! We are left with:
Now we replace π* with our trainable policy πθ and write the maximum likelihood objective:
Worked number: β = 0.1, log-ratios +2.0 and −1.0, gap = 0.1 × 3.0 = 0.30, loss = −log σ(0.30) = 0.554 (a tie, gap 0, would cost 0.693)
That is it. The entire DPO algorithm is in one equation. No reward model. No RL loop. No value function. Just a supervised loss on preference pairs.
The five steps from RLHF objective to DPO loss. Press Next step to reveal them one at a time. The key moment is step 4, where Z(x) cancels in the Bradley-Terry difference.
A summary of the derivation on this page, with steps 1 to 3 in Chapter 3 and steps 4 and 5 above. The equations are in the paper's notation, shortened to fit.
Chapter 5
Read the gradient, and see why the update shrinks once the policy ranks the pair right
The loss function looks simple, but what is it actually doing to the policy at each gradient step? Let us look at the gradient.
The gradient of the DPO loss with respect to the policy parameters θ is:
Here r̂θ(x,y) = β log(πθ(y|x) / πref(y|x)) is the implicit reward.
There are three parts to this gradient:
The weighting factor is the sigmoid of (implicit reward of dispreferred − implicit reward of preferred). When the implicit reward incorrectly ranks the dispreferred completion higher than the preferred one, this weight is large, and the gradient pushes hard to fix the ordering. When the policy already ranks them correctly, the weight is small. The gradient is gentle, which prevents over-optimization.
The weight (warm) is large when the policy ranks the pair wrongly and shrinks as it learns. Drag the implicit reward gap, or press Let it train and watch the gap climb and the push fade.
The weight is the paper's formula, σ(−gap), computed exactly. The push bars show weight × 0.8 for scale. “Let it train” moves the gap by an amount proportional to the weight each tick, a simple stand-in for the real training dynamics.
Chapter 6
Check that the shortcut keeps the same objective and loses no reward you could have learned
DPO is not just a practical trick. It has rigorous theoretical backing that guarantees it optimizes exactly the same objective as RLHF.
DPO and PPO-based RLHF optimize the same KL-constrained reward maximization objective. The only difference is how they optimize it. RLHF does it in two stages (fit reward, then RL). DPO does it in one stage (direct classification on preferences). The optimal solution is identical.
The reparameterization r(x,y) = β log(π(y|x) / πref(y|x)) might seem restrictive. Are we limiting what rewards we can represent? No. The paper proves (Theorem 1) that every reward function's equivalence class can be represented this way. Two rewards that differ by only a function of x (that is, r(x,y) − r'(x,y) = f(x)) produce the same preference distribution and the same optimal policy. The reparameterization just picks a canonical representative from each class.
Two answers to one prompt, with a reward each. Drag the shift f(x), which adds the same number to both. The bars move together, and the preference stays exactly where it was.
Toy numbers: rewards 1.2 for the preferred answer and 0.3 for the other, before the shift. The preference is the Bradley-Terry formula from Chapter 2, computed exactly.
Suppose the true preference data comes from a Bradley-Terry model with some reward r*. Then, as the dataset grows, the DPO solution converges to the optimal policy for r*. This is a standard consistency guarantee. DPO does not introduce any additional bias beyond the Bradley-Terry assumption.
Your language model is a reward model. The implicit reward at any point during training is:
You can extract this reward for any (x, y) pair by computing the log-probability under your policy minus the log-probability under the reference. No separate reward model is needed. This implicit reward is provably as expressive as any explicit one.
Chapter 7
Compare DPO with PPO on sentiment, summaries and dialogue, using the paper's win rates
The paper evaluates DPO on three tasks: controlled sentiment generation (IMDb), summarization (TL;DR), and single-turn dialogue (Anthropic HH).
DPO achieves the best reward-KL frontier of all methods. For any given KL budget, DPO achieves higher reward than PPO, even when PPO uses the ground-truth reward function (PPO-GT). This is remarkable: DPO optimizes the same objective more efficiently than PPO, despite being much simpler.
Using GPT-4 as evaluator against human-written reference summaries:
DPO not only wins but is much more robust to sampling temperature. PPO's performance degrades sharply at high temperatures. DPO remains stable.
Win rates against human-written summaries on TL;DR, judged by GPT-4. The dashed line is a tie at 50%. Each bar ends in its number.
DPO 61%, PPO 57% and Best-of-128 58% are the numbers from the paper's text. The SFT (40%) and Preferred-FT (42%) bars are approximate readings of the paper's figure, so treat them as rough. The bars start at 30% to make the gaps visible.
DPO is the only computationally efficient method that improves over the preferred completions in the dataset. It matches or exceeds Best-of-128 (a computationally impractical baseline) while being orders of magnitude cheaper.
| Task | Model | What the paper reports |
|---|---|---|
| IMDb sentiment | GPT-2 large | Best reward-KL frontier, above PPO even with the true reward |
| TL;DR summaries | GPT-J 6B | DPO 61%, PPO 57%, Best-of-128 58% (GPT-4 judge) |
| Anthropic HH dialogue | Pythia 2.8B | Matches or beats Best-of-128 at a far lower cost |
| Human check on TL;DR | GPT-J 6B | DPO preferred over PPO 58% of the time |
Chapter 8
List what you can delete from your training stack, what you must keep, and write the loss in twenty lines
DPO's simplicity is not just aesthetic. It translates to real practical benefits for training aligned language models.
DPO can be implemented in roughly 20 lines of core training code:
import torch.nn.functional as F
def dpo_loss(pol_w, pol_l, ref_w, ref_l, beta=0.1):
# each argument: summed log-prob of a whole answer, shape [batch]
# ref_* come from the frozen reference, computed under no_grad
gap = beta * ((pol_w - ref_w) - (pol_l - ref_l)) # implicit reward gap
return -F.logsigmoid(gap).mean() # -log sigmoid(gap)
Chapter 9
Place DPO in the field: what it built on, what it started, and the one line to keep
RLHF (Christiano et al., 2017): The foundational framework for learning from human preferences. DPO optimizes the same objective but bypasses the RL loop entirely.
PPO (Schulman et al., 2017): The RL algorithm used in standard RLHF. DPO makes PPO unnecessary for preference learning by showing the optimal policy has a closed form.
Bradley-Terry model (1952): The preference model that DPO inherits. The key property, that it depends only on reward differences, is what allows Z(x) to cancel.
Control as inference (Levine, 2018): The framework connecting optimal control to probabilistic inference. The closed-form solution π* ∝ πref exp(r/β) comes directly from this literature.
SimPO (Meng et al., 2024): Simplifies DPO further by removing the reference model. It uses average log-probability as the implicit reward, adding a target reward margin.
KTO (Ethayarajh et al., 2024): Kahneman-Tversky Optimization extends DPO to work with unpaired preference data (just “good” or “bad” labels, no pairwise comparisons needed).
IPO (Azar et al., 2024): Identity Preference Optimization addresses DPO's potential overfitting to Bradley-Terry assumptions by using a different, more robust loss.
ORPO (Hong et al., 2024): Odds Ratio Preference Optimization combines SFT and preference alignment into a single stage, with no reference model.
DPO has been adopted broadly. Llama 3 (Meta), Gemma (Google), Mistral, Zephyr, and many other open models use DPO or DPO variants for alignment. It has largely replaced PPO-based RLHF in the open-source community because of its simplicity. Some frontier labs continue to use PPO or hybrid approaches (online DPO, iterative DPO) for maximum performance.