concept / kl-divergence
Next task →
University/Info Theory/Divergences/KL Divergence and Cross Entropy
Information Theory · Divergences · Information geometry

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.

39 sectionsadvanced190 minhand-authored · structural 76/100
Take assessment →
Mastery requires: derivation reproduced, from-scratch implementation committed, failure case explained, and assessment score ≥ 80%. Current state: not_started.

1. Concept overview

The Kullback–Leibler divergence (relative entropy) between distributions PP and QQ on the same space is

DKL(P∥Q)=Ex∼P[log⁡p(x)q(x)]=∑xp(x)log⁡p(x)q(x)(or ∫p(x)log⁡p(x)q(x)dx).D_{\mathrm{KL}}(P\|Q)=\mathbb{E}_{x\sim P}\Bigl[\log\frac{p(x)}{q(x)}\Bigr]=\sum_x p(x)\log\frac{p(x)}{q(x)}\quad(\text{or }\int p(x)\log\frac{p(x)}{q(x)}dx).

It is nonnegative, equals zero iff P=QP=Q, but is not symmetric and does not satisfy the triangle inequality — it is a divergence, not a metric.

Cross entropy of PP relative to QQ is

H(P,Q)=Ex∼P[−log⁡q(x)]=H(P)+DKL(P∥Q),H(P,Q)=\mathbb{E}_{x\sim P}[-\log q(x)]=H(P)+D_{\mathrm{KL}}(P\|Q),

so minimizing cross entropy with respect to QQ 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 QQ to reality PP: "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: H(P,Q)−H(P)H(P,Q)-H(P) is the expected extra bits needed when using an optimal code for QQ on data actually drawn from PP.
  • Statistics: the log-likelihood ratio log⁡[p(x)/q(x)]\log[p(x)/q(x)] is the optimal test statistic for distinguishing PP from QQ (Neyman–Pearson lemma); its expectation under PP is KL.
  • Optimization: maximizing EP[log⁡q]\mathbb{E}_P[\log q] is maximum likelihood; minimizing DKL(P∥Q)D_{\mathrm{KL}}(P\|Q) 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 H(P)=−∑plog⁡pH(P)=-\sum p\log p and founded information theory. Kullback and Leibler (1951) defined and studied DKL(P∥Q)D_{\mathrm{KL}}(P\|Q) explicitly in Information Theory and Statistics, deriving its nonnegativity and additivity properties. Jeffreys (1946) independently used the symmetrized DKL(P∥Q)+DKL(Q∥P)D_{\mathrm{KL}}(P\|Q)+D_{\mathrm{KL}}(Q\|P) for hypothesis testing.

Rényi (1961) generalized to an α\alpha-family; Csiszár (1967) and Ali–Silvey introduced ff-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 P,QP,Q 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 PP is the intractable posterior of a Bayesian model, find the member QQ of a tractable family minimizing DKL(Q∥P)D_{\mathrm{KL}}(Q\|P) — 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 pp carries surprise −log⁡p-\log p: rare events are more informative, and independent surprises add because −log⁡(p1p2)=−log⁡p1−log⁡p2-\log(p_1p_2)=-\log p_1-\log p_2.

Fact 2 — entropy. The expected surprise under PP is Shannon entropy H(P)=EP[−log⁡p(x)]H(P)=\mathbb{E}_P[-\log p(x)]; 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 PP using probabilities qq from a wrong model, the expected code length is the cross entropy H(P,Q)=EP[−log⁡q(x)]H(P,Q)=\mathbb{E}_P[-\log q(x)]. Subtracting the optimal length H(P)H(P) gives the excess:

H(P,Q)−H(P)=EP[log⁡p(x)q(x)]=DKL(P∥Q)≥0,H(P,Q)-H(P)=\mathbb{E}_P\Bigl[\log\frac{p(x)}{q(x)}\Bigr]=D_{\mathrm{KL}}(P\|Q)\ge0,

where nonnegativity follows from Jensen's inequality applied to the convex function −log⁡-\log.

Fact 4 — optimality of likelihood. H(P,Q)H(P,Q) is minimized over a parametric family {Qθ}\{Q_\theta\} exactly when EP[log⁡qθ(x)]\mathbb{E}_P[\log q_\theta(x)] is maximized — for empirical PP 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 −log⁡-\log and xlog⁡xx\log x; (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 log⁡\log and the chain rule of probability. See the linked concepts.

7. Complete mathematical formulation

Definition. DKL(P∥Q)=EP[log⁡(p/q)]D_{\mathrm{KL}}(P\|Q)=\mathbb{E}_P[\log(p/q)], with conventions 0log⁡(0/q)=00\log(0/q)=0 and plog⁡(p/0)=+∞p\log(p/0)=+\infty.

Key identities.

H(P,Q)=H(P)+DKL(P∥Q),H(P,Q)=H(P)+D_{\mathrm{KL}}(P\|Q), DKL(P∥Q)≥0,=0  ⟺  P=Q a.e.,D_{\mathrm{KL}}(P\|Q)\ge0,\quad =0\iff P=Q\ \text{a.e.}, I(X;Y)=DKL(PXY∥PXPY)=EY[DKL(PX∣Y∥PX)],I(X;Y)=D_{\mathrm{KL}}(P_{XY}\|P_XP_Y)=\mathbb{E}_Y[D_{\mathrm{KL}}(P_{X\mid Y}\|P_X)], DKL(PXYZ∥QXYZ)=DKL(PXY∥QXY)+E(x,y)∼P[DKL(PZ∣xy∥QZ∣xy)].D_{\mathrm{KL}}(P_{XYZ}\|Q_{XYZ})=D_{\mathrm{KL}}(P_{XY}\|Q_{XY})+\mathbb{E}_{(x,y)\sim P}[D_{\mathrm{KL}}(P_{Z\mid xy}\|Q_{Z\mid xy})].

Gaussians. For P=N(μ1,σ12)P=\mathcal N(\mu_1,\sigma_1^2), Q=N(μ2,σ22)Q=\mathcal N(\mu_2,\sigma_2^2):

DKL(P∥Q)=log⁡σ2σ1+σ12+(μ1−μ2)22σ22−12.D_{\mathrm{KL}}(P\|Q)=\log\frac{\sigma_2}{\sigma_1}+\frac{\sigma_1^2+(\mu_1-\mu_2)^2}{2\sigma_2^2}-\tfrac12 .

Bregman form. DKL(P∥Q)=F(P)−F(Q)−⟨∇F(Q),P−Q⟩D_{\mathrm{KL}}(P\|Q)=F(P)-F(Q)-\langle\nabla F(Q),P-Q\rangle with F(P)=∑ipilog⁡piF(P)=\sum_i p_i\log p_i (negative entropy).

8. Notation dictionary

| Symbol | Meaning | Type | |---|---|---| | P,QP,Q | probability distributions | measures | | p(x),q(x)p(x),q(x) | their densities / mass functions | functions | | DKL(P∥Q)D_{\mathrm{KL}}(P\|Q) | KL divergence from QQ to PP | scalar in [0,∞][0,\infty] | | H(P)H(P) | Shannon entropy −EPlog⁡p-\mathbb E_P\log p | scalar | | H(P,Q)H(P,Q) | cross entropy −EPlog⁡q-\mathbb E_P\log q | scalar | | log⁡\log | natural logarithm (nats); log⁡2\log_2 gives bits | function | | I(X;Y)I(X;Y) | mutual information | scalar | | N(μ,σ2)\mathcal N(\mu,\sigma^2) | Gaussian with mean μ\mu, variance σ2\sigma^2 | distribution | | PX∣YP_{X\mid Y} | conditional distribution of XX given YY | kernel | | F(P)=∑pilog⁡piF(P)=\sum p_i\log p_i | negative entropy (convex generator) | functional | | QθQ_\theta | parametric model family | set of distributions | | BB | batch size in loss computation | integer | | KK | number of classes / categories | integer |

9. Step-by-step derivation

Step 1 — write the excess code length. For a sample x∼Px\sim P, the optimal code length is −log⁡p(x)-\log p(x); using qq costs −log⁡q(x)-\log q(x). The difference is log⁡(p(x)/q(x))\log(p(x)/q(x)).

Step 2 — take the expectation under the true distribution.

DKL(P∥Q)=∫p(x)log⁡p(x)q(x) dx=EP[log⁡p(x)]−EP[log⁡q(x)]=−H(P)+H(P,Q).D_{\mathrm{KL}}(P\|Q)=\int p(x)\log\frac{p(x)}{q(x)}\,dx=\mathbb E_P[\log p(x)]-\mathbb E_P[\log q(x)]=-H(P)+H(P,Q).

Step 3 — prove nonnegativity. Since t↦−log⁡tt\mapsto-\log t is convex, Jensen gives

DKL(P∥Q)=EP[−log⁡q(x)p(x)]≥−log⁡EPq(x)p(x)=−log⁡∫q(x) dx=0,D_{\mathrm{KL}}(P\|Q)=\mathbb E_P\Bigl[-\log\frac{q(x)}{p(x)}\Bigr]\ge-\log\mathbb E_P\frac{q(x)}{p(x)}=-\log\int q(x)\,dx=0,

with equality iff q/pq/p is constant, i.e. P=QP=Q.

Step 4 — Gaussian case. With EP[log⁡q(x)]=−12log⁡(2πσ22)−EP[(x−μ2)2]2σ22\mathbb E_{P}[\log q(x)]=-\tfrac12\log(2\pi\sigma_2^2)-\frac{\mathbb E_P[(x-\mu_2)^2]}{2\sigma_2^2} and H(P)=12log⁡(2πeσ12)H(P)=\tfrac12\log(2\pi e\sigma_1^2), use EP[(x−μ2)2]=σ12+(μ1−μ2)2\mathbb E_P[(x-\mu_2)^2]=\sigma_1^2+(\mu_1-\mu_2)^2 and combine:

DKL(P∥Q)=log⁡σ2σ1+σ12+(μ1−μ2)22σ22−12.D_{\mathrm{KL}}(P\|Q)=\log\frac{\sigma_2}{\sigma_1}+\frac{\sigma_1^2+(\mu_1-\mu_2)^2}{2\sigma_2^2}-\tfrac12 .

Step 5 — empirical / maximum-likelihood link. For data x1,…˙,xnx_1,\.\dots,x_n, let PnP_n be the empirical distribution. Then DKL(Pn∥Qθ)=−H(Pn)−1n∑ilog⁡qθ(xi)D_{\mathrm{KL}}(P_n\|Q_\theta)= -H(P_n)-\frac1n\sum_i\log q_\theta(x_i); minimizing it over θ\theta is exactly maximizing the log-likelihood.

10. Proofs and proof intuition

Theorem (Gibbs inequality). DKL(P∥Q)≥0D_{\mathrm{KL}}(P\|Q)\ge0 with equality iff P=QP=Q almost everywhere. Proof. Jensen as above. Alternatively use log⁡u≤u−1\log u\le u-1 with u=q(x)/p(x)u=q(x)/p(x): ∫plog⁡(q/p)≤∫p(q/p−1)=∫q−∫p=0\int p\log(q/p)\le\int p(q/p-1)=\int q-\int p=0; negate. Equality requires q/p=1q/p=1 a.e. □\square

Theorem (chain rule). DKL(PXY∥QXY)=DKL(PX∥QX)+Ex∼PX[DKL(PY∣x∥QY∣x)]D_{\mathrm{KL}}(P_{XY}\|Q_{XY})=D_{\mathrm{KL}}(P_X\|Q_X)+\mathbb E_{x\sim P_X}[D_{\mathrm{KL}}(P_{Y\mid x}\|Q_{Y\mid x})]. Proof. Expand log⁡p(x)p(y∣x)q(x)q(y∣x)=log⁡p(x)q(x)+log⁡p(y∣x)q(y∣x)\log\frac{p(x)p(y\mid x)}{q(x)q(y\mid x)}=\log\frac{p(x)}{q(x)}+\log\frac{p(y\mid x)}{q(y\mid x)} and take EPXY\mathbb E_{P_{XY}}; the second term iterated yields the conditional expectations. □\square

Theorem (data processing). For a channel X→Y→ZX\to Y\to Z (Markov), DKL(PY∥QY)≤DKL(PX∥QX)D_{\mathrm{KL}}(P_Y\|Q_Y)\le D_{\mathrm{KL}}(P_X\|Q_X). Proof (sketch). By the chain rule, D(PXYZ∥QXYZ)=D(PX∥QX)+D(PYZ∣X∥QYZ∣X)=D(PY∥QY)+D(PZ∣Y∥QZ∣Y)+D(PX∣Y∥QX∣Y)D(P_{XYZ}\|Q_{XYZ})=D(P_X\|Q_X)+D(P_{YZ\mid X}\|Q_{YZ\mid X})=D(P_Y\|Q_Y)+D(P_{Z\mid Y}\|Q_{Z\mid Y})+D(P_{X\mid Y}\|Q_{X\mid Y}). Markovity makes PZ∣XY=PZ∣YP_{Z\mid XY}=P_{Z\mid Y} and QZ∣XY=QZ∣YQ_{Z\mid XY}=Q_{Z\mid Y}, so comparing the two expansions gives D(PX∥QX)−D(PY∥QY)=D(PX∣Y∥QX∣Y)−D(PX∣YZ∥QX∣YZ)≥0D(P_X\|Q_X)-D(P_Y\|Q_Y)=D(P_{X\mid Y}\|Q_{X\mid Y})-D(P_{X\mid YZ}\|Q_{X\mid YZ})\ge0 by the chain rule and nonnegativity. □\square

Proposition (Pinsker inequality, stated). TV(P,Q)≤DKL(P∥Q)/2\mathrm{TV}(P,Q)\le\sqrt{D_{\mathrm{KL}}(P\|Q)/2} — KL controls total variation, justifying its use as a discrepancy measure.

Proof intuition. KL is an expected log-likelihood ratio. Because log⁡\log 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 δ\delta of pp, DKL(P∥P+δ)≈12∑iδi2/piD_{\mathrm{KL}}(P\|P+\delta)\approx\tfrac12\sum_i\delta_i^2/p_i, i.e. half the Fisher information metric. Globally it is asymmetric and fails the triangle inequality — it defines two different affine connections (Amari's α\alpha-geometry), with DKL(P∥Q)D_{\mathrm{KL}}(P\|Q) and DKL(Q∥P)D_{\mathrm{KL}}(Q\|P) governing dual projections.

This asymmetry has a practical face: forward KL DKL(P∥Q)D_{\mathrm{KL}}(P\|Q) averages over PP, so QQ must cover all modes of PP (mean-seeking — infinite cost where p>0,q=0p>0,q=0); reverse KL DKL(Q∥P)D_{\mathrm{KL}}(Q\|P) averages over QQ, so QQ is penalized only where it places mass that PP 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 μ,σ\mu,\sigma). Plot pp, qq, and the integrand plog⁡(p/q)p\log(p/q) shaded red where positive and blue where negative; the integral is always nonnegative. A second view shows KL contours in the (μQ,σQ)(\mu_Q,\sigma_Q) plane for a fixed PP: forward and reverse KL have visibly different contour shapes and minima when PP is bimodal. A third panel shows the cross-entropy decomposition as a stacked bar: H(P)H(P) (irreducible) plus DKLD_{\mathrm{KL}} (avoidable).

13. Numerical worked example

Bernoulli. P=(0.2,0.8)P=(0.2,0.8), Q=(0.5,0.5)Q=(0.5,0.5):

DKL(P∥Q)=0.2ln⁡(0.4)+0.8ln⁡(1.6)=0.2(−0.9163)+0.8(0.4700)=−0.1833+0.3760=0.1927 nats.D_{\mathrm{KL}}(P\|Q)=0.2\ln(0.4)+0.8\ln(1.6)=0.2(-0.9163)+0.8(0.4700)=-0.1833+0.3760=0.1927\ \text{nats}.

H(P)=−[0.2ln⁡0.2+0.8ln⁡0.8]=0.5004H(P)=-[0.2\ln0.2+0.8\ln0.8]=0.5004 nats, and H(P,Q)=0.6931=ln⁡2H(P,Q)=0.6931=\ln2 nats — check: 0.5004+0.1927=0.69310.5004+0.1927=0.6931.

Gaussians. P=N(0,1)P=\mathcal N(0,1), Q=N(1,4)Q=\mathcal N(1,4) (so σ2=2\sigma_2=2):

DKL(P∥Q)=ln⁡2+1+(0−1)22⋅4−12=0.6931+0.25−0.5=0.4431.D_{\mathrm{KL}}(P\|Q)=\ln2+\frac{1+(0-1)^2}{2\cdot4}-\tfrac12=0.6931+0.25-0.5=0.4431 .

Reversing: DKL(Q∥P)=ln⁡12+4+12−12=−0.6931+2.5−0.5=1.3069D_{\mathrm{KL}}(Q\|P)=\ln\tfrac12+\frac{4+1}{2}-\tfrac12=-0.6931+2.5-0.5=1.3069 nats — over 2.9× larger, demonstrating asymmetry.

Classification. For a one-hot label y=2y=2 and softmax probabilities q=(0.1,0.7,0.2)q=(0.1,0.7,0.2), the cross-entropy loss is −ln⁡0.7=0.3567-\ln 0.7=0.3567 nats; since H(P)=0H(P)=0 for one-hot targets, this equals DKL(P∥Q)D_{\mathrm{KL}}(P\|Q) exactly.

14. Real-world analogy

Imagine a meteorologist who uses the same weather-codebook every day. If the true distribution of weather is PP but their codebook assumes QQ, 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 q=0q=0 where p>0p>0. 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 ∑p(log⁡p−log⁡q)\sum p(\log p-\log q) — 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 0log⁡(0/q)=00\log(0/q)=0; np.maximum(q, eps) avoids log⁡0\log 0 when q=0q=0 and p>0p>0 (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 σ\sigma 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 BB and KK classes, logits occupy BKBK floats, log-softmax another BKBK, and the labels BB integers: ~8BK8BK bytes in fp32. At B=512,K=50,000B=512,K=50{,}000 (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 KK, memory is O(K)O(K); for a joint distribution over dd binary variables it is O(2d)O(2^d), which is why variational approximations are necessary. Storing a Monte Carlo KL estimate of NN log-ratio samples costs O(N)O(N); a VAE storing μ\mu and log⁡σ\log\sigma for each of LL latent dimensions in a batch costs 2BL2BL floats.

20. Time complexity

Discrete KL: O(K)O(K). Cross entropy over a batch: O(BK)O(BK). Gaussian KL: O(d)O(d) for dd dimensions. Monte Carlo estimation of KL from NN samples: O(N)O(N) but with variance that can be enormous when p/qp/q is heavy-tailed — practical accuracy is O(1/N)O(1/\sqrt{N}) only when the log-ratio has finite variance, and can be much worse. Computing mutual information by brute force over a joint table is O(∣X∣∣Y∣)O(|X||Y|); estimating it with the k-NN estimator is roughly O(Nlog⁡N)O(N\log N).

21. Space complexity

Discrete KL O(K)O(K); batched cross entropy O(BK)O(BK) (reducible with fused kernels); Gaussian KL O(d)O(d) (or O(1)O(1) with streaming sufficient statistics); joint-distribution KL O(∏i∣Xi∣)O(\prod_i |X_i|), 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 NN samples from PP and averaging log⁡(p/q)\log(p/q); with N=105N=10^5 the error should be a few thousandths. Repeat for the Gaussian pair (0,1)(0,1) vs (1,4)(1,4): the analytic values 0.4431 and 1.3069 must match Monte Carlo within O(1/N)O(1/\sqrt N). Then fit a single Gaussian by minimizing forward versus reverse KL to a two-component mixture P=0.5N(−2,1)+0.5N(2,1)P=0.5\mathcal N(-2,1)+0.5\mathcal N(2,1): 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 512×50000512\times50000 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, 10510^5 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 q(x)=0q(x)=0 where p(x)>0p(x)>0, KL is infinite — a single impossible event dominates.
  • Tail sensitivity: plog⁡(p/q)p\log(p/q) weights regions where pp is small but qq 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 −K/(2n)-K/(2n) for KK categories (Miller–Madow correction).
  • Units: nats vs bits differ by ln⁡2\ln2; 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

  1. Zero probability: a vocabulary item absent from the model but present in data gives q=0q=0, hence infinite KL. Smooth with Laplace/add-ϵ\epsilon smoothing.
  2. 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.
  3. Applying log to probabilities instead of logits with F.cross_entropy: double-logging produces nonsense; pass raw logits.
  4. Reverse KL mode collapse: fitting a unimodal QQ to a multimodal PP by DKL(Q∥P)D_{\mathrm{KL}}(Q\|P) locks onto one mode; use forward KL, mixture families, or α\alpha-divergences.
  5. High-variance MC estimate: rare samples with enormous log⁡(p/q)\log(p/q) dominate; use importance weighting, control variates, or analytic formulas when available.
  6. Comparing KL values across datasets with different numbers of categories without normalization — values are not directly comparable.
  7. Estimating KL on the same data used to fit QQ — 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 H(P)+DKLH(P)+D_{\mathrm{KL}}.
  • "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 ln⁡2≈0.693\ln2\approx0.693.
  • "KL needs both distributions to have the same support." Infinite KL is meaningful — it means QQ assigns impossible events to possible outcomes.

27. Alternative approaches

  • Jensen–Shannon divergence: 12D(P∥M)+12D(Q∥M)\tfrac12 D(P\|M)+\tfrac12 D(Q\|M) with M=(P+Q)/2M=(P+Q)/2; symmetric, bounded in [0,ln⁡2][0,\ln2], but can be blind to disjoint supports.
  • Total variation 12∑∣p−q∣\tfrac12\sum|p-q|: bounded, metric, but ignores the geometry of small probabilities.
  • Hellinger distance, χ2\chi^2 divergence, Rényi α\alpha-divergences: different ff-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 DKL(qϕ(z∣x)∥p(z∣x))D_{\mathrm{KL}}(q_\phi(z\mid x)\|p(z\mid x)) 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 — α\alpha-divergences.
  • Csiszár I. (1967), Information-type measures of difference of probability distributions, Studia Sci. Math. Hungar. — ff-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_div and cross_entropy — read the argument-order notes carefully.

32. Practical exercises

  1. Compute kl_discrete([0.2,0.8],[0.5,0.5]) by hand and in code; verify 0.1927 nats and the decomposition H=0.5004H=0.5004, H(P,Q)=0.6931H(P,Q)=0.6931.
  2. Derive and verify the Gaussian KL formula for (0,1)(0,1) vs (1,4)(1,4) in both directions; explain the asymmetry numerically.
  3. Prove the chain rule of KL and use it to derive I(X;Y)=EY[DKL(PX∣Y∥PX)]I(X;Y)=\mathbb E_Y[D_{\mathrm{KL}}(P_{X\mid Y}\|P_X)].
  4. Implement Monte Carlo KL estimation for the Gaussian case and plot relative error versus N∈{103,104,105,106}N\in\{10^3,10^4,10^5,10^6\}; check the 1/N1/\sqrt N trend.
  5. 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.
  6. Write a unit test that would catch swapping the arguments of F.kl_div.

33. Debugging challenges

  • KL returns a negative number. You swapped PP and QQ in the expectation, or used unnormalized probabilities; check normalization and the log-ratio sign.
  • KL returns inf. Some qi=0q_i=0 while pi>0p_i>0; 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_sigma parameterization is wrong, or the prior variance is not 1; clip log_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

  1. Prove the data processing inequality rigorously using the chain rule; explain what it implies for information loss in Markov chains.
  2. Show that KL is a Bregman divergence generated by F(P)=∑ipilog⁡piF(P)=\sum_i p_i\log p_i and derive the corresponding dual divergence.
  3. Derive the Miller–Madow bias correction D^MM=D^−(K−1)/(2n)\widehat{D}_{\text{MM}}=\widehat D-(K-1)/(2n) and verify it by simulation for K=10K=10.
  4. Prove Pinsker's inequality TV≤DKL/2\mathrm{TV}\le\sqrt{D_{\mathrm{KL}}/2} using DKL≥2 TV2D_{\mathrm{KL}}\ge2\,\mathrm{TV}^2 (a sharper bound due to Vajda).
  5. Derive the ELBO identity log⁡p(x)=ELBO+DKL(q∥p(⋅∣x))\log p(x)=\mathrm{ELBO}+D_{\mathrm{KL}}(q\|p(\cdot\mid x)) and explain why minimizing reverse KL is equivalent to maximizing the ELBO.
  6. Implement the α\alpha-divergence interpolating between forward and reverse KL; show the limits α→0,1\alpha\to0,1.

35. Interview questions

  • Define KL divergence and prove it is nonnegative. Why is it not a metric?
  • Explain the decomposition H(P,Q)=H(P)+DKL(P∥Q)H(P,Q)=H(P)+D_{\mathrm{KL}}(P\|Q) and its consequence for classification losses.
  • Compute DKL(N(0,1)∥N(1,4))D_{\mathrm{KL}}(\mathcal N(0,1)\|\mathcal N(1,4)) 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.``

Research papers linked to this concept

shannon1948 · citation recorded, library entry pending
kullback1951 · citation recorded, library entry pending
jeffreys1946 · citation recorded, library entry pending
csiszar1967 · citation recorded, library entry pending
Differential-Geometrical Methods in Statistics 1985
kingma2013 · citation recorded, library entry pending