AnyLearn
All lessons
AIadvanced

Direct Preference Optimization: DPO, IPO, KTO, and SimPO

A deep dive into DPO (Rafailov et al. 2023) and its successors — how they reformulate RLHF as a classification problem, the math behind the implicit reward, and where each variant wins or loses against PPO-based pipelines.

Not signed in — your progress and quiz score won't be saved.
Lesson progress1 / 12

The RLHF Tax

Reinforcement Learning from Human Feedback (RLHF) as practiced in InstructGPT has three moving parts: a supervised fine-tuned (SFT) base, a separate reward model trained on human preference pairs, and a policy updated by PPO while a KL penalty keeps it from drifting too far from the SFT base. That's three models in GPU memory simultaneously, a reward-model training loop, and PPO's notorious sensitivity to learning rate, batch size, and clipping threshold.

In practice, teams spend more time stabilizing PPO than doing actual alignment work. Reward hacking — where the policy finds high-scoring outputs the reward model didn't anticipate — is endemic. The KL coefficient has to be tuned per task. And the whole pipeline requires thousands of reward-model queries per gradient step.

DPO (Rafailov et al., 2023, Stanford / Berkeley) asks: given that PPO is just optimizing a reward signal derived from preferences, can we skip the reward model entirely and train the policy directly on preference pairs? The answer is yes — and the math is surprisingly clean.

Full lesson text

All 12 steps on one page — for reading, reference, and search.

Show

1. The RLHF Tax

Reinforcement Learning from Human Feedback (RLHF) as practiced in InstructGPT has three moving parts: a supervised fine-tuned (SFT) base, a separate reward model trained on human preference pairs, and a policy updated by PPO while a KL penalty keeps it from drifting too far from the SFT base. That's three models in GPU memory simultaneously, a reward-model training loop, and PPO's notorious sensitivity to learning rate, batch size, and clipping threshold.

In practice, teams spend more time stabilizing PPO than doing actual alignment work. Reward hacking — where the policy finds high-scoring outputs the reward model didn't anticipate — is endemic. The KL coefficient has to be tuned per task. And the whole pipeline requires thousands of reward-model queries per gradient step.

DPO (Rafailov et al., 2023, Stanford / Berkeley) asks: given that PPO is just optimizing a reward signal derived from preferences, can we skip the reward model entirely and train the policy directly on preference pairs? The answer is yes — and the math is surprisingly clean.

2. The Bradley-Terry Model and the Implicit Reward

Standard RLHF fits a reward model rϕr_\phi using the Bradley-Terry assumption: the probability that response ywy_w is preferred over yly_l given prompt xx is

p(ywylx)=σ(rϕ(x,yw)rϕ(x,yl))p(y_w \succ y_l \mid x) = \sigma(r_\phi(x, y_w) - r_\phi(x, y_l))

Then PPO maximizes E[rϕ(x,y)]βKL[πθπref]\mathbb{E}[r_\phi(x,y)] - \beta \cdot \text{KL}[\pi_\theta \| \pi_{\text{ref}}].

The DPO insight: the optimal policy under that KL-constrained objective has a closed form:

r(x,y)=βlogπ(yx)πref(yx)+βlogZ(x)r^*(x, y) = \beta \log \frac{\pi^*(y \mid x)}{\pi_{\text{ref}}(y \mid x)} + \beta \log Z(x)

where Z(x)Z(x) is a partition function that cancels in the preference ratio. Plug this back into the Bradley-Terry likelihood and Z(x)Z(x) drops out, leaving a loss that depends only on log-probability ratios between the current policy and the frozen reference:

LDPO=E(x,yw,yl)[logσ(βlogπθ(ywx)πref(ywx)βlogπθ(ylx)πref(ylx))]\mathcal{L}_{\text{DPO}} = -\mathbb{E}_{(x, y_w, y_l)} \left[ \log \sigma\left( \beta \log \frac{\pi_\theta(y_w \mid x)}{\pi_{\text{ref}}(y_w \mid x)} - \beta \log \frac{\pi_\theta(y_l \mid x)}{\pi_{\text{ref}}(y_l \mid x)} \right) \right]

No reward model. No PPO rollouts. Just a binary cross-entropy over log-ratio differences.

3. DPO vs. PPO-RLHF Pipeline

DPO collapses the three-model RLHF stack into a two-model setup (policy + frozen reference) with a single supervised-style training loop. The reward model and PPO optimizer are both eliminated.

flowchart TD
  A["SFT Base Model"] --> B["PPO-RLHF Path"]
  A --> C["DPO Path"]
  B --> D["Train Reward Model on (x, y_w, y_l) pairs"]
  D --> E["PPO loop: sample rollouts, score with RM, update policy"]
  E --> F["Aligned Policy (PPO)"]
  C --> G["Freeze reference copy of SFT"]
  G --> H["Binary cross-entropy on log-ratio differences"]
  H --> I["Aligned Policy (DPO)"]

4. Implementing DPO in Practice

The loss is straightforward to implement. Given a batch of (prompt, chosen, rejected) triples:

import torch
import torch.nn.functional as F

def dpo_loss(policy_logps_w, policy_logps_l,
             ref_logps_w, ref_logps_l, beta=0.1):
    """All logps are per-token-averaged log-probabilities."""
    log_ratio_w = policy_logps_w - ref_logps_w
    log_ratio_l = policy_logps_l - ref_logps_l
    logits = beta * (log_ratio_w - log_ratio_l)
    loss = -F.logsigmoid(logits).mean()
    return loss

policy_logps_w is sum(log p_theta(token | context)) over the chosen response tokens, divided by length (length-normalisation avoids penalising long preferred responses). The reference model is frozen and run in torch.no_grad().

Heads up: the single most common bug is computing log-probs over the full sequence (prompt + response) rather than masking the prompt tokens out. The loss should measure only the response portion.

5. IPO: Identity Preference Optimization

DPO's Bradley-Terry derivation assumes the preference data comes from a consistent reward function — if that assumption breaks (noisy labels, contradictory annotators), the policy can overfit to the noise and push the chosen/rejected log-ratio gap to infinity. Azar et al. (2023, Google DeepMind) call this the overfitting regime and propose IPO.

IPO replaces the log-sigmoid with a squared loss:

LIPO=E[(logπθ(ywx)πref(ywx)logπθ(ylx)πref(ylx)12τ)2]\mathcal{L}_{\text{IPO}} = \mathbb{E}\left[ \left( \log \frac{\pi_\theta(y_w \mid x)}{\pi_{\text{ref}}(y_w \mid x)} - \log \frac{\pi_\theta(y_l \mid x)}{\pi_{\text{ref}}(y_l \mid x)} - \frac{1}{2\tau} \right)^2 \right]

The 12τ\frac{1}{2\tau} target acts as a margin: it limits how far the log-ratio gap is pushed, preventing the probability of chosen responses from saturating to 1.0. IPO is less aggressive than DPO on clean data but degrades more gracefully on noisy preference datasets — empirically useful when your annotation pipeline has inter-annotator agreement below ~75%.

6. KTO: Kahneman-Tversky Optimization

DPO and IPO both require paired data: for every prompt you need one good and one bad completion. Ethayarajh et al. (2023, Stanford) observed that real-world feedback is often unpaired — thumbs up/down on individual responses, not comparison pairs. KTO works on single-label data.

Inspired by Kahneman & Tversky's prospect theory (losses feel roughly 2x larger than equivalent gains), KTO trains on:

LKTO=E[λwσ(βhθ(x,yw)zref)+λlσ(βhθ(x,yl)+zref)]\mathcal{L}_{\text{KTO}} = \mathbb{E}\left[ \lambda_w \cdot \sigma\left(\beta \cdot h_\theta(x, y_w) - z_{\text{ref}}\right) + \lambda_l \cdot \sigma\left(- \beta \cdot h_\theta(x, y_l) + z_{\text{ref}}\right) \right]

where hθ(x,y)=logπθ(yx)logπref(yx)h_\theta(x,y) = \log \pi_\theta(y|x) - \log \pi_{\text{ref}}(y|x) and zrefz_{\text{ref}} is a running estimate of the KL-penalised expected reward. λw\lambda_w and λl\lambda_l are hyperparameters (default: loss-averse ratio ~λl/λw=1.33\lambda_l / \lambda_w = 1.33).

Key advantage: you can mix independently collected "good" and "bad" completions without needing them paired per prompt. This unlocks large filtered SFT datasets as implicit preference signal.

7. SimPO: Simple Preference Optimization

All the variants above keep a reference model — the frozen SFT copy. SimPO (Meng et al., 2024, UIUC) eliminates it entirely. The reference log-prob terms drop out, and the margin is replaced by a fixed target γ\gamma:

LSimPO=E[logσ(βywlogπθ(ywx)βyllogπθ(ylx)γ)]\mathcal{L}_{\text{SimPO}} = -\mathbb{E}\left[ \log \sigma\left( \frac{\beta}{|y_w|} \log \pi_\theta(y_w \mid x) - \frac{\beta}{|y_l|} \log \pi_\theta(y_l \mid x) - \gamma \right) \right]

The 1/y1/|y| term is length normalisation applied directly to the raw log-probs rather than the log-ratio. Without a reference model you save ~50% GPU memory during training.

Catch: without the KL anchor to the SFT base, SimPO can drift toward degenerate outputs (very short or repetitive responses). The paper recommends γ[0.5,1.5]\gamma \in [0.5, 1.5] and starting from a well-tuned SFT checkpoint, not a raw base model. On AlpacaEval 2, SimPO matched or exceeded DPO with Llama-3-8B-Instruct while using one fewer GPU.

8. DPO Variant Comparison

The four methods split along two axes: whether they require paired preference data and whether they require a frozen reference model.

flowchart LR
  A["Preference Data"] --> B["Paired (w, l) per prompt"]
  A --> C["Unpaired single labels"]
  B --> D["DPO — Bradley-Terry, log-sigmoid"]
  B --> E["IPO — squared loss, explicit margin"]
  B --> F["SimPO — no reference model, length-normalised"]
  C --> G["KTO — prospect theory, single labels OK"]
  D --> H["Needs reference model"]
  E --> H
  F --> I["No reference model needed"]
  G --> H

9. Why DPO Beat PPO for Most Teams

The practical case for DPO over PPO:

  • Memory: PPO needs policy + ref + reward model + value head in memory simultaneously. DPO needs policy + ref (2 models, both the same size).
  • Stability: PPO's policy-gradient variance requires careful clipping, KL coefficients, advantage normalisation, and warm-up schedules. DPO is a cross-entropy loss — optimisers don't need tuning beyond learning rate.
  • Reproducibility: PPO results are notoriously sensitive to implementation details (Engstrom et al., ICLR 2020). DPO results are much more consistent across runs.
  • Data efficiency: DPO reuses collected preference pairs without online rollouts, so you don't need a live inference server during training.

That said, DPO trades away PPO's exploration: PPO continuously samples from the current policy and can discover high-reward completions not in the dataset. DPO is static — it can only improve over distributions present in the preference data.

10. Where DPO Still Loses to PPO

DPO has real failure modes:

Distribution mismatch: The preference pairs were collected from a (usually weaker) policy. If the current policy drifts far from that distribution, the implicit reward signal becomes unreliable. PPO's online rollouts keep the policy and reward model in sync.

Long-horizon tasks: Code generation, multi-step reasoning, and agentic tasks have sparse rewards (did the code compile? did the agent succeed?). PPO can assign credit across many steps via GAE. DPO cannot — it sees the full response as a unit.

Iterative refinement: Anthropic's Constitutional AI and DeepSeek-R1 both use iterative RL loops where the model's own outputs become training signal. DPO cannot close this loop without a new round of human preference collection.

Math and reasoning benchmarks: Multiple papers (including the DPO paper itself) show PPO outperforming DPO on GSM8K and MATH when the SFT base is strong. The on-policy exploration matters for search-like reasoning.

11. Choosing a Method: Decision Guide

A practical decision tree:

  1. Do you have paired (chosen, rejected) data?

    • No → use KTO (single-label thumbs up/down).
    • Yes → continue.
  2. Do you care about GPU memory?

    • Very constrained → SimPO (no reference model).
    • Fine with 2x model copies → continue.
  3. Is your preference data noisy or from multiple annotators?

    • Yes → IPO (squared loss prevents margin collapse).
    • Clean, high-agreement labels → DPO.
  4. Is your task long-horizon or reasoning-heavy?

    • Yes → consider PPO (or GRPO, a group-relative variant used by DeepSeek-R1).

For most chat/instruction-following fine-tunes on a good SFT base, DPO is the right starting point. Layer in iterative DPO (collect new preference data with the updated model, retrain) if quality plateaus.

12. Hyperparameters That Actually Matter

β\beta (KL coefficient): Controls how closely the policy stays to the reference. Too low → the policy barely moves. Too high → aggressive updates that destabilise generation. Start at 0.1 for chat models, 0.05 for creative tasks.

Length normalisation: Without it, DPO penalises long chosen responses because their aggregate log-prob is lower. The fix is to normalise by response token count before computing the loss.

Data ratio (chosen:rejected quality gap): DPO is most effective when the chosen response is clearly better — pairs where the margin is ambiguous add noise. Filter pairs by annotator agreement score if available.

Learning rate and epochs: DPO trains for far fewer steps than SFT. 1-3 epochs at 5×107\leq 5 \times 10^{-7} LR (on top of an SFT checkpoint) is typical. More epochs → reward hacking in the implicit reward space — the policy learns to boost log-ratio gaps without improving quality.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. In the DPO loss, why does the partition function Z(x) disappear?
    • It is assumed to be constant across all prompts
    • It cancels when taking the ratio of preferred to rejected probabilities in the Bradley-Terry model
    • It is absorbed into the beta hyperparameter during derivation
    • DPO does not use the Bradley-Terry model and therefore Z(x) never appears
  2. What specific failure mode does IPO address that vanilla DPO suffers from?
    • IPO removes the need for a reference model to save GPU memory
    • IPO handles unpaired preference data, whereas DPO requires pairs
    • IPO's squared loss prevents the log-ratio gap from saturating to infinity on noisy labels
    • IPO replaces the Bradley-Terry assumption with a prospect-theory utility function
  3. Which method requires neither paired data nor a frozen reference model?
    • DPO
    • IPO
    • KTO
    • SimPO
  4. A team is fine-tuning a model to solve multi-step math competition problems, using a verifier that gives a binary correct/incorrect signal after seeing the full solution. Which training method is MOST appropriate?
    • DPO, because preference pairs are easy to construct from correct vs. incorrect solutions
    • SimPO, because it needs no reference model and saves memory
    • PPO or GRPO, because sparse end-of-sequence rewards require credit assignment across steps
    • KTO, because single binary labels map naturally to its thumbs-up/down formulation
  5. When implementing DPO, what is the most common source of incorrect loss values?
    • Using a learning rate above 1e-5
    • Forgetting to length-normalise the log-probabilities
    • Including the prompt tokens when computing log-probabilities instead of masking them
    • Running the reference model with gradients enabled

Related lessons

AI
advanced

RLHF: From Christiano 2017 to InstructGPT to the Offline Era

Trace the full arc of Reinforcement Learning from Human Feedback — preference data, Bradley-Terry reward models, PPO with KL penalty, reward hacking, and why most labs have moved to offline alternatives like DPO and RAFT.

12 steps·~18 min·audio
AI
advanced

RL in Reasoning Models: How o1, DeepSeek-R1, and Friends Think

A deep look at how reinforcement learning on chains-of-thought powers o1, DeepSeek-R1, Claude reasoning, and Gemini Thinking — covering GRPO, MCTS-style search, test-time compute scaling, and distillation into smaller models.

13 steps·~20 min·audio
AI
advanced

Loop engineering: verification, orchestration, and anti-patterns

Make loops trustworthy. Adversarial verification panels, sub-agent orchestration, loop-until-dry for unbounded discovery, loop-until-budget for paid depth, multi-modal sweeps with diverse prompts, eval-driven cap selection, and the five anti-patterns — silent caps, infinite plans, drift, premature termination, thrashing — that ship to prod more than they should.

9 steps·~14 min
AI
intermediate

Loop engineering in production: state, errors, and budgets

Once an agent loop runs past a few iterations the failure surface shifts: state bloats, tool calls fail in three distinct ways, retries multiply if you stack them wrong, and unbounded budgets rack up four-figure bills overnight. The state, errors, and budgets you need to make the loop survive contact with reality.

8 steps·~12 min