Module contents
Lesson 15 of 19Advanced 115 min

KL as a regularizer: mode seeking, VAEs and RLHF

Compare the mass-covering behavior of forward KL with the mode-seeking behavior of reverse KL. Derive the closed-form optimum of E_q[r] − β D(q‖p), the RLHF policy optimum that underlies DPO, and study the sample-based KL estimators k1, k2 and k3. Interpret a VAE’s KL term as an upper bound on mutual information between inputs and latents.

After this lesson you can

  • Show with a bimodal example why minimizing D(p‖q) covers mass and minimizing D(q‖p) seeks modes.
  • Derive the optimizer π_ref·exp(r/β)/Z of E_q[r] − β D(q‖π_ref) and the optimal value β log Z.
  • Implement k1, k2 and k3 and compare their bias and variance as the distributions become more separated.
  • Prove E_x D(q(z|x)‖p(z)) = I_q(X;Z) + D(q(z)‖p(z)) and interpret a VAE’s KL term as a rate.
  • Write sequence KL as a sum of token-level terms and distinguish exact token-level KL from sample estimates.

Before you start

Motivation: four KL terms and four directions

Kullback-Leibler divergence is asymmetric, and in modern AI it rarely appears as a quantity measured at the end, but as a term optimized within a loss. Whenever you see it in a paper, ask two questions: which direction is written, and which distribution supplies the samples used to estimate it? Four examples in this course:

WhereTermSamples fromWhat it does
Maximum likelihood, classical distillationKL⁡(pdatos ∥ qθ)\KL(p_{\text{datos}}\,\Vert\,q_\theta), KL⁡(pmaestro ∥ qalumno)\KL(p_{\text{maestro}}\,\Vert\,q_{\text{alumno}})data or teacherthe model must cover everything data make probable
Variational inference, ELBOKL⁡(qϕ(z∣x) ∥ p(z∣x))\KL(q_\phi(z \given x)\,\Vert\,p(z \given x))approximation qϕq_\phithe approximation stays inside posterior mass
RLHFE[r]−β KL⁡(πθ ∥ πref)\E[r] - \beta\,\KL(\pi_\theta\,\Vert\,\pi_{\text{ref}})policy πθ\pi_\thetathe policy does not move too far from the starting model
TRPO and PPOKL⁡(πviejo ∥ πθ)\KL(\pi_{\text{viejo}}\,\Vert\,\pi_\theta) as constraint or penaltyold policyeach update is a short step in policy space

The two directions produce qualitatively different solutions when the model cannot represent the target distribution (briefly seen with cross-entropy and maximum likelihood), and their optimization landscapes differ. This lesson does four things:

  1. Explain precisely why KL⁡(p ∥ q)\KL(p\,\|\,q) covers mass and KL⁡(q ∥ p)\KL(q\,\|\,p) seeks modes, and why the second has local minima.
  2. Solve max⁡qEq[r]−β KL⁡(q ∥ p)\max_q \E_q[r] - \beta\,\KL(q\,\|\,p) in closed form. Its solution is a Gibbs distribution and literally the optimal RLHF policy; inverting it yields DPO.
  3. Study estimating KL from samples when vocabulary size makes a full sum impossible: estimators k1k_1, k2k_2 and k3k_3 used by RLHF implementations, their biases, variances and a gradient trap.
  4. Interpret a variational autoencoder’s KL term as an information-theoretic rate: mutual information between data and latent plus mismatch with the prior.

Forward and reverse KL: cover mass or seek modes

Fix target distribution pp and model family Q\mathcal{Q} that does not contain it. There are two natural fitting problems.

The difference is which distribution weights integrand log⁡(p/q)\log(p/q). Forward KL weights pp: points where pp is large and qq small pay log⁡(p/q)≫0\log(p/q) \gg 0 with high weight, and where p(x)>0p(x) > 0 and q(x)=0q(x) = 0 the cost is infinite. Hence forward KL is zero-avoiding: qq must put some mass wherever pp has any, even at the cost of mass where pp has none. Reverse KL weights qq: it pays for placing mass where pp is small, with infinite cost if q(x)>0q(x) > 0 and p(x)=0p(x) = 0. Leaving a region where pp is large uncovered costs nothing because there q≈0q \approx 0 and the integrand barely weighs. Reverse KL is zero-forcing: qq prefers to shrink inside a high-density region of pp.

Forward fitting matches moments

For the Gaussian family, forward fitting has an explicit solution, explaining why it “covers.”

Proof

KL⁡(p ∥ q)=−H⁡(p)−Ep[log⁡q(X)]\KL(p\,\|\,q) = -\Ent(p) - \E_p[\log q(X)] and the first term does not depend on qq. For q=N(μ,σ2)q = \Normal(\mu, \sigma^2),

−Ep[log⁡q(X)]=log⁡σ+12log⁡(2π)+Ep[(X−μ)2]2σ2=log⁡σ+12log⁡(2π)+v+(m−μ)22σ2.-\E_p[\log q(X)] = \log\sigma + \tfrac12\log(2\pi) + \frac{\E_p[(X - \mu)^2]}{2\sigma^2} = \log\sigma + \tfrac12\log(2\pi) + \frac{v + (m - \mu)^2}{2\sigma^2}.

The minimum over μ\mu is μ=m\mu = m for any σ\sigma, and then log⁡σ+v/(2σ2)\log\sigma + v/(2\sigma^2) has derivative 1/σ−v/σ31/\sigma - v/\sigma^3, which vanishes only at σ2=v\sigma^2 = v and changes sign from negative to positive: it is the global minimum. For exponential family qη(x)=h(x)exp⁡(η⊤T(x)−A(η))q_\eta(x) = h(x)\exp(\eta\T T(x) - A(\eta)), −Ep[log⁡qη]=−Ep[log⁡h]−η⊤Ep[T]+A(η)-\E_p[\log q_\eta] = -\E_p[\log h] - \eta\T\E_p[T] + A(\eta) is convex in η\eta (because AA is) and its gradient is ∇A(η)−Ep[T]=Eqη[T]−Ep[T]\nabla A(\eta) - \E_p[T] = \E_{q_\eta}[T] - \E_p[T]. For a differentiable convex function, zero gradient is equivalent to a global minimum.

∎

Thus whatever the shape of pp, the forward fit is the Gaussian with the same mean and variance: if pp has two separated peaks, the bell sits between them and widens to span both, even though its maximum lies in the valley where pp has almost no mass. The problem is convex in natural parameters: one minimum.

Reverse fitting chooses a mode

For reverse KL there is no closed formula, but an approximation explains what we see. Let p=∑kwk N(ak,s2)p = \sum_k w_k\,\Normal(a_k, s^2) be a mixture with well-separated components and suppose qq concentrates its mass near component kk. There p(x)=wk N(x;ak,s2) (1+ε(x))p(x) = w_k\,\Normal(x; a_k, s^2)\,(1 + \eps(x)), with ε(x)≥0\eps(x) \ge 0 the relative contribution of other components, tiny near aka_k. Then

KL⁡(q ∥ p)=KL⁡(q ∥ N(ak,s2))−log⁡wk−Eq[log⁡(1+ε(X))]≈KL⁡(q ∥ N(ak,s2))−log⁡wk,\KL(q\,\|\,p) = \KL\big(q\,\|\,\Normal(a_k, s^2)\big) - \log w_k - \E_q[\log(1 + \eps(X))] \approx \KL\big(q\,\|\,\Normal(a_k, s^2)\big) - \log w_k,

which is minimized at q=N(ak,s2)q = \Normal(a_k, s^2) and is approximately −log⁡wk-\log w_k. There is a local minimum for each mode, whose value depends only on the mode weight: the global one corresponds to the heaviest mode. The broad central bell of the forward fit instead pays heavily under reverse KL because it puts mass in the valley.

InteractiveFitting a Gaussian to two peaks
Densities: pp (mixture), KL⁡(p ∥ q)\KL(p\,\|\,q) fit, and descent endpoint
−6−4−20246
Landscape of KL⁡(q ∥ p)\KL(q\,\|\,p) in the (μ,σ)(\mu, \sigma) plane, σ\sigma on a logarithmic scale
  • pp (two bells)
  • KL⁡(p ∥ q)\KL(p\,\|\,q) fit
  • descent and endpoint
  • start
  • KL⁡(q ∥ p)\KL(q\,\|\,p) minima (filled: global)
2.00
0.60
Landscape
Start (μ,σ)(\mu, \sigma)(3.50, 0.40)
Arrives at (μ,σ)(\mu, \sigma)(1.98, 0.73)
There: KL⁡(q ∥ p)\KL(q\,\|\,p) / KL⁡(p ∥ q)\KL(p\,\|\,q)0.907 / 8.158
Minima of KL⁡(q ∥ p)\KL(q\,\|\,p)0.505, 0.732, 0.907
Forward fit (μ,σ)(\mu, \sigma)(−0.40, 2.08)
There: KL⁡(q ∥ p)\KL(q\,\|\,p) / KL⁡(p ∥ q)\KL(p\,\|\,q)0.815 / 0.422
Local minimum: KL⁡(q ∥ p)=0.907\KL(q\,\|\,p) = 0.907 versus 0.505 for the global minimum. Descent cannot leave this basin: reverse KL is not convex in (μ,σ)(\mu, \sigma).
Above: mixture pp (modes at ±a\pm a with deviation 0.70.7), the KL⁡(p ∥ q)\KL(p\,\|\,q) fit (dashed) and the point reached by gradient descent on the selected divergence from the orange start. Below: the divergence landscape in the (μ,σ)(\mu, \sigma) plane, with logarithmic σ\sigma: each colored band is a level, and valleys are centers of closed bands. Outlined circles are local minima of KL⁡(q ∥ p)\KL(q\,\|\,p) (global filled) and the green point is the forward fit. Drag the start between basins, press “Another start”, switch to forward KL to see one minimum and move modes together until side minima disappear.

With initial values (modes at ±2\pm 2, deviation 0.70.7, weights 0.60.6 and 0.40.4), the forward fit is μ=−0.40\mu = -0.40, σ=2.08\sigma = 2.08, and reverse KL has three local minima:

Minimum of KL⁡(q ∥ p)\KL(q\,\Vert\,p)(μ,σ)(\mu, \sigma)KL⁡(q ∥ p)\KL(q\,\Vert\,p)Approximation
left mode (global)(−1.986, 0.720)(-1.986,\ 0.720)0.5050.505−log⁡0.6=0.511-\log 0.6 = 0.511
central bell(−0.315, 1.822)(-0.315,\ 1.822)0.7320.732
right mode(1.976, 0.733)(1.976,\ 0.733)0.9070.907−log⁡0.4=0.916-\log 0.4 = 0.916

Exact values lie slightly below −log⁡wk-\log w_k because of term −Eq[log⁡(1+ε)]≤0-\E_q[\log(1 + \eps)] \le 0: the other component adds mass and lowers the cost of the tail of qq. The central bell is a genuine local minimum (its Hessian there is positive definite), a compromise an optimizer reaches when starting near the center with large σ\sigma. For a symmetric mixture with components N(±d,1)\Normal(\pm d, 1), the quadrature cell below maps the transition: below d≈2.41d \approx 2.41 only the central minimum exists; beyond that two side minima appear and become global from d≈2.80d \approx 2.80, while the central one survives locally.

Consequence: variational inference underestimates variance

Standard variational inference minimizes KL⁡(q ∥ p)\KL(q\,\|\,p) with pp the posterior, because that direction only requires expectations under qq, which it can sample. The price is the behavior just seen, and in the cleanest case it can be calculated exactly.

That is why variational inference credible intervals are often too narrow, and why a multimodal posterior is approximated by one of its modes.

Between directions: the Rényi family

The two KLs are endpoints of a continuous family. Rényi divergence of order α∈(0,1)∪(1,∞)\alpha \in (0, 1) \cup (1, \infty) is

Dα(p ∥ q)=1α−1log⁡∑xp(x)αq(x)1−α,D_\alpha(p\,\|\,q) = \frac{1}{\alpha - 1}\log \sum_x p(x)^\alpha q(x)^{1 - \alpha},

with Dα(p ∥ q)→KL⁡(p ∥ q)D_\alpha(p\,\|\,q) \to \KL(p\,\|\,q) as α→1\alpha \to 1. For α∈(0,1)\alpha \in (0, 1) it satisfies identity Dα(p ∥ q)=α1−αD1−α(q ∥ p)D_\alpha(p\,\|\,q) = \frac{\alpha}{1 - \alpha}D_{1 - \alpha}(q\,\|\,p), so as α→0\alpha \to 0 it behaves like α KL⁡(q ∥ p)\alpha\,\KL(q\,\|\,p): minimizing over qq gradually moves from seeking modes (α→0\alpha \to 0) to covering mass (α=1\alpha = 1) and covering with even greater aversion to gaps (α>1\alpha > 1). Minka (2005) uses Amari’s alpha family in this role in message passing, and Li and Turner’s Rényi variational inference (2016) makes it a hyperparameter. We only mention it here: divergences ff and their variational representations are the subject of lesson 12.

The regularized objective and its Gibbs solution

Now the problem behind the title. You have a starting distribution pp (a pretrained model, a prior) and a scoring function rr (a reward). You want a new distribution scoring highly without moving too far from pp.

Notice the direction: KL is written with the distribution being optimized first, as in variational inference. This is reverse KL.

Proof

Taking logarithms in the definition of q∗q^\ast, at every yy with p(y)>0p(y) > 0 we have r(y)=βlog⁡q∗(y)p(y)+βlog⁡Zr(y) = \beta\log\frac{q^\ast(y)}{p(y)} + \beta\log Z. Since KL⁡(q ∥ p)<∞\KL(q\,\|\,p) < \infty, qq places mass only where p(y)>0p(y) > 0, and substituting (each summand is integrable under qq because Eq∣r∣\E_q\abs{r} and KL⁡(q ∥ p)\KL(q\,\|\,p) are finite),

J(q)=Eq[βlog⁡q∗(Y)p(Y)+βlog⁡Z−βlog⁡q(Y)p(Y)]=βlog⁡Z−β Eq[log⁡q(Y)q∗(Y)]=βlog⁡Z−β KL⁡(q ∥ q∗).J(q) = \E_q\Big[\beta\log\frac{q^\ast(Y)}{p(Y)} + \beta\log Z - \beta\log\frac{q(Y)}{p(Y)}\Big] = \beta\log Z - \beta\,\E_q\Big[\log\frac{q(Y)}{q^\ast(Y)}\Big] = \beta\log Z - \beta\,\KL(q\,\|\,q^\ast).

By Gibbs’ inequality, KL⁡(q ∥ q∗)≥0\KL(q\,\|\,q^\ast) \ge 0 with equality if and only if q=q∗q = q^\ast.

∎

This is the Gibbs variational principle from lesson 13 with energy −r-r and temperature β\beta: the Gibbs distribution relative to reference measure pp. Three immediate interpretations:

  • β\beta is a temperature. If β→∞\beta \to \infty, q∗→pq^\ast \to p: the penalty dominates. If β→0\beta \to 0, q∗q^\ast concentrates on arg max⁡{r(y):p(y)>0}\argmax\{r(y) : p(y) > 0\} (when that maximum is attained, as on any finite Y\mathcal{Y}): only reward matters, but within the support of pp. What pp declares impossible remains so for any β\beta.
  • It is exponential tilting. q∗q^\ast multiplies each probability of pp by er/βe^{r/\beta} and renormalizes. An answer very unlikely under pp needs enormous reward to gain mass: the KL penalty protects against drastic changes to rare events, not frequent ones.
  • It is a Bayesian posterior. q∗∝p(y) er(y)/βq^\ast \propto p(y)\,e^{r(y)/\beta} is Bayes’ rule with prior pp and likelihood er/βe^{r/\beta}, the probability of an event “the answer is good” proportional to er/βe^{r/\beta}. Korbak, Perez and Buckley (2022) argue that KL-penalized RLHF is better understood as inference than reward maximization.

The reward-KL frontier

As β\beta varies, qβ∗q^\ast_\beta traces a curve in plane (KL⁡,E[r])(\KL, \E[r]). This is the best reward achievable for each divergence budget.

Proof

(1) Differentiating, A′(λ)=Ep[r eλr]/Ep[eλr]=Eq∗[r]A'(\lambda) = \E_p[r\,e^{\lambda r}]/\E_p[e^{\lambda r}] = \E_{q^\ast}[r]. Also KL⁡(q∗ ∥ p)=Eq∗[λr−log⁡Z]=λA′(λ)−A(λ)\KL(q^\ast\,\|\,p) = \E_{q^\ast}[\lambda r - \log Z] = \lambda A'(\lambda) - A(\lambda). (2) By the previous theorem, Eq[r]=βlog⁡Z+β KL⁡(q ∥ p)−β KL⁡(q ∥ q∗)≤βlog⁡Z+βK=R\E_q[r] = \beta\log Z + \beta\,\KL(q\,\|\,p) - \beta\,\KL(q\,\|\,q^\ast) \le \beta\log Z + \beta K = R, because βlog⁡Z=J(q∗)=R−βK\beta\log Z = J(q^\ast) = R - \beta K. (3)  ⁣dR/ ⁣dλ=A′′(λ)=Var⁡q∗(r)>0\dd R/\dd\lambda = A''(\lambda) = \Var_{q^\ast}(r) > 0 and  ⁣dK/ ⁣dλ=λA′′(λ)\dd K/\dd\lambda = \lambda A''(\lambda), so  ⁣dR/ ⁣dK=1/λ=β\dd R/\dd K = 1/\lambda = \beta, which decreases as KK increases (because KK increases with λ\lambda): concavity.

∎

This is the same role as the slope of the rate-distortion Lagrangian: choosing β\beta chooses a frontier point by slope. A calibration detail: when β\beta is large, A(λ)≈λEp[r]+12λ2Var⁡p(r)A(\lambda) \approx \lambda\E_p[r] + \tfrac12\lambda^2\Var_p(r) and K≈Var⁡p(r)/(2β2)K \approx \Var_p(r)/(2\beta^2): KL decreases as 1/β21/\beta^2, and doubling β\beta divides divergence spending by four.

RLHF: reward minus β times KL

RLHF (Ziegler et al., 2019; Ouyang et al., 2022) starts from an instruction-tuned model πref\pi_{\text{ref}} and reward model r(x,y)r(x, y) trained on human preferences. The objective is

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

which, prompt by prompt, is the previous problem with Y\mathcal{Y} the set of responses. Its solution is

π∗(y∣x)=πref(y∣x) er(x,y)/βZ(x),Z(x)=∑yπref(y∣x) er(x,y)/β.\pi^\ast(y \given x) = \frac{\pi_{\text{ref}}(y \given x)\,e^{r(x, y)/\beta}}{Z(x)}, \qquad Z(x) = \sum_y \pi_{\text{ref}}(y \given x)\,e^{r(x, y)/\beta}.

It cannot be used as-is: Z(x)Z(x) sums over all token sequences, on the order of VTV^T terms, and π∗\pi^\ast is not explicitly autoregressive. RLHF is therefore solved with policy gradients (PPO, covered in PPO for LLMs) or reformulated to avoid ZZ (DPO, below). But the closed solution says exactly what all of it converges to under perfect optimization, enough to understand almost every phenomenon.

InteractiveThe optimal RLHF policy
Probability of each response (πref\pi_{\text{ref}} and π∗\pi^\ast) and, below, its reward rr
0.000.25ABCDEFGHIJ−10123
Reward–KL frontier traced by π∗\pi^\ast as β\beta changes; the line has slope β\beta
  • πref\pi_{\text{ref}}
  • π∗∝πref er/β\pi^\ast \propto \pi_{\text{ref}}\,e^{r/\beta} and its reward
  • reward (draggable)
  • true quality
1.00
Eπ∗[r]\E_{\pi^\ast}[r]0.731
KL⁡(π∗ ∥ πref)\KL(\pi^\ast\,\|\,\pi_{\text{ref}})0.111 nats
E[r]−β KL⁡\E[r] - \beta\,\KL0.6200
βlog⁡Z\beta \log Z0.6200
π∗(J)\pi^\ast(\text{J})0.011
Mean true quality0.688
π∗\pi^\ast redistributes the mass of πref\pi_{\text{ref}} with weights er/βe^{r/\beta}. Check the readouts that E[r]−β KL⁡=βlog⁡Z\E[r] - \beta\,\KL = \beta\log Z.
Ten responses to a prompt with probabilities under πref\pi_{\text{ref}} (gray) and π∗∝πref er/β\pi^\ast \propto \pi_{\text{ref}}\,e^{r/\beta} (blue). Below is each response's reward: drag orange points to change it. Response J is a trap: the reward model scores it 3, but πref\pi_{\text{ref}} gives it probability 0.0010.001 and its real quality (red circle) is −1-1. Below is the reward-KL frontier traced by π∗\pi^\ast as β\beta varies, with a slope-β\beta line tangent at the current point; the dashed red curve is real quality. Slowly lower β\beta from 10 to 0.05 and observe when the trap captures the mass.

With β=1\beta = 1 the policy raises mean reward from 0.520.52 (that of πref\pi_{\text{ref}}) to 0.730.73 while spending only 0.110.11 nats, and the readouts let you check identity E[r]−β KL⁡=βlog⁡Z=0.620\E[r] - \beta\,\KL = \beta\log Z = 0.620. As β\beta falls, mass first flows to H, the best legitimate response. The trap wins when 0.001 e3/β0.001\,e^{3/\beta} exceeds 0.05 e1.5/β0.05\,e^{1.5/\beta}, that is, below β=1.5/ln⁡50≈0.383\beta = 1.5/\ln 50 \approx 0.383. Thereafter model reward keeps rising toward 3 while real quality plummets to −1-1. Real quality peaks around β≈0.57\beta \approx 0.57, with KL about 0.470.47 nats.

Overoptimization and the KL budget

What the figure stages with one trap is reward-model overoptimization: rr is a learned proxy for human preference, reliable near its training distribution πref\pi_{\text{ref}} and increasingly unreliable far away. Gao, Schulman and Hilton (2022) measured it using a “gold” reward model standing in for a human: as KL from the initial policy grows, the optimizing reward model’s score keeps rising while the gold score rises, peaks and falls. They fitted simple functional forms in d=KL⁡d = \sqrt{\KL}, with coefficients varying smoothly with reward-model size. The KL penalty is the main defense against this effect and is practically managed as a budget: Ziegler et al. adjust β\beta with a proportional controller to keep KL near a target instead of fixing β\beta in advance (covered in KL penalty control).

A useful budget reference: the best-of-nn policy, which generates nn responses from πref\pi_{\text{ref}} and keeps the highest-reward one, has

KL⁡(πbon ∥ πref)=log⁡n−n−1n\KL(\pi_{\text{bon}}\,\|\,\pi_{\text{ref}}) = \log n - \frac{n - 1}{n}

when reward has a continuous distribution (no ties). The reason: quantile UU of the selected response is the maximum of nn uniform variables, with density nun−1n u^{n-1}, and KL is E[log⁡(nUn−1)]=log⁡n+(n−1)E[log⁡U]=log⁡n−(n−1)/n\E[\log(n U^{n-1})] = \log n + (n - 1)\E[\log U] = \log n - (n - 1)/n. With ties the formula is only an upper bound (Beirami et al., 2024). For n=4n = 4 it is 0.640.64 nats; for n=64n = 64, 3.173.17. KL growing only as log⁡n\log n explains why best-of-nn is such a strong baseline.

Sequence KL is a sum of token KLs

A language policy generates y=(y1,…,yT)y = (y_1, \dots, y_T) token by token, π(y∣x)=∏tπ(yt∣x,y<t)\pi(y \given x) = \prod_t \pi(y_t \given x, y_{<t}). KL between two such policies decomposes similarly.

Proof

This is the KL chain rule applied T−1T - 1 times, or directly: log⁡π(y)πref(y)=∑tlog⁡π(yt∣y<t)πref(yt∣y<t)\log\frac{\pi(y)}{\pi_{\text{ref}}(y)} = \sum_t \log\frac{\pi(y_t \given y_{<t})}{\pi_{\text{ref}}(y_t \given y_{<t})}; taking expectations under π\pi and conditioning each summand on y<ty_{<t}, the inner expectation of summand tt is token KL at prefix y<ty_{<t}. After the end token both conditionals coincide and contribute zero.

∎

The theorem separates two things often confused in code:

  • Exact token KL at a visited prefix, ∑vπ(v∣y<t)log⁡π(v∣y<t)πref(v∣y<t)\sum_{v} \pi(v \given y_{<t})\log\frac{\pi(v \given y_{<t})}{\pi_{\text{ref}}(v \given y_{<t})}, sums over the whole vocabulary. It is cheap because both models’ logits are already calculated at that step.
  • The sample estimate uses only the generated token: log⁡π(yt∣y<t)πref(yt∣y<t)\log\frac{\pi(y_t \given y_{<t})}{\pi_{\text{ref}}(y_t \given y_{<t})}. Its sum over the response is an unbiased but noisy sequence-KL estimator; it enters as token reward in Ziegler et al. and InstructGPT implementations: rt=−βlog⁡π(yt)πref(yt)r_t = -\beta\log\frac{\pi(y_t)}{\pi_{\text{ref}}(y_t)} at each token and model reward added at the last.

Both are unbiased estimators of the same quantity averaged over sequences sampled from π\pi. The second has token-choice variance; the first eliminates it at each step. You will measure this in a small model and a real language model below.

Which direction and which samples?

RLHF’s KL is reverse KL⁡(π ∥ πref)\KL(\pi\,\|\,\pi_{\text{ref}}), estimated from policy samples. As above, it penalizes without bound π\pi placing mass where πref\pi_{\text{ref}} does not, but penalizes little when π\pi abandons responses πref\pi_{\text{ref}} considered plausible: discarding responses with mass mm under πref\pi_{\text{ref}} costs at least −log⁡(1−m)-\log(1 - m) nats (the cost of conditioning πref\pi_{\text{ref}} on the remainder), a finite amount, 0.360.36 nats for m=0.3m = 0.3. Thus the KL penalty slows drift toward rare text without preventing diversity loss typical of RLHF-tuned models. Classical distillation uses the other direction, KL⁡(pmaestro ∥ qalumno)\KL(p_{\text{maestro}}\,\|\,q_{\text{alumno}}), with teacher outputs: the student must cover everything the teacher considers possible. Reverse-KL variants using student samples (“on-policy” distillation) inherit mode seeking; divergence direction in distillation is covered in m21.

From the closed solution to DPO

The formula for π∗\pi^\ast can be read backward: any policy π\pi with the same support as πref\pi_{\text{ref}} is optimal for reward

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

Term βlog⁡Z(x)\beta\log Z(x) depends on the prompt but not the response. Human preferences are modeled with the Bradley-Terry model, P(yw≻yl∣x)=σ(r(x,yw)−r(x,yl))\Pr(y_w \succ y_l \given x) = \sigmoid(r(x, y_w) - r(x, y_l)), which depends only on reward differences for the same prompt, so Z(x)Z(x) cancels:

P(yw≻yl∣x)=σ(βlog⁡π(yw∣x)πref(yw∣x)−βlog⁡π(yl∣x)πref(yl∣x)).\Pr(y_w \succ y_l \given x) = \sigmoid\Big(\beta\log\frac{\pi(y_w \given x)}{\pi_{\text{ref}}(y_w \given x)} - \beta\log\frac{\pi(y_l \given x)}{\pi_{\text{ref}}(y_l \given x)}\Big).

Fitting πθ\pi_\theta by maximum likelihood of those probabilities on preference pairs is DPO (Rafailov et al., 2023): loss is −Elog⁡σ(⋅)-\E\log\sigmoid(\cdot), without an explicit reward model or sampling from the policy. Quantity βlog⁡(πθ/πref)\beta\log(\pi_\theta/\pi_{\text{ref}}) is the implicit reward. It rests on the Gibbs theorem: DPO optimizes the same KL-regularized objective as RLHF but parameterizes reward through the optimal policy it would induce. The module 20 DPO lesson develops the gradient and its issues.

Estimating KL from samples: k1, k2 and k3

With vocabularies of tens of thousands of tokens and long sequences, sequence KL cannot be summed in full, and many implementations do not even save full reference logits, only the generated token’s log probability. We need to estimate KL⁡(q ∥ p)\KL(q\,\|\,p) with samples x∼qx \sim q and ratio ρ(x)=p(x)/q(x)\rho(x) = p(x)/q(x). This is a Monte Carlo estimator, and the task is choosing which function of ρ\rho to average.

Proof

(1) Eq[−log⁡ρ]=Eq[log⁡(q/p)]\E_q[-\log\rho] = \E_q[\log(q/p)] is the definition, and −log⁡ρ<0-\log\rho < 0 if and only if ρ>1\rho > 1. (3) log⁡t≤t−1\log t \le t - 1 for every t>0t > 0 gives k3≥0k_3 \ge 0, with equality only at ρ=1\rho = 1. Since pp and qq have the same support, Eq[ρ]=∑x:q(x)>0p(x)=1\E_q[\rho] = \sum_{x: q(x) > 0} p(x) = 1, hence Eq[k3]=1−1+Eq[−log⁡ρ]=KL⁡(q ∥ p)\E_q[k_3] = 1 - 1 + \E_q[-\log\rho] = \KL(q\,\|\,p). (2) k2≥0k_2 \ge 0 is immediate. By (3), KL⁡(q ∥ p)=Eq[eℓ−1−ℓ]=Eq[12ℓ2+16ℓ3+⋯ ]\KL(q\,\|\,p) = \E_q[e^\ell - 1 - \ell] = \E_q[\tfrac12\ell^2 + \tfrac16\ell^3 + \cdots], so Eq[k2]−KL⁡(q ∥ p)=−Eq[16ℓ3+124ℓ4+⋯ ]=O(ε3)\E_q[k_2] - \KL(q\,\|\,p) = -\E_q[\tfrac16\ell^3 + \tfrac1{24}\ell^4 + \cdots] = \bigO(\eps^3), while KL⁡\KL is of order Eq[ℓ2]=O(ε2)\E_q[\ell^2] = \bigO(\eps^2).

∎

The idea of k3k_3 is a control variate: ρ−1\rho - 1 has zero mean under qq, so k1+λ(ρ−1)k_1 + \lambda(\rho - 1) is unbiased for any λ\lambda, and λ=1\lambda = 1 is the unique value making it nonnegative, because it turns the estimator into the Bregman distance of −log⁡-\log between ρ\rho and 1. When p≈qp \approx q, k1k_1 and ρ−1\rho - 1 are strongly oppositely correlated and their sum cancels nearly all noise.

For two Gaussians everything is explicit. With q=N(0,1)q = \Normal(0, 1) and p=N(μ,1)p = \Normal(\mu, 1), ℓ=μx−μ2/2\ell = \mu x - \mu^2/2 and KL⁡(q ∥ p)=μ2/2\KL(q\,\|\,p) = \mu^2/2 (the KL between Gaussians). Then:

MeanStandard deviation per sampleDeviation relative to KL, μ→0\mu \to 0
k1k_1μ2/2\mu^2/2μ\mu2/μ→∞2/\mu \to \infty
k2k_2μ2/2+μ4/8\mu^2/2 + \mu^4/8μ21/2+μ2/4\mu^2\sqrt{1/2 + \mu^2/4}2\sqrt 2
k3k_3μ2/2\mu^2/2eμ2−1−μ2\sqrt{e^{\mu^2} - 1 - \mu^2}2\sqrt 2

The k2k_2 row follows from ℓ∼N(−μ2/2,μ2)\ell \sim \Normal(-\mu^2/2, \mu^2) and a normal N(a,s2)\Normal(a, s^2) having second moment a2+s2a^2 + s^2 and Var⁡(ℓ2)=2s4+4a2s2\Var(\ell^2) = 2s^4 + 4a^2s^2. Near qq, k2k_2 is as low-noise as k3k_3; its price is bias, whose relative part μ2/4\mu^2/4 becomes large as distributions separate. The k3k_3 row follows from Var⁡(ρ)=eμ2−1\Var(\rho) = e^{\mu^2} - 1, Var⁡(ℓ)=μ2\Var(\ell) = \mu^2 and Cov⁡(ρ,ℓ)=Eq[ρℓ]−Eq[ℓ]=KL⁡(p ∥ q)+μ2/2=μ2\Cov(\rho, \ell) = \E_q[\rho\ell] - \E_q[\ell] = \KL(p\,\|\,q) + \mu^2/2 = \mu^2. For close distributions, relative deviation of k1k_1 explodes while that of k3k_3 stays at 2\sqrt 2: for μ=0.1\mu = 0.1 (KL =0.005= 0.005), k1k_1 has deviation twenty times the quantity measured. But that of k3k_3 grows as eμ2/2e^{\mu^2/2} and exceeds that of k1k_1 when eμ2=1+2μ2e^{\mu^2} = 1 + 2\mu^2, i.e. from μ≈1.12\mu \approx 1.12: when pp places mass where qq barely does, ρ\rho has a heavy tail (heavy-tailed Monte Carlo). The fraction of samples with k1<0k_1 < 0 is P(x>μ/2)=1−Φ(μ/2)\Pr(x > \mu/2) = 1 - \Phi(\mu/2): 40 %40\,\% with μ=0.5\mu = 0.5.

Interactivek1, k2 and k3: bias and variance
Histograms of 3,000 estimates of each type; the solid line is the true KL and the dashed line is the mean
Distributions
0.50
Samples per estimate NN
KL⁡(q ∥ p)\KL(q\,\|\,p) true…
Each histogram contains 3000 estimates of KL⁡(q ∥ p)\KL(q\,\|\,p), each the mean of NN samples from qq. The solid vertical line across all three is true KL, the dashed line in each row is the mean estimate, and the dotted line marks zero. With close distributions (small μ\mu) and N=1N = 1, k1k_1 is centered on truth but much wider, with substantial negative mass, while k3k_3 is narrow. Move μ\mu toward 2.5: k2k_2 separates from truth (bias μ4/8\mu^4/8), and k3k_3, still unbiased, develops a long right tail with most estimates below its mean. Switch to categorical and increase NN to see everything narrow as 1/N1/\sqrt{N}.

Two practical consequences. The standard deviation of the average falls as 1/N1/\sqrt{N} (Monte Carlo error), so estimator differences matter most when used per token or in small batches, exactly the RLHF setting. And since k1k_1 is negative for many tokens, clipping it to zero “because KL cannot be negative” is tempting: that turns an unbiased estimator into an upward-biased one and the penalty no longer corresponds to any divergence. For nonnegative per-token values use k3k_3, not max⁡(k1,0)\max(k_1, 0).

The value is not the gradient

In RLHF the estimator is not merely reported: it is differentiated. Several implementations add estimated KL directly to the loss and differentiate with respect to parameters holding the sample fixed. An estimator unbiased for KL value does not imply its gradient is unbiased for the KL gradient.

Proof

Write s=∇θlog⁡πθ(y)s = \nabla_\theta\log\pi_\theta(y), the score function, with Ey[s]=∑y∇πθ(y)=0\E_y[s] = \sum_y \nabla\pi_\theta(y) = \vb{0}. With k1=log⁡πθ(y)−log⁡πref(y)k_1 = \log\pi_\theta(y) - \log\pi_{\text{ref}}(y), ∇k1=s\nabla k_1 = s and its mean is zero. With k2k_2, ∇k2=log⁡πθ(y)πref(y) s\nabla k_2 = \log\frac{\pi_\theta(y)}{\pi_{\text{ref}}(y)}\,s, whose mean is ∑y∇πθ(y)log⁡πθ(y)πref(y)=∇KL⁡(πθ ∥ πref)\sum_y \nabla\pi_\theta(y)\log\frac{\pi_\theta(y)}{\pi_{\text{ref}}(y)} = \nabla\KL(\pi_\theta\,\|\,\pi_{\text{ref}}), because the other term in the KL derivative is ∑y∇πθ(y)=0\sum_y \nabla\pi_\theta(y) = \vb{0}. With k3=ρ−1+log⁡πθ(y)−log⁡πref(y)k_3 = \rho - 1 + \log\pi_\theta(y) - \log\pi_{\text{ref}}(y), ∇k3=−ρ s+s\nabla k_3 = -\rho\,s + s, whose mean is −∑yπref(y)∇log⁡πθ(y)=∇θ(−∑yπref(y)log⁡πθ(y))=∇θKL⁡(πref ∥ πθ)-\sum_y \pi_{\text{ref}}(y)\nabla\log\pi_\theta(y) = \nabla_\theta\big(-\sum_y \pi_{\text{ref}}(y)\log\pi_\theta(y)\big) = \nabla_\theta\KL(\pi_{\text{ref}}\,\|\,\pi_\theta).

∎

That is: k1k_1 used as a loss regularizes nothing on average; k2k_2 gives the objective’s reverse-KL gradient; and k3k_3, preferred for the value, gives the forward-KL gradient as a loss. GRPO (Shao et al., 2024) uses k3k_3 per token as a loss term, and Tang and Munos (2025) identified precisely this discrepancy. Near πref\pi_{\text{ref}} both directions agree to second order and the effect is small; far away, not. Rule of thumb: if KL enters reward (and gradient passes through the policy-gradient term), a value estimator suffices; if it enters loss and is differentiated, consider the resulting gradient. The last implementation cell checks this numerically.

VAEs: the KL term is a rate

A variational autoencoder has encoder qϕ(z∣x)q_\phi(z \given x), decoder pθ(x∣z)p_\theta(x \given z) and prior p(z)p(z), usually N(0,I)\Normal(\vb{0}, \mat{I}). It trains by maximizing the evidence lower bound (ELBO), obtained by writing log likelihood as

log⁡pθ(x)=Eqϕ(z∣x)[log⁡pθ(x∣z)]−KL⁡(qϕ(z∣x) ∥ p(z))⏟ELBO(x)+KL⁡(qϕ(z∣x) ∥ pθ(z∣x)).\log p_\theta(x) = \underbrace{\E_{q_\phi(z \given x)}[\log p_\theta(x \given z)] - \KL\big(q_\phi(z \given x)\,\|\,p(z)\big)}_{\text{ELBO}(x)} + \KL\big(q_\phi(z \given x)\,\|\,p_\theta(z \given x)\big).

The last term, reverse KL to the true posterior, is the bound gap and cannot be calculated; this is why the VAE is variational inference, with the mode-seeking behavior discussed above. But the KL term inside ELBO has a precise information-theoretic interpretation. Alemi et al. (2018) call D=−E[log⁡pθ(x∣z)]D = -\E[\log p_\theta(x \given z)] distortion and call

R=Ex∼pdatos[KL⁡(qϕ(z∣x) ∥ p(z))].R = \E_{x\sim p_{\text{datos}}}\Big[\KL\big(q_\phi(z \given x)\,\|\,p(z)\big)\Big].

the rate. To interpret it, look at the joint distribution defined by the encoder on the data, q(x,z)=pdatos(x) qϕ(z∣x)q(x, z) = p_{\text{datos}}(x)\,q_\phi(z \given x), and its marginal in zz, the aggregate posterior q(z)=Ex[qϕ(z∣x)]q(z) = \E_{x}[q_\phi(z \given x)].

Proof

For each (x,z)(x, z) with q(z∣x)>0q(z \given x) > 0, log⁡q(z∣x)p(z)=log⁡q(z∣x)q(z)+log⁡q(z)p(z)\log\frac{q(z \given x)}{p(z)} = \log\frac{q(z \given x)}{q(z)} + \log\frac{q(z)}{p(z)}. Take expectations under q(x,z)q(x, z). The first summand gives Eq(x,z)[log⁡q(x,z)pdatos(x) q(z)]=Iq(X;Z)\E_{q(x,z)}\big[\log\frac{q(x, z)}{p_{\text{datos}}(x)\,q(z)}\big] = I_q(X; Z), mutual information. The second depends only on zz, whose marginal under q(x,z)q(x, z) is q(z)q(z), and gives KL⁡(q(z) ∥ p(z))\KL(q(z)\,\|\,p(z)). The inequality follows from KL⁡≥0\KL \ge 0 and equality from Gibbs’ inequality.

∎

We call this the variational rate bound: the ELBO’s KL term averaged over data upper-bounds the information the latent carries about xx, and the excess is the cost of a prior mismatching the true code distribution. This is the same calculation as rate-distortion: the encoder is a channel X→ZX \to Z and RR measures the nats passing through it. Alemi et al. complete the picture with H−D≤Iq(X;Z)≤RH - D \le I_q(X; Z) \le R, where HH is data entropy: rate bounds information above and reconstruction quality bounds it below.

InteractiveA VAE rate decomposed
Joint q(x,z)=p(x) q(z ∣ x)q(x, z) = p(x)\,q(z\,|\,x)
q(z)q(z) y p(z)p(z)
The rate decomposed: ExKL⁡(q(z∣x) ∥ p(z))=Iq(X;Z)+KL⁡(q(z) ∥ p(z))\E_x \KL(q(z|x)\,\|\,p(z)) = I_q(X;Z) + \KL(q(z)\,\|\,p(z))
0 nats123
  • Iq(X;Z)I_q(X;Z): information about xx
  • KL⁡(q(z) ∥ p(z))\KL(q(z)\,\|\,p(z)): mismatch with the prior
  • encoder mean ax+ba x + b
  • prior p(z)=N(0,1)p(z) = \mathcal{N}(0, 1)
0.45
0.00
0.30
Rate ExKL⁡(q(z∣x) ∥ p(z))\E_x \KL(q(z|x)\,\|\,p(z))1.179 nats
Iq(X;Z)I_q(X; Z)0.894 nats
KL⁡(q(z) ∥ p(z))\KL(q(z)\,\|\,p(z))0.286 nats
Mean / variance of q(z)q(z)0.00 / 0.951
Useful latent: 0.89 nats of mutual information and only 0.29 of mismatch with the prior. Lower σe\sigma_e so that II grows as −log⁡σe-\log\sigma_e.
One-dimensional data, a mixture of two bells at ±2\pm 2; toy encoder q(z∣x)=N(ax+b,σe2)q(z \given x) = \Normal(a x + b, \sigma_e^2); prior N(0,1)\Normal(0, 1). Left, joint density q(x,z)q(x, z) with encoder mean line; right, aggregate posterior q(z)q(z) (blue) against prior (dashed). The bar splits rate, closed-form here, into mutual information and marginal mismatch. Press “Collapse”: zero rate and useless latent. Press “Shifted”: positive rate yet zero information. With “Useful”, lower σe\sigma_e and watch information grow; with “Too wide”, see how much rate is lost to mismatch.

Initially (a=0.45a = 0.45, b=0b = 0, σe=0.3\sigma_e = 0.3) rate is 1.1791.179 nats, of which 0.8940.894 is mutual information and 0.2860.286 mismatch: the aggregate posterior is bimodal and the prior a single bell. Extreme cases illustrate two misreadings:

  • Posterior collapse (posterior collapse). If q(z∣x)=p(z)q(z \given x) = p(z) for every xx, rate is zero, ELBO pays nothing for the latent and Iq(X;Z)=0I_q(X; Z) = 0: the latent knows nothing about data. This occurs when the decoder can model data on its own (a powerful autoregressive decoder), because each nat of rate is then cost without benefit. Small VAE KL is compatible with both a useful and a dead latent.
  • Rate without information. With a=0a = 0 and b=1.5b = 1.5, the encoder ignores xx but shifts all codes: R=b2/2=1.125R = b^2/2 = 1.125 nats and I=0I = 0. Large KL also does not certify a useful latent.

What to monitor is Iq(X;Z)I_q(X; Z), not rate. Collapse remedies (KL warmup, “free bits” per dimension; see KL annealing and free bits) and β-VAE (Higgins et al., 2017), minimizing D+βRD + \beta R, can be understood as choosing a point on the rate-distortion curve: β>1\beta > 1 buys a more compressed and, according to its authors, more disentangled code; β<1\beta < 1 lets more information through. And since excess KL⁡(q(z) ∥ p(z))\KL(q(z)\,\|\,p(z)) is wasted rate, another family of improvements learns a more expressive prior closer to the aggregate posterior.

Implementation from scratch

First, mode seeking: both KLs by quadrature on a grid and a derivative-free optimizer from several starts. Parameterize qq by (μ,log⁡σ)(\mu, \log\sigma) to avoid constraints.

[ ]Mode seeking with quadratureBrowser
import numpy as np
from scipy.optimize import minimize
from scipy.stats import norm

x = np.linspace(-12, 12, 1201)
dx = x[1] - x[0]

def mezcla(a, w, s=0.7):
    """Densidad de w N(-a, s²) + (1 - w) N(a, s²) en la malla."""
    return w * norm.pdf(x, -a, s) + (1 - w) * norm.pdf(x, a, s)

def kl(p, q):
    """D(p‖q) por cuadratura (regla del rectángulo), con 0 log 0 = 0."""
    m = p > 1e-300
    return np.sum(p[m] * (np.log(p[m]) - np.log(np.maximum(q[m], 1e-300)))) * dx

def gauss(th):                        # th = (mu, log sigma): sin restricciones
    return norm.pdf(x, th[0], np.exp(th[1]))

def ajustar(f, inicio):
    r = minimize(f, inicio, method="Nelder-Mead", options=dict(xatol=1e-7, fatol=1e-11, maxiter=4000))
    return r.x[0], np.exp(r.x[1]), r.fun

p = mezcla(2.0, 0.6)
m = np.sum(p * x) * dx
s = np.sqrt(np.sum(p * (x - m) ** 2) * dx)
mu_f, s_f, v_f = ajustar(lambda th: kl(p, gauss(th)), [1.0, 0.0])
print(f"KL directa: momentos (μ, σ) = ({m:.4f}, {s:.4f})   optimizador = ({mu_f:.4f}, {s_f:.4f})   D(p‖q) = {v_f:.4f}")

print("KL inversa desde varios arranques:")
for mu0 in [-3.0, 0.0, 3.0]:
    mu, sg, v = ajustar(lambda th: kl(gauss(th), p), [mu0, 0.0])
    print(f"  μ0 = {mu0:+.0f}  ->  (μ, σ) = ({mu:+.4f}, {sg:.4f})   D(q‖p) = {v:.4f}")
print(f"-log 0.6 = {-np.log(0.6):.4f},  -log 0.4 = {-np.log(0.4):.4f}")

# mezcla simétrica de N(±d, 1): ¿desde qué separación existen los mínimos laterales?
print("\n   d    mínimo central (σ, D)     arranque en μ0 = d (μ, D)")
for d in [2.4, 2.45, 2.8, 3.0]:
    pd = mezcla(d, 0.5, 1.0)
    _, sc, vc = ajustar(lambda th: kl(gauss(th), pd), [0.0, 0.3])
    ml, _, vl = ajustar(lambda th: kl(gauss(th), pd), [d, 0.0])
    print(f"  {d:4.2f}   ({sc:.3f}, {vc:.4f})          ({ml:+.3f}, {vl:.4f})")

The optimizer confirms forward-KL moment matching and finds the three reverse-KL minima depending on start. In the symmetric mixture, with d=2.4d = 2.4 starting at a mode returns to the center (μ=0\mu = 0): no side minimum exists. With d=2.45d = 2.45 one exists but is worse than the central one; with d=2.8d = 2.8 they tie, and with d=3d = 3 the side one is better (0.6890.689 versus 0.8400.840).

Now toy RLHF with exact solution. A tabular autoregressive policy over length-3 sequences from a 4-token vocabulary (one logit vector per prefix, 1+4+16=211 + 4 + 16 = 21 prefixes), a random reference and arbitrary reward. We maximize the exact objective, summing all 64 sequences, with its exact gradient (without sampling: sample-estimated policy gradients are covered in m22), and check that we reach πref er/β/Z\pi_{\text{ref}}\,e^{r/\beta}/Z.

[ ]Toy RLHF with exact solutionBrowser
import numpy as np
from itertools import product
from scipy.optimize import minimize

V, T, beta = 4, 3, 0.5
rng = np.random.default_rng(0)
prefijos = [()] + [(a,) for a in range(V)] + list(product(range(V), repeat=2))
idx = {h: i for i, h in enumerate(prefijos)}
secs = list(product(range(V), repeat=T))                      # las 64 secuencias
H = np.array([[idx[s[:t]] for t in range(T)] for s in secs])  # prefijo visitado en cada paso
Y = np.array(secs)                                            # token elegido en cada paso

def log_softmax(z):
    z = z - z.max(-1, keepdims=True)
    return z - np.log(np.exp(z).sum(-1, keepdims=True))

def logp_secs(theta):
    """log π(y) = Σ_t log π(y_t | y_<t) para las 64 secuencias."""
    return log_softmax(theta)[H, Y].sum(1)

theta_ref = rng.normal(size=(len(prefijos), V))
lp_ref = logp_secs(theta_ref)
r = (Y == 3).sum(1) - 0.8 * (Y[:, 0] == Y[:, 1])      # premia el token 3 y castiga repetir el primero

def menos_J(flat):
    """−J(θ) y su gradiente exacto, sumando sobre las 64 secuencias."""
    theta = flat.reshape(theta_ref.shape)
    lp = logp_secs(theta)
    pi = np.exp(lp)
    peso = pi * (r - beta * (lp - lp_ref))
    # ∂J/∂θ[h, a] = Σ_y peso(y) Σ_t 1[h_t = h] (1[y_t = a] − π(a | h))
    probs = np.exp(log_softmax(theta))
    g = np.zeros_like(theta)
    for t in range(T):
        np.add.at(g, (H[:, t], Y[:, t]), peso)
        np.add.at(g, H[:, t], -peso[:, None] * probs[H[:, t]])
    return -peso.sum(), -g.ravel()

res = minimize(menos_J, theta_ref.ravel(), jac=True, method="L-BFGS-B",
               options=dict(ftol=1e-15, gtol=1e-12, maxiter=5000))
theta_opt = res.x.reshape(theta_ref.shape)
lp_opt = logp_secs(theta_opt)
pi_opt = np.exp(lp_opt)

logZ = np.log(np.sum(np.exp(lp_ref + r / beta)))
pi_star = np.exp(lp_ref + r / beta - logZ)              # la solución de Gibbs
kl_opt = pi_opt @ (lp_opt - lp_ref)
print("iteraciones:", res.nit)
print("max |π_θ − π*| =", np.abs(pi_opt - pi_star).max())
print(f"J(θ) = {-res.fun:.10f}    β log Z = {beta * logZ:.10f}")
print(f"E[r]: π_ref {np.exp(lp_ref) @ r:.4f} -> π* {pi_opt @ r:.4f}    KL(π*‖π_ref) = {kl_opt:.4f}")

The generic optimizer, which knows nothing of Gibbs distributions, converges to it with error of order 10−810^{-8}, and attained value βlog⁡Z\beta\log Z. With the optimal policy calculated, check the chain rule and compare three sequence-KL estimators: the sum of k1k_1 per token, the sum of k3k_3 per token and the sum of exact token KL at visited prefixes.

[ ]Sequence KL: chain rule and token estimatorsBrowser
lq = log_softmax(theta_opt)                         # log π*(a | h) en cada prefijo
lr_ = log_softmax(theta_ref)                        # log π_ref(a | h)
kl_tok = np.sum(np.exp(lq) * (lq - lr_), axis=1)    # KL exacta por token en cada prefijo

print(f"KL de secuencias {kl_opt:.10f}   suma de KL por token {pi_opt @ kl_tok[H].sum(1):.10f}")

rng = np.random.default_rng(1)
B, rep = 16, 2000                                   # 2000 lotes de 16 secuencias
y_idx = rng.choice(len(secs), size=(rep, B), p=pi_opt / pi_opt.sum())
h, yy = H[y_idx], Y[y_idx]                          # formas (rep, B, T)
log_rho = lr_[h, yy] - lq[h, yy]                    # log(π_ref / π*) del token muestreado
est = {
    "k1 por token": (-log_rho).sum(-1).mean(-1),
    "k3 por token": (np.expm1(log_rho) - log_rho).sum(-1).mean(-1),
    "KL exacta por token": kl_tok[h].sum(-1).mean(-1),
}
for k, v in est.items():
    print(f"  {k:20s} media {v.mean():.4f}   desviación entre lotes {v.std(ddof=1):.4f}")
print(f"tokens con k1 < 0: {np.mean(log_rho > 0):.1%}")

All three are unbiased and give true KL on average. The sum of exact token KLs has about three times smaller deviation than the others because it retains only randomness of visited prefixes, not of each selected token. Here k3k_3 does not improve k1k_1: token distributions are far apart (total KL is 0.870.87 nats over three tokens) and we are in the regime where ρ\rho has a tail.

The estimator-section results in code: closed formulas for two Gaussians against simulation, and the gradient theorem checked with finite differences on a categorical distribution.

[ ]Estimators: closed formulas and gradientsBrowser
import numpy as np
from scipy.stats import norm

rng = np.random.default_rng(0)
x = rng.normal(size=400_000)                        # muestras de q = N(0, 1)
print("  μ     KL    E[k2] teo/sim    sd k1 teo/sim   sd k2 teo/sim   sd k3 teo/sim   P(k1<0) teo/sim")
for mu in [0.1, 0.5, 1.0, 1.5]:
    l = mu * x - mu**2 / 2                          # log ρ con p = N(μ, 1)
    k1, k2, k3 = -l, 0.5 * l**2, np.expm1(l) - l
    print(f"{mu:4.1f}  {mu**2/2:.3f}   {mu**2/2 + mu**4/8:.4f}/{k2.mean():.4f}   "
          f"{mu:.3f}/{k1.std():.3f}     {mu**2 * np.sqrt(0.5 + mu**2 / 4):.3f}/{k2.std():.3f}     "
          f"{np.sqrt(np.exp(mu**2) - 1 - mu**2):.3f}/{k3.std():.3f}     {1 - norm.cdf(mu / 2):.3f}/{np.mean(k1 < 0):.3f}")

# gradientes esperados de cada estimador usado como pérdida (muestra fija), por enumeración
K = 5
th, th_ref = rng.normal(size=K), rng.normal(size=K)
sm = lambda z: np.exp(z - z.max()) / np.exp(z - z.max()).sum()
pi, pr = sm(th), sm(th_ref)
score = np.eye(K) - pi                              # fila y: ∇_θ log π(y)
lr = np.log(pi / pr)
g1 = pi @ score
g2 = pi @ (lr[:, None] * score)
g3 = pi @ ((1 - pr / pi)[:, None] * score)
def dif(f, h=1e-6):
    return np.array([(f(th + h * e) - f(th - h * e)) / (2 * h) for e in np.eye(K)])
kl_inv = lambda t: np.sum(sm(t) * np.log(sm(t) / pr))
kl_dir = lambda t: np.sum(pr * np.log(pr / sm(t)))
print("\n|E∇k1|                  =", np.abs(g1).max())
print("|E∇k2 − ∇KL(π‖π_ref)|  =", np.abs(g2 - dif(kl_inv)).max())
print("|E∇k3 − ∇KL(π_ref‖π)|  =", np.abs(g3 - dif(kl_dir)).max())
print("|E∇k3 − ∇KL(π‖π_ref)|  =", np.abs(g3 - dif(kl_inv)).max(), " (no es la inversa)")

The table formulas match simulation (with μ=1.5\mu = 1.5 the deviation of k3k_3 already exceeds that of k1k_1 and its sample estimate is noisy, another aspect of the heavy tail), and expected gradients match the theorem to finite-difference precision.

Finally, the figure’s VAE rate decomposition: closed-form rate, marginal mismatch by quadrature, mutual information from entropy difference h(Z)−h(Z∣X)h(Z) - h(Z \given X) and an independent Monte Carlo estimate of Iq(X;Z)=E[log⁡q(z∣x)−log⁡q(z)]I_q(X;Z) = \E[\log q(z \given x) - \log q(z)].

[ ]A toy VAE rate decomposedBrowser
import numpy as np
from scipy.stats import norm

m, s = 2.0, 0.5                                   # datos: ½ N(−2, 0.5²) + ½ N(2, 0.5²)
z = np.linspace(-12, 12, 12001)
dz = z[1] - z[0]

def tasa_descompuesta(a, b, se):
    R = 0.5 * (se**2 + a**2 * (m**2 + s**2) + b**2 - 1 - np.log(se**2))   # E_x KL(N(ax+b, se²) ‖ N(0,1))
    sz = np.sqrt(a**2 * s**2 + se**2)
    qz = 0.5 * norm.pdf(z, -a * m + b, sz) + 0.5 * norm.pdf(z, a * m + b, sz)  # marginal agregada exacta
    ok = qz > 1e-300
    Dm = np.sum(qz[ok] * np.log(qz[ok] / norm.pdf(z[ok]))) * dz
    I = -np.sum(qz[ok] * np.log(qz[ok])) * dz - 0.5 * np.log(2 * np.pi * np.e * se**2)
    return R, I, Dm, sz

rng = np.random.default_rng(0)
for nombre, (a, b, se) in {"útil": (0.45, 0, 0.3), "colapso": (0, 0, 1.0),
                           "desplazado": (0, 1.5, 1.0), "demasiado ancho": (1.2, 0, 0.3)}.items():
    R, I, Dm, sz = tasa_descompuesta(a, b, se)
    # Monte Carlo: x de los datos, z del codificador, log q(z|x) − log q(z)
    xs = rng.choice([-m, m], size=200_000) + s * rng.normal(size=200_000)
    zs = a * xs + b + se * rng.normal(size=xs.size)
    lq = 0.5 * norm.pdf(zs, -a * m + b, sz) + 0.5 * norm.pdf(zs, a * m + b, sz)
    I_mc = np.mean(norm.logpdf(zs, a * xs + b, se) - np.log(lq))
    print(f"{nombre:16s} tasa {R:.4f} = I {I:.4f} + KL marginal {Dm:.4f}  (suma {I + Dm:.4f});  I por MC {I_mc:.4f}")

All three routes agree: closed-form rate is the sum of mutual information and mismatch, and the Monte Carlo information estimate confirms that in “collapse” and “shifted” the latent carries nothing.

With libraries and in a real language model

For distributions with closed-form KL, PyTorch has a registry of exact formulas; otherwise estimate as you just did:

import torch
from torch.distributions import Normal, Categorical, kl_divergence

q, p = Normal(torch.tensor(0.0), torch.tensor(1.0)), Normal(torch.tensor(0.5), torch.tensor(1.0))
kl_divergence(q, p)                       # D(q‖p) exacta: 0.125
x = q.sample((4096,))
log_rho = p.log_prob(x) - q.log_prob(x)
k3 = (torch.expm1(log_rho) - log_rho).mean()

# KL exacta por token entre dos políticas, a partir de los logits de un paso
logits_pol, logits_ref = torch.randn(8, 32000), torch.randn(8, 32000)
kl_tok = kl_divergence(Categorical(logits=logits_pol), Categorical(logits=logits_ref))  # forma (8,)

RLHF libraries expose the estimator as a configuration option (verl and OpenRLHF, for example, allow variants of k1k_1, k2k_2 and k3k_3); know which yours uses and whether it enters reward or loss.

The next cell compares them in a real language model. The reference is SmolLM2-135M (Apache-2.0, revision pinned in code) and the “policy” is the same model sampled at temperature 0.70.7, concentrating each token distribution: π(⋅∣h)∝πref(⋅∣h)1/0.7\pi(\cdot \given h) \propto \pi_{\text{ref}}(\cdot \given h)^{1/0.7}. It generates 32-token responses with key-value cache and at each step calculates exact KL over the full vocabulary and estimators k1k_1 and k3k_3 for the selected token; then sums per sequence. It does not retain full distributions: with a 49,152-token vocabulary, those for 64 responses of 32 steps in double precision would occupy over 1.5 GB. It needs PyTorch and Transformers; selects GPU if available (device placement in m00) and takes under a minute on CPU.

[ ]Token KL in a real language modelLocal GPU
import numpy as np
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM

REPO, REV = "HuggingFaceTB/SmolLM2-135M", "93efa2f097d58c2a74874c7e644dbc9b0cee75a2"
device = "cuda" if torch.cuda.is_available() else "cpu"
tok = AutoTokenizer.from_pretrained(REPO, revision=REV)
model = AutoModelForCausalLM.from_pretrained(REPO, revision=REV, dtype=torch.float32).to(device).eval()

TAU, B, T = 0.7, 64, 32                      # política = referencia a temperatura 0.7
g = torch.Generator(device=device).manual_seed(0)
ids = tok("The history of information theory", return_tensors="pt").input_ids.to(device).repeat(B, 1)

k1, k3, exacta, elegidos = [], [], [], []
with torch.inference_mode():
    out = model(ids, use_cache=True)
    for t in range(T):
        logits = out.logits[:, -1].double()
        lr = torch.log_softmax(logits, -1)            # log π_ref(· | h_t), vocabulario entero
        lpp = torch.log_softmax(logits / TAU, -1)     # log π(· | h_t)
        exacta.append((lpp.exp() * (lpp - lr)).sum(-1))       # KL exacta por token, suma sobre el vocabulario
        y = torch.multinomial(lpp.exp(), 1, generator=g)
        log_rho = (lr.gather(-1, y) - lpp.gather(-1, y))[:, 0]  # log π_ref(y_t | h_t) − log π(y_t | h_t)
        k1.append(-log_rho); k3.append(torch.expm1(log_rho) - log_rho); elegidos.append(y)
        if t < T - 1:
            out = model(y, past_key_values=out.past_key_values, use_cache=True)

k1, k3, exacta, y = torch.stack(k1, 1), torch.stack(k3, 1), torch.stack(exacta, 1), torch.cat(elegidos, 1)   # (B, T)

print(f"{B} respuestas de {T} tokens en {device}")
for nombre, v in [("k1", k1), ("k3", k3), ("exacta por token", exacta)]:
    sec = v.sum(1).cpu().numpy()                      # KL estimada por secuencia
    print(f"  {nombre:17s} media {sec.mean():.3f}   desviación por secuencia {sec.std(ddof=1):.3f}")
print(f"tokens con k1 < 0: {(k1 < 0).float().mean().item():.1%}")
print("ejemplo:", tok.decode(y[0]))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

All three means estimate the same sequence KL (about six nats over 32 tokens), although with 64 responses k3k_3 may be far from the other two because of its tail; their per-sequence deviations differ greatly: the exact token sum’s is several times smaller than k1k_1, and k3k_3 does not improve on k1k_1 but is worse. The cause is the tail of ρ=πref/π\rho = \pi_{\text{ref}}/\pi: the low-temperature policy nearly discards tokens the reference still considers possible, and when one is sampled ρ\rho is enormous. If both models’ logits are available, as is usually the case in RLHF because the reference performs a forward pass on the same response, exact token KL is free and the best of the three estimators.

Common mistakes

Exercises

NumericThe optimal policy with two responses
With πref\pi_{\text{ref}} uniform over two responses, rewards r=(1,0)r = (1, 0) and β=1\beta = 1, calculate π∗(first response)\pi^\ast(\text{first response}).
NumericThe optimal value
In the same problem (πref\pi_{\text{ref}} uniform over two responses, r=(1,0)r = (1, 0), β=1\beta = 1), what is the maximum of Eπ[r]−β KL⁡(π ∥ πref)\E_\pi[r] - \beta\,\KL(\pi\,\|\,\pi_{\text{ref}})?
NumericMean-field variance
Approximate p=N(0,Σ)p = \Normal(\vb{0}, \mat{\Sigma}) in R2\R^2, with unit variances and correlation ρ=0.8\rho = 0.8, by a factorized Gaussian q(x1)q(x2)q(x_1)q(x_2) minimizing KL⁡(q ∥ p)\KL(q\,\|\,p). What is the variance of q(x1)q(x_1)?
NumericThe KL budget of best-of-n
A best-of-nn policy generates n=8n = 8 responses from πref\pi_{\text{ref}} and returns the highest-reward one (continuous reward, no ties). What is KL⁡(πbon ∥ πref)\KL(\pi_{\text{bon}}\,\|\,\pi_{\text{ref}}) in nats?
NumericMutual information of a Gaussian encoder
Data X∼N(0,1)X \sim \Normal(0, 1), encoder q(z∣x)=N(x,σe2)q(z \given x) = \Normal(x, \sigma_e^2) with σe=0.5\sigma_e = 0.5 and prior p(z)=N(0,1)p(z) = \Normal(0, 1). What is Iq(X;Z)I_q(X; Z) in nats?
QuizThe direction of variational inference
Which KL direction does standard variational inference minimize, and what typical consequence does it have for approximation variance?
QuizKL estimators in RLHF
You estimate KL⁡(π ∥ πref)\KL(\pi\,\|\,\pi_{\text{ref}}) with responses sampled from π\pi. Which statements are true?

More than one answer may be correct.

QuizPosterior collapse?
In a VAE with prior N(0,I)\Normal(\vb{0}, \mat{I}), the mean KL term is 3 nats per example. What can you conclude about Iq(X;Z)I_q(X; Z)?
ProofThe optimal policy from the variational principle
Prove: If Z=∑yπref(y) er(y)/β<∞Z = \sum_y \pi_{\text{ref}}(y)\,e^{r(y)/\beta} < \infty and Eπ∗∣r∣<∞\E_{\pi^\ast}\abs{r} < \infty (for example, bounded rr), the maximizer of J(π)=Eπ[r]−β KL⁡(π ∥ πref)J(\pi) = \E_\pi[r] - \beta\,\KL(\pi\,\|\,\pi_{\text{ref}}) is π∗=πref er/β/Z\pi^\ast = \pi_{\text{ref}}\,e^{r/\beta}/Z and the optimal value is βlog⁡Z\beta\log Z.
0
Let π\pi be any distribution with KL⁡(π ∥ πref)<∞\KL(\pi\,\|\,\pi_{\text{ref}}) < \infty and Eπ∣r∣<∞\E_\pi\abs{r} < \infty.

Step 1 of 3. How do you write rr in terms of π∗\pi^\ast?

ProofA VAE's rate
Prove: With q(x,z)=pdatos(x) q(z∣x)q(x, z) = p_{\text{datos}}(x)\,q(z \given x) and q(z)=Ex[q(z∣x)]q(z) = \E_x[q(z \given x)], we have ExKL⁡(q(z∣x) ∥ p(z))=Iq(X;Z)+KL⁡(q(z) ∥ p(z))\E_x\KL(q(z \given x)\,\|\,p(z)) = I_q(X; Z) + \KL(q(z)\,\|\,p(z)).
0
Assume all terms are finite.

Step 1 of 3. What pointwise identity do you use?

Proofk3 is unbiased and nonnegative
Prove: Let qq and pp have the same support, x∼qx \sim q and ρ=p(x)/q(x)\rho = p(x)/q(x). Then k3=(ρ−1)−log⁡ρk_3 = (\rho - 1) - \log\rho satisfies k3≥0k_3 \ge 0 and Eq[k3]=KL⁡(q ∥ p)\E_q[k_3] = \KL(q\,\|\,p).
0
Use only log⁡t≤t−1\log t \le t - 1 and the KL definition.

Step 1 of 3. Why is k3≥0k_3 \ge 0?

CodeSequence KL estimators
Implement estimadores(logp, logp_ref), receiving sampled-token log probabilities under policy and reference (same-shaped arrays, policy samples) and returning (k1, k2, k3) elementwise, with ℓ=log⁡πref−log⁡π\ell = \log\pi_{\text{ref}} - \log\pi: k1=−ℓk_1 = -\ell, k2=ℓ2/2k_2 = \ell^2/2, k3=eℓ−1−ℓk_3 = e^\ell - 1 - \ell (use np.expm1 for stability). Then implement kl_secuencia(logp, logp_ref, mascara, estimador), which takes arrays shaped (B, T) and a 0/1 mask (1 for valid tokens in each response) and returns an array (B,) summing the chosen estimator ('k1', 'k2' or 'k3') over valid tokens, raising ValueError for any other name.
import numpy as np

def estimadores(logp, logp_ref):
  """(k1, k2, k3) elemento a elemento, con muestras de la política."""
  logp = np.asarray(logp, dtype=float)
  logp_ref = np.asarray(logp_ref, dtype=float)
  # tu código
  return np.zeros_like(logp), np.zeros_like(logp), np.zeros_like(logp)

def kl_secuencia(logp, logp_ref, mascara, estimador="k3"):
  """KL estimada por secuencia: suma sobre los tokens válidos. Formas (B, T) -> (B,)."""
  # tu código
  return np.zeros(np.asarray(logp).shape[0])
Shift+Enter to run

Summary

Key idea
KL as a regularizer always has a direction and samples: forward covers mass and matches moments; reverse seeks modes and has local minima. Problem max⁡qEq[r]−β KL⁡(q ∥ p)\max_q \E_q[r] - \beta\,\KL(q\,\|\,p) has Gibbs solution p er/β/Zp\,e^{r/\beta}/Z, with value βlog⁡Z\beta\log Z: the optimal RLHF policy and, read backward, DPO.
  • Forward versus reverse. KL⁡(p ∥ q)\KL(p\,\|\,q) avoids zeros: for Gaussians it matches mean and variance with one minimum. KL⁡(q ∥ p)\KL(q\,\|\,p) forces zeros: it has a minimum near each mode of approximate value −log⁡wk-\log w_k and underestimates mean-field variance (1/Λii≤Σii1/\Lambda_{ii} \le \Sigma_{ii}).
  • Gibbs. J(q)=βlog⁡Z−β KL⁡(q ∥ q∗)J(q) = \beta\log Z - \beta\,\KL(q\,\|\,q^\ast) with q∗∝p er/βq^\ast \propto p\,e^{r/\beta}. The reward-KL frontier traced by q∗q^\ast is concave with slope β\beta.
  • RLHF. π∗=πref er/β/Z(x)\pi^\ast = \pi_{\text{ref}}\,e^{r/\beta}/Z(x); sequence KL is the expected sum of token KLs; lowering β\beta always raises model reward but not real quality (overoptimization). DPO follows from solving for rr and canceling Z(x)Z(x) in Bradley-Terry.
  • Estimators. With ℓ=log⁡(p/q)\ell = \log(p/q) and samples from qq: k1=−ℓk_1 = -\ell unbiased and often negative, k2=ℓ2/2k_2 = \ell^2/2 biased (order ε3\eps^3), k3=eℓ−1−ℓk_3 = e^\ell - 1 - \ell unbiased and nonnegative but with exploding variance if ρ\rho has a tail. Exact token KL, when logits are available, beats all three. As differentiated losses, k1k_1 gives nothing, k2k_2 gives the reverse gradient and k3k_3 the forward gradient.
  • VAEs. Rate ExKL⁡(q(z∣x) ∥ p(z))=Iq(X;Z)+KL⁡(q(z) ∥ p(z))\E_x\KL(q(z \given x)\,\|\,p(z)) = I_q(X;Z) + \KL(q(z)\,\|\,p(z)) upper-bounds information. Zero rate is collapse; high rate does not guarantee information. β-VAE chooses a point on the rate-distortion curve.