AI
Direct Preference Optimization (DPO) Explained
Direct preference optimization (DPO) explained: how it aligns LLMs from preference pairs without a reward model or RL, with the loss, code and pitfalls.
Direct preference optimization (DPO) is a way to teach a language model which of two answers people prefer, without training a separate reward model and without reinforcement learning. You give it examples made of a prompt, a preferred ("chosen") answer and a worse ("rejected") answer. Training then nudges the model to make the chosen answer more likely and the rejected one less likely, relative to a frozen copy of the starting model. That keeps the update stable and stops the model drifting too far.
DPO was introduced in 2023 by Rafailov and colleagues in a paper with the memorable subtitle "Your Language Model is Secretly a Reward Model". It quickly became one of the most widely used alignment methods for open models because it's far simpler to run than classic RLHF. This guide explains how direct preference optimization works, the loss in plain terms with a worked example, how DPO compares with RLHF, PPO and supervised fine-tuning, how to train with it in code, its main variants and the mistakes to avoid.
Direct Preference Optimization at a Glance
| What it does | Aligns a model to preferences using pairs of better and worse answers |
| Input data | Prompt, chosen response, rejected response |
| Needs a reward model? | No; the model's own probabilities act as an implicit reward |
| Needs reinforcement learning? | No; it's a classification-style loss trained like fine-tuning |
| Extra model in memory | A frozen reference model (usually the supervised fine-tuned starting point) |
| Key setting | β (beta): how strongly the model may move away from the reference; 0.1 is TRL's default |
| Typical place in training | After supervised fine-tuning (SFT) |
| Introduced | 2023 (Rafailov et al.) |
Why Preference Training Exists
A model trained only on next-token prediction learns to continue text, not to follow instructions well or behave safely. Supervised fine-tuning fixes much of that by training on good example answers. But many qualities are easier to judge than to write. Is this answer clearer, more honest or more helpful than that one? People can usually pick the better of two answers even when they couldn't write the ideal one.
RLHF (reinforcement learning from human feedback) uses those comparisons in three stages. First supervised fine-tuning, then a reward model trained to score answers the way people do, then reinforcement learning (usually PPO) to make the model produce high-scoring answers while staying close to the original. It works, but it's complex: several models in memory, sampling during training and many settings to tune. Our guide to RLHF explains the full pipeline.
DPO's insight was that the RLHF objective can be rewritten so the optimal model can be trained directly from the preference pairs, with a simple loss and no separate reward model or RL loop.
How Direct Preference Optimization Works
Here's how direct preference optimization works, step by step:
- Start from a supervised fine-tuned model. Make a frozen copy of it: the reference model.
- Collect preference pairs. For each prompt, one chosen and one rejected response, judged by people, a stronger model or rules.
- Score both responses with both models. For each response, compute how likely the training model makes it compared with the reference model (a log-probability ratio).
- Compare chosen against rejected. DPO's implicit reward for a response is β times that log-ratio. The loss rewards the model when the chosen response's implicit reward is higher than the rejected one's.
- Update the model, never the reference, and repeat over the dataset.
In formula form, for prompt x, chosen answer y⁺ and rejected answer y⁻:
Loss = −log σ( β × [ (log π(y⁺|x) − log π_ref(y⁺|x)) − (log π(y⁻|x) − log π_ref(y⁻|x)) ] )
Here π is the model being trained, π_ref the frozen reference and σ the sigmoid function. In words: increase the gap between how much the model has raised the chosen answer's probability and how much it has raised the rejected answer's, relative to where it started. β controls how strongly the model is allowed to move away from the reference.
A worked example with real numbers
Suppose, for one pair, the model and reference give these log-probabilities:
| Training model | Reference model | Log-ratio | |
|---|---|---|---|
| Chosen answer | −40 | −42 | +2 |
| Rejected answer | −45 | −44 | −1 |
The difference of log-ratios is 2 − (−1) = 3. With β = 0.1, the argument is 0.3. Then σ(0.3) ≈ 0.574, and the loss is −log(0.574) ≈ 0.554.
How the loss changes as the model learns:
| Difference of log-ratios | β × difference | σ | Loss |
|---|---|---|---|
| −3 (model prefers the rejected answer) | −0.3 | 0.426 | 0.854 |
| 0 (no preference yet) | 0 | 0.5 | 0.693 |
| 3 | 0.3 | 0.574 | 0.554 |
| 30 (strong preference) | 3.0 | 0.953 | 0.049 |
The loss falls as the model separates chosen from rejected answers, and the gradient is largest on pairs the model still gets wrong.
What Is DPO vs RLHF?
What is DPO vs RLHF in practical terms? Both aim at the same goal, a model that produces the responses people prefer while staying close to its starting point. They get there differently:
| RLHF with PPO | DPO | |
|---|---|---|
| Stages after SFT | Train a reward model, then run RL | One training stage |
| Models in memory during training | Policy, reference, reward model, value model | Policy and reference |
| Generates samples during training? | Yes (on-policy) | No (offline, from a fixed dataset) |
| Stability | Sensitive to many hyperparameters | Generally stable, few settings |
| Compute cost | Higher | Lower |
| Can explore new answers? | Yes: learns from its own fresh outputs | No: only learns from the pairs given |
| Reusable reward model? | Yes, for scoring or filtering later | No separate reward model |
The original paper reported that DPO matched or beat PPO-based RLHF at controlling sentiment and on summarisation and dialogue tasks, while being simpler. Later work has found that on-policy RL can still win on some tasks, especially reasoning, because it learns from the model's own new attempts. Many labs now use both: DPO-style training for preference and style, and RL with verifiable rewards for reasoning.
Is DPO the Same as PPO?
Is DPO the same as PPO? No. PPO (proximal policy optimization) is a reinforcement learning algorithm. In RLHF it updates the model using rewards from a reward model on responses the model generates during training. DPO isn't reinforcement learning at all. It's a supervised-style loss on a fixed set of preference pairs. They're related because DPO was derived from the same objective that RLHF with PPO optimises: maximise reward while staying close to a reference model. DPO solves that objective in closed form instead of with RL.
Direct Preference Optimization vs Supervised Fine Tuning
Direct preference optimization vs supervised fine tuning is about what the model learns from:
- Supervised fine-tuning shows the model good answers and trains it to imitate them. It learns what to do, but not what to avoid.
- DPO shows the model pairs and trains it to prefer one over the other. It learns from contrast: "this, not that".
They work best together. SFT gets the model into the right format and behaviour; DPO then sharpens preferences, such as being concise instead of rambling, refusing harmful requests without over-refusing, or following a house style. Running DPO on a model that hasn't had SFT usually works poorly, because the reference model rarely produces the kind of responses in the preference data. For the SFT side, see our guide on how to fine-tune an LLM.
Training a Model With DPO
The Hugging Face TRL library provides a DPOTrainer. Its quick-start trains a small model on a public preference dataset:
from trl import DPOTrainer
from datasets import load_dataset
trainer = DPOTrainer(
model="Qwen/Qwen3-0.6B",
train_dataset=load_dataset("trl-lib/ultrafeedback_binarized", split="train"),
)
trainer.train()Each example needs a prompt, a chosen response and a rejected response, in either plain text or chat format:
example = {
"prompt": [{"role": "user", "content": "What color is the sky?"}],
"chosen": [{"role": "assistant", "content": "It is blue."}],
"rejected": [{"role": "assistant", "content": "It is green."}],
}Practical settings: TRL's defaults are β = 0.1 and a learning rate of 1e-6, much lower than typical SFT learning rates, because DPO updates can move a model quickly. Parameter-efficient methods such as LoRA work with DPO and cut memory, and the reference model can then be the same base weights with the adapter switched off.
Where preference data comes from
- Human comparisons: people pick the better of two responses. Expensive, but the gold standard for subjective qualities.
- AI feedback: a stronger model ranks responses. Zephyr-7B, an early well-known DPO model, was trained this way on AI-ranked data.
- Rules and tests: for code or maths, a response that passes tests is "chosen" and one that fails is "rejected".
- Your own product: thumbs up and down, edits users make to drafts, or A/B choices.
DPO Variants
DPO spawned a family of related methods. TRL supports many of them as alternative loss types:
| Method | Key idea | Needs reference model? | Data |
|---|---|---|---|
| DPO | Logistic loss on the difference of log-ratios | Yes | Pairs |
| IPO | Identity transform instead of logistic, to reduce overfitting to preferences | Yes | Pairs |
| KTO | Based on prospect theory; learns from single responses labelled good or bad | Yes | Unpaired good/bad labels |
| ORPO | Combines SFT and a preference penalty in one stage | No | Pairs |
| SimPO | Uses the average log-probability of a response as the reward | No | Pairs |
KTO is useful when you only have thumbs-up and thumbs-down data rather than pairs. ORPO and SimPO drop the reference model, which saves memory. None is best everywhere, so evaluate on your own tasks.
Common Problems and How to Avoid Them
- Over-optimisation. With too high a learning rate or too many epochs, the model can drift, lose general ability or become oddly verbose. Use a low learning rate, few epochs and a held-out evaluation set.
- Length bias. If chosen answers in your data tend to be longer, the model learns "longer is better". Balance lengths in the data or use a length-normalised variant.
- Both probabilities falling. DPO only cares about the gap between chosen and rejected, so it can lower the probability of both while widening the gap. Watch the chosen responses' log-probabilities during training; some recipes add a small SFT loss to keep them up.
- Off-distribution data. If the pairs look nothing like what your model would write, DPO learns less. Generating candidates from your own SFT model and ranking them often works better.
- Noisy labels. Inconsistent preferences teach inconsistent behaviour. Check agreement between labellers, and remove ties and near-duplicates.
- No evaluation. Measure before and after on your real tasks, including safety and over-refusal. Our guide to LLM evaluation covers building test sets.
FAQ
What does direct preference optimization do?
It trains a language model to prefer certain responses over others, using pairs of chosen and rejected answers. The result is a model whose outputs better match the preferences in the data, such as helpfulness, safety or style.
Is DPO reinforcement learning?
No. DPO is derived from the reinforcement learning objective used in RLHF, but it trains with a simple supervised-style loss on a fixed dataset, without a reward model or sampling during training.
How much data does DPO need?
It depends on the goal. Narrow style or format changes can work with a few thousand good pairs; broad alignment of a general assistant uses tens or hundreds of thousands. Quality and consistency matter more than raw size.
Can I use DPO with a closed model like GPT or Claude?
Only if the provider offers preference fine-tuning for that model. DPO needs access to the model's weights and log-probabilities, so it's mainly used with open-weight models.
What value should beta be?
0.1 is a common default. A lower β lets the model move further from the reference to fit the preferences; a higher β keeps it closer. Tune it against an evaluation set rather than training loss alone.