Algorithmresearch
Direct preference optimization
Also called DPO.
Fit a language model to preference pairs with a logistic loss on the difference of its log-ratios to a frozen reference model. It optimizes the RLHF objective with no reward model and no sampling.
- Time
- Θ(m n c) worst
- Space
- Θ(m) extra
- Where
- c = the cost of one forward and backward pass of the network per token; m = the number of preference pairs in a batch; n = the length of a response in tokens
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Rafael Rafailov, Archit Sharma, Eric Mitchell, Stefano Ermon, Christopher D. Manning, Chelsea Finn, 2023
Direct preference optimization (DPO) trains a language model on pairs of responses where people said which one they prefer. It fits the same objective as reinforcement learning from human feedback (RLHF), the expected reward minus times the Kullback-Leibler divergence from a reference model, but it skips the two stages of that pipeline. It fits no separate preference reward model, and it does not sample from the model or run PPO. The loss of one pair is , a logistic loss on the difference of two log-ratios. The derivation is exact under the Bradley-Terry model of preferences. Whether DPO gives a better model than RLHF on a given task is a measured question, with mixed answers. DPO is usually run after instruction tuning, which supplies the reference model.
In plain words
You have a model that already answers questions, and a pile of examples where a person saw two answers to the same question and picked the better one.
DPO keeps a frozen copy of the starting model. For each example it asks two things: how much more likely does the new model make the chosen answer than the frozen copy does, and how much more likely does it make the rejected answer? Training pushes the first amount up and the second down.
The push is strong when the model still prefers the rejected answer, and weak when it already ranks the pair correctly. One setting controls how far the new model may move away from the frozen copy.
The problem
The data is a set of triples : a prompt , a preferred response and a dispreferred response . There is a reference policy , usually the model after supervised fine-tuning, which stays frozen. A policy assigns a sequence log probability to a response of tokens, by causal language modeling. The goal is the policy that maximizes the RLHF objective
for a reward that is never observed. What is observed are the preferences, which are assumed to follow the Bradley-Terry model with . The page has no Bradley-Terry page to link; see preference reward model.
Three steps give the DPO loss, and proofs/correctness.md proves each one.
- For a fixed reward, the objective has the unique optimum , with .
- Solving for the reward gives .
- In the Bradley-Terry probability only the difference of two rewards for the same appears, so cancels, and the preference probability is a function of the policy alone.
Replace by the trained policy and maximize the likelihood of the data. That gives the loss
The quantity is the implicit reward of the policy, and is the Bradley-Terry loss of that reward.
The algorithm
For each pair the network computes four sequence log probabilities: and with gradients, and , under with no gradients (they can be computed once before training). The algorithm below takes them as given and returns the mean loss over a batch of pairs and its gradient with respect to and . The training framework multiplies these by and (backpropagation) and takes an optimizer step.
DPO-LOSS(β, P) ▷ P: m tuples (a_w, b_w, a_l, b_l)- 1
total ← 0 - 2
for each (a_w, b_w, a_l, b_l) in P do - 3
z ← β ((a_w - b_w) - (a_l - b_l)) ▷ implicit reward margin - 4
total ← total + log_add(0, -z) ▷ -log σ(z), no overflow - 5
q ← σ(-z) ▷ in [0, 1], computed stably - 6
∂L/∂a_w ← -β q / m; ∂L/∂a_l ← β q / m - 7
return total / m and the gradients
Here log_add, from the log-sum-exp trick.
Example
Take and a batch of two pairs.
| pair | L3 | L4 | L5 | L6 | ||||
|---|---|---|---|---|---|---|---|---|
| 1 | -12 | -13 | -15 | -14 | 0.2 | 0.598139 | 0.450166 | -0.0225083 |
| 2 | -20 | -18 | -21 | -22 | -0.3 | 0.854355 | 0.574443 | -0.0287221 |
Line L7 returns the mean loss . In pair 1 the policy already gives the preferred response a higher log-ratio than the rejected one (implicit rewards and ), so and the weight is below one half. In pair 2 the order is wrong (, ), so and the pair gets the larger weight. Each is the negative of . Pair 2 shows that can be lower than and still count as a win: only the change relative to the reference matters.
The target of the training can be computed by hand for one prompt with three responses. With , rewards and , step 1 gives and . The expected reward rises from 0.7 under to 1.35006, at a KL cost of 0.32283 nats, and the objective is . A smaller moves further: gives and gives . The tests run gradient descent on the population DPO loss with Bradley-Terry labels for these rewards, on a softmax policy over the three responses, and reach within .
Correctness
proofs/correctness.md has the full proofs. The objective equals , so Gibbs' inequality makes the unique optimum (Theorem 1, the result of Appendix A.1 of Rafailov and colleagues). The reward is plus a term in that cancels in every Bradley-Terry difference. So the DPO loss is the negative log likelihood of the preferences under the reward that the policy implies. If every pair of responses is compared with positive probability, the labels follow the Bradley-Terry model, and the policy class can express , the population loss is minimized exactly at (Proposition 4). For lines L5 and L6: , and has slope in and in .
These are statements about the population optimum. A finite data set, a network that cannot express , and an optimizer that stops early can all give another policy; what DPO does then is measured, not proved.
Proof: The KL-regularized objective has the optimum pi_ref exp(r / beta) / Z, the Bradley-Terry likelihood of that optimum does not depend on Z, so the DPO loss is the reward-model loss of the implicit reward, and the gradient is -beta sigmoid(-z) on the preferred log probabilityfull
We use the notation of the page. Fix one prompt and drop it from the notation where it is fixed. is the set of responses, which we take finite (for sequences of bounded length over a finite vocabulary it is). The reference policy is a distribution on with for every , the reward is a function, and . All logs are natural logs. .
Theorem 1: the optimum of the KL-regularized objective
Let
over all distributions on , with . Put
Then for every . Hence is the unique maximizer, and the maximum is .
Proof. is a distribution with for every , so is finite. From the definition, . So
where we used . Multiply by and rearrange: . By Gibbs' inequality (Kullback-Leibler divergence), with equality only when . So , with equality only at .
The objective of the page averages over prompts drawn from a fixed distribution. The policy for each can be chosen apart from the others, so the optimum is for every , with its own .
Corollary 2: the reward in terms of the optimal policy
Take logs in the definition of and solve for :
So the reward is determined by the optimal policy up to the term , which depends on the prompt and not on the response. Conversely, if two rewards differ by a function of only, , then and the two give the same . This is Lemma 2 of Rafailov and colleagues (Section 5.1). Their Lemma 1, that such rewards also give the same Bradley-Terry preferences, holds because cancels in the difference .
Proposition 3: the Bradley-Terry likelihood in terms of the policy
The Bradley-Terry model says that is preferred to for the prompt with probability . Substitute Corollary 2 into the difference. The term appears in both rewards and cancels:
So the preference probabilities can be written with the policy alone, without , which would need a sum over all responses. DPO replaces by the trained policy and maximizes the log likelihood of the observed preferences. With , and , the negative log likelihood of one pair is , which is the loss of line L4. It equals the Bradley-Terry loss of the reward model , the implicit reward.
Proposition 4: the population minimizer is the optimal policy
Fix a prompt. Suppose that each unordered pair of responses is compared with probability , and that the label follows the Bradley-Terry model with the true reward . Suppose that the policy is a softmax over with free logits, so every positive distribution is reachable. Then the expected DPO loss is minimized exactly by .
Proof. For the pair let and . The expected loss of the pair is , using . This is the cross-entropy between the Bernoulli distributions with means and . It equals the entropy of the first plus their Kullback-Leibler divergence, so it is minimized exactly when , that is , because is strictly increasing. At , Corollary 2 gives for every pair, so every term is at its minimum, and so is the weighted sum. Conversely, at a minimizer every pair with has ; since every pair is compared, is the same constant for all , so , which is .
It is enough that the graph of compared pairs is connected: the constant then propagates along its paths. If the graph has two components, the relative mass of the components is not fixed by the data, and the minimizer is not unique. The proposition is about the population loss with Bradley-Terry labels and an unrestricted policy. With a finite data set, a restricted network and an optimizer that stops early, it says nothing about the result; that is a matter of measurement.
Proposition 5: the gradient
Let . Then . For a batch of pairs the loss is , and depends on with slope and on with slope . By the chain rule
which are lines L5 and L6. The reference log probabilities enter with the opposite signs. For a network with weights , the gradient is
and is large when the implicit reward ranks the pair in the wrong order. For the tabular softmax policy of the code, , so the normalizer cancels in , and .
Proposition 6: the loss is computed without overflow
, which is . log_add takes the exponential of a non-positive number only, so it does not overflow for any finite : for it returns , and for it returns , which rounds to . The function sigmoid of the code takes for and for , so it also takes the exponential of a non-positive number only. The sequence log probabilities themselves are sums of per-token log probabilities and are never exponentiated.
Remark: deterministic preferences
If one response always wins, so in Proposition 4, the pair loss decreases in and has no finite minimizer. The population minimizer then puts for any : the KL term of Theorem 1 does not stop it, because the derivation assumed a finite reward. The test "deterministic preferences push without limit" shows the loss falling at each step.
Complexity
The loss and its gradient (lines L1 to L7) cost in the real RAM, which is nothing next to the network. The cost of a training step is dominated by the four sequence log probabilities: two forward passes and one backward pass of over and , and two forward passes of (or none, if the reference log probabilities are cached). For responses of tokens and a cost per token of one pass, that is . RLHF with PPO needs, per step, sampling from the policy token by token, a reward model pass and a value network, so DPO is cheaper per step; the saving in wall-clock time is a measurement that depends on the system. Memory holds the policy, the reference model (unless its log probabilities are cached) and the optimizer state, against four models for PPO (policy, reference, reward and value).
Properties
- No reward model and no sampling (by construction). The loss uses only the four log probabilities of fixed data, so training is supervised learning.
- Same optimum as the RLHF objective (theorem). Under the conditions of Proposition 4, both reach .
- Weighting by error. The weight is large on pairs the implicit reward ranks wrongly and small on pairs it ranks rightly.
- Shift invariance. Adding a function of to the reward does not change or the preferences, so DPO can recover the reward only up to such a term.
- Relative, not absolute. The loss depends on only. It can lower as long as it lowers more.
- Offline. The pairs are fixed. The policy is not evaluated on its own samples during training.
Variants and improvements
- IPO (Azar and colleagues 2024) replaces the logistic loss by a squared loss on the margin, to keep a finite optimum when the preferences in the data are deterministic.
- Several responses. Rafailov and colleagues also give the loss for rankings of more than two responses, under the Plackett-Luce model.
- Iterative or online DPO. Sample new pairs from the current policy, label them, and train again. This brings back part of the sampling of RLHF.
- With LoRA. DPO is often run with low-rank adaptation; then the reference is the base model with the adapter turned off, and no second copy of the weights is needed.
When to use it
Use DPO when you have a fixed set of preference pairs, a reference model after supervised fine-tuning, and you want the KL-regularized objective of RLHF without training a reward model or running PPO. Use RLHF with a reward model when you want to score new samples of the policy during training, to reuse the reward model elsewhere, or to label more data than people can compare. Rafailov and colleagues measured that DPO matched or exceeded PPO-based RLHF on controlled sentiment generation (IMDb with GPT-2-large), summarization (TL;DR with GPT-J) and single-turn dialogue (Anthropic HH with Pythia-2.8B), with GPT-4 as the judge on the last two; these are measurements on their setup.
Pitfalls
- Deterministic preferences. If a pair always has the same winner, the loss has no finite minimizer, and training drives toward 0 for any . The KL term of the objective does not prevent it, because the derivation assumed a finite reward.
- A reference that does not match the data. The derivation assumes is the model the KL is measured against. If the preferred responses are very unlikely under , the log-ratios are large and noisy. Fine-tune the reference on the preferred responses first, as Rafailov and colleagues do when no reference is available.
- Overflow in the loss. computed directly overflows for below about in double precision and much earlier in half precision. Use log_add as in line L4, and the two-branch sigmoid in line L5.
- Per-token means instead of sums. The derivation uses sequence log probabilities, the sums over tokens. Averaging over tokens changes the objective and favors short or long responses.
- Reading as a fixed constant. is a hyperparameter chosen on held out data; Rafailov and colleagues swept values such as 0.05, 0.1, 1 and 5. A smaller lets the policy move further from the reference.
- Expecting the log probability of the preferred response to rise. The loss can fall while both and fall. Watch both, not only the margin.
Implementations
The code takes the four sequence log probabilities of each pair as given and implements the loss and its gradient; it does not train a network and does not load weights. It also has a tabular softmax policy over a few responses of one prompt, used to check the derivation: the tests compare the gradients with central finite differences (, tolerance ), check that no random policy beats , check that gradient descent on the population loss reaches , and check margins of and sequence log probabilities of . It uses log_add from the shared helper nlslog.py.
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/direct-preference-optimization/. The authors are listed in prov/ZDWMJ1.jsonl.
"""Direct preference optimization (DPO): the loss and its gradient.
The input is m preference pairs. For pair i the network gives four sequence
log probabilities (natural log, summed over the tokens of a response):
a_w = log pi_theta(y_w | x) the trained policy on the preferred response
a_l = log pi_theta(y_l | x) the trained policy on the other response
b_w = log pi_ref(y_w | x) the frozen reference policy
b_l = log pi_ref(y_l | x)
With z = beta ((a_w - b_w) - (a_l - b_l)) the loss of the batch is
L = (1 / m) sum_i -log sigmoid(z_i),
and dL/da_w = -beta sigmoid(-z) / m, dL/da_l = +beta sigmoid(-z) / m. The
gradient with respect to the network weights is the chain rule through
a_w and a_l, which the training framework does.
-log sigmoid(z) is computed as log_add(0, -z), so it does not overflow for
large |z|.
The tabular part has one prompt and K responses, a policy pi = softmax(theta)
over them, and a reference pi_ref. It is used to check that the minimizer of
the population DPO loss under Bradley-Terry preferences is
pi_ref exp(r / beta) / Z, the optimum of the KL-regularized objective.
The code takes the four sequence log probabilities as given. It does not
train a network and does not load weights.
"""
import math
from typing import List, Sequence, Tuple
from nlslog import log_add, log_normalize
Pair = Tuple[float, float, float, float] # (a_w, b_w, a_l, b_l)
def sigmoid(z: float) -> float:
"""Return 1 / (1 + exp(-z)) without overflow."""
if z >= 0:
return 1.0 / (1.0 + math.exp(-z))
e = math.exp(z)
return e / (1.0 + e)
def neg_log_sigmoid(z: float) -> float:
"""Return -log sigmoid(z) = log(1 + exp(-z)) = log_add(0, -z)."""
return log_add(0.0, -z)
def implicit_reward(logp: float, logp_ref: float, beta: float) -> float:
"""Return beta (log pi - log pi_ref), the reward that the policy implies up to a term in x."""
return beta * (logp - logp_ref)
def dpo_loss(pairs: Sequence[Pair], beta: float) -> Tuple[float, List[Tuple[float, float]]]:
"""Return (L, grads), where grads[i] = (dL/da_w, dL/da_l) for pair i."""
if beta <= 0:
raise ValueError("beta must be positive")
m = len(pairs)
if m == 0:
raise ValueError("need at least one pair")
total = [] # @line L1
grads = []
for a_w, b_w, a_l, b_l in pairs: # @line L2
z = beta * ((a_w - b_w) - (a_l - b_l)) # @line L3
total.append(neg_log_sigmoid(z)) # @line L4
q = sigmoid(-z) # @line L5
grads.append((-beta * q / m, beta * q / m)) # @line L6
return math.fsum(total) / m, grads # @line L7
def reward_model_loss(r_w: float, r_l: float) -> float:
"""Return the Bradley-Terry loss -log sigmoid(r_w - r_l) of a reward model."""
return neg_log_sigmoid(r_w - r_l)
# ------------------------------------------------------------ tabular policy
def log_policy(theta: Sequence[float]) -> List[float]:
"""Return log softmax(theta)."""
return log_normalize(list(theta))
def optimal_policy(ref: Sequence[float], reward: Sequence[float], beta: float) -> List[float]:
"""Return pi*(y) = pi_ref(y) exp(r(y) / beta) / Z, computed in log space."""
logs = [math.log(p) + r / beta for p, r in zip(ref, reward)]
return [math.exp(v) for v in log_normalize(logs)]
def log_partition(ref: Sequence[float], reward: Sequence[float], beta: float) -> float:
"""Return log Z = log sum_y pi_ref(y) exp(r(y) / beta)."""
logs = [math.log(p) + r / beta for p, r in zip(ref, reward)]
z = logs[0]
for v in logs[1:]:
z = log_add(z, v)
return z
def kl_objective(pi: Sequence[float], ref: Sequence[float], reward: Sequence[float], beta: float) -> float:
"""Return E_pi[r] - beta KL(pi || pi_ref), the objective of RLHF for one prompt."""
er = math.fsum(p * r for p, r in zip(pi, reward))
kl = math.fsum(p * math.log(p / q) for p, q in zip(pi, ref) if p > 0)
return er - beta * kl
def bradley_terry_pairs(reward: Sequence[float]) -> List[Tuple[int, int, float]]:
"""Return (w, l, weight) for every ordered pair: an unordered pair is drawn uniformly,
and w is preferred to l with probability sigmoid(r_w - r_l) (Bradley-Terry)."""
K = len(reward)
n_pairs = K * (K - 1) // 2
out = []
for i in range(K):
for j in range(K):
if i != j:
out.append((i, j, sigmoid(reward[i] - reward[j]) / n_pairs))
return out
def tabular_dpo_loss(theta: Sequence[float], log_ref: Sequence[float], weighted_pairs, beta: float) -> Tuple[float, List[float]]:
"""Return the weighted DPO loss of a softmax policy and its gradient with respect to theta.
weighted_pairs holds (w, l, weight). Since d log pi(y) / d theta_j = [y = j] - pi_j,
the pi_j terms cancel in log pi(w) - log pi(l), and dz/dtheta_j = beta ([w = j] - [l = j]).
"""
lp = log_policy(theta)
terms = []
grad = [0.0] * len(theta)
for w, l, weight in weighted_pairs:
z = beta * ((lp[w] - log_ref[w]) - (lp[l] - log_ref[l]))
terms.append(weight * neg_log_sigmoid(z))
q = sigmoid(-z)
grad[w] -= weight * beta * q
grad[l] += weight * beta * q
return math.fsum(terms), grad
def fit_tabular(log_ref: Sequence[float], weighted_pairs, beta: float, steps: int = 3000, lr: float = 1.0) -> List[float]:
"""Run gradient descent on theta, starting at theta = log_ref. Return pi_theta."""
theta = list(log_ref)
for _ in range(steps):
_, g = tabular_dpo_loss(theta, log_ref, weighted_pairs, beta)
theta = [t - lr * gi for t, gi in zip(theta, g)]
return [math.exp(v) for v in log_policy(theta)]
nlslog.py 152 lines
# SPDX-License-Identifier: MIT
# Shared helper of the natural-language-and-speech pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Log-space arithmetic and semirings for the natural-language-and-speech pages.
Every log is the natural log. A probability of 0 is NEG_INF (float("-inf")),
never a large negative number. A cost is -log p, so a probability of 0 is a
cost of POS_INF.
The semirings are (K, plus, times, zero, one) as on the weighted-automaton page:
PROB probabilities plus = + times = * zero = 0 one = 1
LOG log probabilities plus = log_add times = + zero = -inf one = 0
VITERBI log probabilities plus = max times = + zero = -inf one = 0
TROPICAL costs -log p plus = min times = + zero = +inf one = 0
LOG_COST costs -log p plus = -log_add(-a, -b), times = +, zero = +inf, one = 0
BOOLEAN truth values plus = or times = and zero = False one = True
COUNTING path counts plus = + times = * zero = 0 one = 1
This module holds no algorithm of any page: no forward, Viterbi, CKY, Eisner,
CTC or DTW recursion. The pages build their dynamic programs on top of it.
"""
import math
from dataclasses import dataclass
from typing import Any, Callable, Iterable, List, Sequence
NEG_INF = float("-inf")
POS_INF = float("inf")
def safe_log(p) -> float:
"""Return log p, and NEG_INF for p = 0. Raise ValueError for p < 0."""
if p < 0:
raise ValueError("log of a negative number")
if p == 0:
return NEG_INF
return math.log(p)
def log_add(a: float, b: float) -> float:
"""Return log(exp(a) + exp(b)) = max(a, b) + log(1 + exp(-|a - b|)).
log_add(NEG_INF, NEG_INF) is NEG_INF. No exp of a large number is taken.
"""
if a < b:
a, b = b, a
if b == NEG_INF or a == POS_INF:
return a
return a + math.log1p(math.exp(b - a))
def log_sum(xs: Iterable[float]) -> float:
"""Return log(sum of exp(x)) over xs. An empty input gives NEG_INF."""
xs = list(xs)
if not xs:
return NEG_INF
m = max(xs)
if m == NEG_INF or m == POS_INF:
return m
return m + math.log(math.fsum(math.exp(x - m) for x in xs))
def log_normalize(xs: Sequence[float]) -> List[float]:
"""Return the list x - log_sum(xs): log values whose exps sum to 1.
Raise ValueError if every value is NEG_INF (nothing to normalize).
"""
z = log_sum(xs)
if z == NEG_INF:
raise ValueError("every weight is zero")
return [x - z for x in xs]
def log_softmax(xs: Sequence[float]) -> List[float]:
"""Return log softmax(xs): the logits xs turned into log probabilities."""
return log_normalize(xs)
def softmax(xs: Sequence[float], temperature: float = 1.0) -> List[float]:
"""Return the probabilities exp(x / temperature) / sum, computed stably.
The temperature must be positive. Logits of NEG_INF get probability 0.
"""
if not temperature > 0:
raise ValueError("the temperature must be positive")
m = max(xs)
if m == NEG_INF:
raise ValueError("every logit is -inf")
es = [math.exp((x - m) / temperature) for x in xs]
s = math.fsum(es)
return [e / s for e in es]
def argmax(xs: Sequence[Any]) -> int:
"""Return the first index of a largest value. Raise ValueError if xs is empty."""
if len(xs) == 0:
raise ValueError("argmax of an empty sequence")
best = 0
for i in range(1, len(xs)):
if xs[i] > xs[best]:
best = i
return best
@dataclass(frozen=True)
class Semiring:
"""A semiring (K, plus, times, zero, one). idempotent is True when a plus a = a."""
name: str
plus: Callable[[Any, Any], Any]
times: Callable[[Any, Any], Any]
zero: Any
one: Any
idempotent: bool
def _add(a, b):
return a + b
def _mul(a, b):
return a * b
def _log_add_cost(a: float, b: float) -> float:
return -log_add(-a, -b)
PROB = Semiring("probability", _add, _mul, 0, 1, False)
LOG = Semiring("log", log_add, _add, NEG_INF, 0.0, False)
VITERBI = Semiring("viterbi", max, _add, NEG_INF, 0.0, True)
TROPICAL = Semiring("tropical", min, _add, POS_INF, 0.0, True)
LOG_COST = Semiring("log-cost", _log_add_cost, _add, POS_INF, 0.0, False)
BOOLEAN = Semiring("boolean", lambda a, b: a or b, lambda a, b: a and b, False, True, True)
COUNTING = Semiring("counting", _add, _mul, 0, 1, False)
def sr_sum(sr: Semiring, xs: Iterable[Any]) -> Any:
"""Return the semiring sum of xs, and sr.zero for an empty input."""
acc = sr.zero
for x in xs:
acc = sr.plus(acc, x)
return acc
def sr_prod(sr: Semiring, xs: Iterable[Any]) -> Any:
"""Return the semiring product of xs, and sr.one for an empty input."""
acc = sr.one
for x in xs:
acc = sr.times(acc, x)
return acc
test_direct_preference_optimization.py 187 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/direct-preference-optimization/. The authors are listed in prov/ZDWMJ1.jsonl.
import math
import random
import pytest
from direct_preference_optimization import (bradley_terry_pairs, dpo_loss, fit_tabular, implicit_reward,
kl_objective, log_partition, neg_log_sigmoid, optimal_policy,
reward_model_loss, sigmoid, tabular_dpo_loss)
def test_worked_example():
# beta = 0.1, a_w = -12, b_w = -13, a_l = -15, b_l = -14, so z = 0.2.
loss, grads = dpo_loss([(-12.0, -13.0, -15.0, -14.0)], 0.1)
assert loss == pytest.approx(math.log1p(math.exp(-0.2)), abs=1e-12)
assert loss == pytest.approx(0.598139, abs=1e-6)
gw, gl = grads[0]
assert gw == pytest.approx(-0.0450166, abs=1e-7)
assert gl == pytest.approx(0.0450166, abs=1e-7)
def test_zero_margin_gives_log_2():
loss, grads = dpo_loss([(-5.0, -5.0, -7.0, -7.0)], 0.5)
assert loss == pytest.approx(math.log(2), abs=1e-15)
assert grads[0] == pytest.approx((-0.25, 0.25), abs=1e-15)
def test_loss_is_the_bradley_terry_loss_of_the_implicit_rewards():
rng = random.Random(1)
for _ in range(50):
beta = rng.uniform(0.05, 2.0)
a_w, b_w, a_l, b_l = (rng.uniform(-60, -1) for _ in range(4))
loss, _ = dpo_loss([(a_w, b_w, a_l, b_l)], beta)
r_w = implicit_reward(a_w, b_w, beta)
r_l = implicit_reward(a_l, b_l, beta)
direct = -math.log(1.0 / (1.0 + math.exp(-(r_w - r_l))))
assert loss == pytest.approx(direct, abs=1e-12)
assert reward_model_loss(r_w, r_l) == pytest.approx(direct, abs=1e-12)
def test_gradient_against_finite_differences():
rng = random.Random(2)
beta = 0.7
pairs = [tuple(rng.uniform(-8, -1) for _ in range(4)) for _ in range(5)]
_, grads = dpo_loss(pairs, beta)
h = 1e-6
for i in range(len(pairs)):
for slot, g in ((0, grads[i][0]), (2, grads[i][1])):
up = [list(p) for p in pairs]
dn = [list(p) for p in pairs]
up[i][slot] += h
dn[i][slot] -= h
num = (dpo_loss([tuple(p) for p in up], beta)[0] - dpo_loss([tuple(p) for p in dn], beta)[0]) / (2 * h)
assert num == pytest.approx(g, abs=1e-5)
def test_the_reference_enters_with_the_opposite_sign():
# dL/db_w = -dL/da_w, so the loss depends on a - b only.
base = (-10.0, -11.0, -12.0, -11.5)
l0, _ = dpo_loss([base], 0.3)
shifted = (base[0] + 4.0, base[1] + 4.0, base[2] - 2.0, base[3] - 2.0)
l1, _ = dpo_loss([shifted], 0.3)
assert l0 == pytest.approx(l1, abs=1e-12)
def test_large_margins_are_stable():
# Sequence log probabilities of a few thousand nats and margins of 1000.
loss, grads = dpo_loss([(-2000.0, -3000.0, -3000.0, -2000.0)], 0.5)
assert loss == pytest.approx(0.0, abs=1e-300)
assert grads[0][0] == 0.0 or abs(grads[0][0]) < 1e-300
loss, grads = dpo_loss([(-3000.0, -2000.0, -2000.0, -3000.0)], 0.5)
assert loss == pytest.approx(1000.0, abs=1e-9)
assert grads[0] == pytest.approx((-0.5, 0.5), abs=1e-15)
assert neg_log_sigmoid(-1000.0) == pytest.approx(1000.0, abs=1e-9)
assert sigmoid(-1000.0) == 0.0 and sigmoid(1000.0) == 1.0
def test_wrong_order_gets_a_larger_gradient():
_, g_right = dpo_loss([(-10.0, -12.0, -12.0, -10.0)], 1.0)
_, g_wrong = dpo_loss([(-12.0, -10.0, -10.0, -12.0)], 1.0)
assert abs(g_wrong[0][0]) > abs(g_right[0][0])
assert abs(g_wrong[0][0]) == pytest.approx(sigmoid(4.0), abs=1e-15)
def test_batch_loss_is_the_mean():
pairs = [(-1.0, -2.0, -3.0, -1.0), (-4.0, -4.5, -2.0, -2.2), (-3.0, -3.0, -3.0, -3.0)]
loss, grads = dpo_loss(pairs, 0.2)
singles = [dpo_loss([p], 0.2) for p in pairs]
assert loss == pytest.approx(sum(s[0] for s in singles) / 3, abs=1e-15)
for g, s in zip(grads, singles):
assert g[0] == pytest.approx(s[1][0][0] / 3, abs=1e-15)
def test_bad_arguments():
with pytest.raises(ValueError):
dpo_loss([], 0.1)
with pytest.raises(ValueError):
dpo_loss([(-1.0, -1.0, -1.0, -1.0)], 0.0)
# ------------------------------------------------------------ the derivation
def test_optimal_policy_worked_example():
pi = optimal_policy([0.5, 0.3, 0.2], [0.0, 1.0, 2.0], 1.0)
assert pi == pytest.approx([0.17900, 0.29194, 0.52906], abs=1e-5)
assert sum(pi) == pytest.approx(1.0, abs=1e-15)
value = kl_objective(pi, [0.5, 0.3, 0.2], [0.0, 1.0, 2.0], 1.0)
assert value == pytest.approx(log_partition([0.5, 0.3, 0.2], [0.0, 1.0, 2.0], 1.0), abs=1e-12)
assert value == pytest.approx(1.02722, abs=1e-5)
def test_no_policy_beats_the_closed_form():
rng = random.Random(3)
for _ in range(20):
K = rng.randint(2, 6)
beta = rng.uniform(0.1, 3.0)
ref = [rng.uniform(0.1, 1.0) for _ in range(K)]
s = sum(ref)
ref = [p / s for p in ref]
reward = [rng.uniform(-2, 2) for _ in range(K)]
best = beta * log_partition(ref, reward, beta)
star = optimal_policy(ref, reward, beta)
assert kl_objective(star, ref, reward, beta) == pytest.approx(best, abs=1e-12)
for _ in range(200):
q = [rng.random() + 1e-9 for _ in range(K)]
t = sum(q)
q = [v / t for v in q]
assert kl_objective(q, ref, reward, beta) <= best + 1e-12
def test_reward_shift_by_a_constant_does_not_change_the_optimum():
ref, reward = [0.2, 0.5, 0.3], [1.0, -0.5, 0.25]
a = optimal_policy(ref, reward, 0.4)
b = optimal_policy(ref, [r + 7.0 for r in reward], 0.4)
assert a == pytest.approx(b, abs=1e-12)
def test_reward_is_recovered_from_the_optimal_policy():
# r(y) = beta log(pi*(y) / pi_ref(y)) + beta log Z.
ref, reward, beta = [0.4, 0.4, 0.2], [0.3, -1.0, 2.0], 0.8
star = optimal_policy(ref, reward, beta)
logz = log_partition(ref, reward, beta)
for p, q, r in zip(star, ref, reward):
assert beta * math.log(p / q) + beta * logz == pytest.approx(r, abs=1e-12)
def test_tabular_gradient_against_finite_differences():
rng = random.Random(4)
K, beta = 4, 0.6
theta = [rng.gauss(0, 1) for _ in range(K)]
log_ref = [math.log(p) for p in (0.1, 0.2, 0.3, 0.4)]
pairs = bradley_terry_pairs([0.5, -1.0, 2.0, 0.0])
_, g = tabular_dpo_loss(theta, log_ref, pairs, beta)
h = 1e-6
for j in range(K):
up, dn = list(theta), list(theta)
up[j] += h
dn[j] -= h
num = (tabular_dpo_loss(up, log_ref, pairs, beta)[0] - tabular_dpo_loss(dn, log_ref, pairs, beta)[0]) / (2 * h)
assert num == pytest.approx(g[j], abs=1e-5)
def test_population_dpo_reaches_the_kl_regularized_optimum():
for ref, reward, beta in [([0.5, 0.3, 0.2], [0.0, 1.0, 2.0], 1.0),
([0.25, 0.25, 0.25, 0.25], [1.0, 0.0, -1.0, 0.5], 0.5),
([0.6, 0.3, 0.1], [0.0, 0.5, 3.0], 2.0)]:
log_ref = [math.log(p) for p in ref]
pairs = bradley_terry_pairs(reward)
pi = fit_tabular(log_ref, pairs, beta, steps=4000, lr=2.0)
assert pi == pytest.approx(optimal_policy(ref, reward, beta), abs=1e-6)
def test_deterministic_preferences_push_without_limit():
# If y_0 always wins, the loss keeps falling as pi(y_0) / pi(y_1) grows: no finite minimizer.
log_ref = [math.log(0.5), math.log(0.5)]
pairs = [(0, 1, 1.0)]
losses = []
theta = list(log_ref)
for _ in range(5):
loss, g = tabular_dpo_loss(theta, log_ref, pairs, 0.1)
losses.append(loss)
theta = [t - 50.0 * gi for t, gi in zip(theta, g)]
assert all(b < a for a, b in zip(losses, losses[1:]))
assert theta[0] - theta[1] > 5.0
History
Christiano and colleagues (2017) fitted a reward model to human comparisons with the Bradley-Terry likelihood and trained a policy on it by reinforcement learning. Stiennon and colleagues (2020) and Ouyang and colleagues (2022) applied the same pipeline to language models with PPO and a KL penalty to a reference model. That the optimum of a KL-regularized reward objective is was known from earlier work on KL-controlled and maximum entropy reinforcement learning. Rafailov, Sharma, Mitchell, Ermon, Manning and Finn (2023) used that closed form to write the reward in terms of the policy, observed that cancels in the Bradley-Terry likelihood, and so turned the whole pipeline into one classification loss. Azar and colleagues (2024) analyzed where the derivation breaks with deterministic preferences.
References
- Rafael Rafailov, Archit Sharma, Eric Mitchell, Stefano Ermon, Christopher D. Manning and Chelsea Finn, Direct preference optimization: Your language model is secretly a reward model, NeurIPS 2023, Section 4 (equations 4 to 7: the optimal policy, the reward in terms of the policy, the Bradley-Terry model in terms of the policy, the DPO loss, and the gradient), Appendix A.1 (the optimum of the KL-constrained objective), Appendix A.4 (the gradient), Section 5.1 (Lemmas 1 and 2, Theorem 1), Section 6 (the experiments)
- Bradley and Terry 1952, the paired comparison model, with the probability that i beats j proportional to the ratio of their strengths
- Long Ouyang, Jeff Wu, Xu Jiang and others, Training language models to follow instructions with human feedback, NeurIPS 2022, Section 3.5 (the reward model loss and the KL-penalized objective that DPO targets)
- Mohammad Gheshlaghi Azar, Mark Rowland, Bilal Piot, Daniel Guo, Daniele Calandriello, Michal Valko and Remi Munos, A general theoretical paradigm to understand learning from human preferences, AISTATS 2024, the analysis of DPO with deterministic preferences and the IPO loss
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag ZDWMJ1 Edit this page History Report an error Markdown