Direct Preference Optimization

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.

Train on one preference pair

Ready
0.10

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

The Problem

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:

  1. SFT: Fine-tune a pretrained LM on high-quality demonstrations.
  2. Reward model: Train a separate neural network to score outputs using human preference comparisons.
  3. RL optimization: Use PPO to maximize the learned reward while staying close to the SFT model via a KL penalty.

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.

Count the moving parts

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 wish list: Can we get the same alignment quality without training a reward model, without running PPO, without sampling from the LM during training, and without tuning RL hyperparameters? Can we reduce RLHF to something as simple as supervised fine-tuning? DPO says yes.

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:

  1. The Key Insight: the reward hides inside the policy, and one term cancels.
  2. The RLHF Objective: what RLHF optimizes, and what the β slider does.
  3. The Closed-Form Solution: the best policy, derived in three steps.
  4. The DPO Loss: substitute, cancel, and read the loss off.
  5. Why DPO Works: the update weight you saw shrink in the hero.
  6. Theoretical Properties: same objective, no lost expressiveness.
  7. Results: the win rates against PPO.
  8. Practical Advantages: what you skip, what you keep, and twenty lines of code.
  9. Connections: what DPO built on, and the family it started.
What makes the standard RLHF pipeline complex to implement and run?

Chapter 1

The Key Insight

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:

The optimal policy under the RLHF objective has a closed-form solution. This means you can express the reward function as a function of the optimal policy and the reference policy. Substitute this into the preference model, and the reward model disappears. You get a loss that directly optimizes the policy on preference data.

Let us unpack this step by step. The standard RLHF objective is:

maxπ
Search over policies π, the models that write answers, for the one that makes the rest as large as possible.
E[r(x,y)]
The average reward over prompts x from the data D and answers y that the policy writes. A higher reward means people like the answer more.
β
The price of drifting. A large β keeps the policy near the reference. A small β lets it chase reward.
DKL(π || πref)
How far the policy has moved from the frozen reference model, measured as a KL divergence. It is zero when the two are the same.

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:

π*(y|x)
The best policy: the probability of answer y to prompt x after the objective is fully optimized.
πref(y|x)
The starting point, the frozen SFT model.
exp(r/β)
A boost. Answers with a high reward get multiplied by a big number, and β sets how big.
Z(x)
A normalizing constant that makes the probabilities add up to 1. It depends on the prompt x only.

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:

r(x,y)
The reward of answer y to prompt x. We used to learn it with a separate network.
β log(π*/πref)
β times the log-ratio of the best policy to the reference. Both are models we already have.
β log Z(x)
A constant for each prompt. It is the same for every answer to that prompt.

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.

Why does the partition function Z(x) drop out of the DPO loss?

Chapter 2

The RLHF Objective

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.

The reward model

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:

p*(y1 ≻ y2 | x)
The chance that a person prefers answer y1 to answer y2 for prompt x.
exp r1 / (exp r1 + exp r2)
Each answer gets a share equal to the exponent of its reward. The preferred answer is the one with the larger share.
σ(r1 − r2)
The same number written with the sigmoid function. Only the difference of the two rewards matters.

Here σ is the sigmoid function. The reward model loss is binary cross-entropy:

LR(rφ)
The loss for the reward model with weights φ. Lower is better.
E(x, yw, yl)
An average over the preference triples in the dataset.
σ(r(yw) − r(yl))
How strongly the model ranks the winner above the loser. The loss falls as this nears 1.

The KL-constrained RL objective

Once we have a reward model, we optimize the policy to maximize reward while not drifting too far from the reference (SFT) model:

maxπθ
Tune the weights θ of the policy we are training.
rφ(x,y)
The score from the reward model we trained in the first step. It is frozen here.
DKL(πθ || πref)
The leash: how far the trained policy has drifted from the reference.

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).

Why the KL constraint? Without it, the policy would exploit any imperfections in the reward model. A small bias in the reward model becomes a gaping hole that the policy drives a truck through. The KL penalty keeps the policy close to the reference distribution where the reward model's training data lives. This stops the policy from generating out-of-distribution outputs that “trick” the reward model into giving high scores.

Slide β along the frontier

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.

0.10

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.

What would happen if you maximized reward without any KL constraint (β = 0)?

Chapter 3

The Closed-Form Solution

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.

Step 1: Expand the KL divergence

The objective is:

maxπ E[r]
The reward term: the average reward of the answers the policy writes.
β DKL
The leash term: β times the distance from the reference.

Expanding the KL term, which is itself an average of a log-ratio:

E[r(x,y)]
The same reward term as above.
E[log(π/πref)]
The definition of the KL divergence: the average log-ratio of the policy to the reference, over answers the policy writes.

Both terms average over the same answers, so we merge them:

Step 2: Write as a KL divergence

We can rearrange to recognize this as a KL divergence. Define:

π*(y|x)
Our guess for the best policy.
1/Z(x)
The factor that makes the guess a valid distribution.
πref(y|x)
The reference model's probability, the starting weights of the guess.
exp(r/β)
The reward boost for each answer.

Here Z(x) = Σy πref(y|x) exp(r(x,y)/β) ensures normalization. Then the objective can be rewritten as:

−β DKL(π || π*)
A leash to π*. It is as large as possible (zero) when the policy equals π*.
β log Z(x)
A constant. Nothing the policy does can change it.

Since DKL ≥ 0 with equality iff π = π*, the maximum is achieved at π = π*. Done.

Step 3: Reparameterize the reward

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):

r(x,y)
The reward, now written without any reward network.
β log(π*/πref)
How much more the best policy likes y than the reference does, in log units.
β log Z(x)
The prompt-only constant. It is about to cancel.
The reparameterization: The reward is just β times the log-ratio of optimal policy to reference policy, plus a prompt-dependent constant β log Z(x). This is the equation that makes DPO possible. Instead of learning a reward model, we can express reward entirely in terms of things we already have: the policy we are training and the frozen reference model.

Reweight the reference

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.

0.30

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.

What is the closed-form optimal policy for the KL-constrained reward maximization objective?

Chapter 4

The DPO Loss

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:

Step 4: Substitute and cancel

Plugging in the reparameterized reward:

+ β log Z(x)
The constant that came with the winner's reward.
− β log Z(x)
The same constant, subtracted with the loser's reward. Both sit on the same prompt, so it is the identical number.

The β log Z(x) terms cancel! We are left with:

β log(π*(yw)/πref(yw))
How much more the policy likes the preferred answer than the reference does.
β log(π*(yl)/πref(yl))
The same for the dispreferred answer. We subtract it.

Step 5: The final DPO loss

Now we replace π* with our trainable policy πθ and write the maximum likelihood objective:

LDPO
The loss we minimize by gradient descent, with the reference held frozen.
E(x, yw, yl)~D
An average over the preference triples in the dataset.
σ
The sigmoid. It turns the score gap into the model's chance of ranking the pair correctly.
β log(πθ(yw)/πref(yw))
The implicit reward of the preferred answer.
β log(πθ(yl)/πref(yl))
The implicit reward of the dispreferred answer.

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.

What this loss says in plain English: For each preference pair, compute the log-probability ratio of the preferred completion under the current policy versus the reference policy, minus the same ratio for the dispreferred completion. Push this difference through a sigmoid and do binary cross-entropy. The loss decreases when the policy assigns relatively higher probability to preferred completions (compared to the reference) than to dispreferred ones.

Walk the derivation

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.

What is the DPO loss function?

Chapter 5

Why DPO Works

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 DPO gradient

The gradient of the DPO loss with respect to the policy parameters θ is:

∇θ LDPO
The direction in weight space that raises the loss fastest. We step the other way.
β
The same β as in the loss. It scales the step.
σ(r̂(yl) − r̂(yw))
The update weight. It is near 1 when the policy ranks the pair wrongly, and near 0 when it ranks it correctly.
∇ log πθ(yw|x)
The direction that makes the preferred answer more likely.
∇ log πθ(yl|x)
The direction that makes the dispreferred answer more likely. It is subtracted, so the step makes it less likely.

Here r̂θ(x,y) = β log(πθ(y|x) / πref(y|x)) is the implicit reward.

There are three parts to this gradient:

  1. ∇θ log πθ(yw|x): increase the log-probability of the preferred completion.
  2. ∇θ log πθ(yl|x): decrease the log-probability of the dispreferred completion.
  3. σ(r̂θ(x,yl) − r̂θ(x,yw)): a weighting factor that measures how “wrong” the current policy is.

The importance weight

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.

Self-regulating gradients: Without this weighting, a naive approach (just maximize log π(yw) and minimize log π(yl)) causes the model to degenerate. The paper confirms this experimentally: the “unlikelihood” baseline without proper weighting performs poorly. The sigmoid weight is what prevents DPO from collapsing. It automatically focuses learning on examples the policy currently gets wrong.

Watch the weight shrink

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.

-0.5

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.

What prevents DPO from causing the model to degenerate by aggressively pushing all preferred completions up and all dispreferred completions down?

Chapter 6

Theoretical Properties

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.

Property 1: 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.

Property 2: No loss of expressiveness

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.

Shift the reward, keep the preference

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.

0.0

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.

Property 3: Consistency under Bradley-Terry

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.

Property 4: Implicit reward model

Your language model is a reward model. The implicit reward at any point during training is:

r̂θ(x,y)
The reward the policy implies for answer y. The hat means it is read off the policy, not learned apart from it.
β log(πθ/πref)
β times the gap between the policy's log-probability and the reference's.

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.

Diagnosing RLHF instability: The paper also uses DPO's framework to explain why PPO-based RLHF can be unstable. The normalization term β log Z(x) in the reward acts like a soft value function for the reference policy. Without proper baselines, the policy gradient has high variance. PPO tries to handle this with a learned value function, but that adds another source of error. DPO sidesteps the issue entirely. The reparameterization yields a reward that does not need any baselines.
Does the DPO reparameterization r(x,y) = β log(π/πref) limit what reward functions can be learned?

Chapter 7

Results

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).

Sentiment control (IMDb, GPT-2 large)

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.

Summarization (TL;DR, GPT-J 6B)

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.

Compare the win rates

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.

Dialogue (Anthropic HH, Pythia 2.8B)

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.

TaskModelWhat the paper reports
IMDb sentimentGPT-2 largeBest reward-KL frontier, above PPO even with the true reward
TL;DR summariesGPT-J 6BDPO 61%, PPO 57%, Best-of-128 58% (GPT-4 judge)
Anthropic HH dialoguePythia 2.8BMatches or beats Best-of-128 at a far lower cost
Human check on TL;DRGPT-J 6BDPO preferred over PPO 58% of the time
Human validation: The paper also conducted human evaluations. On TL;DR, DPO samples (temperature 0.25) were preferred 58% of the time over PPO samples (temperature 0.0) by human raters. GPT-4's judgments correlated strongly with human preferences, with agreement rates comparable to inter-annotator agreement.
How does DPO compare to PPO on the sentiment control task?

Chapter 8

Practical Advantages

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.

What you DON'T need

What you DO need

  1. A reference model πref: The SFT model, frozen. You need to compute log-probabilities under it for each training example. This is a forward pass only. It has no gradients, so it can be run in eval mode.
  2. A preference dataset: Triples (x, yw, yl). These can be pre-collected offline.
  3. One hyperparameter β: It controls how conservative the alignment is. The paper uses β ∈ {0.1, 0.5} and finds results are robust.

Implementation

DPO can be implemented in roughly 20 lines of core training code:

Forward
Compute log πθ(yw|x), log πθ(yl|x) for current policy
↓
Reference
Look up log πref(yw|x), log πref(yl|x) (precomputed or cached)
↓
Loss
loss = −log σ(β · ((log πθ(yw) − log πref(yw)) − (log πθ(yl) − log πref(yl))))
↓
Update
Standard backprop + Adam. That is it.
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)
Compute savings: In RLHF, each training step requires (1) generating completions from the policy (autoregressive, slow), (2) scoring them with the reward model (another forward pass), (3) computing advantages, and (4) running PPO with multiple epochs. DPO needs only (1) a forward pass through the policy on the fixed dataset and (2) a backward pass. For a 6B parameter model, this can reduce training time by 5-10x.
What is the most significant computational saving of DPO over PPO-based RLHF?

Chapter 9

Connections

Place DPO in the field: what it built on, what it started, and the one line to keep

What DPO built on

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.

What DPO enabled

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.

Industry adoption

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.

DPO's legacy: DPO showed that RLHF's complexity was mostly unnecessary. The field's reaction was dramatic. Within a year, DPO became the default alignment method for open-source models. It spawned a family of “direct alignment” methods (SimPO, KTO, IPO, ORPO) that continue to simplify and improve preference learning. The core insight, that you can reparameterize reward as a function of policy ratios, is one of the most impactful observations in modern ML.

Cheat sheet

Core equation
L = −E[log σ(β(log πθ(yw)/πref(yw) − log πθ(yl)/πref(yl)))]
Key insight
r(x,y) = β log(π*/πref) + β log Z(x), and Z(x) cancels in Bradley-Terry
Mechanism
Implicit reward via policy/reference log-ratio; sigmoid weighting prevents degeneration
Advantage
No reward model, no RL loop, no sampling, no value function: just supervised learning
Impact
Default alignment for open-source LLMs; enabled SimPO, KTO, IPO, ORPO
What is DPO's core mathematical insight that eliminates the need for a reward model?
Go back to the hero and train from the “Wrong” start at two different β values. Now you can say why the weight shrinks, why β sets where training settles, and why no reward model was ever needed. Then use Present or Teach to explain it back in your own words.
Direct Preference Optimization
Based on “Direct Preference Optimization: Your Language Model is Secretly a Reward Model” by Rafailov et al. (2023)
Read the original paper · Back to Veanors