AI ENGINEERING · FINE-TUNING AND ADAPTATION · ALIGNMENT · 29 OF 35

RLHF and DPO Explained: Preference Tuning

Why a model trained to predict text is not automatically helpful, and how preference tuning fixes it: preference pairs, the three steps of RLHF (supervised fine-tuning, a reward model, reinforcement learning with a KL penalty), reward hacking, DPO with a worked loss, reinforcement learning on checkable answers for reasoning models, rule-based AI feedback, and when an application team should do any of it.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
1 / 19

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Pairs
  • SFT, reward model, RL with a KL leash
  • beware reward hacking
  • DPO on pairs
  • checkable rewards

Notes

The idea

Start with why this is needed. Pretraining teaches one thing: predict the next token of internet text. Ask a raw pretrained model how to reset your password, and it may reply with another question, because on a real FAQ page, questions follow questions. It may also give a confident wrong answer, or repeat something rude it read. Likely text is not the same as helpful text. We need a training signal for helpful.

Pretraining objective
  • predict the next token of text from the internet
  • so a question may get: more questions (a FAQ page) a confident wrong answer something rude it once read
  • likely text is not the same
  • as a helpful answer

Why SFT is not enough

The first fix is supervised fine-tuning, from episode two. Show the model thousands of prompts with an ideal reply, and it learns to act like an assistant. But demonstrations have limits. Writing perfect answers is slow and costly. And the model only ever sees one good answer, never what a worse answer looks like. Here is the key insight. Judging is far easier than writing. Almost anyone can pick the better of two answers.

Limits of demonstrations
  • SFT: copy one ideal answer per prompt, token by token
  • writing ideal answers is slow and expensive
  • it never shows what a worse answer looks like
  • judging is easier than writing: most people can pick the better of two

Preference data

So we collect preference data. Take a prompt, let the model write two answers, and have a person, or a rule, pick the better one. Here answer A just says yes. Answer B explains what will be deleted and why that matters. B is chosen, A is rejected. Labs often rank four or more answers and turn the ranking into pairs. In a product, thumbs, user edits and A B choices are preference signals too.

One preference pair
prompt:   "Safe to run rm -rf /tmp/*?"
answer A: "Yes."
answer B: "Usually, but it deletes every
           file there, including ones
           running programs still use..."
chosen:   B      rejected: A

sources: paid labellers, thumbs up or
down, user edits, A/B picks, a judge
model following written rules

RLHF step 1: SFT

R L H F, reinforcement learning from human feedback, has three steps. Step one is plain supervised fine-tuning. Train the pretrained model on tens of thousands of demonstrations, so it already follows instructions and speaks in the assistant format. This gives a decent starting point. Then freeze a copy of it. That frozen copy is called the reference model, and it comes back in step three as a leash.

Step 1 of 3
  • supervised fine-tuning on ~10k to 100k demonstrations
  • result: the SFT model follows instructions, has the assistant format
  • keep a frozen copy: the reference model, used again in step 3

Step 2: reward model

Step two trains a reward model. It is usually the S F T model with a final layer that outputs one score. The loss only cares about the gap between the chosen and rejected scores. If chosen scores two and rejected zero point five, the gap is one point five, and the loss is a small zero point two. Rank them the wrong way round and the loss jumps to one point seven. Training pushes the gap positive.

Pairwise loss, worked
loss = -log sigmoid(r_chosen - r_rejected)

r_chosen 2.0, r_rejected 0.5
  gap 1.5  sigmoid 0.82  loss 0.20
r_chosen 0.5, r_rejected 2.0
  gap -1.5 sigmoid 0.18  loss 1.70

big loss when it ranks them wrong,
so training pushes the gap positive
usually the SFT model + a score head

Step 3: RL

Step three is the reinforcement learning. The model being tuned is now called the policy. Give it a fresh prompt, let it write an answer, and ask the reward model for a score. Then update the policy so high scorers become more likely and low scorers less likely. The classic algorithm is P P O. The reward model stands in for a person, so you can score millions of answers cheaply.

Step 3 of 3
  • loop: 1 take a fresh prompt 2 policy writes an answer 3 reward model scores it 4 update the policy so high scores get more likely
  • classic algorithm: PPO
  • the reward model stands in for a person, at scale

The KL penalty

Left alone, the policy will chase the score anywhere, including into gibberish the reward model happens to like. So the reward gets a penalty for drifting from the reference model, measured with K L divergence. With a penalty weight of zero point one, answer A scores three with a drift of four, total two point six. Answer B scores three point five but drifted twenty, total one point five. The safer answer wins.

Reward with a leash
total = score - beta x drift
drift: how far the policy's word
  choices moved from the reference

beta = 0.1
answer A: score 3.0, drift 4
  total 3.0 - 0.4 = 2.6   wins
answer B: score 3.5, drift 20
  total 3.5 - 2.0 = 1.5

the drift measure is a KL divergence

Reward hacking

Now the trap, called reward hacking. The reward model is only an imperfect copy of human taste. Suppose labellers often preferred longer answers, so it learned that long means good. The policy discovers this and pads everything. Answers get three times longer, the score climbs, and real people like them no more, or less. Other hacks: flattering the user, or sounding confident when wrong. Fixes: the K L leash, length checks, fresh labels and spot checks.

Reward hacking, in practice
  • reward model learned: longer answers usually won
  • policy learns: pad everything answers 3x longer, score up, real preference flat or down
  • others: flattering the user, confident tone, deleting the failing tests
  • fixes: KL leash, length checks, refresh RM, human spot checks

DPO: the idea

R L H F works, but it is heavy. P P O juggles about four models, generates answers during training, and has many touchy settings. D P O, direct preference optimisation, rewrites the same goal as one plain loss on the pairs you already have. No reward model, no sampling loop. In words: raise the probability of the chosen answer and lower the rejected one, both measured relative to the frozen reference.

Direct preference optimisation
  • RLHF with PPO juggles ~4
  • models, sampling and many
  • touchy settings
  • DPO: one supervised-style loss
  • on the pairs you already have
  • raise P(chosen) lower P(rejected) both relative to the reference

DPO, worked

Here is one pair with numbers. Compared with the reference, the policy has raised the log probability of the chosen answer by two, and lowered the rejected answer by one. The margin is two minus minus one, which is three. Multiply by beta, zero point one, and the loss is about zero point five five. At the start, policy equals reference, the margin is zero, and the loss is zero point six nine. Beta acts as the leash.

One pair, beta = 0.1
log-prob     policy   reference   gain
chosen        -40        -42       +2
rejected      -45        -44       -1

margin = 2 - (-1) = 3
loss = -log sigmoid(0.1 x 3)
     = -log 0.574 = 0.55

at the start policy = reference:
  margin 0, loss = log 2 = 0.69

RLHF vs DPO

So which is better? D P O is one stable loss, needs two models, or one if you cache the reference scores, and runs like normal fine-tuning. But it only learns from a fixed set of pairs, and can overfit them. R L H F scores fresh answers as the policy changes, so it keeps improving, at real cost. Variants exist, like K T O, which learns from single thumbs up or down labels.

Trade-offs
  • DPO + one loss, stable, cheap + 2 models, or 1 with cached reference log-probs
  • only learns from fixed pairs
  • can overfit, even lower both RLHF with a reward model + learns from fresh samples
  • costly, unstable, hackable
  • variants: KTO uses single thumbs up or down labels

Checkable rewards

A newer idea skips human taste entirely. For maths and code, you can check the answer. Take a maths problem whose answer is forty two, sample eight attempts, and reward each with one if correct, zero if not. Three are right, so the average is zero point three seven five. Attempts above average get pushed up, the rest down. For code, the reward is whether tests pass. This is how reasoning models learn long, careful chains of thought.

RL with verifiable rewards
prompt: a maths problem, answer 42
sample 8 attempts, 3 reach 42
reward: 1 if correct, else 0
group mean = 3 / 8 = 0.375

correct:   1 - 0.375 = +0.625  push up
incorrect: 0 - 0.375 = -0.375  push down

code: reward = unit tests pass
how reasoning models learn to think
long and check their own work

Rule-based feedback

One more source of labels. Instead of asking people to compare every pair, write down a short set of principles, like be honest, explain risks, refuse clear harm and do not lecture. A judge model reads two answers and picks the one that follows the rules better. This is called constitutional or A I feedback. It is cheap, consistent and auditable, because the rules are written down. People still review samples, since the judge has blind spots.

AI feedback from rules
  • write a short list of rules: be honest, explain risks, refuse clear harm, do not lecture
  • a judge model reads both answers and picks the one that follows them better
  • cheap, consistent, auditable
  • people still check samples

Should your team?

Should your team do this? Rarely. Frontier providers have already done the heavy R L H F. Try prompting first, then supervised fine-tuning. Reach for preference tuning when S F T got the format right but tone or judgement is off, and you have real signals like user edits. Then the usual move is D P O with a LoRA adapter on a small open model, using a few thousand pairs from your own traffic.

When an app team does this
  • try first: prompting, then SFT
  • consider DPO when:
  • SFT got the format right but tone or judgement is off
  • you have real preference signals: edits, thumbs, picks
  • you serve an open model
  • typical: 1k to 10k pairs, LoRA

Common mistakes

The usual mistakes. Skipping supervised fine-tuning, because D P O polishes behaviour, it does not teach the task. Noisy pairs, where labellers disagree, so the signal cancels out. Length bias, where chosen answers are nearly always longer, so the model learns to ramble. A learning rate that is too high, which makes output repetitive. And no held-out eval set, so you cannot tell polish from damage.

What goes wrong
  • skipping SFT: DPO polishes, it does not teach the task
  • noisy pairs: labellers who disagree teach nothing
  • length bias: chosen answers are always the longer ones
  • learning rate too high: output turns repetitive
  • no held-out eval: you cannot tell polish from damage

Numbers worth knowing

Some numbers to quote. An application team can get a real effect with one to ten thousand pairs. Frontier labs use hundreds of thousands to millions. People agree only about sixty five to eighty percent of the time on hard pairs, so expect noise. D P O beta is usually around zero point one, with a learning rate roughly ten times below supervised fine-tuning, for one to three epochs. Checkable-answer training often samples eight to sixty four attempts per prompt.

Ballpark numbers
pairs for an app-level DPO   ~1k - 10k
frontier preference data     ~100k - 1M+
labeller agreement           ~65 - 80%
DPO beta                     ~0.1
                             (0.01 - 0.5)
DPO learning rate            ~10x below SFT
epochs                       1 - 3
PPO models in memory         ~4
DPO models                   2 (or 1)
RL attempts per prompt       ~8 - 64

Say it like this

How to say it. Supervised fine-tuning taught the format. We then ran D P O with a LoRA adapter on five thousand pairs built from user edits, beta zero point one, one epoch. The frozen reference keeps it close to the S F T version. We balanced answer lengths so it would not ramble, and measured win rate against the S F T model on a held-out set, plus regressions. That names the data, the method and the leash.

In the interview
  • "SFT taught the format. We then ran DPO with LoRA on 5k pairs from user edits, beta 0.1, one epoch. The reference model keeps it close to SFT. We balanced lengths and checked win rate against SFT on a held-out set, plus regressions."

Interview questions

Q1Why is a pretrained language model not automatically a good assistant?

Pretraining only teaches it to predict likely internet text, which can be another question, a confident error or something harmful. Helpfulness, honesty and safety need an extra training signal: demonstrations (SFT) and preferences (RLHF or DPO).

Q2What are the three steps of RLHF?

First, supervised fine-tuning on demonstrations. Second, train a reward model on preference pairs so the chosen answer scores higher than the rejected one. Third, use reinforcement learning (classically PPO) to make high-scoring answers more likely, with a KL penalty that keeps the policy close to the frozen SFT reference.

Q3Why does RLHF include a KL penalty?

Without it the policy drifts wherever the reward model gives high scores, including odd text that exploits its flaws, and loses general ability. Penalising divergence from the reference model keeps outputs fluent and limits reward hacking.

Q4What is reward hacking? Give an example.

The policy optimises the reward model rather than the real goal. If the reward model learned that longer answers usually won, the policy pads every answer, so scores rise while real user preference stays flat. In RL on code, a model may special-case or skip the failing tests.

Q5How does DPO differ from RLHF?

DPO trains directly on preference pairs with one supervised-style loss, with no separate reward model and no sampling loop. It raises the log probability of the chosen answer relative to a frozen reference and lowers the rejected one, with beta controlling how far it may move.

Q6What is reinforcement learning with verifiable rewards?

For tasks with checkable answers, such as maths or code with unit tests, the reward is simply whether the answer is correct. Sample several attempts per prompt and push up the ones that beat the group average. It is a key way reasoning models are trained.

Q7What is constitutional or AI feedback?

Instead of humans labelling every pair, a judge model compares two answers against a written list of principles and picks the better one. It is cheap and consistent, and the rules are auditable, though people still spot-check the judge.

Q8Would an application team ever run preference tuning?

Rarely. After prompting and SFT, if tone or judgement is still off and there are real preference signals such as user edits, the common choice is DPO with a LoRA adapter on a small open model using a few thousand pairs, measured by win rate against the SFT model.