Preference Tuning: Reward Models, RLHF and DPO
After supervised fine-tuning and instruction tuning, a model imitates its demonstrations, good and bad parts alike. Many qualities are easier to judge than to demonstrate: which of two answers is more helpful, more honest, less verbose, safer. Preference tuning learns from such judgements: pairs of responses to the same prompt, one marked as preferred. Training: Pretraining, Fine-tuning, RLHF introduced the idea; Policy Gradients and RLHF has the policy-gradient math. This lesson builds the three working parts from scratch: a Bradley-Terry reward model, the KL-regularised objective that RLHF optimises, and the DPO loss that optimises it without a reward model or reinforcement learning, then runs DPO on a tiny language model.
Reward models: the Bradley-Terry model
Assume each response to prompt has a hidden score , and that a person prefers ("winner") over ("loser") with probability
This is the Bradley-Terry model, the same idea as an Elo rating. A reward model is fitted to preference pairs by maximum likelihood, which is logistic regression on score differences:
In practice is the SFT model with its LM head replaced by a scalar head. In the NumPy version below each response is just four features (how correct, how polite, whether it invents facts, its length), the simulated annotators prefer responses by Bradley-Terry with hidden weights, and the reward is linear, . The annotators' weights include a small preference for length, as real annotators' often do.
import numpy as np
rng = np.random.default_rng(0)
# 400 candidate responses described by 4 features
names = ["correct", "polite", "made-up facts", "length (100 words)"]
X = np.column_stack([rng.random(400), rng.random(400), rng.random(400) < 0.3, rng.uniform(0.2, 3.0, 400)]).astype(float)
w_true = np.array([3.0, 1.0, -2.5, 0.4]) # what the annotators actually reward (length a little)
def sample_pairs(n):
a, b = rng.integers(0, 400, n), rng.integers(0, 400, n)
p_a = 1 / (1 + np.exp(-(X[a] - X[b]) @ w_true)) # Bradley-Terry: P(a preferred over b)
a_wins = rng.random(n) < p_a
chosen, rejected = np.where(a_wins, a, b), np.where(a_wins, b, a)
return X[chosen] - X[rejected] # features of chosen minus rejected
D_train, D_test = sample_pairs(2000), sample_pairs(1000)
# reward model r(x) = w . x, trained with the pairwise loss -log sigmoid(r(chosen) - r(rejected))
w = np.zeros(4)
for step in range(2000):
m = D_train @ w # reward margins
grad = -(D_train * (1 - 1 / (1 + np.exp(-m)))[:, None]).mean(0)
w -= 0.5 * grad
loss = np.mean(np.log1p(np.exp(-(D_train @ w))))
print("learned weights:", {n: round(float(v), 2) for n, v in zip(names, w)})
print(f"train loss {loss:.3f} | held-out pair accuracy {np.mean(D_test @ w > 0):.3f} | with the true weights {np.mean(D_test @ w_true > 0):.3f}")
best = np.argmax(X @ w)
print("highest-reward response:", {n: round(float(v), 2) for n, v in zip(names, X[best])})learned weights: {'correct': 2.96, 'polite': 1.08, 'made-up facts': -2.34, 'length (100 words)': 0.37}
train loss 0.456 | held-out pair accuracy 0.783 | with the true weights 0.779
highest-reward response: {'correct': 0.97, 'polite': 0.99, 'made-up facts': 0.0, 'length (100 words)': 2.37}
The fitted weights recover the hidden ones (2.96 against 3.0 for correctness, against for invented facts), and the held-out pair accuracy, 0.783, equals what the true weights achieve (0.779): about 22 % of the simulated judgements go against the higher true score, so no reward model can be right on all pairs. Human preference data is noisy in the same way; inter-annotator agreement of 60 to 75 % is common. The model also learned the annotators' liking for length (0.37 per 100 words), and the highest-scoring response is a long one: whatever biases the labels have, the reward model inherits.
RLHF: maximise reward, stay close to the reference
RLHF then trains the policy (initialised from the SFT model) to produce high-reward responses, with a penalty for drifting away from the frozen SFT model :
The KL term matters because the reward model is only an approximation: pushed hard, the policy finds responses the reward model over-scores (reward hacking). For a fixed prompt this objective has a closed-form optimum:
With only five possible responses we can evaluate it exactly. The reward model below scores four responses about right but over-rewards a "very long padded" answer (2.5, while people value it at 0.9):
import numpy as np
responses = ["short correct", "long correct", "polite wrong", "rude correct", "very long padded"]
pi_ref = np.array([0.30, 0.25, 0.25, 0.15, 0.05]) # what the SFT model does now
r_true = np.array([1.0, 1.2, -1.0, 0.2, 0.9]) # what people actually want
r_rm = np.array([1.0, 1.3, -0.9, 0.2, 2.5]) # the reward model over-rewards length
def show(p):
return " ".join(f"{x:.3f}" for x in p)
def kl(p, q):
return float(np.sum(p * np.log(p / q)))
print(" beta | policy over the 5 responses | reward model | true reward | KL to ref")
for beta in [5.0, 1.0, 0.5, 0.1]:
pi = pi_ref * np.exp(r_rm / beta) # optimum of E[r] - beta * KL(pi || pi_ref)
pi /= pi.sum()
print(f"{beta:5.1f} | {show(pi)} | {pi @ r_rm:12.3f} | {pi @ r_true:11.3f} | {kl(pi, pi_ref):9.3f}")
print(f" ref | {show(pi_ref)} | {pi_ref @ r_rm:12.3f} | {pi_ref @ r_true:11.3f} | {0:9.3f}") beta | policy over the 5 responses | reward model | true reward | KL to ref
5.0 | 0.322 0.285 0.183 0.137 0.072 | 0.736 | 0.573 | 0.018
1.0 | 0.310 0.349 0.039 0.070 0.232 | 1.323 | 0.913 | 0.358
0.5 | 0.167 0.254 0.003 0.017 0.559 | 1.896 | 0.975 | 1.206
0.1 | 0.000 0.000 0.000 0.000 1.000 | 2.500 | 0.900 | 2.995
ref | 0.300 0.250 0.250 0.150 0.050 | 0.555 | 0.425 | 0.000
As falls, the policy moves away from the reference (KL from 0.018 to 2.995) and the reward-model score rises steadily, from 0.736 to 2.500. The true reward rises only until (0.975) and then falls (0.900 at ), when all probability goes to the padded answer the reward model over-scores. That is reward hacking in five numbers, and the reason , or a KL budget, is tuned by checking real quality, not the reward model's score.
For a real language model the responses cannot be enumerated, so RLHF samples them and uses PPO (proximal policy optimisation). Each sampled response gets the reward model's score at the end and a per-token KL penalty ; a value model estimates advantages ; and the update maximises the clipped objective
which keeps each update close to the policy that generated the samples. That means four models in memory (policy, reference, reward, value), generation inside the training loop, and many hyperparameters: powerful, but expensive and fragile.
DPO: the same objective as a classification loss
Direct Preference Optimization (Rafailov et al., 2023) solves the closed-form optimum for the reward, , and puts it into the Bradley-Terry likelihood. cancels in the difference of two responses to the same prompt, leaving a loss on the policy alone:
Its gradient raises the log-probability of the chosen response and lowers that of the rejected one, weighted by how wrong the current margin is:
No reward model, no sampling, no value model: two models (policy and frozen reference) and a loss over log-probabilities of fixed data. The NumPy version uses a policy that is a softmax over five responses, preference pairs labelled by Bradley-Terry with the true rewards of the previous example, and . It checks the gradient, checks its direction against the raw win counts, and compares the trained policy with the closed-form RLHF optimum:
import numpy as np
rng = np.random.default_rng(0)
K, beta = 5, 0.5
pi_ref = np.array([0.30, 0.25, 0.25, 0.15, 0.05])
r_true = np.array([1.0, 1.2, -1.0, 0.2, 0.9])
# preference data: pairs of responses, labelled by Bradley-Terry with the true reward
a, b = rng.integers(0, K, 3000), rng.integers(0, K, 3000)
keep = a != b; a, b = a[keep], b[keep]
a_wins = rng.random(len(a)) < 1 / (1 + np.exp(-(r_true[a] - r_true[b])))
yw, yl = np.where(a_wins, a, b), np.where(a_wins, b, a)
def log_softmax(z):
return z - np.log(np.exp(z - z.max()).sum()) - z.max()
def dpo_loss_grad(theta):
"""Policy pi = softmax(theta). DPO loss and its gradient with respect to theta."""
logp, logp_ref = log_softmax(theta), np.log(pi_ref)
h = beta * ((logp[yw] - logp_ref[yw]) - (logp[yl] - logp_ref[yl])) # implicit reward margin
loss = np.mean(np.log1p(np.exp(-h)))
coef = -beta * (1 - 1 / (1 + np.exp(-h))) / len(h) # dL/dh = -(1 - sigmoid(h)), times beta
g = np.zeros(K)
np.add.at(g, yw, coef); np.add.at(g, yl, -coef) # d logp[y] / d theta = onehot(y) - pi; the -pi parts cancel
return loss, g
theta = np.log(pi_ref) # start at the reference policy
loss, g = dpo_loss_grad(theta)
e = np.zeros(K); e[1] = 1e-6
print(f"start: loss {loss:.4f} (= ln 2 = {np.log(2):.4f}) | dL/dtheta[1] analytic {g[1]:.6f}, numeric {(dpo_loss_grad(theta + e)[0] - dpo_loss_grad(theta - e)[0]) / 2e-6:.6f}")
wins = np.bincount(yw, minlength=K) - np.bincount(yl, minlength=K)
print("wins minus losses per response:", wins.tolist(), "| first step direction:", np.sign(-g).astype(int).tolist())
for step in range(3000):
loss, g = dpo_loss_grad(theta)
theta -= 2.0 * g
pi = np.exp(log_softmax(theta))
target = pi_ref * np.exp(r_true / beta); target /= target.sum()
print("after DPO:", np.round(pi, 3).tolist(), f"| loss {loss:.4f}")
print("closed form pi_ref * exp(r_true / beta), normalised:", np.round(target, 3).tolist())start: loss 0.6931 (= ln 2 = 0.6931) | dL/dtheta[1] analytic -0.036792, numeric -0.036792
wins minus losses per response: [284, 351, -654, -156, 175] | first step direction: [1, 1, -1, -1, 1]
after DPO: [0.419, 0.489, 0.006, 0.039, 0.047] | loss 0.5563
closed form pi_ref * exp(r_true / beta), normalised: [0.401, 0.498, 0.006, 0.04, 0.055]
At the start the policy equals the reference, every margin is 0 and the loss is exactly . The first step raises the three responses that win more pairs than they lose (284, 351, 175) and lowers the two that lose more. After training, the DPO policy (0.419, 0.489, 0.006, 0.039, 0.047) is close to the RLHF optimum for the true rewards (0.401, 0.498, 0.006, 0.040, 0.055): DPO reached the KL-regularised optimum from 2,385 noisy pairs (3,000 drawn, those comparing a response with itself dropped) without ever fitting a reward. The remaining gap is sampling noise in the pairs.
A tiny DPO run on a language model
The recorded example uses a tiny character-level decoder (as in the SFT lesson; no pretrained generative LLM is available offline). Its SFT data are noisy demonstrations for "reverse the word": 60 % of the answers reverse it, 40 % just copy it. After 300 SFT steps the model is a mix of both habits. DPO then trains on pairs with the reversed word as chosen and the copy as rejected, , AdamW at , 60 steps of 64 pairs, the SFT model frozen as reference. Sequence log-probabilities are sums over the response tokens and the end token. On 200 test words it reports the share of greedy outputs that are exactly the reversal or exactly the copy, and , the share of the two candidates' probability on the wanted one.
import copy, random
import torch, torch.nn as nn, torch.nn.functional as F
VOCAB = "_abcdefghijklmnopqrstuvwxyz>."
stoi = {c: i for i, c in enumerate(VOCAB)}
class TinyGPT(nn.Module):
def __init__(self, V=len(VOCAB), d=64, heads=4, layers=2, T=32):
super().__init__()
self.tok, self.pos = nn.Embedding(V, d), nn.Embedding(T, d)
self.blocks = nn.ModuleList(nn.TransformerEncoderLayer(d, heads, 4 * d, dropout=0.0, batch_first=True, norm_first=True)
for _ in range(layers))
self.norm, self.head = nn.LayerNorm(d), nn.Linear(d, V)
def forward(self, x):
T = x.shape[1]
h = self.tok(x) + self.pos(torch.arange(T))
for b in self.blocks:
h = b(h, src_mask=torch.triu(torch.full((T, T), float("-inf")), 1))
return self.head(self.norm(h))
rng = random.Random(0)
def word(): return "".join(rng.choice("abcdefghijklmnopqrstuvwxyz") for _ in range(rng.randint(3, 6)))
train_words, test_words = [word() for _ in range(2000)], [word() for _ in range(200)]
def batch(pairs): # pairs of (word, response) -> ids, labels with the prompt masked
rows = [([stoi[c] for c in w + ">" + r + "."], len(w) + 1) for w, r in pairs]
T = max(len(i) for i, _ in rows)
x = torch.tensor([i + [0] * (T - len(i)) for i, _ in rows])
y = torch.tensor([[-100] * (p - 1) + i[p:] + [-100] * (T - len(i) + 1) for i, p in rows])
return x, y
def seq_logp(model, pairs): # log pi(response | prompt), summed over the response tokens and EOS
x, y = batch(pairs)
logp = model(x).log_softmax(-1)
tok = logp.gather(-1, y.clamp(min=0).unsqueeze(-1)).squeeze(-1)
return (tok * (y != -100)).sum(1)
# 1) SFT on noisy demonstrations: 60 % reverse the word (wanted), 40 % just copy it (unwanted)
torch.manual_seed(0)
policy = TinyGPT()
opt = torch.optim.AdamW(policy.parameters(), lr=3e-3)
g = random.Random(1)
for step in range(300):
words = g.sample(train_words, 64)
x, y = batch([(w, w[::-1] if g.random() < 0.6 else w) for w in words])
loss = F.cross_entropy(policy(x).flatten(0, 1), y.flatten(), ignore_index=-100)
opt.zero_grad(); loss.backward(); opt.step()
reference = copy.deepcopy(policy).eval() # frozen copy of the SFT model
for p in reference.parameters(): p.requires_grad_(False)
def greedy_says(model, pairs): # greedy decoding outputs exactly r iff the argmax is right at every response step
x, y = batch(pairs)
pred = model(x).argmax(-1) # y[t] is already the target of position t
return ((pred == y) | (y == -100)).all(1).float().mean().item()
def report(name, model):
model.eval()
with torch.no_grad():
rev = seq_logp(model, [(w, w[::-1]) for w in test_words]); cop = seq_logp(model, [(w, w) for w in test_words])
ref_rev = seq_logp(reference, [(w, w[::-1]) for w in test_words])
share_rev = greedy_says(model, [(w, w[::-1]) for w in test_words])
share_copy = greedy_says(model, [(w, w) for w in test_words])
p_rev = torch.sigmoid(rev - cop).mean().item() # share of the two candidates' probability on "reverse"
print(f"{name:9s} | greedy output: reversed {share_rev:.3f}, copied {share_copy:.3f} | P(reverse vs copy) {p_rev:.3f}"
f" | mean log pi: reverse {rev.mean():.2f}, copy {cop.mean():.2f}")
report("after SFT", policy)
# 2) DPO: chosen = reversed word, rejected = copy; reference frozen
beta = 0.1
opt = torch.optim.AdamW(policy.parameters(), lr=1e-3)
for step in range(60):
words = g.sample(train_words, 64)
chosen, rejected = [(w, w[::-1]) for w in words], [(w, w) for w in words]
policy.train()
with torch.no_grad():
ref_c, ref_r = seq_logp(reference, chosen), seq_logp(reference, rejected)
margin = beta * ((seq_logp(policy, chosen) - ref_c) - (seq_logp(policy, rejected) - ref_r))
loss = -F.logsigmoid(margin).mean()
opt.zero_grad(); loss.backward(); opt.step()
if step in (0, 59):
print(f"DPO step {step + 1:2d}: loss {loss.item():.3f}")
report("after DPO", policy)
with torch.no_grad():
drift = (seq_logp(policy, [(w, w[::-1]) for w in test_words]) - seq_logp(reference, [(w, w[::-1]) for w in test_words])).mean()
print(f"mean log pi/pi_ref on the chosen answers: {drift:.2f} (implicit reward = beta times this = {beta * drift:.3f})")after SFT | greedy output: reversed 0.245, copied 0.170 | P(reverse vs copy) 0.561 | mean log pi: reverse -2.56, copy -2.99
DPO step 1: loss 0.693
DPO step 60: loss 0.040
after DPO | greedy output: reversed 0.665, copied 0.015 | P(reverse vs copy) 0.993 | mean log pi: reverse -1.86, copy -36.99
mean log pi/pi_ref on the chosen answers: 0.69 (implicit reward = beta times this = 0.069)
- DPO moved the preference. The probability split between the two candidates went from 0.561 to 0.993, and greedy copies fell from 0.170 to 0.015 of the test words.
- It did not create the skill. Greedy outputs that are exactly the reversal rose from 0.245 to 0.665, but a third of the outputs are still neither (half-reversed words): the SFT model never learned reversal well, and preference tuning re-weights what the model can already produce more than it teaches new abilities. The fix is better SFT data, not more DPO steps.
- Most of the change is in pushing the rejected answer down. The log-probability of the copy fell from to , while the chosen answer rose only from to (an implicit reward of ). DPO only constrains the margin, so it often lowers both responses' probabilities or sinks the rejected one; on real data this can also lower the chosen answers' likelihood, which is why some recipes add an SFT term on the chosen responses.
In practice, TRL's DPOTrainer implements this loss (with beta, typically 0.1 to 0.5) on data sets with prompt, chosen and rejected columns, usually on top of a LoRA adapter so the reference model is simply the base with the adapter switched off.
Variants
- IPO replaces the log-sigmoid with a squared loss on the margin, which keeps DPO from driving margins to infinity on deterministic preferences.
- KTO learns from unpaired labels (this answer is good / this one is bad), which are cheaper to collect than pairs.
- ORPO drops the reference model and adds an odds-ratio penalty on the rejected response to the SFT loss, doing SFT and preference tuning in one stage.
- Online methods (PPO, and newer group-based ones such as GRPO used for reasoning models with automatically checkable rewards) sample new responses from the current policy during training; offline DPO only sees the fixed pairs, which were usually generated by a different model.
Pitfalls
- Reward hacking. The policy exploits whatever the reward model over-scores (length, confident tone, flattery). Keep the KL penalty, check samples, and evaluate with people or held-out judges, not the reward model.
- Length bias. Annotators and judges prefer longer answers; normalise or control for length when building pairs and when evaluating.
- Off-policy pairs. DPO on pairs generated by a very different model can give small or odd changes; generate pairs from your SFT model when you can.
- Wrong reference. The reference must be the model you start from (the SFT model). With LoRA, the base with adapters disabled serves as the reference for free.
- Summing vs averaging log-probabilities. DPO uses the sum over response tokens; averaging per token changes the effective and favours different lengths.
- Over-optimising. Watch the margin and the chosen log-probability; when the chosen answers' likelihood keeps falling, the model is drifting into text neither answer contains.
Practice
- A reward model gives 1.2 to answer A and 0.4 to answer B. What probability does Bradley-Terry assign to "A preferred"?
- In the KL table, why does the true reward fall again at while the reward-model score keeps rising?
- With , a pair has and . Compute the margin and the DPO loss for this pair.
- Why does the DPO loss need the reference model, when ORPO does not?
Answers
- .
- The policy concentrates on the response the reward model over-scores (2.5 for an answer worth 0.9). The reward model's score keeps rising, but the true value of that response is lower than that of the "long correct" one, so the true reward falls: reward hacking.
- ; loss .
- DPO's implicit reward is ; the reference anchors it and plays the role of the KL penalty. ORPO instead adds a penalty on the odds of the rejected response to the ordinary SFT loss, so the SFT term itself keeps the model near its data.
Test yourself
How is a Bradley-Terry reward model trained?
- Regression on human scores from 1 to 10
- By minimising over preference pairs
- By maximising the KL divergence to the reference
- By next-token prediction on the chosen responses
What does the KL penalty in RLHF protect against?
- Slow training
- The policy drifting to responses the imperfect reward model over-scores (reward hacking) and losing the SFT model's abilities
- Overfitting of the reward model
- Long prompts
Which models does DPO need during training?
- Policy, reference, reward model and value model
- Only the policy and a frozen reference model
- Only a reward model
- Policy and value model
In the tiny DPO run, P(reverse vs copy) rose from 0.561 to 0.993 but exact reversals only from 0.245 to 0.665. Why?
- DPO was trained too long
- Preference tuning re-weights behaviours the model already has; the SFT model had not learned to reverse well
- The reference model was wrong
- was too large