Chapter 6 · Post-training and Alignment 6.5
Preference Optimization: From RLHF to DPO
After SFT a model follows instructions, but its answers are not always the ones people prefer. Preference optimization aligns it using comparisons: RLHF trains a reward model and optimizes with PPO, while DPO reduces the pipeline to a classification-style loss on preference pairs.
After this page you will be able to
- Say why preference optimization is still needed after SFT, and what preference data looks like.
- Walk through the three RLHF steps: SFT, a reward model, and reinforcement learning with a KL constraint.
- Write the DPO loss, implement it in code, and explain how it hides the reward model inside the policy.
- Compare RLHF and DPO, and know what motivates the common variants.
On this page
- Why preference optimization is still needed
- What preference data looks like
- RLHF: the three-step pipeline
- Step 2: the reward model
- Step 3: reinforcement learning with a KL constraint
- DPO: hiding the reward model inside the policy
- What the loss is doing
- Implementation
- RLHF versus DPO
- Common variants
- Practical checklist
- Summary and exercises
- Quick self-check
- Further reading
- FAQ
Why preference optimization is still needed
SFT (supervised fine-tuning) teaches a model to “answer according to the instruction”, but it only teaches the model to imitate the given reference answers. It never says which of two reasonable answers is better, and that is exactly what we want to know: more helpful, more honest, safer, better in tone.
Preference optimization builds on a plain fact: for a person, comparing two answers is much easier than writing one perfect answer. A “better / worse” label on two answers to the same prompt is already a valuable training signal.
What preference data looks like
A preference example consists of a prompt and a pair of answers: the preferred one (chosen) and the rejected one (rejected):
{
"prompt": "Explain overfitting in one sentence.",
"chosen": "Overfitting happens when a model learns the noise in the training data as if it were signal, so it does well on the training set but badly on new data.",
"rejected": "Overfitting just means the model is too good."
}
Labels come mainly from two sources: human annotation (ranking several outputs of a model) and AI feedback (scoring with a stronger model or an explicit set of principles, as in Constitutional AI). Data quality matters more than quantity: inconsistent annotation guidelines, or a hidden bias such as “longer is better”, will be picked up directly by the model.
RLHF: the three-step pipeline
Reinforcement learning from human feedback (RLHF) is the standard pipeline established by InstructGPT (paper breakdown):
- SFT: fine-tune the base model on high-quality demonstrations to get .
- Train a reward model: use preference data to train a model that scores answers.
- Reinforcement learning: use the reward model’s score as the return and optimize the policy with PPO, while constraining it not to stray too far from the SFT model.
The best-known result of InstructGPT is that the 1.3B model after RLHF was preferred in human evaluation over the unaligned 175B GPT-3.
Step 2: the reward model
A reward model is usually an SFT model whose output layer is replaced by a scalar head. Its training rests on the Bradley–Terry model: the probability that answer is preferred over equals the sigmoid of the difference between their rewards:
Maximum likelihood on the preference data gives the loss of the reward model:
In other words, the reward model is trained to give the preferred answer a higher score than the rejected one. The details of this step (how a reward is fitted from pairwise comparisons, why the loss only sees differences, and what label noise does to the accuracy ceiling) come with runnable experiments on the Reward Models page; only the loss needed below is kept here.
Step 3: reinforcement learning with a KL constraint
The policy is optimized to maximize reward while penalizing the KL divergence from a reference model (usually the SFT model):
The KL constraint does two things: it keeps the language fluent and the model close to what SFT learned, and it keeps the policy from exploiting the reward model. In implementations, the per-token KL estimate is usually folded into the return at every step, and PPO’s clipped objective and a value function estimate the advantage to update the policy. The derivations, and small experiments on where the KL term goes (into the reward or into the loss) and what PPO’s clipping does, are in Reinforcement Learning Basics.
This pipeline is expensive: during training you must hold four models at once (policy, reference, reward and value models), generate a large number of answers online, tune many hyperparameters, and put up with unstable training.
The reward model is only an approximation of human preferences. The policy learns to maximize the approximation instead of truly getting better: writing longer, more flattering answers, or piling on formatting. In the experiments of Gao et al., a larger “gold-standard” reward model stood in for true preferences, and as the policy drifted further from the reference model the proxy reward kept rising while the quality measured by the gold-standard model first rose and then fell. KL constraints, early stopping, reward-model ensembles and refreshing the reward model with new samples are the usual mitigations.
How this rise-then-fall curve changes with the amount of reward-model training data, and how the KL of best-of-N is computed, is worked out item by item with simulations on the Reward Models page.
DPO: hiding the reward model inside the policy
The core insight of DPO (Direct Preference Optimization) is that the KL-constrained optimization problem above has a closed-form solution, so the reward function can be expressed through the optimal policy itself, and both the reward model and reinforcement learning can be dropped. The derivation takes three steps.
Step 1: the form of the optimal policy. The optimal solution of the KL-constrained objective is
where is a normalizing constant that depends only on . Intuitively, the optimal policy reweights the reference model by the “exponential of the reward”.
Step 2: solve for the reward. Take the logarithm of both sides and rearrange:
Step 3: plug into the Bradley–Terry model. The preference probability depends only on the difference of the two rewards. Because both answers belong to the same prompt , the intractable cancels exactly in the subtraction:
The optimal policy is of course unknown, so we replace it with a trainable and do maximum likelihood on the preference data, which gives the DPO loss:
There is no reward model, no sampling and no value function in this expression: all that is needed are the log-probabilities of the policy and the reference model on the chosen and rejected answers.
What the loss is doing
Define the implicit reward . The loss makes the implicit reward of the chosen answer higher than that of the rejected one. Its gradient is
The reading is intuitive: raise the probability of the chosen answer and lower the probability of the rejected one; the weight measures how wrongly ranked the implicit rewards are, so the more wrong the ranking, the bigger the update, and examples that are already ranked correctly get a naturally smaller weight.
Implementation
import torch
import torch.nn.functional as F
def sequence_logprob(logits, labels, mask):
"""Take per-token log-probabilities and sum them over the response part. logits: [B, T, V], labels/mask: [B, T]."""
logp = torch.log_softmax(logits, dim=-1).gather(-1, labels.unsqueeze(-1)).squeeze(-1)
return (logp * mask).sum(dim=-1)
def dpo_loss(pi_chosen, pi_rejected, ref_chosen, ref_rejected, beta=0.1):
"""All four inputs are log-probabilities of whole responses, with shape [B]."""
chosen_reward = beta * (pi_chosen - ref_chosen)
rejected_reward = beta * (pi_rejected - ref_rejected)
loss = -F.logsigmoid(chosen_reward - rejected_reward).mean()
accuracy = (chosen_reward > rejected_reward).float().mean()
return loss, accuracy
Here mask is 1 only on the response part (the prompt is not counted), and logits and labels have already been shifted so that each position predicts the next token.
A worked example: the policy’s log-probability of the chosen answer is and the reference model’s is ; for the rejected answer they are and ; take .
- Implicit reward of chosen:
- Implicit reward of rejected:
- The margin is , and the loss is
Another very practical sanity check: at the start of training the policy equals the reference model, all implicit rewards are 0, and the loss should be exactly . If the loss at the first step deviates from this value, the log-probability computation or the alignment of the tensors is most likely wrong.
RLHF versus DPO
| RLHF (PPO) | DPO | |
|---|---|---|
| Reward model | Trained separately | Not needed (implicit reward) |
| Training data | Prompts + online sampling + reward scoring | Offline preference pairs |
| Models loaded at once | Policy, reference, reward, value (4) | Policy, reference (2) |
| Implementation and tuning | Complex, sensitive to hyperparameters | Simple, close to ordinary supervised training |
| Main risks | Reward hacking, unstable training | Distribution shift of offline data, length bias |
DPO greatly lowers the barrier to alignment: the post-training of Llama 3 used several rounds of “SFT + rejection sampling + DPO” and did not use PPO. But DPO has limits too:
- Distribution shift of offline data: preference pairs are often generated by other models instead of the current policy, and during training the policy’s output distribution gradually drifts away from this data. A common remedy is iterative (online) DPO: in each round, sample from the current policy, label preferences with a reward model or a judge model, and train the next round.
- The probability of chosen can fall too: the loss only asks for the gap to widen, so the log-probabilities of chosen and rejected can drop together.
- Length bias: longer answers tend to be preferred in preference data, and DPO amplifies this.
Common variants
Around these shortcomings of DPO, many variants have appeared:
| Method | Approach | When to use |
|---|---|---|
| IPO | Replaces the sigmoid loss with a squared loss to reduce overfitting to preference labels | Noisy preference data, a model that overfits easily |
| KTO | Needs no pairs, only a binary “good / bad” label per answer | Only thumbs-up / thumbs-down data is available |
| SimPO | Drops the reference model, uses the length-normalized average log-probability as the reward, and adds a target margin | Save memory, mitigate length bias |
| ORPO | Adds an odds-ratio-based preference penalty directly to the SFT loss, finishing SFT and alignment in one stage | Merge SFT and preference optimization into one step |
Practical checklist
- Start from the SFT model and use it as the reference. The reference model should be close to the distribution of the preference data, or the implicit reward is meaningless. If you train with LoRA, the base model with the adapter switched off can act as the reference, so you do not need to load another copy.
- Start β at 0.1. The learning rate of full-parameter DPO is typically on the order of (Zephyr used ), one or two orders of magnitude smaller than SFT.
- Pay attention to data quality. Zephyr aligned a 7B model well with about 60,000 AI-labeled preference pairs. Cleaning out conflicting labels and pairs that are too short or too long is often more effective than adding more data.
- Monitor these metrics: implicit-reward accuracy (the fraction of pairs where the chosen reward exceeds the rejected one), the reward margin, the change in log-probabilities of chosen and rejected, the average generation length, and general-capability benchmarks (to guard against the alignment tax).
- Control for length in evaluation. When using MT-Bench, AlpacaEval and similar benchmarks, use length-controlled versions, otherwise “more verbose” will be mistaken for “better”. Why judges favor long answers and how to correct for it is covered in LLM-as-a-Judge: Using a Model as the Grader, Its Biases and Calibration.
- When answers are verifiable, consider rule-based rewards directly. Tasks such as math and code can be rewarded by whether the answer is correct, with no need for a reward model that is easy to game. That is the subject of the next chapter, Reinforcement Learning for Reasoning: RLVR and GRPO.
Summary and exercises
Key points of this page:
- Preference optimization aligns a model with comparison signals of “which answer is better”, making up for SFT’s limitation of only imitating.
- RLHF has three steps: SFT, a reward model (Bradley–Terry) and PPO with a KL constraint; it is powerful but expensive and carries the risk of reward hacking.
- DPO uses the closed-form solution of the KL-regularized objective, writes the reward as the log-probability ratio between the policy and the reference model, and reduces the whole pipeline to a classification-style loss.
- DPO is simple and efficient, but is affected by the offline data distribution and by length bias; iterative DPO and various variants mitigate these issues.
Quick self-check
1. Why does the RLHF objective subtract the KL divergence between the policy and the reference model?
- To make the reward model’s scores higher
- To keep the policy from drifting too far from the reference model (usually the SFT model), which keeps the language fluent and stops the policy from exploiting the reward model
- To make training converge faster
- To increase the diversity of the answers
The KL constraint is a form of regularization. A reward model is only reliable on a limited data distribution; without the constraint the policy drifts into regions it has never seen and exploits its loopholes to score high (reward hacking), while the language quality gets worse.
2. Why can DPO do without a reward model and without reinforcement learning?
- Because DPO uses human ratings directly and needs no reward
- Because the KL-constrained reward maximization problem has a closed-form solution, the reward can be written as the log-probability ratio between the policy and the reference model, and maximum likelihood on the preference data becomes a loss on the policy directly
- Because DPO trains on SFT data only
- Because DPO replaces the reward model with a smaller value model
The DPO loss contains only the log-probabilities of the policy and the reference model on the chosen and rejected answers: no reward model, no online sampling and no value function.
3. Take β = 0.2. The policy log-probability of chosen is −10.0 and the reference model’s is −10.4; for rejected they are −13.0 and −12.0. About what is the DPO loss?
- 0.220
- 0.280
- 0.563
- 0.693
The implicit reward of chosen is 0.2×(−10.0+10.4)=0.08 and that of rejected is 0.2×(−13.0+12.0)=−0.20, so the margin is 0.28 and the loss is −ln σ(0.28)≈0.563. 0.280 is the margin, not the loss; 0.220 comes from forgetting to multiply by β (margin 1.4); 0.693 is the loss at the very start of training.
4. At the start of training, when the policy still equals the reference model, what should the DPO loss be?
- 0
- ln 2 ≈ 0.693
- 1
- It depends on β
All implicit rewards are 0, the margin is 0, and the loss is −ln σ(0) = ln 2 ≈ 0.693, independent of β. If the loss of the first step deviates from this value, the log-probability computation or the alignment of tokens is most likely wrong.
5. In DPO you raise β from 0.1 to 0.5 and change nothing else. What does that usually mean?
- The policy departs from the reference model more aggressively
- A stronger constraint: a small change in probability is enough to push the loss down, so the policy stays closer to the reference model
- The preference data gets a smaller weight
- The learning rate becomes larger
β multiplies the log-probability ratio: for the same change in probability the margin is enlarged, the loss falls faster and the gradient weight shrinks sooner. In the example on this page the margin grows from 0.15 to 0.75 and the loss falls from 0.621 to 0.387.
6. While training with DPO you see the log-probability of chosen going down. Is that necessarily an implementation bug?
- Yes, DPO guarantees that the probability of chosen always rises
- Not necessarily; the loss only asks the margin of chosen over rejected to grow, so both log-probabilities can fall together
- Yes, it means the learning rate is too small
- No, it means β is too small
The DPO loss looks only at the margin: it guarantees that “chosen moves in the right direction relative to rejected”, not that the probability of chosen rises. A more reliable check of the implementation is whether the initial loss is ln 2 and what the implicit-reward accuracy is.
Exercises:
- How does DPO behave as approaches 0 and as it approaches infinity?
- Why does cancel in the derivation of the DPO loss? Would it still hold if the two answers belonged to different prompts?
- Change the rejected policy log-probability in the worked example to (the same as the reference model). Does the loss get larger or smaller?
Reference answers
- As , the KL constraint almost vanishes and the scale of the implicit reward is tiny, so the policy can drift from the reference model almost without limit and easily overfits the preference data; as , the constraint is very strong, the policy hardly leaves the reference model, and it learns nothing of the preferences.
- Because Bradley–Terry only uses the difference of the rewards of two answers to the same prompt, and depends only on the prompt, it cancels in the subtraction. If the two answers belonged to different prompts, would differ and could not cancel.
- The implicit reward of rejected becomes , the margin shrinks from to , and the loss is , which is larger than the original .
Further reading
- Christiano et al., Deep Reinforcement Learning from Human Preferences (2017)
- Stiennon et al., Learning to summarize from human feedback (2020); paper breakdown
- Ouyang et al., Training language models to follow instructions with human feedback (InstructGPT, 2022); see also the paper breakdown on this site
- Schulman et al., Proximal Policy Optimization Algorithms (2017); paper breakdown
- Gao et al., Scaling Laws for Reward Model Overoptimization (2022)
- Rafailov et al., Direct Preference Optimization: Your Language Model is Secretly a Reward Model (2023); paper breakdown
- Bai et al., Constitutional AI: Harmlessness from AI Feedback (2022); explainer: Constitutional AI
- Tunstall et al., Zephyr: Direct Distillation of LM Alignment (2023)
- Ethayarajh et al., KTO: Model Alignment as Prospect Theoretic Optimization (2024)
- Meng et al., SimPO: Simple Preference Optimization with a Reference-Free Reward (2024)
- An industrial recipe: six rounds of reward model, rejection sampling, SFT, DPO and model averaging, and why the authors picked DPO over PPO: see the Llama 3 breakdown.
FAQ
- What is the difference between RLHF and DPO, and which should I choose?
- RLHF first trains a reward model on preference data, then uses a reinforcement learning algorithm such as PPO to sample online and optimize the policy. DPO uses the closed-form solution of the KL-regularized objective, hides the reward inside the log-probability ratio between the policy and a reference model, and trains with supervised learning directly on preference pairs, with no reward model and no online sampling. When resources are limited and you already have preference data, start with DPO; consider online reinforcement learning when you need online exploration, verifiable rewards or a higher ceiling.
- What is β in DPO and how should I set it?
- β controls how far the policy may drift from the reference model: the larger β is, the stronger the constraint and the more conservative the model; the smaller β is, the more aggressive the updates. A common starting point is 0.1, which you can adjust between 0.01 and 0.5 while watching the implicit-reward margin, the generation length and general-capability benchmarks.
- Why does preference optimization need a reference model and a KL constraint?
- A reward model is only reliable on a limited data distribution. Without a constraint the policy drifts into regions the reward model has never seen and exploits its flaws to score high (reward hacking), while language quality actually drops. The KL constraint keeps the policy close to the SFT model and acts as regularization.
- After DPO training the answers become long and rambling. What can I do?
- A common bias in preference data is that longer answers are more likely to be chosen, and DPO amplifies it. You can balance the length distribution of the preference pairs, use a length-normalized variant (such as SimPO), use length-controlled metrics in evaluation, and check whether the model is padding its answers unnecessarily.