AS·164
Preference Optimisation and Alignment
Teaching models what "better" means when good behaviour is easier to judge than to write: what alignment aims for (helpful, honest, harmless) and why supervised fine-tuning alone isn't enough, preference datasets (pairwise comparisons, rankings, ratings, AI feedback, annotation guidelines and agreement), the Bradley–Terry model and reward-model training implemented in PyTorch, RLHF with PPO, advantages and the KL penalty, reward hacking and over-optimisation, DPO derived from the RLHF objective and implemented and checked on a toy problem, IPO, KTO, ORPO and SimPO, rejection sampling and best-of-n fine-tuning, GRPO and reinforcement learning from verifiable rewards for reasoning, Constitutional AI and RLAIF, process vs outcome rewards, evaluating aligned models, and practical recipes with TRL.
Start here: teaching a model which answer is better
Supervised fine-tuning (chapter 163) shows a model one good answer. Often it's easier to say which of two answers is better than to write the perfect one: more helpful, more honest, safer, better formatted. Preference optimisation trains on such comparisons:
Question: What is a connection pool?
Chosen: A set of open database connections reused across requests.
Rejected: A set of of open open database connections connections reused.
Two families of methods
- RLHF (reinforcement learning from human feedback): train a reward model to score answers the way people's preferences do, then use reinforcement learning (PPO) to make the model produce high-scoring answers, with a penalty for drifting too far from where it started.
- DPO (direct preference optimisation): skip the reward model and adjust the model directly so the chosen answer becomes more likely relative to the rejected one, compared with a frozen copy of the starting model. A setting called β controls how far it may drift.
What the lab saw
The fine-tuned small GPT from chapter 163 sometimes repeated words ("be be be"). It was trained with DPO on pairs like the ones above:
| Before DPO | DPO, gentle | DPO, aggressive | |
|---|---|---|---|
| prefers the chosen answer (held-out pairs) | 63% | 84% | 85% |
| answers containing a doubled word | 9% | 1–3% | 9% |
| average answer length | 9.6 words | 4–6 words | 1.8 words |
The preference was learned, and repetition fell, but the model also discovered a shortcut: shorter answers have fewer chances to repeat, so it shrank them. Pushed harder, it collapsed into one-word fragments. That is reward hacking in miniature: the model optimises what the data rewards, not what you meant. Real alignment work spends much of its effort on exactly this: varied preference data, length controls, a strong pull back to the starting model, and evaluation of everything the preferences didn't mention.
How deep to go in preference optimisation
Volume 17 defines six mastery levels; for preference optimisation they look like this:
| Level | You can… |
|---|---|
| L1 | explain preference data, reward models, RLHF and DPO |
| L2 | run DPO on a preference dataset with a library |
| L3 | explain the DPO objective, β, the reference model, KL penalties and PPO's moving parts |
| L4 | diagnose reward hacking, length bias, collapse and over-refusal from evals |
| L5 | design a preference-data and evaluation programme for a product's behaviours |
| L6 | run alignment pipelines with human and AI feedback, red-teaming and release gates |
What alignment is for
A pre-trained model imitates its training data, which includes text that is wrong, toxic, manipulative or simply unhelpful. SFT (chapter 163) teaches the assistant format from demonstrations, but:
- Demonstrations are expensive, and annotators can't always write the ideal response, though they can usually tell which of two responses is better.
- SFT teaches the model to imitate, including its demonstrators' mistakes; it doesn't directly teach the model to prefer better outputs over plausible worse ones.
- Many properties are about trade-offs (be concise but complete; refuse harmful requests but don't over-refuse; express uncertainty honestly), which comparisons capture well.
Alignment in the practical sense means shaping model behaviour to match intended goals and values: commonly summarised as helpful, honest and harmless, plus following the operator's and user's legitimate instructions. Preference optimisation is the main post-training tool for it; it is one part of a broader safety effort (evaluations, red-teaming, monitoring, policies; chapter 176).
Preference data
| Format | Example | Used by |
|---|---|---|
| Pairwise | prompt, response A, response B, A ≻ B | Reward models, DPO family |
| Ranking | prompt, responses ranked 1..k | Expanded into pairs |
| Ratings / binary | prompt, response, 👍 or 1–7 score | KTO (binary desirable/undesirable), reward regression |
| AI feedback | A model judges pairs using written principles | RLAIF, Constitutional AI |
| Verifiable outcome | Answer correct? Tests pass? | RL with verifiable rewards |
Collecting good comparisons:
- Generate candidates from the current model(s) at varied temperatures, from different checkpoints, or with deliberate variations (so pairs are informative, not trivially different).
- Annotation guidelines define what "better" means: correctness first, then helpfulness, honesty, harmlessness, style; with worked examples and tie rules.
- Measure agreement between annotators (chapter 150's kappa); human preference data is noisy (agreement often only 60–75% on subtle pairs).
- Watch for biases: annotators (and AI judges) favour longer, more confident, more formatted answers; models then learn verbosity and over-confidence unless controlled.
- Cover safety cases: harmful requests (prefer helpful refusals or safe completions), borderline requests (penalise over-refusal), and honesty (prefer acknowledging uncertainty over confident errors).
{"prompt": "My code throws KeyError: 'user'. What should I check?",
"chosen": "A KeyError means the dict has no 'user' key. Print the keys you actually received (print(data.keys())), check the spelling and case, and use data.get('user') if the key is optional...",
"rejected": "KeyErrors happen in Python. You should debug your code carefully and check for errors."}
Reward models
Bradley–Terry
Model the probability that response y_w ("winner") is preferred to y_l ("loser") for prompt x with a scalar reward r(x, y):
P(y_w ≻ y_l | x) = σ(r(x, y_w) − r(x, y_l))
Only differences of rewards matter. Training maximises the log-likelihood of observed preferences:
L_RM = −E[log σ(r(x, y_w) − r(x, y_l))]
A reward model is usually the SFT model (or a smaller LLM) with its language-model head replaced by a scalar head reading the final token's hidden state.
import torch, torch.nn as nn, torch.nn.functional as F
torch.manual_seed(0)
# Toy setting: responses are feature vectors; hidden "true quality" = w_true · features
d = 16
w_true = torch.randn(d)
def make_pairs(n):
a, b = torch.randn(n, d), torch.randn(n, d)
p_a_better = torch.sigmoid((a - b) @ w_true) # noisy human preferences (Bradley–Terry)
a_wins = torch.rand(n) < p_a_better
chosen = torch.where(a_wins[:, None], a, b); rejected = torch.where(a_wins[:, None], b, a)
return chosen, rejected
chosen, rejected = make_pairs(4000)
reward_model = nn.Sequential(nn.Linear(d, 64), nn.ReLU(), nn.Linear(64, 1))
opt = torch.optim.AdamW(reward_model.parameters(), lr=1e-2)
for step in range(300):
margin = reward_model(chosen).squeeze(-1) - reward_model(rejected).squeeze(-1)
loss = -F.logsigmoid(margin).mean() # Bradley–Terry negative log-likelihood
opt.zero_grad(); loss.backward(); opt.step()
test_c, test_r = make_pairs(2000)
with torch.no_grad():
acc = (reward_model(test_c) > reward_model(test_r)).float().mean().item()
oracle = ((test_c - test_r) @ w_true > 0).float().mean().item()
round(acc, 3), round(oracle, 3) # ≈ 0.87 vs 0.90: close to the ceiling set by label noise
Reward-model accuracy on held-out human preferences is typically 65–80%: the labels themselves are noisy. Reward models are also used for evaluation, best-of-n selection, and data filtering.
RLHF with PPO
The classic recipe (InstructGPT, 2022): SFT → reward model → reinforcement learning to maximise reward while staying close to the SFT model:
maximise E_{x, y ~ π_θ}[ r(x, y) ] − β · KL(π_θ(·|x) ‖ π_ref(·|x))
- π_θ is the policy (the model being trained), π_ref the frozen SFT reference.
- The KL penalty (chapter 147) keeps outputs fluent and close to known-good behaviour and limits reward hacking: exploiting the reward model's blind spots (verbosity, flattery, repetitive phrases that the RM happens to like).
- PPO (Proximal Policy Optimization) estimates advantages (how much better a sampled response did than expected, using a learned value function) and updates the policy with a clipped objective that prevents overly large steps.
- Engineering cost: four models in memory (policy, reference, reward, value), on-policy generation in the training loop, sensitive hyperparameters.
Direct Preference Optimization (DPO)
Derivation sketch
The KL-regularised objective above has a known optimal policy:
π*(y|x) = (1/Z(x)) · π_ref(y|x) · exp(r(x, y)/β)
Rearranging expresses the reward in terms of the policy:
r(x, y) = β log(π*(y|x)/π_ref(y|x)) + β log Z(x)
Substitute into the Bradley–Terry likelihood; the intractable Z(x) cancels in the difference r(y_w) − r(y_l). Optimising the policy directly on preference pairs (Rafailov et al., 2023):
L_DPO = −E[ log σ( β·[log π_θ(y_w|x)/π_ref(y_w|x) − log π_θ(y_l|x)/π_ref(y_l|x)] ) ]
The model is its own implicit reward model: β log(π_θ/π_ref) is the "implicit reward". No separate reward model, no sampling during training, no value network: just a classification-style loss over (prompt, chosen, rejected) triples, plus a frozen reference model to compute log-probabilities (which can be precomputed).
- β (≈ 0.05–0.5) controls how far the policy may move from the reference.
- Log-probabilities are sums over response tokens (masking prompt tokens, chapter 163).
- DPO is offline: it learns from a fixed dataset. Online/iterative DPO regenerates pairs from the current policy and re-labels them, closing some of the gap with RL.
def sequence_logprob(logits, labels, ignore_index=-100):
"""Sum of log p(token) over response tokens. logits: [B, T, V]; labels: [B, T] (already shifted)."""
logp = F.log_softmax(logits, dim=-1)
mask = labels != ignore_index
tok = logp.gather(-1, labels.clamp(min=0).unsqueeze(-1)).squeeze(-1)
return (tok * mask).sum(-1)
def dpo_loss(pi_chosen, pi_rejected, ref_chosen, ref_rejected, beta=0.1):
"""Inputs: summed log-probs of chosen/rejected responses under policy and reference."""
chosen_reward = beta * (pi_chosen - ref_chosen) # implicit rewards
rejected_reward = beta * (pi_rejected - ref_rejected)
loss = -F.logsigmoid(chosen_reward - rejected_reward).mean()
accuracy = (chosen_reward > rejected_reward).float().mean()
return loss, accuracy, (chosen_reward - rejected_reward).mean()
# Toy check: a "policy" over 4 possible responses to one prompt; preferences favour response 0 over 3
ref_logits = torch.zeros(4) # reference: uniform
policy_logits = torch.zeros(4, requires_grad=True)
opt = torch.optim.SGD([policy_logits], lr=0.5)
for _ in range(200):
logp = F.log_softmax(policy_logits, 0); ref = F.log_softmax(ref_logits, 0)
loss, acc, margin = dpo_loss(logp[0:1], logp[3:4], ref[0:1], ref[3:4], beta=0.5)
opt.zero_grad(); loss.backward(); opt.step()
F.softmax(policy_logits, 0).detach() # ≈ [0.96, 0.02, 0.02, 0.0004]: 0 up, 3 down; 1 and 2 shrink only via normalisation
Variants
| Method | Change | Why |
|---|---|---|
| IPO | Squared loss on the log-ratio margin | Avoids over-fitting deterministic preferences |
| KTO | Uses unpaired binary labels (good/bad) with a prospect-theory-inspired loss | Thumbs-up/down data is easier to collect than pairs |
| ORPO | Combines SFT loss with an odds-ratio preference term, no reference model | Single-stage, cheaper |
| SimPO | Length-normalised implicit reward, no reference model, target margin | Reduces length exploitation |
| Online / iterative DPO | Fresh on-policy pairs judged by an RM or AI judge each round | Closer to RL performance |
Rejection sampling and best-of-n
Simpler alternatives that are widely used in practice:
- Best-of-n at inference: sample n responses, return the one with the highest reward/verifier score. Costs n× compute; no training.
- Rejection-sampling fine-tuning (RFT / "expert iteration"): for each prompt, sample n responses, keep the best (by reward model, verifier, tests or judge), and run SFT on them. Repeat. Stable, easy, and effective, especially with verifiable rewards (maths, code).
- Used inside larger pipelines (e.g. Llama 2's post-training combined rejection sampling and PPO).
def rejection_sampling_dataset(prompts, generate, score, n=8, threshold=None):
data = []
for p in prompts:
candidates = [generate(p) for _ in range(n)]
scored = sorted(((score(p, c), c) for c in candidates), reverse=True)
best_score, best = scored[0]
if threshold is None or best_score >= threshold:
data.append({"messages": [{"role": "user", "content": p}, {"role": "assistant", "content": best}]})
return data # then SFT on `data` (chapter 163)
Reinforcement learning from verifiable rewards
For domains with checkable answers, skip the learned reward model: reward = 1 if the final answer is correct (maths), tests pass (code), the proof checks, or the task's end state is reached (agent environments); plus small format rewards.
GRPO (Group Relative Policy Optimization, DeepSeekMath 2024; used for DeepSeek-R1) drops PPO's value network: sample a group of G responses per prompt, and use each response's reward normalised within the group as its advantage:
Aᵢ = (rᵢ − mean(r₁…r_G)) / std(r₁…r_G)
Responses better than their siblings are reinforced, worse ones discouraged; a KL term (or none, in some variants) keeps the policy anchored. Long chains of reasoning emerge because they lead to more correct answers. Variants (DAPO, Dr. GRPO, GSPO and others) fix biases in length normalisation and stabilise training for large models.
def grpo_advantages(rewards, eps=1e-6):
r = torch.as_tensor(rewards, dtype=torch.float32)
return (r - r.mean()) / (r.std() + eps)
grpo_advantages([1, 0, 0, 1, 1, 0, 0, 0]) # correct answers get positive advantage, wrong ones negative
Outcome vs process rewards: outcome reward models score only the final answer; process reward models score each reasoning step, giving denser feedback but needing step-level labels. Verifiable outcome rewards scale best when available.
Reward hacking persists in RL with verifiers: models exploit weak tests (special-casing test inputs, editing tests), find loopholes in environment checks, or learn to look correct to a judge. Robust verifiers, held-out evaluations, and monitoring of reasoning and behaviour are essential.
Constitutional AI and AI feedback
Constitutional AI (Anthropic, 2022) uses a written set of principles (a "constitution") to guide AI-generated feedback:
- Supervised phase: the model critiques and revises its own responses according to principles; fine-tune on revisions.
- RL phase (RLAIF): an AI judge compares response pairs according to the principles; train a preference model on these AI labels and run RL.
Benefits: scalable labelling, explicit and inspectable criteria, consistency. Risks: the judge's biases and blind spots propagate; principles must be carefully written and tested; human oversight remains necessary. AI feedback now features in most post-training pipelines alongside human data.
Evaluating aligned models
- Helpfulness: win rates against a baseline judged by humans or calibrated AI judges (control for length bias, e.g. length-controlled win rates).
- Harmlessness and over-refusal: refusal rates on harmful prompts and on benign-but-sensitive prompts (refusing "how do I kill a Python process?" is a failure).
- Honesty: calibration, admitting uncertainty, factual accuracy, sycophancy tests (does the model abandon a correct answer when the user pushes back?).
- Capability regression: benchmarks before and after (the "alignment tax").
- Reward-model drift: compare reward scores with independent judges; rising reward with falling human preference signals over-optimisation.
Practical recipe
For most teams adapting open models:
- SFT on high-quality demonstrations (chapter 163).
- Collect preference pairs from your SFT model's outputs on real prompts; label with humans for the hardest/most important, AI judges with a rubric for scale, and verifiers where possible.
- Train with DPO (or SimPO/ORPO) using LoRA; β ≈ 0.1; 1–3 epochs; watch implicit reward margins and chosen log-prob (if both chosen and rejected log-probs collapse, the model is drifting).
- Evaluate helpfulness, task metrics, refusals and regressions; iterate with new on-policy pairs.
- For verifiable tasks (code, maths, structured extraction with ground truth), try rejection-sampling fine-tuning or GRPO.
# Hugging Face TRL: DPO with LoRA on a preference dataset {"prompt", "chosen", "rejected"}
from datasets import load_dataset
from peft import LoraConfig
from trl import DPOConfig, DPOTrainer
ds = load_dataset("json", data_files="prefs.jsonl", split="train").train_test_split(test_size=0.05)
args = DPOConfig(output_dir="out/dpo", beta=0.1, learning_rate=5e-6, num_train_epochs=2,
per_device_train_batch_size=2, gradient_accumulation_steps=16, bf16=True,
eval_strategy="steps", eval_steps=100, logging_steps=10)
trainer = DPOTrainer(model="out/sft-merged", args=args, train_dataset=ds["train"], eval_dataset=ds["test"],
peft_config=LoraConfig(r=16, lora_alpha=32, target_modules="all-linear", task_type="CAUSAL_LM"))
trainer.train() # logs rewards/chosen, rewards/rejected, rewards/margins, rewards/accuracies
Lab: DPO on a tiny GPT, and how it games the objective
Setup. PyTorch on 2 CPU threads. Start from chapter 163's full-SFT model (400 steps on glossary Q&A; 891 entries at this point, because this volume's own revision sheets had added a few; 757 train, 134 held out). Preference pairs: chosen = the reference definition; rejected = the same definition with words randomly doubled (the SFT model's characteristic error), so the preference is "don't repeat words". DPO loss −log σ(β[(log π(c) − log π_ref(c)) − (log π(r) − log π_ref(r))]) with sequence log-probabilities over answer tokens, batch 8, AdamW. Scope: synthetic preferences on a tiny model show the mechanics and the classic failure modes; they say nothing about how well a large model aligns.
Metrics: held-out preference accuracy (does the model give the chosen answer higher log-probability?), share of greedy answers to held-out questions with a doubled word, mean answer length, and general loss on ordinary text.
Experiment 1: a confounded preference set
The first version inserted the doubled words, so every rejected answer was longer than its chosen answer:
| Model | Preference accuracy | Doubled-word answers | Mean words | General loss |
|---|---|---|---|---|
| SFT | 0.918 | 0.17 | 8.4 | 5.229 |
| DPO β = 0.1, lr 1e-4, 300 steps | 0.918 | 0.00 | 1.1 | 10.822 |
| DPO β = 0.5, same | 0.918 | 0.00 | 0.8 | 7.059 |
The SFT model already "preferred" the chosen answers 92% of the time, simply because a longer sequence has a lower total log-probability. DPO then learned the cheapest way to make rejected-like text unlikely: stop almost immediately. Repetition vanished because the answers did. Lesson: check your preference data for confounds (length above all) before training.
Experiment 2: length-matched pairs
The rejected answers were truncated to the chosen answer's word count, so length no longer gives the answer away:
| Model | Preference accuracy | Doubled-word answers | Mean words | General loss | Time |
|---|---|---|---|---|---|
| SFT | 0.634 | 0.09 | 9.6 | 5.245 | — |
| DPO β = 0.1, lr 2e-5, 150 steps | 0.843 | 0.03 | 4.0 | 5.688 | 43 s |
| DPO β = 0.5, lr 2e-5, 150 steps | 0.836 | 0.01 | 6.0 | 5.424 | 44 s |
| DPO β = 0.1, lr 1e-4, 300 steps | 0.851 | 0.09 | 1.8 | 6.431 | 88 s |
| control: 300 more SFT steps on chosen answers only | 0.649 | 0.10 | 9.3 | 5.528 | — |
DPO β=0.5: Outbox -> "a system, data that can't be refered."
DPO β=0.1, lr 1e-4: Outbox -> "onecription." Persistence context -> "ceed."
- With an honest preference set, the starting model was near chance on telling chosen from rejected (0.634); DPO raised that to about 0.84, and the doubled-word rate fell to 1–3%.
- More SFT on the chosen answers alone barely moved either number: the rejected examples carry the signal. Showing only good answers doesn't teach the model what to avoid.
- Answers still got shorter, because even length-matched, the remaining degree of freedom (stopping earlier) reduces the risk of a doubled word. Larger β held the model closer to the SFT reference: longer answers (6.0 words), less drift in general loss.
- The aggressive run (5× the learning rate, twice the steps) gained almost nothing in preference accuracy and collapsed the outputs; its doubled-word rate even came back as fragments like "celylyly". Over-optimisation shows up in generations long before it shows in the training objective.
Try it yourself
- Add pairs where the chosen answer is longer than the rejected one, and see whether the shortening stops.
- Use the length-normalised variant (average log-probability per token) and compare.
- Train a small reward model (a linear head on the SFT model's final hidden state) on the pairs, and use best-of-8 sampling with it instead of DPO.
- Track the implicit reward margin during training and plot it against answer length.
Revision sheet: preference optimisation and alignment
Key ideas
- Alignment shapes a pre-trained model into a helpful, honest, harmless assistant; post-training typically = SFT → preference optimisation → safety work.
- Preference data: prompts with chosen/rejected answers from humans or AI judges; quality, diversity and confound control matter most.
- Reward model: Bradley–Terry loss −log σ(r(chosen) − r(rejected)).
- RLHF (PPO): maximise reward minus a KL penalty to the reference model; needs policy, reference, reward and value models.
- DPO: closed-form objective on pairs relative to a frozen reference; β sets drift; variants (IPO, KTO, ORPO, SimPO) change regularisation, data needs or length handling.
- Best-of-n / rejection sampling with a reward model; RL from verifiable rewards for maths and code; Constitutional AI / RLAIF for AI-generated feedback against written principles.
- Failure modes: reward hacking, length bias, sycophancy, over-refusal, mode collapse, forgetting.
- Evaluate preferences won, plus length, capability benchmarks, safety and refusal rates.
Numbers to remember
- Lab (confounded): SFT already "preferred" chosen 92% because rejected were longer; DPO collapsed answers to ~1 word.
- Lab (length-matched): preference accuracy 0.63 → 0.84; doubled-word answers 9% → 1–3%; answers 9.6 → 4–6 words.
- Lab: SFT on chosen only: 0.63 → 0.65; the rejected side carries the signal.
Pitfalls
- Preference pairs where a superficial feature (length, format, politeness) predicts the label.
- Optimising too long or with too small β.
- Judging alignment only by the training objective or reward-model score.
- Using one judge model for both training and evaluation.
- Ignoring over-refusal while measuring harmlessness.
Glossary
- Policy / reference: the model being trained / the frozen starting copy.
- KL penalty: a cost on divergence from the reference distribution.
- Bradley–Terry model: P(A preferred to B) = σ(r_A − r_B).
- Reward hacking: exploiting flaws in the reward signal.
- RLVR: reinforcement learning from verifiable rewards (tests, checkers).