How the KL-regularized RLHF objective collapses into a classification loss on log-probability ratios, how to implement it without silent bugs, the family of variants it spawned, and what is lost when you never sample from your own model.
Chapter 17 · Section 17.1 · 60 min

The closed-form optimal policy

Chapter 16 trained a language model to maximize a learned reward while staying close to the model it started from. The machinery was heavy. Four networks sat in memory (policy, reference, reward model, and value model), every training step began by sampling responses, a critic had to be learned at the same time as the policy, and a dozen hyperparameters each had a way of breaking the run (§16.4, §16.6).

You have already met the answer to the problem PPO was solving. Section 15.7 stated it, with a one-line balance argument for why it has its shape, and §16.4 recapped it as the target PPO chases. If we stop insisting that the policy be a neural network, and allow any distribution over responses at all, the best policy can be written down exactly,

π⋆(y∣x)=1Z(x) πref(y∣x) exp⁡ ⁣(r(x,y)β).\pi^\star(y \mid x) = \frac{1}{Z(x)}\, \pi_{\text{ref}}(y \mid x)\, \exp\!\Big(\frac{r(x, y)}{\beta}\Big).

Take the reference model's distribution, multiply each response's probability by an exponential of its reward, and renormalize. Both earlier chapters used this formula without proving it. This section is where it is proved, and where the facts the rest of the chapter leans on are taken apart one at a time. We derive it twice, once from the Gibbs variational principle and once with Lagrange multipliers (the second turns §15.7's balance argument into a proof), check when the derivation needs care, read off what the formula says about β\beta, reward, and KL, see what changes if the KL is replaced by another divergence, and then explain why, despite having the answer in closed form, nobody can use it directly. The obstacle is one number per prompt, the normalizer Z(x)Z(x). The next section is about the trick that makes that number disappear, which is Direct Preference Optimization.

The problem PPO is solving

Fix the notation we will use for the whole chapter. A prompt xx is drawn from a dataset D\mathcal{D} of prompts. A response yy is a whole sequence of tokens y1,…,y∣y∣y_1, \dots, y_{|y|}, and ∣y∣|y| is its length. A policy π(y∣x)\pi(y \mid x) is a distribution over complete responses, which for a language model is the product of its next-token probabilities, π(y∣x)=∏t=1∣y∣π(yt∣x,y<t)\pi(y\mid x) = \prod_{t=1}^{|y|} \pi(y_t \mid x, y_{<t}), as in §6.4. When a subscript on yy is a position tt, as here, it means a token. Otherwise, y1,y2,…y_1, y_2, \dots and yw,yly_w, y_l name different whole responses. The reference policy πref\pi_{\text{ref}} is fixed, usually the supervised fine-tuned model. The reward r(x,y)r(x, y) is a number that scores a complete response, and β>0\beta > 0 sets how strongly we are tied to the reference. The KL-regularized objective of §15.7 and §16.4 is

J(π)=Ex∼D[ Ey∼π(⋅∣x)[r(x,y)]−β DKL(π(⋅∣x) ∥ πref(⋅∣x))].J(\pi) = \mathbb{E}_{x \sim \mathcal{D}}\Big[\, \mathbb{E}_{y \sim \pi(\cdot\mid x)}\big[r(x, y)\big] - \beta\, D_{\mathrm{KL}}\big(\pi(\cdot \mid x) \,\Vert\, \pi_{\text{ref}}(\cdot \mid x)\big) \Big].

In plain words, produce responses that score well on average, but pay β\beta for every nat of divergence from the reference model. The KL here is over whole responses. By the chain rule of KL divergence it equals the expected sum of the per-token KLs along a sampled response, which is the per-token form PPO implements.

Two observations turn this into a problem we can solve on paper.

First, let the policy be anything. PPO optimizes over the parameters θ\theta of a network. Here we optimize over every conditional distribution π(⋅∣x)\pi(\cdot \mid x), one probability vector per prompt. This is a relaxation, and the answer tells us what a network with unlimited capacity would converge to.

Second, the prompts decouple. The objective is an average over prompts of a term that depends only on that prompt's distribution π(⋅∣x)\pi(\cdot\mid x). Changing the policy on one prompt cannot help or hurt another, so we can maximize each term separately. From here until the end of the derivations, fix one prompt xx and drop it from the notation. We want the probability vector π\pi over responses that maximizes

Jx(π)=∑yπ(y) r(y)  −  β∑yπ(y)log⁡π(y)πref(y),J_x(\pi) = \sum_y \pi(y)\, r(y) \;-\; \beta \sum_y \pi(y) \log\frac{\pi(y)}{\pi_{\text{ref}}(y)},

subject to π(y)≥0\pi(y) \ge 0 and ∑yπ(y)=1\sum_y \pi(y) = 1. The sum runs over every possible response, a huge but finite set once lengths are capped.

A four-response example

Before any derivation, look at numbers small enough to check by hand. Suppose a prompt has only four possible responses. The reference model likes the first one most, and the reward model likes the last one most.

responseπref(y)\pi_{\text{ref}}(y)r(y)r(y)πref(y) er(y)\pi_{\text{ref}}(y)\,e^{r(y)} (β=1\beta = 1)
y1y_10.400.00.400
y2y_20.301.00.815
y3y_30.200.50.330
y4y_40.102.00.739

With β=1\beta = 1 the unnormalized weights in the last column sum to Z=2.284Z = 2.284, so the optimal policy is (0.175,0.357,0.144,0.323)(0.175, 0.357, 0.144, 0.323). The rare but excellent y4y_4 more than triples its probability, the bland favorite y1y_1 loses more than half of its probability, and nothing is set to zero. Now halve β\beta. Each weight becomes πref(y) e2r(y)\pi_{\text{ref}}(y)\,e^{2r(y)}, the exponential gaps double, and y4y_4 takes 0.6330.633 of the mass.

How does the optimal policy reweight each response, and what does the normalizer absorb?
Five responses to one prompt. Outlined bars are the reference policy, filled bars are the optimal policy, proportional to the reference probability times exp(reward / beta). Drag beta and the rewards.
Loading interactive figure…

The cell computes the same thing for several values of β\beta, in log space so that small β\beta cannot overflow (the log-sum-exp trick of §0.4).

Python · cell 1

At β=10\beta = 10 the policy barely moves, its expected reward is 0.640 against the reference's 0.600, and it pays a KL of only 0.002 nats. At β=0.1\beta = 0.1 it puts essentially all its mass on y4y_4, collects the maximum reward of 2, and pays a KL of 2.301 nats, which is almost exactly log⁡(1/0.1)=2.303\log(1/0.1) = 2.303, the price of turning a 10 percent response into a certainty. Every value of β\beta in between gives a different compromise, and the derivations below show that each one is the best compromise available at its price.

Core

The optimal policy, stable and batched

Implement optimal_policy(pi_ref, r, beta) for arrays of shape (..., K), one distribution per row over KK responses. Return π⋆∝πref er/β\pi^\star \propto \pi_{\text{ref}}\,e^{r/\beta} normalized along the last axis. It must not overflow for β\beta as small as 10−410^{-4} with rewards as large as 50, and a response with πref=0\pi_{\text{ref}} = 0 must get probability exactly 0 (even if its reward is huge) without producing warnings or NaN.

Hidden tests, hints, and AI help, from $1.99 a month.

Derivation one, the Gibbs variational principle

Section 15.7 stated the identity this derivation produces and used it, without proof, to grade training runs, and §16.4 sketched it in one line. Here it is proved with every step written out, because the rearrangement it produces along the way, the reward expressed through the policy, is what DPO is built on, and because the maximum value it produces, βlog⁡Z\beta\log Z, is the quantity the rest of this section is about. The cleanest derivation guesses the answer and then proves that nothing beats it. Define the tilted distribution

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

It is a valid distribution, because every weight is nonnegative and dividing by ZZ makes them sum to one. Taking logs and rearranging gives a formula for the reward in terms of π⋆\pi^\star, which we will use again and again,

r(y)=βlog⁡π⋆(y)πref(y)+βlog⁡Z.r(y) = \beta \log\frac{\pi^\star(y)}{\pi_{\text{ref}}(y)} + \beta \log Z .

Now take any policy π\pi and rewrite its objective. Pull β\beta out of both terms and put them under one sum,

Jx(π)=∑yπ(y)[r(y)−βlog⁡π(y)πref(y)]=−β∑yπ(y)[log⁡π(y)πref(y)−r(y)β].J_x(\pi) = \sum_y \pi(y)\Big[r(y) - \beta\log\frac{\pi(y)}{\pi_{\text{ref}}(y)}\Big] = -\beta \sum_y \pi(y)\Big[\log\frac{\pi(y)}{\pi_{\text{ref}}(y)} - \frac{r(y)}{\beta}\Big].

The bracket is a single logarithm, since log⁡π−log⁡πref−r/β=log⁡(π/(πref er/β))\log\pi - \log\pi_{\text{ref}} - r/\beta = \log\big(\pi / (\pi_{\text{ref}}\, e^{r/\beta})\big). Replace the denominator using πref(y)er(y)/β=Z π⋆(y)\pi_{\text{ref}}(y)e^{r(y)/\beta} = Z\,\pi^\star(y),

Jx(π)=−β∑yπ(y)log⁡π(y)Z π⋆(y)=−β∑yπ(y)log⁡π(y)π⋆(y)+βlog⁡Z∑yπ(y).J_x(\pi) = -\beta \sum_y \pi(y) \log\frac{\pi(y)}{Z\,\pi^\star(y)} = -\beta \sum_y \pi(y) \log\frac{\pi(y)}{\pi^\star(y)} + \beta \log Z \sum_y \pi(y).

The first sum is a KL divergence and the last sum is 1, so

  Jx(π)=βlog⁡Z−β DKL(π ∥ π⋆).  \boxed{\;J_x(\pi) = \beta \log Z - \beta\, D_{\mathrm{KL}}\big(\pi \,\Vert\, \pi^\star\big).\;}

In plain words, the objective of any policy equals a constant that does not depend on the policy, minus β\beta times how far the policy is from π⋆\pi^\star. By Gibbs' inequality (§0.5) a KL divergence is never negative and is zero only when the two distributions are equal. So JxJ_x is maximized by π=π⋆\pi = \pi^\star and by nothing else, and the maximum value is

max⁡πJx(π)=Jx(π⋆)=βlog⁡Z=βlog⁡Ey∼πref[er(y)/β].\max_\pi J_x(\pi) = J_x(\pi^\star) = \beta \log Z = \beta \log \mathbb{E}_{y\sim\pi_{\text{ref}}}\big[e^{r(y)/\beta}\big].

This identity, with its maximizer, is called the Gibbs variational principle (in probability it is also known as the Donsker-Varadhan formula). Statistical physicists will recognize the pieces. With energy −r-r and temperature β\beta, π⋆\pi^\star is the Boltzmann distribution relative to the prior πref\pi_{\text{ref}}, and −βlog⁡Z-\beta\log Z is the free energy. The quantity βlog⁡Z\beta\log Z is called the soft value of the prompt, and we will write V⋆(x)=βlog⁡Z(x)V^\star(x) = \beta \log Z(x). It is a soft maximum of the rewards in exactly the sense of log-sum-exp. As β→0\beta \to 0 it approaches the largest reward among responses the reference can produce, and as β→∞\beta \to \infty it approaches the reference's average reward Eπref[r]\mathbb{E}_{\pi_{\text{ref}}}[r] (Exercise 17.1b proves both).

Python · cell 2

None of the 5,000 random policies reaches J(π⋆)=0.826J(\pi^\star) = 0.826, and the identity J=βlog⁡Z−βDKL(π∥π⋆)J = \beta\log Z - \beta D_{\mathrm{KL}}(\pi\Vert\pi^\star) holds for every one of them to rounding error.

Core

The soft value and its two limits

Implement objective(pi, pi_ref, r, beta), the per-prompt objective Jx(π)=∑yπ(y)r(y)−β∑yπ(y)log⁡π(y)πref(y)J_x(\pi) = \sum_y\pi(y)r(y) - \beta\sum_y\pi(y)\log\frac{\pi(y)}{\pi_{\text{ref}}(y)} for 1-D arrays, using the convention 0log⁡0=00\log 0 = 0, and soft_value(pi_ref, r, beta), which returns βlog⁡∑yπref(y)er(y)/β\beta\log\sum_y\pi_{\text{ref}}(y)e^{r(y)/\beta} computed stably. Assume πref>0\pi_{\text{ref}} > 0 everywhere. The tests check that the soft value equals the objective of the optimal policy, beats every other policy, and approaches max⁡yr(y)\max_y r(y) as β→0\beta\to 0 and Eπref[r]\mathbb{E}_{\pi_{\text{ref}}}[r] as β→∞\beta\to\infty. Then convince yourself of the second limit on paper with a first-order Taylor expansion of er/βe^{r/\beta}.

Hidden tests, hints, and AI help, from $1.99 a month.

Derivation two, Lagrange multipliers

The first derivation needed us to guess π⋆\pi^\star. The second one finds it without guessing, which is how you would discover it at a whiteboard. Treat each π(y)\pi(y) as a separate variable and enforce ∑yπ(y)=1\sum_y\pi(y) = 1 with a Lagrange multiplier λ\lambda (nonnegativity will take care of itself). The Lagrangian (we write it J\mathcal{J}, since it is maximized) is

J(π,λ)=∑yπ(y) r(y)−β∑yπ(y)[log⁡π(y)−log⁡πref(y)]+λ(1−∑yπ(y)).\mathcal{J}(\pi, \lambda) = \sum_y \pi(y)\, r(y) - \beta\sum_y \pi(y)\big[\log\pi(y) - \log\pi_{\text{ref}}(y)\big] + \lambda\Big(1 - \sum_y \pi(y)\Big).

Differentiate with respect to one coordinate π(y)\pi(y). The product rule on πlog⁡π\pi\log\pi gives log⁡π+1\log\pi + 1, so

∂J∂π(y)=r(y)−β[log⁡π(y)−log⁡πref(y)+1]−λ=0.\frac{\partial\mathcal{J}}{\partial \pi(y)} = r(y) - \beta\big[\log\pi(y) - \log\pi_{\text{ref}}(y) + 1\big] - \lambda = 0 .

Solve for log⁡π(y)\log \pi(y) and exponentiate,

log⁡π(y)=log⁡πref(y)+r(y)β−β+λβ⟹π(y)=πref(y) er(y)/β e−(β+λ)/β.\log\pi(y) = \log\pi_{\text{ref}}(y) + \frac{r(y)}{\beta} - \frac{\beta + \lambda}{\beta} \quad\Longrightarrow\quad \pi(y) = \pi_{\text{ref}}(y)\, e^{r(y)/\beta}\, e^{-(\beta+\lambda)/\beta}.

The last factor is the same for every yy. The constraint ∑yπ(y)=1\sum_y \pi(y) = 1 fixes it, e−(β+λ)/β=1/Ze^{-(\beta+\lambda)/\beta} = 1/Z, and we recover π⋆\pi^\star.

Read the stationarity condition again, rearranged as r(y)−β[log⁡π(y)πref(y)+1]=λr(y) - \beta\big[\log\frac{\pi(y)}{\pi_{\text{ref}}(y)} + 1\big] = \lambda. The left side is the marginal value of a little extra probability on yy, its reward minus the marginal KL cost, and the condition says it must be the same number λ\lambda for every response. That is exactly the balance argument of §15.7 (if two responses had different marginal values, moving probability from the worse to the better would raise JJ), and λ\lambda is the common value. At the solution it equals βlog⁡Z−β\beta\log Z - \beta, which you can check by substituting π⋆\pi^\star.

Two loose ends make this a proof rather than a calculation. The first is the constraint π(y)≥0\pi(y) \ge 0, which we did not enforce. A maximum could in principle sit on the boundary, with some π(y)=0\pi(y) = 0, where the derivative above does not exist. It cannot. The derivative of −β πlog⁡π-\beta\,\pi\log\pi is −β(log⁡π+1)-\beta(\log\pi + 1), which tends to +∞+\infty as π→0\pi \to 0. So at any point with π(y)=0\pi(y) = 0 and πref(y)>0\pi_{\text{ref}}(y) > 0, moving a sliver of probability δ\delta onto yy from any other response gains about β δlog⁡(1/δ)\beta\,\delta\log(1/\delta) from that term, which beats every finite loss of order δ\delta. No boundary point is optimal, the maximizer is interior, and an interior maximum must satisfy the stationarity condition.

The second is whether this stationary point is a maximum. The second derivatives are ∂2J/∂π(y)2=−β/π(y)<0\partial^2\mathcal{J}/\partial\pi(y)^2 = -\beta/\pi(y) < 0 and every mixed partial is zero, so the Hessian is diagonal with negative entries and the objective is strictly concave on the simplex. For a strictly concave function on a convex set, any local maximum is the unique global one, so the single stationary point is the maximizer. Both derivations agree, as they must.

One case needs care. If πref(y)=0\pi_{\text{ref}}(y) = 0, the KL term is infinite for any π\pi that gives yy positive probability, so π⋆(y)=0\pi^\star(y) = 0 no matter how large r(y)r(y) is. (In the Lagrangian, drop those responses before differentiating, and run the argument above on the support of πref\pi_{\text{ref}}.) The optimal policy can reweight what the reference can say, but it can never say something the reference cannot. For language models this is less restrictive than it sounds, because softmax probabilities are never exactly zero, but it is the precise sense in which the KL penalty keeps the policy near the reference.

A last technical remark, for completeness. The derivations treat the set of responses as finite, which it is once lengths are capped, so ZZ is a finite sum and always exists. Without a length cap, ZZ is an infinite series, and it is finite whenever the reward is bounded above, since then Z≤esup⁡r/βZ \le e^{\sup r/\beta}. The Gibbs derivation goes through unchanged, because it never differentiates and only uses that ZZ is finite and KL is nonnegative.

What the formula says

Write the optimal policy in log space,

log⁡π⋆(y)=log⁡πref(y)+r(y)β−log⁡Z.\log \pi^\star(y) = \log \pi_{\text{ref}}(y) + \frac{r(y)}{\beta} - \log Z .

The tuned model's log-probabilities are the reference's log-probabilities plus the reward divided by β\beta, minus a constant per prompt. This is called an exponential tilt of πref\pi_{\text{ref}}. Five consequences follow, and each one comes back later in the chapter.

Ratios do not need ZZ. For any two responses,

π⋆(y1)π⋆(y2)=πref(y1)πref(y2) exp⁡ ⁣(r(y1)−r(y2)β).\frac{\pi^\star(y_1)}{\pi^\star(y_2)} = \frac{\pi_{\text{ref}}(y_1)}{\pi_{\text{ref}}(y_2)}\, \exp\!\Big(\frac{r(y_1) - r(y_2)}{\beta}\Big).

The normalizer cancels in every ratio. Hold on to this, because it is the whole idea of DPO.

Only reward differences matter. Adding any function f(x)f(x) of the prompt alone to the reward multiplies every weight by ef(x)/βe^{f(x)/\beta}, which ZZ absorbs, so π⋆\pi^\star is unchanged. A reward model trained with the Bradley-Terry loss is only defined up to exactly such a shift (§16.3), so this is reassuring. The shift that reward models cannot pin down is also one the optimal policy cannot see.

β\beta is a temperature. As β→∞\beta\to\infty the tilt vanishes and π⋆→πref\pi^\star \to \pi_{\text{ref}}. As β→0\beta \to 0 the mass concentrates on the highest-reward response among those the reference can produce. In between, β\beta converts reward into log-probability at an exchange rate of one nat per β\beta units of reward.

It is a Bayesian posterior. Read πref\pi_{\text{ref}} as a prior over responses and er(y)/βe^{r(y)/\beta} as a likelihood, proportional to the probability of observing "this response is good" given yy. Then π⋆\pi^\star is the posterior and ZZ is the evidence. Korbak, Perez, and Buckley (2022) argue that this is the right way to think about KL-regularized fine-tuning, as conditioning a prior on evidence rather than as maximizing reward, and it explains why the KL term is not a hack added to stabilize RL but part of what defines the target.

The reward can be read off the policy. Rearranged, the log-space formula is r(y)=βlog⁡(π⋆(y)/πref(y))+βlog⁡Zr(y) = \beta\log\big(\pi^\star(y)/\pi_{\text{ref}}(y)\big) + \beta\log Z. Knowing the optimal policy and the reference, we know the reward up to the per-prompt constant βlog⁡Z\beta\log Z. Section 17.2 builds DPO on exactly this sentence.

The price of reward, in nats

How much reward does a nat of KL buy? Take the expectation of log⁡(π⋆/πref)=r/β−log⁡Z\log(\pi^\star/\pi_{\text{ref}}) = r/\beta - \log Z under π⋆\pi^\star,

DKL(π⋆∥πref)=Eπ⋆[r]β−log⁡Z.D_{\mathrm{KL}}(\pi^\star \Vert \pi_{\text{ref}}) = \frac{\mathbb{E}_{\pi^\star}[r]}{\beta} - \log Z .

Write κ=1/β\kappa = 1/\beta for the inverse temperature and A(κ)=log⁡∑yπref(y)eκr(y)A(\kappa) = \log\sum_y\pi_{\text{ref}}(y)e^{\kappa r(y)}, which is log⁡Z\log Z. Then π⋆\pi^\star is an exponential family in κ\kappa, and its log-normalizer has the familiar derivatives A′(κ)=Eπ⋆[r]A'(\kappa) = \mathbb{E}_{\pi^\star}[r] and A′′(κ)=Var⁡π⋆(r)A''(\kappa) = \operatorname{Var}_{\pi^\star}(r) (differentiate under the sum once and then again). So as κ\kappa grows, which means as β\beta shrinks,

d Eπ⋆[r]dκ=Var⁡π⋆(r)≥0,d DKLdκ=ddκ(κA′(κ)−A(κ))=κVar⁡π⋆(r)≥0.\frac{d\,\mathbb{E}_{\pi^\star}[r]}{d\kappa} = \operatorname{Var}_{\pi^\star}(r) \ge 0, \qquad \frac{d\,D_{\mathrm{KL}}}{d\kappa} = \frac{d}{d\kappa}\big(\kappa A'(\kappa) - A(\kappa)\big) = \kappa\operatorname{Var}_{\pi^\star}(r) \ge 0 .

Both the reward and the KL grow as β\beta shrinks, and the ratio of the two derivatives is the slope of the curve traced by (DKL,E[r])(D_{\mathrm{KL}}, \mathbb{E}[r]),

d Eπ⋆[r]d DKL=Var⁡κVar⁡=β.\frac{d\,\mathbb{E}_{\pi^\star}[r]}{d\,D_{\mathrm{KL}}} = \frac{\operatorname{Var}}{\kappa \operatorname{Var}} = \beta .

In plain words, at the optimum for a given β\beta, one more nat of divergence buys exactly β\beta more units of reward. This is the Lagrangian picture of the problem. πβ⋆\pi^\star_\beta gets the highest reward of any policy with the same KL (if some π\pi had the same KL and more reward, it would have a larger JJ), so the curve is the reward-KL frontier, and β\beta is the price that picks a point on it. Large β\beta makes KL expensive and stops near the origin. Small β\beta makes it cheap and slides far out along a frontier that flattens, because each extra nat buys less and less. When the reward is a learned model with errors, the far end of that flat stretch is where reward hacking lives (§16.5).

Python · cell 3

The measured slope matches β\beta at every point, to the accuracy of the finite differences. The widget below draws the whole frontier for an eight-response prompt, along with the policy that every practitioner reaches for first, best-of-nn, which samples nn responses from the reference and keeps the one with the highest reward (§18.2). Its KL from the reference is often quoted as log⁡n−(n−1)/n\log n - (n-1)/n. Beirami et al. (2024) showed that this formula is only an upper bound, and the widget computes the exact value for this small example, where the best-of-nn distribution is known in closed form. Sort the responses by reward and let FF be the reference CDF in that order. The best of nn independent draws is response ii with probability F(i)n−F(i−1)nF(i)^n - F(i-1)^n.

What does each value of beta buy, and how close does best-of-n get?
Eight responses with a fixed reference policy and rewards. The curve is every optimal policy, from beta = 100 (origin) to beta = 0.01. The dashed tangent at the chosen beta has slope exactly beta. Squares are best-of-n for n = 1 to 256, with exact KL.
Loading interactive figure…

The bound also gives a feel for real KL budgets. Best-of-16 sits at most log⁡16−15/16=1.84\log 16 - 15/16 = 1.84 nats from the reference, and best-of-64 at most 3.17 nats, and nn in this range is where best-of-nn is commonly used to improve outputs. Spread over a 300-token response, 3.17 nats is about 0.01 nats per token. Sequence-level KL is the number that measures how far a policy has moved, and a policy can change its behavior a great deal while every individual token distribution barely moves. Keep this scale in mind when §17.2 finds DPO moving single pairs by tens of nats.

Interview

Choosing beta for a KL budget

Teams often think in KL budgets rather than in β\beta ("move at most 2 nats from the SFT model"). PPO implementations even adapt β\beta during training to hit a target KL. For the closed-form policy we can find the right β\beta exactly. Implement beta_for_kl(pi_ref, r, kl_target, tol=1e-8) that returns the β\beta for which DKL(πβ⋆∥πref)=D_{\mathrm{KL}}(\pi^\star_\beta\Vert\pi_{\text{ref}}) = kl_target, to within tol in KL. Use the fact derived above that the KL decreases monotonically as β\beta grows. Raise a ValueError if the target is not reachable, which happens when it is at least the KL of the β→0\beta\to0 limit, −log⁡∑y∈Ymax⁡πref(y)-\log\sum_{y \in \mathcal{Y}_{\max}}\pi_{\text{ref}}(y) where Ymax⁡\mathcal{Y}_{\max} is the set of responses with the largest reward. Assume πref>0\pi_{\text{ref}} > 0, the rewards are not all equal, and kl_target > 0.

Hidden tests, hints, and AI help, from $1.99 a month.

What is special about the KL

Nothing in the Lagrange derivation used much about the KL, so it is fair to ask what happens with a different penalty. Interviewers ask it, and the answer separates the parts of the closed form that DPO truly needs from the parts that come with the KL.

An ff-divergence measures the gap between two distributions as Dφ(π∥πref)=∑yπref(y) φ(π(y)/πref(y))D_\varphi(\pi\Vert\pi_{\text{ref}}) = \sum_y\pi_{\text{ref}}(y)\,\varphi\big(\pi(y)/\pi_{\text{ref}}(y)\big) for a convex function φ\varphi with φ(1)=0\varphi(1) = 0. (The literature writes ff. We write φ\varphi because f(x)f(x) already names a function of the prompt in this section.) Our KL is the case φ(u)=ulog⁡u\varphi(u) = u\log u, since ∑yπrefππreflog⁡ππref=∑yπlog⁡ππref\sum_y\pi_{\text{ref}}\frac{\pi}{\pi_{\text{ref}}}\log\frac{\pi}{\pi_{\text{ref}}} = \sum_y\pi\log\frac{\pi}{\pi_{\text{ref}}}. The forward KL of §0.5, DKL(πref∥π)=∑yπreflog⁡πrefπD_{\mathrm{KL}}(\pi_{\text{ref}}\Vert\pi) = \sum_y\pi_{\text{ref}}\log\frac{\pi_{\text{ref}}}{\pi}, is the case φ(u)=−log⁡u\varphi(u) = -\log u.

Put DφD_\varphi in place of the KL and repeat the Lagrange calculation. The derivative of πref(y) φ(π(y)/πref(y))\pi_{\text{ref}}(y)\,\varphi\big(\pi(y)/\pi_{\text{ref}}(y)\big) with respect to π(y)\pi(y) is φ′(π(y)/πref(y))\varphi'\big(\pi(y)/\pi_{\text{ref}}(y)\big), by the chain rule, so stationarity reads

r(y)−β φ′(π(y)πref(y))=λ⟹π(y)=πref(y) (φ′)−1(r(y)−λβ),r(y) - \beta\,\varphi'\Big(\frac{\pi(y)}{\pi_{\text{ref}}(y)}\Big) = \lambda \quad\Longrightarrow\quad \pi(y) = \pi_{\text{ref}}(y)\,(\varphi')^{-1}\Big(\frac{r(y) - \lambda}{\beta}\Big),

with λ\lambda chosen so the probabilities sum to one. For φ(u)=ulog⁡u\varphi(u) = u\log u, φ′(u)=log⁡u+1\varphi'(u) = \log u + 1, its inverse is ev−1e^{v - 1}, and this is the tilt again. For the forward KL, φ′(u)=−1/u\varphi'(u) = -1/u, and

πfwd(y)=β πref(y)λ−r(y),∑yβ πref(y)λ−r(y)=1,λ>max⁡yr(y).\pi_{\text{fwd}}(y) = \frac{\beta\,\pi_{\text{ref}}(y)}{\lambda - r(y)}, \qquad \sum_y\frac{\beta\,\pi_{\text{ref}}(y)}{\lambda - r(y)} = 1, \quad \lambda > \max_y r(y).

In plain words, the forward-KL optimum also reweights the reference toward high reward, but by a factor that grows like 1/(λ−r)1/(\lambda - r) rather than exponentially. There is no closed form for λ\lambda. The sum on the right falls from +∞+\infty to below 1 as λ\lambda rises from max⁡r\max r to max⁡r+β\max r + \beta (at λ=max⁡r+β\lambda = \max r + \beta every term is at most its πref\pi_{\text{ref}}), so λ\lambda is a root in that interval, found by bisection. The objective is again strictly concave (the second derivative of −βπreflog⁡(πref/π)-\beta\pi_{\text{ref}}\log(\pi_{\text{ref}}/\pi) is −βπref/π2-\beta\pi_{\text{ref}}/\pi^2), so this is the unique maximum.

Python · cell 4

At β=1\beta = 1 the forward-KL optimum is (0.180,0.246,0.116,0.457)(0.180, 0.246, 0.116, 0.457) with λ=2.219\lambda = 2.219. At β=0.1\beta = 0.1 the difference is stark. The tilt gives y1y_1 a probability of about 8×10−98\times10^{-9}, while the forward-KL policy still gives it 0.020. As β→0\beta \to 0, the losers' probabilities under the forward KL shrink only in proportion to β\beta, about βπref(y)/(max⁡r−r(y))\beta\pi_{\text{ref}}(y)/(\max r - r(y)), while under the reverse KL they shrink like e−(max⁡r−r(y))/βe^{-(\max r - r(y))/\beta}. This is the mode-seeking versus mass-covering contrast of §0.5, now visible in the optimum itself. The forward KL charges infinitely for letting any supported response die, so it never does.

Two properties carry over to every ff-divergence, and three belong to the KL alone.

  • Carries over, the one-constant-per-prompt structure. Rearranged, stationarity says r(x,y)=βφ′(π(y∣x)/πref(y∣x))+λ(x)r(x, y) = \beta\varphi'\big(\pi(y\mid x)/\pi_{\text{ref}}(y\mid x)\big) + \lambda(x). The multiplier plays the role of βlog⁡Z\beta\log Z, it depends only on the prompt, and it enters additively, so it cancels in the reward difference of two responses to the same prompt. That is all the next section needs, and Wang et al. (2023) build exactly this ff-DPO, with forward KL, Jensen-Shannon, and α\alpha-divergences, reporting that the choice trades some alignment performance for more diverse generations. TRL exposes it as f_divergence_type.
  • Carries over, no new support. With πref(y)=0\pi_{\text{ref}}(y) = 0, the formula gives π(y)=0\pi(y) = 0 again.
  • KL only, an explicit normalizer. The tilt has Z=Eπref[er/β]Z = \mathbb{E}_{\pi_{\text{ref}}}[e^{r/\beta}], an expectation, which is what makes its soft value, its Bayesian reading, and the reward-KL calculus above so clean. Other divergences give λ\lambda only as the root of an equation.
  • KL only, a sum over tokens. βlog⁡π(y)πref(y)\beta\log\frac{\pi(y)}{\pi_{\text{ref}}(y)} is a sum of per-token log-ratios, so the implied reward decomposes over tokens. That is what makes the per-token soft values of the callout below, and PPO's per-token penalty, possible. The forward KL's φ′(π/πref)=−πref(y)/π(y)\varphi'(\pi/\pi_{\text{ref}}) = -\pi_{\text{ref}}(y)/\pi(y) is a product of per-token ratios. For whole responses whose log-ratios reach tens of nats (§17.2), that is e±40e^{\pm 40}, which makes such losses numerically delicate on long sequences.
  • KL only, estimable from the policy's own samples. DKL(π∥πref)D_{\mathrm{KL}}(\pi\Vert\pi_{\text{ref}}) is an expectation under π\pi, which is why PPO can penalize it on its rollouts (§15.7). The forward KL is an expectation under the reference, which would need reference samples at every step.
Interview

The optimum under a forward KL

Implement forward_kl_policy(pi_ref, r, beta) for arrays of shape (..., K), one prompt per row. Return the maximizer of ∑yπ(y)r(y)−β∑yπref(y)log⁡πref(y)π(y)\sum_y\pi(y)r(y) - \beta\sum_y\pi_{\text{ref}}(y)\log\frac{\pi_{\text{ref}}(y)}{\pi(y)} for each row, which is π(y)=βπref(y)/(λ−r(y))\pi(y) = \beta\pi_{\text{ref}}(y)/(\lambda - r(y)) with λ\lambda chosen per row so the row sums to one. Do not use scipy. Bisect on λ\lambda for all rows at once, using the bracket derived above, with the maximum taken over responses that have πref>0\pi_{\text{ref}} > 0. Responses with πref=0\pi_{\text{ref}} = 0 must get probability exactly 0, whatever their reward. It must stay accurate for β\beta as small as 10−310^{-3}.

Hidden tests, hints, and AI help, from $1.99 a month.

The partition function problem

So we have the answer. Why does anyone run PPO? Look again at the normalizer,

Z(x)=∑yπref(y∣x) exp⁡ ⁣(r(x,y)β).Z(x) = \sum_{y} \pi_{\text{ref}}(y \mid x)\, \exp\!\Big(\frac{r(x, y)}{\beta}\Big).

The sum is over every possible response. With a vocabulary of VV tokens and responses of up to TT tokens there are about VTV^T of them. Llama 3's tokenizer has about 128,000 tokens, so responses of 100 tokens number about 128,000100≈10511128{,}000^{100} \approx 10^{511}. Enumerating them is not slow, it is impossible, and every prompt has its own Z(x)Z(x).

Could we estimate Z(x)Z(x) instead? It is an expectation under the reference, Z=Ey∼πref[er(y)/β]Z = \mathbb{E}_{y\sim\pi_{\text{ref}}}[e^{r(y)/\beta}], so averaging er/βe^{r/\beta} over NN samples from the reference gives an unbiased estimate. The trouble is the variance. The average is dominated by the rare samples with the largest rewards, and the smaller β\beta is, the more extreme that domination becomes. A clean way to measure it is the effective sample size of the weights wi=er(yi)/βw_i = e^{r(y_i)/\beta},

ESS⁡=(∑iwi)2∑iwi2,\operatorname{ESS} = \frac{\big(\sum_i w_i\big)^2}{\sum_i w_i^2},

which equals NN when all weights are equal and 1 when a single sample carries all the weight. A worked example makes the problem concrete. Suppose rewards under the reference are Gaussian, r∼N(0,s2)r \sim \mathcal{N}(0, s^2), a convenient model for rewards that have been standardized to unit spread. The moment generating function of a Gaussian gives everything in closed form,

Z=E[er/β]=es2/(2β2),ESS⁡N≈(E[w])2E[w2]=es2/β2e2s2/β2=e−s2/β2.Z = \mathbb{E}\big[e^{r/\beta}\big] = e^{s^2/(2\beta^2)}, \qquad \frac{\operatorname{ESS}}{N} \approx \frac{\big(\mathbb{E}[w]\big)^2}{\mathbb{E}[w^2]} = \frac{e^{s^2/\beta^2}}{e^{2s^2/\beta^2}} = e^{-s^2/\beta^2} .

With unit reward spread and β=0.1\beta = 0.1, the fraction of useful samples is e−100≈4×10−44e^{-100} \approx 4\times 10^{-44}. We would need about e100≈3×1043e^{100} \approx 3\times10^{43} samples from the reference just to get one effective sample for one prompt.

Python · cell 5

At β=1\beta = 1 the estimate of log⁡Z\log Z is right and over a third of the samples are useful. At β=0.25\beta = 0.25 the effective sample size has collapsed to about one, and the estimate is wrong by almost 2 nats. At β=0.1\beta = 0.1 it is off by 20 nats, a factor of e20e^{20} in ZZ, while looking perfectly confident. (The predicted ESS for the last rows is far below 1. The measured one cannot go below 1, which is exactly the problem, since one sample is carrying everything.) For reference, β=0.1\beta = 0.1 is the default value in the DPO paper and in many recipes.

And estimating ZZ would not be enough. To use π⋆\pi^\star we must sample from it, and token by token that requires the soft value of every prefix the model might reach, each of which is another sum of the same kind (the callout below spells this out). We also need a policy for prompts that were not in the training set, which means a network πθ\pi_\theta that has learned to approximate π⋆\pi^\star everywhere. So the real problem was never "what is the optimal policy". It is "how do we train πθ\pi_\theta toward π⋆\pi^\star without ever computing ZZ".

Python · cell 6

Three ways around the partition function

Every practical method for KL-regularized preference learning is a way of reaching π⋆\pi^\star without ZZ. There are three families.

Optimize JJ directly with reinforcement learning. The policy gradient of §15.3 needs only samples from πθ\pi_\theta and their rewards, with the KL folded into the reward as a per-token penalty. ZZ never appears, because we never normalize anything over all responses. The price is everything that made Chapter 16 heavy, on-policy sampling during training, a critic or another baseline, and a reward model that is queried on the policy's own outputs, which it may not have been trained on.

Fit πθ\pi_\theta to π⋆\pi^\star by weighted maximum likelihood. Minimize DKL(π⋆∥πθ)D_{\mathrm{KL}}(\pi^\star\Vert\pi_\theta). Up to a constant this is −Ey∼π⋆[log⁡πθ(y)]=−Ey∼πref[er(y)/βZlog⁡πθ(y)]-\mathbb{E}_{y\sim\pi^\star}[\log\pi_\theta(y)] = -\mathbb{E}_{y\sim\pi_{\text{ref}}}\big[\tfrac{e^{r(y)/\beta}}{Z}\log\pi_\theta(y)\big], supervised learning on reference samples weighted by exponentiated reward. This is reward-weighted regression (Peters and Schaal 2007) and, with advantages in place of rewards, advantage-weighted regression (Peng et al. 2019). In practice ZZ is replaced by the sum of the weights in a batch, and the method inherits exactly the effective sample size problem we just measured.

Change variables so that ZZ cancels. We saw that ratios of π⋆\pi^\star do not involve ZZ, and that the reward can be read off the policy up to βlog⁡Z\beta\log Z. Preference data only ever compares two responses to the same prompt, so a loss written on preferences might never need ZZ at all. That is Direct Preference Optimization, the subject of the next section.

routewhat it needswhat it costswhere in the book
RL on JJ (PPO, GRPO)a reward for any response, samples from πθ\pi_\theta during trainingfour models, sampling in the loop, high-variance gradients§16.4, §18.4
weighted regression (RWR, AWR)samples from the reference, a reward for eachself-normalized weights, ESS collapse at small β\betathis section
change of variables (DPO and family)preference pairs, a frozen referenceno exploration, depends on data coverage§17.2 to §17.5

In PyTorch

The closed form is the optimum over all policies. A neural policy is a parameterized subset, and the honest check is that gradient ascent on JJ through a softmax parameterization, with autograd and no knowledge of the formula, finds the same distribution. Here the policy is a free vector of logits, which can represent any distribution with full support, so it should converge to π⋆\pi^\star exactly.

🔥 In PyTorchfor a machine with PyTorch

Notice what this toy hides. We could compute JJ exactly because there were four responses. With a real model there are 1051110^{511}, so the expectation must be estimated from samples of πθ\pi_\theta, and that is the road back to policy gradients.

Read more

Watch next

🎬 Direct Preference Optimization (DPO) and Friends | Post-Training Course, Lecture 6 · Nathan Lambert · starts at 8:01The derivation of the optimal policy, step by step on slides, from the author of the RLHF book.
🎬 Direct Preference Optimization (DPO) - How to fine-tune LLMs directly without reinforcement learning · Luis Serrano AcademyA gentle visual introduction to the KL-constrained problem and why DPO can skip the RL loop.