Direct Preference Optimization
local graph
Chapter 24 — Direct Preference Optimization
Section titled “Chapter 24 — Direct Preference Optimization”The RLHF pipeline of the last chapter is powerful but heavy: a separate reward model, four models in memory, and a temperamental reinforcement-learning loop. Direct Preference Optimization (DPO) asks a sharp question — if the goal is just to prefer good responses over bad ones, why train a reward model and run RL at all? — and answers it with a single supervised loss on preference pairs. DPO is simpler, more stable, and works well enough that it became the default preference-alignment method for much of the open-source community. This short chapter explains the insight and the loss.
24.1 The Key Insight
Section titled “24.1 The Key Insight”DPO rests on a piece of mathematics. The RLHF objective of Chapter 23 — maximize reward subject to a KL penalty toward the reference — has a known optimal solution, and that solution relates the reward to the policy in closed form: the optimal policy’s log-probability ratio against the reference is the reward, up to a constant. Read backward, this says you can express the reward in terms of the policy itself. Substituting that expression into the Bradley-Terry preference loss of Chapter 23 makes the reward model cancel out entirely, leaving a loss that depends only on the policy’s and reference’s log-probabilities of the chosen and rejected responses. The reward model was never necessary; it was implicit in the policy all along.
24.2 The DPO Loss
Section titled “24.2 The DPO Loss”The result is a loss as simple as SFT’s, computed over preference pairs. For each pair, take the policy’s and the frozen reference’s summed log-probabilities of the chosen and rejected responses; the loss pushes the policy to raise the relative likelihood of the chosen response over the rejected one, beyond what the reference already assigns:
def dpo_loss(logp_chosen, logp_rejected, ref_logp_chosen, ref_logp_rejected, beta=0.1): # logp_*: summed log-prob of a response under policy / reference chosen = logp_chosen - ref_logp_chosen # policy vs reference, chosen rejected = logp_rejected - ref_logp_rejected # policy vs reference, rejected return -F.logsigmoid(beta * (chosen - rejected)).mean()Python — dpo.py: the Direct Preference Optimization loss
Compare this to the reward-model loss of Chapter 23: it is the same Bradley-Terry shape, but the “reward” of each response is now the policy’s log-ratio against the reference rather than a separate network’s score. There is no sampling, no reward model, and no RL — just a forward pass of the policy and the frozen reference over fixed preference pairs, and a standard gradient step. The coefficient beta plays the role of the KL strength from PPO, controlling how far the policy may move from the reference. Table 24.1 contrasts the two approaches.
| Aspect | RLHF / PPO | DPO |
|---|---|---|
| Reward model | separate, trained first | implicit — none |
| Training | RL loop: sample, score, update | supervised loss on pairs |
| Models in memory | policy, reference, reward, value | policy + frozen reference |
| Stability | finicky to tune | stable, SFT-like |
| Fresh on-policy samples | yes (generates during training) | no (fixed preference data) |
Table 24.1 — RLHF (PPO) versus DPO
24.3 Variants and When to Use Which
Section titled “24.3 Variants and When to Use Which”DPO’s simplicity spawned a family of refinements. IPO addresses a tendency to overfit confident preferences; KTO learns from unpaired good/bad labels instead of pairwise comparisons, which are cheaper to collect; SimPO removes even the reference model. The practical guidance is straightforward: DPO (or a variant) is the right default for most preference alignment — simple, cheap, and stable. PPO-style online RL retains an edge when you can afford it and want the policy to learn from its own fresh generations rather than a fixed dataset, which matters most for the frontier capability we turn to next: reasoning. There, a different RL method — GRPO — trains the model on problems it can verify, and it is the engine behind DeepSeek-R1.
In practice the loss above is wrapped, like SFT, in a few lines of trl. The real recipe takes a model, a frozen reference, and a dataset of preference triples, and handles the reference-log-probability bookkeeping for you:
from trl import DPOTrainer, DPOConfig
# dataset rows: {"prompt", "chosen", "rejected"}trainer = DPOTrainer( model=model, # the policy (often an SFT model) ref_model=None, # None -> a frozen copy of model args=DPOConfig(beta=0.1, learning_rate=5e-7), train_dataset=pref_dataset,)trainer.train()Python — huggingface/trl: DPO training (reproduced, Apache 2.0)
The mapping to the loss is direct: beta is the same KL-strength coefficient from the dpo_loss function; ref_model=None tells the trainer to snapshot a frozen copy of the policy as the reference; and each row’s chosen and rejected fields are the preferred and dispreferred responses whose log-probabilities the loss compares. There is no reward model to train and no sampling loop — the entire alignment is this single trainer over a fixed preference dataset. The DPO paper derives the loss from the RLHF objective of Chapter 23; trl additionally implements the IPO, KTO, and other variants of Section 24.3 through the same trainer. For most teams aligning an open model to preferences, this is the shortest, sturdiest path there is.
SFT taught the model to follow instructions; preference optimization taught it which responses humans prefer. Neither, however, directly teaches a model to reason — to work through a hard problem step by step and arrive at a correct answer. That capability turned out to be learnable by reinforcement learning against automatically verifiable rewards, and the recipe — GRPO, as used in DeepSeek-R1 — is one of the most important results in recent open research. It is the subject of the next chapter.
24.4 Worked Example: The DPO Loss in One Line
Section titled “24.4 Worked Example: The DPO Loss in One Line”Direct Preference Optimization (Chapter 24) replaces the entire RL loop with a classification loss on preference pairs: raise the chosen response and lower the rejected one, each measured relative to a frozen reference model. The reward is implicit in the log-ratio:
# log-probs of chosen / rejected under the policy and the frozen referencechosen = beta * (logp_chosen - ref_logp_chosen)reject = beta * (logp_reject - ref_logp_reject)loss = -F.logsigmoid(chosen - reject).mean()# this single expression targets RLHF's optimum (Chapter 24): the reward# is the policy's log-ratio against the reference, never modeled explicitlyPython — DPO: a preference-pair loss, no reward model, no RL
24.5 Why DPO Drifts, and How to Anchor It
Section titled “24.5 Why DPO Drifts, and How to Anchor It”The DPO loss of Section 24.2 increases the margin by which the policy prefers the chosen response over the rejected one. But a margin is a difference, and nothing in the objective pins the two absolute likelihoods in place: the model can widen the gap while pushing both the chosen and rejected log-probabilities down. This failure mode — sometimes called likelihood displacement — degrades fluency even as the preference metric improves. The common fix anchors the chosen response with a small supervised term:
chosen_margin = chosen_logp - chosen_ref_logprejected_margin = rejected_logp - rejected_ref_logp
dpo = -F.logsigmoid(beta * (chosen_margin - rejected_margin))nll = -chosen_logp.mean() # keep the good answer likely
loss = dpo + alpha * nll # alpha small, e.g. 0.05-0.1Python — dpo/anchored.py: DPO with a chosen-likelihood anchor
The added negative-log-likelihood term re-introduces a piece of the SFT objective (Chapter 22): it rewards the policy for keeping the chosen response probable in absolute terms, not merely more probable than the rejected one. With alpha small, this barely perturbs the preference signal while removing the incentive to win by making everything worse. Several popular DPO variants are, at heart, different ways of supplying this same anchoring pressure.
24.6 Worked Example: One DPO Step, by the Numbers
Section titled “24.6 Worked Example: One DPO Step, by the Numbers”Make the loss concrete. Suppose for one preference pair the policy and the frozen reference assign these per-response log- probabilities (summed over tokens):
| Response | Policy log p | Reference log p | Margin |
|---|---|---|---|
| Chosen | -12.0 | -12.5 | +0.5 |
| Rejected | -14.0 | -13.0 | -1.0 |
Table 24.1 — Log-probabilities for one preference pair
With beta = 0.1, the loss is . The gradient pushes the chosen margin up and the rejected margin down — that is, it raises the policy’s preference for the chosen response relative to the reference and lowers it for the rejected one. Notice that the reference log- probabilities enter only as fixed offsets: DPO never needs a reward model or a sampling loop, which is the entire reason it replaced the PPO pipeline of Chapter 23 for preference alignment. The reference model is consulted, frozen, exactly twice per pair, and the rest is a single logistic loss.
A margin needs an anchor Optimizing a difference of likelihoods can be satisfied by lowering both. Production DPO almost always adds a small term that keeps the chosen response likely in absolute terms — without it, preference accuracy can rise while the model quietly gets worse at writing.
24.7 The DPO Family: IPO, KTO, and Beyond
Section titled “24.7 The DPO Family: IPO, KTO, and Beyond”DPO’s simplicity made it a starting point rather than a final answer, and a family of variants now addresses its known weaknesses. Each keeps DPO’s core idea — optimize preferences directly, without a reward model — while changing one ingredient:
| Method | Key change | Buys you |
|---|---|---|
| DPO | logistic loss on the margin | the original; simple |
| IPO | squared loss on the margin | less overfitting to preferences |
| KTO | single label, not pairs | cheaper data (thumbs up/down) |
| SimPO | no reference model | lower memory; length control |
Table 24.2 — Selected members of the DPO family
The differences encode different bets about what limits alignment. IPO observes that DPO’s logistic loss can drive the preference margin arbitrarily large and overfit to the training pairs, and replaces it with a bounded squared loss. KTO makes a data-collection argument: paired comparisons are expensive, but a single thumbs-up or thumbs-down per response is cheap and plentiful, so it reformulates the objective to learn from unpaired binary feedback. SimPO removes the reference model entirely, normalizing by length instead, trading a little principle for lower memory and better control of response length. None is universally best; the choice follows from which constraint — data cost, overfitting, memory, length — binds hardest in your setting, and knowing the family lets you pick deliberately rather than defaulting.
One idea, many dialects The DPO family all optimize preferences without a reward model; they differ in the loss shape, whether data must be paired, and whether a reference model is kept. Match the variant to your tightest constraint — data, memory, or overfitting.
24.8 The Implicit Reward in DPO
Section titled “24.8 The Implicit Reward in DPO”DPO can look like a trick — aligning to preferences with no reward model and no reinforcement learning — but it rests on a precise theoretical result, and seeing it demystifies the whole method. The insight is that the optimal policy of the RLHF objective (maximize reward subject to a KL penalty, Section 23.6) has a known closed form in terms of the reward, and that relationship can be inverted:
he reward implied by any policy is, up to a constant, the log-ratio of that policy to the reference.
In other words, the quantity — the scaled log-ratio of the policy to the frozen reference — is an implicit reward function. DPO substitutes this implicit reward into the Bradley-Terry preference loss of Section 23.9, and the two stages of RLHF collapse into one: fitting a reward model and then running RL against it becomes a single supervised loss on the policy itself. This is why DPO needs no reward model (the policy is the reward model, implicitly) and no sampling loop (the loss is computed directly on the preference pairs). The reference model that appears in every DPO formula is exactly the of this relationship, and the margin DPO optimizes (Section 24.6) is the difference of these implicit rewards between the chosen and rejected responses — the RLHF reward comparison, in disguise.
The policy is its own reward model DPO works because the RLHF-optimal policy and its reward are two views of one relationship. The scaled policy-to-reference log-ratio is an implicit reward, so optimizing preferences on the policy directly is RLHF with the reward model folded in.
24.9 Length Bias in Preference Optimization
Section titled “24.9 Length Bias in Preference Optimization”Preference optimization carries a notorious and instructive failure mode: models trained on preferences tend to drift toward producing longer responses, whether or not the extra length adds value. The cause is a subtle form of reward hacking (Section 23.6). Human raters, and the AI judges that imitate them (Section 29.7), often prefer longer, more detailed answers — so “longer” becomes correlated with “preferred” in the training data, and the model learns to exploit that correlation, inflating its responses because length itself has become a proxy for quality.
DPO is particularly susceptible, because its objective directly maximizes the margin between preferred and rejected responses and has no built-in penalty for verbosity. The result is a model that has, in effect, learned that padding its answers raises its reward — a real and frequently observed outcome, not a hypothetical one. The mitigations target the proxy directly: length normalization in the loss, so that the model is rewarded for quality per token rather than total length (the approach SimPO takes, Section 24.7); explicit length penalties; and curating the preference data so that the chosen responses are not systematically longer than the rejected ones, breaking the correlation at its source. Length bias is worth dwelling on because it is the clearest everyday example of the central hazard of optimizing a proxy: the model will faithfully maximize what you actually rewarded, which may not be what you meant — here, detail — but rather what merely correlated with it — length.
Optimize length’s proxy, get verbosity Raters prefer longer answers, so length correlates with reward, and preference optimization — DPO especially — learns to pad. Length normalization, penalties, or balanced data break the correlation. It is reward hacking in miniature.