Module contents
Lesson 12 of 19Advanced 110 min

f-divergences, Jensen-Shannon and variational representations

Unify KL, reverse KL, total variation, Hellinger, chi-squared, and Jensen–Shannon as f-divergences. Study data processing, Jensen–Shannon and GANs, Pinsker's inequality, and variational representations that turn divergence estimation into optimization over critics.

After this lesson you can

  • Express KL, reverse KL, total variation, Hellinger, chi-squared, and Jensen–Shannon as f-divergences using their generators.
  • Prove data processing for f-divergences using Jensen's inequality.
  • Prove the Jensen–Shannon upper bound and derive the original GAN objective with the optimal discriminator.
  • Prove Pinsker's inequality and use it to bound differences in probabilities.
  • Derive the Fenchel and Donsker–Varadhan representations and explain why the latter is tighter for KL.

Before you start

Motivation: each divergence is an algorithm

Much of distribution learning consists of choosing a way to measure how far a model QθQ_\theta is from data PP and minimizing it. This choice is not a technical detail: it changes the algorithm, what can be estimated from samples, and how it fails.

  • Maximum likelihood minimizes KL divergence KL⁡(P ∥ Qθ)\KL(P\,\|\,Q_\theta): it requires evaluating log⁡qθ(x)\log q_\theta(x) and severely penalizes a model that assigns almost zero probability to something produced by the data.
  • The original GAN (Goodfellow et al., 2014) minimizes Jensen–Shannon divergence with an optimal discriminator. It only needs samples from qθq_\theta, not its evaluation, but stops providing a gradient when model and data do not overlap (the GAN minimax game).
  • The Wasserstein GAN (Arjovsky, Chintala, and Bottou, 2017) replaces JSD with an optimal transport distance that can see how far apart disjoint supports are (WGAN).
  • Two-sample tests (do these data come from the same distribution as those?) use total variation, which exactly determines the best achievable error (classifier two-sample test).
  • Neural mutual-information estimators (MINE, InfoNCE) maximize a KL lower bound over a “critic” network, using a variational representation we will see later (InfoNCE as a mutual-information bound).

This lesson shows that almost all these quantities are cases of one family, the f-divergences independently introduced by Csiszár (1963) and Ali and Silvey (1966). They share properties (nonnegativity, convexity, data processing) proved once for all, and each is specified by a convex function of one variable. We then study the three most common in machine learning besides KL: total variation, Hellinger, and Jensen–Shannon; relate them to one another (Pinsker); and reach the idea that makes them useful in practice: each divergence is the value of an optimization problem over critic functions, and can therefore be estimated by training a discriminator.

f-divergences

KL compares pp and qq through the likelihood ratio p(x)/q(x)p(x)/q(x): KL⁡(P ∥ Q)=∑xq(x) p(x)q(x)log⁡p(x)q(x)\KL(P\,\|\,Q) = \sum_x q(x)\,\frac{p(x)}{q(x)}\log\frac{p(x)}{q(x)}. It is the mean under QQ of f(t)=tlog⁡tf(t) = t\log t evaluated at that ratio. Changing ff gives a whole family.

The second convention is the natural limit: q f(p/q)=p⋅f(p/q)p/q→p f′(∞)q\,f(p/q) = p\cdot\frac{f(p/q)}{p/q} \to p\,f'(\infty) as q→0q \to 0. It specifies the cost of mass of PP where QQ puts none. For KL, f′(∞)=∞f'(\infty) = \infty, recovering KL⁡(P ∥ Q)=∞\KL(P\,\|\,Q) = \infty if PP is not absolutely continuous with respect to QQ.

DivergenceGenerator f(t)f(t)Df(P ∥ Q)D_f(P\,\|\,Q)Maximumf′′(1)f''(1)
KLtlog⁡tt\log t∑plog⁡pq\sum p\log\frac{p}{q}∞\infty11
Reverse KL−log⁡t-\log t∑qlog⁡qp=KL⁡(Q ∥ P)\sum q\log\frac{q}{p} = \KL(Q\,\|\,P)∞\infty11
Total variation12∣t−1∣\tfrac12\abs{t - 1}12∑∣p−q∣\tfrac12\sum\abs{p - q}11does not exist
Squared Hellinger(t−1)2(\sqrt{t} - 1)^2∑(p−q)2\sum(\sqrt{p} - \sqrt{q})^22212\tfrac12
Pearson χ2\chi^2(t−1)2(t - 1)^2∑(p−q)2q\sum\frac{(p - q)^2}{q}∞\infty22
Jensen–Shannon12[tlog⁡t−(1+t)log⁡1+t2]\tfrac12\big[t\log t - (1 + t)\log\tfrac{1 + t}{2}\big]12KL⁡(P ∥ M)+12KL⁡(Q ∥ M)\tfrac12\KL(P\,\|\,M) + \tfrac12\KL(Q\,\|\,M)log⁡2\log 214\tfrac14

In the last row, M=(P+Q)/2M = (P + Q)/2; an exercise checks that this generator gives JSD. There are two Hellinger conventions: here H2(P,Q)=∑(p−q)2∈[0,2]H^2(P, Q) = \sum(\sqrt p - \sqrt q)^2 \in [0, 2]; other texts put 12\tfrac12 in front so it lies in [0,1][0, 1]. Always check the source’s convention.

Three observations about the generator save work:

  1. The generator is not unique. For any c∈Rc \in \R, f(t)+c(t−1)f(t) + c(t - 1) gives the same divergence, because ∑xq c (p/q−1)=c∑x(p−q)=0\sum_x q\,c\,(p/q - 1) = c\sum_x (p - q) = 0 (if P≪QP \ll Q). Choosing c=−f′(1)c = -f'(1) (or minus a subgradient at 1 if ff is not differentiable there, as in TV) gives a generator with minimum at t=1t = 1, and thus nonnegative: for KL, tlog⁡t−t+1≥0t\log t - t + 1 \ge 0. Its integrand is also pointwise nonnegative, although that of tlog⁡tt\log t is not.
  2. Swapping arguments changes the generator. Df(Q ∥ P)=∑p f(q/p)=∑q pqf(qp)=Df⋄(P ∥ Q)D_f(Q\,\|\,P) = \sum p\,f(q/p) = \sum q\,\frac{p}{q}f\big(\frac{q}{p}\big) = D_{f^\diamond}(P\,\|\,Q) with f⋄(t)=t f(1/t)f^\diamond(t) = t\,f(1/t), which is also convex (the perspective of ff). For f=tlog⁡tf = t\log t, f⋄=−log⁡tf^\diamond = -\log t: reverse KL. An f-divergence is symmetric if and only if f−f⋄f - f^\diamond has the form c(t−1)c(t - 1).
  3. Near P=QP = Q, all resemble χ2\chi^2. If ff is twice differentiable at 1, Taylor expansion f(t)=f′(1)(t−1)+12f′′(1)(t−1)2+o((t−1)2)f(t) = f'(1)(t - 1) + \tfrac12 f''(1)(t - 1)^2 + o((t - 1)^2), multiplied by qq and summed, gives Df(P ∥ Q)≈f′′(1)2 χ2(P ∥ Q)D_f(P\,\|\,Q) \approx \tfrac{f''(1)}{2}\,\chi^2(P\,\|\,Q): the linear term vanishes by observation 1. Thus all smooth divergences locally have the same quadratic form, the Fisher information of lesson 16, up to a factor.
InteractiveThe f-divergence zoo
Generator f(t)f(t) with t=p/qt = p/q
f(1) = 0
Densities pp, qq and integrand q f(p/q)q\,f(p/q): its area is DfD_f
  • p=N(0,1)p = \mathcal{N}(0, 1)
  • q=N(Δ,σ2)q = \mathcal{N}(\Delta, \sigma^2)
  • q f(p/q)q\,f(p/q)
The six divergences Df(P ∥ Q)D_f(P\,\|\,Q) versus separation Δ\Delta (in nats)
  • KL
  • Reverse KL
  • Total variation
  • Hellinger²
  • Pearson χ²
  • Jensen-Shannon
1.50
1.00
Vertical scale
f(t)=tlog⁡tf(t) = t\log t
KL⁡(P ∥ Q)\KL(P\,\|\,Q)1.125
KL⁡(Q ∥ P)\KL(Q\,\|\,P)1.125
Upper boundnone
f′′(1)f''(1)1.00
Df / f′′(1)2χ2D_f \,/\, \tfrac{f''(1)}{2}\chi^20.265
The shaded (signed) area is the divergence. Enable the nonnegative form: the integrand changes, the area does not.
P=N(0,1)P = \mathcal{N}(0, 1) in blue and Q=N(Δ,σ2)Q = \mathcal{N}(\Delta, \sigma^2) in orange. At top left, the chosen generator; at right, integrand q f(p/q)q\,f(p/q), whose signed area is the divergence. Below, the six divergences against separation Δ\Delta. Notice which curves flatten (and at what value), which shoot up, and what happens at σ≠1\sigma \neq 1: which change when swapping PP and QQ? On the logarithmic scale near Δ=0\Delta = 0 all but one grow as Δ2\Delta^2. Enable the nonnegative form for KL: the integrand no longer has negative parts and the area is unchanged.

With σ=1\sigma = 1 the figure shows the main division in the family. Total variation, Hellinger, and Jensen–Shannon saturate at 1, 2, and log⁡2\log 2: beyond a certain separation they no longer distinguish “far” from “very far.” KL grows as Δ2/2\Delta^2/2 and χ2\chi^2 explodes as eΔ2−1e^{\Delta^2} - 1. With σ≠1\sigma \neq 1, KL and χ2\chi^2 change on swapping arguments (with σ≥2\sigma \ge \sqrt 2, χ2(Q ∥ P)\chi^2(Q\,\|\,P) is even infinite while χ2(P ∥ Q)\chi^2(P\,\|\,Q) is finite); TV, Hellinger, and JSD do not, because their generators satisfy f⋄=ff^\diamond = f. On a logarithmic scale, Df/(f′′(1)2χ2)D_f / (\tfrac{f''(1)}{2}\chi^2) tends to 1 as Δ→0\Delta \to 0 with σ=1\sigma = 1, for all except TV, whose generator has a cusp at t=1t = 1 and grows linearly.

Common properties

Proof

We handle the case P≪QP \ll Q (if q(x)=0q(x) = 0 then p(x)=0p(x) = 0); the general case adds P(q=0) f′(∞)P(q = 0)\,f'(\infty) and is treated similarly using f(t+s)≤f(t)+s f′(∞)f(t + s) \le f(t) + s\,f'(\infty).

(1) By Jensen’s inequality with variable t=p(X)/q(X)t = p(X)/q(X), X∼QX \sim Q: Df(P ∥ Q)=EQ[f(t)]≥f(EQ[t])=f(∑xp(x))=f(1)=0D_f(P\,\|\,Q) = \E_Q[f(t)] \ge f(\E_Q[t]) = f\big(\sum_x p(x)\big) = f(1) = 0. If ff is strictly convex at 1, equality in Jensen requires tt to be constant QQ-almost surely, that is, p=qp = q.

(2) It suffices to show that the perspective g(a,b)=b f(a/b)g(a, b) = b\,f(a/b) is jointly convex in b>0b > 0 and sum over xx. If (a,b)=λ(a1,b1)+(1−λ)(a2,b2)(a, b) = \lambda(a_1, b_1) + (1 - \lambda)(a_2, b_2), then ab=λb1ba1b1+(1−λ)b2ba2b2\frac{a}{b} = \frac{\lambda b_1}{b}\frac{a_1}{b_1} + \frac{(1 - \lambda)b_2}{b}\frac{a_2}{b_2} is a convex combination, and by convexity of ff, b f(a/b)≤λb1f(a1/b1)+(1−λ)b2f(a2/b2)b\,f(a/b) \le \lambda b_1 f(a_1/b_1) + (1 - \lambda)b_2 f(a_2/b_2). For KL this is the log-sum inequality, used to prove its joint convexity.

(3) Fix an output yy with (QK)(y)>0(QK)(y) > 0 and define weights wx(y)=Q(x)K(y∣x)/(QK)(y)w_x(y) = Q(x)K(y \given x)/(QK)(y), which sum to 1 over xx (they are the input posterior given the output under QQ). Then

(PK)(y)(QK)(y)=∑xP(x)K(y∣x)(QK)(y)=∑xwx(y) P(x)Q(x),\frac{(PK)(y)}{(QK)(y)} = \sum_x \frac{P(x)K(y \given x)}{(QK)(y)} = \sum_x w_x(y)\,\frac{P(x)}{Q(x)},

and by Jensen, f((PK)(y)/(QK)(y))≤∑xwx(y)f(P(x)/Q(x))f\big((PK)(y)/(QK)(y)\big) \le \sum_x w_x(y) f(P(x)/Q(x)). Multiply by (QK)(y)(QK)(y) and sum over yy: the right-hand side becomes ∑x∑yQ(x)K(y∣x)f(P(x)/Q(x))=∑xQ(x)f(P(x)/Q(x))\sum_x\sum_y Q(x)K(y \given x)f(P(x)/Q(x)) = \sum_x Q(x)f(P(x)/Q(x)), because ∑yK(y∣x)=1\sum_y K(y \given x) = 1.

(4) For a convex function, the chord slope from 0, (f(t)−f(0))/t(f(t) - f(0))/t, increases with tt and tends to f′(∞)f'(\infty). Hence f(t)≤f(0)+t f′(∞)f(t) \le f(0) + t\,f'(\infty), and multiplying by qq gives q f(p/q)≤q f(0)+p f′(∞)q\,f(p/q) \le q\,f(0) + p\,f'(\infty). Summing, Df≤f(0)+f′(∞)D_f \le f(0) + f'(\infty). If the supports are disjoint, each xx has p=0p = 0 (contributing q f(0)q\,f(0)) or q=0q = 0 (contributing p f′(∞)p\,f'(\infty)), and the sum is exactly f(0)+f′(∞)f(0) + f'(\infty).

∎

Point (3) generalizes the data-processing inequality for mutual information: no transformation of data, deterministic or random, makes two distributions more distinguishable, and this holds for every f-divergence at once. If the transformation is invertible, apply it both ways and divergence is unchanged. This invariance has a hidden side: an f-divergence does not care how space is organized, only about ratios p/qp/q.

Point (4) is the saturation seen in the figure, now for the entire family: TV is 12+12=1\tfrac12 + \tfrac12 = 1 on disjoint supports, Hellinger 1+1=21 + 1 = 2, JSD 12log⁡2+12log⁡2=log⁡2\tfrac12\log 2 + \tfrac12\log 2 = \log 2, and KL and χ2\chi^2, ∞\infty. Two distributions with disjoint supports have the same f-divergence whether their supports are 10−610^{-6} or 10610^6 apart. We return to this with GANs.

Total variation and Hellinger: error of the best test

The three expressions agree. With A∗={x:p(x)>q(x)}A^* = \{x : p(x) > q(x)\}, for any event AA, P(A)−Q(A)=∑A(p−q)≤∑A∩A∗(p−q)≤∑A∗(p−q)P(A) - Q(A) = \sum_{A}(p - q) \le \sum_{A \cap A^*}(p - q) \le \sum_{A^*}(p - q), and by symmetry Q(A)−P(A)≤∑(A∗)c(q−p)Q(A) - P(A) \le \sum_{(A^*)^c}(q - p). Since ∑x(p−q)=0\sum_x (p - q) = 0, the two sums over A∗A^* and its complement are equal, 12∑∣p−q∣\tfrac12\sum\abs{p - q}, and the supremum is attained at A∗A^*. The third expression follows from ∣p−q∣=p+q−2min⁡(p,q)\abs{p - q} = p + q - 2\min(p, q). It is the f-divergence of f(t)=12∣t−1∣f(t) = \tfrac12\abs{t - 1} and also a metric: half the ℓ1\ell_1 norm.

Its operational interpretation explains why it appears everywhere.

Proof

A deterministic rule is a set AA on which one says “PP.” Its error probability is 12P(Ac)+12Q(A)=12(1−(P(A)−Q(A)))\tfrac12 P(A^c) + \tfrac12 Q(A) = \tfrac12\big(1 - (P(A) - Q(A))\big), minimized when P(A)−Q(A)P(A) - Q(A) is maximal, that is, at A∗A^*, where it equals TV\mathrm{TV}. A randomized rule says “PP” with probability ϕ(x)∈[0,1]\phi(x) \in [0, 1] and its error, 12(1−∑xϕ(x)(p(x)−q(x)))\tfrac12\big(1 - \sum_x \phi(x)(p(x) - q(x))\big), is linear in ϕ\phi, so its minimum is at a vertex ϕ=1A\phi = \ind_{A}.

∎

Thus TV=0\mathrm{TV} = 0 means no test beats a coin flip, and TV=1\mathrm{TV} = 1 means a perfect test exists. With priors π\pi and 1−π1 - \pi the minimum error is ∑xmin⁡(πp(x),(1−π)q(x))\sum_x \min(\pi p(x), (1 - \pi)q(x)) by the same argument. This is the simplest form of the Neyman–Pearson lemma and the basis for using a classifier trained to distinguish samples as a two-sample test: its accuracy is bounded by 12(1+TV)\tfrac12(1 + \mathrm{TV}).

Many observations: Hellinger tensorizes

What if you observe nn iid samples? The question becomes TV(P⊗n,Q⊗n)\mathrm{TV}(P^{\otimes n}, Q^{\otimes n}), which has no simple expression in terms of TV(P,Q)\mathrm{TV}(P, Q). Hellinger, however, behaves beautifully with products. Write it using the Bhattacharyya coefficient BC(P,Q)=∑xp(x)q(x)\mathrm{BC}(P, Q) = \sum_x\sqrt{p(x)q(x)}:

H2(P,Q)=∑x(p−2pq+q)=2(1−BC(P,Q)).H^2(P, Q) = \sum_x\big(p - 2\sqrt{pq} + q\big) = 2\big(1 - \mathrm{BC}(P, Q)\big).

For products, p1(x1)p2(x2) q1(x1)q2(x2)\sqrt{p_1(x_1)p_2(x_2)\,q_1(x_1)q_2(x_2)} factors, so BC(P1⊗P2,Q1⊗Q2)=BC(P1,Q1) BC(P2,Q2)\mathrm{BC}(P_1 \otimes P_2, Q_1 \otimes Q_2) = \mathrm{BC}(P_1, Q_1)\,\mathrm{BC}(P_2, Q_2) and BC(P⊗n,Q⊗n)=BC(P,Q)n\mathrm{BC}(P^{\otimes n}, Q^{\otimes n}) = \mathrm{BC}(P, Q)^n. It remains to relate Hellinger and TV:

Proof

Left: min⁡(p,q)≤pq\min(p, q) \le \sqrt{pq}, hence 1−TV=∑min⁡(p,q)≤BC=1−H2/21 - \mathrm{TV} = \sum\min(p, q) \le \mathrm{BC} = 1 - H^2/2. Right: by Cauchy–Schwarz, ∑∣p−q∣=∑∣p−q∣ (p+q)≤∑(p−q)2 ∑(p+q)2=H2+2 BC=H4−H2\sum\abs{p - q} = \sum\abs{\sqrt p - \sqrt q}\,(\sqrt p + \sqrt q) \le \sqrt{\sum(\sqrt p - \sqrt q)^2}\,\sqrt{\sum(\sqrt p + \sqrt q)^2} = H\sqrt{2 + 2\,\mathrm{BC}} = H\sqrt{4 - H^2}, and divide by 2.

∎

The consequence is a scaling law: distinguishing PP from QQ with small error requires on the order of 1/H2(P,Q)1/H^2(P, Q) samples, no more and no less. For a fair coin against one with probability 0.550.55 of heads, BC=0.5⋅0.55+0.5⋅0.45=0.998746\mathrm{BC} = \sqrt{0.5\cdot 0.55} + \sqrt{0.5\cdot 0.45} = 0.998746 and H2=0.00251H^2 = 0.00251. To guarantee error ≤0.05\le 0.05 requires TV(P⊗n,Q⊗n)≥0.9\mathrm{TV}(P^{\otimes n}, Q^{\otimes n}) \ge 0.9. The left bound says BCn≤0.1\mathrm{BC}^n \le 0.1 suffices, that is, n≥1836n \ge 1836; the right says at least n≥662n \ge 662 is needed. The exact value, computed with the two binomials, is n=1079n = 1079, between the two and of order 1/H2≈3991/H^2 \approx 399 times a constant. KL tensorizes even better, KL⁡(P⊗n ∥ Q⊗n)=n KL⁡(P ∥ Q)\KL(P^{\otimes n}\,\|\,Q^{\otimes n}) = n\,\KL(P\,\|\,Q) (the chain rule), and χ2\chi^2 satisfies 1+χ2(P⊗n ∥ Q⊗n)=(1+χ2(P ∥ Q))n1 + \chi^2(P^{\otimes n}\,\|\,Q^{\otimes n}) = (1 + \chi^2(P\,\|\,Q))^n. TV does not tensorize: that is why statistical lower-bound proofs usually go through Hellinger or KL and return to TV at the end.

Jensen–Shannon: a divergence that can be symmetrized sensibly

KL is asymmetric and can be infinite. The naive fix, KL⁡(P ∥ Q)+KL⁡(Q ∥ P)\KL(P\,\|\,Q) + \KL(Q\,\|\,P), is symmetric but remains infinite whenever one support does not contain the other. Lin (1991) proposed comparing both with their mixture, which always contains them.

The second form explains the name: it is the Jensen gap of entropy, which is concave, between the entropy of the mixture and the mixture of entropies. Since p≤2mp \le 2m and q≤2mq \le 2m, the ratios p/mp/m and q/mq/m are bounded by 2, and both KL terms are finite.

Proof

(1) Mutual information is the average KL between conditionals and the marginal: I(Z;X)=∑zP(Z=z) KL⁡(PX∣z ∥ PX)I(Z; X) = \sum_z \Pr(Z = z)\,\KL(P_{X \given z}\,\|\,P_X), and here the marginal of XX is MM. (2) I(Z;X)≤H⁡(Z)=log⁡2I(Z; X) \le \Ent(Z) = \log 2, with equality if and only if H⁡(Z∣X)=0\Ent(Z \given X) = 0, that is, if seeing XX reveals which distribution it came from: disjoint supports. Nonnegativity, with equality only if P=M=QP = M = Q, follows from KL. (3) Symmetry is immediate from the definition; the exercises verify the generator. (5) Lower bound: TV(P,M)=12∑∣p−(p+q)/2∣=12TV(P,Q)\mathrm{TV}(P, M) = \tfrac12\sum\abs{p - (p + q)/2} = \tfrac12\mathrm{TV}(P, Q), and by Pinsker’s inequality in the next section, KL⁡(P ∥ M)≥2 TV(P,M)2=12TV(P,Q)2\KL(P\,\|\,M) \ge 2\,\mathrm{TV}(P, M)^2 = \tfrac12\mathrm{TV}(P, Q)^2, likewise for QQ, then average. Upper bound: with t=TV(P,Q)∈(0,1)t = \mathrm{TV}(P, Q) \in (0, 1), decompose P=(1−t)C+tP′P = (1 - t)C + tP' and Q=(1−t)C+tQ′Q = (1 - t)C + tQ', where C=min⁡(p,q)/(1−t)C = \min(p, q)/(1 - t), P′=(p−q)+/tP' = (p - q)^+/t, and Q′=(q−p)+/tQ' = (q - p)^+/t; P′P' and Q′Q' have disjoint supports. By joint convexity, JS(P ∥ Q)≤(1−t) JS(C ∥ C)+t JS(P′ ∥ Q′)=tlog⁡2\mathrm{JS}(P\,\|\,Q) \le (1 - t)\,\mathrm{JS}(C\,\|\,C) + t\,\mathrm{JS}(P'\,\|\,Q') = t\log 2.

∎

The mutual-information interpretation is most useful: JSD measures how much an observer learns about the “real or generated” label upon seeing a sample from the equally weighted mixture. With weights πi\pi_i and kk distributions, JSπ(P1,…,Pk)=H⁡(∑iπiPi)−∑iπiH⁡(Pi)=I(Z;X)\mathrm{JS}_\pi(P_1, \dots, P_k) = \Ent(\sum_i\pi_i P_i) - \sum_i\pi_i\Ent(P_i) = I(Z; X) with Z∼πZ \sim \pi, and its maximum over π\pi is the channel capacity z↦Pzz \mapsto P_z (the “information radius” of lesson 9). The root JS\sqrt{\mathrm{JS}} is used as a distance between distributions in clustering and document retrieval because it is a bounded metric; JSD without the root does not satisfy the triangle inequality (you will check this numerically).

JSD and GANs

A GAN pits a generator GθG_\theta, which transforms noise zz into samples x=Gθ(z)x = G_\theta(z) with distribution QθQ_\theta, against a discriminator D:X→(0,1)D: \mathcal{X} \to (0, 1) estimating the probability that xx comes from data PP. The original objective is

min⁡θmax⁡D V(D,θ)=Ex∼P[log⁡D(x)]+Ex∼Qθ[log⁡(1−D(x))].\min_\theta\max_D\ V(D, \theta) = \E_{x \sim P}\big[\log D(x)\big] + \E_{x \sim Q_\theta}\big[\log(1 - D(x))\big].

For fixed θ\theta, the maximum over DD can be found pointwise: at each xx maximize alog⁡D+blog⁡(1−D)a\log D + b\log(1 - D) with a=p(x)a = p(x), b=qθ(x)b = q_\theta(x), whose derivative a/D−b/(1−D)a/D - b/(1 - D) vanishes at D=a/(a+b)D = a/(a + b). Therefore the optimal discriminator is

D∗(x)=p(x)p(x)+qθ(x),D^*(x) = \frac{p(x)}{p(x) + q_\theta(x)},

the posterior probability of “real” with equal priors. Substitution gives:

The proof is one line of algebra you will do in the guided exercise: write pp+q=12⋅pm\frac{p}{p + q} = \frac12\cdot\frac{p}{m}. This result justified GANs, but also points to their weakness. If PP and QθQ_\theta have disjoint supports, property (4) says JS(P ∥ Qθ)=log⁡2\mathrm{JS}(P\,\|\,Q_\theta) = \log 2 for every θ\theta in a neighborhood: the objective is constant and its gradient with respect to θ\theta is exactly zero. This is not rare. Arjovsky and Bottou (2017) observed that when data and generator samples live on manifolds of lower dimension than the ambient space (images of 64×64×364\times 64\times 3 pixels generated from 100-dimensional noise), they typically do not intersect, and a perfect discriminator exists.

InteractiveWhy the original GAN stops learning
Data pp (fixed) and generator qθq_\theta; dashed curves show generator positions during training
Optimal discriminator D∗(x)=p/(p+qθ)D^*(x) = p/(p + q_\theta)
1½0
JSD (bits) and TV versus θ
Wasserstein W1W_1 versus θ
  • data pp
  • generator qθq_\theta
  • JSD
  • total variation
  • W1W_1
3.00
1.00
JSD (bits)1.000
log⁡2−JSD\log 2 - \mathrm{JSD} (nats)0.000
∂ JSD/∂θ\partial\,\mathrm{JSD}/\partial\theta (nats)0.000
Total variation1.000
W1(P,Qθ)W_1(P, Q_\theta)3.00
∂W1/∂θ\partial W_1/\partial\theta1.000
Without overlap the optimal discriminator separates perfectly, with D∗=1D^* = 1 on PP and D∗=0D^* = 0 on QQ, and JSD equals log⁡2\log 2 for any θ: there is no slope to follow.
Data pp (blue) are fixed and generator qθq_\theta (orange) is the same shape shifted by θ\theta. The central strip is the optimal discriminator. Below, JSD (in bits) and total variation against θ\theta, and Wasserstein distance W1W_1; the short segments are tangents at the current θ\theta. Separate the supports until they no longer overlap and select ‘Train’: the generator descends each loss gradient (hollow points and dashed curves). Switch to the Gaussian shape, whose supports always overlap: what is the JSD gradient at θ=5\theta = 5?

With uniform shapes, while supports overlap, JSD is exactly θ2alog⁡2\frac{\theta}{2a}\log 2, a straight line, and stops increasing at θ=2a\theta = 2a. Beyond that the optimal discriminator is 1 throughout the support of PP and 0 on that of QθQ_\theta, and shifting the generator does not change it. With Gaussians the gradient is never zero, but at θ=5\theta = 5 with a=1a = 1 it is already of order 10−610^{-6}: practically the same. In contrast, W1(P,Qθ)=∣θ∣W_1(P, Q_\theta) = \abs{\theta} for any translation: slope 1 at any distance.

Goodfellow et al. already proposed in 2014 training the generator with the non-saturating loss −Ez[log⁡D(Gθ(z))]-\E_{z}[\log D(G_\theta(z))] instead of Ez[log⁡(1−D(Gθ(z)))]\E_z[\log(1 - D(G_\theta(z)))]: with a discriminator that confidently rejects fake samples, log⁡(1−D)≈0\log(1 - D) \approx 0 is flat, but −log⁡D-\log D is very steep. This fix works, but no longer minimizes JSD: Arjovsky and Bottou showed that, with an optimal discriminator, its gradient is that of KL⁡(Qθ ∥ P)−2 JS(P ∥ Qθ)\KL(Q_\theta\,\|\,P) - 2\,\mathrm{JS}(P\,\|\,Q_\theta), a peculiar combination that pushes both to reduce reverse KL (which tolerates forgetting modes of PP) and to move away in JSD. You will measure this in the minimal GAN at the end of the lesson.

The fundamental solution was to change families. The Wasserstein distance W1W_1 is defined by optimal transport and, by Kantorovich–Rubinstein duality, is also a supremum over critics: W1(P,Q)=sup⁡{EP[g]−EQ[g]:g 1-lipschitziana}W_1(P, Q) = \sup\{\E_P[g] - \E_Q[g] : g \text{ 1-lipschitziana}\}. Compare it with total variation, which has the same form with another class: TV(P,Q)=12sup⁡{EP[g]−EQ[g]:∣g∣≤1}\mathrm{TV}(P, Q) = \tfrac12\sup\{\E_P[g] - \E_Q[g] : \abs{g} \le 1\}. TV lets the critic jump from −1-1 to 11 in one step, so it ignores support separation; W1W_1 forces it to rise with bounded slope, making distance between supports count. It is not an f-divergence: it depends on the space’s metric, precisely what f-divergences ignore.

Pinsker’s inequality and other relations

Does small KL force the probabilities of every event to be close? Yes, with an optimal constant.

Pinsker’s inequality is proved in two steps; the first is the general pattern for relating f-divergences: reduce to the binary case using data processing. Let A∗={p>q}A^* = \{p > q\} and apply to PP and QQ the deterministic channel x↦1[x∈A∗]x \mapsto \ind[x \in A^*]. The outputs are two coins, Bern⁡(a)\Bern(a) and Bern⁡(b)\Bern(b) with a=P(A∗)a = P(A^*) and b=Q(A∗)b = Q(A^*). By data processing, KL⁡(P ∥ Q)≥kl(a ∥ b)\KL(P\,\|\,Q) \ge \mathrm{kl}(a\,\|\,b), where kl(a ∥ b)=alog⁡ab+(1−a)log⁡1−a1−b\mathrm{kl}(a\,\|\,b) = a\log\frac{a}{b} + (1 - a)\log\frac{1 - a}{1 - b} is binary KL; TV loses nothing, because exactly TV(P,Q)=a−b\mathrm{TV}(P, Q) = a - b (the supremum was attained at A∗A^*). This leaves an inequality between two numbers,

kl(a ∥ b)≥2(a−b)2para 0≤b≤a≤1,\mathrm{kl}(a\,\|\,b) \ge 2(a - b)^2 \qquad \text{para } 0 \le b \le a \le 1,

proved using single-variable calculus: function g(b)=kl(a ∥ b)−2(a−b)2g(b) = \mathrm{kl}(a\,\|\,b) - 2(a - b)^2 is 0 at b=ab = a and decreases on b∈(0,a]b \in (0, a], because g′(b)=(a−b)(4−1b(1−b))g'(b) = (a - b)\big(4 - \frac{1}{b(1 - b)}\big) and b(1−b)≤14b(1 - b) \le \tfrac14. You will reconstruct the details in the guided exercise.

InteractivePinsker on the simplex
Three-outcome simplex (each vertex is certainty in one)
123
Each gray point is a random pair: (TV,KL⁡)(\mathrm{TV}, \KL)
  • random pairs
  • Pinsker: KL⁡=2 TV2\KL = 2\,\mathrm{TV}^2
  • your pair
KL direction
pp0.50, 0.30, 0.20
qq0.20, 0.30, 0.50
TV0.300
KL⁡(p ∥ q)\KL(p\,\|\,q) (nats)0.275
Pinsker: 2 TV22\,\mathrm{TV}^20.180
Ratio KL⁡/2 TV2\KL / 2\,\mathrm{TV}^21.527
Maximum TV from Pinsker0.371
KL is 1.53 times 2 TV22\,\mathrm{TV}^2. Find a case where the ratio approaches 1.
At left, the triangle of all distributions over three outcomes, with draggable points pp and qq. At right, 1500 random pairs in the (TV, KL) plane and Pinsker curve KL⁡=2 TV2\KL = 2\,\mathrm{TV}^2: none falls below it. Your pair is the large point, and the vertical segment measures slack in the bound. Find a pair whose ratio approaches 1 (hint: the intuition above). Then move qq to an edge of the triangle: KL becomes infinite at moderate TV. Enable Bretagnolle-Huber to see which bound dominates as TV approaches 1.

In practice, Pinsker translates KL constraints, which can be imposed and optimized, into guarantees about probabilities, which are what matter. If a model satisfies KL⁡(P ∥ Q)≤0.02\KL(P\,\|\,Q) \le 0.02 nats, no event’s probability changes by more than 0.01=0.1\sqrt{0.01} = 0.1, whether “the answer is toxic” or “the action is to jump.” This is used in policy trust-region methods (TRPO bounds KL between new and old policies and Pinsker converts that to a TV bound used in its improvement guarantee) and in RLHF’s KL penalty.

The figure also shows what Pinsker does not say. The bound is one-way: there is no upper bound on KL in terms of TV, because qq only needs to assign probability 0 where pp assigns a little for KL to be infinite with arbitrarily small TV. And when TV approaches 1, 2 TV2≤22\,\mathrm{TV}^2 \le 2 falls short while KL may be enormous. A better bound exists in that regime.

Proof

All follow from Jensen. H2=2(1−BC)≤−2log⁡BCH^2 = 2(1 - \mathrm{BC}) \le -2\log\mathrm{BC} because 1−u≤−log⁡u1 - u \le -\log u. Next, log⁡BC=log⁡EP[q/p]≥EP[log⁡q/p]=−12KL⁡\log\mathrm{BC} = \log\E_P\big[\sqrt{q/p}\big] \ge \E_P\big[\log\sqrt{q/p}\big] = -\tfrac12\KL. By concavity of the logarithm, KL⁡=EP[log⁡(p/q)]≤log⁡EP[p/q]=log⁡∑p2/q=log⁡(1+χ2)\KL = \E_P[\log(p/q)] \le \log\E_P[p/q] = \log\sum p^2/q = \log(1 + \chi^2), and log⁡(1+u)≤u\log(1 + u) \le u. For Bretagnolle–Huber, Cauchy–Schwarz gives BC2=(∑min⁡(p,q)max⁡(p,q))2≤∑min⁡(p,q)∑max⁡(p,q)=(1−TV)(1+TV)\mathrm{BC}^2 = \big(\sum\sqrt{\min(p, q)\max(p, q)}\big)^2 \le \sum\min(p, q)\sum\max(p, q) = (1 - \mathrm{TV})(1 + \mathrm{TV}), and with BC2≥e−KL⁡\mathrm{BC}^2 \ge e^{-\KL} we obtain 1−TV2≥e−KL⁡1 - \mathrm{TV}^2 \ge e^{-\KL}.

∎

Bretagnolle–Huber, written as KL⁡≥−log⁡(1−TV2)\KL \ge -\log(1 - \mathrm{TV}^2), is worse than Pinsker for small TV (growing as TV2\mathrm{TV}^2 rather than 2 TV22\,\mathrm{TV}^2) but tends to infinity as TV→1\mathrm{TV} \to 1. The two curves cross at TV≈0.893\mathrm{TV} \approx 0.893, where KL⁡≈1.59\KL \approx 1.59 nats. Comparison KL⁡≤log⁡(1+χ2)\KL \le \log(1 + \chi^2) also explains the zoo figure: χ2\chi^2 explodes exponentially while KL grows only quadratically.

Variational representations: a divergence is the best discriminator

All previous formulas require densities pp and qq. In learning we rarely have them: we have samples from data and samples (or a simulator) from the model. The solution is to rewrite each divergence as the maximum of an optimization problem over functions T:X→RT: \mathcal{X} \to \R, whose objective contains only expectations, estimable by sample means.

Fenchel representation

Recall the convex conjugate f∗(u)=sup⁡t (ut−f(t))f^*(u) = \sup_t\,\big(ut - f(t)\big). For convex lower-semicontinuous ff, f=f∗∗f = f^{**}, that is, f(t)=sup⁡u (ut−f∗(u))f(t) = \sup_u\,\big(ut - f^*(u)\big): every convex function is the upper envelope of its tangent lines.

Proof

By Fenchel–Young, f(t)≥ut−f∗(u)f(t) \ge ut - f^*(u) for every tt and uu. Apply it at each xx with t=p(x)/q(x)t = p(x)/q(x) and u=T(x)u = T(x), multiply by q(x)≥0q(x) \ge 0 and sum: Df(P ∥ Q)≥∑xp(x)T(x)−∑xq(x)f∗(T(x))D_f(P\,\|\,Q) \ge \sum_x p(x)T(x) - \sum_x q(x)f^*(T(x)). Equality in Fenchel–Young holds when uu is a subgradient of ff at tt, so T∗(x)=f′(p(x)/q(x))T^*(x) = f'(p(x)/q(x)) turns the inequality into equality at every xx.

∎

This variational representation of divergence has a transformative interpretation: divergence is the value of the best critic. TT tries to take high values where PP lies and values with low f∗f^* where QQ lies; the better it separates them, the larger the bound; and the optimal critic is a function of the likelihood ratio, like the optimal GAN discriminator. For KL, f∗(u)=eu−1f^*(u) = e^{u - 1} and the bound is that of Nguyen, Wainwright, and Jordan (NWJ, 2010):

KL⁡(P ∥ Q)≥EP[T]−EQ[eT−1],T∗=1+log⁡pq.\KL(P\,\|\,Q) \ge \E_P[T] - \E_Q\big[e^{T - 1}\big], \qquad T^* = 1 + \log\frac{p}{q}.
Divergencef∗(u)f^*(u)Domain of f∗f^*Optimal critic T∗T^*
KLeu−1e^{u - 1}R\R1+log⁡(p/q)1 + \log(p/q)
Reverse KL−1−log⁡(−u)-1 - \log(-u)u<0u < 0−q/p-q/p
χ2\chi^2u+u2/4u + u^2/4 (and −1-1 if u<−2u < -2)R\R2(p/q−1)2(p/q - 1)
Hellinger²u/(1−u)u/(1 - u)u<1u < 11−q/p1 - \sqrt{q/p}
Total variationuu∣u∣≤12\abs{u} \le \tfrac1212sign⁡(p−q)\tfrac12\operatorname{sign}(p - q)
GAN: f=tlog⁡t−(1+t)log⁡(1+t)f = t\log t - (1 + t)\log(1 + t)−log⁡(1−eu)-\log(1 - e^u)u<0u < 0log⁡pp+q\log\frac{p}{p + q}

The last row closes the circle. The GAN generator is convex but does not satisfy f(1)=0f(1) = 0 (it equals f(1)=−log⁡4f(1) = -\log 4), so ∑q f(p/q)\sum q\,f(p/q) does not vanish at P=QP = Q but equals that constant: Df(P ∥ Q)=2 JS(P ∥ Q)−log⁡4D_f(P\,\|\,Q) = 2\,\mathrm{JS}(P\,\|\,Q) - \log 4, and if the critic is written T=log⁡DT = \log D with D∈(0,1)D \in (0, 1), the Fenchel objective is EP[log⁡D]−EQ[−log⁡(1−D)]=V(D,θ)\E_P[\log D] - \E_Q[-\log(1 - D)] = V(D, \theta): the original GAN is the variational representation of an f-divergence. Nowozin, Cseke, and Tomioka (2016) generalized the recipe as f-GANs (f-GAN): choose a generator ff, parameterize the critic as Tω(x)=gf(Vω(x))T_\omega(x) = g_f(V_\omega(x)) with network VωV_\omega and output activation gfg_f respecting the domain of f∗f^*, and solve min⁡θmax⁡ω EP[Tω]−EQθ[f∗(Tω)]\min_\theta\max_\omega\ \E_P[T_\omega] - \E_{Q_\theta}[f^*(T_\omega)]. Each choice of ff gives a different GAN, and all inherit point (4): with disjoint supports, they all saturate.

Donsker–Varadhan representation

For KL there is a different, tighter representation.

Proof

Given TT, define the tilted distribution QTQ_T with qT(x)=q(x)eT(x)/EQ[eT]q_T(x) = q(x)e^{T(x)}/\E_Q[e^T]. Then log⁡pqT=log⁡pq−T+log⁡EQ[eT]\log\frac{p}{q_T} = \log\frac{p}{q} - T + \log\E_Q[e^T], and taking expectation under PP,

0≤KL⁡(P ∥ QT)=KL⁡(P ∥ Q)−(EP[T]−log⁡EQ[eT]).0 \le \KL(P\,\|\,Q_T) = \KL(P\,\|\,Q) - \Big(\E_P[T] - \log\E_Q[e^T]\Big).

Equality holds if and only if QT=PQ_T = P, that is, eT∝p/qe^T \propto p/q.

∎

Why is it tighter? Because log⁡x≤x/e\log x \le x/e for every x>0x > 0 (with equality at x=ex = e), so for the same TT, log⁡EQ[eT]≤EQ[eT−1]\log\E_Q[e^T] \le \E_Q[e^{T - 1}], and

EP[T]−log⁡EQ[eT]⏟DV(T) ≥ EP[T]−EQ[eT−1]⏟NWJ(T).\underbrace{\E_P[T] - \log\E_Q[e^T]}_{\text{DV}(T)} \ \ge\ \underbrace{\E_P[T] - \E_Q[e^{T - 1}]}_{\text{NWJ}(T)}.

Moreover, if you optimize NWJ only over the constant, sup⁡cNWJ(T+c)\sup_c \text{NWJ}(T + c), derivative 1−ec−1EQ[eT]1 - e^{c - 1}\E_Q[e^T] vanishes at c=1−log⁡EQ[eT]c = 1 - \log\E_Q[e^T] and the value is exactly DV(T)\text{DV}(T). DV is NWJ with the constant chosen optimally. Two practical consequences: if the critic class admits adding constants (a network with output bias), the suprema coincide; and DV is invariant to that constant, while NWJ must learn it. The difference is in estimation: NWJ is linear in EQ[eT−1]\E_Q[e^{T - 1}], so a minibatch mean is an unbiased estimator of the bound for fixed TT; DV contains the logarithm of a mean, and E[log⁡μ^]≤log⁡μ\E[\log\hat\mu] \le \log\mu by Jensen, so its estimator is biased upward, as are its minibatch gradients. MINE (Belghazi et al., 2018), the neural mutual-information estimator based on DV, corrects that bias with a moving average of the denominator.

InteractiveA divergence is the best discriminator
Densities and samples of PP (blue, above) and QQ (gray, below)
Learned critics versus optimal log⁡(p/q)\log(p/q)
  • log⁡(p/q)\log(p/q)
  • TNWJ−1T_{\text{NWJ}} - 1
  • TDV−log⁡E^QeTT_{\text{DV}} - \log\hat{\E}_Q e^{T}
KL estimate during training
  • True KL
  • NWJ (samples)
  • DV (samples)
Repetitions (select “Repeat 20 times”)
0.631.131.63KLNWJDV
Filled: sample value. Hollow: exact bound value for the learned critic. Values outside the scale (including −∞) are drawn at the edge.
1.5
1.00
Samples per distribution
Critic family
True KL (nats)1.125
Iteration0
NWJ on samples−0.368
DV on samples0.000
Exact critic NWJ−0.368
Exact critic DV0.000
Select “Train”. Both critics start at T=0T = 0: the DV bound is 0 and NWJ is −1/e-1/e.
We see only nn samples from P=N(μ,σ2)P = \mathcal{N}(\mu, \sigma^2) and Q=N(0,1)Q = \mathcal{N}(0, 1). Two critics from the same family use gradient ascent (Adam) on the NWJ bound (orange) and Donsker–Varadhan bound (purple); the right plot compares them with true KL, and the left compares learned critics with the optimum log⁡(p/q)\log(p/q). ‘Repeat 20 times’ fits to the maximum with 20 new sample sets. With a linear family and σ=1\sigma = 1 the optimum is in the family; with σ≠1\sigma \neq 1 it is not (try quadratic). Reduce to n=50n = 50 with 10 radial basis functions: estimates exceed KL, but exact bound values for those critics (hollow) do not. Raise μ\mu to 3: what happens to dispersion?

The figure shows four facts that determine whether a variational estimator is useful. With a family containing the optimum and many samples, both bounds reach KL; DV is often ahead in early iterations because it starts at 0 instead of −1/e-1/e and need not learn the constant. With an overly poor family (linear with σ≠1\sigma \neq 1), both stay below: the bound is valid but loose. With a very flexible family and few samples, the critic memorizes samples and the estimate exceeds KL: it is no longer a bound, because the bound holds for fixed TT and here TT was selected using the same data on which it is evaluated. Dispersion across repetitions grows very quickly with KL: term EQ[eT]\E_Q[e^T] is dominated by rare samples of QQ where p/qp/q is enormous. This is not specific to these estimators: McAllester and Stratos (2020) proved that no high-confidence lower bound built from NN samples, without further distributional assumptions, can exceed a value of order log⁡N\log N. Estimating large divergences or mutual information from samples is intrinsically difficult; see variational mutual-information bounds.

Beyond: Rényi and optimal transport

Two neighboring families complete the map. The Rényi divergence of order α∈(0,1)∪(1,∞)\alpha \in (0, 1) \cup (1, \infty),

Dα(P ∥ Q)=1α−1log⁡∑xp(x)αq(x)1−α,D_\alpha(P\,\|\,Q) = \frac{1}{\alpha - 1}\log\sum_x p(x)^\alpha q(x)^{1 - \alpha},

is not an f-divergence, but is an increasing function of one: ∑pαq1−α=∑q (p/q)α\sum p^\alpha q^{1 - \alpha} = \sum q\,(p/q)^\alpha equals 1+Df1 + D_f with convex generator f(t)=tα−1f(t) = t^\alpha - 1 if α>1\alpha > 1, and 1−Df1 - D_f with f(t)=1−tαf(t) = 1 - t^\alpha if α<1\alpha < 1; in both cases prefactor 1α−1\frac{1}{\alpha - 1} makes DαD_\alpha increase with DfD_f. It therefore inherits data processing. It interpolates between familiar cases: D1/2=−2log⁡BCD_{1/2} = -2\log\mathrm{BC}, Dα→KL⁡D_\alpha \to \KL as α→1\alpha \to 1, and D2=log⁡(1+χ2)D_2 = \log(1 + \chi^2); the comparison chain above is monotonicity of DαD_\alpha in α\alpha. It appears in differential privacy (Rényi accounting) and variational inference.

Optimal transport distances WpW_p measure the cost of moving mass from PP to QQ when moving one unit from xx to yy costs d(x,y)pd(x, y)^p. Unlike f-divergences, they depend on the geometry of space, are finite between disjoint supports, and grow with their separation; in return, they have no closed-form expression in terms of p/qp/q, are costlier to compute, and their sample estimation worsens with dimension. Neither family is better: each answers a different question (how much are they confused versus how far must mass move?).

Implementation from scratch

First, a function computes any discrete f-divergence from its generator, with both zero conventions. We check it against the table, symmetry under swapping arguments, and saturation on disjoint supports.

[ ]f-divergences from their generatorBrowser
import numpy as np

def f_divergencia(p, q, f, f_inf):
    """D_f(p||q) = sum_x q f(p/q), con 0 f(0/0) = 0 y, si q = 0 < p, el término p * f'(inf)."""
    p, q = np.asarray(p, float), np.asarray(q, float)
    total = 0.0
    for pi, qi in zip(p, q):
        if qi > 0:
            total += qi * f(pi / qi)
        elif pi > 0:
            total += pi * f_inf              # f_inf = lim f(t)/t cuando t -> inf
    return total

def xlogx(t):
    return t * np.log(t) if t > 0 else 0.0

# nombre: (generador, f'(inf))
GEN = {
    "KL":         (xlogx, np.inf),
    "KL inversa": (lambda t: -np.log(t) if t > 0 else np.inf, 0.0),
    "TV":         (lambda t: 0.5 * abs(t - 1), 0.5),
    "Hellinger²": (lambda t: (np.sqrt(t) - 1) ** 2, 1.0),
    "χ²":         (lambda t: (t - 1) ** 2, np.inf),
    "JS":         (lambda t: 0.5 * (xlogx(t) - (1 + t) * np.log((1 + t) / 2)), np.log(2) / 2),
}

p = np.array([0.6, 0.3, 0.1])
q = np.array([0.2, 0.3, 0.5])
print(f"{'':11s} {'D(p||q)':>9s} {'D(q||p)':>9s}")
for nombre, (f, f_inf) in GEN.items():
    print(f"{nombre:11s} {f_divergencia(p, q, f, f_inf):9.4f} {f_divergencia(q, p, f, f_inf):9.4f}")

def H(r):
    r = r[r > 0]
    return -np.sum(r * np.log(r))
m = (p + q) / 2
print("\nJS como hueco de Jensen de la entropía:", round(H(m) - (H(p) + H(q)) / 2, 6))

# soportes disjuntos: toda divergencia f vale f(0) + f'(inf)
a = np.array([0.5, 0.5, 0.0, 0.0])
b = np.array([0.0, 0.0, 0.3, 0.7])
for nombre, (f, f_inf) in GEN.items():
    print(f"disjuntas, {nombre:11s}: {f_divergencia(a, b, f, f_inf):.4f}   f(0) + f'(inf) = {f(0.0) + f_inf:.4f}")

KL and χ2\chi^2 change on swapping pp and qq; TV, Hellinger, and JSD do not. On disjoint supports each divergence takes exactly its maximum f(0)+f′(∞)f(0) + f'(\infty): 11, 22, and log⁡2≈0.6931\log 2 \approx 0.6931 for the bounded ones, ∞\infty for the others.

Now test the lesson’s general claims on many random pairs: data processing with random channels for all six divergences, Pinsker, Bretagnolle–Huber, JSD bounds in terms of TV, and the triangle inequality for JS\sqrt{\mathrm{JS}} (and its failure without the square root).

[ ]Data processing and relationships between divergencesBrowser
import numpy as np

rng = np.random.default_rng(0)

def divs(p, q):
    """Las seis divergencias, vectorizadas por filas (p, q de forma (N, k), sin ceros)."""
    m = (p + q) / 2
    kl = np.sum(p * np.log(p / q), axis=1)
    return {
        "KL": kl,
        "KL inversa": np.sum(q * np.log(q / p), axis=1),
        "TV": 0.5 * np.abs(p - q).sum(axis=1),
        "Hellinger²": np.sum((np.sqrt(p) - np.sqrt(q)) ** 2, axis=1),
        "χ²": np.sum((p - q) ** 2 / q, axis=1),
        "JS": 0.5 * np.sum(p * np.log(p / m), axis=1) + 0.5 * np.sum(q * np.log(q / m), axis=1),
    }

N, k, k_sal = 20000, 5, 3
p = rng.dirichlet(np.ones(k), N)
q = rng.dirichlet(np.ones(k), N)
K = rng.dirichlet(np.ones(k_sal), (N, k))          # un canal aleatorio k -> k_sal por par
pK = np.einsum("nx,nxy->ny", p, K)
qK = np.einsum("nx,nxy->ny", q, K)
antes, despues = divs(p, q), divs(pK, qK)
print("Procesamiento de datos: máximo de D(PK||QK) / D(P||Q) en", N, "pares")
for nombre in antes:
    print(f"   {nombre:11s} {np.max(despues[nombre] / antes[nombre]):.4f}")

d = divs(p, q)
tv, kl, js = d["TV"], d["KL"], d["JS"]
print("\nPinsker, mín KL / (2 TV²):              ", round(np.min(kl / (2 * tv**2)), 4))
print("Bretagnolle-Huber, máx TV / sqrt(1-e^-KL):", round(np.max(tv / np.sqrt(1 - np.exp(-kl))), 4))
print("JS >= TV²/2, mín JS / (TV²/2):           ", round(np.min(js / (tv**2 / 2)), 4))
print("JS <= TV log 2, máx JS / (TV log 2):     ", round(np.max(js / (tv * np.log(2))), 4))
H2, c2 = d["Hellinger²"], d["χ²"]
print("cadena H² <= KL <= log(1+χ²) <= χ²:      ", bool(np.all(H2 <= kl) and np.all(kl <= np.log1p(c2)) and np.all(np.log1p(c2) <= c2)))

# desigualdad triangular con tríos de distribuciones de 3 resultados
a, b, c = (rng.dirichlet(0.5 * np.ones(3), N) + 1e-12 for _ in range(3))
js_ab, js_bc, js_ac = divs(a, b)["JS"], divs(b, c)["JS"], divs(a, c)["JS"]
print("\nsqrt(JS): máx de d(a,c) - d(a,b) - d(b,c) =", round(np.max(np.sqrt(js_ac) - np.sqrt(js_ab) - np.sqrt(js_bc)), 6))
print("JS sin raíz: máx de JS(a,c) - JS(a,b) - JS(b,c) =", round(np.max(js_ac - js_ab - js_bc), 4))

No data-processing ratio exceeds 1 and all inequalities hold. The extremes are informative: the minimum Pinsker ratio is very close to 1 (the constant 2 cannot be improved), as is JSD against TV2/2\mathrm{TV}^2/2. The square root of JSD never violates the triangle inequality; JSD without the root violates it substantially.

Finally, variational bounds from samples. With P=N(μ,1)P = \mathcal{N}(\mu, 1) and Q=N(0,1)Q = \mathcal{N}(0, 1), ratio log⁡(p/q)=μx−μ2/2\log(p/q) = \mu x - \mu^2/2 is linear in xx, so a linear critic T(x)=θ0+θ1xT(x) = \theta_0 + \theta_1 x contains the optimum and what we measure is estimation error, not approximation error. Both empirical bounds are concave in θ\theta, and we maximize them with scipy.optimize.minimize using analytic gradient and Hessian (with BFGS and no Hessian, exponentials overflow as soon as line search tries a long step).

[ ]NWJ and Donsker–Varadhan bounds from samplesBrowser
import numpy as np
from scipy.optimize import minimize
from scipy.special import logsumexp, softmax

def rasgos(x):
    return np.stack([np.ones_like(x), x], axis=1)        # crítico lineal T(x) = th0 + th1 x

def nwj(th, Fp, Fq):
    """Valor, gradiente y hessiana de la cota NWJ empírica (cóncava en th)."""
    e = np.exp(Fq @ th - 1) / len(Fq)
    return Fp.mean(0) @ th - e.sum(), Fp.mean(0) - Fq.T @ e, -(Fq.T * e) @ Fq

def dv(th, Fp, Fq):
    """Lo mismo para Donsker-Varadhan, con log-sum-exp para no desbordar."""
    s = Fq @ th
    w = softmax(s)
    g = Fq.T @ w
    return Fp.mean(0) @ th - (logsumexp(s) - np.log(len(s))), Fp.mean(0) - g, -((Fq.T * w) @ Fq - np.outer(g, g))

def maximizar(cota, Fp, Fq):
    res = minimize(lambda th: -cota(th, Fp, Fq)[0], np.zeros(2), jac=lambda th: -cota(th, Fp, Fq)[1],
                   hess=lambda th: -cota(th, Fp, Fq)[2], method="trust-exact")
    return -res.fun

rng = np.random.default_rng(1)
n, reps = 1000, 25
print(f"n = {n} muestras de cada distribución, {reps} repeticiones")
print(" mu  | KL verdadera | NWJ: media (desv.) | DV: media (desv.) | máx |NWJ - DV|")
for mu in [1.0, 2.0, 2.5]:
    kl_verdad = mu**2 / 2
    est_n, est_d = [], []
    for _ in range(reps):
        Fp, Fq = rasgos(rng.normal(mu, 1, n)), rasgos(rng.normal(0, 1, n))
        est_n.append(maximizar(nwj, Fp, Fq))
        est_d.append(maximizar(dv, Fp, Fq))
    est_n, est_d = np.array(est_n), np.array(est_d)
    print(f" {mu:.1f} | {kl_verdad:12.3f} | {est_n.mean():8.3f} ({est_n.std():.3f})  | {est_d.mean():7.3f} ({est_d.std():.3f})  | {np.max(np.abs(est_n - est_d)):.1e}")

# El sesgo del logaritmo de una media: crítico ÓPTIMO fijo, estimaciones en minilotes de tamaño B
mu = 1.5
kl_verdad, chi2 = mu**2 / 2, np.exp(mu**2) - 1
print(f"\nCrítico óptimo fijo, mu = {mu}: KL = {kl_verdad:.4f}, chi² = {chi2:.2f}")
for B in [16, 64, 256]:
    xp = rng.normal(mu, 1, (4000, B))
    xq = rng.normal(0, 1, (4000, B))
    T_p, T_q = mu * xp - mu**2 / 2, mu * xq - mu**2 / 2          # T* = log(p/q)
    dv_mb = T_p.mean(1) - np.log(np.exp(T_q).mean(1))
    nwj_mb = (T_p + 1).mean(1) - np.exp(T_q).mean(1)                # T* de NWJ = 1 + log(p/q)
    print(f"B = {B:3d}: sesgo DV = {dv_mb.mean() - kl_verdad:+.4f} (predicción chi²/2B = {chi2 / (2 * B):.4f}),"
          f" sesgo NWJ = {nwj_mb.mean() - kl_verdad:+.4f}, desv. DV = {dv_mb.std():.3f}, NWJ = {nwj_mb.std():.3f}")

Three results. The NWJ and DV maxima agree to optimizer precision because the linear critic has a constant term and DV is NWJ with the optimal constant. Standard deviation grows rapidly with KL (from 0.050.05 at KL 0.50.5 to 0.320.32 at KL 3.13.1), and the mean begins to overshoot (3.343.34 versus 3.1253.125). There is a concrete reason: for large θ1\theta_1, log⁡E^Q[eθ1x]≈θ1max⁡ixiQ−log⁡n\log\hat\E_Q[e^{\theta_1 x}] \approx \theta_1\max_i x^Q_i - \log n, so if no sample from QQ exceeds the mean of samples from PP, the empirical maximum is infinite. With μ=3\mu = 3 and n=500n = 500 this happens about half the time; that is why the table stops at μ=2.5\mu = 2.5 with n=1000n = 1000. With the optimal critic fixed, minibatch DV estimation is biased upward while NWJ is not. A second-order expansion of −log⁡μ^-\log\hat\mu around μ=1\mu = 1 predicts bias χ2/(2B)\chi^2/(2B), because the variance of eT∗e^{T^*} under QQ is χ2(P ∥ Q)\chi^2(P\,\|\,Q); the prediction works well for B=256B = 256 and exaggerates with small minibatches, where heavy tails of eT∗e^{T^*} break the expansion. In return, DV has somewhat less variance than NWJ here: no estimator is free.

A minimal 1D GAN

To see saturation in real training, without networks or automatic differentiation, an affine generator x=az+bx = a z + b with z∼N(0,1)z \sim \mathcal{N}(0, 1) and a logistic discriminator on quadratic features, D(x)=σ(w0+w1x+w2x2)D(x) = \sigmoid(w_0 + w_1 x + w_2 x^2), suffice; it can represent the optimal discriminator between two Gaussians. Data are N(2,0.52)\mathcal{N}(2, 0.5^2). The two generator losses differ only in their derivative with respect to xx: with s(x)s(x) the logit and s′(x)=w1+2w2xs'(x) = w_1 + 2w_2 x,

∂∂xlog⁡(1−D(x))=−D(x) s′(x),∂∂x(−log⁡D(x))=−(1−D(x)) s′(x).\frac{\partial}{\partial x}\log\big(1 - D(x)\big) = -D(x)\,s'(x), \qquad \frac{\partial}{\partial x}\big(-\log D(x)\big) = -\big(1 - D(x)\big)\,s'(x).

When the discriminator confidently rejects a fake sample, D(x)≈0D(x) \approx 0: the first derivative vanishes and the second does not. First measure the generator gradient with the discriminator fitted to optimum (logistic regression by Newton’s method) at different separations; then actually train both versions from far away.

[ ]Minimal GAN: saturating versus non-saturating lossBrowser
import numpy as np

def sigmoide(s):
    return 0.5 * (1 + np.tanh(0.5 * s))

def phi(x):
    return np.stack([np.ones_like(x), x, x * x], axis=1)

MU_P, SD_P = 2.0, 0.5

def discriminador_optimo(xr, xf, iters=25, lam=1e-3):
    """Regresión logística (reales = 1, falsos = 0) por Newton: el mejor D de la familia."""
    X = np.vstack([phi(xr), phi(xf)])
    y = np.r_[np.ones(len(xr)), np.zeros(len(xf))]
    w = np.zeros(3)
    for _ in range(iters):
        d = sigmoide(X @ w)
        g = X.T @ (y - d) / len(y) - lam * w
        H = (X * (d * (1 - d))[:, None]).T @ X / len(y) + lam * np.eye(3)
        w = w + np.linalg.solve(H, g)
    return w

def grad_generador(w, a, b, z, perdida):
    x = a * z + b
    d = sigmoide(phi(x) @ w)
    ds = w[1] + 2 * w[2] * x
    gx = -d * ds if perdida == "saturante" else -(1 - d) * ds
    return np.array([np.mean(gx * z), np.mean(gx)])          # (dL/da, dL/db)

rng = np.random.default_rng(0)
xr, z = rng.normal(MU_P, SD_P, 4000), rng.normal(size=4000)
print("  b  | JSD estimada (nats) | |grad| saturante | |grad| no saturante")
for b in [1.0, 0.0, -1.0, -2.0, -3.0]:
    xf = SD_P * z + b
    w = discriminador_optimo(xr, xf)
    V = np.mean(np.log(sigmoide(phi(xr) @ w))) + np.mean(np.log(1 - sigmoide(phi(xf) @ w)))
    js = (V + np.log(4)) / 2                                    # V(D*, G) = 2 JS - log 4
    gs = np.linalg.norm(grad_generador(w, SD_P, b, z, "saturante"))
    gn = np.linalg.norm(grad_generador(w, SD_P, b, z, "no saturante"))
    print(f" {b:4.1f} | {js:19.4f} | {gs:16.2e} | {gn:.2e}")

def entrenar(perdida, pasos=1200, lote=128, k=3, lr_d=0.1, lr_g=0.05, seed=1):
    r = np.random.default_rng(seed)
    a, b, w = 0.5, -3.0, np.zeros(3)
    normas, llegada = [], None
    for t in range(pasos):
        for _ in range(k):                                      # k pasos del discriminador
            xr_, xf_ = r.normal(MU_P, SD_P, lote), a * r.normal(size=lote) + b
            dr, df = sigmoide(phi(xr_) @ w), sigmoide(phi(xf_) @ w)
            w += lr_d * (phi(xr_).T @ (1 - dr) - phi(xf_).T @ df) / lote
        g = grad_generador(w, a, b, r.normal(size=lote), perdida)
        a, b = a - lr_g * g[0], b - lr_g * g[1]
        normas.append(np.linalg.norm(g))
        if llegada is None and abs(b - MU_P) < 0.25:
            llegada = t
    return a, b, np.median(normas[:200]), llegada

print("\nEntrenamiento desde b = -3 (los datos están en 2):")
for perdida in ["saturante", "no saturante"]:
    a, b, med, llegada = entrenar(perdida)
    print(f"  {perdida:13s} mediana de |grad| en los 200 primeros pasos = {med:.1e};"
          f" llega a |b - 2| < 0.25 en el paso {llegada}; final a = {a:.2f}, b = {b:.2f}")

With the optimal discriminator, estimated JSD approaches log⁡2≈0.693\log 2 \approx 0.693 as soon as the Gaussians separate, and the saturating loss gradient falls with separation while the non-saturating one remains of order 1. At b=−3b = -3 the saturating gradient is about 570 times smaller. In real training the discriminator is not optimal (it gets only three gradient steps per generator step), leaving some gradient: the saturating version eventually arrives, but at step 1061, after hundreds of almost stalled steps with gradients of order 10−210^{-2}; the non-saturating version arrives at step 64. Notice the final value of aa: the saturating run ends with a≈0a \approx 0 (0.002), a generator producing almost always the same point near the data mean. This is miniature mode collapse: a=0a = 0 is a fixed point, because with constant x=bx = b and symmetric zz the gradient with respect to aa is E[g(x) z]=g(b) E[z]=0\E[g(x)\,z] = g(b)\,\E[z] = 0, and the generator cannot escape. The non-saturating version ends with a=0.61a = 0.61, near 0.50.5 for the data, but there is no guarantee: another seed or step count can also collapse.

The library version

SciPy provides the pieces, with conventions worth knowing:

FunctionWhat it computesWatch out for
scipy.special.rel_entr(p, q)plog⁡(p/q)p\log(p/q) elementwisesum yourself; handles p=0p = 0 and q=0q = 0
scipy.special.kl_div(p, q)plog⁡(p/q)−p+qp\log(p/q) - p + qnonnegative generator tlog⁡t−t+1t\log t - t + 1; sum equals KL only if ∑p=∑q\sum p = \sum q
scipy.stats.entropy(p, q, base=2)KL⁡(p ∥ q)\KL(p\,\|\,q), normalizing pp and qqnormalizes silently
scipy.spatial.distance.jensenshannon(p, q, base=2)JS\sqrt{\mathrm{JS}}returns the square root; base ee by default
torch.distributions.kl_divergence(P, Q)closed-form KL between parametric distributionsregistered pairs only
torch.nn.functional.kl_div(input, target)KL⁡(target ∥ ⋅)\KL(\text{target}\,\|\,\cdot) with input in logarithmsargument order is reversed relative to notation
[ ]The same quantities with SciPyBrowser
import numpy as np
from scipy.special import rel_entr, kl_div
from scipy.stats import entropy
from scipy.spatial.distance import jensenshannon

p = np.array([0.6, 0.3, 0.1])
q = np.array([0.2, 0.3, 0.5])
print("KL con rel_entr:      ", rel_entr(p, q).sum())
print("KL con kl_div:        ", kl_div(p, q).sum(), "  (elemento a elemento:", np.round(kl_div(p, q), 4), ")")
print("KL con entropy:       ", entropy(p, q))
print("JS (divergencia, nats):", jensenshannon(p, q) ** 2)
print("JS (distancia, bits):  ", jensenshannon(p, q, base=2))

# sin normalizar: kl_div incluye -p + q, rel_entr no; entropy normaliza en silencio
p2, q2 = 2 * p, q
print("\nsin normalizar: rel_entr =", round(rel_entr(p2, q2).sum(), 4), " kl_div =", round(kl_div(p2, q2).sum(), 4),
      " entropy =", round(entropy(p2, q2), 4))

All three paths give the same KL for normalized distributions; kl_div has positive contributions in every term although that of rel_entr in the third is negative, because it uses the shifted generator from the first section. With unnormalized vectors all three differ. In PyTorch, loss F.kl_div(log_q, p, reduction="batchmean") computes KL⁡(p ∥ q)\KL(p\,\|\,q) with log⁡q\log q as the first argument: reversing the order is a classic silent error.

Common mistakes

Exercises

QuizSymmetric and bounded
Which divergences are both symmetric and bounded?

More than one answer may be correct.

NumericA total variation
Calculate the total variation distance between p=(0.5,0.3,0.2)p = (0.5, 0.3, 0.2) and q=(0.2,0.3,0.5)q = (0.2, 0.3, 0.5).
NumericJSD of disjoint supports
Let p=(0.5,0.5,0,0)p = (0.5, 0.5, 0, 0) and q=(0,0,0.3,0.7)q = (0, 0, 0.3, 0.7). What is JS(p ∥ q)\mathrm{JS}(p\,\|\,q) in bits?
NumericHow many coin tosses?
You want to distinguish a fair coin, P=Bern⁡(0.5)P = \Bern(0.5), from one with Q=Bern⁡(0.6)Q = \Bern(0.6) using nn tosses. What is the smallest nn with BC(P,Q)n≤0.1\mathrm{BC}(P, Q)^n \le 0.1? (Then TV between P⊗nP^{\otimes n} and Q⊗nQ^{\otimes n} is at least 0.9 and the best test errs at most 5% of the time.)
NumericFrom KL to probabilities
A fitted model satisfies KL⁡(P ∥ Q)≤0.08\KL(P\,\|\,Q) \le 0.08 nats relative to a reference distribution. According to Pinsker, what is the largest difference ∣P(A)−Q(A)∣\abs{P(A) - Q(A)} possible for any event AA?
QuizDonsker–Varadhan on minibatches
You train a mutual-information estimator by maximizing the Donsker–Varadhan bound with minibatches of size 32 and an already trained fixed critic. Which statement is correct about the mean estimate over many minibatches?
QuizWhich are metrics?
Which of these functions of (P,Q)(P, Q) are metrics on distributions over a finite alphabet?

More than one answer may be correct.

ProofThe Jensen–Shannon generator
Prove: JSD is the f-divergence of generator f(t)=12[tlog⁡t−(1+t)log⁡1+t2]f(t) = \tfrac12\big[t\log t - (1 + t)\log\tfrac{1 + t}{2}\big], which is convex with f(1)=0f(1) = 0.
0
Take P≪QP \ll Q for the calculation and m=(p+q)/2m = (p + q)/2.

Step 1 of 4. What do you check first?

ProofThe GAN objective is a JSD
Prove: With optimal discriminator D∗=p/(p+q)D^* = p/(p + q), V(D∗,θ)=EP[log⁡D∗]+EQ[log⁡(1−D∗)]=2 JS(P ∥ Q)−log⁡4V(D^*, \theta) = \E_P[\log D^*] + \E_Q[\log(1 - D^*)] = 2\,\mathrm{JS}(P\,\|\,Q) - \log 4.
0
Write qq for qθq_\theta and m=(p+q)/2m = (p + q)/2.

Step 1 of 3. How do you rewrite D∗D^* and 1−D∗1 - D^* in terms of mm?

ProofPinsker step by step
Prove: For any PP and QQ, KL⁡(P ∥ Q)≥2 TV(P,Q)2\KL(P\,\|\,Q) \ge 2\,\mathrm{TV}(P, Q)^2 (in nats).
0
Let A∗={x:p(x)>q(x)}A^* = \{x : p(x) > q(x)\}, a=P(A∗)a = P(A^*), and b=Q(A∗)b = Q(A^*).

Step 1 of 3. How do you reduce the problem to two coins?

CodeAn f-divergence robust to zeros
Implement div_f(p, q, nombre) for nombre in 'kl', 'tv', 'hellinger2', 'chi2', and 'js', vectorized with NumPy and using the lesson's conventions: xx with p=q=0p = q = 0 do not count, those with q=0<pq = 0 < p contribute p f′(∞)p\,f'(\infty) (which may be np.inf), and those with p=0<qp = 0 < q contribute q f(0)q\,f(0). Return a float in nats. Do not use Python loops over elements or SciPy.
import numpy as np

def div_f(p, q, nombre):
  """Divergencia f discreta D_f(p||q) en nats, con los convenios para los ceros."""
  p, q = np.asarray(p, float), np.asarray(q, float)
  # tu código: separa los casos q > 0, q = 0 < p y p = q = 0
  return 0.0
Shift+Enter to run

Summary

Key idea
An f-divergence is the mean under QQ of a convex function of the likelihood ratio, and convexity also makes it the value of the best critic: measuring how different two distributions are is equivalent to training their best discriminator, and what that discriminator cannot see (the distance between disjoint supports) neither can the divergence.
  • Df(P ∥ Q)=∑q f(p/q)D_f(P\,\|\,Q) = \sum q\,f(p/q) with convex ff and f(1)=0f(1) = 0 includes KL (tlog⁡tt\log t), reverse KL (−log⁡t-\log t), TV (12∣t−1∣\tfrac12\abs{t - 1}), Hellinger ((t−1)2(\sqrt t - 1)^2), χ2\chi^2 ((t−1)2(t - 1)^2), and JSD. All are nonnegative, jointly convex, decrease under data processing, and attain maximum f(0)+f′(∞)f(0) + f'(\infty) on disjoint supports. Near P=QP = Q, Df≈f′′(1)2χ2D_f \approx \tfrac{f''(1)}{2}\chi^2.
  • TV gives the best test error: min⁡P(error)=12(1−TV)\min\Pr(\text{error}) = \tfrac12(1 - \mathrm{TV}). Hellinger tensorizes (BCn\mathrm{BC}^n) and establishes that distinguishing two distributions costs on the order of 1/H21/H^2 samples.
  • JSD is mutual information between a mixture sample and its label: symmetric, bounded by log⁡2\log 2 (1 bit), with JS\sqrt{\mathrm{JS}} a metric. With optimal discriminator, the GAN objective is 2 JS−log⁡42\,\mathrm{JS} - \log 4, so it saturates when supports do not overlap; Wasserstein does not, because it uses spatial geometry.
  • Pinsker, TV≤KL⁡/2\mathrm{TV} \le \sqrt{\KL/2}, converts KL bounds into bounds on event probabilities; it follows by reducing to the binary case via data processing and is tight for nearly fair coins. Bretagnolle–Huber improves it as TV approaches 1.
  • By convex duality, Df=sup⁡TEP[T]−EQ[f∗(T)]D_f = \sup_T \E_P[T] - \E_Q[f^*(T)] (NWJ for KL, f-GAN generally), and for KL, Donsker–Varadhan sup⁡TEP[T]−log⁡EQ[eT]\sup_T \E_P[T] - \log\E_Q[e^T] is tighter for each TT and equal after optimizing a constant. Estimating them from samples requires monitoring the critic (underestimation if too weak, overfitting if flexible), minibatch logarithm bias, and variance growing exponentially with divergence.