DPO Derivation › Deriving the Optimal Policy

Michael BrenndoerferJanuary 1, 20269 min read
Language AI HandbookAll chapters
Part 37 of 67Alignment and RLHF
Chapter 283DPO Derivation › Deriving the Optimal Policy
Reading section 3 of 12 · Deriving the Optimal Policy · 9 minSection 3 of 12 · 9 min

Book contents

Section 3 of 12 · 9 min read

DPO Derivation › Deriving the Optimal PolicyOne section · Sections in this chapter3 / 12 ↓
Reading tools Definitions & inline links

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

The key insight behind DPO is that this optimization problem has a closed-form solution. Unlike many optimization problems in machine learning that require iterative gradient descent, this particular formulation admits an analytical answer. For a fixed prompt xx, we're optimizing over the distribution π(y∣x)\pi(y|x) for all possible responses yy. This is a constrained optimization problem over probability distributions: we must ensure our solution is a valid probability distribution that sums to one and assigns non-negative probability to every possible response.

The special structure of the RLHF objective allows for this closed-form solution. The expectation under π\pi combined with the KL divergence creates what's known as a variational problem over distributions. Such problems often have elegant solutions when the constraints are simple probability simplex constraints.

Let's work through the derivation step by step. For a single prompt xx, the objective is:

max⁡π(⋅∣x)∑yπ(y∣x)[r(x,y)−βlog⁡π(y∣x)πref(y∣x)]\max_{\pi(\cdot|x)} \sum_{y} \pi(y|x) \left[ r(x, y) - \beta \log \frac{\pi(y|x)}{\pi_{\text{ref}}(y|x)} \right]

where:

  • ∑y\sum_{y}: sum over all possible responses in the vocabulary
  • π(⋅∣x)\pi(\cdot|x): the entire probability distribution over responses for prompt xx
  • π(y∣x)\pi(y|x): probability of response yy given prompt xx
  • r(x,y)r(x, y): the reward function
  • β\beta: the KL penalty coefficient
  • log⁡\log: the natural logarithm
  • πref(y∣x)\pi_{\text{ref}}(y|x): the reference policy probability

We need to maximize this subject to the constraint that π(⋅∣x)\pi(\cdot|x) is a valid probability distribution: ∑yπ(y∣x)=1\sum_y \pi(y|x) = 1 and π(y∣x)≥0\pi(y|x) \geq 0 for all yy.

To solve this constrained optimization problem, we use the method of Lagrange multipliers, a classical technique from calculus. The idea is to incorporate the constraint directly into the objective by introducing a new variable (the Lagrange multiplier) that penalizes violations of the constraint. At the optimal solution, the gradient of the objective with respect to the decision variables must be proportional to the gradient of the constraint.

The Lagrangian is:

L=∑yπ(y∣x)[r(x,y)−βlog⁡π(y∣x)+βlog⁡πref(y∣x)]+λ(1−∑yπ(y∣x))\mathcal{L} = \sum_{y} \pi(y|x) \left[ r(x, y) - \beta \log \pi(y|x) + \beta \log \pi_{\text{ref}}(y|x) \right] + \lambda \left( 1 - \sum_y \pi(y|x) \right)

where:

  • L\mathcal{L}: the Lagrangian function
  • ∑y\sum_{y}: sum over all responses
  • π(y∣x)\pi(y|x): probability of response yy
  • r(x,y)r(x, y): the reward function
  • β\beta: the KL penalty coefficient
  • log⁡\log: the natural logarithm
  • πref(y∣x)\pi_{\text{ref}}(y|x): the reference policy probability
  • λ\lambda: the Lagrange multiplier for the constraint that probabilities sum to 1

Notice that we've expanded the log ratio term from the original objective, separating it into −βlog⁡π(y∣x)-\beta \log \pi(y|x) and +βlog⁡πref(y∣x)+\beta \log \pi_{\text{ref}}(y|x). This separation makes taking derivatives more straightforward. The term λ(1−∑yπ(y∣x))\lambda(1 - \sum_y \pi(y|x)) enforces our normalization constraint: if the probabilities don't sum to one, this term will be nonzero, and the Lagrange multiplier λ\lambda will adjust to push us toward a valid distribution.

Taking the derivative with respect to π(y∣x)\pi(y|x) for a specific yy:

∂L∂π(y∣x)=r(x,y)−βlog⁡π(y∣x)−β+βlog⁡πref(y∣x)−λ=0\frac{\partial \mathcal{L}}{\partial \pi(y|x)} = r(x, y) - \beta \log \pi(y|x) - \beta + \beta \log \pi_{\text{ref}}(y|x) - \lambda = 0

where:

  • ∂L∂π(y∣x)\frac{\partial \mathcal{L}}{\partial \pi(y|x)}: the partial derivative of the Lagrangian with respect to the probability of response yy
  • r(x,y)r(x, y): the reward function
  • β\beta: the KL penalty coefficient
  • log⁡\log: the natural logarithm
  • π(y∣x)\pi(y|x): the policy probability
  • πref(y∣x)\pi_{\text{ref}}(y|x): the reference policy probability
  • λ\lambda: the Lagrange multiplier

The −β-\beta term comes from differentiating πlog⁡π\pi \log \pi, which gives log⁡π+1\log \pi + 1. This is a standard result from calculus: when we differentiate πlog⁡π\pi \log \pi with respect to π\pi, we apply the product rule, obtaining log⁡π+π⋅(1/π)=log⁡π+1\log \pi + \pi \cdot (1/\pi) = \log \pi + 1. Setting this derivative equal to zero gives us the first-order optimality conditions.

Solving for log⁡π(y∣x)\log \pi(y|x):

βlog⁡π(y∣x)=r(x,y)+βlog⁡πref(y∣x)−β−λlog⁡π(y∣x)=1βr(x,y)+log⁡πref(y∣x)−1−λβ\begin{aligned} \beta \log \pi(y|x) &= r(x, y) + \beta \log \pi_{\text{ref}}(y|x) - \beta - \lambda \\ \log \pi(y|x) &= \frac{1}{\beta} r(x, y) + \log \pi_{\text{ref}}(y|x) - 1 - \frac{\lambda}{\beta} \end{aligned}

where:

  • log⁡π(y∣x)\log \pi(y|x): the log-probability of response yy
  • r(x,y)r(x, y): the reward function
  • β\beta: the KL penalty coefficient
  • πref(y∣x)\pi_{\text{ref}}(y|x): the reference policy probability
  • λ/β\lambda/\beta: constant terms related to the normalization constraint

This expression for the log-probability has an illuminating structure. The log-probability under our optimal policy equals the log-probability under the reference, adjusted by the scaled reward r(x,y)/βr(x,y)/\beta, plus some constants that don't depend on yy. Higher reward responses get higher log-probabilities, with β\beta controlling how much the reward matters relative to staying close to the reference.

Exponentiating both sides:

π(y∣x)=πref(y∣x)⋅exp⁡(r(x,y)β)⋅exp⁡(−1−λβ)\pi(y|x) = \pi_{\text{ref}}(y|x) \cdot \exp\left( \frac{r(x, y)}{\beta} \right) \cdot \exp\left( -1 - \frac{\lambda}{\beta} \right)

where:

  • π(y∣x)\pi(y|x): the policy probability
  • πref(y∣x)\pi_{\text{ref}}(y|x): the reference policy probability
  • exp⁡(⋅)\exp(\cdot): the exponential function
  • exp⁡(r(x,y)/β)\exp(r(x, y)/\beta): the reward-scaling term
  • r(x,y)r(x, y): the reward function
  • β\beta: the KL penalty coefficient
  • exp⁡(−1−λ/β)\exp(-1 - \lambda/\beta): the normalization term constant across all yy

The term exp⁡(−1−λ/β)\exp(-1 - \lambda/\beta) is just a normalizing constant that ensures the distribution sums to 1. This term doesn't depend on yy; it only depends on xx through the constraint that all probabilities must sum to one. We can absorb it into a partition function Z(x)Z(x):

π∗(y∣x)=1Z(x)πref(y∣x)exp⁡(r(x,y)β)\pi^*(y|x) = \frac{1}{Z(x)} \pi_{\text{ref}}(y|x) \exp\left( \frac{r(x, y)}{\beta} \right)

where:

  • π∗(y∣x)\pi^*(y|x): the optimal policy distribution
  • Z(x)=∑y′πref(y′∣x)exp⁡(r(x,y′)β)Z(x) = \sum_{y'} \pi_{\text{ref}}(y'|x) \exp\left( \frac{r(x, y')}{\beta} \right): the partition function (normalizing constant) for prompt xx
  • πref(y∣x)\pi_{\text{ref}}(y|x): the reference policy distribution
  • r(x,y)r(x, y): the reward function
  • β\beta: the temperature parameter

This is the optimal policy for the RLHF objective. It has a clear interpretation: the optimal policy takes the reference distribution and reweights each response by the exponentiated reward, then normalizes. The exponential function ensures all probabilities are positive, naturally satisfying the π(y∣x)≥0\pi(y|x) \ge 0 constraint. Responses with higher reward get exponentially more probability mass, with β\beta controlling how aggressively we reweight.

Consider what happens at extreme values of beta to see how this reweighting works. When β\beta is very large, the reward term r(x,y)/βr(x,y)/\beta becomes small, and exp⁡(r(x,y)/β)≈1\exp(r(x,y)/\beta) \approx 1 for all responses. In this limit, the optimal policy stays very close to the reference distribution, barely adjusting for reward at all. Conversely, when β\beta is very small, the exponential amplifies small reward differences into massive probability shifts, putting all probability mass on the highest-reward response. The choice of β\beta therefore controls the exploration-exploitation trade-off: larger values favor staying close to the reference (exploration), while smaller values favor chasing high reward (exploitation).

Out[3]:
Visualization
Bar chart for beta=0.2 showing reference and optimal policy distributions, with optimal distribution heavily concentrated on the highest-reward response D.
Reference vs optimal policy distribution for $\beta = 0.2$. Low temperature concentrates probability heavily on the highest-reward response (D).
Bar chart for beta=0.5 showing reference and optimal policy distributions with moderate concentration on the highest-reward response D.
Reference vs optimal policy distribution for $\beta = 0.5$. Moderate-low temperature still noticeably shifts mass toward high-reward responses.
Bar chart for beta=1.0 showing reference and optimal policy distributions with balanced reweighting toward higher-reward responses.
Reference vs optimal policy distribution for $\beta = 1.0$. Moderate temperature produces a balanced reweighting of the reference distribution.
Bar chart for beta=2.0 showing reference and optimal policy distributions nearly identical, preserving the reference distribution.
Reference vs optimal policy distribution for $\beta = 2.0$. High temperature preserves the shape of the reference distribution closely.
Boltzmann Distribution

The optimal policy has the form of a Boltzmann (or Gibbs) distribution from statistical mechanics, where r(x,y)r(x,y) plays the role of negative energy and β\beta plays the role of temperature. Lower temperature (smaller β\beta) concentrates probability on the highest-reward responses.

The Partition Function Problem

Before moving on, we should acknowledge a serious computational obstacle lurking in the optimal policy formula. The partition function Z(x)Z(x) is defined as:

Z(x)=∑y′πref(y′∣x)exp⁡(r(x,y′)β)Z(x) = \sum_{y'} \pi_{\text{ref}}(y'|x) \exp\left( \frac{r(x, y')}{\beta} \right)

where the sum ranges over all possible responses y′y'. For a language model, "all possible responses" means all sequences of tokens up to some maximum length. The number of such sequences is astronomical: a modest vocabulary of 32,000 tokens with a maximum length of 200 tokens gives 3200020032000^{200} possible responses, a number larger than the estimated number of atoms in the observable universe. Computing Z(x)Z(x) directly is completely intractable.

This intractability is precisely why naive approaches to optimizing the RLHF objective are so expensive. Algorithms like PPO work around it by using sample-based estimates and importance weighting, but those approaches have their own difficulties, including high variance and sensitivity to hyperparameters. The DPO derivation sidesteps this problem entirely, and the key step is coming up next in the reparameterization.