AI State of the Art
Fundamentals/LLM: Understanding Large Language Models/30 min
Section 54

DPO: Direct Preference Optimization

Listen as a podcast →

"What if we cut through all this complexity?"

RLHF works, but it is a Rube Goldberg machine. Let us recap the chain: you first need an SFT (Supervised Fine-Tuning) model, then you train a separate reward model on human preferences, then you run a reinforcement learning algorithm (PPO) that juggles four models in memory at once, the policy being trained, its frozen reference copy, the reward model, and the critic. Add a KL (Kullback-Leibler) penalty to stop the policy from drifting, plus the fact that you have to generate complete answers at every step to have them scored. And that is before the chronic stability problems, reward hacking (the model learns to fool the judge rather than improve), and the compute bill.

Three words to keep in mind

This page uses three terms borrowed from reinforcement learning, laid out in detail on the RLHF page. In brief:

  • policy: the model itself, seen as a rule that produces a token given the text written so far. Written π\pi, the Greek letter pi. When you read "the policy", read "the model".
  • reward model: a second network, trained separately, whose only job is to score an answer. Its score is called the reward, written rr.
  • reference model: a frozen copy of the starting model, used as a yardstick for how far the model has moved. Written πref\pi_{\text{ref}}.

The whole DPO argument consists in making the second of these disappear.

In May 2023, a team at Stanford published a paper that surprised the community. Its contribution: a mathematical proof that the reward model is superfluous. The technique is called DPO (Direct Preference Optimization).

Direct Preference Optimization: Your Language Model Is Secretly a Reward Model (Rafailov et al., 2023)
Two side-by-side panels. On the left, RLHF: preference data (a response y_w preferred over a response y_l) first trains a reward model by maximum likelihood, then the reward model and the LM policy run in a loop, the policy samples completions, the reward model labels rewards. On the right, DPO: the same preference data leads directly to the final LM by maximum likelihood, with no reward model and no reinforcement learning loop.
The opening figure of the DPO paper, which sums up the whole argument. Both pipelines start from the same preference data. The left one builds an intermediate reward model and then enters a reinforcement learning loop; the right one drops both and goes straight to the final model. Note that maximum likelihood appears on both sides: it is the same kind of optimization, except DPO applies it only once.Source : DPO paper (Rafailov et al., figure 1), via Dragonscale

The central idea: the model already is a reward model

Here is the idea behind DPO, one of those elegant observations that changes everything. Recall what RLHF is trying to do: adjust the model so that it earns the best possible rewards, without straying too far from what it was after SFT. Mathematically:

max⁡  E[r(x,y)]−β⋅DKL(π∥πref)\max \; \mathbb{E}[r(x, y)] - \beta \cdot D_{KL}(\pi \| \pi_{\text{ref}})

Term by term:

  • xx: the prompt, that is, the text handed to the model
  • yy: the answer produced
  • r(x,y)r(x, y): the reward, the score the reward model assigns to answer yy for prompt xx
  • E[…]\mathbb{E}[\ldots]: the expectation, that is, the average of that score over all possible prompts and answers
  • β\beta (beta): a hand-tuned coefficient that sets the strength of the constraint (the larger it is, the tighter the model is held)
  • DKL(π∥πref)D_{KL}(\pi \| \pi_{\text{ref}}): the Kullback-Leibler divergence, a measure of the gap between the current model's probabilities π\pi and the reference model's πref\pi_{\text{ref}}. It is 0 if the two coincide and grows with the gap. It is not quite a distance: it is not symmetric
  • max⁡\max: we are looking for the weights that make this quantity as large as possible

In one sentence: get the best scores you can, without moving away from your starting point. The β\beta arbitrates between the two demands.

Most researchers saw this problem as requiring iterative reinforcement learning: generate answers, score them, update the model, repeat. The DPO authors proved something remarkable: this optimization problem has an exact analytical solution. In other words, you can write down the formula for the optimal model directly, with no RL loop at all:

πopt(y∣x)∝πref(y∣x)⋅exp⁡(r(x,y)β)\pi_{\text{opt}}(y|x) \propto \pi_{\text{ref}}(y|x) \cdot \exp\left(\frac{r(x, y)}{\beta}\right)

Let us read that formula. πopt(y∣x)\pi_{\text{opt}}(y|x) is the probability the optimal model gives answer yy when handed xx; the symbol ∝\propto means "proportional to"; exp⁡\exp is the exponential function. Plainly: the optimal model's probability is the reference model's, multiplied by a factor that grows with the reward. A well-scored answer sees its probability shoot up; a badly scored one is crushed. And the β\beta in the denominator sets how brutal the operation is: a large β\beta flattens reward differences, a small β\beta exaggerates them.

The decisive trick: this equality can be inverted. So the reward can be expressed using nothing but the model's probabilities:

r(x,y)=β⋅log⁡π(y∣x)πref(y∣x)+βlog⁡Z(x)r(x, y) = \beta \cdot \log \frac{\pi(y|x)}{\pi_{\text{ref}}(y|x)} + \beta \log Z(x)

The ratio π(y∣x)πref(y∣x)\frac{\pi(y|x)}{\pi_{\text{ref}}(y|x)} compares the probability the current model assigns to answer yy with the probability the reference would assign it. If the current model gives a probability ten times higher than the reference, this ratio is 10 and the "implicit reward" is high.

That leaves the term βlog⁡Z(x)\beta \log Z(x), and it is worth pausing on it for a second, because it is what makes the trick work. Z(x)Z(x) is a normalizing factor: it depends only on the prompt xx, never on the answer yy. In practice it is uncomputable, you would have to sum over every conceivable answer. But as soon as you subtract two rewards for the same prompt, it appears twice with opposite signs and cancels out. That is exactly what the loss in the next section does, and it is why its being uncomputable does not matter at all.

What does all this say concretely? That every language model implicitly defines a reward model, through the ratio of its probabilities to a reference's. No need to train a second network: the model already encodes its preferences in the way it spreads its probabilities.

The implicit reward, the heart of DPO

This is not merely a computational trick. It says something strong: the way a model assigns its probabilities is its scoring scale. If the tuned model gives an answer a higher probability than the reference does, it prefers it, no need to ask an external judge. DPO exploits that structure directly.

The DPO loss: elegantly simple

Substituting the implicit reward into the Bradley-Terry model gives the DPO cost function (its loss) directly.

Bradley-Terry is a simple idea, the same one behind Elo ratings in chess: to predict who wins between A and B, you look only at the gap between their scores. Formally, the probability that A is preferred to B is σ(rA−rB)\sigma(r_A - r_B), where σ\sigma is the sigmoid. If A is worth 8 and B is worth 3, the gap is 5, and σ(5)=0.99\sigma(5) = 0.99: A wins almost every time. Note that only the gap matters, never the absolute values, which is precisely what lets the Z(x)Z(x) term from the previous section vanish.

The resulting loss:

LDPO=−E[log⁡σ(β(log⁡π(yw∣x)πref(yw∣x)−log⁡π(yl∣x)πref(yl∣x)))]\mathcal{L}_{\text{DPO}} = -\mathbb{E}\left[\log \sigma\left(\beta \left(\log \frac{\pi(y_w|x)}{\pi_{\text{ref}}(y_w|x)} - \log \frac{\pi(y_l|x)}{\pi_{\text{ref}}(y_l|x)}\right)\right)\right]

Let us decode this piece by piece:

  • xx: the prompt (the question put to the model)
  • ywy_w: the chosen answer (w for "win", the one humans prefer)
  • yly_l: the rejected answer (l for "lose", the one humans dislike)
  • log⁡π(yw∣x)πref(yw∣x)\log \frac{\pi(y_w|x)}{\pi_{\text{ref}}(y_w|x)}: how much the current model has raised the good answer relative to the reference
  • log⁡π(yl∣x)πref(yl∣x)\log \frac{\pi(y_l|x)}{\pi_{\text{ref}}(y_l|x)}: how much it has raised the bad answer relative to the reference
  • the subtraction between the two: the preference gap. We want the model to raise the good answer more than the bad one
  • σ\sigma: the sigmoid, which converts that gap into a value between 0 and 1, readable as a probability
  • β\beta: amplifies or dampens the gap, it is exactly the same β\beta as in the RLHF formula above, which is no coincidence: it still plays the part of the leash
  • E[…]\mathbb{E}[\ldots]: the average over the whole preference dataset

In one sentence: the loss is low when the model has separated the good answer from the bad one more than the reference did. It is high when it cannot tell them apart, and worse still when it prefers the bad one.

Notice what the formula does not contain: no rr, no reward model. It is gone, replaced by the model's own probabilities. That is the paper's entire argument in one line.

The practical consequence: this is ordinary supervised learning with an unusual cost function. No reinforcement learning, no generating answers mid-training, no critic. Just a forward pass (running the data through the network to compute the loss) and a backward pass (going back through the network to correct the weights), over pairs that are already written.

Annotated PyTorch code for the dpo_loss function. It takes the log-probabilities of the trained policy and of the reference model, picks out those of the chosen and rejected completions, computes two log-ratios (pi_logratios and ref_logratios), then returns the loss as minus the log-sigmoid of beta times the difference between those two log-ratios.
The entire DPO loss fits in these few lines of PyTorch, taken from the paper. You can spot the formula from the previous section: the two log-ratios (current model vs reference, on the good and then the bad response), their subtraction, and the log-sigmoid. It is a plain computation over log-probabilities you already have, no RL loop anywhere.Source : DPO paper (reference implementation), annotated by Cameron R. Wolfe

The DPO pipeline: before vs after

Before (RLHF with PPO):

StepConsumesProduces
1. SFTideal answers written by annotatorsa model that answers
2. Annotationanswers generated by that modela human ranking of those answers
3. Reward modelthose rankingsan automatic judge
4. PPOprompts alone + the judgethe final model
5. Monitoringweeks of engineer timecurves that do not collapse
Three-column diagram of the InstructGPT RLHF pipeline. Step 1: a prompt is sampled from the dataset, a labeler writes the desired output, and this data fine-tunes GPT-3 with supervised learning (SFT). Step 2: for a prompt, several model outputs are sampled, a labeler ranks them from best to worst, and this ranking trains the reward model. Step 3: a policy is optimized against the reward model using reinforcement learning.
This is what DPO replaces: the three-step InstructGPT RLHF pipeline, the one that produced ChatGPT. Each step has its own model, its own labelers, and its own training loop. DPO keeps step 1 (the SFT) and the preference data from step 2, but removes reward model training and the whole of step 3 outright.Source : InstructGPT paper (Ouyang et al., figure 2), via Secure Machinery

After (DPO):

StepConsumesProduces
1. SFTideal answers written by annotatorsa model that answers, which will also serve as the frozen reference
2. Annotationpairs of answersfor each prompt, which one is preferred
3. DPOthose pairs, directlythe final model

That is all. Steps 1 and 2 are identical to RLHF's: DPO does not reduce the annotators' workload by one gram. What it removes is the intermediate judge and the reinforcement loop, steps 3 and 4 of the previous chain, folded into a single supervised training run.

The DPO data format

Each training example is a triplet: (prompt, chosen answer, rejected answer). For instance: prompt = "Explain gravity to an 8-year-old", chosen = a clear explanation with analogies, rejected = an explanation full of physicist jargon.

Public datasets provide exactly this format: UltraFeedback, or Anthropic's HH-RLHF (the two Hs stand for helpful and harmless, the two axes along which annotators compared the answers).

The hyperparameters that matter

The values given here are common practice in training libraries, not results from a paper, treat them as a starting point to adjust, not as constants.

  • beta (β\beta): the strength of the KL constraint, hence how free the model is to move away from the reference. Often around 0.1. Too low: the model strays too far and can lose its base capabilities. Too high: it stays glued to the reference and learns nothing from the preferences.
  • Learning rate: the size of each weight correction. Much lower than for SFT, on the order of 5×10−75 \times 10^{-7} to 10−610^{-6}. Alignment is a delicate adjustment; going too fast damages what SFT built.
  • Number of epochs, an epoch being one complete pass over the dataset: 1 to 3 at most. Overfitting in DPO is fast and brutal; the model memorizes the pairs and loses diversity. Watch the validation loss closely.

Concrete advantages: what DPO really changes

Simplicity: DPO fits in a few dozen lines. No critic (PPO's fourth model, the one that predicts the expected score), no generating answers at each step, no clipping coefficient to calibrate.

Stability: DPO loss curves are smooth and regular. No sudden collapse, and no reward hacking, for the simplest reason in the world: there is no judge left to fool. The only yardstick is the frozen reference, and it does not move.

Memory: two models to keep loaded (the one being trained and its frozen copy) instead of four with PPO.

QLoRA compatibility: DPO combines naturally with quantization (storing each weight on fewer bits to save memory) and LoRA adapters (Low-Rank Adaptation, you train only a small matrix added alongside the original weights, described on the page about fine-tuning).

DPO + QLoRA: alignment within reach of one graphics card

QLoRA is LoRA applied on top of a quantized model (Quantized LoRA). The order of magnitude can be worked out by hand: a 7-billion-parameter model stored on 4 bits, that is half a byte per parameter, occupies 0.5×7×109≈3.50.5 \times 7 \times 10^9 \approx 3.5 GB. The adapters and optimizer states concern only a fraction of a percent of the weights. So this fits comfortably on a 24 GB consumer card, all the more so since with LoRA you get the reference model for free, simply by switching the adapter off.

What took a laboratory a few years ago now fits on a desktop machine.

The honest limitations of DPO

Data sensitivity: if the chosen answer and the rejected answer are nearly equivalent, the gap to be maximized is tiny and the signal near zero. It is the contrast between the two answers, more than their absolute quality, that drives learning.

Distribution shift: DPO trains on pairs produced by the SFT model. But as the model changes, it no longer produces the same answers, so the pairs describe a model that no longer exists. RLHF with PPO does not have this problem, since it regenerates answers at every step with the current model. That is exactly the trade DPO accepts by removing the loop.

No reusable judge: RLHF's reward model has a life after alignment, filtering data, ranking answers, evaluating other models. With DPO you never build it, so you do not have it.

Possible collapse: with beta too low or too many epochs, the model finds it cheaper to crush the probability of the bad answers than to raise that of the good ones. The loss falls, the gap grows, and answer diversity collapses. This is precisely the flaw the DPOP variant, below, is meant to fix.

The variants born after DPO

DPO inspired a series of improvements:

  • IPO (Identity Preference Optimisation, Azar et al. 2023): replaces the step through Bradley-Terry, which reduces overfitting on the pairs
  • cDPO (conservative DPO): softens the labels to allow for the fact that an annotator may have got it wrong
  • Online / iterative DPO: regenerates fresh pairs at each round, which catches up the distribution shift described above, at the cost, obviously, of the simplicity just gained
  • DPOP (DPO-Positive): adds a term forbidding the model to lower the probability of the good answer, the collapse mode described above
DPO in open models

DPO is used extensively in the open-model community: Zephyr-7B is the best-documented example, its technical report explicitly describing alignment by distilled DPO. Many other models published on Hugging Face follow the same recipe.

Some labs combine both families of methods, DPO for the bulk of the alignment, then online reinforcement for the final stretch. The exact division of labour is generally not published, so read this claim as a reported tendency rather than a verified fact.

DPO or RLHF: the verdict

CriterionRLHF (PPO)DPO
Complexityvery highlow
Training stabilitydifficultstable
Models held in memory42
Online learning (fresh answers along the way)yesnot by default
Reusable judge afterwardsyesno
Maximum performance-- see below --

The last row deserves an explicit caveat. The DPO paper reports results equal to or better than PPO on the tasks it tests; later work argues the opposite, holding that a well-tuned PPO retains an edge. The question is not settled, and any page that declares a winner goes beyond what the literature establishes.

For a modestly sized team, however, the choice is clear: DPO is the better starting point. It gives competitive results with a fraction of the resources and without RLHF's debugging burden. PPO remains relevant for labs that have the teams and infrastructure to exploit it, and that need an online loop.

Check your understanding0 / 4

1. What is the central discovery of the DPO paper?

2. What does DPO not remove from the RLHF pipeline?

3. Why does reward hacking disappear with DPO?

4. What trade-off does DPO accept by removing the reinforcement loop?