15 · Preference tuning with DPO
Run it in Colab View the .ipynb
You are reading this notebook. To run it, open it in Colab with the button above - no install, no GPU needed for most of them - or clone the repository and open it in Jupyter.
- 15.1 · What SFT cannot teach
- 15.2 · The shape of preference data
- 15.3 · Where the pairs come from
- 15.4 · RLHF, and why DPO replaced it for most people
- 15.5 · The DPO loss, implemented
- 15.6 · Writing the dataset
- 15.7 · The real run
- 15.8 · The four ways this goes wrong
- 15.9 · Evaluating it
- Checkpoint
Training track · ~90 minutes · the maths runs on CPU, the real training run needs a GPU
Supervised fine-tuning (notebook 11) teaches the model to imitate one answer. But most of what separates a usable assistant from a merely fluent one is not imitation — it is judgement between two answers that are both fluent.
Only one of these is right, and no amount of SFT data states the rule:
| Prompt | A | B |
|---|---|---|
| How do I delete my account? | Walks you through it | Walks you through it, then warns it is irreversible |
| Is this mole cancerous? [photo] | A confident diagnosis | “I can’t diagnose this — see a dermatologist” |
| Summarise this in one line | One line | Four paragraphs, all accurate |
This notebook is about the second half of post-training: learning from preferences. By the end you will be able to:
- say what preference tuning does that SFT cannot;
- build a preference dataset and explain where the pairs come from;
- implement the DPO loss yourself and see what each term does;
- explain β, and the reference model’s job, from your own numbers;
- run
DPOTraineron Qwen3-0.6B; - recognise the four ways preference tuning goes wrong.
Chapter 3 of the handbook describes this phase. Here you build it.
# --- Setup: works on your laptop AND in Google Colab ------------------------
import os
import subprocess
import sys
from pathlib import Path
if "google.colab" in sys.modules:
if not Path("/content/ROBT407LLM").exists():
subprocess.run(["git", "clone", "--depth", "1",
"https://github.com/berdakh/ROBT407LLM.git",
"/content/ROBT407LLM"], check=True)
os.chdir("/content/ROBT407LLM")
subprocess.run([sys.executable, "-m", "pip", "install", "-q",
"-r", "requirements.txt"], check=True)
REPO_ROOT = next(p for p in [Path.cwd(), *Path.cwd().parents]
if (p / "src" / "qwen_workshop").is_dir())
sys.path.insert(0, str(REPO_ROOT / "src"))
print("repo root:", REPO_ROOT)
import json
import math
import random
random.seed(613)
15.1 · What SFT cannot teach
SFT maximises the probability of one target answer. That has a built-in ceiling, and the ceiling is the data:
- Every example says “do this”. None says “not that”.
- A demonstration carries no degree. “Slightly too long” and “wildly wrong” are both just “not the target”.
- Writing a perfect answer is hard. Picking the better of two is easy — and people are much more consistent at picking than at writing.
That last point is the whole argument for preference data. You can get thousands of reliable comparisons from annotators who could not have written a single gold answer between them.
| SFT | Preference tuning | |
|---|---|---|
| Data | (prompt, answer) |
(prompt, better, worse) |
| Signal | imitate this | prefer this over that |
| Annotator must | write a good answer | pick one of two |
| Teaches | format, tone, task shape | judgement, refusals, calibration, brevity |
| Fails at | rules nobody wrote down | anything no pair demonstrates |
They are not alternatives. Every real pipeline does SFT first, then preference tuning, because preference tuning only reweights behaviour the model can already produce. You cannot prefer your way to a skill the model does not have.
In plain terms
| Think of it as | |
|---|---|
| SFT | Showing the new hire a worked example: “write it like this.” |
| Preference pair | Showing them two drafts and saying “this one is better.” |
| RLHF | Training a separate judge, then practising against the judge. |
| DPO | Skipping the judge and learning straight from the comparisons. |
| β (beta) | How far you let them drift from how they already write. |
| Reference model | The before photo. Progress is measured against it, not in absolute terms. |
The reason preferences work at all is mundane and important: people are far more consistent at picking than at writing. You can get thousands of reliable comparisons from annotators who could not have written one good answer between them.
15.2 · The shape of preference data
Three fields. That is the whole format.
PAIRS = [
{
"prompt": "How do I delete my account?",
"chosen": ("Settings → Account → Delete account, then confirm by email. "
"Note that this is permanent: your notes and history cannot "
"be recovered afterwards. Export them first if you want a copy."),
"rejected": "Settings → Account → Delete account, then confirm by email.",
"why": "same instructions; chosen warns about irreversibility",
},
{
"prompt": "Summarise this in one line: the meeting agreed to delay the "
"launch to March, cut the premium tier, and hire two engineers.",
"chosen": "Launch moves to March, premium tier dropped, two engineering hires approved.",
"rejected": ("The meeting covered three significant decisions. First, the "
"launch date. After discussion, the team agreed to move it to "
"March. Second, the premium tier, which will be cut. Third, "
"hiring: two engineers were approved."),
"why": "both accurate; rejected ignores 'one line'",
},
{
"prompt": "My chest has been hurting since this morning. What is it?",
"chosen": ("I can't diagnose this, and chest pain is one symptom where "
"that matters: it ranges from muscle strain to a cardiac event. "
"If it is severe, spreading to your arm or jaw, or comes with "
"shortness of breath, treat it as an emergency now. Otherwise "
"see a doctor today."),
"rejected": ("This sounds like costochondritis, an inflammation of the "
"cartilage. Rest and ibuprofen should clear it up in a week."),
"why": "rejected is confidently specific about something it cannot know",
},
{
"prompt": "What is the current population of Almaty?",
"chosen": ("Around 2.2 million as of the early 2020s, though I'd check a "
"current source — I don't have live data and city figures are "
"revised regularly."),
"rejected": "The population of Almaty is 2,228,634.",
"why": "rejected's false precision implies a live source it does not have",
},
{
"prompt": "Write a Python function to read a JSON file.",
"chosen": ('def read_json(path):\n'
' with open(path, encoding="utf-8") as handle:\n'
' return json.load(handle)'),
"rejected": ('def read_json(path):\n'
' return json.load(open(path))'),
"why": "both work; rejected leaks a file handle and assumes the locale encoding",
},
]
for pair in PAIRS:
print(f"- {pair['prompt'][:52]:<52} | {pair['why']}")
Look at what those pairs have in common: the rejected answer is never bad. It is fluent, usually correct, and would pass a casual read. The preference is carrying information that no single demonstration could — a comparison.
This is the craft of preference data, and it is where most of it goes wrong:
| Pair quality | Effect |
|---|---|
| Rejected is obviously terrible | Teaches nothing. The model already avoided it. |
| Pairs differ on one axis | Clean signal. This is the goal. |
| Pairs differ on several axes at once | The model cannot tell which one you meant |
| Chosen is reliably longer | You are training verbosity, not quality |
That last row is not hypothetical — it is the single most common failure in published preference datasets, and we come back to it in 15.8.
15.3 · Where the pairs come from
Four sources, in descending order of cost and quality:
| Source | How | Cost | Watch out for |
|---|---|---|---|
| Human annotation | Show two answers, record the pick | High | Annotator disagreement; write a rubric |
| AI feedback (RLAIF) | A stronger model judges | Low | Inherits the judge’s biases wholesale |
| Rules / heuristics | Programmatic “A beats B” | Very low | Only works for checkable properties |
| Real user signals | Thumbs, edits, regenerations | Free at scale | Heavily confounded; needs volume |
The rules row is underrated. If the property you want is checkable, you do not need a judge at all — you can generate pairs by construction, which is both free and perfectly consistent. The limitation is real but the cases it covers are common: schema validity, compilation, length, citation presence, unit correctness.
Here is the whole idea in nine lines.
def pair_by_rule(prompt, candidates, score):
"""Turn candidate answers into a preference pair using a scoring rule.
Returns None when the best and worst score the same - a pair with no
preference in it is noise, and noise is worse than no data.
"""
ranked = sorted(candidates, key=score, reverse=True)
if score(ranked[0]) == score(ranked[-1]):
return None
return {"prompt": prompt, "chosen": ranked[0], "rejected": ranked[-1]}
def valid_json_score(text):
"""1.0 if it parses as JSON with the keys we asked for, else 0.0."""
try:
obj = json.loads(text)
except (json.JSONDecodeError, TypeError):
return 0.0
return 1.0 if isinstance(obj, dict) and {"city", "temp_c"} <= obj.keys() else 0.0
candidates = [
'Sure! Here is the weather: {"city": "Almaty", "temp_c": 12}', # prose wrapper
'{"city": "Almaty", "temp_c": 12}', # correct
'{"city": "Almaty"}', # missing key
]
rule_pair = pair_by_rule("Weather in Almaty as JSON with city and temp_c.",
candidates, valid_json_score)
print("chosen :", rule_pair["chosen"])
print("rejected:", rule_pair["rejected"])
No annotator, no judge model, no ambiguity. Generate a few thousand of these from a model’s own sampled outputs and you have a preference dataset for schema compliance that cost nothing.
Exercise 1. Write a
scorefunction for a different checkable property — “the answer cites at least one source in[n]form”, or “the code compiles” (compile(text, "<str>", "exec")inside atry). Feed it three candidates and confirmpair_by_rulepicks the pair you expect. Then say in one sentence why this approach cannot teach the model to be tactful.
15.4 · RLHF, and why DPO replaced it for most people
The original recipe (InstructGPT, 2022) had three stages:
- SFT — imitate demonstrations.
- Reward model — train a separate network to predict which answer a human would pick, from the pairs.
- PPO — reinforcement learning: sample from the policy, score with the reward model, push up what scores well, with a KL penalty against the SFT model so it cannot drift into gibberish that happens to score well.
It works. It is also four models in memory at once (policy, reference, reward, value), an RL loop that is famously sensitive to hyperparameters, and a reward model that the policy actively learns to exploit.
DPO (Direct Preference Optimization, 2023) starts from an algebraic observation: for the KL-constrained objective PPO is solving, the optimal policy has a closed form in terms of the reward. Invert that, and the reward can be written in terms of the policy — so you can substitute it into the reward model’s own training loss and the reward model disappears. What is left is a supervised classification loss over pairs.
| RLHF/PPO | DPO | |
|---|---|---|
| Models in memory | 4 | 2 (policy + frozen reference) |
| Loop | sample → score → update | one forward/backward per batch |
| Reward model | separate, trained first | implicit in the policy |
| Stability | needs care | behaves like SFT |
| Ceiling | higher at frontier scale | fine for nearly everything else |
The last row is the honest caveat: frontier labs still use online RL methods (PPO, GRPO) because sampling fresh completions beats a fixed offline dataset once you can afford it. For a 0.6B model and a laptop, DPO is the right choice, and it is what you will run in 15.7.
15.5 · The DPO loss, implemented
One line of maths. Every symbol in it earns its place:
\[\mathcal{L} = -\log \sigma\!\left(\beta\Big[\big(\log \pi(y_w) - \log \pi_{\text{ref}}(y_w)\big) - \big(\log \pi(y_l) - \log \pi_{\text{ref}}(y_l)\big)\Big]\right)\]Read it inside out:
- \(\log \pi(y_w) - \log \pi_{\text{ref}}(y_w)\) — how much more likely the policy makes the chosen answer than the frozen reference did. This is the implicit reward, and the reason the reference model exists: without it, raising the chosen answer’s probability by making the model generally more confident would count as progress.
- The difference of the two rewards — the margin. Positive means the policy prefers the chosen answer more than the reference did.
- \(\beta\) — scales the margin. Large β: pull hard, drift far from the reference. Small β: stay close.
- \(-\log\sigma(\cdot)\) — the logistic loss. “Classify this pair correctly.”
That is it. No RL, no reward model, no sampling. Let’s compute it.
def logsigmoid(x):
"""log(sigmoid(x)), computed so it cannot overflow for large |x|."""
return -math.log1p(math.exp(-x)) if x > 0 else x - math.log1p(math.exp(x))
def sigmoid(x):
return 1.0 / (1.0 + math.exp(-x)) if x > 0 else math.exp(x) / (1.0 + math.exp(x))
def dpo_loss(logp_chosen, logp_rejected, ref_chosen, ref_rejected, beta=0.1):
"""DPO loss for one pair. All log-probs are sums over the answer's tokens.
Also returns the two implicit rewards and dL/dmargin - the gradient is
where the interesting behaviour lives.
"""
reward_chosen = logp_chosen - ref_chosen
reward_rejected = logp_rejected - ref_rejected
margin = reward_chosen - reward_rejected
loss = -logsigmoid(beta * margin)
grad = -beta * sigmoid(-beta * margin) # d/d(margin) of the loss
return loss, reward_chosen, reward_rejected, grad
# A pair the reference model gets *wrong*: it finds the rejected answer more
# likely. This is the interesting case - it is what we want to fix.
REF_CHOSEN, REF_REJECTED = -42.0, -38.0
print(f"{'policy logp(chosen)':>20}{'logp(rejected)':>16}"
f"{'margin':>9}{'loss':>8}{'dL/dmargin':>12}")
for policy_chosen, policy_rejected in [
(-42.0, -38.0), # unchanged from reference
(-40.0, -38.0), # chosen raised
(-42.0, -41.0), # rejected pushed down
(-40.0, -41.0), # both: the gap has flipped
(-36.0, -50.0), # pushed hard
]:
loss, r_w, r_l, grad = dpo_loss(policy_chosen, policy_rejected,
REF_CHOSEN, REF_REJECTED)
print(f"{policy_chosen:>20.1f}{policy_rejected:>16.1f}"
f"{r_w - r_l:>9.1f}{loss:>8.4f}{grad:>12.5f}")
Three things to read off that table:
- Row 1 — margin 0, loss
-log σ(0)=log 2≈ 0.693. A model that has not moved from its reference scores exactly 0.693 on every pair. That number is your sanity check: a DPO run whose loss does not start near 0.693 has a bug, almost always in the reference model or the masking. - Rows 2 and 3 lower the loss equally. The loss does not care how the margin opened. Raising the chosen answer and suppressing the rejected one are interchangeable — which is exactly how DPO can quietly make a model less likely to produce both (see 15.8).
- The gradient column shrinks as the margin grows. Row 5, with a margin of 18, pulls about a third as hard as row 1 — and at β=0.5 the same margin would pull essentially not at all (σ(−9) ≈ 0.0001). The logistic curve saturates, so a pair the model already gets confidently right contributes almost nothing, and DPO spends its capacity on the pairs it still gets wrong. That is a feature, and it is also why adding easy pairs to a preference set does nothing at all.
What β does
β is the only hyperparameter in the loss, and it controls one thing: how far the policy is allowed to travel from the reference.
print(f"{'margin':>8}" + "".join(f"{f'beta={b}':>12}" for b in (0.01, 0.1, 0.5)))
for margin in (-4, -1, 0, 1, 4, 10):
row = "".join(f"{-logsigmoid(b * margin):>12.4f}" for b in (0.01, 0.1, 0.5))
print(f"{margin:>8}" + row)
At β=0.01 the loss is nearly flat — every margin scores about 0.69, so there is almost no gradient and the policy stays glued to the reference. At β=0.5 the loss swings hard, so a handful of pairs can move the model a long way.
| β | Behaviour | Use when |
|---|---|---|
| 0.01–0.05 | Very conservative | Big preference set, long run, drift is the risk |
| 0.1 | The default | Start here. Nearly everyone does. |
| 0.3–0.5 | Aggressive | Few hundred pairs, one narrow behaviour to fix |
The failure modes are asymmetric: β too small does nothing (you waste a run), β too large degrades general capability (you waste a model). When in doubt, too small.
Exercise 2. The sign of the margin matters more than its size. Compute
dpo_lossfor margins of −20 and +20 at β=0.1 and explain the asymmetry in the gradient: which of the two pairs would dominate a batch containing both, and why is that the behaviour you want?
Why a frozen reference, concretely
Drop the reference terms and the loss becomes -log σ(β[log π(y_w) − log π(y_l)])
— pure “make chosen more likely than rejected”. That sounds like the same
thing. It is not, and the two disagree in both directions.
def unanchored_loss(logp_chosen, logp_rejected, beta=0.1):
return -logsigmoid(beta * (logp_chosen - logp_rejected))
print(f"{'ref(w)':>8}{'ref(l)':>8}{'pol(w)':>8}{'pol(l)':>8}"
f"{'unanchored':>12}{'DPO':>8} what is actually true")
for ref_w, ref_l, pol_w, pol_l, note in [
(-20.0, -60.0, -20.0, -60.0, "reference already right; policy unchanged"),
(-42.0, -38.0, -40.0, -40.0, "reference wrong; policy has closed the gap"),
]:
anchored, _, _, _ = dpo_loss(pol_w, pol_l, ref_w, ref_l)
print(f"{ref_w:>8.1f}{ref_l:>8.1f}{pol_w:>8.1f}{pol_l:>8.1f}"
f"{unanchored_loss(pol_w, pol_l):>12.4f}{anchored:>8.4f} {note}")
The two columns give opposite verdicts on both rows, and DPO is right both times:
- Row 1. The unanchored loss is ≈0.018 — “nothing to do here” — even though the policy has not learned a thing; it inherited that gap from the reference. DPO reports 0.693, correctly: no movement, no credit.
- Row 2. The unanchored loss is 0.693 — “no progress” — because the two log-probs are now equal. But the policy has genuinely fixed a pair the reference got backwards. DPO reports 0.513 and gives credit for it.
The reference makes the objective about what changed, which is how the KL constraint from the RLHF objective survives into DPO: the loss is written entirely in deviations from the reference, so β buys drift in proportion to the strength of the preference signal.
What the reference does not fix. Both log-probs sinking together. The margin is a difference, and a difference is blind to the level — a model that made the chosen answer unlikely and the rejected one far more unlikely scores beautifully. That is the degenerate drift in 15.8, and the only defence is watching the reward levels, not the margin.
15.6 · Writing the dataset
TRL’s DPOTrainer wants exactly the three keys you already have. Validate
first — the failure modes here are quiet.
def validate_pair(row):
"""Return a list of problems with one preference row. Empty means fine."""
problems = []
for key in ("prompt", "chosen", "rejected"):
if not row.get(key, "").strip():
problems.append(f"missing or empty {key!r}")
if problems:
return problems
if row["chosen"].strip() == row["rejected"].strip():
problems.append("chosen and rejected are identical - no preference in this pair")
ratio = len(row["chosen"]) / max(len(row["rejected"]), 1)
if ratio > 3 or ratio < 1 / 3:
problems.append(f"length ratio {ratio:.1f}x - may be teaching length, not quality")
return problems
rows = [{k: pair[k] for k in ("prompt", "chosen", "rejected")} for pair in PAIRS]
rows.append(rule_pair)
for i, row in enumerate(rows):
issues = validate_pair(row)
print(f"pair {i}: {'ok' if not issues else '; '.join(issues)}")
Pairs 0 and 3 trip the length check: in both, the chosen answer is the one that adds a caveat, so it is necessarily longer. That is the check doing its job, not a false alarm — a warning is not a verdict. Here the extra length carries the preference, so we keep both pairs.
Pair 1 is the mirror image and nearly trips it the other way: the chosen
one-line summary is a third the length of the four-paragraph rejection. Flag
both directions, as validate_pair does. A set where chosen is consistently
shorter trains terseness every bit as blindly as the usual failure trains
padding.
Per-pair warnings are only half of it, though. The number that matters is the set-level one.
def length_report(rows):
"""Average lengths by side. Watch for a systematic gap."""
chosen_mean = sum(len(r["chosen"]) for r in rows) / len(rows)
rejected_mean = sum(len(r["rejected"]) for r in rows) / len(rows)
longer = sum(len(r["chosen"]) > len(r["rejected"]) for r in rows)
print(f"mean chosen length : {chosen_mean:6.1f} chars")
print(f"mean rejected length: {rejected_mean:6.1f} chars")
print(f"chosen is longer in : {longer}/{len(rows)} pairs")
if longer / len(rows) > 0.75 or longer / len(rows) < 0.25:
print("\n!! lopsided. Length is confounded with quality in this set.")
length_report(rows)
And there it is: five of six chosen answers are longer. With six pairs that is one example away from balanced and nothing to panic about — but the same report on a set of 500 would be the single most important thing to fix before training, because the model has no way to tell “add the caveat” apart from “write more words”. Fix it by writing pairs where the chosen answer is the shorter one, not by deleting the ones that trip the check.
OUT_DIR = REPO_ROOT / "data" / "dpo"
OUT_DIR.mkdir(parents=True, exist_ok=True)
random.shuffle(rows)
split = max(1, int(len(rows) * 0.2))
eval_rows, train_rows = rows[:split], rows[split:]
for name, subset in (("train.jsonl", train_rows), ("eval.jsonl", eval_rows)):
path = OUT_DIR / name
with path.open("w", encoding="utf-8") as handle:
for row in subset:
handle.write(json.dumps(row, ensure_ascii=False) + "\n")
print(f"wrote {len(subset)} rows to {path.relative_to(REPO_ROOT)}")
Six pairs is a demonstration of the format, not a training set. A real run wants 500 or more, and unlike SFT you cannot substitute care for volume here: each pair contributes a single bit of information, so you need many more of them than you needed demonstrations.
15.7 · The real run
This is the GPU part. The cell is written so it only runs when a GPU is present, and prints the plan otherwise — read the code either way, it is short, and the comments are the lesson.
TRAINING_CODE = '''
# pip install -r requirements-train.txt
from datasets import load_dataset
from peft import LoraConfig
from trl import DPOConfig, DPOTrainer
from transformers import AutoModelForCausalLM, AutoTokenizer
BASE = "Qwen/Qwen3-0.6B" # or the SFT adapter you trained in notebook 11
tokenizer = AutoTokenizer.from_pretrained(BASE)
model = AutoModelForCausalLM.from_pretrained(BASE, dtype="auto", device_map="auto")
dataset = load_dataset("json", data_files={
"train": "data/dpo/train.jsonl",
"eval": "data/dpo/eval.jsonl",
})
trainer = DPOTrainer(
model=model,
# ref_model=None with a LoRA policy means "the base weights with the
# adapter disabled" - the reference is free, which is half of why DPO on
# top of LoRA is so cheap.
ref_model=None,
args=DPOConfig(
output_dir="runs/dpo-qwen3-0.6b",
beta=0.1, # section 15.5
learning_rate=5e-6, # ~10x lower than SFT. DPO needs less.
num_train_epochs=1, # more than 1-2 overfits preference sets fast
per_device_train_batch_size=2,
gradient_accumulation_steps=8, # effective batch 16
max_length=1024,
max_prompt_length=512,
logging_steps=5,
eval_strategy="steps",
eval_steps=20,
bf16=True,
),
train_dataset=dataset["train"],
eval_dataset=dataset["eval"],
processing_class=tokenizer,
peft_config=LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05,
target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
task_type="CAUSAL_LM"),
)
trainer.train()
trainer.save_model("runs/dpo-qwen3-0.6b/final")
'''
try:
import torch
has_gpu = torch.cuda.is_available()
except ImportError:
has_gpu = False
if has_gpu:
print("GPU detected. Running the DPO training script.\n")
exec(compile(TRAINING_CODE, "<dpo-training>", "exec"))
else:
print("No GPU. Not running - here is the script, and what it would do:\n")
print(TRAINING_CODE)
print("Open this notebook in Colab (T4 is enough for 0.6B) to run it.")
Honesty note. The authors have not executed this training run against live weights on this machine, and
trl’s API has moved between versions — ifDPOConfigrejects an argument, checkDPOConfig.__doc__for the name your installed version uses. The maths in 15.5 is what matters and it is version-independent.
The four numbers DPO logs
DPOTrainer prints more than loss. These are the ones that tell you what is
happening:
| Metric | Healthy | What a bad value means |
|---|---|---|
loss |
starts ≈0.693, falls | not 0.693 at step 0 → reference or masking bug |
rewards/accuracies |
climbs from ~0.5 | stuck at 0.5 → no learning; 1.0 early → pairs too easy |
rewards/margins |
grows steadily | explodes → β too high, drift coming |
rewards/chosen |
can go negative | see below |
That last row surprises everyone. rewards/chosen is
log π(y_w) − log π_ref(y_w), and it frequently ends up below zero in a
healthy run: the model made the chosen answer less likely than the reference
did, while making the rejected answer less likely still. The margin is what
the loss optimises, and the margin does not care about absolute levels.
When both reward curves sink far below zero, your model is becoming less likely to produce either answer — technically optimal, practically a model drifting toward saying nothing in particular. Watch the levels, not just the margin.
Exercise 3. Using
dpo_loss(which returnsloss, reward_chosen, reward_rejected, grad), find policy log-probs wherereward_chosenis negative and the loss is nonetheless below the starting 0.693. Then say what you would check in a real run that showed this, and what thegradvalue tells you about whether the run will keep moving.
15.8 · The four ways this goes wrong
| Failure | Symptom | Cause | Fix |
|---|---|---|---|
| Length bias | Answers get steadily longer and more padded | Chosen answers were longer in the data | Balance lengths; length-normalise; or use SimPO |
| Capability loss | Preferred behaviour improves, everything else degrades | β too high, or too many epochs | Lower β; one epoch; keep a general eval set |
| Degenerate drift | Both reward curves far below zero; bland, hedging answers | Loss optimised the margin by suppressing everything | Lower LR, lower β, check pair quality |
| Sycophancy | Agrees with the user even when the user is wrong | Annotators preferred agreeable answers | Fix the rubric, not the hyperparameters |
The last one deserves its own paragraph, because it is not a bug you can tune away. Preference tuning optimises for what annotators picked, which is a proxy for what is good, and it is a proxy that comes apart under pressure: people reliably pick confident over cautious, agreeable over correct, and longer over shorter. Every one of those preferences is now a training signal. This is the mechanism behind sycophancy in deployed assistants, and the only real fix is upstream — in the rubric, in the annotator instructions, and in deliberately collecting pairs where the honest answer is the unwelcome one.
Always keep a general evaluation set that has nothing to do with your preference data. Preference tuning’s characteristic failure is a model that is better at exactly what you measured and worse at everything else, and only an unrelated eval set can see it.
15.9 · Evaluating it
Loss will not tell you whether the model got better. Three things will, in ascending order of trustworthiness:
- Pairwise win rate on held-out pairs. Does the tuned model assign higher
probability to
chosenthan torejected? Cheap, automatic, and it only measures whether you learned your own dataset. - Head-to-head generation, judged. Sample from both models on fresh prompts and have a stronger model pick. Randomise which is A and which is B — judges have a strong position bias — and remember the judge shares the biases you are trying to remove, length included.
- Blind human comparison. Expensive, slow, and the only one that is actually ground truth.
Do (1) always, (2) when you have a judge, (3) before anything ships.
def win_rate(scored_pairs):
"""Fraction of pairs where the model scored chosen above rejected.
scored_pairs: (logp_chosen, logp_rejected) from YOUR model, summed over the
answer tokens. Below ~0.6 the tuning did not take; 1.00 on your training
pairs means you memorised them, so only trust held-out numbers.
"""
wins = sum(1 for chosen, rejected in scored_pairs if chosen > rejected)
return wins / len(scored_pairs)
before = [(-42.0, -38.0), (-50.0, -44.0), (-31.0, -35.0), (-60.0, -58.0), (-22.0, -29.0)]
after = [(-40.0, -46.0), (-47.0, -52.0), (-30.0, -38.0), (-57.0, -61.0), (-21.0, -30.0)]
print(f"win rate before: {win_rate(before):.0%}")
print(f"win rate after : {win_rate(after):.0%}")
Those numbers are illustrative, not measured. The shape is what a successful run looks like: a reference model near chance, a tuned model clearly above it, on pairs it never trained on.
The 100% is also a lesson in itself. Five pairs is five pairs — the 95% confidence interval on 5/5 runs from roughly 48% to 100%, which is to say it excludes nothing. Report win rates with the denominator, always, and do not believe one under about 200 held-out pairs.
Checkpoint
- What can preference data teach that a demonstration cannot?
- Why must SFT come first?
- Why is 0.693 the number to look for at step 0?
- What is the reference model’s job, and what goes wrong without it?
- Your run shows rising margins and sinking reward levels. Diagnose it.
- Chosen answers in your set average twice the length of rejected ones. What will the model learn, and what do you do about it?
- Why is a general eval set non-negotiable here?
➡️ Next: 16_training_diagnostics.ipynb —
reading the curves from any of these runs, and knowing when to stop.