How does DPO differ from RLHF?

Learning path, stage 3 of 5: RAG and fine-tuning · question 10 of 10

Both train a model on human preference pairs (a chosen response and a rejected one). RLHF first trains a separate reward model, then optimises the LLM against it with reinforcement learning (PPO), with a KL penalty to stay close to the original. DPO (Direct Preference Optimization) shows the same objective can be optimised directly with a simple classification-style loss on the pairs: no reward model, no RL loop.

RLHF pipeline

  1. Collect comparisons → train a reward model to score responses.
  2. Generate samples from the policy → score them → PPO update, with a KL penalty against the reference model.
  3. Powerful but complex and unstable: several models in memory, sensitive hyperparameters, reward hacking.

DPO

  • Loss: increase the policy's log-probability ratio (against the reference model) for chosen over rejected, scaled by β.
  • Simpler, cheaper and more stable. Common in open-model fine-tuning.
  • Offline: it learns from a fixed preference dataset, which can limit exploration compared with online RL.

Related terms

  • RLAIF / Constitutional AI: preferences come from an AI judge following principles.
  • Online and iterative DPO: regenerate the pairs from the current policy.
  • RL with verifiable rewards: used for reasoning models, where correctness can be checked automatically.

Sources

Code example

tsx
1// DPO loss over a batch, given summed log-probs of each response.
2interface PairLogps {
3 policyChosen: number; policyRejected: number; // from the model being trained
4 refChosen: number; refRejected: number; // from the frozen reference model
5}
6
7const logSigmoid = (x: number) => -Math.log1p(Math.exp(-x));
8
9export function dpoBatchLoss(batch: PairLogps[], beta = 0.1) {
10 let loss = 0, accuracy = 0;
11 for (const p of batch) {
12 const chosenReward = beta * (p.policyChosen - p.refChosen);
13 const rejectedReward = beta * (p.policyRejected - p.refRejected);
14 const margin = chosenReward - rejectedReward;
15 loss += -logSigmoid(margin);
16 if (margin > 0) accuracy++;
17 }
18 return { loss: loss / batch.length, accuracy: accuracy / batch.length };
19}
20
21// No reward model, no sampling loop: just a supervised-style loss on preference pairs.

To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk zod pg, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.

Open in study app