Type at least 2 letters. Enter opens the first result, Esc closes.

    Information Theory · Lesson 3 · KL divergence, cross-entropy and compression

    Jensen's inequality and the KL divergence

    Intermediate 60 min 3 interactive figures 4 videos Colab notebook

    Before this lesson: lesson 01 (surprisal and entropy) and lesson 02 (conditional entropy). Convex functions from optimization lesson 02; the expectation of a function of a random variable from the probability track. Time: about 60 minutes, plus the notebook.


    Why this matters #

    KL divergence is inside many training objectives. The cross-entropy loss of every classifier and language model is the entropy of the data plus a KL term (lesson 04). RLHF (reinforcement learning from human feedback) adds a penalty β KL(πθ ∥ πref)\beta\,\mathrm{KL}(\pi_\theta\,\|\,\pi_{\text{ref}}) so that the tuned language model stays close to the reference model. Knowledge distillation trains a small student to match a large teacher by minimizing a KL. The VAE loss has a KL term that pulls the encoder towards the prior (lesson 09). TRPO limits each policy update to a small KL ball (a trust region). Monitoring systems detect data drift by comparing the feature distributions of two time windows with KL or a symmetric version of it.

    Jensen's inequality is the tool behind the proofs. It shows that KL is never negative, that the uniform distribution has the largest entropy, and that the ELBO of variational inference is a lower bound on the log-likelihood.

    In this track log⁡\log is the natural logarithm and gives nats; log⁡2\log_2 gives bits, and 1 nat=1/ln⁡2≈1.4431\text{ nat} = 1/\ln 2 \approx 1.443 bits. NumPy, SciPy and PyTorch use nats.

    1. Predict first #

    2. The picture #

    Jensen with two points: the chord #

    A function ff is convex if every chord lies on or above its graph. Take two points aa and bb and a weight λ∈[0,1]\lambda \in [0, 1]. Let XX be a random variable that equals aa with probability λ\lambda and bb with probability 1−λ1 - \lambda. Then

    • E[X]=λa+(1−λ)b\mathbb{E}[X] = \lambda a + (1 - \lambda) b is a point between aa and bb;
    • E[f(X)]=λf(a)+(1−λ)f(b)\mathbb{E}[f(X)] = \lambda f(a) + (1 - \lambda) f(b) is the height of the chord above that point;
    • f(E[X])f(\mathbb{E}[X]) is the height of the graph above the same point.

    The chord is above the graph, so f(E[X])≤E[f(X)]f(\mathbb{E}[X]) \le \mathbb{E}[f(X)]. For two points, this inequality is exactly the definition of convexity.

    Many points: the centre of mass #

    Now let XX take values x1,…,xnx_1, \dots, x_n with probabilities p1,…,pnp_1, \dots, p_n. Put a mass pip_i on the graph at the point (xi,f(xi))(x_i, f(x_i)). The centre of mass of these masses is (∑ipixi, ∑ipif(xi))=(E[X], E[f(X)])\big(\sum_i p_i x_i,\ \sum_i p_i f(x_i)\big) = \big(\mathbb{E}[X],\ \mathbb{E}[f(X)]\big). It lies inside the polygon spanned by the points. For a convex ff this polygon lies on or above the graph, so the centre of mass does too: E[f(X)]≥f(E[X])\mathbb{E}[f(X)] \ge f(\mathbb{E}[X]). This is Jensen's inequality.

    Interactive figure: loading…

    Drag the blue points along the curve and move the weight sliders. The yellow dot is the centre of mass (E[X],E[f(X)])(\mathbb{E}[X], \mathbb{E}[f(X)]); the small dot on the curve is (E[X],f(E[X]))(\mathbb{E}[X], f(\mathbb{E}[X])). The aqua segment is the Jensen gap. For a convex ff the yellow dot is always above the curve; switch to log⁡x\log x or x\sqrt{x} and it is always below. Put all the weight on one point: the gap closes.

    Concave functions turn the inequality around #

    A function is concave if −f-f is convex: every chord lies on or below the graph. The logarithm is concave, so

    E[log⁡X]≤log⁡E[X](X>0).\mathbb{E}[\log X] \le \log \mathbb{E}[X] \qquad (X > 0).

    Example. XX is 1 or 4, each with probability 12\frac12. Then E[X]=2.5\mathbb{E}[X] = 2.5 and log⁡E[X]=log⁡2.5=0.916\log \mathbb{E}[X] = \log 2.5 = 0.916, but E[log⁡X]=12(log⁡1+log⁡4)=log⁡2=0.693\mathbb{E}[\log X] = \frac12(\log 1 + \log 4) = \log 2 = 0.693. Take the exponential of both sides: the geometric mean 1⋅4=2\sqrt{1 \cdot 4} = 2 is at most the arithmetic mean 2.52.5. This is the AM–GM inequality, and it is Jensen for log⁡\log.

    Quick check

    Apply Jensen's inequality to the convex function f(x)=x2f(x) = x^2. Which known fact do you get?

    KL divergence: the extra surprise of a wrong model #

    Lesson 01 measured the surprisal of an outcome xx as −log⁡2p(x)-\log_2 p(x) bits. Now the data come from pp, but you predict with a model qq. Each outcome surprises you by −log⁡2q(x)-\log_2 q(x).

    A fair coin, p=(0.5,0.5)p = (0.5, 0.5), and a model that believes q=(0.8,0.2)q = (0.8, 0.2):

    outcome p(x)p(x) q(x)q(x) surprise under qq: −log⁡2q(x)-\log_2 q(x) surprise under pp: −log⁡2p(x)-\log_2 p(x)
    heads 0.5 0.8 0.322 bits 1 bit
    tails 0.5 0.2 2.322 bits 1 bit

    The coin is fair, so each row happens half of the time.

    1. Your average surprise with the model is 12(0.322+2.322)=1.322\frac12(0.322 + 2.322) = 1.322 bits. This average is the cross-entropy H(p,q)H(p, q) (lesson 04 studies it).
    2. The best possible average is the entropy H(p)=1H(p) = 1 bit. You reach it only with the right model q=pq = p.
    3. The difference, 1.322−1=0.3221.322 - 1 = 0.322 bits, is the Kullback–Leibler (KL) divergence KL(p ∥ q)\mathrm{KL}(p\,\|\,q): the price of the wrong belief, per coin flip.

    Look at the rows separately. On heads, the model is less surprised than the truth would be (0.322<10.322 < 1). On tails it is more surprised (2.322>12.322 > 1). The losses on tails are larger than the gains on heads, so the average is positive. This is the content of Gibbs' inequality below.

    Interactive figure: loading…

    Drag the tops of the bars to change the true distribution pp (blue) and the model qq (orange). The lower chart shows each term p(x)log⁡p(x)q(x)p(x)\log\frac{p(x)}{q(x)} (aqua): some terms are negative, but their sum is never below 0. Switch the lower chart to the terms of KL(q ∥ p)\mathrm{KL}(q\,\|\,p) and compare the two totals. Then drag one orange bar to 0 where the blue bar is not 0.

    Quick check

    For one outcome, p(x)=0.3p(x) = 0.3 and q(x)=0.4q(x) = 0.4. What is the sign of the term p(x)log⁡p(x)q(x)p(x)\log\frac{p(x)}{q(x)}?

    3. Definitions and main results #

    Convex and concave functions #

    A function ff on an interval II is convex if

    f(λa+(1−λ)b)≤λf(a)+(1−λ)f(b)f(\lambda a + (1 - \lambda) b) \le \lambda f(a) + (1 - \lambda) f(b)

    for all a,b∈Ia, b \in I and all λ∈[0,1]\lambda \in [0, 1].

    It is strictly convex if the inequality is strict whenever a≠ba \ne b and 0<λ<10 < \lambda < 1. It is (strictly) concave if −f-f is (strictly) convex. A twice differentiable ff is convex when f′′(x)≥0f''(x) \ge 0 on II, and strictly convex when f′′(x)>0f''(x) > 0 (optimization lesson 02).

    • Strictly convex: x2x^2, exe^x, 1/x1/x for x>0x > 0, tlog⁡tt \log t for t≥0t \ge 0.
    • Strictly concave: log⁡x\log x and x\sqrt{x} for x>0x > 0.
    • Convex but not strictly: ∣x∣|x|, and every linear function ax+bax + b (it is also concave).

    Jensen's inequality #

    Theorem 1 (Jensen). Let ff be convex on an interval II, and let XX take values in II with E[X]\mathbb{E}[X] and E[f(X)]\mathbb{E}[f(X)] finite. Then

    f(E[X])≤E[f(X)].f(\mathbb{E}[X]) \le \mathbb{E}[f(X)].

    If ff is strictly convex, equality holds if and only if XX is constant (with probability 1). For a concave ff the inequality is reversed: f(E[X])≥E[f(X)]f(\mathbb{E}[X]) \ge \mathbb{E}[f(X)].

    Why this is true. A convex function lies above each of its tangent lines. A line is easy to average: the average of a line is the line at the average. So the average of ff is above the average of the line, which is the value of ff at the mean.

    Proof.

    1. Let μ=E[X]\mu = \mathbb{E}[X]. If μ\mu is an endpoint of II, say the left one, then X−μ≥0X - \mu \ge 0 and E[X−μ]=0\mathbb{E}[X - \mu] = 0. A non-negative variable with mean 0 is 0 with probability 1, so X=μX = \mu and both sides equal f(μ)f(\mu). From now on, μ\mu is an interior point of II.
    2. A convex ff has a supporting line at every interior point: a slope cc with f(x)≥f(μ)+c (x−μ)f(x) \ge f(\mu) + c\,(x - \mu) for all x∈Ix \in I. If ff is differentiable, c=f′(μ)c = f'(\mu) and the line is the tangent line.
    3. Put x=Xx = X and take the expectation of both sides. Expectation is linear and keeps inequalities, so E[f(X)]≥f(μ)+c (E[X]−μ)=f(μ)\mathbb{E}[f(X)] \ge f(\mu) + c\,(\mathbb{E}[X] - \mu) = f(\mu).
    4. Equality case. The difference D=f(X)−f(μ)−c (X−μ)D = f(X) - f(\mu) - c\,(X - \mu) is ≥0\ge 0. Equality in step 3 means E[D]=0\mathbb{E}[D] = 0, so D=0D = 0 with probability 1: XX only takes values where the graph touches the supporting line.
    5. A strictly convex ff touches a line below it at one point only. (If it touched at μ\mu and at x′≠μx' \ne \mu, then at the midpoint of μ\mu and x′x' the graph would lie strictly below the chord, which is a piece of the line. That contradicts f≥f \ge line.) So X=μX = \mu with probability 1.
    6. For a concave ff, apply steps 1–5 to the convex function −f-f. ■\blacksquare

    For a convex ff that is not strictly convex, equality can hold with a random XX: when ff is linear on the values of XX. For example f(x)=∣x∣f(x) = |x| and X∈{1,3}X \in \{1, 3\}: ∣E[X]∣=2=E[∣X∣]|\mathbb{E}[X]| = 2 = \mathbb{E}[|X|].

    How large is the gap for the logarithm? #

    The Jensen gap for log⁡\log is log⁡E[X]−E[log⁡X]≥0\log \mathbb{E}[X] - \mathbb{E}[\log X] \ge 0. Let μ=E[X]\mu = \mathbb{E}[X] and σ2=Var⁡(X)\sigma^2 = \operatorname{Var}(X). When XX stays close to μ\mu,

    log⁡E[X]−E[log⁡X]≈σ22μ2.\log \mathbb{E}[X] - \mathbb{E}[\log X] \approx \frac{\sigma^2}{2\mu^2}.

    Derivation.

    1. Second-order Taylor expansion of log⁡\log at μ\mu: log⁡x≈log⁡μ+x−μμ−(x−μ)22μ2\log x \approx \log \mu + \frac{x - \mu}{\mu} - \frac{(x - \mu)^2}{2\mu^2}.
    2. Put x=Xx = X and take expectations. E[X−μ]=0\mathbb{E}[X - \mu] = 0 and E[(X−μ)2]=σ2\mathbb{E}[(X - \mu)^2] = \sigma^2, so E[log⁡X]≈log⁡μ−σ22μ2\mathbb{E}[\log X] \approx \log \mu - \frac{\sigma^2}{2\mu^2}.
    3. Subtract from log⁡E[X]=log⁡μ\log \mathbb{E}[X] = \log \mu.

    For X∈{0.9,1.1}X \in \{0.9, 1.1\} with equal probabilities, the exact gap is 0.005030.00503 and the approximation gives 0.0050.005. For X∈{1,4}X \in \{1, 4\} (a large spread) the exact gap is 0.2230.223 and the approximation gives 0.180.18: the Taylor expansion is only good for a small spread. The lesson to remember: the gap grows with the relative spread σ/μ\sigma/\mu. Lesson 09 uses this to explain why the IWAE bound, which averages several samples inside the log, is tighter than the ELBO.

    Preview: why the ELBO is a lower bound

    In a latent-variable model p(x,z)p(x, z), the evidence p(x)=∑zp(x,z)p(x) = \sum_z p(x, z) is often too expensive to compute. Choose any distribution q(z)q(z) that is positive wherever p(x,z)>0p(x, z) > 0, and define the weight w(z)=p(x,z)/q(z)w(z) = p(x, z)/q(z). Then p(x)=∑zq(z) w(z)=Ez∼q[w(z)]p(x) = \sum_z q(z)\,w(z) = \mathbb{E}_{z \sim q}[w(z)]. Jensen for the concave log⁡\log gives

    log⁡p(x)=log⁡Eq[w] ≥ Eq[log⁡w]=Eq[log⁡p(x,z)q(z)].\log p(x) = \log \mathbb{E}_q[w] \ \ge\ \mathbb{E}_q[\log w] = \mathbb{E}_q\Big[\log \frac{p(x, z)}{q(z)}\Big].

    The right side is the evidence lower bound (ELBO). Lesson 09 shows that the gap is exactly a KL divergence, KL(q(z) ∥ p(z∣x))\mathrm{KL}(q(z)\,\|\,p(z \mid x)).

    The KL divergence #

    Let pp and qq be distributions on the same finite set. The Kullback–Leibler divergence (also called relative entropy) of qq from pp is

    KL(p ∥ q)=∑xp(x)log⁡p(x)q(x)=Ex∼p[log⁡p(x)q(x)]=Ep[−log⁡q(X)]−Ep[−log⁡p(X)].\begin{aligned} \mathrm{KL}(\htmlClass{c1}{p}\,\|\,\htmlClass{c2}{q}) &= \sum_x p(x) \log \frac{p(x)}{q(x)} \\ &= \mathbb{E}_{x \sim p}\Big[\log \frac{p(x)}{q(x)}\Big] \\ &= \mathbb{E}_{p}\big[-\log q(X)\big] - \mathbb{E}_{p}\big[-\log p(X)\big]. \end{aligned}

    Read it as: the average, under the truth pp, of the extra surprise −log⁡q(x)−(−log⁡p(x))-\log q(x) - (-\log p(x)). The first argument is the distribution we average under. In machine learning it is usually the data distribution, and the second argument is the model.

    Conventions for zeros (they are the limits of tlog⁡tt \log t and tlog⁡(t/s)t \log(t/s)):

    • 0log⁡0q=00 \log \frac{0}{q} = 0 for every q≥0q \ge 0: outcomes that never happen cost nothing.
    • plog⁡p0=+∞p \log \frac{p}{0} = +\infty for p>0p > 0: an outcome that happens but has model probability 0 makes the KL infinite.

    So KL(p ∥ q)<∞\mathrm{KL}(p\,\|\,q) < \infty exactly when q(x)>0q(x) > 0 for every xx with p(x)>0p(x) > 0 (the support of pp lies inside the support of qq). For densities, replace the sum by an integral; the results below stay the same (lesson 06).

    Gibbs' inequality: KL is never negative #

    Theorem 2 (Gibbs' inequality). KL(p ∥ q)≥0\mathrm{KL}(p\,\|\,q) \ge 0, with equality if and only if p=qp = q.

    Proof.

    1. Let S={x:p(x)>0}S = \{x : p(x) > 0\} be the support of pp. If q(x)=0q(x) = 0 for some x∈Sx \in S, the KL is +∞+\infty and there is nothing to prove. Otherwise, the terms outside SS are 0, and −KL(p ∥ q)=∑x∈Sp(x)log⁡q(x)p(x)-\mathrm{KL}(p\,\|\,q) = \sum_{x \in S} p(x) \log \frac{q(x)}{p(x)}.
    2. This is E[log⁡q(X)p(X)]\mathbb{E}\big[\log \frac{q(X)}{p(X)}\big] with X∼pX \sim p. Jensen for the concave log⁡\log moves the log outside: −KL(p ∥ q)≤log⁡∑x∈Sp(x)q(x)p(x)-\mathrm{KL}(p\,\|\,q) \le \log \sum_{x \in S} p(x) \frac{q(x)}{p(x)}, and the right side simplifies to log⁡∑x∈Sq(x)\log \sum_{x \in S} q(x).
    3. The probabilities q(x)q(x) over the part SS add up to at most 1, so the right side is ≤log⁡1=0\le \log 1 = 0. Hence KL(p ∥ q)≥0\mathrm{KL}(p\,\|\,q) \ge 0.
    4. Equality needs both steps to be tight. Step 2 is tight only if q(x)/p(x)=cq(x)/p(x) = c is the same number for all x∈Sx \in S (log⁡\log is strictly concave). Step 3 is tight only if ∑x∈Sq(x)=1\sum_{x \in S} q(x) = 1. Then 1=∑Sq=c∑Sp=c1 = \sum_{S} q = c \sum_{S} p = c, so q=pq = p on SS, and q=0q = 0 outside SS. That is, q=pq = p. ■\blacksquare
    Second proof: the log-sum inequality (and the convexity of KL)

    Theorem 3 (log-sum inequality). For ai≥0a_i \ge 0 and bi>0b_i > 0, with A=∑iaiA = \sum_i a_i and B=∑ibiB = \sum_i b_i,

    ∑iailog⁡aibi ≥ Alog⁡AB,\sum_i a_i \log \frac{a_i}{b_i} \ \ge\ A \log \frac{A}{B},

    with equality if and only if ai/bia_i / b_i is the same for all ii.

    Proof.

    1. Let g(t)=tlog⁡tg(t) = t \log t for t≥0t \ge 0. Then g′′(t)=1/t>0g''(t) = 1/t > 0, so gg is strictly convex.
    2. Define weights wi=bi/Bw_i = b_i / B (positive, sum 1) and ratios ti=ai/bit_i = a_i / b_i.
    3. Rewrite the left side: ∑iailog⁡aibi=∑ibi tilog⁡ti=B∑iwi g(ti)\sum_i a_i \log \frac{a_i}{b_i} = \sum_i b_i\, t_i \log t_i = B \sum_i w_i\, g(t_i).
    4. Jensen with the weights ww: ∑iwi g(ti)≥g(∑iwiti)=g(A/B)\sum_i w_i\, g(t_i) \ge g\big(\sum_i w_i t_i\big) = g(A/B), because ∑iwiti=∑iai/B=A/B\sum_i w_i t_i = \sum_i a_i / B = A / B.
    5. Multiply by BB: the left side is ≥B⋅ABlog⁡AB=Alog⁡AB\ge B \cdot \frac{A}{B} \log \frac{A}{B} = A \log \frac{A}{B}.
    6. Equality holds when Jensen is tight for the strictly convex gg: all tit_i are equal. ■\blacksquare

    Gibbs from log-sum. Put a=pa = p and b=qb = q (restrict to the xx with q(x)>0q(x) > 0). Then A=B=1A = B = 1 and the right side is 1⋅log⁡1=01 \cdot \log 1 = 0.

    KL is jointly convex. For two pairs (p1,q1)(p_1, q_1), (p2,q2)(p_2, q_2) and λ∈[0,1]\lambda \in [0, 1],

    KL(λp1+(1−λ)p2 ∥ λq1+(1−λ)q2)≤λ KL(p1 ∥ q1)+(1−λ) KL(p2 ∥ q2).\begin{aligned} &\mathrm{KL}\big(\lambda p_1 + (1 - \lambda) p_2 \,\big\|\, \lambda q_1 + (1 - \lambda) q_2\big) \\ &\qquad \le \lambda\, \mathrm{KL}(p_1\,\|\,q_1) + (1 - \lambda)\, \mathrm{KL}(p_2\,\|\,q_2). \end{aligned}

    Proof: fix one outcome xx and apply the log-sum inequality to the two terms a1=λp1(x)a_1 = \lambda p_1(x), a2=(1−λ)p2(x)a_2 = (1 - \lambda) p_2(x), b1=λq1(x)b_1 = \lambda q_1(x), b2=(1−λ)q2(x)b_2 = (1 - \lambda) q_2(x). The λ\lambda inside the logs cancels. Then add over xx. Convexity is why minimizing a KL over a convex set of distributions has no bad local minima.

    Quick check

    The true distribution is p=(0.99,0.01)p = (0.99, 0.01). A model predicts q=(1,0)q = (1, 0). What is KL(p ∥ q)\mathrm{KL}(p\,\|\,q)?

    Two consequences for entropy #

    Gibbs' inequality proves two facts that lessons 01 and 02 stated.

    Corollary 1 (maximum entropy). For pp on KK values, H(p)≤log⁡KH(p) \le \log K, with equality only for the uniform distribution u=(1K,…,1K)u = (\frac1K, \dots, \frac1K).

    Proof. Put u(x)=1/Ku(x) = 1/K into the definition:

    KL(p ∥ u)=∑xp(x)log⁡p(x)1/K=∑xp(x)log⁡p(x)+log⁡K∑xp(x)=log⁡K−H(p).\begin{aligned} \mathrm{KL}(p\,\|\,u) &= \sum_x p(x) \log \frac{p(x)}{1/K} \\ &= \sum_x p(x)\log p(x) + \log K \sum_x p(x) = \log K - H(p). \end{aligned}

    Gibbs gives log⁡K−H(p)≥0\log K - H(p) \ge 0, with equality only if p=up = u. ■\blacksquare

    So the entropy gap to the maximum is a KL divergence to the uniform distribution. For p=(12,14,18,18)p = (\frac12, \frac14, \frac18, \frac18): H(p)=1.75H(p) = 1.75 bits, log⁡24=2\log_2 4 = 2 bits, and KL(p ∥ u)=0.25\mathrm{KL}(p\,\|\,u) = 0.25 bits.

    Corollary 2 (conditioning reduces entropy on average). H(Y∣X)≤H(Y)H(Y \mid X) \le H(Y), with equality if and only if XX and YY are independent.

    Proof.

    1. Write both entropies as averages over the joint distribution p(x,y)p(x, y): H(Y)=∑x,yp(x,y)log⁡1p(y)H(Y) = \sum_{x, y} p(x, y) \log \frac{1}{p(y)} and H(Y∣X)=∑x,yp(x,y)log⁡1p(y∣x)H(Y \mid X) = \sum_{x, y} p(x, y) \log \frac{1}{p(y \mid x)}.
    2. Subtract: H(Y)−H(Y∣X)=∑x,yp(x,y)log⁡p(y∣x)p(y)H(Y) - H(Y \mid X) = \sum_{x, y} p(x, y) \log \frac{p(y \mid x)}{p(y)}.
    3. Multiply the top and bottom of the fraction by p(x)p(x): p(y∣x)p(y)=p(x,y)p(x) p(y)\frac{p(y \mid x)}{p(y)} = \frac{p(x, y)}{p(x)\,p(y)}.
    4. So H(Y)−H(Y∣X)=KL(p(x,y) ∥ p(x) p(y))≥0H(Y) - H(Y \mid X) = \mathrm{KL}\big(p(x, y)\,\|\,p(x)\,p(y)\big) \ge 0 by Gibbs. Equality holds only if p(x,y)=p(x) p(y)p(x, y) = p(x)\,p(y) for all x,yx, y: independence. ■\blacksquare

    The difference H(Y)−H(Y∣X)H(Y) - H(Y \mid X) is the mutual information I(X;Y)I(X;Y) (lesson 07). Step 4 shows that it is the KL divergence from the joint distribution to the product of the marginals.

    Quick check

    A distribution on 8 values has entropy H(p)=2.2H(p) = 2.2 bits. What is KL(p ∥ u)\mathrm{KL}(p\,\|\,u) for the uniform uu on the 8 values?

    KL is not a metric #

    A metric (distance) dd must be symmetric, d(p,q)=d(q,p)d(p, q) = d(q, p), and must satisfy the triangle inequality, d(p,r)≤d(p,q)+d(q,r)d(p, r) \le d(p, q) + d(q, r). KL fails both.

    • Not symmetric. For the coin, KL(p ∥ q)=0.223\mathrm{KL}(p\,\|\,q) = 0.223 nats (0.3220.322 bits) but KL(q ∥ p)=0.8log⁡1.6+0.2log⁡0.4=0.376−0.183=0.193\mathrm{KL}(q\,\|\,p) = 0.8 \log 1.6 + 0.2 \log 0.4 = 0.376 - 0.183 = 0.193 nats (0.2780.278 bits). The two arguments play different roles: the first one decides where we average.
    • No triangle inequality. Write Ber(a)\mathrm{Ber}(a) for the coin with P(heads)=aP(\text{heads}) = a. Then KL(Ber(0.9) ∥ Ber(0.1))=1.758\mathrm{KL}(\mathrm{Ber}(0.9)\,\|\,\mathrm{Ber}(0.1)) = 1.758 nats, but the two steps through the fair coin give KL(Ber(0.9) ∥ Ber(0.5))+KL(Ber(0.5) ∥ Ber(0.1))=0.368+0.511=0.879\mathrm{KL}(\mathrm{Ber}(0.9)\,\|\,\mathrm{Ber}(0.5)) + \mathrm{KL}(\mathrm{Ber}(0.5)\,\|\,\mathrm{Ber}(0.1)) = 0.368 + 0.511 = 0.879 nats. The direct route is twice as long as the detour.

    This is why the name is "divergence", not "distance". For two close distributions, KL behaves like half a squared distance (see the folded block below), and squared distances also break the triangle inequality: 22>12+122^2 > 1^2 + 1^2.

    Bernoulli KL. For two coins, KL(Ber(a) ∥ Ber(b))\mathrm{KL}(\mathrm{Ber}(a)\,\|\,\mathrm{Ber}(b)) has two terms, one for heads and one for tails:

    alog⁡ab+(1−a)log⁡1−a1−b.a \log \frac{a}{b} + (1 - a) \log \frac{1 - a}{1 - b}.
    Interactive figure: loading…

    Move aa (the true coin) and bb (the model coin). The aqua curve is KL(Ber(a) ∥ Ber(b))\mathrm{KL}(\mathrm{Ber}(a)\,\|\,\mathrm{Ber}(b)) as a function of bb; the grey dashed curve is the reverse, KL(Ber(b) ∥ Ber(a))\mathrm{KL}(\mathrm{Ber}(b)\,\|\,\mathrm{Ber}(a)). Both touch 0 only at b=ab = a. Near b=0b = 0 or b=1b = 1 the aqua curve shoots up to infinity, but the dashed one stays finite. Try the preset a=0a = 0.

    Near pp, KL is half a squared distance

    Let q=p+δq = p + \delta with a small change δ\delta (∑xδ(x)=0\sum_x \delta(x) = 0, and p(x)>0p(x) > 0). A second-order Taylor expansion of log⁡(1+t)≈t−t2/2\log(1 + t) \approx t - t^2/2 gives

    KL(p ∥ p+δ)=−∑xp(x)log⁡(1+δ(x)p(x))≈−∑xδ(x)+12∑xδ(x)2p(x)=12∑xδ(x)2p(x).\begin{aligned} \mathrm{KL}(p\,\|\,p + \delta) &= -\sum_x p(x) \log\Big(1 + \frac{\delta(x)}{p(x)}\Big) \\ &\approx -\sum_x \delta(x) + \frac12 \sum_x \frac{\delta(x)^2}{p(x)} = \frac12 \sum_x \frac{\delta(x)^2}{p(x)}. \end{aligned}

    This is half a weighted squared distance (the weights 1/p(x)1/p(x) are the Fisher information of the categorical distribution). The reverse KL has the same second-order term, so for close distributions the asymmetry disappears; it shows up only at third order. For p=(0.5,0.5)p = (0.5, 0.5) and q=(0.52,0.48)q = (0.52, 0.48): both KLs are 0.0008000.000800 nats, and the formula gives 12(0.0008+0.0008)=0.0008\frac12(0.0008 + 0.0008) = 0.0008. Natural-gradient methods and TRPO use this local metric.

    Answers to section 1. (1) No. KL(p ∥ q)=0.322\mathrm{KL}(p\,\|\,q) = 0.322 bits for the fair coin modelled as (0.8,0.2)(0.8, 0.2), but KL(q ∥ p)=0.278\mathrm{KL}(q\,\|\,p) = 0.278 bits for the reverse situation. (2) Infinite: the term 0.01log⁡0.0100.01 \log \frac{0.01}{0} is +∞+\infty. (3) Yes. A term is negative wherever q(x)>p(x)q(x) > p(x); only the total is ≥0\ge 0.

    Quick check

    What is KL(Ber(0.5) ∥ Ber(0.25))\mathrm{KL}(\mathrm{Ber}(0.5)\,\|\,\mathrm{Ber}(0.25)) in bits?

    4. Worked example #

    (a) Jensen for the log. XX is 1 or 4 with probability 12\frac12 each.

    • E[X]=12⋅1+12⋅4=2.5\mathbb{E}[X] = \frac12 \cdot 1 + \frac12 \cdot 4 = 2.5, so log⁡E[X]=log⁡2.5=0.916\log \mathbb{E}[X] = \log 2.5 = 0.916.
    • E[log⁡X]=12log⁡1+12log⁡4\mathbb{E}[\log X] = \frac12 \log 1 + \frac12 \log 4 =0+log⁡2=0.693= 0 + \log 2 = 0.693.
    • Gap: 0.916−0.693=0.223=log⁡2.52=log⁡1.250.916 - 0.693 = 0.223 = \log \frac{2.5}{2} = \log 1.25. It is positive, as Jensen says.
    • Variance: E[X2]−2.52=12(1+16)−6.25=2.25\mathbb{E}[X^2] - 2.5^2 = \frac12(1 + 16) - 6.25 = 2.25. The Taylor estimate σ2/(2μ2)=2.25/12.5=0.18\sigma^2/(2\mu^2) = 2.25/12.5 = 0.18 is in the right range, but not exact, because the spread is large.

    (b) KL on three outcomes, term by term. p=(0.6,0.3,0.1)p = (0.6, 0.3, 0.1) and q=(0.3,0.4,0.3)q = (0.3, 0.4, 0.3), in bits.

    xx p(x)p(x) q(x)q(x) p(x)/q(x)p(x)/q(x) p(x)log⁡2p(x)q(x)p(x)\log_2\frac{p(x)}{q(x)}
    1 0.6 0.3 2 0.6⋅1=0.6000.6 \cdot 1 = 0.600
    2 0.3 0.4 0.75 0.3⋅(−0.415)=−0.1250.3 \cdot (-0.415) = -0.125
    3 0.1 0.3 0.333 0.1⋅(−1.585)=−0.1580.1 \cdot (-1.585) = -0.158

    KL(p ∥ q)=0.600−0.125−0.158=0.317\mathrm{KL}(p\,\|\,q) = 0.600 - 0.125 - 0.158 = 0.317 bits. Two of the three terms are negative.

    The reverse direction averages under qq: KL(q ∥ p)=0.3log⁡20.30.6+0.4log⁡20.40.3+0.3log⁡20.30.1=−0.300+0.166+0.475=0.342\mathrm{KL}(q\,\|\,p) = 0.3 \log_2 \frac{0.3}{0.6} + 0.4 \log_2 \frac{0.4}{0.3} + 0.3 \log_2 \frac{0.3}{0.1} = -0.300 + 0.166 + 0.475 = 0.342 bits. The largest term now comes from outcome 3, where qq puts three times the mass of pp. In nats, multiply by ln⁡2\ln 2: 0.2200.220 and 0.2370.237 nats.

    (c) Distance to the uniform distribution. p=(12,14,18,18)p = (\frac12, \frac14, \frac18, \frac18) on K=4K = 4 values. Surprisals: 1, 2, 3, 3 bits, so H(p)=12⋅1+14⋅2+18⋅3+18⋅3=1.75H(p) = \frac12 \cdot 1 + \frac14 \cdot 2 + \frac18 \cdot 3 + \frac18 \cdot 3 = 1.75 bits. Then KL(p ∥ u)=log⁡24−1.75=0.25\mathrm{KL}(p\,\|\,u) = \log_2 4 - 1.75 = 0.25 bits. Direct check: 12log⁡21/21/4+14log⁡21+2⋅18log⁡21/81/4=0.5+0−0.25=0.25\frac12 \log_2 \frac{1/2}{1/4} + \frac14 \log_2 1 + 2 \cdot \frac18 \log_2 \frac{1/8}{1/4} = 0.5 + 0 - 0.25 = 0.25 bits.

    (d) The triangle inequality fails. In nats,

    • KL(Ber(0.9) ∥ Ber(0.5))\mathrm{KL}(\mathrm{Ber}(0.9)\,\|\,\mathrm{Ber}(0.5)) =0.9log⁡1.8+0.1log⁡0.2= 0.9 \log 1.8 + 0.1 \log 0.2 =0.529−0.161=0.368= 0.529 - 0.161 = 0.368;
    • KL(Ber(0.5) ∥ Ber(0.1))\mathrm{KL}(\mathrm{Ber}(0.5)\,\|\,\mathrm{Ber}(0.1)) =0.5log⁡5+0.5log⁡59= 0.5 \log 5 + 0.5 \log \frac{5}{9} =0.805−0.294=0.511= 0.805 - 0.294 = 0.511;
    • KL(Ber(0.9) ∥ Ber(0.1))\mathrm{KL}(\mathrm{Ber}(0.9)\,\|\,\mathrm{Ber}(0.1)) =0.9log⁡9+0.1log⁡19= 0.9 \log 9 + 0.1 \log \frac19 =0.8log⁡9=1.758= 0.8 \log 9 = 1.758, which is larger than 0.368+0.5110.368 + 0.511.

    5. In code #

    SciPy has the KL divergence built in: scipy.stats.entropy(p, q) is KL(p ∥ q)\mathrm{KL}(p\,\|\,q), and scipy.special.rel_entr(p, q) returns the single terms plog⁡(p/q)p \log(p/q) with the zero conventions.

    import numpy as np
    from scipy.stats import entropy
    from scipy.special import rel_entr
    
    # (a) Jensen for log: E[log X] <= log E[X]
    x, w = np.array([1.0, 4.0]), np.array([0.5, 0.5])
    print(np.log(w @ x), w @ np.log(x))          # 0.9163 0.6931
    
    # (b) KL term by term, in bits, and the reverse
    p, q = np.array([0.6, 0.3, 0.1]), np.array([0.3, 0.4, 0.3])
    print(rel_entr(p, q) / np.log(2))            # [ 0.6    -0.1245 -0.1585]
    print(entropy(p, q, base=2), entropy(q, p, base=2))   # 0.3170 0.3415
    
    # The coin: not symmetric
    print(entropy([0.5, 0.5], [0.8, 0.2]), entropy([0.8, 0.2], [0.5, 0.5]))   # 0.2231 0.1927 nats
    
    # (c) KL to the uniform distribution = log K - H(p)
    p4 = np.array([1/2, 1/4, 1/8, 1/8])
    print(entropy(p4, np.full(4, 1/4), base=2), 2 - entropy(p4, base=2))   # 0.25 0.25
    
    # Zeros: q = 0 where p > 0 gives inf; p = 0 terms give 0
    print(entropy([0.99, 0.01], [1.0, 0.0]), entropy([1.0, 0.0], [0.99, 0.01]))   # inf 0.01005
    

    entropy(p, q) normalizes both inputs so that they sum to 1. Pass probabilities, not counts with different totals, if you want to see a mistake instead of a silent fix.

    6. Where it shows up #

    • RLHF and fine-tuning. PPO-based RLHF maximizes reward minus β KL(πθ ∥ πref)\beta\,\mathrm{KL}(\pi_\theta\,\|\,\pi_{\text{ref}}), estimated on samples from the tuned policy. Without this term the policy drifts into text that fools the reward model. DPO is derived from the same KL-regularized objective.
    • Knowledge distillation. A student qq is trained on KL(pteacher ∥ q)\mathrm{KL}(p_{\text{teacher}}\,\|\,q), the KL from the teacher's softened output distribution (lesson 04).
    • VAEs and variational inference. The VAE loss contains KL(qϕ(z∣x) ∥ p(z))\mathrm{KL}(q_\phi(z \mid x)\,\|\,p(z)), and the gap of the ELBO is a KL (lesson 09). Which direction of KL you minimize changes the fit (lesson 06).
    • Trust regions. TRPO constrains Es[KL(πold(⋅∣s) ∥ πθ(⋅∣s))]≤δ\mathbb{E}_s\big[\mathrm{KL}(\pi_{\text{old}}(\cdot \mid s)\,\|\,\pi_\theta(\cdot \mid s))\big] \le \delta. Near the old policy, KL is half a squared distance with the Fisher information as the metric.
    • Data drift and monitoring. The population stability index (PSI) used in credit scoring and model monitoring is ∑x(p(x)−q(x))log⁡p(x)q(x)\sum_x (p(x) - q(x)) \log \frac{p(x)}{q(x)} =KL(p ∥ q)+KL(q ∥ p)= \mathrm{KL}(p\,\|\,q) + \mathrm{KL}(q\,\|\,p), a symmetric version of KL between the binned feature distributions of two time windows.
    • ML for science. Model selection with AIC estimates the expected KL from the true data distribution to a fitted model. In climate and weather work, KL compares a forecast distribution with an observed or reference one; it needs the support condition, so forecasts must never give probability 0 to an event that can occur.

    7. Common mistakes #

    • Wrong direction of Jensen for the log. E[log⁡X]≤log⁡E[X]\mathbb{E}[\log X] \le \log \mathbb{E}[X], because log⁡\log is concave. If unsure, draw the chord, or check with X∈{1,4}X \in \{1, 4\}.
    • "Every term of KL is non-negative." Single terms p(x)log⁡p(x)q(x)p(x) \log \frac{p(x)}{q(x)} are negative wherever q(x)>p(x)q(x) > p(x). Only the sum is ≥0\ge 0.
    • Swapping the arguments. KL(p ∥ q)\mathrm{KL}(p\,\|\,q) averages under pp. In general KL(p ∥ q)≠KL(q ∥ p)\mathrm{KL}(p\,\|\,q) \ne \mathrm{KL}(q\,\|\,p), so always say which one you mean.
    • Calling KL a distance. It is not symmetric and it breaks the triangle inequality. If you need a true metric, use the total variation distance, the Hellinger distance or the square root of the Jensen–Shannon divergence (lesson 08).
    • Forgetting the zeros. A model probability of exactly 0 for a possible outcome gives an infinite KL (and an infinite loss). In code, p * np.log(p / q) gives nan for p=0p = 0; use scipy.special.rel_entr, which applies 0log⁡0q=00 \log \frac{0}{q} = 0.
    • Wrong equality condition in Jensen. For a strictly convex ff, equality holds only if XX is constant. For a convex ff that is linear on the range of XX (such as ∣x∣|x| on x>0x > 0), equality can hold with a random XX.

    8. Check yourself #

    1. Use Jensen to show E[1/X]≥1/E[X]\mathbb{E}[1/X] \ge 1/\mathbb{E}[X] for a positive random variable XX. Check it for XX uniform on {1,3}\{1, 3\}.
      Answerf(x)=1/xf(x) = 1/x has f′′(x)=2/x3>0f''(x) = 2/x^3 > 0 on x>0x > 0, so it is strictly convex and Jensen gives 1/E[X]≤E[1/X]1/\mathbb{E}[X] \le \mathbb{E}[1/X], with equality only for a constant XX. Example: E[1/X]=12(1+13)=23\mathbb{E}[1/X] = \frac12(1 + \frac13) = \frac23 and 1/E[X]=121/\mathbb{E}[X] = \frac12; indeed 23≥12\frac23 \ge \frac12.
    2. Compute KL(Ber(0.5) ∥ Ber(0.9))\mathrm{KL}(\mathrm{Ber}(0.5)\,\|\,\mathrm{Ber}(0.9)) and KL(Ber(0.9) ∥ Ber(0.5))\mathrm{KL}(\mathrm{Ber}(0.9)\,\|\,\mathrm{Ber}(0.5)) in nats.
      Answer0.5log⁡0.50.9+0.5log⁡0.50.1=12log⁡259=log⁡53=0.5110.5 \log \frac{0.5}{0.9} + 0.5 \log \frac{0.5}{0.1} = \frac12 \log \frac{25}{9} = \log \frac53 = 0.511 nats. The other way: 0.9log⁡1.8+0.1log⁡0.2=0.529−0.161=0.3680.9 \log 1.8 + 0.1 \log 0.2 = 0.529 - 0.161 = 0.368 nats. Not equal.
    3. In the proof of Gibbs' inequality, why do we sum q(x)q(x) only over the support SS of pp, and why is that sum at most 1?
      AnswerTerms with p(x)=0p(x) = 0 contribute 0 by the convention 0log⁡0q=00 \log \frac{0}{q} = 0, so the KL is a sum over SS only, and Jensen is applied to X∼pX \sim p, which lives on SS. qq may put some mass outside SS, so ∑x∈Sq(x)≤∑xq(x)=1\sum_{x \in S} q(x) \le \sum_x q(x) = 1.
    4. A model predicts q=(0.5,0.5,0)q = (0.5, 0.5, 0) for data with p=(0.5,0.25,0.25)p = (0.5, 0.25, 0.25). What is KL(p ∥ q)\mathrm{KL}(p\,\|\,q)? What is KL(q ∥ p)\mathrm{KL}(q\,\|\,p) in bits?
      AnswerKL(p ∥ q)=+∞\mathrm{KL}(p\,\|\,q) = +\infty, because outcome 3 has p=0.25>0p = 0.25 > 0 and q=0q = 0. The reverse is finite: 0.5log⁡20.50.5+0.5log⁡20.50.25+0=0.50.5 \log_2 \frac{0.5}{0.5} + 0.5 \log_2 \frac{0.5}{0.25} + 0 = 0.5 bits.
    5. Show that H(X,Y)≤H(X)+H(Y)H(X, Y) \le H(X) + H(Y), using a result of this lesson.
      AnswerBy the chain rule of lesson 02, H(X,Y)=H(X)+H(Y∣X)H(X, Y) = H(X) + H(Y \mid X). Corollary 2 gives H(Y∣X)≤H(Y)H(Y \mid X) \le H(Y). So H(X,Y)≤H(X)+H(Y)H(X, Y) \le H(X) + H(Y), with equality only for independent XX and YY. Equivalently, H(X)+H(Y)−H(X,Y)=KL(p(x,y) ∥ p(x)p(y))≥0H(X) + H(Y) - H(X, Y) = \mathrm{KL}(p(x, y)\,\|\,p(x)p(y)) \ge 0.
    6. Two distributions are very close: p=(0.5,0.5)p = (0.5, 0.5) and q=(0.52,0.48)q = (0.52, 0.48). Estimate KL(p ∥ q)\mathrm{KL}(p\,\|\,q) without a calculator.
      AnswerUse KL≈12∑xδ(x)2/p(x)\mathrm{KL} \approx \frac12 \sum_x \delta(x)^2 / p(x) with δ=(0.02,−0.02)\delta = (0.02, -0.02): 12(0.0004/0.5+0.0004/0.5)=0.0008\frac12 (0.0004/0.5 + 0.0004/0.5) = 0.0008 nats. The exact value is 0.0008000.000800 nats.
    Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
    1. State Jensen's inequality for a convex function ff, with the equality condition.

    2. Which way does Jensen's inequality go for log⁡\log, and why?

    3. About how large is the Jensen gap log⁡E[X]−E[log⁡X]\log \mathbb{E}[X] - \mathbb{E}[\log X] when XX has mean μ\mu and small variance σ2\sigma^2?

    4. Define the KL divergence KL(p ∥ q)\mathrm{KL}(p\,\|\,q) of two discrete distributions.

    5. State Gibbs' inequality.

    6. When is KL(p ∥ q)\mathrm{KL}(p\,\|\,q) infinite?

    7. What is KL(p ∥ u)\mathrm{KL}(p\,\|\,u) for the uniform distribution uu on KK values?

    8. Write the KL divergence between two coins, KL(Ber(a) ∥ Ber(b))\mathrm{KL}(\mathrm{Ber}(a)\,\|\,\mathrm{Ber}(b)).

    9. Compute KL(p ∥ q)\mathrm{KL}(p\,\|\,q) in bits for a fair coin pp and the model q=(0.8,0.2)q = (0.8, 0.2).

    10. Why is the KL divergence not a metric?

    Open the review →

    9. Interview angle #

    • "Prove that the KL divergence is non-negative." Write −KL(p ∥ q)=Ep[log⁡(q/p)]-\mathrm{KL}(p\,\|\,q) = \mathbb{E}_p[\log(q/p)], apply Jensen for the concave log: ≤log⁡Ep[q/p]=log⁡∑x:p(x)>0q(x)≤0\le \log \mathbb{E}_p[q/p] = \log \sum_{x: p(x) > 0} q(x) \le 0. Equality only for p=qp = q.
    • "Is KL a distance?" No: not symmetric, no triangle inequality. Give the coin numbers. Near pp it behaves like half a squared distance with the Fisher metric.
    • "What happens if the model assigns probability 0 to a real outcome?" The KL (and the cross-entropy loss) is infinite. This is why models use a softmax, which is never exactly 0, and why probabilities are clipped or smoothed.
    • "Why is the ELBO a lower bound?" Jensen for the concave log: log⁡Eq[p(x,z)/q(z)]\log \mathbb{E}_q[p(x, z)/q(z)] ≥Eq[log⁡(p(x,z)/q(z))]\ge \mathbb{E}_q[\log(p(x, z)/q(z))].
    • "Which distribution on KK outcomes has the largest entropy?" The uniform one, because log⁡K−H(p)=KL(p ∥ u)≥0\log K - H(p) = \mathrm{KL}(p\,\|\,u) \ge 0.

    10. Practice #

    The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution:

    1. jensen_gap(f, values, probs), and a check of the Taylor estimate σ2/(2μ2)\sigma^2/(2\mu^2) for log⁡\log.
    2. kl_divergence(p, q, base) with the right handling of zeros, checked against scipy.special.rel_entr.
    3. Random pairs of distributions: check KL≥0\mathrm{KL} \ge 0, and find the pair with the largest asymmetry.
    4. Verify log⁡K−H(p)=KL(p ∥ u)\log K - H(p) = \mathrm{KL}(p\,\|\,u) and H(Y)−H(Y∣X)=KL(p(x,y) ∥ p(x)p(y))H(Y) - H(Y \mid X) = \mathrm{KL}(p(x,y)\,\|\,p(x)p(y)) on random tables.
    5. The log-sum inequality on random positive vectors, and its equality case.

    11. Watch and read #

    The chord and centre-of-mass picture of section 2, with the equality condition.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    KL as the average log-ratio of two distributions, built up from the likelihood ratio.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Entropy, cross-entropy and KL as message lengths; the same decomposition as our coin example.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Surprise, entropy, cross-entropy and KL divergence in one story, with clear animations.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play