KL Divergence

KL Divergence measures how much one probability distribution differs from a reference distribution . Key result: it is always non-negative, equals zero only when , but is not symmetric and is not a true distance. Applies in: information theory, statistics, machine learning, thermodynamics. Origin: Solomon Kullback and Richard Leibler, 1951.

The Kullback–Leibler divergence (also called relative entropy) quantifies the "information lost" when distribution is used to approximate the true distribution . Concretely, it is the expected number of extra bits (or nats) you pay for encoding samples from using a code optimized for instead of the optimal code for . It matters because it is the natural measure of distributional discrepancy that arises from coding theory, maximum-likelihood estimation, and Bayesian inference all at once. The surprising fact: although it behaves like a "squared distance" for nearby distributions, in general, so swapping the two arguments can change the answer dramatically — even from finite to infinite.

The Core Insight

KL divergence is the expectation, under , of the log-ratio of the two densities. It answers: "On average over the true world , how surprised would I be if I believed ?" Because is positive where over-predicts and negative where it under-predicts, and because weights the average, the convexity of forces the total to be non-negative. It is an asymmetric gap, not a metric.

Formal Statement

KL Divergence — Discrete Case

Let and be probability distributions on a discrete set , with mass functions and . The Kullback–Leibler divergence of from is

1
⟳Take the expectation under of the pointwise log-ratio ; this is the definition, not a theorem.

Here is the true probability, the model probability, and the logarithm base sets the units: base 2 gives bits, base gives nats. Conventions: (justified by ), and if any where .

KL Divergence — Continuous Case

For distributions with densities and on (with respect to Lebesgue measure),

2
⟳Replace the sum in [1] by an integral; this requires to be absolutely continuous with respect to for finiteness.

The general measure-theoretic form uses the Radon–Nikodym derivative :

3
⟳When , the density ratio is exactly ; integrating against unifies the discrete and continuous cases.

Gibbs' Inequality / Non-negativity

For any two distributions on the same space,

4
⟳Apply Jensen's inequality to the convex function with the expectation taken under ; strict convexity gives the equality condition.

Why It Holds / Derivation

Non-negativity via Jensen's Inequality

We prove [4].

Step 1. Write the divergence as a negative expectation:
5
⟳Flip the ratio inside the log, which negates the whole expression by .
Step 2. The function is concave, so Jensen's inequality applies with :
6
⟳Jensen for a concave states .
Step 3. Evaluate the inner expectation (the 's cancel):
7
⟳Each summand survives; the total mass of is at most 1 (exactly 1 if is a genuine distribution over the same support).
Step 4. Therefore , i.e. . Step 5 (equality). Since is strictly concave, Jensen is an equality only if is constant -almost-surely. Combined with , this constant must be 1, forcing everywhere has mass.

Solomon Kullback & Richard Leibler | 1907–1994, 1914–2003

Kullback and Leibler, both cryptanalysts and statisticians, introduced the quantity in their 1951 paper "On Information and Sufficiency" while working on statistical decision theory and the discrimination between hypotheses. Kullback was a chief scientist at the U.S. National Security Agency and authored the influential 1959 monograph Information Theory and Statistics. Their original motivation was the discrimination information between two statistical hypotheses — how decisively data favors over — which links directly to the Neyman–Pearson Lemma and the theory of Sufficient Statistics.

Building Intuition

Imagine you must design a code to compress messages whose letters truly follow distribution . The optimal code (Shannon's source coding) assigns roughly bits to letter if you believe the distribution is . The true expected code length is then , the cross-entropy . The unavoidable minimum is the entropy . KL divergence is exactly the excess:

8
⟳Expand inside the sum and recognize the two entropy expressions.

So KL divergence = wasted bits from using the wrong codebook. It cannot be negative (you can never beat the optimal code) and is zero only when your codebook matches reality. The asymmetry now makes sense: paying with the wrong codebook in one direction is a different penalty than the other.

KL divergence as the gap between cross-entropy and entropy, and a mismatched density pair

KL Divergence = Cross-Entropy − Entropy x density P (true) Q (model) D_KL(P‖Q) = H(P,Q) − H(P) ≥ 0 ; wasted bits using Q's codebook on P-data

Worked Examples

Two Coins — Discrete KL in Bits

Given: True coin . Model coin . Compute in bits (base-2 log). Step 1. Apply [1]:
Step 2. Evaluate each term: , so first term . , so second term . Step 3. Sum: .
Asymmetry check: Reversing, . Different value — confirming asymmetry.

Two Gaussians — Continuous KL in Nats

Given: and . The closed-form result is
9
⟳Plug the two Gaussian densities into [2], expand the log into quadratic terms, and use and .
Numbers: Let (standard normal) and . Step 1. nats. Step 2. Numerator . Denominator . Ratio . Step 3. Subtract : total .

(Multiply by to convert to bits: bits.)

Common Misconceptions

KL divergence is NOT a distance metric. It fails two of the three metric axioms:
  1. Asymmetry: in general (see Example 1).
  2. Triangle inequality fails: there is no general .
It does satisfy non-negativity and the identity-of-indiscernibles. To get a symmetric, metric-like quantity, use the Jensen–Shannon Divergence (whose square root is a metric) or symmetrize as (still not a metric).

Infinite Divergence from Support Mismatch

Let be uniform on and uniform on . Then but , so the term . Hence

Yet is finite: assigns no mass to , so no division-by-zero occurs, and nats. This dramatic asymmetry shows why the direction of KL matters: harshly punishes for placing zero mass where has support, while the reverse is forgiving.

Connections

KL divergence is the hub of a web of information-theoretic quantities. Mutual Information is the KL divergence between a joint distribution and the product of its marginals: . Cross-Entropy equals , which is why minimizing cross-entropy loss is exactly minimizing KL to the data distribution. Minimizing over a parametric family is equivalent to Maximum Likelihood Estimation. The local quadratic approximation of KL recovers the Fisher Information Matrix as its Hessian — the foundation of information geometry. Finally, Shannon Entropy is the self-reference baseline that KL measures excess against.

KL and Fisher Information — Local Structure

For a smooth parametric family , the KL divergence between nearby parameters is, to second order,

10
⟳Taylor-expand to second order; the first-order term vanishes (score has zero mean) and the second-order term is the Fisher information matrix .

This shows KL is locally a (Riemannian) squared distance, even though it is globally asymmetric.

Real-World Applications

  1. Machine learning loss functions — Cross-entropy/KL loss trains nearly all classification networks; minimizing it is minimizing .
  2. Variational inference & VAEs — The Evidence Lower Bound (ELBO) contains a KL term regularizing the approximate posterior toward the prior; this is the core of variational autoencoders.
  3. Reinforcement learning — Trust Region Policy Optimization (TRPO) and PPO constrain policy updates by bounding between old and new policies to ensure stable improvement.
  4. Model selection — The Akaike Information Criterion (AIC) is derived as an estimator of expected KL divergence between the true and fitted models.
  5. Hypothesis testing & cryptanalysis — The original Kullback–Leibler use: the divergence equals the expected log-likelihood-ratio, governing the error exponents of Neyman–Pearson tests (Stein's lemma).
  6. Statistical physics — Relative entropy bounds free-energy differences; the non-negativity underpins the second law and the Jarzynski/Crooks fluctuation theorems.
  7. Anomaly & drift detection — Monitoring between a reference data distribution and live streaming data flags distribution shift in deployed ML systems.

Historical Development

  • 1948 — Claude Shannon introduces entropy and source coding in A Mathematical Theory of Communication, providing the bit-counting framework KL later exploits.
  • 1951 — Solomon Kullback and Richard Leibler publish "On Information and Sufficiency" (Annals of Mathematical Statistics), defining the divergence as discrimination information between hypotheses.
  • 1959 — Kullback's monograph Information Theory and Statistics systematizes relative entropy in statistical inference.
  • 1957 — E. T. Jaynes formulates the Maximum Entropy Principle, in which minimizing KL to a prior generalizes entropy maximization.
  • 1960s — Stein's lemma connects KL to the optimal error exponent of hypothesis tests, formalizing the cryptanalytic origin.
  • 1973 — Hirotugu Akaike derives AIC, showing model selection approximates minimizing expected KL divergence.
  • 1985–1990s — Shun'ichi Amari develops information geometry, treating KL as a dual-flat divergence with the Fisher metric, unifying it with differential geometry.
  • 2013–2014 — Kingma & Welling (VAEs) and Schulman et al. (TRPO) embed KL divergence at the heart of modern deep learning objectives.

Subtleties & Limits

Unboundedness and estimation. KL divergence can be infinite under support mismatch, which destabilizes training of generative models (motivating Wasserstein distances in GANs, which remain finite). Estimating KL from samples in high dimensions is notoriously hard: nonparametric estimators suffer the curse of dimensionality and have high variance, and there is no unbiased estimator of from finite samples in general. The choice of forward (, "mean-seeking," covers all modes of ) versus reverse (, "mode-seeking," collapses onto one mode) divergence remains an active design question in variational inference, with no universally optimal answer. Generalizations such as -divergences, Rényi divergences, and integral probability metrics each repair different shortcomings, but no single divergence is simultaneously symmetric, metric, finite, and easily estimable.

See Also

Mutual Information · Cross-Entropy · Shannon Entropy · Jensen–Shannon Divergence · Fisher Information Matrix · Maximum Likelihood Estimation · Variational Inference · Jensen's Inequality · Wasserstein Distance

Before this

Where this leads