P1.E3 ended with a split. The cross-entropy of a model against the truth is the entropy , which belongs to the data, plus an extra cost that belongs to the model. For and the extra was 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 and 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 and :
Read the last form as an average. Outcome happens with probability . The model finds it surprising and the truth finds it surprising, so the difference is , and the formula averages that difference over what really happens. Equivalently, . 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 add , by the same convention as in P1.E2 and P1.E3. For a variable with a density the sum becomes an integral, , and everything below holds in the same form.
The example, term by term. Take and in bits:
The sum is bits, matching from P1.E3. In nats, the unit that machine-learning code uses, it is . Two things to notice. The model underrates the first class ( against ) 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 , but the whole sum cannot be, as the next section shows.
Units. The base of the logarithm sets the unit: bits for and nats for . As for entropy, , so bits is nats.
The extra is at least zero
For every pair of distributions and over the same outcomes,
and exactly when . This is Gibbs’ inequality, the fact behind 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, , is reached when the model is exactly right.
Go deeper Why KL is at least zero
Use natural logs. Let be the outcomes with , so the sums run over . The fact needed is for every , with equality only at (the picture: the curve lies below its tangent line at ). Apply it with :
So . Equality needs for every in , and then forces outside too, so . The proof is the one that P1.D10 and P1.E3 used. The version with Jensen’s inequality (P1.D4) reads , because is concave. For densities the proof is the same with integrals, and equality holds when except on a set of probability .
It is not a distance
KL is 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 and the extra is bits. Compare:
These are two different questions. asks how much extra it costs to use when is the truth. asks the reverse. Weights come from the first argument, so the two sums emphasize different outcomes. This is the same asymmetry as against in P1.E3, because the entropies also differ ( and ).
It can be infinite. If the model says for an outcome that can happen, , the term is infinite, and so is . With against , . The swap is finite, bits, since has no zeros. A zero in is harmless in and a zero in is not. In practice a very small on something that happens gives a very large value, as the widget below shows.
The triangle inequality can fail. A distance must satisfy , 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 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 , the closed form of the next section gives . Take and the three Gaussians , , . Then and , so the detour through costs , but . 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 : . It is symmetric, stays finite even when one distribution has zeros, and lies between and nats. For the example it is nats ( 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 and in one dimension, in nats,
Check the two corners. If the Gaussians are equal, and , then . If only the means differ, the formula is , the squared gap between the means measured in units of the standard deviation.
A worked example. Let and . Then , , , :
Swapping the roles puts and gives nats. The asymmetry is large here, against . Intuitively, is wide and narrow. Using the wide to model data from the narrow wastes little, but using the narrow to model data from the wide is surprised by the points in the tails of .
The case in variational autoencoders. When the second Gaussian is the standard one, , the formula becomes
For and this is nats, and it is exactly at , . 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 with and the same form for . Under the expected squared deviation from is , so . For , (the variance plus the squared offset of the means, P1.D4), so . 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 : multiplying by adds nats to it. The KL divergence does not change. Rescale both Gaussians of the example by to and : the formula gives again. The reason is that the density of a rescaled variable changes by the same factor for and , and that factor cancels in the ratio 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 has two peaks, and you must describe it with a single Gaussian . No Gaussian is right, so the question is which one is least wrong, and the answer depends on which KL you minimize. Below, (pink) is a mixture of two Gaussian peaks. You choose the target, then move the Gaussian (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.
What to try:
- Best forward KL. Press “Best forward KL” with “Two peaks”. The Gaussian is centred at with standard deviation , the mean and standard deviation of . It is wide and covers both peaks, and it puts more than half of its probability in the valley between them, where is small. The forward KL is nats and the reverse KL is .
- Find best reverse KL. Press it. Three local optima appear. The lowest sits on the left, heavier peak: , , reverse KL nats. There is also one on the right peak () and a wide one in the middle (). On the left peak the forward KL is , because of (the right peak) lies where is under a twentieth of .
- Compare the integrands. At the forward optimum the upper chart has two small red humps over the peaks, where is lower than , and the lower chart has a taller red hump in the valley, where puts mass that 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 that ignores.
- Equal peaks. Choose “Equal peaks” and find the reverse optima: the left and the right peak tie, at nats each, close to . A Gaussian sitting on a peak that holds half of covers half of and ignores the other half, which costs when the peaks are far apart.
- Overlapping peaks. Choose “Overlapping” and press both buttons. With the peaks only apart, one Gaussian is nearly exact: the forward KL is and the reverse KL at the moment-matched is .
- Far from p. Set and with “Two peaks”. The forward KL is nats and the reverse KL is . A that is tiny where has mass makes the forward KL enormous.
Forward and reverse KL
When you choose from a family to match a target , the two directions are two different recipes.
Forward KL, : weighted by . The sum is dominated by the places where has probability. At a place where has mass and is nearly , the term is huge, and as goes to it is infinite. So has to cover everything that 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, : weighted by . Now the sum counts only where has probability. A place where is contributes nothing, even if is large there. But where puts mass and is tiny, is huge. So must stay out of the places where is small, and it is free to ignore parts of . 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.
| Where | Forward KL charges | Reverse KL charges |
|---|---|---|
| tiny, has mass | a lot | almost nothing |
| has mass, tiny | little | a 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 of its probability where is under a twentieth of . The reverse fit on the left peak leaves of (the right peak) where is under a twentieth of .
Reverse KL does not always pick a peak. When the peaks overlap, the wide Gaussian can win. For two equal peaks of standard deviation a distance apart (set the distance slider to after choosing Equal peaks), the wide Gaussian has reverse KL nats and a Gaussian on one peak has . At a distance the peak wins ( against ), and at the gap is large ( against ). 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 gives the mean of for and the variance of for . This is moment matching. For the widget’s target the mean is and the variance is , so . It holds for any 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 . The entropy of does not involve , so only the second term matters. For , with and the mean and variance of , and so
The smallest value over comes from , whatever is. Put and set the derivative with respect to to zero: , so . Nothing in the derivation used the shape of , only its mean and variance.
Maximum likelihood minimizes the forward KL
Here is why the forward direction matters most in machine learning. Let be the empirical distribution of the data: each data point gets weight . By the identity of this lesson, the cross-entropy of the model against the data is . It is also the average negative log-likelihood of P1.D10. The entropy does not depend on the parameters , so:
P1.D10 stated this as minimizing , with the letter for the data’s distribution and 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 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 .
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 . That is moment matching: the sample mean and the variance are the mean and variance of , 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 , so minimizing it brings the model’s probabilities toward the true ones. In the spam example of P1.E3, reporting when the truth is costs nats, and reporting costs .
- Distillation (P10.F2). A student is trained to match a teacher’s probabilities by minimizing , 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 holds for any distribution over the latent variable . The left side does not depend on , so maximizing the evidence lower bound (ELBO) is minimizing the reverse KL from the approximation to the true posterior. The reverse direction is used because its average is under , 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 times , where is the model being tuned and 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
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The first block prints bits ( nats) for , the same number from , and bits for the swap. The second prints inf for and for the swap. The third shows that the closed form and the numerical integral agree, and nats, and prints the VAE term . The fourth shows against . The fifth searches a grid: the best forward fit is , ( nats), the best reverse fit is , (), and restricting to the right side finds the right peak (). Challenge: change the weights and to and and see the two reverse optima tie. Then change the peak at to 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 . Because the average is taken under the first distribution, swapping the two changes what is emphasized. When you fit a simple to a complicated , minimizing the forward KL makes afraid of missing anything can produce, so it spreads out and covers everything. Minimizing the reverse KL makes afraid of putting probability where has none, so it can settle on one part of and leave the rest out.
Math
For two Gaussians, in nats:
Facts to remember:
- it is exactly when , and at least otherwise
- it is not symmetric, the triangle inequality can fail, and it is if where
- bits for , nats for ; frameworks use nats
- for a one-hot label,
- forward KL (averaged under ): covers , and for a Gaussian the best fit has the mean and variance of ; it is what maximum likelihood minimizes
- reverse KL (averaged under ): 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 to something that happens.
Code
KL for discrete distributions in NumPy, with the convention , 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 ), and returns , which is when the input is . 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.4431Common mistakes
Check your understanding
The true distribution is and a model predicts . What is ?
The KL is the cross-entropy minus the entropy, bits, which also comes from adding the three terms . The value bits is the cross-entropy itself. The value bits is the entropy of . The value bits is , with the roles swapped.
Which statement about is correct?
This is Gibbs' inequality. The two orders give different numbers in general ( against bits in the lesson example). The triangle inequality can fail: three Gaussians with equal spread and means , and give for the direct route and for the detour. A zero in where is positive makes a term , which is infinite.
A Gaussian is fitted to a target with two well-separated peaks by minimizing the forward KL, . What does the best look like?
The forward KL is averaged under , so is charged wherever has mass, and for the Gaussian family the minimizer has the mean and variance of , which spreads it over both peaks. Locking onto one peak is the behaviour of the reverse KL. A fixed standard Gaussian ignores . A single Gaussian cannot have two peaks, so two narrow Gaussians is not an option in this family.
Why can the reverse KL, , leave one peak of without any probability from ?
Each term is weighted by , so an outcome that gives probability near contributes almost nothing, even when is large there. The statement about averaging under describes the forward direction. The reverse KL is finite for the Gaussian fits in the lesson, since a Gaussian is positive everywhere. It is also not symmetric.
Maximum likelihood fits the parameters of a model to data. Which divergence does it minimize?
The average negative log-likelihood is the cross-entropy of the model against the data, which is the entropy of the data (it does not depend on the parameters) plus . The reverse direction is what variational inference minimizes. The Jensen–Shannon divergence is not in the likelihood. Matching the means is only part of what a Gaussian fit does, which also matches the variance.
Exercises
- A fair coin has and a model says . Find and in bits.
Show answer
bits, which is from P1.E3. bits, which is . They differ. - Convert bits to nats.
Show answer
nats. Going the other way, divide nats by . - A model gives for a fair coin . Find both directions in bits.
Show answer
, because the second term is . bit, a term with adds . The forward direction punishes the model that rules out tails, and the reverse direction does not notice. - Find and the reverse in nats.
Show answer
and . - A variational autoencoder coordinate has mean and standard deviation . Find the KL term against the standard Gaussian, and the values of and that make it .
Show answer
nats. It is at , , where . - A target is fitted by one Gaussian. What are the forward-KL optimum and the reverse-KL value on one peak?
Show answer
The mean of is and its variance is , so the forward optimum is , standard deviation , with forward KL nats. A Gaussian on one peak (, ) has reverse KL nats, close to , because it covers half of and none of the other half. There are two such fits, one for each peak, with equal value. - In the spam example of P1.E3 the truth is and a model reports . Find in nats for the two outcomes, and the KL of the swap.
Show answer
nats, the gap in P1.E3. The swap is nats. - A one-hot label puts probability on the true class and the model gives it . What is in nats?
Show answer
The entropy of a one-hot label is , and the only term with is , so the KL is 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.