KL Divergence and Cross Entropy
KL divergence measures the expected extra cost of encoding samples from P using a code designed for Q; it is nonnegative, zero only when P=Q, asymmetric, and decomposes cross entropy into entropy plus divergence.
1. Concept overview
The Kullback–Leibler divergence (relative entropy) between distributions and on the same space is
It is nonnegative, equals zero iff , but is not symmetric and does not satisfy the triangle inequality — it is a divergence, not a metric.
Cross entropy of relative to is
so minimizing cross entropy with respect to is equivalent to minimizing KL divergence. This single identity is why softmax cross-entropy is the default classification loss and why variational inference minimizes a KL.
2. Why this concept exists
We constantly need to compare a model to reality : "how wrong is my fitted distribution?", "how much information does one variable carry about another?", "how much does this posterior differ from my approximating family?"
Plain probability differences or Euclidean distances on densities ignore the multiplicative nature of probability and behave badly in the tails. KL arises naturally from three independent viewpoints:
- Coding theory: is the expected extra bits needed when using an optimal code for on data actually drawn from .
- Statistics: the log-likelihood ratio is the optimal test statistic for distinguishing from (Neyman–Pearson lemma); its expectation under is KL.
- Optimization: maximizing is maximum likelihood; minimizing is therefore the statistical goal itself, not a proxy.
Alternatives exist (total variation, Hellinger, Wasserstein), but KL is uniquely tied to likelihood-based inference and information theory, and it factorizes cleanly through conditional distributions.
3. Historical background
The logarithmic measure of "surprise" traces to Gibbs (1902), who introduced the entropy-like quantity later called relative entropy in statistical mechanics. Shannon (1948) axiomatized entropy and founded information theory. Kullback and Leibler (1951) defined and studied explicitly in Information Theory and Statistics, deriving its nonnegativity and additivity properties. Jeffreys (1946) independently used the symmetrized for hypothesis testing.
Rényi (1961) generalized to an -family; Csiszár (1967) and Ali–Silvey introduced -divergences containing KL, TV, and Hellinger as special cases. Bregman (1967) gave the convex-analysis interpretation of KL as a Bregman divergence of Shannon entropy, and Amari (1985) placed it at the center of information geometry, where it defines the dual geometries of a statistical manifold. In modern ML, KL became the objective of variational autoencoders (Kingma & Welling, 2013) and the regularizer in reinforcement learning (trust-region methods, Schulman et al., 2015).
4. Fundamental problem
Given two probability distributions on the same space, quantify their discrepancy in a way that (a) is zero exactly when they coincide, (b) reflects the statistical distinguishability of samples, (c) is compatible with likelihood-based learning and decomposes over independent components.
A related computational problem: when the true is the intractable posterior of a Bayesian model, find the member of a tractable family minimizing — the variational inference problem. The choice of KL direction is consequential: it determines whether the fit is mass-covering (mean-seeking) or mode-seeking.
5. First-principles explanation
Fact 1 — surprise. Observing an event of probability carries surprise : rare events are more informative, and independent surprises add because .
Fact 2 — entropy. The expected surprise under is Shannon entropy ; it is the minimum expected code length in bits (base-2 logs) or nats (natural logs).
Fact 3 — mismatched code. If we encode samples from using probabilities from a wrong model, the expected code length is the cross entropy . Subtracting the optimal length gives the excess:
where nonnegativity follows from Jensen's inequality applied to the convex function .
Fact 4 — optimality of likelihood. is minimized over a parametric family exactly when is maximized — for empirical this is maximum likelihood. So KL is the objective that statistical fitting optimizes.
6. Prerequisite concepts
Required: (1) probability mass/density functions, marginals and conditionals; (2) expectation and the law of the unconscious statistician; (3) Jensen's inequality and convexity of and ; (4) Shannon entropy and basic coding intuition; (5) the Gaussian, Bernoulli and categorical families; (6) maximum likelihood and log-likelihood; (7) for proofs, concavity of and the chain rule of probability. See the linked concepts.
7. Complete mathematical formulation
Definition. , with conventions and .
Key identities.
Gaussians. For , :
Bregman form. with (negative entropy).
8. Notation dictionary
| Symbol | Meaning | Type | |---|---|---| | | probability distributions | measures | | | their densities / mass functions | functions | | | KL divergence from to | scalar in | | | Shannon entropy | scalar | | | cross entropy | scalar | | | natural logarithm (nats); gives bits | function | | | mutual information | scalar | | | Gaussian with mean , variance | distribution | | | conditional distribution of given | kernel | | | negative entropy (convex generator) | functional | | | parametric model family | set of distributions | | | batch size in loss computation | integer | | | number of classes / categories | integer |
9. Step-by-step derivation
Step 1 — write the excess code length. For a sample , the optimal code length is ; using costs . The difference is .
Step 2 — take the expectation under the true distribution.
Step 3 — prove nonnegativity. Since is convex, Jensen gives
with equality iff is constant, i.e. .
Step 4 — Gaussian case. With and , use and combine:
Step 5 — empirical / maximum-likelihood link. For data , let be the empirical distribution. Then ; minimizing it over is exactly maximizing the log-likelihood.
10. Proofs and proof intuition
Theorem (Gibbs inequality). with equality iff almost everywhere. Proof. Jensen as above. Alternatively use with : ; negate. Equality requires a.e.
Theorem (chain rule). . Proof. Expand and take ; the second term iterated yields the conditional expectations.
Theorem (data processing). For a channel (Markov), . Proof (sketch). By the chain rule, . Markovity makes and , so comparing the two expansions gives by the chain rule and nonnegativity.
Proposition (Pinsker inequality, stated). — KL controls total variation, justifying its use as a discrepancy measure.
Proof intuition. KL is an expected log-likelihood ratio. Because is concave, averaging cannot create negative values; equality forces the ratio to be constant. Every other property follows from expanding the joint ratio into marginal and conditional pieces.
11. Geometric interpretation
On the manifold of probability distributions, KL plays the role of a squared distance locally: for a small perturbation of , , i.e. half the Fisher information metric. Globally it is asymmetric and fails the triangle inequality — it defines two different affine connections (Amari's -geometry), with and governing dual projections.
This asymmetry has a practical face: forward KL averages over , so must cover all modes of (mean-seeking — infinite cost where ); reverse KL averages over , so is penalized only where it places mass that lacks, preferring to collapse onto a single mode (mode-seeking).
12. Visual explanation
Use the interactive KL Explorer: two adjustable distributions on a line (e.g. Gaussians with sliders for ). Plot , , and the integrand shaded red where positive and blue where negative; the integral is always nonnegative. A second view shows KL contours in the plane for a fixed : forward and reverse KL have visibly different contour shapes and minima when is bimodal. A third panel shows the cross-entropy decomposition as a stacked bar: (irreducible) plus (avoidable).
13. Numerical worked example
Bernoulli. , :
nats, and nats — check: .
Gaussians. , (so ):
Reversing: nats — over 2.9× larger, demonstrating asymmetry.
Classification. For a one-hot label and softmax probabilities , the cross-entropy loss is nats; since for one-hot targets, this equals exactly.
14. Real-world analogy
Imagine a meteorologist who uses the same weather-codebook every day. If the true distribution of weather is but their codebook assumes , they waste bits whenever reality surprises them. KL is the average number of extra bits per day. A codebook that assigns zero probability to "flood" is catastrophically bad if a flood ever occurs — the analogue of infinite KL when where . Conversely, assigning tiny probability to rare events costs little on average, which is why tail behavior matters so much.
15. Algorithm pseudocode
algorithm KLDiscrete(p, q, eps=1e-12):
p <- p / sum(p); q <- q / sum(q) # normalize
mask <- p > 0
return sum_{mask} p[mask] * (log p[mask] - log(max(q[mask], eps)))
algorithm CrossEntropy(logits, labels):
# logits shape (B, K); labels are class indices
log_q <- logits - logsumexp(logits, axis=classes)
return -mean_i log_q[i, labels[i]]
algorithm GaussianKL(mu1, s1, mu2, s2):
return log(s2/s1) + (s1^2 + (mu1-mu2)^2)/(2 s2^2) - 0.5
algorithm VariationalObjective(phi):
# minimize D_KL(q_phi(z) || p(z|x))
sample z ~ q_phi(.|x)
ELBO <- E_z[ log p(x,z) - log q_phi(z|x) ]
return -ELBO # = KL + log p(x)
16. Implementation from scratch
import numpy as np
def kl_discrete(p, q, eps=1e-12):
"""D_KL(P||Q) in nats, with zero-probability conventions."""
p = np.asarray(p, float); q = np.asarray(q, float)
p /= p.sum(); q /= q.sum()
mask = p > 0
return float(np.sum(p[mask] * (np.log(p[mask]) - np.log(np.maximum(q[mask], eps)))))
def cross_entropy_from_logits(logits, labels):
"""Stable softmax cross entropy; labels are integer class indices."""
m = logits.max(axis=-1, keepdims=True)
logq = logits - m - np.log(np.exp(logits - m).sum(axis=-1, keepdims=True))
return -logq[np.arange(len(labels)), labels].mean()
def kl_gaussian(mu1, var1, mu2, var2):
s1, s2 = np.sqrt(var1), np.sqrt(var2)
return np.log(s2/s1) + (var1 + (mu1-mu2)**2)/(2*var2) - 0.5
def kl_mc(logp_fn, logq_fn, n=200000, seed=0):
"""Monte Carlo estimate by sampling from P (requires a sampler)."""
rng = np.random.default_rng(seed)
z = np.array([logp_fn(rng.normal()) for _ in range(n)]) # placeholder sampler
return float(np.mean(z))
print(kl_discrete([0.2, 0.8], [0.5, 0.5])) # ~0.1927
print(kl_gaussian(0, 1, 1, 4)) # ~0.4431
print(kl_gaussian(1, 4, 0, 1)) # ~1.3069
17. Professional library implementation
from scipy.stats import entropy
import torch
import torch.nn.functional as F
p = torch.tensor([0.2, 0.8]); q = torch.tensor([0.5, 0.5])
print(entropy(p.numpy(), q.numpy(), base=np.e)) # 0.1927 nats
print(F.kl_div(q.log(), p, reduction="sum")) # same, arguments are log(q), p
logits = torch.randn(8, 3, requires_grad=True)
labels = torch.tensor([0, 1, 2, 1, 0, 2, 1, 0])
loss = F.cross_entropy(logits, labels) # stable, fused log-softmax
loss.backward()
# Gaussian KL in PyTorch (used in VAEs)
mu1, ls1 = torch.zeros(2), torch.zeros(2) # ls = log sigma
mu2, ls2 = torch.ones(2), torch.ones(2)
kl = (ls2 - ls1 + (ls1.exp()**2 + (mu1-mu2)**2)/(2*ls2.exp()**2) - 0.5).sum()
Note the argument order of F.kl_div: it expects log_q first and p second, and computes — a classic source of sign and direction bugs. In production use F.cross_entropy instead of manually applying log_softmax, since it is fused and numerically stable.
18. Code walkthrough
Discrete KL. Normalizing both vectors prevents silent errors from unnormalized scores. mask = p > 0 implements the convention ; np.maximum(q, eps) avoids when and (returning a large finite penalty rather than infinity).
Cross entropy. Subtracting the row max before exponentiation prevents overflow; the log-sum-exp correction gives exact log-softmax. Indexing with [np.arange(len(labels)), labels] selects the true class probability per row.
Gaussian KL. The formula needs variances, not standard deviations — a frequent error. The implementation takes variances and extracts only for the log-ratio.
PyTorch. F.cross_entropy expects raw logits and integer class indices, not probabilities. F.kl_div expects log(q) and p in that order. For VAEs, the Gaussian KL is summed over latent dimensions; using log_sigma (rather than sigma) avoids negative standard deviations and improves numerical behavior.
19. Tensor and memory analysis
For classification with batch and classes, logits occupy floats, log-softmax another , and the labels integers: ~ bytes in fp32. At (large vocabulary) that is ~200 MB per buffer, so frameworks fuse the operation to avoid materializing both. For KL between two discrete distributions of size , memory is ; for a joint distribution over binary variables it is , which is why variational approximations are necessary. Storing a Monte Carlo KL estimate of log-ratio samples costs ; a VAE storing and for each of latent dimensions in a batch costs floats.
20. Time complexity
Discrete KL: . Cross entropy over a batch: . Gaussian KL: for dimensions. Monte Carlo estimation of KL from samples: but with variance that can be enormous when is heavy-tailed — practical accuracy is only when the log-ratio has finite variance, and can be much worse. Computing mutual information by brute force over a joint table is ; estimating it with the k-NN estimator is roughly .
21. Space complexity
Discrete KL ; batched cross entropy (reducible with fused kernels); Gaussian KL (or with streaming sufficient statistics); joint-distribution KL , exponential in the number of variables — the core reason exact inference is intractable and variational methods minimize KL instead.
22. Experimental demonstration
Check the analytic values: compute kl_discrete([0.2,0.8],[0.5,0.5]) twice with different random orderings — it must return 0.1927 exactly. Estimate the same KL by drawing samples from and averaging ; with the error should be a few thousandths. Repeat for the Gaussian pair vs : the analytic values 0.4431 and 1.3069 must match Monte Carlo within . Then fit a single Gaussian by minimizing forward versus reverse KL to a two-component mixture : forward KL finds a wide variance covering both modes; reverse KL collapses onto one mode — plot both fits to see the asymmetry.
Benchmark the cross-entropy implementation on a logits tensor: F.cross_entropy should be markedly faster and use less memory than a NumPy log-softmax followed by indexing.
23. Benchmark results
Monte Carlo KL estimates converge slowly in the tails: for the Gaussian example, samples typically give 1–2% relative error; for heavy-tailed ratios the error is dominated by rare events and can be an order of magnitude worse. Report both the estimate and an empirical standard error. On classification, cross entropy and accuracy move together but not one-to-one: a model can improve cross entropy while accuracy is flat (better calibration on confident examples); always report both plus a reliability diagram. Reverse-KL variational fits typically have lower reconstruction error but poorer mode coverage than forward-KL fits — never report a single "distance" without naming the direction.
24. Limitations
- Not a metric: asymmetric, can be infinite, violates the triangle inequality.
- Absolute continuity required: if where , KL is infinite — a single impossible event dominates.
- Tail sensitivity: weights regions where is small but is tiny; rare events can make estimates unstable.
- Direction matters: forward and reverse KL answer different questions; picking the wrong one silently changes the solution.
- Sample estimates are biased: plug-in estimates of KL from finite data have a negative bias of roughly for categories (Miller–Madow correction).
- Units: nats vs bits differ by ; mixing them in reported numbers causes systematic errors.
- Undefined for continuous P vs discrete Q without care (densities depend on the reference measure).
25. Failure scenarios
- Zero probability: a vocabulary item absent from the model but present in data gives , hence infinite KL. Smooth with Laplace/add- smoothing.
- Wrong argument order in PyTorch:
F.kl_div(p.log(), q)computes the opposite direction and a different value; always write a unit test with the Bernoulli example. - Applying log to probabilities instead of logits with
F.cross_entropy: double-logging produces nonsense; pass raw logits. - Reverse KL mode collapse: fitting a unimodal to a multimodal by locks onto one mode; use forward KL, mixture families, or -divergences.
- High-variance MC estimate: rare samples with enormous dominate; use importance weighting, control variates, or analytic formulas when available.
- Comparing KL values across datasets with different numbers of categories without normalization — values are not directly comparable.
- Estimating KL on the same data used to fit — optimistically biased; use held-out data.
26. Common misconceptions
- "KL is a distance between distributions." It is a divergence; asymmetry is essential and useful.
- "KL(P||Q) = KL(Q||P)." False in general (see the Gaussian example: 0.4431 vs 1.3069).
- "Cross entropy is just a loss with no interpretation." It is expected code length under the wrong model, and equals .
- "Minimizing KL always gives a good fit." Under model misspecification, the chosen direction determines which aspect (modes vs mass coverage) is preserved.
- "KL can be negative." Never, by Gibbs' inequality; a negative value signals a numerical bug.
- "Bits and nats are interchangeable." They differ by a factor of .
- "KL needs both distributions to have the same support." Infinite KL is meaningful — it means assigns impossible events to possible outcomes.
27. Alternative approaches
- Jensen–Shannon divergence: with ; symmetric, bounded in , but can be blind to disjoint supports.
- Total variation : bounded, metric, but ignores the geometry of small probabilities.
- Hellinger distance, divergence, Rényi -divergences: different -divergence trade-offs.
- Wasserstein / earth-mover distance: metric sensitive to underlying geometry, stable for disjoint supports, used in WGANs; costs an optimal-transport solve.
- Maximum mean discrepancy (MMD): kernel-based, sample-efficient for high dimensions.
- Fisher information / natural gradient: local Riemannian geometry instead of a global divergence.
29. Research applications
- Variational autoencoders: minimize via the ELBO.
- Reinforcement learning: TRPO/PPO constrain policy change with a KL trust region; soft-actor-critic uses a KL-regularized objective.
- Language modeling and distillation: cross-entropy training; KL between teacher and student distributions.
- Information bottleneck: compress inputs while preserving information about a target, with KL as the compression term.
- Model comparison: AIC approximates expected KL between the fitted model and truth.
- Privacy and fairness: KL-based leakage bounds and demographic disparity measures.
- Neuroscience: KL and free-energy principles as models of perception and action.
30. Important research papers
- Gibbs J. W. (1902), Elementary Principles in Statistical Mechanics — early relative entropy.
- Shannon C. E. (1948), A Mathematical Theory of Communication, Bell System Technical Journal 27:379–423, 623–656 — entropy and coding.
- Jeffreys H. (1946), An invariant process for statistical inference, Proceedings of the Cambridge Philosophical Society — symmetrized divergence.
- Kullback S., Leibler R. A. (1951), On Information and Sufficiency, Annals of Mathematical Statistics 22(1):79–86 — KL divergence.
- Rényi A. (1961), On measures of entropy and information, Proc. 4th Berkeley Symposium — -divergences.
- Csiszár I. (1967), Information-type measures of difference of probability distributions, Studia Sci. Math. Hungar. — -divergences.
- Amari S.-I. (1985), Differential-Geometrical Methods in Statistics — information geometry.
- Kingma D. P., Welling M. (2013), Auto-Encoding Variational Bayes, ICLR — KL in VAEs.
31. Further reading
- Cover & Thomas, Elements of Information Theory (2nd ed., 2006), chapters 2, 4, 8, 11.
- Kullback, Information Theory and Statistics (1959) — the monograph.
- Amari & Nagaoka, Methods of Information Geometry (2000).
- Van Erven & Harremoës, Rényi divergence and Kullback–Leibler divergence (2014), IEEE Trans. Inf. Theory.
- Goodfellow et al., Deep Learning (2016), chapter 3.13.
- PyTorch docs:
torch.nn.functional.kl_divandcross_entropy— read the argument-order notes carefully.
32. Practical exercises
- Compute
kl_discrete([0.2,0.8],[0.5,0.5])by hand and in code; verify 0.1927 nats and the decomposition , . - Derive and verify the Gaussian KL formula for vs in both directions; explain the asymmetry numerically.
- Prove the chain rule of KL and use it to derive .
- Implement Monte Carlo KL estimation for the Gaussian case and plot relative error versus ; check the trend.
- Fit a single Gaussian to a bimodal mixture by minimizing forward versus reverse KL; plot both and describe the mass-covering vs mode-seeking behavior.
- Write a unit test that would catch swapping the arguments of
F.kl_div.
33. Debugging challenges
- KL returns a negative number. You swapped and in the expectation, or used unnormalized probabilities; check normalization and the log-ratio sign.
- KL returns
inf. Some while ; apply smoothing or check for a zero softmax probability. - Cross entropy is negative. You passed probabilities to
F.cross_entropy(it expects logits) or took the log twice. - VAE KL explodes early in training. The
log_sigmaparameterization is wrong, or the prior variance is not 1; cliplog_sigma. - Monte Carlo estimate is unstable across seeds. The log-ratio has heavy tails; use analytic KL or more samples with a variance report.
- PyTorch KL differs from SciPy by a constant. Bits vs nats, or reduction='mean' vs 'sum' mismatch.
34. Advanced exercises
- Prove the data processing inequality rigorously using the chain rule; explain what it implies for information loss in Markov chains.
- Show that KL is a Bregman divergence generated by and derive the corresponding dual divergence.
- Derive the Miller–Madow bias correction and verify it by simulation for .
- Prove Pinsker's inequality using (a sharper bound due to Vajda).
- Derive the ELBO identity and explain why minimizing reverse KL is equivalent to maximizing the ELBO.
- Implement the -divergence interpolating between forward and reverse KL; show the limits .
35. Interview questions
- Define KL divergence and prove it is nonnegative. Why is it not a metric?
- Explain the decomposition and its consequence for classification losses.
- Compute and the reverse; why do they differ?
- In variational inference, why is reverse KL commonly minimized even though forward KL is "mass covering"?
- State and prove the data processing inequality. What does it say about sufficient statistics?
- When is KL infinite, and why is that sometimes the correct answer?
- How do bits and nats relate, and how do you convert between them?
36. Research questions
- How can KL be estimated reliably from finite samples when the log-density ratio is heavy-tailed?
- Which divergence best captures perceptual similarity for images, and can this be justified axiomatically?
- How does the choice of KL direction affect generalization in amortized inference?
- Can one design unbiased low-variance estimators of mutual information using KL structure?
- What are the right divergence notions for comparing distributions on manifolds or graphs?
37. Mastery assessment
To pass: (1) derive KL from cross entropy and prove Gibbs' inequality without notes; (2) compute both Bernoulli and Gaussian examples numerically; (3) implement discrete KL, stable cross entropy and Gaussian KL, with tests; (4) explain asymmetry, infinite KL and the data processing inequality; (5) answer the interview questions. Complete the linked assessment; reading alone is not mastery.`
38. Implementation submission
Push a repository with kl.py (discrete KL with zero handling, stable cross entropy, Gaussian KL, Monte Carlo estimator), experiments.ipynb (analytic vs MC checks, forward/reverse KL mode fits, timing of fused vs unfused cross entropy), a README.md with derivations and recorded numbers, and tests asserting 0.1927 and 0.4431/1.3069 plus Gibbs nonnegativity on random inputs. Submit the repository URL and exact reproduction command.`
39. Completion criteria
All of: every section read; Gibbs inequality and chain rule proofs reproduced on paper; scratch implementation passing tests; numerical experiments with recorded values and plots; one failure scenario reproduced and explained; a one-page answer to a research question citing at least one paper. Only then mark the concept mastered.``