25.3 f-Divergences
Throughout this book, whenever we fit a model by maximum likelihood, we measure how well it matches the data with a single number: the KL divergence. As we saw at the end of Section 25.1, however, KL divergence has a glaring blind spot: it jumps to infinity the moment a model assigns zero probability to an event that actually occurs. A classifier rarely runs into this problem, because a softmax layer never outputs an exact zero. A generative network that maps a low-dimensional noise vector into image space runs into it immediately, because its samples lie on a thin surface in image space that can miss the real data altogether. How else can we compare two distributions, and which comparisons can still distinguish a model that is nearly right from one that is far off?
The simplest possible example already reveals what can go wrong. Suppose the data sit at a single point, , while the model places all its mass at a single point a distance away, . Intuitively, a model at is nearly right and one at is far off, so a useful loss should tell them apart. Table 25.3.1 shows what five standard comparisons report.
| comparison | |||
|---|---|---|---|
| KL divergence | |||
| Jensen--Shannon divergence | |||
| total variation distance | |||
| maximum mean discrepancy | |||
| Wasserstein distance |
Look closely at the table: three of the five rows do not budge as varies. A model trained with any of those three receives the same loss at as at , and therefore zero gradient with respect to . The original generative adversarial network (GAN) of Chapter 16 sat in this predicament, since its objective reduces to the Jensen--Shannon row up to constants.
Those three frozen rows belong to a single family. KL divergence compares and through the ratio of their densities. If we keep that density ratio and vary the convex function applied to it, we obtain a broad family called the f-divergences. All of its members share one proof of non-negativity, one method for estimation from samples, and one structural reason for being blind to the distance . The remaining two rows, which do move with , avoid the density ratio altogether; we will study them in Section 25.4.
Once the family is in place, we will address three questions that recur throughout deep learning. First, does it matter which distribution comes first in KL, the data as in maximum likelihood or the model as in variational inference (Section 25.3.2)? Second, what does a small divergence actually guarantee to someone trying to tell from (Section 25.3.3)? Third, what can we still compute when both distributions are known only through samples (Section 25.3.4)? Section 25.2 ended on that last question, and adversarial training rests on its answer.
Throughout this section, all logarithms are natural, so KL and Jensen--Shannon divergences are measured in nats. We write for the data or target distribution and for the model, and for their probability mass functions or densities, and for their density ratio.
from scipy import integrate, optimize
We can check every entry of Table 25.3.1 directly in code. The next cell represents and as the probability vectors and on the two-point support and evaluates each comparison from its definition. Three of these definitions follow in this section and the other two in the next.
def kl_div(p, q):
"""D_KL(P||Q) on a finite support: 0 log 0 = 0, and inf if q = 0 < p."""
s = p > 0
with np.errstate(divide='ignore'):
return np.sum(p[s] * np.log(p[s] / q[s]))
def five_comparisons(atoms, p, q, ell=1.0):
"""KL, JS, TV, RBF MMD^2 and W1 between pmfs p, q on sorted atoms."""
m = (p + q) / 2 # the mixture for JS
K = np.exp(-(atoms[:, None] - atoms[None, :]) ** 2 / (2 * ell ** 2))
F_gap = np.abs(np.cumsum(p) - np.cumsum(q))[:-1] # |F_P - F_Q| between atoms
return {'KL': kl_div(p, q), 'JS': (kl_div(p, m) + kl_div(q, m)) / 2,
'TV': np.abs(p - q).sum() / 2, 'MMD^2': (p - q) @ K @ (p - q),
'W1': np.sum(F_gap * np.diff(atoms))}
delta_0, delta_d = np.array([1.0, 0.0]), np.array([0.0, 1.0]) # on atoms (0, d)
for d in (0.01, 1.0, 100.0):
vals = five_comparisons(np.array([0.0, d]), delta_0, delta_d)
print(f'd = {d:6}: ' + ' '.join(f'{k} {v:.4g}' for k, v in vals.items()))
d = 0.01: KL inf JS 0.6931 TV 1 MMD^2 0.0001 W1 0.01
d = 1.0: KL inf JS 0.6931 TV 1 MMD^2 0.7869 W1 1
d = 100.0: KL inf JS 0.6931 TV 1 MMD^2 2 W1 100
25.3.1 The f-Divergence Family#
Before generalizing KL divergence, let us pin down the minimum properties that any comparison between two distributions should satisfy. The f-divergence family then emerges naturally when we ask which ingredients the non-negativity proof of KL truly uses.
25.3.1.1 Divergences and Metrics#
At a minimum, a "distance between distributions" should vanish when the two distributions coincide and stay strictly positive when they differ. A divergence is any function of two distributions with this property:
Nothing else is required. A metric, like the Euclidean distance between two vectors (Section 1.3), must additionally be symmetric, , and obey the triangle inequality, . KL divergence is a divergence: Gibbs' inequality (Section 25.1) guarantees that , with equality only when . It fails both metric axioms, however, and a pair of univariate Gaussians shows both failures immediately. As we computed in that section, the KL divergence between two Gaussians is
For and , this formula gives nats in one direction and nats in the other, so KL is not symmetric. The triangle inequality fails for a different reason. Take three unit-variance Gaussians centered at , , and : the formula gives for each adjacent pair, yet for the outer pair, and . Because KL grows like the square of the distance between the means, it behaves like a squared Euclidean distance rather than a true length.
Neither failure needs repair. Minimizing a divergence uses neither symmetry nor the triangle inequality, and the asymmetry of KL turns out to be a genuine modeling choice (Section 25.3.2). Still, whenever a proof needs to chain comparisons from to and from to , the triangle inequality becomes essential. Fortunately, the family we are about to construct includes true metrics as well.
25.3.1.2 The f-Divergence Template#
Gibbs' inequality is what makes KL a valid divergence. Let us inspect its proof closely, because any other function that shares the same two properties will yield a divergence too.
First, rewrite KL as an expectation under of a function of the density ratio :
Viewed this way, KL weights each outcome by and penalizes its density ratio through the function . Let us check this formula on our running example from Section 25.1, the discrete pair and . Here the ratios are , , and , weighted by , , and :
matching the KL divergence we found earlier.
Second, look at the proof of non-negativity. In Section 25.1, we applied Jensen's inequality once to under . Run instead under on the function , that same one-step argument uses only two facts: the function is convex, and it equals zero at . Nothing stops us from replacing by any function with those two properties. Let be convex with , and define , which may be . Assume for now that wherever , written , so that an expectation under sees all of . The f-divergence of with respect to is (Csiszár, 1967)
Point by point, the ratio measures how much over- or
under-represents relative to , and assigns a penalty that vanishes
when . We call the divergence function. Much of the literature
calls it the generator of the divergence, and our code below stores these
functions in a dictionary named generators. In the prose, however, we reserve
the word generator for a network that produces samples, as in
Section 16.2.
To pin down when the divergence equals zero, we need one mild refinement of convexity: we call strictly convex at if some line through lies strictly below everywhere else, meaning for all and some slope .
Proposition (non-negativity). For any convex with and ,
and if is strictly convex at , then if and only if .
Proof. Jensen's inequality (Section 23.3.3.1) states that for any convex and random variable . Apply it to with . Everything rests on a single identity: the density ratio averages to one under , since . Therefore
For the equality case, take the supporting line lying strictly below away from . Then , and the gap is the expectation of , which is strictly positive wherever . Hence forces at every with , meaning .
The identity that powered this proof has a second handy consequence we will use repeatedly: adding any multiple to leaves every divergence unchanged, because . The functions and , for example, define the same KL divergence.
So far we have assumed , yet our opening point-mass example violates that condition. A generative model starts training in the same regime, with its samples and the data occupying disjoint regions, so we must extend to handle zeros in . Outcomes with contribute nothing. Where , the contribution is simply , as the definition already says. Where , the ratio blows up, so we define the contribution as the limit of as . Substituting rewrites this as , whose limit is with . For a convex function , the secant and the derivative share the same limit at infinity, which explains the notation. Either or may be .
Now apply this rule to the point masses and for any . At we have , and at we have , so
Notice that has vanished from the right-hand side. This tells us something far stronger than Table 25.3.1 alone showed: every f-divergence is constant on disjoint supports. It cannot distinguish a near miss from a distant one, so a model trained on it gets zero gradient from the distance separating the supports. For KL, gives and , reproducing the first row of Table 25.3.1. The other two frozen rows follow as soon as we write down their divergence functions.
25.3.1.3 Common Divergence Functions#
Each row of Table 25.3.2 corresponds to one choice of , and Figure 25.3.1 plots six of these curves side by side. The column , recording the curvature at , will play a central role in the next subsection.
| Divergence | Symmetric? | Metric? | ||
|---|---|---|---|---|
| Kullback--Leibler (forward) | no | no | ||
| reverse KL | no | no | ||
| Pearson | no | no | ||
| squared Hellinger | yes | is a metric | ||
| total variation | none (corner) | yes | yes | |
| Jensen--Shannon | yes | is a metric | ||
| -divergence () | only at | square root at |
Six divergence functions, with the smooth curves shifted by so that each touches zero tangentially at without changing its divergence. Near the smooth curves are parabolas with the curvatures listed in the table, while total variation has a sharp corner instead. Away from they penalize disagreement very differently: reverse KL blows up as , KL and grow superlinearly, and total variation grows linearly.
Reverse KL uses , because . Swapping the arguments of KL is therefore just another choice of , so both directions sit side by side in the same table. Exercise 1a gives the general recipe for swapping the arguments of any f-divergence.
Total variation uses , which simplifies to . We write it as . It is half the distance between the probability vectors; on our running pair, . We will unpack what this number means for distinguishing from in Section 25.3.3. On the point masses, its divergence function gives , accounting for the third row of Table 25.3.1.
Pearson's divergence uses the parabola , giving . On the running pair, it evaluates to . Notice how heavily a mismatch is weighted where is small: the first outcome alone, where , contributes of the total.
The Jensen--Shannon divergence (Lin, 1991) symmetrizes KL by comparing both distributions against their even mixture (with mass function ):
Because puts mass wherever either or does, the ratios and can never blow up: , so each KL term is at most . Hence JS is symmetric and bounded, , and it hits its ceiling only when and have disjoint supports (where wherever ). Remarkably, its square root is a true metric (Endres and Schindelin, 2003). Writing (25.3.3) in terms of the ratio yields the divergence function in the table (Exercise 1c), which satisfies . Their sum is , the second row of Table 25.3.1. Our single identity has now explained all three frozen rows.
The squared Hellinger divergence is . Its square root is simply the Euclidean distance between the vectors and , which immediately makes a metric (Exercise 2b).
The final row of the table is a continuous family inside the family, the -divergences (Amari, 2016), generated by
For every , this function is convex with and curvature . As it approaches , and as it approaches . Since adding a multiple of changes no divergence, the two limits recover forward and reverse KL. Halfway between them, at , we get (twice squared Hellinger), while gives half of . A single parameter therefore interpolates smoothly from reverse KL through Hellinger to forward KL and on to (Exercise 1d connects this family to Rényi's divergence).
Let us evaluate the first six rows on our running pair in both argument orders. KL should print and nats, matching Section 25.1, while TV and should match the hand calculations above.
def f_divergence(f, p, q):
"""D_f(P||Q) = sum_x q(x) f(p(x)/q(x)); nats for KL/JS, else unitless."""
return np.sum(q * f(p / q))
generators = {
'KL': lambda u: u * np.log(u),
'reverse KL': lambda u: -np.log(u),
'chi^2': lambda u: (u - 1) ** 2,
'Hellinger^2': lambda u: (np.sqrt(u) - 1) ** 2,
'TV': lambda u: 0.5 * np.abs(u - 1),
'JS': lambda u: u / 2 * np.log(u) - (u + 1) / 2 * np.log((u + 1) / 2),
}
p = np.array([0.6, 0.3, 0.1])
q = np.array([0.2, 0.5, 0.3])
for name, f in generators.items():
print(f'{name:12s} D_f(P||Q) = {f_divergence(f, p, q):.4f} '
f'D_f(Q||P) = {f_divergence(f, q, p):.4f}')
KL D_f(P||Q) = 0.3961 D_f(Q||P) = 0.3653
reverse KL D_f(P||Q) = 0.3653 D_f(Q||P) = 0.3961
chi^2 D_f(P||Q) = 1.0133 D_f(Q||P) = 0.8000
Hellinger^2 D_f(P||Q) = 0.1862 D_f(Q||P) = 0.1862
TV D_f(P||Q) = 0.4000 D_f(Q||P) = 0.4000
JS D_f(P||Q) = 0.0911 D_f(Q||P) = 0.0911
As expected, the KL row is asymmetric, and the reverse-KL row is simply the KL row with its columns swapped. The row is asymmetric too ( against ). By contrast, squared Hellinger (), TV (), and JS are symmetric, with JS at nats sitting well below its ceiling of . Six divergences have looked at the same pair of distributions and returned values spanning an order of magnitude, from to . Yet if we multiply KL by , squared Hellinger by , and JS by , the three rescaled values are , , and . Why would three quite different functions of the density ratio nearly agree, and where did the factors , , and come from?
25.3.1.4 The Local Quadratic#
The curves in Figure 25.3.1 behave very differently far from . Near , however, they collapse into a single function up to a constant factor, which is perhaps the most surprising property of the entire family. Nothing later in this section depends on this subsection, so you can skip it on a first reading.
Because adding a linear term leaves every divergence unchanged, neither the value nor the slope affects . The first property that distinguishes one smooth divergence function from another is its curvature . Near , every smooth looks like the parabola , and the expectation of under is none other than the divergence, . Let measure how far the density ratio strays from .
Proposition (local quadratic). Let , let , let be three times differentiable on with there, and let for every with . Then
Proof. Since , Taylor's theorem with remainder gives with . Take term by term. The linear term vanishes because , eliminating the only first-order difference between one and another. The quadratic term becomes , and the remainder satisfies .
In short, with a relative error proportional to : whenever is close to , all smooth f-divergences are scalar multiples of one another. The factors , , and we applied to KL, squared Hellinger, and JS are simply , and the target all three products approximate is . On our running pair they still fall about a quarter short, which is no surprise: the largest ratio is , so , outside the proposition's hypothesis . To watch the quadratic approximation tighten, let us slide toward along the line segment . This scales every by , giving . For four smooth divergences, we print the ratio , which should converge to at a rate proportional to .
curvature = {'KL': 1.0, 'reverse KL': 1.0, 'Hellinger^2': 0.5, 'JS': 0.25}
for t in (0.5, 0.1, 0.01):
p_t = q + t * (p - q) # moves P_t toward Q as t -> 0
chi2 = f_divergence(generators['chi^2'], p_t, q)
ratios = [f_divergence(generators[name], p_t, q) / (c / 2 * chi2)
for name, c in curvature.items()]
print(f't = {t:4}: ' + ' '.join(f'{name} {r:.3f}'
for name, r in zip(curvature, ratios)))
t = 0.5: KL 0.844 reverse KL 0.747 Hellinger^2 0.789 JS 0.783
t = 0.1: KL 0.956 reverse KL 0.917 Hellinger^2 0.936 JS 0.935
t = 0.01: KL 0.995 reverse KL 0.990 Hellinger^2 0.993 JS 0.993
At , the four divergences sit at roughly to of their quadratic approximations; at they exceed , and at they exceed . Between the last two rows drops tenfold and each shortfall drops nearly tenfold too, matching the linear factor in the proposition. The bound itself is conservative: for KL at we have and , which allows a relative error of about , whereas the actual gap is only . The takeaway for optimization is practical: smooth f-divergences disagree meaningfully only on distant distributions, which is the regime early in training when the model is still far from the data.
Inside a parametric family, this common local quadratic is governed by the Fisher information matrix of Section 24.6. For a small parameter step , the density ratio of to expands as . Therefore , so every smooth has Hessian at . The natural gradient of Section 23.5, though usually motivated by KL divergence, would yield the same update under any smooth f-divergence. Total variation is the lone exception in our table: its divergence function has a corner at and no second derivative there, and Exercise 4b explores how that changes its behavior as approaches .
25.3.2 Forward and Reverse KL#
Maximum likelihood, the training criterion behind most models in this book, minimizes KL divergence with the data in the first argument. Variational inference minimizes KL divergence with the model in the first argument. Both orders appear as separate rows in Table 25.3.2, and when we fit a model (with density ) to a target that lies outside the model family, they push the model in opposite directions:
- Forward KL, , takes its expectation over the truth. Whenever at a point where , the divergence blows up. Forward KL is therefore zero-avoiding, or mode-covering: the model must stretch to cover every mode of the data, that is, every region where concentrates, even if that forces it to spill mass across empty regions never visits.
- Reverse KL, , takes its expectation over the model. Here the model is penalized heavily for placing mass where the truth has none, while any mode the model ignores contributes nothing to the objective. Reverse KL is therefore zero-forcing, or mode-seeking: the model locks onto the portion of the target it can explain well.
In practice, the choice of direction is often settled by what we can actually compute. Forward KL requires samples from and the density of the model, and minimizing it is just maximum likelihood: Section 24.6.2.1 shows that the average negative log-likelihood equals the cross-entropy from the empirical distribution to the model, which differs from forward KL only by a constant independent of . Reverse KL requires samples from the model and the density of the target, and it works even when the target density is known only up to a normalizing constant. Variational inference (Section 24.7) sits in this setting: its target is a posterior with an intractable normalizer, so it minimizes over tractable approximations .
When samples and densities are available on both sides, however, the direction becomes a genuine design choice. A student network distilled from a teacher spreads out to cover everything the teacher might say when the teacher comes first, and concentrates on the teacher's likeliest outputs when the student comes first. Similarly, the KL penalty in Section 15.3 places the learned policy first, keeping it away from actions that the reference policy never takes.
If the model family contains , both directions recover . They part ways when the model is misspecified, and the clearest illustration is fitting a single Gaussian to a bimodal mixture. For forward KL, no optimization is even needed. Because forward KL equals a constant minus , its minimizer is the maximum-likelihood Gaussian with replacing the empirical distribution, and maximum likelihood in an exponential family matches the expected sufficient statistics (Section 24.4.3.2): and , provided the variance is finite. Reverse KL has no such closed-form solution, and it can have a separate local minimum near each mode.
For the bimodal mixture , we can predict the forward fit in advance. Its mean is . Its variance is the within-component variance plus the between-component variance, which for weights , and means separated by equals , giving . For the reverse fit, we run a derivative-free optimizer over from two starting points, once at the origin and once near the smaller mode, evaluating each KL by numerical quadrature on a grid. For each fit, the next cell reports the mean, standard deviation, and both divergences.
w, mus, sigmas = np.array([0.7, 0.3]), np.array([-2.0, 2.0]), np.array([0.6, 0.6])
x = np.linspace(-8.0, 8.0, 4001)
def log_components(x, w, mus, sigmas):
"""log(w_k N(x; mu_k, sigma_k^2)) for every component k; shape (k, len(x))."""
return (np.log(w)[:, None] - 0.5 * np.log(2 * np.pi * sigmas[:, None] ** 2)
- (x - mus[:, None]) ** 2 / (2 * sigmas[:, None] ** 2))
def log_mix(x, w, mus, sigmas):
"""Log-density of the mixture sum_k w_k N(mu_k, sigma_k^2), computed stably."""
c = log_components(x, w, mus, sigmas)
c_max = c.max(axis=0)
return c_max + np.log(np.exp(c - c_max).sum(axis=0))
log_p = lambda x: log_mix(x, w, mus, sigmas)
def log_q(x, theta):
mu, log_sigma = theta
return (-0.5 * np.log(2 * np.pi) - log_sigma
- (x - mu) ** 2 / (2 * np.exp(2 * log_sigma)))
def kl(log_a, log_b, x):
"""D_KL(A||B) by quadrature on the grid x; in nats."""
return integrate.trapezoid(np.exp(log_a) * (log_a - log_b), x)
fwd = lambda th: kl(log_p(x), log_q(x, th), x) # D_KL(P || Q_theta)
rev = lambda th: kl(log_q(x, th), log_p(x), x) # D_KL(Q_theta || P)
th_fwd = optimize.minimize(fwd, x0=[0.0, 0.0], method='Nelder-Mead').x
th_rev = optimize.minimize(rev, x0=[0.0, 0.0], method='Nelder-Mead').x
th_rev2 = optimize.minimize(rev, x0=[2.5, -0.5], method='Nelder-Mead').x
print(f'{"fit":26s}{"mu":>8s}{"sigma":>7s}'
f'{"forward KL":>12s}{"reverse KL":>12s}')
for name, th in [('forward-KL fit', th_fwd), ('reverse-KL fit', th_rev),
('reverse-KL fit, 2nd start', th_rev2)]:
print(f'{name:26s}{th[0]:+8.3f}{np.exp(th[1]):7.3f}'
f'{fwd(th):12.3f}{rev(th):12.3f}')
d2l.plot(x, [np.exp(log_p(x)), np.exp(log_q(x, th_fwd)),
np.exp(log_q(x, th_rev))], 'x', 'density',
legend=['target P (mixture)', 'forward-KL fit', 'reverse-KL fit'],
figsize=(6, 3))fit mu sigma forward KL reverse KL
forward-KL fit -0.800 1.929 0.558 1.274
reverse-KL fit -1.998 0.603 5.981 0.356
reverse-KL fit, 2nd start +1.995 0.607 14.534 1.202
The forward fit matches our calculation: and . It is a broad bell curve draped over both modes, putting substantial mass in the valley between them where has almost none. The first reverse fit lands at , : it hugs the dominant component and leaves almost no mass on the minor one. Its reverse KL, nats, is close to , the cost of treating the component as if it were the entire distribution. When started near the minor mode, the optimizer settles instead on , with reverse KL nats, close to . Which mode a variational approximation captures therefore depends on its initialization.
Because reverse KL averages under the model, any mode the model fails to visit is never inspected. The objective only notices that the chosen mode carries weight (or ) instead of . That is why variational posteriors notoriously underestimate uncertainty: here the reverse fit has standard deviation , whereas the target's is .
The last two columns highlight how sharply the two criteria disagree on the same model. Forward KL, the maximum-likelihood criterion, penalizes the dominant-mode fit at nats (more than ten times the nats of the broad fit) and the minor-mode fit at nats. In both cases, the dropped mode sits more than six of the model's standard deviations away from its mean, where is deeply negative (Exercise 3c). Reverse KL ranks the first two fits in the opposite order, nats against : what it cannot forgive is the broad fit's mass sitting in the empty valley between the modes.
Our boundary rules for vanishing densities capture this contrast in the limit. For forward KL, has , so placing zero model mass where has positive mass costs infinity, while means placing model mass where has none adds no boundary term at all. For reverse KL, , those two values swap places.
25.3.3 Total Variation, Pinsker's Inequality, and Data Processing#
Knowing that a divergence equals tells us very little on its own until we know what that number actually guarantees. For total variation, the operational meaning is completely transparent, and Pinsker's inequality passes much of that meaning on to KL divergence.
25.3.3.1 Total Variation#
The divergence function is the simplest entry in Table 25.3.2: it penalizes only the absolute distance of the ratio from . Its divergence, half the distance between and , admits a second, equivalent form that makes the number immediately interpretable. Total variation is the largest gap between the probabilities that and assign to any event :
If , no event whatsoever can separate the two distributions by more than three percentage points. The supremum is achieved by the event of outcomes that favors over . To verify this, pick any event . Then , because switching from to only adds non-negative terms and drops non-positive ones. Since , the positive and negative parts of have equal total magnitude, so the right-hand side equals ; the same bound applies to .
On our running pair, consists of the first outcome alone, giving , as we found earlier. Figure 25.3.2 illustrates the same geometry for two continuous densities. Total variation is also a true metric: both forms are manifestly symmetric, and the triangle inequality follows directly from the formula (Exercise 2a).
Two equal-variance densities and the regions where they disagree. The lobe where and the lobe where have equal area, and that common area is the total variation distance. The event attaining the supremum is , here the half-line left of the crossing: guessing there and elsewhere is the optimal single-sample test.
The supremum form gives TV a concrete statistical meaning. Imagine handing a tester a single sample, drawn with equal probability from or from , and asking which distribution generated it. Any deterministic test answers "" when the sample falls in some region , and "" otherwise, succeeding with probability
with equality at . Every test takes this form for some (a randomized test merely averages deterministic ones and cannot do better), so even the optimal tester beats a fair coin flip by at most . On our running pair, the optimal test answers "" on the first outcome and is right of the time. Both the discriminator of a GAN (trying to tell real data from generated samples) and a detector of machine-generated text are testers of this kind, and total variation sets a hard ceiling on how accurate either can be from a single sample.
25.3.3.2 Pinsker's Inequality#
Total variation bounds every statistical test, while KL divergence is what we can usually compute or control in practice because neural network losses are built from log-probabilities. Pinsker's inequality bridges the two: a small KL divergence certifies that no test can reliably tell from . Policy trust regions in Section 15.2 are a classic example: the monotonic improvement guarantee is proved in terms of total variation, yet enforced through a bound on KL.
Proposition (Pinsker's inequality). (Pinsker, 1964; Csiszár, 1967) For distributions and on a finite or countable set,
Proof. Step 1: two outcomes. Write for a coin with heads probability . For and , we have and . We therefore need to show that is non-negative. Fix . Clearly , the first derivative also vanishes at , and for the second derivative is
because . A convex function with both value and slope zero at is non-negative everywhere on , and by continuity (with ) at the endpoints and as well. If is or , the KL divergence is infinite unless , so the inequality holds trivially.
Step 2: reduction to two outcomes. Let , and set and , so that . Coarsening the space by merging all outcomes inside into one bucket and all outcomes outside into another can only decrease KL. That follows from the log-sum inequality: for non-negative numbers and ,
which is itself one application of Jensen's inequality to . Applying it separately to and its complement gives
which rearranges to (25.3.7).
On our running pair, Pinsker's inequality reads , and we can trace Step 2 by hand. Merging the second and third outcomes collapses the pair to two coins, and . Their TV distance remains , their KL divergence drops from to nats, and Step 1 lower bounds that by .
For a coin of bias compared with a fair coin, KL is nats, while : for nearly equal coins, Pinsker's inequality is almost tight. Crucially, however, there is no useful converse. A model that puts on a single rare outcome has infinite KL even when its TV distance is tiny. The bound also becomes vacuous for well-separated distributions, since TV can never exceed : two unit-variance Gaussians separated by have , whereas (25.3.1) gives KL nats.
How tight is Pinsker's bound on typical distributions, and can the constant be improved? To check the first question, we sample random pairs of distributions on five outcomes uniformly from the simplex. To check the second, we let two coins approach each other at : Step 1 lost nothing to second order there, so the ratio should climb all the way to .
rng = np.random.default_rng()
pr, qr = rng.dirichlet(np.ones(5), 10000), rng.dirichlet(np.ones(5), 10000)
tv = 0.5 * np.abs(pr - qr).sum(axis=1)
kl_pq = np.sum(pr * np.log(pr / qr), axis=1)
ratio = tv / np.sqrt(kl_pq / 2)
print(f'TV / sqrt(KL/2) over 10,000 random pairs: median {np.median(ratio):.2f}, '
f'max {ratio.max():.3f}')
for delta in (0.1, 0.01, 0.001):
a, b = np.array([0.5, 0.5]), np.array([0.5 + delta, 0.5 - delta])
print(f'coins 1/2 vs 1/2 + {delta:5}: TV / sqrt(KL/2) = '
f'{delta / np.sqrt(kl_div(a, b) / 2):.6f}')
grid = np.linspace(0, 3, 100)
d2l.plot([kl_pq[:2000], grid], [tv[:2000], np.sqrt(grid / 2)], 'KL (nats)',
'TV', legend=['random pairs', 'sqrt(KL/2)'], fmts=('.', '-'),
xlim=[0, 3], figsize=(4.5, 3))TV / sqrt(KL/2) over 10,000 random pairs: median 0.78, max 0.986
coins 1/2 vs 1/2 + 0.1: TV / sqrt(KL/2) = 0.989881
coins 1/2 vs 1/2 + 0.01: TV / sqrt(KL/2) = 0.999900
coins 1/2 vs 1/2 + 0.001: TV / sqrt(KL/2) = 0.999999
Every point in the scatter plot falls beneath the curve . The median pair sits near of the bound, and the tightest of the random pairs comes within a few hundredths of . Once , the curve rises above and the bound becomes vacuous. For nearly fair coins, the ratio climbs through , , and , confirming that the constant cannot be tightened further (Exercise 4c). Pinsker's original proof had a weaker constant; the sharp factor is due to Csiszár (1967) and, independently, to Kullback and Kemperman.
25.3.3.3 Data Processing#
Can a feature extractor, a quantizer, or any other post-processing step make two distributions easier to tell apart? In Pinsker's proof, merging outcomes could only decrease KL, and the chain rule of Section 25.1.2.4 showed the same for discarding one variable of a pair. The same principle holds for every f-divergence and every form of processing. A channel is any rule, deterministic or randomized, that transforms an input into an output . Passing through the channel produces the output distribution , and passing produces analogously.
Proposition (data processing for f-divergences). For any channel , convex with , and on a finite or countable set,
Proof. Since , we can expand . Fix an output with . The normalized weights sum to one over , and averaging the density ratios under these weights yields . Applying Jensen's inequality to the inner sum therefore bounds it below by , which is the -th term of . Any output with must have wherever , hence as well, contributing nothing to either side. Summing over completes the proof.
No matter which divergence function we pick, processing data can never make two distributions more distinguishable. In deep learning, this inequality is often read in reverse: a divergence measured on learned features, quantized outputs, or any other summary of the data is always a lower bound on the divergence between the raw inputs. Merging outcomes in Pinsker's proof is simply the deterministic channel . On our running pair, it lowered KL from to , and it lowers from to . The KL special case is also the engine behind the data-processing inequality for mutual information in Section 25.6.2.2.
An invertible transformation acts as a channel in both directions, forcing equality in (25.3.8): every f-divergence is invariant to relabeling outcomes or rescaling the axes. By contrast, the last two rows of Table 25.3.1 do change when you rescale the axis. What those distances gain in geometric sensitivity to , they give up in scale invariance.
25.3.4 The Fenchel Conjugate and the Critic Bound#
Suppose we have a generative network that produces samples from a distribution , alongside a dataset of samples from the true distribution . Neither collection of samples gives us access to the density ratio required by (25.3.2). Can we still estimate from samples alone? As it turns out, we can lower-bound any f-divergence using only expectations under and , and that lower bound turns any divergence into an adversarial training objective.
25.3.4.1 Derivation of the Bound#
The key tool is the convex conjugate from Section 23.7.4. For a convex function , its conjugate is defined by
so that is the vertical intercept of the tangent line to with slope (Figure 25.3.3). For , the supremum occurs where , giving . Because a convex function always lies above every one of its tangent lines, we obtain the Fenchel--Young inequality:
with equality whenever matches the slope of at , namely .
A convex divergence function, here , is the upper envelope of its tangent lines. The tangent of slope has vertical intercept , here . Keeping a single tangent gives the Fenchel--Young lower bound, and taking the supremum over slopes recovers . Applying this inequality pointwise to the density ratio yields the critic bound.
Now apply (25.3.9) pointwise inside the divergence, letting the slope vary with . Specifically, pick any function , called the critic, and substitute and .
Proposition (critic bound). Let be convex and differentiable with , let , and let be any critic with and . Then
Moreover, the supremum of the right-hand side over all critics equals , and it is attained by wherever is finite (Nguyen et al., 2010; Nowozin et al., 2016).
Proof. Multiply (25.3.9) at and by :
Summing (or integrating) over yields (25.3.10). Because Fenchel--Young holds with equality at , choosing turns the inequality into an equality at every , and therefore in expectation as well.
Both terms on the right-hand side of (25.3.10) are simple expectations, of over real data and of over generated samples, requiring no explicit densities at all. We can therefore parameterize as a neural network and train it on minibatches to maximize the bound. For KL divergence, the bound reads for every critic . The f-GAN of Nowozin et al. (2016) (after which (25.3.10) is also called the f-GAN bound) turns this variational form into a two-player game: the critic maximizes the bound so that it tracks the divergence, while the generator producing minimizes it. Section 16.2 implements and trains such pairs.
25.3.4.2 The Original GAN#
The original GAN of Goodfellow et al. (2014) falls right out of this framework when we choose . Its convex conjugate is for . If we write the critic as the logarithm of a discriminator , setting , the critic bound becomes the familiar binary cross-entropy game:
The optimal critic corresponds to the Bayes-optimal discriminator . Comparing with the Jensen--Shannon divergence function in Table 25.3.2, we find that : twice the Jensen--Shannon function, plus a linear term in (which changes no divergence) and the constant (which only shifts the value). At , the minimax game therefore achieves , which on our running pair equals .
25.3.4.3 Limits of the Bound#
In practice, the critic bound runs into two limitations, and we can measure the first one directly. Because the bound is tight only at , an undertrained critic reports less than the true divergence. Let us watch how a critic closes that gap as it trains.
On our discrete running pair, expectations are simple sums and a critic is just a vector of three numbers, one per outcome. Take the divergence, with , conjugate , and optimal critic . (Here the conjugate takes the supremum over all real ; Exercise 6a derives it and checks that this loses nothing at .) Starting from , where the bound is , we run gradient ascent with step size on the bound, whose derivative with respect to is . By the proposition, the ascent must climb from below toward . As a sanity check, the final line also evaluates an overconfident critic that points in the right direction but overshoots by a factor of two.
def fgan_bound(T, p, q, f_star):
"""E_P[T] - E_Q[f*(T)]: a lower bound on D_f(P||Q) for any critic T."""
return np.sum(p * T) - np.sum(q * f_star(T))
chi2_star = lambda t: t + t ** 2 / 4 # conjugate of f(u) = (u - 1)^2
exact = f_divergence(generators['chi^2'], p, q)
T, bounds = np.zeros(3), [] # untrained critic: one number per outcome
for step in range(51):
bounds.append(fgan_bound(T, p, q, chi2_star))
T = T + (p - q * (1 + T / 2)) # ascent step 1 along p - q f*'(T)
shown = (0, 1, 2, 5, 10, 20, 50)
print(f'exact chi^2(P||Q) = {exact:.4f}')
print('steps ' + ''.join(f'{s:8d}' for s in shown))
print('bound ' + ''.join(f'{bounds[s]:8.4f}' for s in shown))
T_star = 2 * (p / q - 1) # the optimal critic f'(p/q)
print(f'overconfident critic 2 T*: bound = '
f'{fgan_bound(2 * T_star, p, q, chi2_star):.4f}')
d2l.plot(np.arange(51), [bounds, [exact] * 51], 'ascent steps', 'value',
legend=['bound', 'chi^2(P||Q)'], figsize=(4.5, 2.8))exact chi^2(P||Q) = 1.0133
steps 0 1 2 5 10 20 50
bound 0.0000 0.2240 0.3935 0.7036 0.9107 1.0013 1.0133
overconfident critic 2 T*: bound = 0.0000
After five steps, the critic certifies out of (about of the true divergence); after ten steps it reaches , and after twenty steps . At no point does the bound overshoot the true value. Even the overconfident critic reports zero, no better than an untrained critic. With exact expectations, any adversarial divergence estimate is an underestimate, and the number itself never reveals how much is missing. When expectations are replaced by finite-sample averages, it remains a valid lower bound (in expectation) only on fresh samples that were not used to train the critic.
The gradient update also reveals where the missing divergence hides. Because moves at a rate proportional to , the critic learns slowest where the model's samples are rarest. On our running pair, that is the first outcome, where the density ratio is largest and most of the divergence lives (Exercise 6b).
The second limitation brings us back to disjoint supports, now viewed from the critic's perspective. Extending formally beyond the hypothesis , the ratio equals on the data support and on the model support, so takes the constant value on one and on the other. Because the generator updates its parameters using the gradient of the critic evaluated at its own samples, a critic that is locally constant there provides zero gradient. The generator receives no signal telling it which way to move.
Both limitations stem from the same root: the density ratio . Finite samples never hand us directly, and whenever the supports separate, the ratio collapses to or and erases all trace of how far apart the distributions sit. In Section 25.4, we turn to comparisons that do not rely on density ratios at all.
25.3.5 Summary#
KL divergence is one member of a broad family: an f-divergence averages a convex function of the density ratio under . Jensen's inequality guarantees non-negativity for every member, all smooth members agree up to their curvature when and are close, and no post-processing of the data can increase any f-divergence. Choosing the direction of KL is a modeling decision: forward KL (maximum likelihood) stretches to cover every mode, whereas reverse KL (variational inference) can lock onto a single one. Operationally, the best single-sample test distinguishing from succeeds with probability , and Pinsker's inequality bounds TV by . Using the convex conjugate, any critic lower-bounds via expectations over and alone, which is how adversarial training estimates divergences from samples. Yet every member shares the same blind spot of the density ratio: on disjoint supports, freezes at the constant , regardless of how near or far the supports lie.
25.3.6 Exercises#
-
Divergence functions and argument order. Each row of Table 25.3.2 is one choice of in the template (25.3.2).
- For a divergence function , define . Show that is convex with and that . Compute for the KL function and for the function , and write the divergence that the second one defines as a sum over .
- Adding to does not change the divergence. Show that is symmetric whenever for some constant . Check this condition for the rows of Table 25.3.2 that are marked symmetric, and show that for the function (25.3.4). Use this identity to confirm the entry of the -divergence row in the "Symmetric?" column.
- Expand (25.3.3) in terms of the ratio and recover the Jensen--Shannon function of Table 25.3.2.
- Rényi divergence. For , , define (Rényi, 1961). Show that and that is an increasing function of . Deduce that and that satisfies the data-processing inequality (25.3.8). Find , and explain why it is whenever and are positive on the same outcomes. Why does the Rényi family therefore not reach reverse KL as , while does?
-
Metrics among divergences. The last column of Table 25.3.2 records which divergences are metrics.
- Prove the triangle inequality for TV from its half- form.
- Show that the Hellinger distance is the Euclidean distance between the vectors and , so that is a metric. Find three distributions on two outcomes for which both and JS violate the triangle inequality.
-
Cost of dropping a mode. A model misses part of a data distribution .
- Let with , where is a distribution on a set to which assigns probability zero. Compute , , and as functions of . Which direction of KL penalizes the missing mass? How do the finite divergences behave as ?
- Now let with separation , and let the model keep only the first component. Show that for every , with equality in the limit , and relate the limit to (a). Use the bound to explain the two reverse-KL values, and nats, that the fit of a Gaussian to the mixture prints.
- Assume that the components are well separated, so that almost every
has non-negligible density under at most one of them. Show that
. Evaluate the approximation for
the mixture of that experiment, and check it
with
kl(log_p(x), log_q(x, [-2.0, np.log(0.6)]), x). The experiment prints two values in its forward-KL column to compare with: nats at the reverse-KL fit, whose parameters are not quite , and nats at the forward fit.
-
Local quadratic regime. The proposition (25.3.5) bounds the gap between and .
- Exercise 7b of Section 25.1 finds the order at which the two directions of the Gaussian KL divergence first differ. Which property of the KL and reverse-KL functions explains that order? Carry the Taylor expansion of the proof one term further, and show that the ratio which the local-quadratic experiment prints is with , about for the running pair. Compute for the four functions. Why is the shortfall of reverse KL at twice that of KL, and why do squared Hellinger and JS print the same value there?
- The total-variation function has no second derivative at . Let for . How do and scale with ? Explain from this why Pinsker's inequality (25.3.7) bounds TV by the square root of KL and not by a multiple of KL.
- Let and be coins with heads probabilities and . Use the proposition to show that . Exercise 5a of Section 25.2 obtains the same expansion directly from the Bernoulli KL divergence. The factor is the Fisher information of the coin (Section 24.6). Find the limit of as , and the values of for which Pinsker's inequality is tight in this limit. The coin experiment that follows Pinsker's inequality takes and prints a ratio of at . Why does the ratio approach at the rate and not ?
-
Hellinger bounds and testing. ● Pinsker's inequality is vacuous once . Let be the Bhattacharyya coefficient.
- Prove that , using .
- Prove that with the Cauchy--Schwarz inequality of Section 21.1, and rewrite the bound as .
- Use Jensen's inequality to show that , and conclude the Bretagnolle--Huber inequality (Bretagnolle and Huber, 1978; Canonne, 2022). For which values of is it tighter than (25.3.7)?
- A test sees independent samples, all from or all from , each case with probability . Use (c) and the additivity of KL over independent samples from Section 25.1.2.4 to show that every test errs with probability at least . How many samples does an error probability of at most require? Why can Pinsker's inequality not give a bound of this kind?
-
Conjugates and critics. The critic bound (25.3.10) needs the conjugate of the divergence function.
- Derive the conjugate of the function , taking the supremum over , and its optimal critic . Redo the computation over the function's domain , and show that the supremum is for and for .
- Use the -conjugate. Show that for every critic the gap between and the bound equals . Deduce that a scaled critic certifies , which explains the value that the experiment prints for . Show that one ascent step of the experiment multiplies by . Which outcome of the running pair accounts for most of the gap after ten steps, and why? For which step sizes does the ascent converge?
- Compute the conjugate of the total-variation function over . Show that critics with values in suffice to maximize the bound, and conclude that over all functions with , a supremum of the kind that Section 25.4.1 studies. Which attains it?