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.
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,
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 , 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 . 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 is drawn from a dataset of prompts. A response is a whole sequence of tokens , and is its length. A policy is a distribution over complete responses, which for a language model is the product of its next-token probabilities, , as in §6.4. When a subscript on is a position , as here, it means a token. Otherwise, and name different whole responses. The reference policy is fixed, usually the supervised fine-tuned model. The reward is a number that scores a complete response, and sets how strongly we are tied to the reference. The KL-regularized objective of §15.7 and §16.4 is
In plain words, produce responses that score well on average, but pay 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 of a network. Here we optimize over every conditional distribution , 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 . 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 and drop it from the notation. We want the probability vector over responses that maximizes
subject to and . 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 | () | ||
|---|---|---|---|
| 0.40 | 0.0 | 0.400 | |
| 0.30 | 1.0 | 0.815 | |
| 0.20 | 0.5 | 0.330 | |
| 0.10 | 2.0 | 0.739 |
With the unnormalized weights in the last column sum to , so the optimal policy is . The rare but excellent more than triples its probability, the bland favorite loses more than half of its probability, and nothing is set to zero. Now halve . Each weight becomes , the exponential gaps double, and takes of the mass.
The cell computes the same thing for several values of , in log space so that small cannot overflow (the log-sum-exp trick of §0.4).
At 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 it puts essentially all its mass on , collects the maximum reward of 2, and pays a KL of 2.301 nats, which is almost exactly , the price of turning a 10 percent response into a certainty. Every value of in between gives a different compromise, and the derivations below show that each one is the best compromise available at its price.
The optimal policy, stable and batched
Implement optimal_policy(pi_ref, r, beta) for arrays of shape (..., K), one distribution per row over responses. Return normalized along the last axis. It must not overflow for as small as with rewards as large as 50, and a response with must get probability exactly 0 (even if its reward is huge) without producing warnings or NaN.
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, , 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
It is a valid distribution, because every weight is nonnegative and dividing by makes them sum to one. Taking logs and rearranging gives a formula for the reward in terms of , which we will use again and again,
Now take any policy and rewrite its objective. Pull out of both terms and put them under one sum,
The bracket is a single logarithm, since . Replace the denominator using ,
The first sum is a KL divergence and the last sum is 1, so
In plain words, the objective of any policy equals a constant that does not depend on the policy, minus times how far the policy is from . By Gibbs' inequality (§0.5) a KL divergence is never negative and is zero only when the two distributions are equal. So is maximized by and by nothing else, and the maximum value is
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 and temperature , is the Boltzmann distribution relative to the prior , and is the free energy. The quantity is called the soft value of the prompt, and we will write . It is a soft maximum of the rewards in exactly the sense of log-sum-exp. As it approaches the largest reward among responses the reference can produce, and as it approaches the reference's average reward (Exercise 17.1b proves both).
None of the 5,000 random policies reaches , and the identity holds for every one of them to rounding error.
The soft value and its two limits
Implement objective(pi, pi_ref, r, beta), the per-prompt objective for 1-D arrays, using the convention , and soft_value(pi_ref, r, beta), which returns computed stably. Assume everywhere. The tests check that the soft value equals the objective of the optimal policy, beats every other policy, and approaches as and as . Then convince yourself of the second limit on paper with a first-order Taylor expansion of .
Derivation two, Lagrange multipliers
The first derivation needed us to guess . The second one finds it without guessing, which is how you would discover it at a whiteboard. Treat each as a separate variable and enforce with a Lagrange multiplier (nonnegativity will take care of itself). The Lagrangian (we write it , since it is maximized) is
Differentiate with respect to one coordinate . The product rule on gives , so
Solve for and exponentiate,
The last factor is the same for every . The constraint fixes it, , and we recover .
Read the stationarity condition again, rearranged as . The left side is the marginal value of a little extra probability on , its reward minus the marginal KL cost, and the condition says it must be the same number 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 ), and is the common value. At the solution it equals , which you can check by substituting .
Two loose ends make this a proof rather than a calculation. The first is the constraint , which we did not enforce. A maximum could in principle sit on the boundary, with some , where the derivative above does not exist. It cannot. The derivative of is , which tends to as . So at any point with and , moving a sliver of probability onto from any other response gains about from that term, which beats every finite loss of order . 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 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 , the KL term is infinite for any that gives positive probability, so no matter how large is. (In the Lagrangian, drop those responses before differentiating, and run the argument above on the support of .) 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 is a finite sum and always exists. Without a length cap, is an infinite series, and it is finite whenever the reward is bounded above, since then . The Gibbs derivation goes through unchanged, because it never differentiates and only uses that is finite and KL is nonnegative.
What the formula says
Write the optimal policy in log space,
The tuned model's log-probabilities are the reference's log-probabilities plus the reward divided by , minus a constant per prompt. This is called an exponential tilt of . Five consequences follow, and each one comes back later in the chapter.
Ratios do not need . For any two responses,
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 of the prompt alone to the reward multiplies every weight by , which absorbs, so 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.
is a temperature. As the tilt vanishes and . As the mass concentrates on the highest-reward response among those the reference can produce. In between, converts reward into log-probability at an exchange rate of one nat per units of reward.
It is a Bayesian posterior. Read as a prior over responses and as a likelihood, proportional to the probability of observing "this response is good" given . Then is the posterior and 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 . Knowing the optimal policy and the reference, we know the reward up to the per-prompt constant . 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 under ,
Write for the inverse temperature and , which is . Then is an exponential family in , and its log-normalizer has the familiar derivatives and (differentiate under the sum once and then again). So as grows, which means as shrinks,
Both the reward and the KL grow as shrinks, and the ratio of the two derivatives is the slope of the curve traced by ,
In plain words, at the optimum for a given , one more nat of divergence buys exactly more units of reward. This is the Lagrangian picture of the problem. gets the highest reward of any policy with the same KL (if some had the same KL and more reward, it would have a larger ), so the curve is the reward-KL frontier, and is the price that picks a point on it. Large makes KL expensive and stops near the origin. Small 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).
The measured slope matches 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-, which samples responses from the reference and keeps the one with the highest reward (§18.2). Its KL from the reference is often quoted as . 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- distribution is known in closed form. Sort the responses by reward and let be the reference CDF in that order. The best of independent draws is response with probability .
The bound also gives a feel for real KL budgets. Best-of-16 sits at most nats from the reference, and best-of-64 at most 3.17 nats, and in this range is where best-of- 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.
Choosing beta for a KL budget
Teams often think in KL budgets rather than in ("move at most 2 nats from the SFT model"). PPO implementations even adapt during training to hit a target KL. For the closed-form policy we can find the right exactly. Implement beta_for_kl(pi_ref, r, kl_target, tol=1e-8) that returns the for which kl_target, to within tol in KL. Use the fact derived above that the KL decreases monotonically as grows. Raise a ValueError if the target is not reachable, which happens when it is at least the KL of the limit, where is the set of responses with the largest reward. Assume , the rewards are not all equal, and kl_target > 0.
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 -divergence measures the gap between two distributions as for a convex function with . (The literature writes . We write because already names a function of the prompt in this section.) Our KL is the case , since . The forward KL of §0.5, , is the case .
Put in place of the KL and repeat the Lagrange calculation. The derivative of with respect to is , by the chain rule, so stationarity reads
with chosen so the probabilities sum to one. For , , its inverse is , and this is the tilt again. For the forward KL, , and
In plain words, the forward-KL optimum also reweights the reference toward high reward, but by a factor that grows like rather than exponentially. There is no closed form for . The sum on the right falls from to below 1 as rises from to (at every term is at most its ), so is a root in that interval, found by bisection. The objective is again strictly concave (the second derivative of is ), so this is the unique maximum.
At the forward-KL optimum is with . At the difference is stark. The tilt gives a probability of about , while the forward-KL policy still gives it 0.020. As , the losers' probabilities under the forward KL shrink only in proportion to , about , while under the reverse KL they shrink like . 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 -divergence, and three belong to the KL alone.
- Carries over, the one-constant-per-prompt structure. Rearranged, stationarity says . The multiplier plays the role of , 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 -DPO, with forward KL, Jensen-Shannon, and -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 , the formula gives again.
- KL only, an explicit normalizer. The tilt has , an expectation, which is what makes its soft value, its Bayesian reading, and the reward-KL calculus above so clean. Other divergences give only as the root of an equation.
- KL only, a sum over tokens. 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 is a product of per-token ratios. For whole responses whose log-ratios reach tens of nats (§17.2), that is , which makes such losses numerically delicate on long sequences.
- KL only, estimable from the policy's own samples. is an expectation under , 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.
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 for each row, which is with chosen per row so the row sums to one. Do not use scipy. Bisect on for all rows at once, using the bracket derived above, with the maximum taken over responses that have . Responses with must get probability exactly 0, whatever their reward. It must stay accurate for as small as .
The partition function problem
So we have the answer. Why does anyone run PPO? Look again at the normalizer,
The sum is over every possible response. With a vocabulary of tokens and responses of up to tokens there are about of them. Llama 3's tokenizer has about 128,000 tokens, so responses of 100 tokens number about . Enumerating them is not slow, it is impossible, and every prompt has its own .
Could we estimate instead? It is an expectation under the reference, , so averaging over 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 is, the more extreme that domination becomes. A clean way to measure it is the effective sample size of the weights ,
which equals 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, , a convenient model for rewards that have been standardized to unit spread. The moment generating function of a Gaussian gives everything in closed form,
With unit reward spread and , the fraction of useful samples is . We would need about samples from the reference just to get one effective sample for one prompt.
At the estimate of is right and over a third of the samples are useful. At the effective sample size has collapsed to about one, and the estimate is wrong by almost 2 nats. At it is off by 20 nats, a factor of in , 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, is the default value in the DPO paper and in many recipes.
And estimating would not be enough. To use 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 that has learned to approximate everywhere. So the real problem was never "what is the optimal policy". It is "how do we train toward without ever computing ".
Three ways around the partition function
Every practical method for KL-regularized preference learning is a way of reaching without . There are three families.
Optimize directly with reinforcement learning. The policy gradient of §15.3 needs only samples from and their rewards, with the KL folded into the reward as a per-token penalty. 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 to by weighted maximum likelihood. Minimize . Up to a constant this is , 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 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 cancels. We saw that ratios of do not involve , and that the reward can be read off the policy up to . Preference data only ever compares two responses to the same prompt, so a loss written on preferences might never need at all. That is Direct Preference Optimization, the subject of the next section.
| route | what it needs | what it costs | where in the book |
|---|---|---|---|
| RL on (PPO, GRPO) | a reward for any response, samples from during training | four models, sampling in the loop, high-variance gradients | §16.4, §18.4 |
| weighted regression (RWR, AWR) | samples from the reference, a reward for each | self-normalized weights, ESS collapse at small | this section |
| change of variables (DPO and family) | preference pairs, a frozen reference | no 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 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 exactly.
Notice what this toy hides. We could compute exactly because there were four responses. With a real model there are , so the expectation must be estimated from samples of , and that is the road back to policy gradients.
Read more
- Rafailov, Sharma, Mitchell, Ermon, Manning & Finn (2023). Direct Preference Optimization: Your Language Model is Secretly a Reward Model. Section 4 and Appendix A.1 derive the closed-form optimum exactly as the first derivation here does, as the first step of DPO.
- Korbak, Perez & Buckley (2022). RL with KL penalties is better viewed as Bayesian inference. The posterior view of , and why the KL term defines the target rather than stabilizing RL.
- Peng, Kumar, Zhang & Levine (2019). Advantage-Weighted Regression: Simple and Scalable Off-Policy Reinforcement Learning. Derives the same exponential tilt with Lagrange multipliers and fits it by weighted regression, the second route around .
- Beirami, Agarwal, Berant, D'Amour, Eisenstein, Nagpal & Suresh (2024). Theoretical guarantees on the best-of-n alignment policy. Shows that the popular is an upper bound on the KL of best-of-, and how loose it can be.
- Rafailov, Hejna, Park & Finn (2024). From r to Q*: Your Language Model is Secretly a Q-Function. The token-level version of the closed form, with soft values at every prefix.
- Wang, Jiang, Yang, Liu & Chen (2023). Beyond Reverse KL: Generalizing Direct Preference Optimization with Diverse Divergence Constraints. The optimum under -divergence penalties from the KKT conditions, and the -DPO losses built on it.
- Gao, Schulman & Hilton (2023). Scaling Laws for Reward Model Overoptimization. Measures what happens far out along the reward-KL frontier when the reward is a learned proxy.