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
- 07Kullback-Leibler divergence (relative entropy)Chain rule for KL divergenceMutual informationCross-entropy minimization as maximum likelihoodClosed-form KL between GaussiansGibbs distributionGibbs variational principleRate-distortion Lagrangian
- 09Monte Carlo estimatorMonte Carlo error and confidence intervals
- 00Device placement and CPU-GPU transfers
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:
| Where | Term | Samples from | What it does |
|---|---|---|---|
| Maximum likelihood, classical distillation | , | data or teacher | the model must cover everything data make probable |
| Variational inference, ELBO | approximation | the approximation stays inside posterior mass | |
| RLHF | policy | the policy does not move too far from the starting model | |
| TRPO and PPO | as constraint or penalty | old policy | each 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:
- Explain precisely why covers mass and seeks modes, and why the second has local minima.
- Solve in closed form. Its solution is a Gibbs distribution and literally the optimal RLHF policy; inverting it yields DPO.
- Study estimating KL from samples when vocabulary size makes a full sum impossible: estimators , and used by RLHF implementations, their biases, variances and a gradient trap.
- 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 and model family that does not contain it. There are two natural fitting problems.
The difference is which distribution weights integrand . Forward KL weights : points where is large and small pay with high weight, and where and the cost is infinite. Hence forward KL is zero-avoiding: must put some mass wherever has any, even at the cost of mass where has none. Reverse KL weights : it pays for placing mass where is small, with infinite cost if and . Leaving a region where is large uncovered costs nothing because there and the integrand barely weighs. Reverse KL is zero-forcing: prefers to shrink inside a high-density region of .
Forward fitting matches moments
For the Gaussian family, forward fitting has an explicit solution, explaining why it “covers.”
Proof
and the first term does not depend on . For ,
The minimum over is for any , and then has derivative , which vanishes only at and changes sign from negative to positive: it is the global minimum. For exponential family , is convex in (because is) and its gradient is . For a differentiable convex function, zero gradient is equivalent to a global minimum.
∎Thus whatever the shape of , the forward fit is the Gaussian with the same mean and variance: if has two separated peaks, the bell sits between them and widens to span both, even though its maximum lies in the valley where 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 be a mixture with well-separated components and suppose concentrates its mass near component . There , with the relative contribution of other components, tiny near . Then
which is minimized at and is approximately . 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.
With initial values (modes at , deviation , weights and ), the forward fit is , , and reverse KL has three local minima:
| Minimum of | Approximation | ||
|---|---|---|---|
| left mode (global) | |||
| central bell | |||
| right mode |
Exact values lie slightly below because of term : the other component adds mass and lowers the cost of the tail of . 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 . For a symmetric mixture with components , the quadrature cell below maps the transition: below only the central minimum exists; beyond that two side minima appear and become global from , while the central one survives locally.
Consequence: variational inference underestimates variance
Standard variational inference minimizes with the posterior, because that direction only requires expectations under , 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 is
with as . For it satisfies identity , so as it behaves like : minimizing over gradually moves from seeking modes () to covering mass () and covering with even greater aversion to gaps (). 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 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 (a pretrained model, a prior) and a scoring function (a reward). You want a new distribution scoring highly without moving too far from .
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 , at every with we have . Since , places mass only where , and substituting (each summand is integrable under because and are finite),
By Gibbs’ inequality, with equality if and only if .
∎This is the Gibbs variational principle from lesson 13 with energy and temperature : the Gibbs distribution relative to reference measure . Three immediate interpretations:
- is a temperature. If , : the penalty dominates. If , concentrates on (when that maximum is attained, as on any finite ): only reward matters, but within the support of . What declares impossible remains so for any .
- It is exponential tilting. multiplies each probability of by and renormalizes. An answer very unlikely under needs enormous reward to gain mass: the KL penalty protects against drastic changes to rare events, not frequent ones.
- It is a Bayesian posterior. is Bayes’ rule with prior and likelihood , the probability of an event “the answer is good” proportional to . Korbak, Perez and Buckley (2022) argue that KL-penalized RLHF is better understood as inference than reward maximization.
The reward-KL frontier
As varies, traces a curve in plane . This is the best reward achievable for each divergence budget.
Proof
(1) Differentiating, . Also . (2) By the previous theorem, , because . (3) and , so , which decreases as increases (because increases with ): concavity.
∎This is the same role as the slope of the rate-distortion Lagrangian: choosing chooses a frontier point by slope. A calibration detail: when is large, and : KL decreases as , and doubling 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 and reward model trained on human preferences. The objective is
which, prompt by prompt, is the previous problem with the set of responses. Its solution is
It cannot be used as-is: sums over all token sequences, on the order of terms, and is not explicitly autoregressive. RLHF is therefore solved with policy gradients (PPO, covered in PPO for LLMs) or reformulated to avoid (DPO, below). But the closed solution says exactly what all of it converges to under perfect optimization, enough to understand almost every phenomenon.
With the policy raises mean reward from (that of ) to while spending only nats, and the readouts let you check identity . As falls, mass first flows to H, the best legitimate response. The trap wins when exceeds , that is, below . Thereafter model reward keeps rising toward 3 while real quality plummets to . Real quality peaks around , with KL about nats.
Overoptimization and the KL budget
What the figure stages with one trap is reward-model overoptimization: is a learned proxy for human preference, reliable near its training distribution 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 , 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 with a proportional controller to keep KL near a target instead of fixing in advance (covered in KL penalty control).
A useful budget reference: the best-of- policy, which generates responses from and keeps the highest-reward one, has
when reward has a continuous distribution (no ties). The reason: quantile of the selected response is the maximum of uniform variables, with density , and KL is . With ties the formula is only an upper bound (Beirami et al., 2024). For it is nats; for , . KL growing only as explains why best-of- is such a strong baseline.
Sequence KL is a sum of token KLs
A language policy generates token by token, . KL between two such policies decomposes similarly.
Proof
This is the KL chain rule applied times, or directly: ; taking expectations under and conditioning each summand on , the inner expectation of summand is token KL at prefix . 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, , 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: . 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: at each token and model reward added at the last.
Both are unbiased estimators of the same quantity averaged over sequences sampled from . 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 , estimated from policy samples. As above, it penalizes without bound placing mass where does not, but penalizes little when abandons responses considered plausible: discarding responses with mass under costs at least nats (the cost of conditioning on the remainder), a finite amount, nats for . Thus the KL penalty slows drift toward rare text without preventing diversity loss typical of RLHF-tuned models. Classical distillation uses the other direction, , 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 can be read backward: any policy with the same support as is optimal for reward
Term depends on the prompt but not the response. Human preferences are modeled with the Bradley-Terry model, , which depends only on reward differences for the same prompt, so cancels:
Fitting by maximum likelihood of those probabilities on preference pairs is DPO (Rafailov et al., 2023): loss is , without an explicit reward model or sampling from the policy. Quantity 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 with samples and ratio . This is a Monte Carlo estimator, and the task is choosing which function of to average.
Proof
(1) is the definition, and if and only if . (3) for every gives , with equality only at . Since and have the same support, , hence . (2) is immediate. By (3), , so , while is of order .
∎The idea of is a control variate: has zero mean under , so is unbiased for any , and is the unique value making it nonnegative, because it turns the estimator into the Bregman distance of between and 1. When , and are strongly oppositely correlated and their sum cancels nearly all noise.
For two Gaussians everything is explicit. With and , and (the KL between Gaussians). Then:
| Mean | Standard deviation per sample | Deviation relative to KL, | |
|---|---|---|---|
The row follows from and a normal having second moment and . Near , is as low-noise as ; its price is bias, whose relative part becomes large as distributions separate. The row follows from , and . For close distributions, relative deviation of explodes while that of stays at : for (KL ), has deviation twenty times the quantity measured. But that of grows as and exceeds that of when , i.e. from : when places mass where barely does, has a heavy tail (heavy-tailed Monte Carlo). The fraction of samples with is : with .
Two practical consequences. The standard deviation of the average falls as (Monte Carlo error), so estimator differences matter most when used per token or in small batches, exactly the RLHF setting. And since 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 , not .
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 , the score function, with . With , and its mean is zero. With , , whose mean is , because the other term in the KL derivative is . With , , whose mean is .
∎That is: used as a loss regularizes nothing on average; gives the objective’s reverse-KL gradient; and , preferred for the value, gives the forward-KL gradient as a loss. GRPO (Shao et al., 2024) uses per token as a loss term, and Tang and Munos (2025) identified precisely this discrepancy. Near 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 , decoder and prior , usually . It trains by maximizing the evidence lower bound (ELBO), obtained by writing log likelihood as
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 distortion and call
the rate. To interpret it, look at the joint distribution defined by the encoder on the data, , and its marginal in , the aggregate posterior .
Proof
For each with , . Take expectations under . The first summand gives , mutual information. The second depends only on , whose marginal under is , and gives . The inequality follows from 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 , 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 and measures the nats passing through it. Alemi et al. complete the picture with , where is data entropy: rate bounds information above and reconstruction quality bounds it below.
Initially (, , ) rate is nats, of which is mutual information and mismatch: the aggregate posterior is bimodal and the prior a single bell. Extreme cases illustrate two misreadings:
- Posterior collapse (posterior collapse). If for every , rate is zero, ELBO pays nothing for the latent and : 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 and , the encoder ignores but shifts all codes: nats and . Large KL also does not certify a useful latent.
What to monitor is , not rate. Collapse remedies (KL warmup, “free bits” per dimension; see KL annealing and free bits) and β-VAE (Higgins et al., 2017), minimizing , can be understood as choosing a point on the rate-distortion curve: buys a more compressed and, according to its authors, more disentangled code; lets more information through. And since excess 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 by to avoid constraints.
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 starting at a mode returns to the center (): no side minimum exists. With one exists but is worse than the central one; with they tie, and with the side one is better ( versus ).
Now toy RLHF with exact solution. A tabular autoregressive policy over length-3 sequences from a 4-token vocabulary (one logit vector per prefix, 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 .
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 , and attained value . With the optimal policy calculated, check the chain rule and compare three sequence-KL estimators: the sum of per token, the sum of per token and the sum of exact token KL at visited prefixes.
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 does not improve : token distributions are far apart (total KL is nats over three tokens) and we are in the regime where 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.
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 the deviation of already exceeds that of 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 and an independent Monte Carlo estimate of .
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 , and ); 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 , concentrating each token distribution: . It generates 32-token responses with key-value cache and at each step calculates exact KL over the full vocabulary and estimators and 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.
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]))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 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 , and does not improve on but is worse. The cause is the tail of : the low-temperature policy nearly discards tokens the reference still considers possible, and when one is sampled 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
More than one answer may be correct.
Step 1 of 3. How do you write in terms of ?
Step 1 of 3. What pointwise identity do you use?
Step 1 of 3. Why is ?
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 : , , (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])Summary
- Forward versus reverse. avoids zeros: for Gaussians it matches mean and variance with one minimum. forces zeros: it has a minimum near each mode of approximate value and underestimates mean-field variance ().
- Gibbs. with . The reward-KL frontier traced by is concave with slope .
- RLHF. ; sequence KL is the expected sum of token KLs; lowering always raises model reward but not real quality (overoptimization). DPO follows from solving for and canceling in Bradley-Terry.
- Estimators. With and samples from : unbiased and often negative, biased (order ), unbiased and nonnegative but with exploding variance if has a tail. Exact token KL, when logits are available, beats all three. As differentiated losses, gives nothing, gives the reverse gradient and the forward gradient.
- VAEs. Rate upper-bounds information. Zero rate is collapse; high rate does not guarantee information. β-VAE chooses a point on the rate-distortion curve.