Algorithm Search⌘K

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
Properties
deterministicexactofflineiterative
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 β\beta 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 −log⁡σ(β((log⁡πθ(yw)−log⁡πref(yw))−(log⁡πθ(yl)−log⁡πref(yl))))-\log \sigma(\beta ((\log \pi_\theta(y_w) - \log \pi_{\text{ref}}(y_w)) - (\log \pi_\theta(y_l) - \log \pi_{\text{ref}}(y_l)))), 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 (x,yw,yl)(x, y_w, y_l): a prompt xx, a preferred response ywy_w and a dispreferred response yly_l. There is a reference policy πref\pi_{\text{ref}}, usually the model after supervised fine-tuning, which stays frozen. A policy assigns a sequence log probability log⁡π(y∣x)=∑t=1nlog⁡π(yt∣x,y1:t−1)\log \pi(y \mid x) = \sum_{t=1}^{n} \log \pi(y_t \mid x, y_{1:t-1}) to a response of nn tokens, by causal language modeling. The goal is the policy that maximizes the RLHF objective

max⁡π  Ex[Ey∼π(⋅∣x)[r(x,y)]−β KL(π(⋅∣x) ∥ πref(⋅∣x))]\max_{\pi}\; \mathbb{E}_{x}\Big[ \mathbb{E}_{y \sim \pi(\cdot \mid x)} [r(x, y)] - \beta\, \mathrm{KL}\big(\pi(\cdot \mid x) \,\|\, \pi_{\text{ref}}(\cdot \mid x)\big) \Big]

for a reward rr that is never observed. What is observed are the preferences, which are assumed to follow the Bradley-Terry model p(yw≻yl∣x)=σ(r(x,yw)−r(x,yl))p(y_w \succ y_l \mid x) = \sigma(r(x, y_w) - r(x, y_l)) with σ(z)=1/(1+e−z)\sigma(z) = 1 / (1 + e^{-z}). 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.

  1. For a fixed reward, the objective has the unique optimum π∗(y∣x)=πref(y∣x) er(x,y)/β/Z(x)\pi^*(y \mid x) = \pi_{\text{ref}}(y \mid x)\, e^{r(x, y)/\beta} / Z(x), with Z(x)=∑yπref(y∣x) er(x,y)/βZ(x) = \sum_y \pi_{\text{ref}}(y \mid x)\, e^{r(x, y)/\beta}.
  2. Solving for the reward gives r(x,y)=βlog⁡(π∗(y∣x)/πref(y∣x))+βlog⁡Z(x)r(x, y) = \beta \log (\pi^*(y \mid x) / \pi_{\text{ref}}(y \mid x)) + \beta \log Z(x).
  3. In the Bradley-Terry probability only the difference of two rewards for the same xx appears, so βlog⁡Z(x)\beta \log Z(x) cancels, and the preference probability is a function of the policy alone.

Replace π∗\pi^* by the trained policy πθ\pi_\theta and maximize the likelihood of the data. That gives the loss

L(θ)=−E(x,yw,yl)log⁡σ ⁣(βlog⁡πθ(yw∣x)πref(yw∣x)−βlog⁡πθ(yl∣x)πref(yl∣x)).L(\theta) = -\mathbb{E}_{(x, y_w, y_l)} \log \sigma\!\left( \beta \log \frac{\pi_\theta(y_w \mid x)}{\pi_{\text{ref}}(y_w \mid x)} - \beta \log \frac{\pi_\theta(y_l \mid x)}{\pi_{\text{ref}}(y_l \mid x)} \right).

The quantity r^(x,y)=βlog⁡(πθ(y∣x)/πref(y∣x))\hat r(x, y) = \beta \log (\pi_\theta(y \mid x) / \pi_{\text{ref}}(y \mid x)) is the implicit reward of the policy, and LL is the Bradley-Terry loss of that reward.

The algorithm

For each pair the network computes four sequence log probabilities: aw=log⁡πθ(yw∣x)a_w = \log \pi_\theta(y_w \mid x) and al=log⁡πθ(yl∣x)a_l = \log \pi_\theta(y_l \mid x) with gradients, and bwb_w, blb_l under πref\pi_{\text{ref}} 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 mm pairs and its gradient with respect to awa_w and ala_l. The training framework multiplies these by ∇θaw\nabla_\theta a_w and ∇θal\nabla_\theta a_l (backpropagation) and takes an optimizer step.

  1. DPO-LOSS(β, P) ▷ P: m tuples (a_w, b_w, a_l, b_l)
  2. 1total ← 0
  3. 2for each (a_w, b_w, a_l, b_l) in P do
  4. 3z ← β ((a_w - b_w) - (a_l - b_l)) ▷ implicit reward margin
  5. 4total ← total + log_add(0, -z) ▷ -log σ(z), no overflow
  6. 5q ← σ(-z) ▷ in [0, 1], computed stably
  7. 6∂L/∂a_w ← -β q / m; ∂L/∂a_l ← β q / m
  8. 7return total / m and the gradients

Here log_add(a,b)=max⁡(a,b)+log⁡(1+e−∣a−b∣)(a, b) = \max(a, b) + \log(1 + e^{-|a - b|}), from the log-sum-exp trick.

Example

Take β=0.1\beta = 0.1 and a batch of two pairs.

pair awa_w bwb_w ala_l blb_l L3 zz L4 −log⁡σ(z)-\log \sigma(z) L5 q=σ(−z)q = \sigma(-z) L6 ∂L/∂aw\partial L / \partial a_w
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 (0.598139+0.854355)/2=0.726247(0.598139 + 0.854355) / 2 = 0.726247. In pair 1 the policy already gives the preferred response a higher log-ratio than the rejected one (implicit rewards 0.10.1 and −0.1-0.1), so z>0z > 0 and the weight qq is below one half. In pair 2 the order is wrong (r^w=−0.2\hat r_w = -0.2, r^l=0.1\hat r_l = 0.1), so z<0z < 0 and the pair gets the larger weight. Each ∂L/∂al\partial L / \partial a_l is the negative of ∂L/∂aw\partial L / \partial a_w. Pair 2 shows that awa_w can be lower than ala_l 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 πref=(0.5,0.3,0.2)\pi_{\text{ref}} = (0.5, 0.3, 0.2), rewards r=(0,1,2)r = (0, 1, 2) and β=1\beta = 1, step 1 gives Z=0.5+0.3e+0.2e2=2.793296Z = 0.5 + 0.3 e + 0.2 e^2 = 2.793296 and π∗=(0.17900,0.29194,0.52906)\pi^* = (0.17900, 0.29194, 0.52906). The expected reward rises from 0.7 under πref\pi_{\text{ref}} to 1.35006, at a KL cost of 0.32283 nats, and the objective is βlog⁡Z=1.02722\beta \log Z = 1.02722. A smaller β\beta moves further: β=0.5\beta = 0.5 gives π∗=(0.03667,0.16256,0.80077)\pi^* = (0.03667, 0.16256, 0.80077) and β=2\beta = 2 gives (0.32504,0.32154,0.35342)(0.32504, 0.32154, 0.35342). 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 π∗\pi^* within 10−610^{-6}.

Correctness

proofs/correctness.md has the full proofs. The objective equals βlog⁡Z(x)−β KL(π ∥ π∗)\beta \log Z(x) - \beta\, \mathrm{KL}(\pi \,\|\, \pi^*), so Gibbs' inequality makes π∗\pi^* the unique optimum (Theorem 1, the result of Appendix A.1 of Rafailov and colleagues). The reward is βlog⁡(π∗/πref)\beta \log(\pi^* / \pi_{\text{ref}}) plus a term in xx 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 π∗\pi^*, the population loss is minimized exactly at π∗\pi^* (Proposition 4). For lines L5 and L6: ddz(−log⁡σ(z))=−σ(−z)\frac{d}{dz}(-\log \sigma(z)) = -\sigma(-z), and zz has slope β\beta in awa_w and −β-\beta in ala_l.

These are statements about the population optimum. A finite data set, a network that cannot express π∗\pi^*, 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 xx and drop it from the notation where it is fixed. Y\mathcal{Y} is the set of responses, which we take finite (for sequences of bounded length over a finite vocabulary VV it is). The reference policy πref\pi_{\text{ref}} is a distribution on Y\mathcal{Y} with πref(y)>0\pi_{\text{ref}}(y) > 0 for every yy, the reward r:Y→Rr : \mathcal{Y} \to \mathbb{R} is a function, and β>0\beta > 0. All logs are natural logs. σ(z)=1/(1+e−z)\sigma(z) = 1 / (1 + e^{-z}).

Theorem 1: the optimum of the KL-regularized objective

Let

J(π)=∑yπ(y)r(y)−β KL(π ∥ πref),KL(π ∥ πref)=∑yπ(y)log⁡π(y)πref(y),J(\pi) = \sum_{y} \pi(y) r(y) - \beta\, \mathrm{KL}(\pi \,\|\, \pi_{\text{ref}}), \qquad \mathrm{KL}(\pi \,\|\, \pi_{\text{ref}}) = \sum_{y} \pi(y) \log \frac{\pi(y)}{\pi_{\text{ref}}(y)},

over all distributions π\pi on Y\mathcal{Y}, with 0log⁡0=00 \log 0 = 0. Put

Z=∑yπref(y) er(y)/β,π∗(y)=πref(y) er(y)/βZ.Z = \sum_{y} \pi_{\text{ref}}(y)\, e^{r(y) / \beta}, \qquad \pi^*(y) = \frac{\pi_{\text{ref}}(y)\, e^{r(y)/\beta}}{Z}.

Then J(π)=βlog⁡Z−β KL(π ∥ π∗)J(\pi) = \beta \log Z - \beta\, \mathrm{KL}(\pi \,\|\, \pi^*) for every π\pi. Hence π∗\pi^* is the unique maximizer, and the maximum is βlog⁡Z\beta \log Z.

Proof. π∗\pi^* is a distribution with π∗(y)>0\pi^*(y) > 0 for every yy, so KL(π ∥ π∗)\mathrm{KL}(\pi \,\|\, \pi^*) is finite. From the definition, log⁡π∗(y)=log⁡πref(y)+r(y)/β−log⁡Z\log \pi^*(y) = \log \pi_{\text{ref}}(y) + r(y) / \beta - \log Z. So

KL(π ∥ π∗)=∑yπ(y)(log⁡π(y)πref(y)−r(y)β+log⁡Z)=KL(π ∥ πref)−1β∑yπ(y)r(y)+log⁡Z,\mathrm{KL}(\pi \,\|\, \pi^*) = \sum_y \pi(y) \left( \log \frac{\pi(y)}{\pi_{\text{ref}}(y)} - \frac{r(y)}{\beta} + \log Z \right) = \mathrm{KL}(\pi \,\|\, \pi_{\text{ref}}) - \frac{1}{\beta} \sum_y \pi(y) r(y) + \log Z,

where we used ∑yπ(y)=1\sum_y \pi(y) = 1. Multiply by −β-\beta and rearrange: J(π)=βlog⁡Z−β KL(π ∥ π∗)J(\pi) = \beta \log Z - \beta\, \mathrm{KL}(\pi \,\|\, \pi^*). By Gibbs' inequality (Kullback-Leibler divergence), KL(π ∥ π∗)≥0\mathrm{KL}(\pi \,\|\, \pi^*) \ge 0 with equality only when π=π∗\pi = \pi^*. So J(π)≤βlog⁡ZJ(\pi) \le \beta \log Z, with equality only at π∗\pi^*. □\square

The objective of the page averages JJ over prompts xx drawn from a fixed distribution. The policy for each xx can be chosen apart from the others, so the optimum is π∗(⋅∣x)\pi^*(\cdot \mid x) for every xx, with its own Z(x)Z(x).

Corollary 2: the reward in terms of the optimal policy

Take logs in the definition of π∗\pi^* and solve for rr:

r(x,y)=βlog⁡π∗(y∣x)πref(y∣x)+βlog⁡Z(x).r(x, y) = \beta \log \frac{\pi^*(y \mid x)}{\pi_{\text{ref}}(y \mid x)} + \beta \log Z(x).

So the reward is determined by the optimal policy up to the term βlog⁡Z(x)\beta \log Z(x), which depends on the prompt and not on the response. Conversely, if two rewards differ by a function of xx only, r′(x,y)=r(x,y)+f(x)r'(x, y) = r(x, y) + f(x), then Z′(x)=Z(x)ef(x)/βZ'(x) = Z(x) e^{f(x)/\beta} and the two give the same π∗\pi^*. 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 f(x)f(x) cancels in the difference r′(x,yw)−r′(x,yl)r'(x, y_w) - r'(x, y_l).

Proposition 3: the Bradley-Terry likelihood in terms of the policy

The Bradley-Terry model says that ywy_w is preferred to yly_l for the prompt xx with probability σ(r(x,yw)−r(x,yl))\sigma(r(x, y_w) - r(x, y_l)). Substitute Corollary 2 into the difference. The term βlog⁡Z(x)\beta \log Z(x) appears in both rewards and cancels:

p(yw≻yl∣x)=σ ⁣(βlog⁡π∗(yw∣x)πref(yw∣x)−βlog⁡π∗(yl∣x)πref(yl∣x)).p(y_w \succ y_l \mid x) = \sigma\!\left( \beta \log \frac{\pi^*(y_w \mid x)}{\pi_{\text{ref}}(y_w \mid x)} - \beta \log \frac{\pi^*(y_l \mid x)}{\pi_{\text{ref}}(y_l \mid x)} \right).

So the preference probabilities can be written with the policy alone, without ZZ, which would need a sum over all responses. DPO replaces π∗\pi^* by the trained policy πθ\pi_\theta and maximizes the log likelihood of the observed preferences. With a=log⁡πθa = \log \pi_\theta, b=log⁡πrefb = \log \pi_{\text{ref}} and z=β((aw−bw)−(al−bl))z = \beta ((a_w - b_w) - (a_l - b_l)), the negative log likelihood of one pair is −log⁡σ(z)-\log \sigma(z), which is the loss of line L4. It equals the Bradley-Terry loss −log⁡σ(r^w−r^l)-\log \sigma(\hat r_w - \hat r_l) of the reward model r^(x,y)=βlog⁡(πθ(y∣x)/πref(y∣x))\hat r(x, y) = \beta \log (\pi_\theta(y \mid x) / \pi_{\text{ref}}(y \mid x)), the implicit reward.

Proposition 4: the population minimizer is the optimal policy

Fix a prompt. Suppose that each unordered pair {y,y′}\{y, y'\} of responses is compared with probability μ({y,y′})>0\mu(\{y, y'\}) > 0, and that the label follows the Bradley-Terry model with the true reward rr. Suppose that the policy is a softmax over Y\mathcal{Y} with free logits, so every positive distribution is reachable. Then the expected DPO loss is minimized exactly by πθ=π∗\pi_\theta = \pi^*.

Proof. For the pair {y,y′}\{y, y'\} let p=σ(r(y)−r(y′))p = \sigma(r(y) - r(y')) and z=β((log⁡πθ(y)−log⁡πref(y))−(log⁡πθ(y′)−log⁡πref(y′)))z = \beta ((\log \pi_\theta(y) - \log \pi_{\text{ref}}(y)) - (\log \pi_\theta(y') - \log \pi_{\text{ref}}(y'))). The expected loss of the pair is −plog⁡σ(z)−(1−p)log⁡σ(−z)-p \log \sigma(z) - (1 - p) \log \sigma(-z), using 1−σ(z)=σ(−z)1 - \sigma(z) = \sigma(-z). This is the cross-entropy between the Bernoulli distributions with means pp and σ(z)\sigma(z). It equals the entropy of the first plus their Kullback-Leibler divergence, so it is minimized exactly when σ(z)=p\sigma(z) = p, that is z=r(y)−r(y′)z = r(y) - r(y'), because σ\sigma is strictly increasing. At πθ=π∗\pi_\theta = \pi^*, Corollary 2 gives z=r(y)−r(y′)z = r(y) - r(y') for every pair, so every term is at its minimum, and so is the weighted sum. Conversely, at a minimizer every pair with μ>0\mu > 0 has z=r(y)−r(y′)z = r(y) - r(y'); since every pair is compared, βlog⁡(πθ(y)/πref(y))−r(y)\beta \log (\pi_\theta(y) / \pi_{\text{ref}}(y)) - r(y) is the same constant cc for all yy, so πθ(y)∝πref(y)er(y)/β\pi_\theta(y) \propto \pi_{\text{ref}}(y) e^{r(y)/\beta}, which is π∗\pi^*. □\square

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 f(z)=−log⁡σ(z)=log⁡(1+e−z)f(z) = -\log \sigma(z) = \log(1 + e^{-z}). Then f′(z)=−e−z/(1+e−z)=−σ(−z)f'(z) = -e^{-z} / (1 + e^{-z}) = -\sigma(-z). For a batch of mm pairs the loss is L=1m∑if(zi)L = \frac{1}{m} \sum_i f(z_i), and ziz_i depends on aw,ia_{w,i} with slope β\beta and on al,ia_{l,i} with slope −β-\beta. By the chain rule

∂L∂aw,i=−βmσ(−zi),∂L∂al,i=+βmσ(−zi),\frac{\partial L}{\partial a_{w,i}} = -\frac{\beta}{m} \sigma(-z_i), \qquad \frac{\partial L}{\partial a_{l,i}} = +\frac{\beta}{m} \sigma(-z_i),

which are lines L5 and L6. The reference log probabilities enter with the opposite signs. For a network with weights θ\theta, the gradient is

∇θL=−βm∑iσ(−zi)(∇θlog⁡πθ(yw,i∣xi)−∇θlog⁡πθ(yl,i∣xi)),\nabla_\theta L = -\frac{\beta}{m} \sum_i \sigma(-z_i) \left( \nabla_\theta \log \pi_\theta(y_{w,i} \mid x_i) - \nabla_\theta \log \pi_\theta(y_{l,i} \mid x_i) \right),

and σ(−zi)=σ(r^l,i−r^w,i)\sigma(-z_i) = \sigma(\hat r_{l,i} - \hat r_{w,i}) is large when the implicit reward ranks the pair in the wrong order. For the tabular softmax policy of the code, log⁡πθ(y)=θy−log⁡∑y′eθy′\log \pi_\theta(y) = \theta_y - \log \sum_{y'} e^{\theta_{y'}}, so the normalizer cancels in log⁡πθ(yw)−log⁡πθ(yl)=θyw−θyl\log \pi_\theta(y_w) - \log \pi_\theta(y_l) = \theta_{y_w} - \theta_{y_l}, and ∂z/∂θj=β([j=yw]−[j=yl])\partial z / \partial \theta_j = \beta ([j = y_w] - [j = y_l]).

Proposition 6: the loss is computed without overflow

f(z)=log⁡(1+e−z)=log⁡(e0+e−z)f(z) = \log(1 + e^{-z}) = \log(e^{0} + e^{-z}), which is log_add(0,−z)\text{log\_add}(0, -z). log_add takes the exponential of a non-positive number only, so it does not overflow for any finite zz: for z=−1000z = -1000 it returns 1000+log⁡(1+e−1000)=10001000 + \log(1 + e^{-1000}) = 1000, and for z=1000z = 1000 it returns log⁡(1+e−1000)\log(1 + e^{-1000}), which rounds to 00. The function sigmoid of the code takes e−ze^{-z} for z≥0z \ge 0 and eze^{z} for z<0z < 0, 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 p=1p = 1 in Proposition 4, the pair loss −log⁡σ(z)-\log \sigma(z) decreases in zz and has no finite minimizer. The population minimizer then puts πθ(yl)/πθ(yw)→0\pi_\theta(y_l) / \pi_\theta(y_w) \to 0 for any β\beta: 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 Θ(m)\Theta(m) 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 πθ\pi_\theta over ywy_w and yly_l, and two forward passes of πref\pi_{\text{ref}} (or none, if the reference log probabilities are cached). For responses of nn tokens and a cost cc per token of one pass, that is Θ(mnc)\Theta(m n c). 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 π∗\pi^*.
  • Weighting by error. The weight σ(−z)=σ(r^l−r^w)\sigma(-z) = \sigma(\hat r_l - \hat r_w) is large on pairs the implicit reward ranks wrongly and small on pairs it ranks rightly.
  • Shift invariance. Adding a function of xx to the reward does not change π∗\pi^* or the preferences, so DPO can recover the reward only up to such a term.
  • Relative, not absolute. The loss depends on aw−al−(bw−bl)a_w - a_l - (b_w - b_l) only. It can lower log⁡πθ(yw)\log \pi_\theta(y_w) as long as it lowers log⁡πθ(yl)\log \pi_\theta(y_l) 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 πθ(yl)\pi_\theta(y_l) toward 0 for any β\beta. 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 πref\pi_{\text{ref}} is the model the KL is measured against. If the preferred responses are very unlikely under πref\pi_{\text{ref}}, 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. log⁡(1+e−z)\log(1 + e^{-z}) computed directly overflows for zz below about −709-709 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 β\beta as a fixed constant. β\beta is a hyperparameter chosen on held out data; Rafailov and colleagues swept values such as 0.05, 0.1, 1 and 5. A smaller β\beta lets the policy move further from the reference.
  • Expecting the log probability of the preferred response to rise. The loss can fall while both awa_w and ala_l 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 (h=10−6h = 10^{-6}, tolerance 10−510^{-5}), check that no random policy beats βlog⁡Z\beta \log Z, check that gradient descent on the population loss reaches π∗\pi^*, and check margins of ±1000\pm 1000 and sequence log probabilities of −3000-3000. 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.

direct_preference_optimization.pyI0RawGitHub
# 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 πrefer/β/Z\pi_{\text{ref}} e^{r/\beta} / Z 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 ZZ 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

  1. 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)
  2. Bradley and Terry 1952, the paired comparison model, with the probability that i beats j proportional to the ratio of their strengths
  3. 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)
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example