TL;DR
Suppose the world produces outcomes with distribution , but you describe them with a model . KL divergence, written , is the average extra surprise you pay for using in place of . It is never negative, and it is zero only when and agree everywhere.
It is not a distance. It is not symmetric, so the cost of believing when is true differs from the cost of the reverse.
Where you'll see it: in the loss that trains variational autoencoders, in the cross-entropy loss used to train classifiers, and in the penalty that keeps a fine-tuned language model close to its original.
Intuition
Paying for a wrong model
Imagine a weather forecaster who thinks rain has probability each day, while the true chance is . Each day, the forecaster's surprise is not the surprise the true process would produce. Rain feels less surprising to them than it should, and dry days feel more surprising. Averaged over many days, the forecaster loses some bits per day compared with someone who knew the true odds.
KL divergence is exactly that loss. It is measured against the best achievable, which is the entropy of the true distribution (see Entropy). The extra cost of using is the number of bits you waste on average.
- D(P || Q) with Q = (0.5, 0.5)
The curve shows the key feature: the cost is zero only at the match, and it grows as the mismatch grows. The plot fixes as a fair coin, so it cannot show that swapping and changes the answer. The math section explains that asymmetry.
The math
Definition
For two probability distributions and on the same set of outcomes, with and their probabilities, the KL divergence of from is
in bits, and the same expression with the natural logarithm gives it in nats. For continuous distributions the sum becomes an integral over the density:
Read the definition as an expectation. It is the average, under , of the log ratio . Where puts weight and does not, the ratio blows up, so the divergence is infinite. Where puts no weight, the term is zero by convention, since .
Decomposition into entropy and cross-entropy
Split the logarithm: . Then
The first term is the average code length when you encode outcomes from using a code designed for . The second is the best possible average code length for . Their difference is the waste. This is why KL and cross-entropy are so closely tied: when is fixed, minimising cross-entropy over is the same as minimising KL.
Non-negativity (Gibbs' inequality)
The divergence is never negative, and it is zero only when . A short proof uses Jensen's inequality for the concave logarithm, with weights :
The last step uses the fact that 's probabilities sum to at most 1. Equality throughout forces wherever is positive.
Asymmetry
In general . The two directions weight the log ratio by different distributions, so they answer different questions. It also fails the triangle inequality, so it is not a metric. People sometimes call it a divergence for this reason.
Gaussian closed form
When both distributions are univariate Gaussians, the integral has a closed form. With natural logarithms,
Setting and gives zero, as it should. This formula is what makes KL cheap to compute inside neural network training, where distributions are Gaussian by design.
For a diagonal Gaussian against the standard normal in dimensions, the same calculation coordinate by coordinate gives
This is the regularisation term in a variational autoencoder, and it is the reason the encoder's outputs are pulled toward the standard normal.
Worked examples
Let describe a fair coin, and describe a model that expects tails.
- Write the divergence from to : .
- The first ratio is 2, so . The second ratio is , and .
- Combine: bits.
- Now reverse the roles: .
- The first term is . The second is . Sum: bits.
- The two directions give and bits. They differ, which confirms the asymmetry. Both are positive, as Gibbs' inequality requires.
A classifier sees an image of a cat. The true label is one-hot, so on the classes (dog, cat, bird). The model predicts .
- The entropy of a one-hot label is zero, because there is no uncertainty: .
- So the KL divergence equals the cross-entropy, which is the only nonzero term: nats.
- If the model had been less sure, predicting for cat, the loss would be nats. Training pushes up, and every reduction in loss is a reduction in KL.
Let and . Outcome 2 has probability under but probability 0 under .
- The term for outcome 2 is , and the ratio is infinite.
- So . The model claims an outcome is impossible when it is possible.
- The reverse, , is finite, because the outcome where puts all its weight has . Asymmetry again.
Tradeoffs and failure modes
Which direction you minimise matters, and the two choices behave differently:
| Objective | Behaviour | Typical use |
|---|---|---|
| , with the data distribution first | Forces to cover every place has mass. A model that misses a mode is punished heavily. | Maximum likelihood, cross-entropy training |
| , with the model first | Lets sit on one mode and ignore others, because placing mass where is zero is punished. | Variational inference, many RL penalties |
Other practical points:
- Zero probabilities break it. If is zero where is positive, the divergence is infinite. Smoothing or mixing with a small uniform term avoids this.
- Disjoint supports carry no gradient information. When and have no overlap, KL is infinite or constant, so it cannot guide a model toward the data. Distances such as the Wasserstein distance, which stay finite and informative for disjoint supports, are used instead.
- Sample estimates are noisy. Estimating KL from samples of is a Monte Carlo average of the log ratio. Its variance can be large when the ratio varies widely, which is common in the tails.
- Units must match. A value in bits and a value in nats differ by . Mixing them in a loss silently changes its weight.
History
Solomon Kullback and Richard Leibler introduced the quantity in 1951, in a paper titled "On Information and Sufficiency". They were working on statistical questions about when data can be summarised without losing information, and they wanted a measure of how well one distribution could discriminate against another. Claude Shannon had defined entropy in 1948, and the Kullback–Leibler divergence can be read as entropy's relative version. Kullback's 1959 book on information theory and statistics made the measure widely used among statisticians.
It spread in machine learning through the connection to maximum likelihood, which is minimising a cross-entropy, and later through variational inference. The variational lower bound used to train VAEs is built from a KL term, and the same idea appears in the reinforcement learning penalties used to keep a fine-tuned model close to its base. It caught on because it is one number that has a clear meaning in bits or nats, a closed form for the common Gaussian case, and a direct link to coding and likelihood.
Check yourself
QuestionIs symmetric in and ? Give a reason, not just the answer.Show answer
No. The divergence weights the log ratio by , so swapping and changes the weights as well as the ratio. The two-coin example gives bits in one direction and bits in the other. The divergence is also not a metric because it fails the triangle inequality.
QuestionLet and . Compute in bits, to three decimal places.Show answer
. The first term is . The second is . The total is bits.
QuestionWhy is the KL divergence never negative? Use the idea of Jensen's inequality, not just the formula.Show answer
The logarithm is concave, so the average of its values is at most the log of the average. Applying this to the ratio , weighted by , the expected log of is at most the log of the sum of over the support of . That sum is at most 1, so the expected log is at most 0, which makes the divergence at least 0. Equality holds only when is constant on the support, which with probabilities summing to 1 means .
QuestionA VAE encoder outputs a Gaussian with mean and standard deviation for one latent dimension. Using the standard normal as the prior, what is this dimension's contribution to the KL term, in nats?Show answer
Use . Here , , and . So the term is nats. A smaller would raise the penalty through the term, which is why the encoder cannot collapse to a point.