Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
Direct Preference
Optimization, explained.
Teaching a model to be helpful and harmless used to mean building a second AI to grade the first, then running finicky reinforcement learning to chase those grades — a Rube Goldberg machine that fell over constantly. This 2023 paper proved you can throw the whole contraption away and get there with one ordinary training loss.
Contents 15 sections
The delta The RLHF machine The insight: your model is already the reward model One loss instead of three stages The loss, worked with real numbers Why it's stable How it works The math The evidence Since then Solve it yourself Why it still matters Questions Check yourself Where this sitsWhat changes against InstructGPT: the reward model and the RL both go
Rung 1's step three is the expensive and fragile one: train a separate reward model, then run reinforcement learning against it while holding four models in play and watching for divergence. This rung removes the reward model and the reinforcement learning, and it does so by algebra rather than approximation — which is why it is a different kind of result from most of this ladder.
The argument, in outline. The objective rung 1 optimises is "maximise reward while staying close to the reference model", and for that objective the optimal policy has a closed form in terms of the reward. Because the relation is invertible, the reward can equally be written in terms of the policy — so a preference between two responses can be expressed directly as a function of the policy's own probabilities. The reward model does not need to be built, because the language model already implies one. What is left is a supervised loss that raises the probability of the preferred response relative to the rejected one, weighted so that pairs the model already gets right contribute little.
Stated in rung 1's units: four models and an RL loop become two models and a classification-style loss — the policy being trained and a frozen reference. No reward model to train, no value network, no sampling during training, no explicit reward model to over-exploit (though DPO can still over-optimize against the preference data, as later work showed), and the failure modes are closer to the familiar ones of supervised learning.
The RLHF machine
The reason a raw language model becomes a helpful assistant is alignment — tuning it to prefer the responses humans actually like. The dominant recipe, RLHF (reinforcement learning from human feedback), does this in three stages: collect human preferences (this answer is better than that one), train a separate reward model to imitate those judgments, then use reinforcement learning (PPO) to push the model toward high-reward outputs.
It works — it's how ChatGPT was aligned — but that third stage is a beast. Reinforcement learning on a giant model is memory-hungry, hyperparameter-sensitive, prone to instability, and happy to "reward-hack" by finding cheap tricks that score high without being good.
The insight: your model is already the reward model
DPO's authors did the algebra everyone had skipped. They showed that the reward function RLHF works so hard to learn can be rewritten in terms of the model's own probabilities relative to a frozen reference copy. The policy and the reward aren't two separate things to train — they're two views of the same object.
The paper's memorable framing: your language model is secretly a reward model. If that's true, you never need to build the reward model or run RL against it. You can optimize the model directly.
One loss instead of three stages
DPO uses the exact same data as RLHF — pairs of a chosen (preferred) and a rejected response for each prompt — but trains with a single, supervised, classification-style loss: raise the model's probability of the chosen response and lower the rejected one, gently anchored to the reference model so it doesn't drift.
Same inputs, same goal, two stages deleted.
The loss, worked with real numbers
Here is the entire method as one line. For a prompt x with chosen response yw and rejected response yl:
Each bracketed term is a log-ratio: how much more (or less) the policy likes a response than the frozen reference does. The paper's key claim is that β times this log-ratio is the reward — the reward model RLHF trains separately already lives implicitly inside the policy. Concrete numbers, with β = 0.1:
| Quantity | Chosen yw | Rejected yl |
|---|---|---|
| log πθ (policy) | −10 | −9 |
| log πref (reference) | −12 | −7 |
| Log-ratio (implicit reward ÷ β) | +2 — policy likes it more than ref | −2 — policy likes it less |
Margin = 2 − (−2) = 4, so the loss is −log σ(0.1 × 4) = −log σ(0.4) = −log 0.5987 = 0.513. Three behaviors fall straight out of the formula:
| Situation | Margin | Loss | Gradient weight σ(−βΔ) |
|---|---|---|---|
| Model prefers the right answer (above) | +4 | 0.513 | 0.40 — keep nudging |
| Model has no preference yet | 0 | log 2 = 0.693 | 0.50 |
| Model prefers the wrong answer | −4 | 0.913 | 0.60 — pushed hardest |
That last column is DPO's quiet elegance: the gradient on each pair is scaled by σ(−βΔ) — how wrong the model currently is about that pair. Examples it already ranks correctly fade; examples it ranks backwards shout. And β controls the anchor: small β lets the policy drift far from the reference, large β pins it close — the same KL-leash PPO enforces with machinery, achieved by one scalar.
Why it's stable
PPO is online reinforcement learning: it samples fresh outputs from the model, scores them, updates, and repeats — a feedback loop with many ways to wobble. DPO is offline and supervised: a fixed dataset of preference pairs, one loss, gradient descent. It trains as calmly and reproducibly as ordinary fine-tuning, on far less hardware.
The practical unlock is accessibility: a team that could never stand up a stable PPO pipeline can run DPO with a standard training script, which is a big part of why open models aligned so quickly after 2023.
How DPO derives its loss and trains, step by step
DPO uses exactly the data RLHF uses: prompts x, each with a preferred response yw and a dispreferred response yl. The difference is that the RLHF objective is solved on paper first, and only the result is trained. The derivation is short enough to follow line by line.
- Start from the RLHF objective. Maximize expected reward while staying close to a reference policy: maxπ Ex, y ~ π[r(x, y)] − β·DKL[π(y | x) ‖ πref(y | x)]. This is the objective PPO approximately optimizes in InstructGPT-style pipelines.
- Solve it in closed form. For any reward function, the maximizer is π*(y | x) = πref(y | x)·exp(r(x, y)/β) / Z(x), where Z(x) = Σy πref(y | x)·exp(r(x, y)/β). Z sums over every possible response, so it cannot be computed, which is why nobody samples from this formula directly.
- Invert for the reward. Taking logs and rearranging gives r(x, y) = β·log[π*(y | x)/πref(y | x)] + β·log Z(x). Any reward can be written through the policy it induces, plus a term that depends only on the prompt.
- Substitute into Bradley–Terry. The standard preference model is p(yw ≻ yl | x) = σ(r(x, yw) − r(x, yl)). Both responses share the prompt, so β·log Z(x) appears in both rewards and cancels in the difference. The preference probability now depends only on log-ratios of the policy to the reference.
- Fit by maximum likelihood. Replace π* with the trainable πθ and minimize the negative log-likelihood of the observed preferences. That is the DPO loss in the worked example above, and its implicit reward is r̂θ(x, y) = β·log[πθ(y | x)/πref(y | x)].
- Train it like supervised learning. Set πref to the supervised fine-tuned model. When none exists, the paper first fine-tunes on the preferred responses (Preferred-FT) and uses that as the reference, so the reference sits close to the data. Each step needs the log-probabilities of yw and yl, summed over their response tokens with the prompt excluded, under the policy and under the frozen reference; the reference values can be computed once, ahead of time. Nothing is sampled during training.
Why the shortcut loses nothing
Rewards that differ only by a function of the prompt induce the same preferences and the same optimal policy, so they form an equivalence class. The paper proves that every such class consistent with the Bradley–Terry model, and with its ranking generalization Plackett–Luce, contains a reward of the form β·log[π(y | x)/πref(y | x)] for some policy π. Writing the reward through the policy therefore does not restrict which preferences can be learned.
Settings used in the paper
The default was β = 0.1 with batch size 64 and the RMSprop optimizer at a learning rate of 10^−6, warmed up linearly over 150 steps; the summarization experiments used β = 0.5. At β = 0.1, a pair's implicit reward gap is one tenth of its log-ratio margin.
The DPO gradient, and what β does
Differentiating the DPO loss gives:
∇ log πθ(yw | x)— raises the probability of the preferred response.− ∇ log πθ(yl | x)— lowers the probability of the dispreferred one.σ(r̂l − r̂w)— the per-pair weight: large when the implicit reward ranks the pair the wrong way round, small when it already ranks it correctly.β— the KL strength inherited from the RLHF objective; it scales both the implicit reward and the gradient.
The weight is not decoration. The paper reports that a naive version without it, essentially unlikelihood training, made the model degenerate; on summarization it produced long runs of a single repeated word. At the extremes of β: as β grows, a small change in log-ratio already saturates the sigmoid, so the policy is held close to πref; as β shrinks, fitting the same preferences requires much larger log-ratios, which means drifting further from the reference.
What DPO was tested on, and what it showed
Three tasks were chosen so that one has a known true reward. In controlled sentiment generation, GPT-2-large continues 2–8-token prefixes of IMDb reviews and should write positively; preferences come from a sentiment classifier that also serves as the ground-truth reward. In summarization, a GPT-J model fine-tuned on Reddit TL;DR summaries learns from human preference data. In single-turn dialogue, Pythia-2.8B learns from Anthropic's helpful-and-harmless (HH) preferences. Baselines included PPO with a learned reward model, PPO with the ground-truth reward (PPO-GT, sentiment only), Preferred-FT, unlikelihood training and best-of-N sampling. GPT-4 judged summaries and dialogue.
| Task | Measure | Result |
|---|---|---|
| IMDb sentiment | reward against KL to the reference | DPO highest reward at every KL; dominates PPO and even PPO-GT |
| TL;DR summarization | GPT-4 win rate vs reference summaries | DPO about 61% at temperature 0; PPO about 57% at its best temperature |
| Anthropic HH dialogue | GPT-4 win rate vs the chosen responses | the only efficient method to beat the chosen responses; matches or beats best-of-128 |
| CNN/DailyMail, trained on TL;DR | GPT-4 win rate vs reference | DPO 0.36, PPO 0.26 at temperature 0 |
A human study checked the judge: GPT-4's verdicts agreed with human raters about as often as the raters agreed with each other. DPO was also more robust to sampling temperature, while PPO's summaries degraded toward the base GPT-J's quality at high temperature.
The negative results came from the simpler baselines. Unlikelihood training, which pushes the preferred response up and the rejected one down with no per-pair weighting, degenerated on summarization and dialogue, producing meaningless text, and was left out of those experiments. And the PPO model tried for dialogue could not improve on the base Pythia-2.8B at all.
What the authors admit, and what happened next
The structural limitation is that the method is offline. It learns from a fixed set of preference pairs and never generates a new response to be judged, whereas rung 1's loop samples from the current policy and scores what it actually produces — so it keeps getting signal about the model's present behaviour rather than a previous model's. When there is budget to collect fresh judgements, several careful comparisons found reinforcement learning with a reward model still ahead, and the honest summary of the field's position is a conditional: take this rung for simplicity and a fixed dataset, take rung 1's shape when you can afford to keep scoring new samples.
Two practical failure modes were documented afterwards. Results are sensitive to the strength of the reference constraint, and the loss can reduce the probability of both responses in a pair while still improving their ratio — it optimises a relative quantity, and a relative quantity can be satisfied in ways nobody wanted.
How it held up: enormously adopted, and then largely bypassed at the frontier for a reason that has little to do with its merits. Its whole premise is that the reward must be learned from preferences, which is true for helpfulness and tone. For mathematics and code the reward can be computed — run the tests — and once the reward is a program rather than a model, the objections to reinforcement learning largely dissolve, which is the opening the next rung walks through.
The DPO loss in 15 lines
The complete loss from the worked example, running in your browser through WebAssembly. Feed it the four log-probabilities and β; get the loss and the implicit rewards. Run it to reproduce the 0.513 from above, then flip the preference or shrink β and watch the gradient weight respond exactly as the table predicts.
Write the body of dpo_loss. Everything else in the file is
already written; this is the function the paper is about. Press ▶ Run to check it against
the 5 assertions below — they start red.
- Reproduces the worked example
- No preference gives log 2
- Wrong preference is punished harder
- Sigmoid(0) is 0.5
- The chosen response earns a higher implicit reward than the rejected
Why it still matters
DPO became the default alignment method for a huge fraction of open models — its simplicity made preference tuning something any team could do. It also opened a whole family of direct-preference variants (IPO, KTO, ORPO and more), each tweaking the loss for different data or goals.
More deeply, it's a lesson in looking harder before reaching for heavy machinery: an entire reinforcement-learning stage turned out to be unnecessary once someone did the math. Sometimes the reward model you're training is already sitting inside the model you have.
Questions people ask about Direct Preference Optimization
How is the DPO loss derived from the RLHF objective?
Start with the RLHF objective: maximize expected reward minus beta times the KL divergence from a reference policy. Its optimal policy has a closed form, the reference policy times the exponential of reward divided by beta, normalized by a partition function Z that depends on the prompt. Take logs and solve for the reward: it equals beta times the log-ratio of the optimal policy to the reference, plus beta times log Z. Plug that into the Bradley–Terry preference model, which only uses the difference between the rewards of two responses to the same prompt, and the log Z terms cancel. Replacing the optimal policy with the trainable one and maximizing the likelihood of the observed preferences gives the DPO loss.
What does the beta parameter do in DPO?
Beta is the strength of the KL penalty in the RLHF objective that DPO solves. In the loss it multiplies the log-ratio between the policy and the reference model, so beta times that log-ratio is the implicit reward. A larger beta means a small change in the log-ratio already counts as a large reward difference, so the loss is satisfied while the policy stays close to the reference. A smaller beta lets, and requires, the policy move further away to fit the same preferences. The DPO paper used beta of 0.1 by default and 0.5 for its summarization experiments. In practice beta is tuned per dataset, and results are known to be sensitive to it.
Why does the partition function Z(x) cancel in DPO?
Because preference data always compares two responses to the same prompt. When the reward is rewritten in terms of the policy, it picks up an extra term, beta times log Z(x), where Z(x) sums over every possible response and cannot be computed. That term depends only on the prompt x, not on the response. The Bradley–Terry model uses only the difference between two rewards, r(x, y_w) minus r(x, y_l), and since both rewards contain the same beta log Z(x), it subtracts away exactly. If you compared responses to different prompts, two different Z terms would remain and the trick would fail, which is why DPO's data must be paired by prompt.
Does DPO need a reference model, and which one should it be?
Yes. The reference policy appears in every term of the loss: DPO raises the preferred response's probability relative to the reference and lowers the rejected one's, so the reference defines both the starting point and the anchor. The paper sets it to the supervised fine-tuned model the preference data was sampled from, whenever that model is available. When no such model exists, it first fine-tunes on the preferred responses and uses that as the reference, because a reference far from the data distribution makes the log-ratios unreliable. During training the reference stays frozen, and its log-probabilities for each pair can be computed once in advance, so it costs one extra forward pass per example rather than a model to train.
Is DPO better than PPO?
In the DPO paper, on its three tasks, yes. It traced a better reward-versus-KL frontier than PPO on controlled sentiment, won about 61% of GPT-4 comparisons against reference summaries versus about 57% for PPO on TL;DR, and was the only efficient method to beat the preferred responses on Anthropic's dialogue data. Later work is more mixed. A 2024 comparative study titled Is DPO Superior to PPO for LLM Alignment? found well-tuned PPO ahead in the settings it tested, including code generation, and the IPO paper argued DPO can overfit when preferences are close to deterministic. The usual reading is that DPO is the simpler, stable choice for a fixed preference dataset, and online RL can win when fresh samples are scored during training.
What is IPO, and what problem with DPO does it address?
IPO, identity preference optimization, comes from a 2023 Google DeepMind paper by Azar and colleagues that analyzes DPO within a more general framework. Their argument is that DPO's Bradley–Terry loss misbehaves when preferences are deterministic or nearly so, which is common in practice because each pair is usually labeled once. If y_w always beats y_l in the data, the loss keeps falling as the gap in log-ratios grows without limit, so the KL anchor to the reference model stops constraining the policy and it can overfit. IPO replaces the log-sigmoid with a squared loss that pulls the log-ratio gap toward a fixed target set by the regularization strength, so the optimum stays finite.
4 questions to test what you just read
Work each one out before you open it — a number, a prediction or a reason, not a definition. Producing the answer is what makes it stick. Your progress is kept on this device.
A pair has policy log-probs of −50 for the chosen response and −52 for the rejected one, and reference log-probs of −51 for both. What is the DPO loss at β = 0.1?
Show answer
Log-ratios: chosen −50 − (−51) = +1, rejected −52 − (−51) = −1, so the margin is 2. Loss = −log σ(0.1 × 2) = −log σ(0.2) = −log 0.550 ≈ 0.598. The gradient weight is σ(−0.2) ≈ 0.45, so this pair still gets a substantial push.
Why does Z(x) cancel in the DPO derivation, and why would it not if the two responses came from different prompts?
Show answer
The reparameterized reward is β·log(π/πref) + β·log Z(x), and Bradley–Terry uses only r(x, yw) − r(x, yl). With a shared prompt the two β·log Z(x) terms are identical and subtract to zero. With prompts x1 and x2, β·log Z(x1) − β·log Z(x2) remains, and neither term can be computed.
If you raise β from 0.1 to 1.0 on the same data, which way does the policy move relative to the reference, and why?
Show answer
Each log-ratio is now multiplied by 1.0 instead of 0.1, so the same margin gives a ten times larger implicit reward gap and the sigmoid saturates after much smaller changes. Training stops pushing earlier, and the policy stays closer to πref: less drift, but less of the preference signal absorbed.
During DPO training, the log-probabilities of both the chosen and the rejected responses can fall while the loss improves. How is that possible, given the form of the loss?
Show answer
The loss depends only on the difference of log-ratios. If log πθ(yl) falls faster than log πθ(yw), the margin grows and the loss drops even though yw became less likely too. Nothing in the loss anchors the absolute probability of the chosen response, so probability mass can flow to responses that appear in neither.
Teaching a base model to follow
A pre-trained model completes text; it does not take instructions. Nine papers on getting from one to the other, from RLHF to a loss with no reward model in it.
- 1InstructGPT2022
- 2Constitutional AI2022
- 3Self-Instruct2023
- 4LoRA2022
- 5QLoRA2023
- 6Direct Preference Optimization2023
- 7GRPO2024
- 8STaR2022
- 9Let's Verify Step by Step2023
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Paper Breakdowns
- Attention Is All You NeedThe paper that introduced the Transformer — the architecture underneath GPT, BERT, Claude, and Gemini. Self-attention, Query/Key/Value, multi-head attention, positional encoding, and the real BLEU results, explained in depth with analogies and animated visuals, not just equations.Read →
- BERTThe paper that made "pre-train once, fine-tune anywhere" the default for NLP. Bidirectional context, masked language modeling, next-sentence prediction, the [CLS]/[SEP] tokens, and the GLUE sweep — explained with analogies, not just equations.Read →
- Chain-of-Thought PromptingShow a model a few worked examples with their reasoning and it starts solving problems it used to fail. Why reasoning emerges only at scale, the GSM8K jump, zero-shot "Let's think step by step", and how CoT seeded modern reasoning models.Read →
- LoRAThe paper that made fine-tuning affordable. Freeze the giant pretrained model and train two tiny low-rank matrices instead — up to 10,000x fewer trainable parameters, no extra inference latency, and swappable per-task adapters. The road to QLoRA and PEFT.Read →
- ChinchillaThe compute-optimal scaling law that said models were too big. Parameters and training tokens should scale together — ~20 tokens per parameter — so a 70B model trained on 1.4T tokens beat the 280B giants. Why every model since trains on trillions of tokens.Read →
- FlashAttentionAttention was slow for the wrong reason. By treating it as a memory-movement problem — tiling, online softmax, keeping work in fast SRAM instead of slow HBM — FlashAttention makes exact attention several times faster and cuts its memory from quadratic to linear, unlocking long context windows.Read →