Tuning with preferences: RLHF and DPO
9 min read
From examples to preferences
Supervised fine-tuning shows the model one good answer. Fine-tune a model to follow instructions covered it. A preference example shows two answers to the same prompt and says which is better. This helps when "better" is easier to judge than to write: a clearer reply, a safer refusal, a more faithful summary.
Each pair needs a written criterion, such as "uses only the supplied source" or "declines requests outside the policy". Reviewers will disagree on some pairs, so measure agreement as Human review and model judges showed, and drop or re-review pairs the raters split on.
RLHF in outline
Reinforcement learning from human feedback has three stages:
- Supervised fine-tuning to get a model that follows instructions.
- A reward model. Train a model to give a higher score to the chosen answer than to the rejected one.
- Optimisation. Adjust the language model to produce answers the reward model scores highly, with a penalty for drifting too far from the starting model.
The program below shows stage 2 in miniature. Four answers, A to D, were compared 10 times per pair. The Bradley–Terry model gives each answer a strength so that the chance that one beats another is its strength divided by the sum of both. The loop finds strengths that best match the counts.
a_beats = {("A", "B"): 8, ("A", "C"): 9, ("A", "D"): 10,
("B", "C"): 7, ("B", "D"): 8, ("C", "D"): 6}
wins = {}
for (x, y), k in a_beats.items():
wins[(x, y)] = k
wins[(y, x)] = 10 - k
names = ["A", "B", "C", "D"]
def beaten(x, y):
return wins.get((x, y), 0), wins.get((y, x), 0)
strength = {n: 1.0 for n in names}
for _ in range(200):
updated = {}
for i in names:
total_wins = sum(beaten(i, j)[0] for j in names if j != i)
denominator = sum(sum(beaten(i, j)) / (strength[i] + strength[j]) for j in names if j != i)
updated[i] = total_wins / denominator
scale = sum(updated.values())
strength = {n: v / scale for n, v in updated.items()}
for n in names:
print(f"answer {n}: strength {strength[n]:.3f}")
print(f"P(A beats B) = {strength['A'] / (strength['A'] + strength['B']):.2f}")
print(f"P(C beats D) = {strength['C'] / (strength['C'] + strength['D']):.2f}")It prints:
answer A: strength 0.743
answer B: strength 0.157
answer C: strength 0.063
answer D: strength 0.036
P(A beats B) = 0.83
P(C beats D) = 0.63The ranking matches the votes, and the gaps show how sure the data is. The fitted chance that A beats B is 0.83, close to the 8 of 10 observed, and for C against D it is 0.63 against 6 of 10. The fit pools every comparison, so each pair is nudged towards what the rest of the data implies. A real reward model does the same job with a neural network, so it can score answers it has never seen. That is also its weakness. If it learned to like length or confident tone, the language model will be pushed towards length and confident tone, whether or not the answer is right.
DPO: skip the reward model
Direct preference optimisation trains the language model directly on chosen and rejected pairs. It compares the model being trained with a frozen reference copy, usually the model you started from. For each pair, it asks how much more likely the chosen answer became, relative to the reference, than the rejected one did. The loss is the negative log of a sigmoid of that gap, scaled by a number called beta.
import math
beta = 0.1
reference = {"chosen": -42.0, "rejected": -40.0}
def dpo_loss(chosen, rejected):
gain = beta * ((chosen - reference["chosen"]) - (rejected - reference["rejected"]))
return gain, -math.log(1 / (1 + math.exp(-gain)))
for label, chosen, rejected in [
("start", -42.0, -40.0),
("early", -40.5, -41.0),
("later", -38.0, -45.0),
("extreme", -30.0, -70.0),
]:
gain, loss = dpo_loss(chosen, rejected)
print(f"{label:8} chosen {chosen:6.1f} rejected {rejected:6.1f} gain {gain:5.2f} loss {loss:.4f}")It prints:
start chosen -42.0 rejected -40.0 gain 0.00 loss 0.6931
early chosen -40.5 rejected -41.0 gain 0.25 loss 0.5759
later chosen -38.0 rejected -45.0 gain 0.90 loss 0.3412
extreme chosen -30.0 rejected -70.0 gain 4.20 loss 0.0149The numbers are log-probabilities of whole answers under the model, so less negative means more likely. At the start the model equals the reference, the gain is zero and the loss is log 2, about 0.693. As training raises the chosen answer and lowers the rejected one, the gain grows and the loss falls. The last row shows the risk. A model can push the loss close to zero by moving far from the reference, and far from the reference is where odd behaviour appears. Beta controls how strongly the loss pays for that movement, and a held-out check catches it.
When to use it
Start with a supervised baseline and a solid evaluation, as Evaluating a fine-tuned model describes. Add preference tuning when you have reliable pairs and a behaviour that examples alone do not fix, such as tone, refusals or ranking between acceptable answers. Check held-out prompts for regressions, especially answers that read well and are wrong. For methods and results, see the DPO paper and the InstructGPT paper, and for ready-made trainers the TRL library.
| Needs a reward model | Needs a reference model | Main risk | |
|---|---|---|---|
| RLHF | Yes | Yes, as a drift penalty | A reward model that rewards the wrong things |
| DPO | No | Yes | Moving too far from the reference |
What does a preference example contain?
You build a dataset for preference tuning.
The model learns from which answer is better.
What is an advantage of DPO over RLHF?
You want a simpler pipeline.
DPO optimises directly on chosen and rejected pairs.
What is a risk of a reward model?
It prefers long, confident answers.
A reward model is an imperfect judge, and the model learns whatever it likes.
Your reading position is saved
0 of 36 complete
Lesson complete
Tuning with preferences: RLHF and DPO
Up next