DPO & preference optimization
Tune a model directly on (prompt, chosen, rejected) pairs with a simple classification-style loss: the RLHF objective without a reward model or an RL loop, so it is cheaper and far more stable than PPO.
Analogy: Instead of training a critic to grade essays and then coaching the writer against that critic, you show the writer two drafts at a time and say: "more like this one, less like that one."
How it works
- The RLHF objective has a closed-form optimum, so the policy can act as its own reward model.
- The loss raises the log-probability of chosen over rejected, each measured against a frozen reference model.
- β (typically 0.1) limits drift from the reference; a lower β allows a more aggressive update.
- Start from an SFT model with thousands to tens of thousands of pairs, ideally sampled on-policy.
- Variants: KTO learns from unpaired thumbs-up/down; ORPO and SimPO drop the reference model.
Check yourself
Answer to mark it learned; your answers aren't scored.
To build DPO pairs fast, you take chosen answers from a frontier model and rejected ones from a small open model. Training loss falls quickly, yet held-out win rate against your SFT model barely moves. Most likely cause?
Go deeper
Full explanation
DPO (Direct Preference Optimization) fine-tunes a model on preference data, triples of (prompt, chosen, rejected), with a plain supervised loss. No reward model, no RL loop, no sampling during training.
Classic RLHF: reinforcement learning from human feedback first trains a reward model on those pairs, then runs PPO against it: four models in memory (policy, reference, reward, value) and a famously touchy loop. Rafailov et al. (2023) showed the RLHF objective has a closed-form optimum, so the policy can act as its own reward model.
The loss raises the log-probability of chosen relative to rejected, each measured against a frozen reference copy of the SFT model. β (typically 0.1) sets how far the policy may drift from it: a lower β allows a more aggressive update.
Variants to know:
- IPO: a bounded loss that overfits less when preferences are near-deterministic.
- KTO: learns from unpaired thumbs-up/down, the signal your product already logs.
- ORPO: merges SFT and preference into one stage, no reference model.
- SimPO: reference-free, length-normalized reward; less memory and less length bias.
Data: start from an Supervised fine-tuning (SFT) model and use a few thousand to tens of thousands of pairs, ideally sampled from that same model (on-policy).
Code DPO on preference pairs with TRL
from datasets import load_dataset
from transformers import AutoModelForCausalLM, AutoTokenizer
from trl import DPOConfig, DPOTrainer
MODEL = "Qwen/Qwen2.5-1.5B-Instruct" # use your own SFT checkpoint
model = AutoModelForCausalLM.from_pretrained(MODEL)
tokenizer = AutoTokenizer.from_pretrained(MODEL)
# Columns: "prompt", "chosen", "rejected" (strings or chat messages)
pairs = load_dataset("trl-lib/ultrafeedback_binarized", split="train")
args = DPOConfig(
output_dir="model-dpo",
beta=0.1, # pull toward the reference: higher = more conservative
learning_rate=5e-7, # far below SFT; DPO overfits fast
num_train_epochs=1,
per_device_train_batch_size=4,
gradient_accumulation_steps=8,
# loss_type="ipo", # same trainer covers several variants
)
trainer = DPOTrainer(
model=model, # ref_model=None -> TRL makes a frozen copy
args=args,
train_dataset=pairs,
processing_class=tokenizer,
)
trainer.train()
# Watch rewards/margins (should rise) and rewards/chosen (should not crash)Real example
An insurer's 8B claims assistant, already SFT'd, is accurate but hedges and writes 400-word answers. The team samples two answers from that model for each of 6,000 real prompts, an LLM-as-a-judge with a rubric picks the better one, and claims adjusters audit 300 pairs (88% agreement). They drop ties and low-confidence pairs, keep 4,800, and run one epoch of DPO with LoRA at β = 0.1. On 400 held-out prompts, human raters prefer the DPO model over the SFT model 66% of the time; median length falls from 410 to 230 words with no loss in factual accuracy.
Trade-offs +4 · −3
+ You gain
- Supervised-style training: one loss, no sampling, no reward model; runs on standard fine-tuning infra.
- Far more stable and cheaper than PPO: 2 models in memory instead of 4, and few hyperparameters.
- With LoRA the reference is just the base with adapters off, so 7–8B models fit on one GPU.
- KTO lets you use the thumbs-up/down you already collect, no pairs needed.
− You pay
- Offline: it only learns from the pairs it is given and cannot explore beyond them like online RL.
- Sensitive to data: off-policy or length-biased pairs teach the wrong lesson ("longer is better").
- Overfits fast and can lower the likelihood of chosen answers too; needs a low learning rate and monitoring.
Use it when
After SFT, to shape tone, verbosity, refusals or format preferences when you can collect pairwise judgments (humans or a calibrated judge) or thumbs up/down (KTO).
Avoid it when
When the model lacks knowledge or skill (fix with retrieval or SFT), when answers are programmatically checkable (prefer RL with verifiable rewards (GRPO)), or with fewer than a few hundred reliable pairs.
Numbers to know 5
- β ≈ 0.1 is the usual default (TRL's); sweeps commonly span ~0.01–0.5.
- Memory: PPO-based RLHF holds 4 models (policy, reference, reward, value); DPO holds 2; ORPO and SimPO hold 1.
- Zephyr-7B: SFT + DPO on ~60k GPT-4-scored UltraFeedback pairs beat Llama-2-70B-chat on MT-Bench.
- Llama 3 post-training chose DPO over PPO, citing less compute at scale and better instruction following.
- Rule of thumb: learning rate ~5e-7 to 1e-6 for full fine-tuning, far below SFT's ~1e-5.
Common pitfalls 4
- Off-policy pairs: chosen written by GPT-4, rejected by a weak model. The model learns to tell the two apart, not to improve its own outputs.
- Length bias: if chosen answers are usually longer, DPO learns verbosity. Compare length stats per side; consider SimPO or length-matched pairs.
- Over-training at SFT-like learning rates or for many epochs. If
rewards/chosendrops fast, the model is unlearning good answers too. - Keeping noisy pairs: ties and low-agreement labels are coin flips. Drop them instead of training on noise.
Interview questions 3
Answer out loud first, then reveal.
DPO or PPO-based RLHF: how do you choose?Show answer
DPO is my default for preference tuning. It's offline and supervised: two models in memory, one loss, few hyperparameters, and it runs on the same infra as SFT. Llama 3 made the same call. I reach for online RL when the model must explore beyond the dataset and I have a reward I can query during training: a verifier (then GRPO) or a strong reward model. The middle ground is iterative DPO: regenerate pairs from the current policy each round, which recovers much of the on-policy benefit.
Your product logs thumbs up/down but no pairwise comparisons. Can you still do preference tuning?Show answer
Yes, with KTO, which trains on unpaired desirable/undesirable labels. But I clean the signal first: thumbs come from a biased slice of users, a thumbs-down often means the product failed rather than the text, and the up/down ratio is rarely balanced, so I rebalance or set KTO's class weights. The alternative is to build pairs: sample two answers per logged prompt and let a calibrated judge pick, audited against humans. Either way I hold out real prompts and compare win rate against the SFT model before shipping.
What does the reference model do in DPO, and what is β?Show answer
DPO's implicit reward is how much more likely the policy makes an answer than the frozen SFT reference does, so the reference anchors the update: the loss rewards the change in preference, not raw likelihood. β scales that reward and plays the role of RLHF's KL penalty. Too high and the model barely moves; too low and it drifts, overfits the pairs and can lose fluency. I start at 0.1 and sweep, watching held-out win rate, not training loss. ORPO and SimPO drop the reference to save memory and give up that anchor.