The Kullback-Leibler divergence
Introduce relative entropy as a measure of how wrong model q is relative to reality p. Prove nonnegativity (Gibbs' inequality), log-sum inequality, joint convexity and chain rule, and study asymmetry and differing supports. Interpret KL as expected excess surprise and mean evidence per observation for p against q.
After this lesson you can
- Calculate D(p‖q) for discrete distributions and identify infinite values from support differences.
- Prove Gibbs' inequality with Jensen and log-sum, including equality conditions.
- Prove joint convexity of KL and apply its chain rule to joint and product distributions.
- Interpret KL as expected log-likelihood ratio, or mean evidence per sample.
- Construct counterexamples showing KL is asymmetric and fails the triangle inequality.
Before you start
Motivation: the cost of choosing the wrong model
A source emits four symbols with probabilities . Each has surprise bits, and its entropy, mean surprise, is bits: the minimum average cost of describing a source symbol. An engineer who does not know assumes all four symbols equally likely and designs a 2-bit-per-symbol code. It works, but pays extra bits per symbol. This overhead is not a code defect: it is the cost of the engineer’s ignorance of , measurable without constructing a code.
That quantity is Kullback–Leibler divergence, among the objects you will encounter most on this platform. Whenever you fit a model to data from an unknown distribution , you are, knowingly or not, performing the same experiment:
- Train with cross-entropy. A classifier or language model’s mean loss is : a parameter-independent term, data entropy, plus divergence between data and model. Minimizing loss minimizes divergence, and maximum likelihood is exactly that.
- Regularize. RLHF adds penalty to reward to keep policy near a reference model (KL penalty control). A variational autoencoder contains a KL term between encoder and prior (VAE), and variational inference minimizes KL between an approximation and posterior.
- Test hypotheses. Divergence sets the rate at which data distinguish hypotheses: see the following sections and the formal Stein lemma.
This lesson carefully builds divergence. First its definition and support conventions (where it breaks), then its two interpretations, informational and statistical. Next we prove structural properties with all assumptions: nonnegativity (Gibbs’ inequality), log-sum inequality, joint convexity and chain rule. It ends with what it is not: neither symmetric nor a distance. Unless stated otherwise, is base-2 logarithm and quantities are in bits; multiply by to convert to nats.
Definition and conventions
Let be a finite alphabet (lesson 11 extends everything to continuous variables) and two distributions on . Write for the support of .
The conventions are not arbitrary; they are natural limits: as , and as with fixed . This reveals asymmetric roles. The first distribution samples: it decides which terms count and their weights. The second describes: the model whose surprise is measured. A model assigning zero probability to something that occurs is infinitely wrong; a model reserving mass for something that never occurs merely wastes some probability, at finite cost.
The following histograms show where each term comes from. The sign matters.
Three things the figure shows and the rest of the lesson proves:
- Some terms are negative but the total never is. Since , wherever puts more mass than in one category it must put less in another. What is paid where underestimates always exceeds savings where it overestimates. This is Gibbs’ inequality, proved below.
- Lowering toward zero where makes divergence explode. Contribution grows without bound; at it is and other bars cannot compensate.
- Directions differ. Switch from to and watch which categories dominate.
Two interpretations of the same sum
Expected excess surprise
Expand the logarithm of the ratio. For ,
The first term is cross-entropy : the mean bits paid when describing data with a code fitted to (lesson 5 constructs actual prefix codes and 6 studies it in depth). The second is the minimum possible cost, entropy of . Divergence is the difference: expected excess surprise,
This is the motivating identity: . In a real code lengths are integers, and using lengths costs less than one extra bit per symbol above (cost of coding with the wrong model); arithmetic coding (lesson 7) makes that rounding disappear on long sequences and excess per symbol approaches .
The same in learning terms: if is a dataset’s empirical distribution and a model, cross-entropy loss is . The first term does not depend on , so training reduces a KL toward the data distribution. Minimum loss is not 0 but : irreducible noise. Excess over that minimum, measuring model error, is exactly divergence.
Mean evidence per observation
A second statistical interpretation explains why direction matters. Given hypotheses (data from ) and (from ), the likelihood ratio of observation is , and by the Neyman–Pearson lemma the most powerful test at a given level is based on it. Its logarithm,
is the evidence supplies for in bits: bit means is twice as likely under as . If data come from , mean evidence per observation is
Divergence is evidence each observation from supplies on average to distinguish it from . With independent observations total evidence is a sum of iid variables, and by the strong law of large numbers almost surely: evidence for the true hypothesis grows linearly with divergence as slope. Since there is a divergence for each direction, the next simulation’s slopes differ.
Notice two things. First, slope is divergence in the true-hypothesis direction. With and , bits and bits: if data come from , evidence rises by bits per sample; if from , it falls by bits per sample. Distinguishing one hypothesis from the other does not cost the same in both directions. Second, time to accumulate bits of evidence is approximately . There is an exact version. If is the first time (Wald’s sequential test), Wald’s identity gives when data come from and ; if probability of crossing the wrong threshold is small, is almost always just over (an overshoot of a few bits), so . With bits and the parameters above theory gives samples and a simulation of sequences averages (with bits of overshoot and only 1% crossing ).
Finally, fixed-sample hypothesis testing. If type-I error (deciding when is true) is bounded by a constant, best type-II error (deciding when is true) decays as with sample size . This is Stein’s lemma (lesson 16), why rather than another quantity appears when asking “how much data is needed”.
Gibbs’ inequality
The earlier figure suggested the total is never negative. Now we prove it, also finding exactly when it is zero.
Proof
Let . If for some , then and there is nothing to prove or equality possible (also ). So assume throughout . Function is strictly concave, and numbers , are positive weights summing to 1. By Jensen’s inequality,
where . Hence .
Equality. If both inequalities are equalities. In Jensen, strict concavity forces ratio to be constant on . In the second, forces . Thus , so on , and since , is zero outside like . That is, . The converse is immediate: if every ratio is 1.
∎Another shorter proof is worth keeping handy. Use , with equality only at :
A third geometric interpretation connects it with optimization convexity. Function (negative entropy) is convex on the simplex, and its Bregman divergence is exactly after simplifying . KL nonnegativity is the first-order convexity condition of (a convex function lies above its tangent), and strict positivity follows from strict convexity of (whose second derivative is , the second-order condition).
Immediate corollaries
This follows from . The motivation was one case: bits excess. You have used the result without proof whenever saying “uniform distribution maximizes uncertainty”; its origin is that divergence to uniform cannot be negative.
The log-sum inequality
KL is a sum of terms . Understanding what happens when grouping terms is key to its convexity.
The interpretation is simple: grouping bins cannot increase divergence. If and are masses and assign to a group of outcomes, the left side is those bins’ separate contribution to , and the right their contribution merged into a single bin with masses and . This is the next lesson’s data processing inequality in miniature.
Proof
Trivial cases. If both sides are 0. If any has , the left side is . Assume and whenever . Indices with contribute nothing on the left and can only increase , lowering the right side (strictly if any has ): it suffices to prove the inequality without them, with , because . Thus assume all .
Function is strictly convex on (). With weights summing to 1 and points , Jensen’s inequality gives
Convexity is strict, so Jensen equality holds only if all agree. Returning to the general case, equality also requires , i.e. no indices with : this gives stated condition for every .
∎Consider the most important consequence.
Proof
Fix and apply the two-term log-sum inequality: , , , . Then and are mixture masses, and factors and cancel inside ratios,
Summing over gives the desired inequality. (If equality holds.)
∎Mixing is generally beneficial. With , and , each pair has bit; their equal mixture is versus , with zero divergence. The inequality can be very loose: here the left side is and right bit. In the 10⁵ Dirichlet pairs tested in implementation the inequality always holds and mean gap is one bit.
Consequences you will use: KL is convex in with fixed (strictly), and convex in with fixed , so minimizing over a convex set (an “information projection”, lesson 13) is convex optimization without misleading local minima. But it is not generally jointly strictly convex (if for both pairs, their mixture remains on diagonal where KL is 0, so strictness fails).
The chain rule
Entropy decomposes as . Divergence has the same structure, making it manageable for sequences and multivariable models.
Proof
If and , then and . Taking logarithms and expectation under ,
The first summand is after summing over . In the second, leaving . Infinite cases are consistent: if , either (and marginal divergence is ) or (and the conditional for that is weighted by ). Both sides equal .
∎At initial values, and . Total divergence is bits. The marginal contributes (with and ) and conditionals, weighted by , contribute . Total : the same number as cellwise summation.
Three consequences of the rule:
- Forgetting variables cannot increase divergence. The conditional term is nonnegative by Gibbs, so , with equality if and only if for every with : ignored information cannot distinguish. With initial tables, the marginal gives only bits versus jointly. This is data processing for marginalization, generalized to any transformation in lesson 3.
- It is additive on products. If and are product distributions, conditionals do not depend on and . For iid samples, : divergence is extensive, like entropy. This explains in the evidence figure.
- It decomposes token by token. For autoregressive models , applying the rule times gives Divergence between two language models over full sequences is the sum of per-token divergences averaged over prefixes generated by . This is penalized token by token in RLHF.
Asymmetry, supports and the triangle inequality
All the above applies separately in each direction. What fails is swapping and .
This is not an extreme-point accident. For nearby distributions KL resembles a squared distance, and squared distances do not satisfy the triangle inequality: .
Proof
Let , so . With , the first case is and the second . The linear term vanishes because .
∎Both directions share second-order term (half Pearson divergence, ), a positive-definite quadratic form: locally KL is squared distance, the Fisher metric seen in lesson 16. They differ in the cubic term, so far from the two directions’ level curves separate.
What to take from the figure:
- They are not circles. Level curves near are ellipses of quadratic form , narrower in directions moving a low-probability outcome (deviation in an outcome of probability weighs much more than in one of , so a shorter step reaches the same level). This is “information geometry”: distance between distributions is not Euclidean.
- Both directions agree nearby and separate far away, as the cubic term predicts: almost identical bands inside the ellipse, different outside.
- Edges explode in one direction only. With interior and on the edge, , while remains bounded by . With on the edge, throughout the interior: the right map fills with the highest-level color. A model whose support exceeds the data’s is no problem for (it merely wastes mass), but smaller support is an irreparable problem.
The consequence for model training is serious. Maximum likelihood minimizes : if data contain a symbol assigned zero probability by the model, loss is infinite. Hence outputs are parametrized with softmax, never giving exact zeros, yet near-zero probability where data exist produces huge losses and gradients. The other direction (minimized by variational inference and many penalties) punishes the reverse: model mass where data have none. Each prefers a type of error. Study this as forward and reverse KL in lesson 15.
What can be saved from the idea of distance? A metric requires symmetrization: square root of Jensen–Shannon divergence with does satisfy the triangle inequality (lesson 12). KL is instead a divergence in information geometry: nonnegative, zero only on the diagonal and smooth, but neither symmetric nor triangular.
Implementation from scratch
First divergence with all conventions and checks from earlier sections: motivation, asymmetry, triangle inequality, supports and Gibbs on Dirichlet pairs. Function kl_lote computes divergences at once without loops.
import numpy as np
def kl(p, q, base=2.0):
"""D(p||q) con las convenciones 0 log(0/q) = 0 y p log(p/0) = inf (bits por defecto)."""
p = np.asarray(p, dtype=float)
q = np.asarray(q, dtype=float)
if p.shape != q.shape:
raise ValueError("p y q deben tener la misma forma")
if np.any(p < 0) or np.any(q < 0) or not np.isclose(p.sum(), 1) or not np.isclose(q.sum(), 1):
raise ValueError("p y q deben ser distribuciones de probabilidad")
soporte = p > 0 # solo cuentan los x con p(x) > 0
if np.any(q[soporte] == 0):
return np.inf # p no es absolutamente continua respecto a q
return float(np.sum(p[soporte] * np.log(p[soporte] / q[soporte])) / np.log(base))
def entropia(p, base=2.0):
p = np.asarray(p, dtype=float)
p = p[p > 0]
return float(-np.sum(p * np.log(p)) / np.log(base))
# la motivación: describir p con un código pensado para la uniforme
p = np.array([1/2, 1/4, 1/8, 1/8])
u = np.full(4, 1/4)
print("H(p) =", entropia(p), " coste con el código uniforme =", -np.sum(p * np.log2(u)), " D(p||u) =", round(kl(p, u), 6))
# asimetría, soportes y desigualdad triangular
b = lambda a: [1 - a, a]
print("D(B(.1)||B(.5)) =", round(kl(b(.1), b(.5)), 4), " D(B(.5)||B(.1)) =", round(kl(b(.5), b(.1)), 4))
print("D(B(.1)||B(.9)) =", round(kl(b(.1), b(.9)), 4), " > ", round(kl(b(.1), b(.5)) + kl(b(.5), b(.9)), 4), "= D(.1||.5) + D(.5||.9)")
print("soportes: D(p||q) =", kl([1/2, 1/2, 0], [1/2, 1/4, 1/4]), " D(q||p) =", kl([1/2, 1/4, 1/4], [1/2, 1/2, 0]))
# Gibbs en 10^5 pares de Dirichlet, sin bucles
rng = np.random.default_rng(0)
N, K = 100_000, 5
def kl_lote(P, Q):
"""D(P_i || Q_i) en bits para cada fila de dos arrays de forma (N, K)."""
with np.errstate(divide="ignore", invalid="ignore"):
T = np.where(P > 0, P * np.log2(P / Q), 0.0)
return T.sum(axis=1)
P, Q = rng.dirichlet(np.ones(K) * 0.5, N), rng.dirichlet(np.ones(K) * 0.5, N)
D = kl_lote(P, Q)
neg = np.mean((P * np.log2(P / Q) < 0).any(axis=1))
print(f"Gibbs: mín D = {D.min():.2e}; D < 0 en {np.sum(D < -1e-12)} de {N} pares")
print(f"pares con alguna contribución negativa: {100 * neg:.1f} % (y aun así, ninguno con total negativo)")Minimum divergence across pairs is positive, although all have at least one category with negative contribution: as the first figure showed. Now joint convexity, chain rule and Pinsker’s inequality from the note above, using the same samples.
import numpy as np
rng = np.random.default_rng(1)
N, K = 100_000, 5
def kl_lote(P, Q):
with np.errstate(divide="ignore", invalid="ignore"):
T = np.where(P > 0, P * np.log2(P / Q), 0.0)
return T.sum(axis=1)
P1, Q1 = rng.dirichlet(np.ones(K) * 0.5, N), rng.dirichlet(np.ones(K) * 0.5, N)
P2, Q2 = rng.dirichlet(np.ones(K) * 0.5, N), rng.dirichlet(np.ones(K) * 0.5, N)
lam = rng.uniform(size=(N, 1))
# convexidad conjunta: KL de la mezcla <= mezcla de KLs
izq = kl_lote(lam * P1 + (1 - lam) * P2, lam * Q1 + (1 - lam) * Q2)
der = lam[:, 0] * kl_lote(P1, Q1) + (1 - lam[:, 0]) * kl_lote(P2, Q2)
print(f"convexidad: violaciones {np.sum(izq > der + 1e-12)} de {N}; mayor (izq - der) = {np.max(izq - der):.2e}; hueco medio = {np.mean(der - izq):.3f} bits")
# Pinsker: KL >= ||p - q||_1^2 / (2 ln 2)
l1 = np.abs(P1 - Q1).sum(axis=1)
cociente = kl_lote(P1, Q1) / (l1**2 / (2 * np.log(2)))
print(f"Pinsker: cociente mínimo KL / (||p-q||_1^2 / 2 ln 2) = {cociente.min():.4f} (>= 1)")
# regla de la cadena en tablas conjuntas 4 x 3, sin ceros (con ceros hay que tener cuidado: es un ejercicio)
def kl(p, q):
return float(np.sum(p * np.log2(p / q)))
def cadena(Pxy, Qxy):
px, qx = Pxy.sum(axis=1), Qxy.sum(axis=1)
condicional = sum(px[i] * kl(Pxy[i] / px[i], Qxy[i] / qx[i]) for i in range(len(px)))
return kl(Pxy.ravel(), Qxy.ravel()), kl(px, qx) + condicional
error = 0.0
for _ in range(2000):
A, B = rng.dirichlet(np.ones(12)).reshape(4, 3), rng.dirichlet(np.ones(12)).reshape(4, 3)
izq, der = cadena(A, B)
error = max(error, abs(izq - der))
print(f"regla de la cadena: error máximo en 2000 tablas aleatorias = {error:.1e}")
# la divergencia es extensiva: n muestras iid dan n veces la KL de una
p, q = np.array([0.6, 0.4]), np.array([0.5, 0.5])
p2, q2 = np.outer(p, p).ravel(), np.outer(q, q).ravel()
print("KL de un lanzamiento:", round(kl(p, q), 5), " de dos:", round(kl(p2, q2), 5))Convexity holds in every case, Pinsker ratio is always at least 1, and the chain rule is verified up to floating-point rounding. But that cadena implementation fails whenever a cell is zero (0 * log(0) gives nan) or an entire row has zero mass (division by zero): the final coding exercise asks you to fix it.
The library version
SciPy offers three related functions, and they are not equivalent.
| Function | Computes | Notes |
|---|---|---|
scipy.special.rel_entr(x, y) | term by term | nats; if , if ; preserves sign |
scipy.stats.entropy(p, q, base=2) | renormalizes and to sum 1 silently | |
scipy.special.kl_div(x, y) | term by term | nonnegative per term; equals KL only if and sum equally |
import numpy as np
from scipy.special import rel_entr, kl_div
from scipy.stats import entropy
def kl(p, q, base=2.0):
p = np.asarray(p, dtype=float); q = np.asarray(q, dtype=float)
s = p > 0
if np.any(q[s] == 0):
return np.inf
return float(np.sum(p[s] * np.log(p[s] / q[s])) / np.log(base))
p = np.array([0.5, 0.25, 0.25])
q = np.array([0.4, 0.4, 0.2])
print("a mano (nats): ", kl(p, q, base=np.e))
print("rel_entr(p, q).sum(): ", rel_entr(p, q).sum())
print("entropy(p, q): ", entropy(p, q), " en bits:", entropy(p, q, base=2))
print("kl_div(p, q).sum(): ", kl_div(p, q).sum())
print("términos rel_entr:", np.round(rel_entr(p, q), 4), " (uno es negativo)")
print("términos kl_div: ", np.round(kl_div(p, q), 4), " (todos positivos)")
# entropy normaliza sin avisar; rel_entr no
print("\nentropy(2 * p, q) =", entropy(2 * p, q), " (renormaliza: igual que con p)")
print("rel_entr(2 * p, q).sum() =", rel_entr(2 * p, q).sum(), " (sin renormalizar: otra cosa)")
# soportes distintos
p3, q3 = np.array([0.5, 0.25, 0.25]), np.array([0.5, 0.5, 0.0])
print("\nsoportes: entropy(p3, q3) =", entropy(p3, q3), " entropy(q3, p3) =", round(entropy(q3, p3), 4))
# la trampa del epsilon: el valor depende de la constante que elijas
dato = np.array([0.5, 0.5, 0.0])
modelo = np.array([0.5, 0.25, 0.25])
for eps in [1e-3, 1e-6, 1e-12]:
suave = (dato + eps) / (dato + eps).sum()
print(f"eps = {eps:.0e}: D(modelo || dato + eps) = {kl(modelo, suave):6.3f} bits")All three agree with hand calculation for properly normalized distributions, but diverge when something is unusual. The final loop shows why “smoothing with small ” does not solve infinite support: divergence grows as because the model puts mass outside data support, and each yields a different number (, and bits). If your loss depends on , you are not measuring KL: you are measuring your .
PyTorch: the kl_div convention
torch.nn.functional.kl_div(input, target) causes more silent KL mistakes because it does not receive and : it receives input (model probability logarithms) and target (data probabilities), and calculates elementwise in nats, with . Then it reduces. reduction='batchmean' divides the sum by batch size (mathematical mean KL per example); default 'mean' divides by total element count .
import torch
import torch.nn.functional as F
# logits del modelo -> log q, nunca q; p son las probabilidades objetivo (datos, profesor...)
log_q = F.log_softmax(logits, dim=-1)
kl_medio = F.kl_div(log_q, p, reduction="batchmean") # KL(p || q) media por ejemplo, en nats
# trampas: F.kl_div(q, p) con probabilidades en vez de log-probabilidades; reduction="mean"
# (por defecto) que divide además entre K; y F.kl_div(log_p, q) que calcula KL(q || p).
For concrete numbers this cell reproduces kl_div in NumPy (without PyTorch) and shows three common mistakes:
import numpy as np
def kl_div_torch(entrada, objetivo, reduction="batchmean"):
"""Réplica de F.kl_div(entrada, objetivo, reduction=...): entrada = log q, objetivo = p."""
seguro = np.where(objetivo > 0, objetivo, 1.0)
puntual = np.where(objetivo > 0, objetivo * (np.log(seguro) - entrada), 0.0)
if reduction == "sum":
return puntual.sum()
if reduction == "batchmean":
return puntual.sum() / entrada.shape[0]
return puntual.mean() # 'mean': divide entre TODOS los elementos
P = np.array([[0.5, 0.25, 0.25], [0.1, 0.8, 0.1]]) # datos
Q = np.array([[0.4, 0.4, 0.2], [0.2, 0.6, 0.2]]) # modelo
def kl_fila(p, q):
return float(np.sum(p * np.log(p / q)))
exacto = np.mean([kl_fila(a, b) for a, b in zip(P, Q)])
print("KL(p||q) media por fila (nats): ", round(exacto, 6))
print("kl_div(log q, p, 'batchmean'): ", round(kl_div_torch(np.log(Q), P), 6))
print("kl_div(log q, p, 'mean'): ", round(kl_div_torch(np.log(Q), P, "mean"), 6), " <- dividida entre B*K = 6")
print("argumentos cambiados (log p, q): ", round(kl_div_torch(np.log(P), Q), 6), " = KL(q||p), otra cantidad")The numbers match PyTorch (checked on CPU with the same tensors). PyTorch documentation warns of this and announces that 'mean' will behave like 'batchmean' in a major release, so always state the reduction.
Common mistakes
Exercises
More than one answer may be correct.
q is a tensor with model probabilities (sum 1 per row) and p of the same shape has target probabilities. Which call computes mean divergence per example in nats?Step 1 of 4. How do you rewrite to apply Jensen?
Step 1 of 4. How do you write the left side to apply Jensen to ?
cadena(P, Q), where P and Q are joint tables (rows , columns ) summing to 1. Return (izq, der) with izq and der , in bits, with usual conventions: , . Rows with do not count (their conditional is undefined and weight 0), and if has mass where is zero both outputs must be inf. No nan may appear.import numpy as np
def kl(p, q):
"""KL en bits entre dos vectores (ya con las convenciones de soporte)."""
p = np.asarray(p, dtype=float)
q = np.asarray(q, dtype=float)
s = p > 0
if np.any(q[s] == 0):
return np.inf
return float(np.sum(p[s] * np.log2(p[s] / q[s])))
def cadena(P, Q):
"""Devuelve (izq, der): KL conjunta y suma marginal + condicional, en bits."""
P = np.asarray(P, dtype=float)
Q = np.asarray(Q, dtype=float)
# tu código: izquierda con las tablas aplanadas; derecha con las marginales de X y los condicionales
return 0.0, 0.0Summary
- Definition. , with and . It is finite if and only if . samples; describes.
- Two interpretations. (excess bits and training loss) and (mean evidence per sample; bits require about observations).
- Gibbs. , with equality if and only if : by Jensen, by , or as the negative-entropy tangent. Corollary: .
- Log-sum and convexity. , hence is jointly convex in .
- Chain rule. : forgetting variables cannot increase KL, and KL between autoregressive models is the sum of per-token KLs.
- Geometry. Near , : squared distance, symmetric to second order. Thus it fails the triangle inequality () and directions separate far from .
- Practice. PyTorch
kl_divreceives and (in that order), with correctbatchmeanreduction;scipy.stats.entropyrenormalizes; to avoid gives divergence depending on .