DPO: turn preference odds into a policy loss
直接偏好优化
Derive the reference-ratio objective and test what it does to a response absent from the comparison data.
dpoA comparison can train the policy without a separate reward network
Suppose A is preferred to B. Supervised fine-tuning on A raises its likelihood but discards the comparison with B. A reward-model pipeline learns a score difference and then optimizes a policy against the scores. Direct preference optimization, or DPO, instead uses the policy’s probability ratios to parameterize that score difference.
The reference policy matters. Raising the probability of an already-common answer and raising the probability of an initially-rare answer are different changes relative to the reference. DPO compares those relative changes for the preferred and dispreferred responses. It is not simply “maximize the winning answer’s probability.”
Rafailov and colleagues, sections 3–4, derive DPO from a KL-regularized reward objective and a preference model. The latter belongs to the same broad comparison-learning tradition illustrated by Christiano and colleagues, section 2.2.3. Neither the derivation nor a low training loss establishes that all human preferences have been captured.
The partition function disappears from a comparison
Fix a prompt and a finite set of answers. Let be the reference probabilities, the policy, a reward and . Start with:
The constraint is . As derived in the RLHF chapter, the optimal distribution is:
Taking logarithms and rearranging expresses reward through the optimal policy:
The last term is shared by answers to the same prompt. Under a Bradley–Terry comparison model, it cancels from the reward difference:
Now substitute a trainable policy for . For pair , define and . With soft target , the loss is:
For a dataset always ordered winner first, reduces this to the original negative log-sigmoid loss in the DPO paper’s equation 7. Our fractional targets describe explicitly synthetic preference frequencies, not a new label-smoothing recommendation.
In a tabular policy, . Its log-normalizer cancels between the two answers, so the gradient is particularly simple:
Here is the coordinate basis vector. For a language model, replace basis-vector differences with the difference of sequence log-probability gradients; shared parameters can affect many other responses. Sequence log-probabilities sum the response-token log-probabilities under the prompt context. Prompt loss masking, EOS inclusion and sum-versus-length-normalized scores must be specified; silently changing them changes the objective.
The implicit reward associated with the learned policy is:
It has no separate reward-network parameters. That does not mean preferences or reward assumptions disappeared. Equalities between the ideal optimum and a preference model do not guarantee recovery from finite, noisy or disconnected comparison data, an insufficient model class, or an unfinished optimization run.
Recover an exact policy, then leave one answer unobserved
The complete Python/NumPy program below uses three answers. The reference is (0.5,0.3,0.2), , and synthetic reward is . Pair targets are 0.8,0.8,16/17 in the order (A,B),(B,C),(A,C). The reward generates labels and an independent oracle; the training loop receives only the reference, pairs and targets.
"""Original tabular DPO with synthetic fractional labels and an exact oracle."""
import json
import numpy as np
def sigmoid(x):
x = np.asarray(x, dtype=float)
return np.exp(-np.logaddexp(0, -x))
def softmax(x):
x = np.asarray(x, dtype=float)
if x.ndim != 1 or not len(x) or not np.isfinite(x).all():
raise ValueError("Expected a nonempty finite vector")
e = np.exp(x - x.max())
return e / e.sum()
def preferences(scores, pairs):
return sigmoid(scores[pairs[:, 0]] - scores[pairs[:, 1]])
def pair_loss_grad(scores, pairs, targets):
scores = np.asarray(scores, dtype=float)
pairs = np.asarray(pairs, dtype=int)
targets = np.asarray(targets, dtype=float)
if (scores.ndim != 1 or pairs.ndim != 2 or pairs.shape[1] != 2
or len(pairs) == 0 or targets.shape != (len(pairs),)
or not np.isfinite(scores).all() or not np.isfinite(targets).all()
or np.any((targets < 0) | (targets > 1))
or pairs.min() < 0 or pairs.max() >= len(scores)):
raise ValueError("Invalid scores, pairs or soft labels")
delta = scores[pairs[:, 0]] - scores[pairs[:, 1]]
loss = np.mean(np.logaddexp(0, delta) - targets * delta)
residual = (sigmoid(delta) - targets) / len(pairs)
gradient = np.zeros_like(scores)
np.add.at(gradient, pairs[:, 0], residual)
np.add.at(gradient, pairs[:, 1], -residual)
return float(loss), gradient
def fit_scores(pairs, targets, size=3, steps=2000):
scores = np.zeros(size)
for _ in range(steps):
_, gradient = pair_loss_grad(scores, pairs, targets)
scores -= 0.5 * gradient
return scores
def policy_for_reward(reference, reward, beta):
reference = np.asarray(reference, dtype=float)
reward = np.asarray(reward, dtype=float)
if (reference.ndim != 1 or reference.shape != reward.shape
or not np.isfinite(reference).all() or not np.isfinite(reward).all()
or np.any(reference <= 0) or not np.isclose(reference.sum(), 1)
or not np.isfinite(beta) or beta <= 0):
raise ValueError("Positive normalized reference and beta are required")
return softmax(np.log(reference) + reward / beta)
PAIRS = np.array([[0, 1], [1, 2], [0, 2]])
def dpo_loss_grad(logits, reference, beta, pairs, targets):
policy_for_reward(reference, np.zeros_like(reference), beta)
# log-softmax normalization cancels from each pairwise log ratio.
implicit = beta * (np.asarray(logits) - np.log(reference))
loss, grad = pair_loss_grad(implicit, pairs, targets)
return loss, beta * grad
def train(reference, beta, pairs, targets, steps=3000):
logits = np.log(reference)
trace = []
for step in range(steps+1):
loss, gradient = dpo_loss_grad(logits, reference, beta, pairs, targets)
if step % 300 == 0: trace.append([step,loss])
if step < steps: logits -= .5 * gradient
return softmax(logits), logits, trace
def demo():
reference = np.array([.5,.3,.2]); beta = .7
truth = np.array([np.log(4),0.,-np.log(4)])
target = preferences(truth, PAIRS)
policy, logits, trace = train(reference,beta,PAIRS,target)
oracle = policy_for_reward(reference,truth,beta)
implicit = beta*np.log(policy/reference)
# Unobserved response: its raw logit gets no update, its probability can move.
ref4 = np.array([.4,.25,.15,.2])
p4, l4, _ = train(ref4,beta,PAIRS,target)
return dict(reference=reference.tolist(), beta=beta, targets=target.tolist(),
policy=policy.tolist(), oracle=oracle.tolist(),
max_error=float(np.max(abs(policy-oracle))),
implicit_reward=implicit.tolist(),
recovered_preferences=preferences(implicit,PAIRS).tolist(),trace=trace,
unseen_raw_logit_change=float(l4[3]-np.log(ref4[3])),
unseen_probability_before=float(ref4[3]),unseen_probability_after=float(p4[3]))
if __name__ == "__main__":
print(json.dumps(demo(), indent=2))
After 3,000 updates, probabilities are approximately (0.9170731565,0.0759398142,0.0069870294), within of the oracle in this run. The implicit rewards recover the three preference probabilities. They differ from the original rewards by a common constant, which comparisons cannot identify.
The second experiment adds a fourth answer with initial probability 0.2, but never compares it. Its raw logit does not change at all. Its normalized probability nevertheless falls to about 0.05936449 as other logits move. “No label for this answer” does not imply “its output probability is protected.”
For pairs and tabular logits, one update costs time and storage including the dataset. The code avoids enumerating pair combinations beyond those supplied. In language-model DPO, computing chosen and rejected sequence probabilities, backward activations and reference probabilities dominates instead. A frozen reference can be evaluated or precomputed for a fixed dataset under a declared recipe; this toy does not benchmark that tradeoff.
The clean derivation has conditions
The reference must have positive support on compared responses. A disconnected comparison graph cannot determine all relative scores: each disconnected component can shift without changing its internal comparisons. Our unseen fourth answer is the simplest example. General language models add parameter sharing rather than eliminating this data-coverage issue.
Preference cycles or annotator disagreement may not fit a single scalar utility. A larger is not a universal knob that guarantees a specific measured KL after finite-data training. Nor is improving a pairwise loss a guarantee that a winner’s absolute probability increases on every update in a shared network. The relative log ratio is the quantity in the loss.
The original DPO training stage uses offline preference pairs and avoids a PPO-style on-policy sampling loop and explicit reward fitting. Data collection, supervised preparation, validation and ordinary inference still cost work. The finite example proves its own arithmetic, not an advantage over RLHF on real tasks.
Test what the ratio actually controls
- The policy initially equals its reference. What probability does its implicit comparison model assign to either answer?
Answer: Both log ratios are zero, so the comparison probability is , even if the reference gives the answers very different probabilities.
- Why can we use raw logits when computing the tabular pair difference?
Answer: Each log probability is its logit minus the same log-normalizer. Subtracting the two log probabilities cancels that normalizer. Reference log probabilities still remain.
- An unobserved answer’s raw logit stays fixed. Must its probability stay fixed?
Answer: No. Softmax divides by the exponential sum of all logits. The four-answer experiment leaves the unobserved logit unchanged while its probability moves from 0.2 to approximately 0.05936449.
- If A beats B, B beats C and C beats A, each with probability 0.8, can one scalar reward exactly represent all three under Bradley–Terry?
Answer: No. The requested differences are each , but their sum around the cycle must be zero. A scalar model must compromise. DPO’s implicit reward does not escape this contradiction.
Read the assumptions alongside the simplification
DPO’s equations 3–7 connect the regularized optimum to the comparison loss; section 4 also explains the update weighting and dataset/reference relationship. Christiano’s section 2.2.3 helps separate the basic comparison assumption from a practical reward-learning recipe. For a real experiment, compare objectives, reference policies, label coverage and evaluation conditions before attributing a difference to the optimizer alone.
Make a prediction, then check
Is an unobserved response guaranteed to retain its probability during DPO?
Learning objectives
- Derive partition cancellation and distinguish ideal equivalence from finite-data guarantees.
- Verify the toy calculation and state what it cannot establish.
Prerequisites & connections
Explore related knowledge →References
- Direct Preference Optimization: Your Language Model is Secretly a Reward Model — v2
Rafael Rafailov; Archit Sharma; Eric Mitchell; Stefano Ermon; Christopher D. Manning; Chelsea Finn · 2023 - Deep Reinforcement Learning from Human Preferences — v1
Paul F. Christiano; Jan Leike; Tom B. Brown; Miljan Martic; Shane Legg; Dario Amodei · 2017
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author. Sections3/4, PDF3/4 viewed; gradient and procedure text read. BT, KL objective, partition cancellation and DPO; v2 dated2023-12-13. Section2.2 through2.2.4 opening; PDF5 viewed: trajectory comparisons, soft labels, negative cross-entropy and actual recipe modifications. Seven paired equations and four explained exercises. Reference-ratio derivation, normalizer cancellation, all-logit finite differences, exact policy and unobserved logit/probability distinction; finite-data assumptions explicit.
- Reference-ratio derivation, normalizer cancellation, all-logit finite differences, exact policy and unobserved logit/probability distinction; finite-data assumptions explicit.
- Four computed SVG variants per topic;10 numeric/geometry tests and30 responsive cases passed. Ten selected final captures directly viewed. Full article acceptance recorded separately.
Source locations checked:
- Direct Preference Optimization: Your Language Model is Secretly a Reward Model — v2 · Sections3/4, PDF3/4 viewed; gradient and procedure text read. BT, KL objective, partition cancellation and DPO; v2 dated2023-12-13.
- Deep Reinforcement Learning from Human Preferences — v1 · Section2.2 through2.2.4 opening; PDF5 viewed: trajectory comparisons, soft labels, negative cross-entropy and actual recipe modifications.
Related topics