The Math Behind the Methods

KL Divergence: Measuring How One Distribution Differs From Another

Compute KL divergence by hand, understand why direction matters, and see how it behaves in training, distillation and monitoring.

Key takeaways

  • KL(p ‖ q) is the expected value under p of ln(p/q), and it is never negative.
  • The divergence is not symmetric, and it is infinite if q gives zero probability to something p can produce.
  • Minimizing cross-entropy against fixed labels is the same as minimizing KL divergence from the labels to the model.
  • Minimizing KL(p ‖ q) pushes a limited model q to cover all of p, while minimizing KL(q ‖ p) lets it settle on part of p.
  • Estimates from finite samples depend heavily on binning and smoothing, especially in high dimensions.

The Kullback-Leibler divergence, or KL divergence, measures how much one probability distribution differs from another. Written KL(p ‖ q), it is the average, over outcomes drawn from p, of the log ratio of p to q. It is zero when the two match and positive otherwise.

It is not a distance in the everyday sense: swapping p and q usually gives a different number. That asymmetry is useful once you know which direction you need.

The definition

For distributions over a discrete set of outcomes:

KL(p ‖ q) = ∑ₓ p(x) ln [ p(x) / q(x) ]

For densities, replace the sum with an integral. Terms with p(x) = 0 count as zero. If p(x) > 0 while q(x) = 0, the divergence is infinite. With the natural logarithm the unit is the nat, and with base 2 it is the bit.

One interpretation comes from coding. If data come from p but you design an ideal code for q, you pay on average KL(p ‖ q) extra units per symbol. Another comes from evidence: it is the expected log likelihood ratio in favor of p over q for each observation actually drawn from p.

A worked example in both directions

Let p describe a fair coin, (0.5, 0.5), and q a biased one, (0.9, 0.1).

KL(p ‖ q) = 0.5 ln(0.5/0.9) + 0.5 ln(0.5/0.1)
          = −0.294 + 0.805
          ≈ 0.511 nats

KL(q ‖ p) = 0.9 ln(0.9/0.5) + 0.1 ln(0.1/0.5)
          = 0.529 − 0.161
          ≈ 0.368 nats

The first is larger because outcomes that are common under p, the second side of the coin, are rare under q. Being surprised often costs a lot. In the other direction, the weighting comes from q, which rarely produces that side.

Individual terms can be negative, as you see above. The total cannot. That follows from the logarithm being concave, through a result called Jensen's inequality.

Relation to entropy and cross-entropy

The entropy H(p) = −∑ p ln p is the average surprise of p itself. The cross-entropy H(p, q) = −∑ p ln q is the average surprise when you believe q. Their difference is the divergence.

KL(p ‖ q) = H(p, q) − H(p)

When p is fixed, such as the empirical distribution of your training labels, H(p) is a constant. Minimizing cross-entropy over the model q therefore minimizes the divergence, and also maximizes likelihood. Cross-entropy from likelihood walks through that path.

When both distributions are being changed, the two objectives are no longer interchangeable, because the entropy term moves.

Forward and reverse

Suppose p is a target with two well-separated peaks and q can only be a single Gaussian.

Forward KL, KL(p ‖ q), averages over p. Anywhere p has mass and q has almost none produces a large penalty. The best single Gaussian therefore spreads to cover both peaks, matching the mean and variance of p, and puts density in the gap.

Reverse KL, KL(q ‖ p), averages over q. Now the penalty falls on placing q where p is nearly zero. The optimum often locks onto one peak and ignores the other.

Fitting one bump to a target with two peaks
Forward: KL(p to q) Averages over the target p Punishes missing any mode Tends to spread wide Maximum likelihood works this way Reverse: KL(q to p) Averages over the model q Punishes mass where p is tiny Tends to pick one mode Common in variational inference VS Forward: KL(p to q) Averages over the target p Punishes missing any mode Tends to spread wide Maximum likelihood works this way Reverse: KL(q to p) Averages over the model q Punishes mass where p is tiny Tends to pick one mode Common in variational inference

The direction is often forced by what you can compute. Forward KL needs samples from p, which data supply. Reverse KL needs samples from q and the ability to evaluate p, perhaps up to a constant, which is the situation in variational inference.

These tendencies are strongest when the model family is too restricted to match the target. If q can represent p exactly, both directions have their minimum at q = p.

The Gaussian formula

For two one-dimensional Gaussians with means μ₁, μ₂ and standard deviations σ₁, σ₂:

KL(N₁ ‖ N₂) = ln(σ₂/σ₁) + [ σ₁² + (μ₁ − μ₂)² ] / (2σ₂²) − 1/2
First Second KL(first ‖ second)
mean 1, sd 1 mean 0, sd 1 0.500
mean 0, sd 1 mean 0, sd 2 0.318
mean 0, sd 2 mean 0, sd 1 0.807

The last two rows show the asymmetry again. A wide distribution measured against a narrow one is penalized more than the reverse.

Setting the second to a standard Gaussian gives ½(μ² + σ² − 1 − ln σ²). Summed over latent dimensions with diagonal covariance, this is the regularizing term in a common form of the variational autoencoder.

Where you will meet it

  • Distillation. A student is trained to reduce the divergence from a teacher's output distribution to its own, usually after softening both with a temperature.
  • Policy updates. Several reinforcement learning methods limit or penalize the divergence between the old and new policy so that one update cannot change behavior drastically.
  • Preference tuning. A divergence penalty often keeps a tuned language model close to its starting model.
  • Drift monitoring. The population stability index sums (a − e) ln(a/e) over bins, which equals KL(a ‖ e) + KL(e ‖ a), a symmetrized version. See drift detection.

Why it can never be negative

The proof is short and worth seeing once. The natural logarithm satisfies ln t ≤ t − 1 for every t > 0, with equality only at t = 1. Apply it to the ratio q/p, summing over outcomes where p is positive.

−KL(p ‖ q) = ∑ p ln(q/p)
           ≤ ∑ p (q/p − 1)
           = ∑ q − ∑ p          over outcomes with p > 0
           ≤ 1 − 1 = 0

So the divergence is at least zero. Equality needs q/p = 1 wherever p is positive, which then leaves no probability for q anywhere else. The two distributions must be identical.

Two further properties are handy. For independent variables, divergences add: the divergence between joint distributions equals the sum of the divergences for each part. And the divergence cannot increase when both distributions are passed through the same processing step, such as merging categories. Coarse bins can therefore hide a difference, but cannot manufacture one between the true distributions. Sampling noise in estimates is a separate matter.

Reading a value as a change in probability

A divergence in nats is abstract, so it helps to anchor it. For two distributions that are close together, KL is approximately half the sum of (q − p)²/p over outcomes.

Take p = (0.5, 0.5) and q = (0.55, 0.45).

approximation:  ½ · (0.05²/0.5 + 0.05²/0.5)              = 0.0050
exact:          0.5 ln(0.5/0.55) + 0.5 ln(0.5/0.45)      ≈ 0.0050

Near zero the two directions nearly agree, and the divergence grows with the square of the shift. Doubling a small shift roughly quadruples it. The same local quadratic form defines the Fisher information metric used by natural gradient methods.

That agreement disappears for large differences, especially where one distribution gives an outcome very little probability.

Symmetric alternatives

The Jensen-Shannon divergence compares each distribution with their midpoint m = (p + q)/2.

JS(p, q) = ½ KL(p ‖ m) + ½ KL(q ‖ m)

It is symmetric, always finite and at most ln 2 in nats. Its square root satisfies the rules of a true metric. Total variation distance, half the sum of absolute differences, is another bounded choice. Wasserstein distance accounts for how far probability must travel, which matters when outcomes have a geometry, such as numbers on a line. KL ignores that: moving mass to a neighboring bin or a distant one can cost the same.

Computing it in code

import numpy as np

def kl(p, q):                      # p, q: arrays of shape (K,) that sum to 1
    p, q = np.asarray(p, float), np.asarray(q, float)
    m = p > 0
    if np.any(q[m] == 0):
        return np.inf
    return np.sum(p[m] * (np.log(p[m]) - np.log(q[m])))

print(kl([0.5, 0.5], [0.9, 0.1]))  # about 0.511
print(kl([0.9, 0.1], [0.5, 0.5]))  # about 0.368

In model code, work with log probabilities from a stable log-softmax. Library functions differ in argument order and in whether they expect probabilities or logarithms. PyTorch's kl_div, for example, takes the model's log probabilities as its first argument and the target as its second, and its reduction setting changes the scale. Check the current documentation and test on the coin example.

Estimating from samples

With data, you rarely know p and q. Histograms are the usual shortcut, and the answer moves with the number of bins. An empty bin in q and a filled one in p gives infinity, so people add a small pseudo-count, which then influences the result. Say which choices you made.

Two samples from the same distribution will show a positive estimated divergence simply through noise. Establish a baseline by randomly splitting reference data and computing the same statistic. In many dimensions, binning breaks down, and estimators based on classifiers or nearest neighbors carry their own bias.

Common questions

Can I average the two directions to get a distance?

Averaging gives symmetry, but not the triangle inequality, so it is still not a metric. It also remains infinite when either distribution misses part of the other.

What counts as a large value?

There is no universal threshold. A value depends on the number of outcomes, the binning and the sample size. Compare it with the value you see between periods you consider normal.

Written for 4MachineLearning with AI writing tools and not reviewed line by line by a person. Check anything you rely on against a textbook or primary source. Report an error.

Keep reading

All 26 articles in The Math Behind the Methods →

Latest news on this topic