Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsInformation Theory

KL divergence

P1.E435 min●●○ IntermediateReviewed Dec 1, 2026

Why this matters for machine learning

The KL divergence is the number that says how far a model's probabilities are from the truth, and it sits inside the training objective of classifiers, variational autoencoders, distillation and language-model fine-tuning.

  • Training a classifier by cross-entropy is minimizing the KL divergence from the label distribution to the model's predictions, because the entropy of the labels is a constant. (P3.A8: Softmax regression)
  • A variational autoencoder adds a KL term between two Gaussians, in the closed form of this lesson, to keep its latent codes close to a standard Gaussian. (P8.3: Variational Autoencoders, coming soon)
  • Fine-tuning a language model with reinforcement learning from human feedback subtracts a KL penalty that keeps the model close to the model it started from. (P10.D2: Reward models and RLHF, coming soon)
  • Distillation trains a small student to match a teacher's probabilities by minimizing the KL divergence between them. (P10.F2: Distillation and small models, coming soon)
  • Monitoring a deployed model can compare the distribution of an input today with a reference period using KL or a relative of it. (P12.5: Monitoring and drift, coming soon)

Before this: Cross-entropy, Common distributions, Maximum Likelihood Estimation

After this lesson you can

  • Define KL(p ∥ q)=∑xp(x)log⁡p(x)q(x)\mathrm{KL}(p\,\|\,q)=\sum_x p(x)\log\frac{p(x)}{q(x)} as the extra average surprise of using the model qq for data from pp, equal to H(p,q)−H(p)H(p,q)-H(p), compute it for the three-class example (0.1430.143 bits, 0.09930.0993 nats), and convert between bits and nats
  • State and prove that KL(p ∥ q)≥0\mathrm{KL}(p\,\|\,q)\ge0 with equality exactly when p=qp=q, and explain why KL is not a distance: it is not symmetric (0.1430.143 against 0.1680.168 bits), the triangle inequality can fail, and it is infinite when q=0q=0 where p>0p>0
  • Compute the KL divergence between two one-dimensional Gaussians in closed form, including the special case against a standard Gaussian used in variational autoencoders
  • Explain forward KL, KL(p ∥ q)\mathrm{KL}(p\,\|\,q), and reverse KL, KL(q ∥ p)\mathrm{KL}(q\,\|\,p), as ways to fit qq to pp: forward covers all of pp (for a Gaussian it matches the mean and variance, and it is what maximum likelihood minimizes), reverse locks onto one peak (what variational inference minimizes); read both on a Gaussian fitted to two peaks

P1.E3 ended with a split. The cross-entropy of a model qq against the truth pp is the entropy H(p)H(p), which belongs to the data, plus an extra cost that belongs to the model. For p=(0.7,0.2,0.1)p=(0.7,0.2,0.1) and q=(0.5,0.25,0.25)q=(0.5,0.25,0.25) the extra was 0.1430.143 bits. That extra has its own name, the KL divergence, and this lesson studies it alone.

Three questions drive the lesson. Why can the extra never be negative? Why does swapping pp and qq change it? And when you fit a simple model to a complicated distribution, what does it mean to minimize the divergence one way or the other? The last question has a surprising answer, and a widget at the middle of the lesson lets you see it.

The extra, written out

Start from the cross-entropy and subtract the entropy. With H(p,q)=−∑xp(x)log⁡q(x)H(p,q)=-\sum_x p(x)\log q(x) and H(p)=−∑xp(x)log⁡p(x)H(p)=-\sum_x p(x)\log p(x):

KL(p ∥ q)=H(p,q)−H(p)=∑xp(x)log⁡p(x)q(x).\begin{aligned} \mathrm{KL}(p\,\|\,q)&=H(p,q)-H(p)\\ &=\sum_x p(x)\log\frac{p(x)}{q(x)}. \end{aligned}

Read the last form as an average. Outcome xx happens with probability p(x)p(x). The model finds it log⁡1q(x)\log\frac{1}{q(x)} surprising and the truth finds it log⁡1p(x)\log\frac{1}{p(x)} surprising, so the difference is log⁡p(x)q(x)\log\frac{p(x)}{q(x)}, and the formula averages that difference over what really happens. Equivalently, KL(p ∥ q)=Ex∼p[log⁡p(x)−log⁡q(x)]\mathrm{KL}(p\,\|\,q)=\mathbb{E}_{x\sim p}\bigl[\log p(x)-\log q(x)\bigr]. The two bars in the notation are a separator, not a division. The first argument is the truth and the second is the model.

Terms with p(x)=0p(x)=0 add 00, by the same convention as in P1.E2 and P1.E3. For a variable with a density the sum becomes an integral, ∫p(x)ln⁡p(x)q(x) dx\int p(x)\ln\frac{p(x)}{q(x)}\,dx, and everything below holds in the same form.

The example, term by term. Take p=(0.7, 0.2, 0.1)p=(0.7,\,0.2,\,0.1) and q=(0.5, 0.25, 0.25)q=(0.5,\,0.25,\,0.25) in bits:

0.7log⁡20.70.5=  0.3400.2log⁡20.20.25=−0.0640.1log⁡20.10.25=−0.132.\begin{aligned} 0.7\log_2\tfrac{0.7}{0.5}&=\ \ 0.340\\ 0.2\log_2\tfrac{0.2}{0.25}&=-0.064\\ 0.1\log_2\tfrac{0.1}{0.25}&=-0.132. \end{aligned}

The sum is 0.1430.143 bits, matching H(p,q)−H(p)=1.300−1.157H(p,q)-H(p)=1.300-1.157 from P1.E3. In nats, the unit that machine-learning code uses, it is 0.143×ln⁡2=0.09930.143\times\ln2=0.0993. Two things to notice. The model underrates the first class (0.50.5 against 0.70.7) and that term is large and positive. The model overrates the other two classes, so their terms are negative. A single term can be below 00, but the whole sum cannot be, as the next section shows.

Units. The base of the logarithm sets the unit: bits for log⁡2\log_2 and nats for ln⁡\ln. As for entropy, nats=bits×ln⁡2\text{nats}=\text{bits}\times\ln2, so 0.1430.143 bits is 0.09930.0993 nats.

The extra is at least zero

For every pair of distributions pp and qq over the same outcomes,

KL(p ∥ q)≥0,\mathrm{KL}(p\,\|\,q)\ge0,

and KL(p ∥ q)=0\mathrm{KL}(p\,\|\,q)=0 exactly when p=qp=q. This is Gibbs’ inequality, the fact behind H(p,q)≥H(p)H(p,q)\ge H(p) in P1.E3. In words: a code built for the wrong distribution cannot beat the code built for the right one, and it ties only when the two distributions are the same. It is also why KL is a sensible quantity to minimize. Its lowest possible value, 00, is reached when the model is exactly right.

Go deeper Why KL is at least zero

Use natural logs. Let SS be the outcomes with p(x)>0p(x)>0, so the sums run over SS. The fact needed is ln⁡u≤u−1\ln u\le u-1 for every u>0u>0, with equality only at u=1u=1 (the picture: the curve ln⁡u\ln u lies below its tangent line at u=1u=1). Apply it with u=q(x)/p(x)u=q(x)/p(x):

−KL(p ∥ q)=∑Spln⁡qp≤∑Sp(qp−1)=∑Sq−1 ≤ 0.\begin{aligned} -\mathrm{KL}(p\,\|\,q)&=\sum_S p\ln\frac{q}{p}\\ &\le\sum_S p\Bigl(\frac{q}{p}-1\Bigr)\\ &=\sum_S q-1\ \le\ 0. \end{aligned}

So KL≥0\mathrm{KL}\ge0. Equality needs q(x)=p(x)q(x)=p(x) for every xx in SS, and then ∑Sq=1\sum_S q=1 forces q=0q=0 outside SS too, so q=pq=p. The proof is the one that P1.D10 and P1.E3 used. The version with Jensen’s inequality (P1.D4) reads −KL=Ep[ln⁡qp]≤ln⁡Ep[qp]=ln⁡∑Sq≤0-\mathrm{KL}=\mathbb{E}_p[\ln\frac qp]\le\ln\mathbb{E}_p[\frac qp]=\ln\sum_S q\le0, because ln⁡\ln is concave. For densities the proof is the same with integrals, and equality holds when p=qp=q except on a set of probability 00.

It is not a distance

KL is 00 for identical distributions and grows as they differ, so it feels like a distance. It is not one, and the differences matter.

It is not symmetric. Swap the roles in the example. Now outcomes come from qq and the extra is KL(q ∥ p)=0.5log⁡20.50.7+0.25log⁡20.250.2+0.25log⁡20.250.1=0.168\mathrm{KL}(q\,\|\,p)=0.5\log_2\frac{0.5}{0.7}+0.25\log_2\frac{0.25}{0.2}+0.25\log_2\frac{0.25}{0.1}=0.168 bits. Compare:

KL(p ∥ q)=0.143 bitsKL(q ∥ p)=0.168 bits.\begin{aligned} \mathrm{KL}(p\,\|\,q)&=0.143\text{ bits}\\ \mathrm{KL}(q\,\|\,p)&=0.168\text{ bits}. \end{aligned}

These are two different questions. KL(p ∥ q)\mathrm{KL}(p\,\|\,q) asks how much extra it costs to use qq when pp is the truth. KL(q ∥ p)\mathrm{KL}(q\,\|\,p) asks the reverse. Weights come from the first argument, so the two sums emphasize different outcomes. This is the same asymmetry as H(p,q)=1.300H(p,q)=1.300 against H(q,p)=1.668H(q,p)=1.668 in P1.E3, because the entropies also differ (1.1571.157 and 1.51.5).

It can be infinite. If the model says q(x)=0q(x)=0 for an outcome that can happen, p(x)>0p(x)>0, the term p(x)log⁡p(x)0p(x)\log\frac{p(x)}{0} is infinite, and so is KL(p ∥ q)\mathrm{KL}(p\,\|\,q). With q=(0.5,0.5,0)q=(0.5,0.5,0) against p=(0.7,0.2,0.1)p=(0.7,0.2,0.1), KL(p ∥ q)=∞\mathrm{KL}(p\,\|\,q)=\infty. The swap is finite, KL(q ∥ p)=0.418\mathrm{KL}(q\,\|\,p)=0.418 bits, since pp has no zeros. A zero in pp is harmless in KL(p ∥ q)\mathrm{KL}(p\,\|\,q) and a zero in qq is not. In practice a very small qq on something that happens gives a very large value, as the widget below shows.

The triangle inequality can fail. A distance must satisfy d(a,c)≤d(a,b)+d(b,c)d(a,c)\le d(a,b)+d(b,c), and KL need not. A short counterexample with three Gaussians is in the box below. KL is called a divergence for this reason: it is non-negative and 00 only for equal distributions, but it has no promise of symmetry or of the triangle inequality.

Go deeper A counterexample to the triangle inequality

For two Gaussians with the same standard deviation σ\sigma, the closed form of the next section gives KL=(μ1−μ2)22σ2\mathrm{KL}=\frac{(\mu_1-\mu_2)^2}{2\sigma^2}. Take σ=1\sigma=1 and the three Gaussians a=N(0,1)a=\mathcal N(0,1), b=N(1,1)b=\mathcal N(1,1), c=N(2,1)c=\mathcal N(2,1). Then KL(a ∥ b)=12\mathrm{KL}(a\,\|\,b)=\frac12 and KL(b ∥ c)=12\mathrm{KL}(b\,\|\,c)=\frac12, so the detour through bb costs 11, but KL(a ∥ c)=222=2\mathrm{KL}(a\,\|\,c)=\frac{2^2}{2}=2. The direct route costs more than the detour, which a distance would not allow. The reason is that KL grows with the square of the gap between the means.

A symmetric relative. The Jensen–Shannon divergence averages the two KLs against the midpoint m=12(p+q)m=\frac12(p+q): JS(p,q)=12KL(p ∥ m)+12KL(q ∥ m)\mathrm{JS}(p,q)=\frac12\mathrm{KL}(p\,\|\,m)+\frac12\mathrm{KL}(q\,\|\,m). It is symmetric, stays finite even when one distribution has zeros, and lies between 00 and ln⁡2\ln2 nats. For the example it is 0.02640.0264 nats (0.03800.0380 bits). The square root of the JS divergence satisfies the triangle inequality, so it is a true distance. This lesson uses it only as a name; KL is the one that appears in the training objectives below.

KL between two Gaussians

Gaussians have a closed form, which is why they appear in so many training objectives. For p=N(μ1,σ12)p=\mathcal N(\mu_1,\sigma_1^2) and q=N(μ2,σ22)q=\mathcal N(\mu_2,\sigma_2^2) in one dimension, in nats,

KL=ln⁡σ2σ1+σ12+(μ1−μ2)22σ22−12.\begin{aligned} \mathrm{KL}&=\ln\frac{\sigma_2}{\sigma_1}\\ &\quad+\frac{\sigma_1^2+(\mu_1-\mu_2)^2}{2\sigma_2^2}-\frac12. \end{aligned}

Check the two corners. If the Gaussians are equal, μ1=μ2\mu_1=\mu_2 and σ1=σ2\sigma_1=\sigma_2, then ln⁡1+12−12=0\ln1+\frac12-\frac12=0. If only the means differ, the formula is (μ1−μ2)22σ2\frac{(\mu_1-\mu_2)^2}{2\sigma^2}, the squared gap between the means measured in units of the standard deviation.

A worked example. Let p=N(0,1)p=\mathcal N(0,1) and q=N(1,22)q=\mathcal N(1,2^2). Then μ1=0\mu_1=0, σ1=1\sigma_1=1, μ2=1\mu_2=1, σ2=2\sigma_2=2:

KL(p ∥ q)=ln⁡2+1+18−12=0.6931+0.25−0.5=0.4431.\begin{aligned} \mathrm{KL}(p\,\|\,q)&=\ln2+\frac{1+1}{8}-\frac12\\ &=0.6931+0.25-0.5\\ &=0.4431. \end{aligned}

Swapping the roles puts μ1=1, σ1=2, μ2=0, σ2=1\mu_1=1,\ \sigma_1=2,\ \mu_2=0,\ \sigma_2=1 and gives KL(q ∥ p)=ln⁡12+4+12−12=−0.6931+2.5−0.5=1.3069\mathrm{KL}(q\,\|\,p)=\ln\frac12+\frac{4+1}{2}-\frac12=-0.6931+2.5-0.5=1.3069 nats. The asymmetry is large here, 0.44310.4431 against 1.30691.3069. Intuitively, qq is wide and pp narrow. Using the wide qq to model data from the narrow pp wastes little, but using the narrow pp to model data from the wide qq is surprised by the points in the tails of qq.

The case in variational autoencoders. When the second Gaussian is the standard one, N(0,1)\mathcal N(0,1), the formula becomes

KL(N(μ,σ2) ∥ N(0,1))=12(σ2+μ2−1−ln⁡σ2).\begin{aligned} &\mathrm{KL}\bigl(\mathcal N(\mu,\sigma^2)\,\|\,\mathcal N(0,1)\bigr)\\ &=\tfrac12\bigl(\sigma^2+\mu^2-1-\ln\sigma^2\bigr). \end{aligned}

For μ=1\mu=1 and σ=0.5\sigma=0.5 this is 12(0.25+1−1+1.3863)=0.8181\frac12(0.25+1-1+1.3863)=0.8181 nats, and it is exactly 00 at μ=0\mu=0, σ=1\sigma=1. A variational autoencoder (P8.3) outputs a mean and a standard deviation for each latent coordinate and adds this expression to its loss, which pulls the codes toward the standard Gaussian. Each coordinate adds one such term. The multivariate Gaussians of P1.D7 have a similar formula with covariance matrices, not needed here.

Go deeper Where the Gaussian formula comes from

Write KL(p ∥ q)=Ep[ln⁡p(x)]−Ep[ln⁡q(x)]\mathrm{KL}(p\,\|\,q)=\mathbb{E}_p[\ln p(x)]-\mathbb{E}_p[\ln q(x)] with ln⁡p(x)=−ln⁡σ1−12ln⁡2π−(x−μ1)22σ12\ln p(x)=-\ln\sigma_1-\frac12\ln2\pi-\frac{(x-\mu_1)^2}{2\sigma_1^2} and the same form for qq. Under pp the expected squared deviation from μ1\mu_1 is σ12\sigma_1^2, so Ep[ln⁡p]=−ln⁡σ1−12ln⁡2π−12\mathbb{E}_p[\ln p]=-\ln\sigma_1-\frac12\ln2\pi-\frac12. For qq, Ep[(x−μ2)2]=σ12+(μ1−μ2)2\mathbb{E}_p[(x-\mu_2)^2]=\sigma_1^2+(\mu_1-\mu_2)^2 (the variance plus the squared offset of the means, P1.D4), so Ep[ln⁡q]=−ln⁡σ2−12ln⁡2π−σ12+(μ1−μ2)22σ22\mathbb{E}_p[\ln q]=-\ln\sigma_2-\frac12\ln2\pi-\frac{\sigma_1^2+(\mu_1-\mu_2)^2}{2\sigma_2^2}. Subtracting gives the formula.

Go deeper The KL divergence does not depend on the units

The differential entropy of P1.E2 changes when you change the units of xx: multiplying xx by 10001000 adds ln⁡1000=6.908\ln1000=6.908 nats to it. The KL divergence does not change. Rescale both Gaussians of the example by 10001000 to p=N(0,10002)p=\mathcal N(0,1000^2) and q=N(1000,20002)q=\mathcal N(1000,2000^2): the formula gives ln⁡2+10002+100028×10002−12=0.4431\ln2+\frac{1000^2+1000^2}{8\times1000^2}-\frac12=0.4431 again. The reason is that the density of a rescaled variable changes by the same factor for pp and qq, and that factor cancels in the ratio p(x)q(x)\frac{p(x)}{q(x)} inside the logarithm. The same holds for any one-to-one change of variable. This is why KL is the safe quantity to compare continuous distributions.

Fit one Gaussian to two peaks

Now the main event. Suppose the truth pp has two peaks, and you must describe it with a single Gaussian qq. No Gaussian is right, so the question is which one is least wrong, and the answer depends on which KL you minimize. Below, pp (pink) is a mixture of two Gaussian peaks. You choose the target, then move the Gaussian qq (blue) by dragging its top dot (the mean) and the ring on the axis (the spread), or with the sliders. The two readouts are the numerical KL values in both directions, and the two lower charts show where each one comes from.

Fit one Gaussian to a two-peak target, and read both KL divergences

Target p:
−10−5051000.20.40.6x

“Find best reverse KL” searches from three starting points and lists every local optimum it finds.

Forward integrand p · ln(p/q). Red above 0 adds to KL(p‖q), green below 0 subtracts. The net area is the KL.

−10−5051000.5

Reverse integrand q · ln(q/p). Same colors; the net area is KL(q‖p).

−10−5051000.51
forward KL(p‖q) = 1.46 nats (2.1 bits)
reverse KL(q‖p) = 1.77 nats (2.55 bits)
p has mean −0.6 and standard deviation 3.1. q has mean 0 and standard deviation 1.5.

33% of q's probability lies where p is under a twentieth of q. Reverse KL, which weights by q, charges for this: 1.77 nats, against 1.46 for the forward KL.

The KLs are computed by the trapezoid rule on 6001 evenly spaced points that reach at least 8 standard deviations beyond both curves, so tails outside the plotted range count too. Drag the dot and the ring, or Tab to one and use the arrow keys (0.1) and Page Up and Page Down (1). Values are rounded for display.

A single Gaussian q fitted to a target p that is a mixture of two Gaussian peaks. The pink curve is p, with sliders for the distance between its peaks, the weight of its left peak and the width of each peak, and five presets. The blue curve is q, with a mean and a standard deviation set by a draggable dot and ring or by two sliders. Two readouts give the forward KL, the divergence from p to q, and the reverse KL, the divergence from q to p, in nats and bits, computed by the trapezoid rule on 6001 grid points. The button Best forward KL sets q to the mean and standard deviation of p. The button Find best reverse KL searches for local optima of the reverse KL and lists them, with the lowest one marked. Two lower charts show the integrands p times log of p over q and q times log of q over p, with positive area in red and negative area in green. A status line explains where the current q is charged most.

What to try:

  • Best forward KL. Press “Best forward KL” with “Two peaks”. The Gaussian is centred at −0.6-0.6 with standard deviation 3.103.10, the mean and standard deviation of pp. It is wide and covers both peaks, and it puts more than half of its probability in the valley between them, where pp is small. The forward KL is 0.4640.464 nats and the reverse KL is 0.9430.943.
  • Find best reverse KL. Press it. Three local optima appear. The lowest sits on the left, heavier peak: μ=−2.99\mu=-2.99, σ=1.02\sigma=1.02, reverse KL 0.5070.507 nats. There is also one on the right peak (0.9110.911) and a wide one in the middle (0.8460.846). On the left peak the forward KL is 6.246.24, because 40%40\% of pp (the right peak) lies where qq is under a twentieth of pp.
  • Compare the integrands. At the forward optimum the upper chart has two small red humps over the peaks, where qq is lower than pp, and the lower chart has a taller red hump in the valley, where qq puts mass that pp does not have. On the left peak the lower chart is small and the upper chart has a tall red hump under the right peak, the part of pp that qq ignores.
  • Equal peaks. Choose “Equal peaks” and find the reverse optima: the left and the right peak tie, at 0.6890.689 nats each, close to ln⁡2=0.693\ln2=0.693. A Gaussian sitting on a peak that holds half of pp covers half of pp and ignores the other half, which costs ln⁡2\ln2 when the peaks are far apart.
  • Overlapping peaks. Choose “Overlapping” and press both buttons. With the peaks only 22 apart, one Gaussian is nearly exact: the forward KL is 0.00970.0097 and the reverse KL at the moment-matched qq is 0.01120.0112.
  • Far from p. Set μ=8\mu=8 and σ=0.3\sigma=0.3 with “Two peaks”. The forward KL is 462462 nats and the reverse KL is 14.214.2. A qq that is tiny where pp has mass makes the forward KL enormous.

Forward and reverse KL

When you choose qq from a family to match a target pp, the two directions are two different recipes.

Forward KL, KL(p ∥ q)\mathrm{KL}(p\,\|\,q): weighted by pp. The sum is dominated by the places where pp has probability. At a place where pp has mass and qq is nearly 00, the term plog⁡pqp\log\frac pq is huge, and as qq goes to 00 it is infinite. So qq has to cover everything that pp covers, even if that means spreading thin over a valley. This behaviour is called mass-covering (or zero-avoiding). The forward fit for two peaks is a broad Gaussian over both.

Reverse KL, KL(q ∥ p)\mathrm{KL}(q\,\|\,p): weighted by qq. Now the sum counts only where qq has probability. A place where qq is 00 contributes nothing, even if pp is large there. But where qq puts mass and pp is tiny, qlog⁡qpq\log\frac qp is huge. So qq must stay out of the places where pp is small, and it is free to ignore parts of pp. This is mode-seeking (or zero-forcing). The reverse fit for two far-apart peaks is a narrow Gaussian on one of them, and which one depends on where you start, since each is a separate local optimum of the objective.

WhereForward KL chargesReverse KL charges
qq tiny, pp has massa lotalmost nothing
qq has mass, pp tinylittlea lot

Neither direction is the correct one in general. Forward KL suits cases where missing a possibility is the worst error. Reverse KL suits cases where you want one coherent explanation and can accept that other explanations are left out. The widget shows the price on the default target. The forward fit puts 13%13\% of its probability where pp is under a twentieth of qq. The reverse fit on the left peak leaves 40%40\% of pp (the right peak) where qq is under a twentieth of pp.

Reverse KL does not always pick a peak. When the peaks overlap, the wide Gaussian can win. For two equal peaks of standard deviation 11 a distance 55 apart (set the distance slider to 55 after choosing Equal peaks), the wide Gaussian has reverse KL 0.4810.481 nats and a Gaussian on one peak has 0.6660.666. At a distance 66 the peak wins (0.6890.689 against 0.8410.841), and at 99 the gap is large (0.6930.693 against 2.542.54). So “mode-seeking” describes well-separated peaks, and the best reverse fit still has to be checked, since the local optima can differ.

For the Gaussian family the forward answer has a formula. Minimizing the forward KL over Gaussians q=N(μ,σ2)q=\mathcal N(\mu,\sigma^2) gives the mean of pp for μ\mu and the variance of pp for σ2\sigma^2. This is moment matching. For the widget’s target the mean is 0.6×(−3)+0.4×3=−0.60.6\times(-3)+0.4\times3=-0.6 and the variance is 1+0.6×0.4×62=9.641+0.6\times0.4\times6^2=9.64, so σ=3.105\sigma=3.105. It holds for any pp with a finite mean and variance, not only for mixtures.

Go deeper Why the forward fit of a Gaussian matches the mean and variance

Split KL(p ∥ q)=−H(p)−Ep[ln⁡q(x)]\mathrm{KL}(p\,\|\,q)=-H(p)-\mathbb{E}_p[\ln q(x)]. The entropy of pp does not involve qq, so only the second term matters. For q=N(μ,σ2)q=\mathcal N(\mu,\sigma^2), with mm and vv the mean and variance of pp, Ep[(x−μ)2]=v+(m−μ)2\mathbb{E}_p[(x-\mu)^2]=v+(m-\mu)^2 and so

−Ep[ln⁡q]=ln⁡σ+12ln⁡2π+v+(m−μ)22σ2.\begin{aligned} -\mathbb{E}_p[\ln q]&=\ln\sigma+\tfrac12\ln2\pi\\ &\quad+\frac{v+(m-\mu)^2}{2\sigma^2}. \end{aligned}

The smallest value over μ\mu comes from μ=m\mu=m, whatever σ\sigma is. Put μ=m\mu=m and set the derivative with respect to σ\sigma to zero: 1σ−vσ3=0\frac1\sigma-\frac{v}{\sigma^3}=0, so σ2=v\sigma^2=v. Nothing in the derivation used the shape of pp, only its mean and variance.

Maximum likelihood minimizes the forward KL

Here is why the forward direction matters most in machine learning. Let p^\hat p be the empirical distribution of the data: each data point gets weight 1N\frac1N. By the identity of this lesson, the cross-entropy of the model qθq_{\boldsymbol\theta} against the data is H(p^,qθ)=H(p^)+KL(p^ ∥ qθ)H(\hat p,q_{\boldsymbol\theta})=H(\hat p)+\mathrm{KL}(\hat p\,\|\,q_{\boldsymbol\theta}). It is also the average negative log-likelihood of P1.D10. The entropy H(p^)H(\hat p) does not depend on the parameters θ\boldsymbol\theta, so:

P1.D10 stated this as minimizing KL(q ∥ pθ)\mathrm{KL}(q\,\|\,p_{\boldsymbol\theta}), with the letter qq for the data’s distribution and pθp_{\boldsymbol\theta} for the model; here the letters are the other way round, and the direction is the same: from the data to the model. For a finite data set of real numbers p^\hat p is a set of spikes and has no density, so the KL itself is infinite (or undefined, depending on the convention), but the cross-entropy part is finite, and it is the only part that depends on θ\boldsymbol\theta.

So maximum likelihood is mass-covering. P1.D10 fitted a Gaussian to data that formed two clusters and found a Gaussian centred between them with the large spread 2.532.53. That is moment matching: the sample mean and the 1N\frac1N variance are the mean and variance of p^\hat p, and the fitted Gaussian covers both clusters, just as the forward fit does above. A model family that cannot represent two clusters pays for it with a wide curve.

Where each direction appears

  • Classification (forward, P3.A8). The expected cross-entropy is H(p)+KLH(p)+\mathrm{KL}, so minimizing it brings the model’s probabilities toward the true ones. In the spam example of P1.E3, reporting 0.90.9 when the truth is 0.80.8 costs KL=0.0444\mathrm{KL}=0.0444 nats, and reporting 0.80.8 costs 00.
  • Distillation (P10.F2). A student is trained to match a teacher’s probabilities pp by minimizing KL(p ∥ q)\mathrm{KL}(p\,\|\,q), which is the soft-target cross-entropy of P1.E3 minus a constant, the teacher’s entropy.
  • Variational inference and variational autoencoders (reverse, P8.3). The exact identity ln⁡p(x)=ELBO+KL(q(z) ∥ p(z∣x))\ln p(x)=\mathrm{ELBO}+\mathrm{KL}\bigl(q(z)\,\|\,p(z\mid x)\bigr) holds for any distribution q(z)q(z) over the latent variable zz. The left side does not depend on qq, so maximizing the evidence lower bound (ELBO) is minimizing the reverse KL from the approximation qq to the true posterior. The reverse direction is used because its average is under qq, which can be sampled from, and the posterior only has to be known up to a constant. The part of the ELBO that is a KL between two Gaussians is the closed form above.
  • Fine-tuning a language model (P10.D2). A common objective maximizes a reward minus β\beta times KL(πθ ∥ πref)\mathrm{KL}(\pi_{\boldsymbol\theta}\,\|\,\pi_{\text{ref}}), where πθ\pi_{\boldsymbol\theta} is the model being tuned and πref\pi_{\text{ref}} is the model it started from. It is the divergence of the tuned model from the reference model, with the tuned model first, and its job is to stop the model drifting far from the reference while it chases reward.
  • Diffusion models (P8.8). The variational bound that their training loss comes from is a sum of KL divergences between Gaussians, using the formula of this lesson; the loss used in practice is a simplified form of it.
  • Mutual information (P1.E5). The mutual information of two variables is the KL divergence from their joint distribution to the product of their separate distributions.
  • Monitoring (P12.5). The distribution of an input feature today can be compared with a reference period. Direction matters, and empty bins make KL infinite, so practice smooths the counts or uses a symmetric relative.

Try it

Try it: KL in both directions, Gaussians, and fitting one Gaussian to two peaks

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

The first block prints 0.14320.1432 bits (0.09930.0993 nats) for KL(p ∥ q)\mathrm{KL}(p\,\|\,q), the same number from H(p,q)−H(p)H(p,q)-H(p), and 0.16830.1683 bits for the swap. The second prints inf for KL(p ∥ q0)\mathrm{KL}(p\,\|\,q_0) and 0.41830.4183 for the swap. The third shows that the closed form and the numerical integral agree, 0.44310.4431 and 1.30691.3069 nats, and prints the VAE term 0.81810.8181. The fourth shows 2.02.0 against 1.01.0. The fifth searches a grid: the best forward fit is μ=−0.6\mu=-0.6, σ=3.1\sigma=3.1 (0.4640.464 nats), the best reverse fit is μ=−3.0\mu=-3.0, σ=1.0\sigma=1.0 (0.5080.508), and restricting μ\mu to the right side finds the right peak (0.9120.912). Challenge: change the weights 0.60.6 and 0.40.4 to 0.50.5 and 0.50.5 and see the two reverse optima tie. Then change the peak at 33 to 22 and watch the best reverse fit move away from a single peak.

Intuition, math and code at a glance

Intuition

The KL divergence is the price of believing the wrong distribution. The truth decides which outcomes occur, and the model decides how surprised it is by them. The KL is how much more surprised the model is than the truth itself, averaged over what happens, and it is at least 00. Because the average is taken under the first distribution, swapping the two changes what is emphasized. When you fit a simple qq to a complicated pp, minimizing the forward KL makes qq afraid of missing anything pp can produce, so it spreads out and covers everything. Minimizing the reverse KL makes qq afraid of putting probability where pp has none, so it can settle on one part of pp and leave the rest out.

Math

KL=∑xp(x)log⁡p(x)q(x)=H(p,q)−H(p) ≥ 0\begin{aligned} \mathrm{KL}&=\sum_x p(x)\log\frac{p(x)}{q(x)}\\ &=H(p,q)-H(p)\ \ge\ 0 \end{aligned}

For two Gaussians, in nats:

KL=ln⁡σ2σ1+σ12+(μ1−μ2)22σ22−12\begin{aligned} \mathrm{KL}&=\ln\frac{\sigma_2}{\sigma_1}\\ &\quad+\frac{\sigma_1^2+(\mu_1-\mu_2)^2}{2\sigma_2^2}-\frac12 \end{aligned}

Facts to remember:

  • it is 00 exactly when p=qp=q, and at least 00 otherwise
  • it is not symmetric, the triangle inequality can fail, and it is ∞\infty if q(x)=0q(x)=0 where p(x)>0p(x)>0
  • bits for log⁡2\log_2, nats for ln⁡\ln; frameworks use nats
  • for a one-hot label, KL(y ∥ q)=−log⁡qtrue\mathrm{KL}(\mathbf y\,\|\,\mathbf q)=-\log q_{\text{true}}
  • forward KL (averaged under pp): covers pp, and for a Gaussian qq the best fit has the mean and variance of pp; it is what maximum likelihood minimizes
  • reverse KL (averaged under qq): can lock onto one peak; it is what variational inference minimizes
  • KL does not depend on the units or coordinates of a continuous variable

Questions that come up:

  • Why is the cross-entropy loss the same as minimizing KL? The entropy term does not depend on the model.
  • Why is KL not a distance? It is not symmetric and the triangle inequality can fail.
  • Which direction gives a model that covers all modes? The forward direction.
  • Why can the KL be infinite? A model that gives probability 00 to something that happens.

Code

KL for discrete distributions in NumPy, with the convention 0log⁡0=00\log0=0, and the Gaussian closed form. In PyTorch, torch.nn.functional.kl_div takes log-probabilities as its first argument and probabilities as its second (the second is the target pp), and returns ∑p(log⁡p−input)\sum p(\log p-\text{input}), which is KL(p ∥ q)\mathrm{KL}(p\,\|\,q) when the input is log⁡q\log q. Use reduction='batchmean' to match the usual definition; the default averages over every element instead of over the examples.

import numpy as np

def kl(p, q):                       # in nats; p and q sum to 1
    p, q = np.asarray(p, float), np.asarray(q, float)
    m = p > 0                       # terms with p = 0 count as 0
    return np.inf if np.any(q[m] == 0) else float(np.sum(p[m] * np.log(p[m] / q[m])))

def kl_gauss(m1, s1, m2, s2):       # KL(N(m1, s1^2) || N(m2, s2^2)) in nats
    return np.log(s2 / s1) + (s1**2 + (m1 - m2)**2) / (2 * s2**2) - 0.5

print(kl([0.7, 0.2, 0.1], [0.5, 0.25, 0.25]))   # about 0.0993
print(kl_gauss(0, 1, 1, 2))                      # about 0.4431

Common mistakes

Check your understanding

  1. The true distribution is p=(0.7, 0.2, 0.1)p=(0.7,\,0.2,\,0.1) and a model predicts q=(0.5, 0.25, 0.25)q=(0.5,\,0.25,\,0.25). What is KL(p ∥ q)\mathrm{KL}(p\,\|\,q)?

  2. Which statement about KL(p ∥ q)\mathrm{KL}(p\,\|\,q) is correct?

  3. A Gaussian qq is fitted to a target pp with two well-separated peaks by minimizing the forward KL, KL(p ∥ q)\mathrm{KL}(p\,\|\,q). What does the best qq look like?

  4. Why can the reverse KL, KL(q ∥ p)\mathrm{KL}(q\,\|\,p), leave one peak of pp without any probability from qq?

  5. Maximum likelihood fits the parameters of a model qθq_{\boldsymbol\theta} to data. Which divergence does it minimize?

Exercises

  1. A fair coin has p=(0.5,0.5)p=(0.5,0.5) and a model says q=(0.9,0.1)q=(0.9,0.1). Find KL(p ∥ q)\mathrm{KL}(p\,\|\,q) and KL(q ∥ p)\mathrm{KL}(q\,\|\,p) in bits.
    Show answerKL(p ∥ q)=0.5log⁡20.50.9+0.5log⁡20.50.1=0.5(−0.848)+0.5(2.322)=0.737\mathrm{KL}(p\,\|\,q)=0.5\log_2\frac{0.5}{0.9}+0.5\log_2\frac{0.5}{0.1}=0.5(-0.848)+0.5(2.322)=0.737 bits, which is H(p,q)−H(p)=1.737−1H(p,q)-H(p)=1.737-1 from P1.E3. KL(q ∥ p)=0.9log⁡20.90.5+0.1log⁡20.10.5=0.9(0.848)+0.1(−2.322)=0.531\mathrm{KL}(q\,\|\,p)=0.9\log_2\frac{0.9}{0.5}+0.1\log_2\frac{0.1}{0.5}=0.9(0.848)+0.1(-2.322)=0.531 bits, which is 1−0.4691-0.469. They differ.
  2. Convert KL(p ∥ q)=0.737\mathrm{KL}(p\,\|\,q)=0.737 bits to nats.
    Show answer0.737×ln⁡2=0.5110.737\times\ln2=0.511 nats. Going the other way, divide nats by ln⁡2\ln2.
  3. A model gives q=(1,0)q=(1,0) for a fair coin p=(0.5,0.5)p=(0.5,0.5). Find both directions in bits.
    Show answerKL(p ∥ q)=∞\mathrm{KL}(p\,\|\,q)=\infty, because the second term is 0.5log⁡20.500.5\log_2\frac{0.5}{0}. KL(q ∥ p)=1×log⁡210.5=1\mathrm{KL}(q\,\|\,p)=1\times\log_2\frac{1}{0.5}=1 bit, a term with q=0q=0 adds 00. The forward direction punishes the model that rules out tails, and the reverse direction does not notice.
  4. Find KL(N(0,1) ∥ N(1,22))\mathrm{KL}(\mathcal N(0,1)\,\|\,\mathcal N(1,2^2)) and the reverse in nats.
    Show answerln⁡2+1+18−12=0.4431\ln2+\frac{1+1}{8}-\frac12=0.4431 and ln⁡12+4+12−12=1.3069\ln\frac12+\frac{4+1}{2}-\frac12=1.3069.
  5. A variational autoencoder coordinate has mean μ=1\mu=1 and standard deviation σ=0.5\sigma=0.5. Find the KL term against the standard Gaussian, and the values of μ\mu and σ\sigma that make it 00.
    Show answer12(0.25+1−1−ln⁡0.25)=12(0.25+1.3863)=0.8181\frac12(0.25+1-1-\ln0.25)=\frac12(0.25+1.3863)=0.8181 nats. It is 00 at μ=0\mu=0, σ=1\sigma=1, where 12(1+0−1−0)=0\frac12(1+0-1-0)=0.
  6. A target p=12N(−3,1)+12N(3,1)p=\frac12\mathcal N(-3,1)+\frac12\mathcal N(3,1) is fitted by one Gaussian. What are the forward-KL optimum and the reverse-KL value on one peak?
    Show answerThe mean of pp is 00 and its variance is 1+9=101+9=10, so the forward optimum is N(0, 10)\mathcal N(0,\ 10), standard deviation 3.1623.162, with forward KL 0.4620.462 nats. A Gaussian on one peak (μ≈±2.98\mu\approx\pm2.98, σ≈1.02\sigma\approx1.02) has reverse KL 0.6890.689 nats, close to ln⁡2=0.693\ln2=0.693, because it covers half of pp and none of the other half. There are two such fits, one for each peak, with equal value.
  7. In the spam example of P1.E3 the truth is 0.80.8 and a model reports 0.90.9. Find KL(p ∥ q)\mathrm{KL}(p\,\|\,q) in nats for the two outcomes, and the KL of the swap.
    Show answer0.8ln⁡0.80.9+0.2ln⁡0.20.1=−0.0942+0.1386=0.04440.8\ln\frac{0.8}{0.9}+0.2\ln\frac{0.2}{0.1}=-0.0942+0.1386=0.0444 nats, the gap 0.5448−0.50040.5448-0.5004 in P1.E3. The swap is 0.9ln⁡0.90.8+0.1ln⁡0.10.2=0.1060−0.0693=0.03670.9\ln\frac{0.9}{0.8}+0.1\ln\frac{0.1}{0.2}=0.1060-0.0693=0.0367 nats.
  8. A one-hot label puts probability 11 on the true class and the model gives it 0.250.25. What is KL(y ∥ q)\mathrm{KL}(\mathbf y\,\|\,\mathbf q) in nats?
    Show answerThe entropy of a one-hot label is 00, and the only term with y>0y>0 is 1×ln⁡10.251\times\ln\frac{1}{0.25}, so the KL is −ln⁡0.25=1.386-\ln0.25=1.386 nats, the cross-entropy loss of P1.E3. The KL and the cross-entropy are equal for a one-hot target.

Next: P1.E5 covers mutual information, which is the KL divergence from a joint distribution to the product of its marginals, and perplexity. P3.A8 trains softmax regression by minimizing the cross-entropy, P8.3 uses the Gaussian KL in variational autoencoders, and P10.D2 uses a KL penalty to a reference model in RLHF.

Key takeaways

  • The KL divergence of a model qq from the truth pp is KL(p ∥ q)=∑xp(x)log⁡p(x)q(x)=H(p,q)−H(p)\mathrm{KL}(p\,\|\,q)=\sum_x p(x)\log\frac{p(x)}{q(x)}=H(p,q)-H(p): the extra average surprise, or the extra bits per symbol, from using qq instead of pp. For p=(0.7,0.2,0.1)p=(0.7,0.2,0.1) and q=(0.5,0.25,0.25)q=(0.5,0.25,0.25) it is 0.1430.143 bits (0.09930.0993 nats). One term of the sum can be negative, but the sum cannot.
  • For every pair of distributions KL(p ∥ q)≥0\mathrm{KL}(p\,\|\,q)\ge0, and it is 00 exactly when p=qp=q (Gibbs' inequality). The proof uses ln⁡u≤u−1\ln u\le u-1. So a loss built from KL has its lowest value, 00, when the model equals the truth.
  • KL measures how different two distributions are but is not a distance. It is not symmetric: KL(q ∥ p)=0.168\mathrm{KL}(q\,\|\,p)=0.168 bits for the same example. The triangle inequality can fail. It is infinite when q(x)=0q(x)=0 where p(x)>0p(x)>0, while a zero in pp is harmless in KL(p ∥ q)\mathrm{KL}(p\,\|\,q).
  • For Gaussians p=N(μ1,σ12)p=\mathcal N(\mu_1,\sigma_1^2) and q=N(μ2,σ22)q=\mathcal N(\mu_2,\sigma_2^2): KL(p ∥ q)=ln⁡σ2σ1+σ12+(μ1−μ2)22σ22−12\mathrm{KL}(p\,\|\,q)=\ln\frac{\sigma_2}{\sigma_1}+\frac{\sigma_1^2+(\mu_1-\mu_2)^2}{2\sigma_2^2}-\frac12 nats. Against N(0,1)\mathcal N(0,1) it is 12(σ2+μ2−1−ln⁡σ2)\frac12(\sigma^2+\mu^2-1-\ln\sigma^2), the KL term of a variational autoencoder.
  • Forward KL, KL(p ∥ q)\mathrm{KL}(p\,\|\,q), averages under pp, so qq is charged wherever pp has mass and a fitted Gaussian spreads out to cover it: its mean and variance equal those of pp. Reverse KL, KL(q ∥ p)\mathrm{KL}(q\,\|\,p), averages under qq, so qq is charged only where it puts mass, and a fitted Gaussian can lock onto one peak of pp and ignore the rest.
  • Maximum likelihood and the cross-entropy loss minimize the forward KL from the data's distribution to the model. Variational inference and the KL penalty that keeps a fine-tuned language model near its starting model use the reverse direction, with the model being trained first.
Found a mistake? Tell us