Search

Search papers and lessons

Kullback–Leibler Divergence

Level 3 · 9 min read

KL divergence measures how much extra surprise you get when you model a distribution P with a different distribution Q, and it is zero only when the two match.

On this page

  • Colour = topic mix
  • Calculus
  • Probability
  • Discrete math
  • Information theory
  • Sign in to see your progress

TL;DR

Suppose the world produces outcomes with distribution PP, but you describe them with a model QQ. KL divergence, written DKL(P ∥ Q)D_{\mathrm{KL}}(P \,\|\, Q), is the average extra surprise you pay for using QQ in place of PP. It is never negative, and it is zero only when QQ and PP agree everywhere.

It is not a distance. It is not symmetric, so the cost of believing QQ when PP 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 0.50.5 each day, while the true chance is 0.90.9. 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 QQ is the number of bits you waste on average.

0.20.40.60.800.20.40.60.811.2p, the true probability of headsKL divergence (bits)
  • D(P || Q) with Q = (0.5, 0.5)
P is a coin with heads probability p and Q is a fair coin. The divergence is zero when the coin is fair and grows as the true coin becomes more biased.

The curve shows the key feature: the cost is zero only at the match, and it grows as the mismatch grows. The plot fixes QQ as a fair coin, so it cannot show that swapping PP and QQ changes the answer. The math section explains that asymmetry.

The math

Definition

Definition: Kullback–Leibler divergence

For two probability distributions PP and QQ on the same set of outcomes, with p(x)p(x) and q(x)q(x) their probabilities, the KL divergence of QQ from PP is

DKL(P ∥ Q)=∑x: p(x)>0p(x) log⁡2p(x)q(x)D_{\mathrm{KL}}(P \,\|\, Q) = \sum_{x:\, p(x) \gt 0} p(x)\,\log_2\frac{p(x)}{q(x)}

in bits, and the same expression with the natural logarithm ln⁡\ln gives it in nats. For continuous distributions the sum becomes an integral over the density:

DKL(P ∥ Q)=∫p(x) log⁡p(x)q(x) dx.D_{\mathrm{KL}}(P \,\|\, Q) = \int p(x)\,\log\frac{p(x)}{q(x)}\,dx.

Read the definition as an expectation. It is the average, under PP, of the log ratio log⁡(p(x)/q(x))\log\big(p(x)/q(x)\big). Where PP puts weight and QQ does not, the ratio blows up, so the divergence is infinite. Where PP puts no weight, the term is zero by convention, since 0log⁡0=00 \log 0 = 0.

Decomposition into entropy and cross-entropy

Split the logarithm: log⁡(p/q)=log⁡p−log⁡q\log(p/q) = \log p - \log q. Then

DKL(P ∥ Q)=−∑xp(x)log⁡2q(x)⏟H(P, Q), cross-entropy  −  (−∑xp(x)log⁡2p(x))⏟H(P), entropy.D_{\mathrm{KL}}(P \,\|\, Q) = \underbrace{-\sum_x p(x)\log_2 q(x)}_{H(P,\,Q),\ \text{cross-entropy}} \;-\; \underbrace{\left(-\sum_x p(x)\log_2 p(x)\right)}_{H(P),\ \text{entropy}}.

The first term is the average code length when you encode outcomes from PP using a code designed for QQ. The second is the best possible average code length for PP. Their difference is the waste. This is why KL and cross-entropy are so closely tied: when PP is fixed, minimising cross-entropy over QQ is the same as minimising KL.

Non-negativity (Gibbs' inequality)

The divergence is never negative, and it is zero only when P=QP = Q. A short proof uses Jensen's inequality for the concave logarithm, with weights p(x)p(x):

−DKL(P ∥ Q)=∑x: p(x)>0p(x) log⁡q(x)p(x)≤log⁡∑x: p(x)>0p(x) q(x)p(x)=log⁡∑x: p(x)>0q(x)  ≤  log⁡1=0.\begin{aligned} -D_{\mathrm{KL}}(P \,\|\, Q) &= \sum_{x:\, p(x) \gt 0} p(x)\,\log\frac{q(x)}{p(x)} \\ &\le \log \sum_{x:\, p(x) \gt 0} p(x)\,\frac{q(x)}{p(x)} \\ &= \log \sum_{x:\, p(x) \gt 0} q(x) \;\le\; \log 1 = 0. \end{aligned}

The last step uses the fact that QQ's probabilities sum to at most 1. Equality throughout forces q=pq = p wherever pp is positive.

Asymmetry

In general DKL(P ∥ Q)≠DKL(Q ∥ P)D_{\mathrm{KL}}(P \,\|\, Q) \ne D_{\mathrm{KL}}(Q \,\|\, P). 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,

DKL(N(μ1,σ12) ∥ N(μ2,σ22))=ln⁡σ2σ1+σ12+(μ1−μ2)22σ22−12.D_{\mathrm{KL}}\big(\mathcal{N}(\mu_1, \sigma_1^2) \,\|\, \mathcal{N}(\mu_2, \sigma_2^2)\big) = \ln\frac{\sigma_2}{\sigma_1} + \frac{\sigma_1^2 + (\mu_1 - \mu_2)^2}{2\sigma_2^2} - \frac{1}{2}.

Setting μ1=μ2\mu_1 = \mu_2 and σ1=σ2\sigma_1 = \sigma_2 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 q(z)=N(μ,diag⁡(σ2))q(\mathbf{z}) = \mathcal{N}(\boldsymbol{\mu}, \operatorname{diag}(\sigma^2)) against the standard normal N(0,I)\mathcal{N}(\mathbf{0}, \mathbf{I}) in dd dimensions, the same calculation coordinate by coordinate gives

DKL=12∑i=1d(μi2+σi2−1−ln⁡σi2).D_{\mathrm{KL}} = \frac{1}{2}\sum_{i=1}^{d}\left(\mu_i^2 + \sigma_i^2 - 1 - \ln \sigma_i^2\right).

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

Example
Two coins in bits

Let P=(1/2, 1/2)P = (1/2,\ 1/2) describe a fair coin, and Q=(1/4, 3/4)Q = (1/4,\ 3/4) describe a model that expects tails.

  1. Write the divergence from PP to QQ: D(P ∥ Q)=12log⁡21/21/4+12log⁡21/23/4D(P \,\|\, Q) = \tfrac{1}{2}\log_2\frac{1/2}{1/4} + \tfrac{1}{2}\log_2\frac{1/2}{3/4}.
  2. The first ratio is 2, so log⁡22=1\log_2 2 = 1. The second ratio is 2/32/3, and log⁡2(2/3)=ln⁡(2/3)/ln⁡2≈−0.5850\log_2(2/3) = \ln(2/3)/\ln 2 \approx -0.5850.
  3. Combine: D(P ∥ Q)=12(1)+12(−0.5850)=0.2075D(P \,\|\, Q) = \tfrac{1}{2}(1) + \tfrac{1}{2}(-0.5850) = 0.2075 bits.
  4. Now reverse the roles: D(Q ∥ P)=14log⁡21/41/2+34log⁡23/41/2D(Q \,\|\, P) = \tfrac{1}{4}\log_2\frac{1/4}{1/2} + \tfrac{3}{4}\log_2\frac{3/4}{1/2}.
  5. The first term is 14(−1)=−0.25\tfrac{1}{4}(-1) = -0.25. The second is 34log⁡21.5=34(0.5850)=0.4387\tfrac{3}{4}\log_2 1.5 = \tfrac{3}{4}(0.5850) = 0.4387. Sum: 0.18870.1887 bits.
  6. The two directions give 0.20750.2075 and 0.18870.1887 bits. They differ, which confirms the asymmetry. Both are positive, as Gibbs' inequality requires.
Example
A classifier's loss

A classifier sees an image of a cat. The true label is one-hot, so P=(0, 1, 0)P = (0,\ 1,\ 0) on the classes (dog, cat, bird). The model predicts Q=(0.1, 0.8, 0.1)Q = (0.1,\ 0.8,\ 0.1).

  1. The entropy of a one-hot label is zero, because there is no uncertainty: H(P)=0H(P) = 0.
  2. So the KL divergence equals the cross-entropy, which is the only nonzero term: −ln⁡q(cat)=−ln⁡0.8≈0.2231-\ln q(\text{cat}) = -\ln 0.8 \approx 0.2231 nats.
  3. If the model had been less sure, predicting 0.30.3 for cat, the loss would be −ln⁡0.3≈1.204-\ln 0.3 \approx 1.204 nats. Training pushes q(cat)q(\text{cat}) up, and every reduction in loss is a reduction in KL.
Example
Why a zero in Q is fatal

Let P=(1/2, 1/2)P = (1/2,\ 1/2) and Q=(1, 0)Q = (1,\ 0). Outcome 2 has probability 1/21/2 under PP but probability 0 under QQ.

  1. The term for outcome 2 is 12log⁡21/20\tfrac{1}{2}\log_2\frac{1/2}{0}, and the ratio is infinite.
  2. So D(P ∥ Q)=∞D(P \,\|\, Q) = \infty. The model claims an outcome is impossible when it is possible.
  3. The reverse, D(Q ∥ P)D(Q \,\|\, P), is finite, because the outcome where QQ puts all its weight has p>0p \gt 0. Asymmetry again.

Tradeoffs and failure modes

Which direction you minimise matters, and the two choices behave differently:

ObjectiveBehaviourTypical use
D(P ∥ Q)D(P \,\|\, Q), with the data distribution firstForces QQ to cover every place PP has mass. A model that misses a mode is punished heavily.Maximum likelihood, cross-entropy training
D(Q ∥ P)D(Q \,\|\, P), with the model firstLets QQ sit on one mode and ignore others, because placing mass where PP is zero is punished.Variational inference, many RL penalties

Other practical points:

  • Zero probabilities break it. If QQ is zero where PP is positive, the divergence is infinite. Smoothing or mixing QQ with a small uniform term avoids this.
  • Disjoint supports carry no gradient information. When PP and QQ 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 PP 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 ln⁡2\ln 2. 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 DKL(P ∥ Q)D_{\mathrm{KL}}(P \,\|\, Q) symmetric in PP and QQ? Give a reason, not just the answer.Show answer

No. The divergence weights the log ratio by p(x)p(x), so swapping PP and QQ changes the weights as well as the ratio. The two-coin example gives 0.20750.2075 bits in one direction and 0.18870.1887 bits in the other. The divergence is also not a metric because it fails the triangle inequality.

QuestionLet P=(0.5, 0.5)P = (0.5,\ 0.5) and Q=(0.9, 0.1)Q = (0.9,\ 0.1). Compute DKL(P ∥ Q)D_{\mathrm{KL}}(P \,\|\, Q) in bits, to three decimal places.Show answer

D=12log⁡20.50.9+12log⁡20.50.1D = \tfrac{1}{2}\log_2\frac{0.5}{0.9} + \tfrac{1}{2}\log_2\frac{0.5}{0.1}. The first term is 12log⁡2(0.5556)=12(−0.8480)=−0.4240\tfrac{1}{2}\log_2(0.5556) = \tfrac{1}{2}(-0.8480) = -0.4240. The second is 12log⁡25=12(2.3219)=1.1610\tfrac{1}{2}\log_2 5 = \tfrac{1}{2}(2.3219) = 1.1610. The total is 0.7370.737 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 q/pq/p, weighted by pp, the expected log of q/pq/p is at most the log of the sum of qq over the support of PP. 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 q/pq/p is constant on the support, which with probabilities summing to 1 means q=pq = p.

QuestionA VAE encoder outputs a Gaussian with mean μ=0.6\mu = 0.6 and standard deviation σ=0.5\sigma = 0.5 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 12(μ2+σ2−1−ln⁡σ2)\tfrac{1}{2}(\mu^2 + \sigma^2 - 1 - \ln \sigma^2). Here μ2=0.36\mu^2 = 0.36, σ2=0.25\sigma^2 = 0.25, and ln⁡σ2=ln⁡0.25≈−1.3863\ln \sigma^2 = \ln 0.25 \approx -1.3863. So the term is 12(0.36+0.25−1+1.3863)=12(0.9963)≈0.498\tfrac{1}{2}(0.36 + 0.25 - 1 + 1.3863) = \tfrac{1}{2}(0.9963) \approx 0.498 nats. A smaller σ\sigma would raise the penalty through the −ln⁡σ2-\ln \sigma^2 term, which is why the encoder cannot collapse to a point.

Sources