25.7 Estimating Mutual Information

Every mutual information we have computed so far came from a closed-form joint density. In practice, data never come with a density attached. Instead, we are given a collection of pairs, such as spoken sentences with their transcripts or search queries with the documents that answered them, and from those samples alone we want to quantify how much one member of a pair reveals about the other. Representation learning pushes this one step further: it trains models to make that shared information large, turning the estimate itself into a training objective.

A familiar contrastive loss makes the challenge concrete. Systems such as SimCLR and CLIP train on paired views of the same example, such as two random crops of a photograph or an image paired with its caption. Given one view, the model learns to identify its true partner among a batch of candidates, say 128128 of them, by minimizing a cross-entropy loss known as the InfoNCE loss. Papers frequently subtract this loss from ln⁡128=4.85\ln 128 = 4.85 and report the difference as the mutual information between the two views. Yet that difference can never exceed 4.854.85 nats, no matter how much information the views actually share: a model that picks the right partner every time has only proved that it can distinguish 128128 candidates. Because we both train models on such quantities and interpret them as measurements, we need to distinguish a genuine measurement from a lower bound, and to separate the slack of a bound from the error of a learned model.

There are two main ways to estimate mutual information from samples. The direct approach counts samples, either inside histogram bins or within nearest-neighbor regions; it works well for small amounts of information between low-dimensional variables, but breaks down for vectors. The second approach replaces the unknown densities with a learned model arranged so that the resulting expectation is a lower bound on I(X;Y)I(X; Y), and then maximizes that bound. Two results anchor the rest of this section: the fundamental limit on what any estimator can guarantee without distributional assumptions (Section 25.7.2.4), and the variational bound behind the InfoNCE loss together with its logarithmic ceiling (Section 25.7.4).

from scipy.spatial.distance import cdist
from scipy.special import digamma, logsumexp

25.7.1 A Pair with Known Information#

To judge an estimator fairly, we need a benchmark whose exact mutual information we already know. Throughout this section we use the standard bivariate Gaussian pair from Section 25.6.1.3 with correlation ρ\rho, which shares

I(X;Y)=−12log⁡(1−ρ2)(25.7.1)I(X; Y) = -\tfrac{1}{2}\log\left(1 - \rho^2\right) \tag{25.7.1}

nats: 0.830.83 nats at ρ=0.9\rho = 0.9 and 1.961.96 nats at ρ=0.99\rho = 0.99. All logarithms in this section are natural.

The variational bounds we will derive rely on the pointwise mutual information (Section 25.6.1.4), pmi(x,y)=log⁡p(x,y)p(x) p(y)\textrm{pmi}(x, y) = \log \frac{p(x, y)}{p(x)\,p(y)}, which measures how much more likely a specific pair (x,y)(x, y) is under the joint distribution than under independence. For our standard Gaussian pair, the pmi is a simple quadratic function:

pmi(x,y)=−12log⁡(1−ρ2)−x2−2ρxy+y22(1−ρ2)+x2+y22.(25.7.2)\textrm{pmi}(x, y) = -\tfrac{1}{2}\log(1 - \rho^2) - \frac{x^2 - 2\rho x y + y^2}{2(1 - \rho^2)} + \frac{x^2 + y^2}{2}. \tag{25.7.2}

Two identities follow immediately from this definition. First, averaging pmi(x,y)\textrm{pmi}(x, y) over pairs drawn from the joint distribution gives I(X;Y)I(X; Y). Second, averaging its exponential epmi(x,y)e^{\textrm{pmi}(x, y)} over independent draws of xx and yy gives 11, because p(x) p(y) epmi(x,y)=p(x,y)p(x)\,p(y)\,e^{\textrm{pmi}(x, y)} = p(x, y) integrates to 11. Let us verify both identities on samples. For the second identity, we break the dependence by pairing each xx with the yy from the next sample in the array. We call these mismatched pairs; each one is an independent draw from PX⊗PYP_X \otimes P_Y, and we will reuse this simple trick whenever a bound requires independent pairs.

def gauss_pair(rng, rho, n):
    """Samples of the standard Gaussian pair; n is a count or a shape."""
    x = rng.standard_normal(n)
    y = rho * x + np.sqrt(1 - rho**2) * rng.standard_normal(n)
    return x, y

def mi_gauss(rho):
    """I(X;Y) of the pair, in nats."""
    return -0.5 * np.log(1 - rho**2)

def pmi_gauss(x, y, rho):
    """Pointwise mutual information pmi(x, y) of the pair, in nats."""
    c = 1 - rho**2
    return (-0.5 * np.log(c) - (x**2 - 2 * rho * x * y + y**2) / (2 * c)
            + (x**2 + y**2) / 2)

rng = np.random.default_rng()
x, y = gauss_pair(rng, 0.9, 200_000)
print(f'I(X;Y) = {mi_gauss(0.9):.3f} nats, mean pmi over pairs = '
      f'{pmi_gauss(x, y, 0.9).mean():.3f}')
print(f'mean exp(pmi) over independent pairs = '
      f'{np.exp(pmi_gauss(x, np.roll(y, 1), 0.9)).mean():.3f}')
I(X;Y) = 0.830 nats, mean pmi over pairs = 0.833
mean exp(pmi) over independent pairs = 0.994

Both sample averages match their theoretical values to within about 0.010.01. Every variational bound in this section builds on these two identities, and it is the second one that will cause almost all of our statistical trouble. At ρ=0.9\rho = 0.9, epmie^{\textrm{pmi}} is well behaved: its variance over independent pairs is e2I−1e^{2I} - 1 (Exercise 1), which is only 4.34.3 here. At I=6I = 6, however, that variance explodes to 160,000160{,}000, leaving the same 200,000200{,}000-sample average uncertain by roughly 0.90.9.

25.7.2 Nonparametric Estimation#

The most direct way to estimate a probability distribution from data is to count how many samples fall into each region of space. The key design choice is how to define those regions. We begin with the simplest choice: a fixed grid.

25.7.2.1 Histograms#

The histogram estimator partitions the range of each variable into bb equal-width intervals, counts how many samples land in each of the b×bb \times b cells, and plugs the resulting empirical frequencies into the discrete formula for mutual information. Despite its simplicity, this estimator suffers from two competing biases that push in opposite directions.

The first bias pulls the estimate down. Replacing a continuous value by its bin index applies a deterministic function to XX, and by the data-processing inequality (Section 25.6.2.2) any function of XX shares at most as much information with YY as XX itself does. Binning can therefore only destroy information, and the loss is severe whenever the dependence is narrower than a bin. At ρ=0.99\rho = 0.99, for example, the conditional standard deviation of yy given xx is 1−ρ2=0.14\sqrt{1 - \rho^2} = 0.14. Dividing a sample that spans roughly [−4.5,4.5][-4.5, 4.5] into 1010 bins produces cells of width 0.90.9, more than six times wider than the conditional spread.

The second bias pulls the estimate up. The plug-in estimate is the KL divergence between the empirical joint table and the product of its row and column marginals. It is therefore always nonnegative, and equals zero only if the table factorizes exactly. Even when XX and YY are completely independent, random sampling fluctuations prevent exact factorization, so noise masquerades as dependence. The fewer samples each cell contains, the worse this upward bias becomes.

On top of these two errors, a histogram has a hard ceiling. Its estimate cannot exceed the entropy of the binned XX, and bb bins can carry at most log⁡b\log b nats: just 2.302.30 nats for ten bins, no matter how tightly XX and YY are linked. We will encounter a version of this ceiling in every estimator in this section: no method can report more information than the logarithm of the number of states it can distinguish.

Let us implement this estimator as binned_mi and test it on 200,000200{,}000 samples from four distributions using b=10b = 10, 4040, and 160160: an independent pair, the Gaussian pair at ρ=0.9\rho = 0.9 and ρ=0.99\rho = 0.99, and the parabolic pair Y=X2+0.3 ϵY = X^2 + 0.3\,\epsilon from Section 25.6.1.5, which has zero linear correlation yet shares 1.1411.141 nats.

def binned_mi(x, y, bins):
    """Plug-in MI of the bins x bins histogram of (x, y), in nats."""
    p = np.histogram2d(x, y, bins=bins)[0] / len(x)       # cell frequencies
    q = p.sum(axis=1, keepdims=True) * p.sum(axis=0, keepdims=True)
    nz = p > 0                                            # occupied cells
    return float((p[nz] * np.log(p[nz] / q[nz])).sum())

mi_parabola = 1.141  # by quadrature, sec_mdl-mi-nonlinear-correlation
n = 200_000
x = rng.standard_normal(n)
pairs = {'rho = 0': (gauss_pair(rng, 0.0, n), 0.0),
         'rho = 0.9': (gauss_pair(rng, 0.9, n), mi_gauss(0.9)),
         'rho = 0.99': (gauss_pair(rng, 0.99, n), mi_gauss(0.99)),
         'parabola': ((x, x**2 + 0.3 * rng.standard_normal(n)), mi_parabola)}
print('pair        truth  b = 10  b = 40  b = 160')
for name, ((u, v), truth) in pairs.items():
    print(f'{name:10}  {truth:5.3f}'
          + ''.join(f'  {binned_mi(u, v, b):6.3f}' for b in (10, 40, 160)))
pair        truth  b = 10  b = 40  b = 160
rho = 0     0.000   0.000   0.003   0.035
rho = 0.9   0.830   0.629   0.813   0.845
rho = 0.99  1.959   1.090   1.800   1.955
parabola    1.141   0.551   0.989   1.136

Both biases show up clearly in the table. With b=10b = 10, every dependent pair reads low: roughly 0.60.6 instead of 0.830.83 nats at ρ=0.9\rho = 0.9, and only about half the true value at ρ=0.99\rho = 0.99 and for the parabola. With b=160b = 160, the independent pair is credited with a few hundredths of a nat, and the pair at ρ=0.9\rho = 0.9 actually overshoots its true value, something coarse binning alone could never cause. At ρ=0.99\rho = 0.99 with b=160b = 160, the estimate lands within about 0.010.01 of the truth, but only through a fortunate cancellation of opposite errors; the row directly above shows the same grid overshooting. When the true value is unknown, nothing in the table tells us which column to trust.

A third weakness is sensitivity to coordinates. Applying an invertible transformation to either variable leaves mutual information unchanged (Section 25.6.1.5), yet it distorts a fixed-width grid. Suppose we replace xx with x3x^3 in the Gaussian pair at ρ=0.9\rho = 0.9. The largest of 200,000200{,}000 standard normal draws is around ±4.5\pm 4.5, so x3x^3 spans roughly ±90\pm 90. Each of 4040 equal-width bins is then about 4.54.5 wide, which packs roughly nine out of ten samples into the two or three bins around zero. A clean fix is to bin the ranks, meaning each value's position in the sorted sample. Any strictly increasing map preserves ranks, and every rank bin automatically holds the same number of samples.

x, y = gauss_pair(rng, 0.9, n)
rank = lambda a: np.argsort(np.argsort(a))       # position in sorted order
print(f'true I = {mi_gauss(0.9):.3f} nats; histograms with b = 40:')
for name, u in (('x', x), ('x**3', x**3)):
    print(f'{name:4}: correlation {np.corrcoef(u, y)[0, 1]:.3f}, '
          f'raw {binned_mi(u, y, 40):.3f}, '
          f'ranks {binned_mi(rank(u), rank(y), 40):.3f} nats')
true I = 0.830 nats; histograms with b = 40:
x   : correlation 0.901, raw 0.819, ranks 0.819 nats
x**3: correlation 0.699, raw 0.439, ranks 0.819 nats

Even though the true mutual information remains 0.8300.830 nats, cubing xx drops the linear correlation from 0.900.90 to about 0.70.7 and slashes the raw histogram estimate to between 0.30.3 and 0.50.5 nats (with the exact value depending on the few extreme draws that set the bin span). Binning the ranks, by contrast, gives the exact same estimate for xx and x3x^3, digit for digit, and stays within 0.020.02 nats of the truth.

Ranks fix the coordinate problem, but nothing can save histograms from high dimension. A pair of five-dimensional vectors requires a ten-dimensional grid; putting just ten bins along each axis creates 101010^{10} cells, almost all of which will be empty for any realistic sample size. To handle vectors, an estimator must let the data themselves set the resolution, using small regions where samples are dense and larger ones where they are sparse.

25.7.2.2 The KSG Estimator#

The estimator of Kraskov et al. (2004), known as KSG, replaces fixed histogram cells with adaptive nearest-neighbor regions around each data point. It is the standard nonparametric tool for pairs of low-dimensional variables. (This subsection and the next can be skipped on a first reading.)

KSG measures distances using the largest coordinate difference (the Chebyshev, or ℓ∞\ell_\infty, distance), so that a ball of radius rr is a square in two dimensions and a hypercube in higher dimensions. Around each sample point ii, we draw the smallest box in the joint (x,y)(x, y) space that reaches its mm-th nearest neighbor, and let rir_i denote the half-width of that box. By construction, this box contains a fraction m/nm/n of the nn samples, giving a local estimate of the joint probability mass near (xi,yi)(x_i, y_i).

Next, we measure the two marginal probabilities at the exact same scale rir_i. Let nx(i)n_x^{(i)} be the number of other samples falling strictly inside the vertical strip ∣x−xi∣<ri|x - x_i| \lt r_i, and let ny(i)n_y^{(i)} be the number falling strictly inside the horizontal strip ∣y−yi∣<ri|y - y_i| \lt r_i. Sharing the half-width rir_i is what lets raw counts stand in for probability densities: if the densities are roughly constant across the box, the box holds probability mass about p(xi,yi) (2ri)2p(x_i, y_i)\,(2r_i)^2 while the two strips hold about p(xi) 2rip(x_i)\,2r_i and p(yi) 2rip(y_i)\,2r_i. When we divide the box fraction by the product of the two strip fractions, the geometric factors 2ri2r_i cancel out. Taking the logarithm produces a local estimate of the pointwise mutual information computed purely by counting. Figure 25.7.1 illustrates these three counts at a single point.

Figure 25.7.1:

The KSG count at one sample point ii (the star), with m=3m = 3. The box of half-width rir_i reaches the third nearest neighbor in the joint plane (the ring on its left edge, which lies in the horizontal strip and counts toward ny(i)n_y^{(i)} only), while two neighbors lie strictly inside. The vertical strip of the same half-width holds nx(i)n_x^{(i)} other samples and the horizontal strip holds ny(i)n_y^{(i)} (blue and green dots lie in one strip only). Each summand of the estimator is approximately log⁡m/n(nx/n)(ny/n)\log\frac{m/n}{(n_x/n)(n_y/n)}, a pointwise mutual information computed from counts.

Averaging these local log ratios across all nn points estimates I(X;Y)I(X; Y), with one finite-sample correction. Taking the logarithm of a small count is a biased estimate of a log probability: for the box reaching the mm-th of n−1n - 1 neighbors, the expected log probability mass is E[log⁡p]=ψ(m)−ψ(n)\mathbb{E}[\log p] = \psi(m) - \psi(n) rather than log⁡(m/n)\log(m/n), where ψ=(log⁡Γ)′\psi = (\log \Gamma)' is the digamma function (we omit the derivation). Replacing logarithms with ψ\psi gives the KSG estimator:

I^KSG=ψ(m)+ψ(n)−1n∑i=1n(ψ(nx(i)+1)+ψ(ny(i)+1)).(25.7.3)\hat{I}_{\textrm{KSG}} = \psi(m) + \psi(n) - \frac{1}{n} \sum_{i=1}^{n} \left(\psi\left(n_x^{(i)} + 1\right) + \psi\left(n_y^{(i)} + 1\right)\right). \tag{25.7.3}

Because ψ(j)≈log⁡j\psi(j) \approx \log j for large jj, each summand is approximately log⁡m nnx(i) ny(i)\log\frac{m\,n}{n_x^{(i)}\, n_y^{(i)}}, matching the local log ratio of the box fraction to the product of the strip fractions. The +1+1 inside the strip terms aligns them with the box: ψ(m)\psi(m) corresponds to a box whose boundary passes through its mm-th neighbor, so a strip containing nx(i)n_x^{(i)} points strictly inside is treated as if its boundary passed through the (nx(i)+1)(n_x^{(i)} + 1)-th point. Both strip counts use strict inequalities and exclude point ii itself, so a neighbor lying right on a strip boundary is not counted. Because every radius rir_i adapts automatically to the local sample density, there is no bin width or kernel bandwidth to tune.

We can compute all neighbor counts at once from the n×nn \times n matrices of Chebyshev distances in xx and yy using cdist, taking their elementwise maximum for the joint distance.

def ksg_counts(x, y, m=5):
    """Strip counts n_x, n_y of every sample point; x, y are (n, d)."""
    dx, dy = cdist(x, x, 'chebyshev'), cdist(y, y, 'chebyshev')
    d = np.maximum(dx, dy)                       # joint Chebyshev distance
    np.fill_diagonal(d, np.inf)
    r = np.partition(d, m - 1, axis=1)[:, m - 1]  # half-width: m-th neighbor
    n_x = (dx < r[:, None]).sum(axis=1) - 1      # strict, self excluded
    n_y = (dy < r[:, None]).sum(axis=1) - 1
    return n_x, n_y

def ksg_mi(x, y, m=5):
    """KSG nearest-neighbor estimate of I(X;Y) in nats; x, y are (n, d)."""
    n_x, n_y = ksg_counts(x, y, m)
    return float(digamma(m) + digamma(len(x))
                 - (digamma(n_x + 1) + digamma(n_y + 1)).mean())

Because every summand in (25.7.3) depends solely on neighbor counts, counting alone places a hard ceiling on what KSG can report.

Proposition (sample-size ceiling of KSG). For any sample of nn points in which no two joint distances from the same point are equal,

I^KSG≤ψ(n)−ψ(m),(25.7.4)\hat{I}_{\textrm{KSG}} \leq \psi(n) - \psi(m), \tag{25.7.4}

with equality when Y=XY = X.

Proof. Without distance ties, exactly m−1m - 1 samples lie strictly closer to point ii than its mm-th neighbor. Since the joint Chebyshev distance is the larger of the two coordinate distances, each of these m−1m - 1 points satisfies both ∣xj−xi∣<ri|x_j - x_i| \lt r_i and ∣yj−yi∣<ri|y_j - y_i| \lt r_i, so it lies in both strips: nx(i)≥m−1n_x^{(i)} \geq m - 1 and ny(i)≥m−1n_y^{(i)} \geq m - 1. Because ψ\psi is strictly increasing, every summand is at most ψ(m)+ψ(n)−2ψ(m)=ψ(n)−ψ(m)\psi(m) + \psi(n) - 2\psi(m) = \psi(n) - \psi(m). When Y=XY = X, the joint and marginal distances coincide, so both strips contain only the m−1m - 1 points strictly inside the box and every summand attains the bound. ■\blacksquare

For n=2,000n = 2{,}000 and m=5m = 5, this ceiling is ψ(2000)−ψ(5)=6.09\psi(2000) - \psi(5) = 6.09 nats, close to log⁡(n/m)=5.99\log(n/m) = 5.99. Even for Y=XY = X with continuous XX, where the true mutual information is infinite, KSG reports 6.16.1 nats, and doubling the sample size raises that ceiling by only about log⁡2\log 2. We are seeing the histogram's log⁡b\log b ceiling again, with adaptive neighborhoods in place of bins: a neighbor-counting estimator can report at most the logarithm of the number of distinct neighborhoods the sample affords, roughly n/mn/m.

25.7.2.3 KSG in High Dimension#

Unfortunately, in higher dimensions KSG breaks down well below its sample-size ceiling, and for a geometric reason. Consider dd independent copies of our Gaussian pair, each with ρ=0.9\rho = 0.9, so that XX and YY are dd-dimensional vectors. Because the log density ratio splits into a sum of dd independent terms, mutual information is additive across independent coordinates, making the true value d×0.83d \times 0.83 nats.

KSG relies on the joint and marginal densities being nearly constant across each neighbor box, an assumption that collapses as dimension grows. With n=2,000n = 2{,}000 and m=5m = 5, each box captures a fraction m/n=0.0025m/n = 0.0025 of the sample. If points were spread uniformly across 2d2d dimensions, such a box would span a fraction (m/n)1/(2d)(m/n)^{1/(2d)} of the data's width along every axis: 0.050.05 at d=1d = 1, jumping to 0.470.47 at d=4d = 4 and 0.830.83 at d=16d = 16. Yet the dependence lives inside a thin band around y=ρxy = \rho x: given xx, each coordinate of yy has standard deviation 1−ρ2=0.44\sqrt{1 - \rho^2} = 0.44, roughly 0.070.07 of the total span (about −3.3-3.3 to 3.33.3) of the sample. A box many times wider than that band smears out the dependence just like an overly coarse histogram bin. Let us run KSG on 2,0002{,}000 samples for d=1,2,4,8,16d = 1, 2, 4, 8, 16, recording both the estimate and the average strip count, along with the Y=XY = X case that attains the ceiling.

n, rho = 2000, 0.9
print(' d  true I    KSG  mean strip count')
for dim in (1, 2, 4, 8, 16):
    x, y = gauss_pair(rng, rho, (n, dim))        # dim independent pairs
    n_x, n_y = ksg_counts(x, y)
    print(f'{dim:2d}  {dim * mi_gauss(rho):6.2f}  {ksg_mi(x, y):5.2f}  '
          f'{(n_x.mean() + n_y.mean()) / 2:16.1f}')
x = rng.standard_normal((n, 1))
print(f'Y = X:  KSG = {ksg_mi(x, x):.2f}, '
      f'ceiling psi(n) - psi(m) = {digamma(n) - digamma(5):.2f} nats')
 d  true I    KSG  mean strip count
 1    0.83   0.83              71.3
 2    1.66   1.60              50.0
 4    3.32   2.51              31.3
 8    6.64   2.85              26.0
16   13.29   2.75              26.8
Y = X:  KSG = 6.09, ceiling psi(n) - psi(m) = 6.09 nats

In one and two dimensions, KSG stays within about 0.10.1 nat of the truth. By d=4d = 4, it drops to roughly 2.52.5 nats against a true value of 3.33.3, nearly a full nat low. After that it stalls: at both d=8d = 8 and d=16d = 16, KSG reports just under 33 nats even as the true mutual information doubles from 6.66.6 to 13.313.3. Notice that the sample-size ceiling is not what stops it here, since 33 nats is less than half of the 6.16.1-nat ceiling printed for Y=XY = X.

The average strip counts expose why the estimate stalls. Each summand is approximately log⁡m nnxny\log\frac{m\,n}{n_x n_y}, so the estimate can climb only if the marginal strips empty out. They drop from about 7070 points at d=1d = 1 to about 3131 at d=4d = 4, and then level off near 2626. To keep boxes as local at d=16d = 16 as they were at d=1d = 1, we would need m/n=0.0532m/n = 0.05^{32}, requiring a sample of roughly 104210^{42} points. The sample size needed to maintain local neighborhoods grows exponentially with the dimension.

25.7.2.4 Limits of Distribution-Free Estimation#

Perhaps a more clever estimator could bypass this bottleneck. To test that hope, let us ask for something weaker than an exact measurement: a lower bound. Specifically, we seek a function BB of nn samples such that B≤I(X;Y)B \leq I(X; Y) with probability at least 0.950.95 for every distribution of the pair (X,Y)(X, Y). (Any confidence level above 1/21/2 would work just as well.) Lower bounds are also what representation learning wants, since we want to be confident that two views share a large amount of information.

The simplest possible case already reveals the fundamental barrier. Set Y=XY = X for a discrete variable XX, so that I(X;Y)=H(X)I(X; Y) = H(X). If an estimator treats the discrete symbols as arbitrary labels with no built-in metric or ordering, it cannot exploit which symbols appeared. All it can inspect is the pattern of repetitions: how many distinct values appeared once, how many appeared twice, and so on. This summary is called the type of the sample, and we assume BB depends only on it. Four short steps establish the limit, with the third step doing the real work:

  1. Let XX be uniform over MM symbols and draw nn samples. Any given pair of draws collides with probability 1/M1/M, so by the union bound the probability that some two of the n(n−1)/2n(n-1)/2 pairs coincide is at most n(n−1)/(2M)n(n-1)/(2M).
  2. Apply the 0.950.95 guarantee to the uniform distribution on M=n2M = n^2 symbols, whose entropy is 2log⁡n2 \log n: on a sample drawn from this distribution, B≤2log⁡nB \leq 2 \log n with probability at least 0.950.95.
  3. By the first step, a sample of size nn from M=n2M = n^2 symbols consists of nn distinct values with probability greater than 12\tfrac{1}{2}. Because two events whose probabilities sum to more than 11 must overlap, there exists at least one all-distinct sample on which B≤2log⁡nB \leq 2 \log n.
  4. Every sample of nn distinct values has the exact same type, so BB must return the same value (at most 2log⁡n2 \log n) on every all-distinct sample, no matter what distribution actually generated it.

Now test this bound on a uniform distribution over M=2256M = 2^{256} symbols, whose entropy is 256ln⁡2=177256 \ln 2 = 177 nats. With n=106n = 10^6 samples, all draws are distinct with probability at least 1−4.3×10−661 - 4.3 \times 10^{-66}, and on that sample BB can certify at most 2log⁡106=27.62 \log 10^6 = 27.6 nats. A million samples cannot guarantee 177177 nats; in fact, they cannot even guarantee 3030. Exercise 4 sharpens the constant and asks how many samples would be needed.

McAllester and Stratos (2020) proved the general theorem without restricting the estimator to depend only on the sample type:

Theorem (McAllester–Stratos, informal). Any distribution-free lower bound on I(X;Y)I(X; Y) that holds with fixed confidence from nn samples is O(log⁡n)O(\log n).

The invariance of mutual information lies behind this barrier. Because any invertible relabelling of XX or YY leaves I(X;Y)I(X; Y) unchanged (Section 25.6.1.5), an estimator that makes no assumptions about the coordinates must behave consistently under every possible relabelling, leaving only the pattern of repetitions to work with. To break past O(log⁡n)O(\log n), an estimator must assume something about the data. KSG assumes that coordinate distances are meaningful and that densities are smooth, yielding an estimate with no finite-sample guarantee. The variational bounds of Section 25.7.3 can report numbers larger than log⁡n\log n, and in Section 25.7.4.4 we will see how much we can actually trust them when they do.

25.7.2.5 The Compression-Phase Debate#

The two limitations we have just seen, coordinate-dependent histograms and the logarithmic sample ceiling, shed light on a famous debate in deep learning. Shwartz-Ziv and Tishby (2017) trained a small classifier on the 4,0964{,}096 binary patterns of 1212 bits, binned the activations of each hidden layer ZZ throughout training, and plotted estimates of I(X;Z)I(X; Z) and I(Y;Z)I(Y; Z) for input XX and label YY. They observed a brief fitting phase in which both quantities rose, followed by a long compression phase in which I(X;Z)I(X; Z) dropped while I(Y;Z)I(Y; Z) remained high, and proposed that this compression explains why deep networks generalize. Later, Saxe et al. (2018) showed that this compression phase appears with saturating activations like tanh⁡\tanh, but disappears with ReLU activations, even though ReLU networks generalize just as well.

What was the histogram actually measuring? In a deterministic network, the binned activation ZbinZ_{\textrm{bin}} is a deterministic function of the input XX. Consequently, H(Zbin∣X)=0H(Z_{\textrm{bin}} \mid X) = 0, and the binned estimate simplifies to I(X;Zbin)=H(Zbin)I(X; Z_{\textrm{bin}}) = H(Z_{\textrm{bin}}), simply the entropy of the binned activations. That quantity can never exceed the logarithm of the number of inputs, ln⁡4096=8.3\ln 4096 = 8.3 nats, and it drops whenever distinct inputs collapse into the same histogram cell, exactly what happens when training drives saturating tanh⁡\tanh units into the two outer bins near ±1\pm 1. The true mutual information I(X;Z)I(X; Z) itself never moves: as long as distinct inputs produce distinct activations, I(X;Z)=H(X)I(X; Z) = H(X) for a finite input set, and for continuous inputs I(X;Z)I(X; Z) is infinite (Section 25.6.1.3). The plotted curves track how activations cluster across fixed bins, a property of the estimator rather than of the network's true mutual information (Exercise 8).

25.7.3 Variational Lower Bounds#

Because counting cannot measure large mutual information in high dimensions, variational methods change the goal. Rather than estimating the unknown densities in log⁡p(x,y)p(x) p(y)\log\frac{p(x, y)}{p(x)\,p(y)} directly, we introduce an auxiliary model arranged so that its expected score is guaranteed to be a lower bound on I(X;Y)I(X; Y), no matter how imperfect the model is. Training the model to maximize that expectation tightens the bound without ever overshooting I(X;Y)I(X; Y). Estimation thus becomes optimization. Its output carries two distinct sources of error: approximation error from the auxiliary model, which may fall short of the optimal one, and sampling error, because we must replace population expectations with finite batch averages.

We examine four variational bounds in turn, unified in a single framework by Poole et al. (2019). The first uses a normalized decoder (Barber–Agakov). The next two use an unnormalized scoring function, yielding the Donsker–Varadhan (DV) bound and the bound of Nguyen, Wainwright, and Jordan (NWJ). The fourth, InfoNCE, is important enough to merit its own section. Every proof relies on a single tool, Gibbs' inequality (Section 25.1): a KL divergence is always nonnegative.

25.7.3.1 The Barber–Agakov Bound#

The simplest variational bound replaces the unknown posterior p(x∣y)p(x \mid y) with a tractable model q(x∣y)q(x \mid y).

Proposition (Barber–Agakov bound). For any conditional density q(x∣y)q(x \mid y),

I(X;Y)≥H(X)+E(x,y)∼PX,Y[log⁡q(x∣y)],(25.7.5)I(X; Y) \geq H(X) + \mathbb{E}_{(x,y) \sim P_{X,Y}}\left[\log q(x \mid y)\right], \tag{25.7.5}

with equality if and only if q(x∣y)=p(x∣y)q(x \mid y) = p(x \mid y). For continuous XX, the differential entropy h(X)h(X) replaces H(X)H(X).

Proof. Starting from I(X;Y)=H(X)−H(X∣Y)I(X; Y) = H(X) - H(X \mid Y), we subtract the right-hand side of (25.7.5):

I(X;Y)−H(X)−E[log⁡q(x∣y)]=E[log⁡p(x∣y)q(x∣y)]=Ey[DKL(p(⋅∣y) ∥ q(⋅∣y))]≥0.\begin{aligned} I(X; Y) - H(X) - \mathbb{E}\left[\log q(x \mid y)\right] &= \mathbb{E}\left[\log \frac{p(x \mid y)}{q(x \mid y)}\right] \\ &= \mathbb{E}_{y}\left[D_{\textrm{KL}}\big(p(\cdot \mid y) \,\|\, q(\cdot \mid y)\big)\right] \geq 0. \end{aligned}

The inequality follows from Gibbs' inequality applied for each yy and averaged over PYP_Y. Equality holds if and only if the KL divergence vanishes for every yy, meaning q(x∣y)=p(x∣y)q(x \mid y) = p(x \mid y). ■\blacksquare

The Barber–Agakov bound (Barber and Agakov, 2003) gives an information-theoretic reading of an encoder–decoder: if a decoder q(x∣y)q(x \mid y) reconstructs XX from YY with low cross-entropy, then XX and YY must share a large amount of information. Its practical limitation is the term H(X)H(X), which is usually unknown. Fortunately, H(X)H(X) does not depend on qq, so maximizing the bound over qq never requires knowing it. Writing H(X)=−E[log⁡p(x)]H(X) = -\mathbb{E}[\log p(x)] yields the equivalent ratio form I(X;Y)≥E[log⁡(q(x∣y)/p(x))]I(X; Y) \geq \mathbb{E}\left[\log \left(q(x \mid y)/p(x)\right)\right], which will be the key step in proving the InfoNCE bound.

Throughout this section, we say that a model certifies the value of its bound. Keep in mind that this certification holds at the level of population expectations; a finite batch average only estimates the certified value and can fluctuate above or below it.

A standard classifier is a familiar special case. By the symmetry of mutual information, we can swap XX and YY and treat a classifier q(y∣x)q(y \mid x) as a decoder of the label. This recovers the loss certificate of Section 25.6.2.4: for kk balanced classes and held-out cross-entropy LL, I(X;Y)≥log⁡k−LI(X; Y) \geq \log k - L. Because L≥0L \geq 0, a 1010-class classifier can never certify more than ln⁡10=2.30\ln 10 = 2.30 nats. InfoNCE will take the exact same form.

Our Gaussian pair illustrates how much a mismatched decoder can lose. Training a predictor by squared error alone corresponds to a unit-variance Gaussian decoder q(x∣y)=N(x;ay,1)q(x \mid y) = \mathcal{N}(x; a y, 1). Since h(X)=12log⁡(2πe)h(X) = \tfrac{1}{2}\log(2\pi e), the Barber–Agakov bound evaluates to 12−12E[(X−aY)2]=12−12(1−2aρ+a2)\tfrac{1}{2} - \tfrac{1}{2}\mathbb{E}[(X - aY)^2] = \tfrac{1}{2} - \tfrac{1}{2}(1 - 2a\rho + a^2), which peaks at a=ρa = \rho with value ρ2/2\rho^2/2. At ρ=0.9\rho = 0.9, this decoder certifies only 0.410.41 nats out of the true 0.830.83, and no matter how close ρ\rho gets to 11, it can never certify more than 12\tfrac{1}{2} nat. The missing information is the penalty for fixing the decoder's variance at 11 instead of matching the true conditional variance 1−ρ21 - \rho^2 (Exercise 2).

25.7.3.2 The Donsker–Varadhan Bound#

Our second bound removes both requirements of Barber–Agakov: it needs neither H(X)H(X) nor a normalized density qq. Because mutual information is the KL divergence from the joint distribution to the product of its marginals (Section 25.6), any lower bound on KL divergence immediately bounds I(X;Y)I(X; Y). The Donsker–Varadhan bound achieves this using an arbitrary scoring function TT, called a critic (as in Section 25.3.4), with no normalization constraint whatsoever.

Proposition (Donsker–Varadhan bound). For distributions PP and QQ and any function TT for which EP[T]\mathbb{E}_P[T] is defined and EQ[eT]<∞\mathbb{E}_Q[e^T] \lt \infty,

DKL(P∥Q)≥EP[T]−log⁡EQ[eT],(25.7.6)D_{\textrm{KL}}(P \| Q) \geq \mathbb{E}_P[T] - \log \mathbb{E}_Q\left[e^{T}\right], \tag{25.7.6}

with equality if and only if T=log⁡dPdQ+cT = \log \frac{dP}{dQ} + c for some constant cc. When P≪QP \ll Q and the divergence is finite, the supremum over TT attains DKL(P∥Q)D_{\textrm{KL}}(P \| Q), giving the Donsker–Varadhan representation of KL divergence (Donsker and Varadhan, 1983).

Proof. If PP is not absolutely continuous with respect to QQ, the left-hand side is infinite and the inequality is trivial. Otherwise, use the critic to reweight QQ: define the tilted distribution Q~\tilde{Q} with density q~(x)=q(x) eT(x)/Z\tilde{q}(x) = q(x)\, e^{T(x)} / Z, where Z=EQ[eT]Z = \mathbb{E}_Q[e^T] is the normalizing constant. Then

DKL(P∥Q)−(EP[T]−log⁡Z)=EP[log⁡pq−T+log⁡Z]=EP[log⁡pq~]=DKL(P∥Q~)≥0\begin{aligned} D_{\textrm{KL}}(P \| Q) - \left(\mathbb{E}_P[T] - \log Z\right) &= \mathbb{E}_P\left[\log \frac{p}{q} - T + \log Z\right] \\ &= \mathbb{E}_P\left[\log \frac{p}{\tilde{q}}\right] = D_{\textrm{KL}}(P \| \tilde{Q}) \geq 0 \end{aligned}

by Gibbs' inequality. Equality holds if and only if P=Q~P = \tilde{Q}, which means p/q=eT/Zp/q = e^{T}/Z, or equivalently T=log⁡(p/q)+log⁡ZT = \log(p/q) + \log Z. ■\blacksquare

The slack in the bound is simply DKL(P∥Q~)D_{\textrm{KL}}(P \| \tilde{Q}), so a critic is accurate precisely when tilting QQ by eTe^T reproduces PP. Notice also that shifting TT by any constant cc cancels between the two terms. Setting P=PX,YP = P_{X,Y} and Q=PX⊗PYQ = P_X \otimes P_Y gives a lower bound on mutual information for any critic T(x,y)T(x, y):

I(X;Y)≥EPX,Y[T]−log⁡EPX⊗PY[eT],I(X; Y) \geq \mathbb{E}_{P_{X,Y}}[T] - \log \mathbb{E}_{P_X \otimes P_Y}\left[e^{T}\right],

whose optimal critic is pmi(x,y)\textrm{pmi}(x, y) up to an arbitrary additive constant. In practice, we estimate the first expectation by averaging TT over observed pairs and the second by averaging eTe^T over mismatched pairs from the same minibatch. Parameterizing TT with a neural network yields MINE (mutual information neural estimation) (Belghazi et al., 2018).

25.7.3.3 The NWJ Bound#

Although the Donsker–Varadhan bound is tight in expectation, the logarithm outside EQ[eT]\mathbb{E}_Q[e^T] creates a subtle bias on minibatches. Because log⁡\log is concave, Jensen's inequality implies that the logarithm of a batch average is on average smaller than the logarithm of the true expectation. Subtracting a smaller number pushes the batch estimate T‾−log⁡eT‾\overline{T} - \log \overline{e^T} upward on average, an undesirable property for an estimator of a lower bound.

We can eliminate the logarithm using the elementary tangent inequality log⁡z≤z/e\log z \leq z/e, which holds for all z>0z > 0 with equality at z=ez = e. Applying it to Z=EQ[eT]Z = \mathbb{E}_Q[e^T] in (25.7.6) gives, for every critic TT,

I(X;Y)≥EPX,Y[T]−e−1 EPX⊗PY[eT].(25.7.7)I(X; Y) \geq \mathbb{E}_{P_{X,Y}}[T] - e^{-1}\, \mathbb{E}_{P_X \otimes P_Y}\left[e^{T}\right]. \tag{25.7.7}

This is the NWJ bound (Nguyen et al., 2010). For any fixed critic TT, NWJ is never larger than DV, matching it only when Z=eZ = e. It is tight at T∗=1+pmiT^* = 1 + \textrm{pmi}: whereas DV is invariant to adding a constant to the critic, NWJ pins that constant to 11. Writing e−1 EQ[eT]=EQ[eT−1]e^{-1}\, \mathbb{E}_Q[e^T] = \mathbb{E}_Q[e^{T-1}] shows that NWJ is simply the general f-divergence dual bound of Section 25.3.4 specialized to the KL divergence, DKL(P∥Q)≥EP[T]−EQ[eT−1]D_{\textrm{KL}}(P \| Q) \geq \mathbb{E}_P[T] - \mathbb{E}_Q[e^{T-1}], derived there from the convex conjugate of ulog⁡uu \log u. For KL divergence, Donsker–Varadhan strictly sharpens that general bound.

Because no logarithm wraps the second expectation, evaluating (25.7.7) on a minibatch yields an unbiased estimate of the lower bound. Unbiased, however, does not mean reliable. At the optimal critic, eT∗−1=epmie^{T^*-1} = e^{\textrm{pmi}} is the density ratio p(x,y)/(p(x)p(y))p(x,y)/(p(x)p(y)). Its expectation over independent pairs is 11, but when XX and YY are strongly dependent, that expectation is dominated by a tiny fraction of huge values mixed among many values near zero. Any batch that happens to miss those rare spikes severely underestimates the second term and therefore overshoots the bound. We will quantify and measure this behavior in Section 25.7.4.4.

25.7.4 InfoNCE#

25.7.4.1 The Contrastive Loss#

Because the exponential term eTe^T in the DV and NWJ bounds is unnormalized, a single extreme pair can dominate an entire batch. InfoNCE avoids this instability by normalizing within the batch, forcing the candidates to compete against one another. Specifically, we draw one positive pair (x,y+)∼PX,Y(x, y^+) \sim P_{X,Y}, calling xx the anchor, together with N−1N - 1 negatives y2,…,yNy_2, \ldots, y_N drawn independently from the marginal PYP_Y. We score all NN candidates with a critic T(x,y)T(x, y) and pass the scores through a softmax to predict which candidate is the true partner. The InfoNCE loss (van den Oord et al., 2018) is the resulting cross-entropy:

LNCE=−E[log⁡eT(x,y+)eT(x,y+)+∑j=2NeT(x,yj)],(25.7.8)\mathcal{L}_{\textrm{NCE}} = -\mathbb{E}\left[\log \frac{e^{T(x, y^+)}}{e^{T(x, y^+)} + \sum_{j=2}^{N} e^{T(x, y_j)}}\right], \tag{25.7.8}

where the expectation runs over both the positive pair and the N−1N - 1 negatives. The corresponding mutual information estimate subtracts this loss from log⁡N\log N:

I^NCE=log⁡N−LNCE.(25.7.9)\hat{I}_{\textrm{NCE}} = \log N - \mathcal{L}_{\textrm{NCE}}. \tag{25.7.9}

Some papers write the denominator as an average 1N∑j=1NeT(x,yj)\frac{1}{N}\sum_{j=1}^N e^{T(x, y_j)}, in which case the expected log ratio directly equals I^NCE\hat{I}_{\textrm{NCE}}. Conceptually, LNCE\mathcal{L}_{\textrm{NCE}} is simply an NN-class cross-entropy whose classes are the other examples in the batch rather than fixed labels. This is the training objective behind CPC, SimCLR, and CLIP (van den Oord et al., 2018; Chen et al., 2020; Radford et al., 2021), where xx and yy are two views or two modalities of the same example and the remaining examples in the batch serve as negatives.

Figure 25.7.2:

The InfoNCE task. Left: an anchor xx is scored by the critic against its positive partner y+y^+, drawn jointly with it, and N−1N-1 negatives drawn independently from the marginal; the rays carry the scores T(x,yj)T(x, y_j). Right: a softmax over the NN scores must identify the positive. The resulting cross-entropy certifies I(X;Y)≥log⁡N−LNCEI(X;Y) \geq \log N - \mathcal{L}_{\textrm{NCE}}, a bound that can never exceed log⁡N\log N.

Figure 25.7.2 illustrates the setup. In the smallest nontrivial case, N=2N = 2, the model faces a single negative and the loss reduces to binary cross-entropy: telling the true partner from one distractor. Even a perfect model can then demonstrate only that it chose the right option out of two, so the estimate is capped at ln⁡2=0.69\ln 2 = 0.69 nats.

25.7.4.2 The InfoNCE Bound#

The following proposition confirms that minimizing the InfoNCE loss certifies a lower bound on mutual information, and shows where the log⁡N\log N ceiling comes from (Poole et al., 2019).

Proposition (InfoNCE bound). For any measurable critic TT and any N≥1N \geq 1,

I(X;Y)≥log⁡N−LNCE.(25.7.10)I(X; Y) \geq \log N - \mathcal{L}_{\textrm{NCE}}. \tag{25.7.10}

Moreover, the right-hand side is at most log⁡N\log N.

Proof. Label the candidates y1=y+,y2,…,yNy_1 = y^+, y_2, \ldots, y_N and collect them into a single random bag V=(Y1,…,YN)V = (Y_1, \ldots, Y_N), where the negatives Y2:NY_{2:N} are independent of (X,Y1)(X, Y_1). The strategy is to replace YY with the bag VV, construct a normalized conditional distribution over bags given XX, and invoke the Barber–Agakov bound.

Step 1: independent negatives add no information. By the chain rule for mutual information (Section 25.6), I(X;Y1,Y2:N)=I(X;Y1)+I(X;Y2:N∣Y1)I(X; Y_1, Y_{2:N}) = I(X; Y_1) + I(X; Y_{2:N} \mid Y_1). Because Y2:NY_{2:N} is independent of (X,Y1)(X, Y_1), it remains independent of XX given Y1Y_1. The second term is therefore 00, giving I(X;V)=I(X;Y)I(X; V) = I(X; Y).

Step 2: the softmax ratio defines a normalized model. Here is the key calculation. Define the rescaled softmax score

γ(x,v)=eT(x,y1)1N∑j=1NeT(x,yj),\gamma(x, v) = \frac{e^{T(x, y_1)}}{\frac{1}{N}\sum_{j=1}^N e^{T(x, y_j)}},

which takes values in (0,N](0, N]. Let p(v)p(v) be the distribution of a bag of NN independent draws from PYP_Y, including the first slot. Because all NN entries are i.i.d., permuting them leaves p(v)p(v) unchanged. Consequently, all NN ratios eT(x,Yi)/(1N∑jeT(x,Yj))e^{T(x, Y_i)} / \left(\frac{1}{N}\sum_j e^{T(x, Y_j)}\right) have the same expectation under p(v)p(v), and for every fixed xx we have

Ep(v)[γ(x,V)]=1N∑i=1NEp(v)[eT(x,Yi)1N∑jeT(x,Yj)]=Ep(v)[1N∑ieT(x,Yi)1N∑jeT(x,Yj)]=1.\begin{aligned} \mathbb{E}_{p(v)}\left[\gamma(x, V)\right] &= \frac{1}{N}\sum_{i=1}^{N} \mathbb{E}_{p(v)}\left[\frac{e^{T(x, Y_i)}}{\frac{1}{N}\sum_{j} e^{T(x, Y_j)}}\right] \\ &= \mathbb{E}_{p(v)}\left[\frac{\frac{1}{N}\sum_{i} e^{T(x, Y_i)}}{\frac{1}{N}\sum_{j} e^{T(x, Y_j)}}\right] = 1. \end{aligned}

Thus q(v∣x)=p(v) γ(x,v)q(v \mid x) = p(v)\, \gamma(x, v) is a valid conditional probability distribution over bags.

Step 3: apply Barber–Agakov to the bag. Because Y1Y_1 has marginal PYP_Y and is independent of Y2:NY_{2:N}, the marginal distribution of VV is also p(v)p(v). Applying the ratio form of (25.7.5) to (X,V)(X, V) with the roles of the two variables swapped (using the symmetry of II) gives

I(X;V)≥Ep(x,v)[log⁡q(v∣x)p(v)]=E[log⁡γ(X,V)]=log⁡N−LNCE.I(X; V) \geq \mathbb{E}_{p(x, v)}\left[\log \frac{q(v \mid x)}{p(v)}\right] = \mathbb{E}\left[\log \gamma(X, V)\right] = \log N - \mathcal{L}_{\textrm{NCE}}.

The final equality holds because log⁡γ\log \gamma equals log⁡N\log N plus the log-softmax probability assigned to the positive. Combining this with Step 1 proves the bound. Finally, since the softmax probability of the positive cannot exceed 11, we have LNCE≥0\mathcal{L}_{\textrm{NCE}} \geq 0, and hence the right-hand side is at most log⁡N\log N. ■\blacksquare

Intuitively, picking the true partner out of NN candidates, even with zero error, demonstrates at most log⁡N\log N nats: the information contained in a single choice among NN alternatives. No critic can squeeze more information out of that task, just as a 1010-class classifier could never certify more than ln⁡10\ln 10 nats. Increasing NN raises the ceiling, which is one motivation given for the large batches of contrastive methods such as CPC, SimCLR, and CLIP. It is not the whole story: as we will see at the end of the section, a tighter bound is not what makes a representation good. The loss is minimized by any critic of the form T∗(x,y)=pmi(x,y)+c(x)T^*(x, y) = \textrm{pmi}(x, y) + c(x), where c(x)c(x) is an arbitrary function of the anchor alone (Exercise 5).

25.7.4.3 The Ceiling with an Exact Critic#

One might naturally expect that with the exact critic T=pmiT = \textrm{pmi}, I^NCE\hat{I}_{\textrm{NCE}} tracks the true I(X;Y)I(X; Y) all the way up to log⁡N\log N and then flattens out at a sharp corner. Substituting T=pmiT = \textrm{pmi} into (25.7.9) reveals a softer, and more sobering, behavior:

I^NCE=I(X;Y)−E[log⁡1N∑j=1Nepmi(x,yj)].(25.7.11)\hat{I}_{\textrm{NCE}} = I(X; Y) - \mathbb{E}\left[\log \frac{1}{N}\sum_{j=1}^N e^{\textrm{pmi}(x, y_j)}\right]. \tag{25.7.11}

The estimate equals the true mutual information minus a slack term, which is nonnegative by the proposition. We can estimate the size of this slack with a quick back-of-the-envelope calculation. Inside the logarithm sits an average of NN terms: the N−1N - 1 negatives are independent of xx, so each has mean 11 (the second identity we checked at the start of the section), contributing roughly 11 to the average; meanwhile, the positive contributes epmi(x,y+)/Ne^{\textrm{pmi}(x, y^+)}/N, which is roughly eI/Ne^I / N for a typical pair. Replacing the random average by this typical value yields

I^NCE≈I−log⁡(1+eIN)=−log⁡(e−I+1N).(25.7.12)\hat{I}_{\textrm{NCE}} \approx I - \log\left(1 + \frac{e^I}{N}\right) = -\log\left(e^{-I} + \frac{1}{N}\right). \tag{25.7.12}

The right-hand side is a smooth minimum of II and log⁡N\log N. It tracks II closely when eI≪Ne^I \ll N, approaches log⁡N\log N when eI≫Ne^I \gg N, and bends well below both in the transition region: right at I=log⁡NI = \log N, it reads log⁡N−log⁡2\log N - \log 2, falling 0.690.69 nats short. Our initial guess forgot that the positive sits inside its own denominator alongside negatives that average 11; the positive dominates the denominator only once eIe^I greatly exceeds NN.

Because replacing a heavy-tailed average with its mean is a rough heuristic, we should check (25.7.12) empirically. For N=128N = 128 and I=4I = 4, it predicts 3.63.6 nats even though the ceiling ln⁡128=4.85\ln 128 = 4.85 still looks comfortably far away. Below, we score all N×NN \times N pairs in a batch simultaneously: row ii pairs anchor xix_i with every yjy_j, so its diagonal entry is the positive and the N−1N - 1 off-diagonal entries are its negatives. Although the rows share candidates, the bound remains valid (Exercise 6). Let us sweep I(X;Y)I(X; Y) for N=16N = 16, 128128, and 10241024 (ceilings 2.772.77, 4.854.85, and 6.936.93 nats) and compare the empirical estimates against the truth.

def infonce_bound(f):
    """log N minus the InfoNCE loss of an N x N score matrix f[i, j]."""
    return np.log(len(f)) + np.mean(np.diag(f) - logsumexp(f, axis=1))

def exact_scores(x, y, rho):
    """The exact critic T = pmi on all N x N pairs (x_i, y_j) of a batch."""
    return pmi_gauss(x[:, None], y[None, :], rho)

true_mi = np.array([0.25, 0.5, 1, 1.5, 2, 2.5, 3, 4, 5, 6, 7])
rhos = np.sqrt(1 - np.exp(-2 * true_mi))                 # invert mi_gauss
Ns = (16, 128, 1024)
ests = np.array([[np.mean([infonce_bound(exact_scores(*gauss_pair(rng, r, N), r))
                            for _ in range(200 if N <= 128 else 50)])
                  for r in rhos] for N in Ns])              # (N, level)
ceilings = [[np.log(N)] * len(true_mi) for N in Ns]
d2l.plot(true_mi, [*ests, true_mi, *ceilings], 'true I(X;Y) (nats)',
         'InfoNCE estimate (nats)',
         legend=[f'N = {N}' for N in Ns] + ['truth'] + [f'ln {N}' for N in Ns],
         fmts=('C0-', 'C1-', 'C2-', 'k--', 'C0:', 'C1:', 'C2:'),
         figsize=(5.5, 3), legend_loc='outside')
for I in (1, 4, 7):
    k = list(true_mi).index(I)
    print(f'I = {I}:  ' + '   '.join(f'N = {N}: {e:.2f}'
                                     for N, e in zip(Ns, ests[:, k])))
I = 1:  N = 16: 0.89   N = 128: 0.98   N = 1024: 1.00
I = 4:  N = 16: 2.56   N = 128: 3.67   N = 1024: 3.95
I = 7:  N = 16: 2.76   N = 128: 4.76   N = 1024: 6.31

None of the curves has a sharp corner. Each peels away from the diagonal early and bends smoothly toward its ceiling, with all nine printed values falling within 0.10.1 nat of (25.7.12). At I=1I = 1, every batch size lands within about 0.10.1 nat of the truth. By I=4I = 4, a batch of 128128 reports only 3.73.7 nats, and even N=1024N = 1024 begins to lag slightly behind. At I=7I = 7, just past its ceiling of 6.936.93, N=1024N = 1024 reports only 6.36.3.

Two exact facts explain why this happens. First, the average inside the logarithm is at least the positive's own term epmi(x,y+)/Ne^{\textrm{pmi}(x, y^+)}/N, so the slack is at least E[pmi(x,y+)]−log⁡N=I−log⁡N\mathbb{E}[\textrm{pmi}(x, y^+)] - \log N = I - \log N, recovering the log⁡N\log N ceiling. Second, the slack disappears only in the limit N→∞N \to \infty (Exercise 5). The hard ceiling log⁡N\log N is merely the crudest symptom of this finite-batch slack.

This smooth compression also makes the estimate difficult to invert. With N=128N = 128, a reading of 3.73.7 corresponds to 44 nats and a reading near 4.754.75 corresponds to 77 nats, squeezing every true value from 44 nats to infinity into the top 1.21.2 nats of the scale.

Image classification puts these numbers in perspective. Suppose two views of an image each determine its class among 1,0001{,}000 balanced categories. Because the label is a function of either view, the data-processing inequality (Section 25.6.2.2) implies that the two views share at least the entropy of the label, ln⁡1000=6.91\ln 1000 = 6.91 nats. An InfoNCE loss with N=128N = 128 candidates can never certify anything close to that, and even with N=1024N = 1024 the estimate reads only 6.36.3 when the true shared information is 77. Whether two views retain enough information for fine-grained classification simply cannot be read off such a number.

25.7.4.4 Exact Critics Compared#

We can now compare DV, NWJ, and InfoNCE on equal footing: batch size N=128N = 128, each given the exact optimal critic T∗=1+pmiT^* = 1 + \textrm{pmi} (adding a constant leaves InfoNCE unchanged). DV and NWJ draw their independent pairs from the NN mismatched pairs of the batch, and the heavy-tailed behavior we noted earlier lets us predict what will happen before running a single line of code.

A typical joint pair has pmi close to II. Under the product distribution PX⊗PYP_X \otimes P_Y, such a pair occurs with probability roughly e−Ie^{-I}, since p(x) p(y)=p(x,y) e−pmip(x)\,p(y) = p(x, y)\,e^{-\textrm{pmi}}. In other words, roughly one mismatched pair in eIe^I looks plausible enough to pass for a genuine pair. Each of these rare pairs carries a huge weight epmi≈eIe^{\textrm{pmi}} \approx e^I, and together they account for the entire expectation E[epmi]=1\mathbb{E}[e^{\textrm{pmi}}] = 1. A batch of size NN contains roughly Ne−IN e^{-I} such pairs on average: about six at I=3I = 3, two at I=4I = 4, and only 0.30.3 at I=6I = 6.

As long as a batch contains several rare pairs, its sample average of epmie^{\textrm{pmi}} stays near 11 and all three bounds should agree. Once the expected count Ne−IN e^{-I} drops below 11, most batches contain no rare pairs at all. Call such a batch starved. On a starved batch, the average of epmie^{\textrm{pmi}} is close to zero: NWJ then reports the batch mean of T∗T^* minus almost nothing (about I+1I + 1, one nat too high), while DV subtracts the logarithm of a tiny number and overshoots by many nats.

Because NWJ is unbiased, something must balance those starved batches. That counterweight is a hit batch, one that happens to contain a mismatched pair with epmi≥Ne^{\textrm{pmi}} \geq N. A single such pair adds at least 11 to the batch mean of epmie^{\textrm{pmi}} and drags NWJ down by at least a nat, leaving it near II or occasionally far below. At I=6I = 6, a rare pair has epmi≈e6=403>Ne^{\textrm{pmi}} \approx e^6 = 403 > N, so every batch that contains one is a hit batch. With an average of 0.30.3 rare pairs per batch, roughly one batch in four should be hit, while most of the remaining batches are starved.

InfoNCE behaves completely differently. Because it normalizes within the batch, a convincing negative affects at most one row of the softmax. It should stay steady right where (25.7.12) predicts, around 4.64.6 nats at I=6I = 6. Notice that the crossover Ne−I≈1N e^{-I} \approx 1 occurs at I≈ln⁡NI \approx \ln N. The logarithm of the batch size limits DV and NWJ just as much as it limits InfoNCE; DV and NWJ simply hide that limit behind exploding variance instead of a visible ceiling.

Let us test these predictions by drawing 200200 batches at each level of II. Because heavy-tailed distributions distort sample means and standard deviations, we report the median and interquartile range for each bound, along with the sample mean for NWJ. The final two columns track the fraction of starved batches (mean epmi<0.1e^{\textrm{pmi}} \lt 0.1) and the fraction of hit batches (max⁡epmi≥N\max e^{\textrm{pmi}} \geq N), and the plot compares the three medians.

def quartiles(a):
    """Median and quartiles of a list of batch values, as text."""
    q1, med, q3 = np.percentile(a, [25, 50, 75])
    return f'{med:5.2f} [{q1:5.2f}, {q3:5.2f}]'

N, true_mi = 128, np.array([0.5, 1, 2, 3, 4, 5, 6])
medians = []
# Last two columns: share of batches whose mean e^pmi over mismatched pairs
# is below 0.1, and share holding a mismatched pair with e^pmi >= N.
print(f'{"I":>3}  {"DV median [IQR]":20}  {"NWJ median [IQR]":20}  '
      f'{"NWJ mean":>8}  {"InfoNCE median [IQR]":20}  {"<0.1":>4}  {">=N":>4}')
for I in true_mi:
    rho, batches = np.sqrt(1 - np.exp(-2 * I)), []
    for _ in range(200):
        x, y = gauss_pair(rng, rho, N)
        T_joint = 1 + pmi_gauss(x, y, rho)               # T* on true pairs
        T_prod = 1 + pmi_gauss(x, np.roll(y, 1), rho)    # T* on mismatched
        e_pmi = np.exp(T_prod - 1)                       # e^pmi, mismatched
        batches.append((T_joint.mean() - (logsumexp(T_prod) - np.log(N)),  # DV
                        T_joint.mean() - e_pmi.mean(),                     # NWJ
                        infonce_bound(exact_scores(x, y, rho)),
                        e_pmi.mean() < 0.1, e_pmi.max() >= N))
    dv, nwj, nce, low, rare = np.array(batches).T
    medians.append([np.median(a) for a in (dv, nwj, nce)])
    print(f'{I:3.1f}  {quartiles(dv)}  {quartiles(nwj)}  {nwj.mean():8.2f}'
          f'  {quartiles(nce)}  {low.mean():4.0%}  {rare.mean():4.0%}')
d2l.plot(true_mi, [*np.array(medians).T, true_mi, [np.log(N)] * len(true_mi)],
         'true I(X;Y) (nats)', 'median batch value (nats)',
         legend=['DV', 'NWJ', 'InfoNCE', 'truth', 'ln N'], ylim=[0, 8],
         fmts=('C0-', 'C1-', 'C2-', 'k--', 'k:'), figsize=(5.5, 3),
         legend_loc='outside')
  I  DV median [IQR]       NWJ median [IQR]      NWJ mean  InfoNCE median [IQR]  <0.1   >=N
0.5   0.51 [ 0.43,  0.58]   0.51 [ 0.43,  0.58]      0.50   0.50 [ 0.45,  0.54]    0%    0%
1.0   0.99 [ 0.88,  1.13]   0.99 [ 0.88,  1.12]      0.99   0.99 [ 0.92,  1.04]    0%    0%
2.0   2.02 [ 1.81,  2.17]   2.01 [ 1.80,  2.16]      1.97   1.95 [ 1.90,  2.01]    0%    1%
3.0   3.08 [ 2.75,  3.47]   3.08 [ 2.70,  3.36]      3.02   2.85 [ 2.79,  2.92]    0%    2%
4.0   4.23 [ 3.74,  4.95]   4.20 [ 3.71,  4.57]      3.76   3.68 [ 3.62,  3.74]    8%    6%
5.0   5.21 [ 4.54,  8.28]   5.18 [ 4.44,  5.94]      4.83   4.27 [ 4.22,  4.31]   32%   36%
6.0   9.47 [ 5.33, 29.04]   6.91 [ 5.10,  7.00]      5.93   4.60 [ 4.58,  4.64]   57%   28%

Up to I=3I = 3, all three medians stay within about 0.20.2 nat of the truth, almost no batch is starved or hit, and InfoNCE displays the tightest spread. Beyond that point, starved batches appear right on schedule: at most about one in ten at I=4I = 4, roughly a third at I=5I = 5, and more than half at I=6I = 6.

In the I=6I = 6 row, NWJ's median climbs to about 7=I+17 = I + 1 with its upper quartile sitting right on top of it, meaning that half of all batches overshoot by roughly a full nat. The quarter or so of hit batches drag the sample mean back to within about half a nat of 66. DV fares even worse: its median sits several nats above the truth, and its upper quartile reaches into the tens, sending its curve right off the top of the plot. InfoNCE, by contrast, reads a rock-steady 4.64.6 nats with an interquartile range under 0.10.1.

We can also calculate NWJ's spread analytically. Its mismatched-pair term is a batch average of epmie^{\textrm{pmi}}, whose variance is (e2I−1)/N(e^{2I} - 1)/N. At I=6I = 6 and N=128N = 128, that works out to a standard deviation of 3636 nats, driven by extreme hit batches so rare that 200200 draws rarely contain one (Exercise 1).

None of this contradicts the variational inequalities, which hold for population expectations. Rather, it shows how variational bounds reconcile with the distribution-free limit of Section 25.7.2.4. InfoNCE cannot exceed log⁡N\log N (with NN at most the sample size), so it obeys the logarithmic limit by construction. DV and NWJ are free to report larger numbers, but whenever they do, their batch estimates cease to be reliable lower bounds.

25.7.4.5 Training a Critic#

In real applications we do not know the true pmi, so the critic must be learned from data. When a contrastive loss reports less than the true mutual information, how do we tell whether the shortfall comes from an imperfect critic or from the slack of the bound itself? To answer this, let us train a dual-encoder critic of the exact form used by CLIP and SimCLR: two small networks g,h:R→R16g, h : \mathbb{R} \to \mathbb{R}^{16} embed xx and yy, and the critic is their inner product T(x,y)=g(x)⊤h(y)T(x, y) = g(x)^\top h(y). Computing all N×NN \times N scores for a batch then takes just one matrix multiplication of the two embedding matrices, reducing N2N^2 network evaluations to 2N2N. We generate two disjoint pools of 4,0964{,}096 pairs at ρ=0.99\rho = 0.99 (true information 1.961.96 nats), one for training and one for evaluation.

rho, n_pool = 0.99, 4096
x_tr, y_tr = (a.astype(np.float32) for a in gauss_pair(rng, rho, n_pool))
x_ev, y_ev = (a.astype(np.float32) for a in gauss_pair(rng, rho, n_pool))

Each encoder is a multilayer perceptron with two hidden layers of 6464 ReLU units and Glorot-uniform initialization. On the resulting N×NN \times N score matrix, the InfoNCE loss is simply standard multi-class cross-entropy where the target class for row ii is ii, the index of its diagonal positive pair.

def encoder(d_out=16, hidden=64):
    """An MLP that embeds a scalar in d_out dimensions."""
    net = torch.nn.Sequential(torch.nn.Linear(1, hidden), torch.nn.ReLU(),
                              torch.nn.Linear(hidden, hidden), torch.nn.ReLU(),
                              torch.nn.Linear(hidden, d_out))
    for layer in net[::2]:                          # the Linear layers
        torch.nn.init.xavier_uniform_(layer.weight)
        torch.nn.init.zeros_(layer.bias)
    return net

def scores(g, h, x, y):
    """All N x N critic values T(x_i, y_j) = g(x_i) . h(y_j)."""
    return g(x[:, None]) @ h(y[:, None]).T

def infonce_loss(f):
    """Cross-entropy of each row's softmax at its positive, the diagonal."""
    return torch.nn.functional.cross_entropy(f, torch.arange(len(f)))

g, h = encoder(), encoder()

We train for 1,0001{,}000 Adam steps with learning rate 10−310^{-3} on minibatches of N=128N = 128 pairs sampled from the training pool, then wrap the trained model as critic_np so it accepts NumPy arrays just like exact_scores.

opt = torch.optim.Adam([*g.parameters(), *h.parameters()], lr=1e-3)
N = 128
for step in range(1000):
    idx = rng.choice(n_pool, N, replace=False)
    loss = infonce_loss(scores(g, h, torch.tensor(x_tr[idx]),
                               torch.tensor(y_tr[idx])))
    opt.zero_grad()
    loss.backward()
    opt.step()

def critic_np(a, b):
    """The trained critic on NumPy inputs, as an N x N NumPy array."""
    with torch.inference_mode():
        return scores(g, h, torch.tensor(a), torch.tensor(b)).numpy()

To separate critic error from bound slack cleanly, we evaluate both the learned critic and the exact critic on the same held-out batches. Below, we partition the evaluation pool into disjoint batches of size N∈{2,8,32,128}N \in \{2, 8, 32, 128\} and average the InfoNCE bound across them. Notice that a critic trained at N=128N = 128 can be evaluated at any other batch size, because the optimal critic pmi(x,y)+c(x)\textrm{pmi}(x, y) + c(x) does not depend on NN.

def infonce_eval(score, x, y, N):
    """Mean InfoNCE bound over the disjoint batches of N pairs in (x, y)."""
    return np.mean([infonce_bound(score(x[i:i + N], y[i:i + N]))
                    for i in range(0, len(x), N)])

exact_np = lambda a, b: exact_scores(a, b, rho)   # the exact critic T = pmi

print('   N   ln N   learned   exact')
for N_ev in (2, 8, 32, 128):
    print(f'{N_ev:4d}  {np.log(N_ev):5.2f}  '
          f'{infonce_eval(critic_np, x_ev, y_ev, N_ev):7.2f}  '
          f'{infonce_eval(exact_np, x_ev, y_ev, N_ev):6.2f}')
print(f'true I(X;Y) = {mi_gauss(rho):.2f} nats')
   N   ln N   learned   exact
   2   0.69     0.58    0.58
   8   2.08     1.42    1.42
  32   3.47     1.78    1.80
 128   4.85     1.89    1.91
true I(X;Y) = 1.96 nats

Across every batch size, the learned critic matches the exact critic to within a few hundredths of a nat. The remaining gap to the true 1.961.96 nats therefore belongs entirely to the bound, closing gradually as NN increases until both critics reach about 1.91.9 nats at N=128N = 128. Look closely at N=8N = 8: the ceiling ln⁡8=2.08\ln 8 = 2.08 already sits above the true value of 1.961.96, so the shortfall of roughly 0.550.55 nat is not caused by hitting the ceiling. It is the smooth-minimum slack of the bound, which (25.7.12) predicts at about 0.60.6 nat. Of course, a scalar Gaussian pair gives the critic an easy task; in high dimensions, critic approximation error is no longer negligible, and without a known ground truth the two sources of error cannot be disentangled.

Contrastive systems such as SimCLR modify the critic slightly: they normalize the embeddings zxz_x and zyz_y to unit length and divide their cosine similarity by a temperature τ\tau, setting T(x,y)=sim(zx,zy)/τT(x, y) = \textrm{sim}(z_x, z_y)/\tau (Chen et al., 2020). The temperature controls how sharply the softmax separates candidates, and it introduces a second ceiling of its own. Because cosine similarity lies in [−1,1][-1, 1], no two scores can differ by more than 2/τ2/\tau, so a cosine critic can never certify 2/τ2/\tau nats or more regardless of how large NN is (Exercise 3): that caps the bound below 44 nats at τ=0.5\tau = 0.5 and below 2020 nats at τ=0.1\tau = 0.1. A large temperature can therefore bottle up the bound well before the batch size does.

In practice, which estimator should we choose? For a pair of one- or two-dimensional variables sharing at most a few nats, nearest-neighbor counting is the right tool: KSG landed within about 0.10.1 nat of the truth in that regime. For high-dimensional vectors, none of the estimators in this section can accurately measure a large mutual information, so the question shifts from how much information two views share to at least how much. InfoNCE answers that question reliably: train it with as many negatives as memory allows and interpret log⁡N−LNCE\log N - \mathcal{L}_{\textrm{NCE}} strictly as a lower bound. A reading within a nat or so of log⁡N\log N tells us only that the views share at least that much, while a low reading could simply reflect a weak critic. As for DV and NWJ, they have no sweet spot of their own: several nats below log⁡N\log N, where their batch estimates remain trustworthy, InfoNCE is nearly as accurate and far steadier; higher up, their typical minibatch overshoots.

Finally, a tighter lower bound does not automatically produce a better representation. Tschannen et al. (2020) showed that downstream task performance correlates poorly with the tightness of the mutual information bound being maximized: looser bounds often yield stronger representations, and architectural choices for the encoder and critic matter at least as much as the estimated information. Two fundamental questions thus remain open: how to estimate large mutual information reliably in high dimensions, and why maximizing loose variational bounds still produces such effective representations.

25.7.5 Summary#

From finite samples alone, mutual information can be measured directly only when the variables are low-dimensional and the shared information is modest. Beyond that regime, every estimator is constrained by the logarithm of the number of outcomes it can distinguish: log⁡b\log b for a histogram with bb bins, roughly log⁡(n/m)\log(n/m) for KSG nearest-neighbor counts (which saturate far below even that ceiling in high dimensions), and O(log⁡n)O(\log n) for any distribution-free lower bound. Variational methods sidestep density estimation by maximizing a lower bound parameterized by a decoder or a critic. InfoNCE, the cross-entropy objective of contrastive learning, is low-variance and well behaved, yielding roughly −log⁡(e−I+1/N)-\log(e^{-I} + 1/N) with an exact critic and never exceeding log⁡N\log N for NN candidates. Donsker–Varadhan and NWJ have no hard ceiling, yet their minibatch estimates remain reliable only a couple of nats below log⁡N\log N. On our Gaussian benchmark, a learned dual-encoder critic matched the exact pmi critic to within a few hundredths of a nat, confirming that the observed gap belonged to the bound itself. Even so, the tightness of an information bound does not by itself predict the quality of a learned representation.

25.7.6 Exercises#

  1. Heavy tails of the exponentiated pmi. ● Let (X,Y)(X, Y) be the Gaussian pair with correlation ρ\rho, I=−12log⁡(1−ρ2)I = -\tfrac{1}{2}\log(1 - \rho^2), and Q=PX⊗PYQ = P_X \otimes P_Y. Under QQ the mean of epmie^{\textrm{pmi}} is 11 for every ρ\rho, although a typical independent pair has epmie^{\textrm{pmi}} near 00 when ρ\rho is close to 11.

    1. Show that EQ[e2 pmi]=∫p2/q=1/(1−ρ2)=e2I\mathbb{E}_Q[e^{2\,\textrm{pmi}}] = \int p^2/q = 1/(1 - \rho^2) = e^{2I}, so that epmie^{\textrm{pmi}} has variance e2I−1e^{2I} - 1 under QQ. Hint: the integrand is proportional to a Gaussian density with precision matrix 2Σ−1−I2\boldsymbol{\Sigma}^{-1} - \mathbf{I}, where Σ\boldsymbol{\Sigma} is the covariance of the pair, and det⁡(2Σ−1−I)=1\det(2\boldsymbol{\Sigma}^{-1} - \mathbf{I}) = 1.
    2. A random permutation of a batch leaves on average one yy paired with its own xx. Show that such a fixed point adds epmi/Ne^{\textrm{pmi}}/N to the batch mean of epmie^{\textrm{pmi}} over the permuted pairs, with expectation e2I/Ne^{2I}/N: 0.430.43, 2323 and 12701270 at I=2,4,6I = 2, 4, 6 with N=128N = 128. Why does np.roll avoid this?
    3. For the NWJ critic T∗=1+pmiT^* = 1 + \textrm{pmi}, show that the batch estimate has mean II when the mismatched pairs are independent draws, and that its mismatched-pair term then has variance (e2I−1)/N(e^{2I} - 1)/N: standard deviations of 0.650.65, 4.84.8 and 3636 nats at I=2,4,6I = 2, 4, 6 with N=128N = 128. Show that the rolled pairs (xj,yj+1)(x_j, y_{j+1}) of the cell give the same variance for N≥3N \geq 3, although neighboring terms share a variable. Hint: condition on the shared pair.
  2. Barber–Agakov with a Gaussian decoder. Take the standard bivariate Gaussian pair with correlation ρ\rho, whose information is −12log⁡(1−ρ2)-\tfrac{1}{2}\log(1 - \rho^2), and the decoders q(x∣y)=N(x;ay,s2)q(x \mid y) = \mathcal{N}(x; a y, s^2) with parameters a∈Ra \in \mathbb{R} and s2>0s^2 > 0. In the bound (25.7.5), use the differential entropy h(X)=12log⁡(2πe)h(X) = \tfrac{1}{2}\log(2\pi e).

    1. Evaluate the right-hand side of (25.7.5) as a function of aa and s2s^2. Maximize it over both parameters and show that the maximum is the true information.
    2. The text fixes s2=1s^2 = 1, which is what training with the squared error alone amounts to, and finds the best bound ρ2/2\rho^2/2. Show that its gap to the true information is DKL(N(0,1−ρ2) ∥ N(0,1))D_{\textrm{KL}}\big(\mathcal{N}(0, 1 - \rho^2) \,\|\, \mathcal{N}(0, 1)\big), as the proof of the proposition says it must be. How does the gap behave as ρ→1\rho \to 1?
    3. Let x^(y)\hat{x}(y) be any predictor of XX with mean squared error DD. Use the decoder N(x;x^(y),D)\mathcal{N}(x; \hat{x}(y), D) to show that I(X;Y)≥−12log⁡DI(X; Y) \geq -\tfrac{1}{2}\log D. What is the corresponding bound when X∼N(0,v)X \sim \mathcal{N}(0, v)? Compare it with the Gaussian rate–distortion function R(D)=12log⁡(v/D)R(D) = \tfrac{1}{2}\log(v/D) for D<vD \lt v of Section 25.6.3.2, the least information any description of XX needs to reach squared error DD.
  3. Temperature of a cosine critic. SimCLR-style systems score candidates with T(x,y)=s(x,y)/τT(x, y) = s(x, y)/\tau, where s(x,y)=sim(zx,zy)∈[−1,1]s(x, y) = \textrm{sim}(z_x, z_y) \in [-1, 1] is a cosine similarity and τ>0\tau > 0 is the temperature. For one anchor xx, write sj=s(x,yj)s_j = s(x, y_j), with y1=y+y_1 = y^+ the positive, and let ℓ\ell be the loss inside the expectation (25.7.8).

    1. Show that LNCE≥log⁡(1+(N−1)e−2/τ)\mathcal{L}_{\textrm{NCE}} \geq \log\big(1 + (N-1)e^{-2/\tau}\big), and hence I^NCE<2/τ\hat{I}_{\textrm{NCE}} \lt 2/\tau for every NN. Evaluate the ceiling log⁡N−log⁡(1+(N−1)e−2/τ)\log N - \log\big(1 + (N-1)e^{-2/\tau}\big) for N=4096N = 4096 and τ∈{1,0.5,0.1}\tau \in \{1, 0.5, 0.1\} (you should find about 2.02.0, 4.04.0 and 8.38.3 nats). When does the temperature rather than the batch size limit the bound?
    2. Show that ∂ℓ/∂sj=pj/τ\partial \ell / \partial s_j = p_j/\tau for every negative j≥2j \geq 2, where pjp_j is the softmax probability of candidate jj. Express ∂ℓ/∂s1\partial \ell / \partial s_1 through the pjp_j.
    3. Show that τℓ→max⁡{0,max⁡j≥2sj−s1}\tau \ell \to \max\{0, \max_{j \geq 2} s_j - s_1\} as τ→0\tau \to 0, and that
ℓ=log⁡N−1τ(s1−1N∑j=1Nsj)+O(τ−2)as τ→∞.(25.7.13)\ell = \log N - \frac{1}{\tau}\Big(s_1 - \frac{1}{N}\sum_{j=1}^N s_j\Big) + O(\tau^{-2}) \quad \textrm{as } \tau \to \infty. \tag{25.7.13}

Which negatives drive the gradient in each limit (Wang and Liu, 2021)?

  1. Entropy bounds from samples. ● Section 25.7.2.4 states the theorem of McAllester and Stratos (2020) informally and proves a version of it for entropy; this problem sharpens and applies that proof. Draw a sample SS of nn i.i.d. values from a discrete distribution pp. The type of SS records, for each i≥1i \geq 1, how many distinct values occur exactly ii times in SS; it forgets which values these are. Let BB be a function of the type that is a lower confidence bound for every discrete distribution: PS∼pn(B≤H(p))≥0.95P_{S \sim p^n}\big(B \leq H(p)\big) \geq 0.95 for every pp. Let T0\mathcal{T}_0 be the type of a sample of nn distinct values.

    1. The text applies the guarantee to the uniform distribution on n2n^2 values. Show that any integer M≥n2/1.9M \geq n^2/1.9 serves as well, so that B(T0)≤log⁡MB(\mathcal{T}_0) \leq \log M. By how much does this improve on 2log⁡n2 \log n?
    2. Let pp be uniform on M=2256M = 2^{256} values. How large must nn be before 2log⁡n2 \log n reaches H(p)H(p)? What does this say about measuring the entropy of a cryptographic key from samples?
  2. Optimal InfoNCE critic. ● For one anchor xx and one bag v=(y1,…,yN)v = (y_1, \ldots, y_N) with y1=y+y_1 = y^+, write ℓ(x,v)=−log⁡(eT(x,y1)/∑j=1NeT(x,yj))\ell(x, v) = -\log\big(e^{T(x, y_1)} / \sum_{j=1}^N e^{T(x, y_j)}\big), so that LNCE\mathcal{L}_{\textrm{NCE}} of (25.7.8) is its expectation.

    1. Show that replacing T(x,y)T(x, y) by T(x,y)+c(x)T(x, y) + c(x), for any function cc, leaves LNCE\mathcal{L}_{\textrm{NCE}} unchanged.
    2. Shuffle the bag so that the positive sits at a uniformly random position JJ and the other N−1N - 1 positions hold the negatives. Show that
P(J=i∣x,y1,…,yN)=epmi(x,yi)∑j=1Nepmi(x,yj).(25.7.14)P(J = i \mid x, y_1, \ldots, y_N) = \frac{e^{\textrm{pmi}(x, y_i)}}{\sum_{j=1}^N e^{\textrm{pmi}(x, y_j)}}. \tag{25.7.14}

Use Gibbs' inequality to conclude that every critic T(x,y)=pmi(x,y)+c(x)T(x, y) = \textrm{pmi}(x, y) + c(x) minimizes LNCE\mathcal{L}_{\textrm{NCE}}.

  1. For this critic, show that
I^NCE=I(X;Y)−E[log⁡1N∑j=1Nepmi(x,yj)].(25.7.15)\hat{I}_{\textrm{NCE}} = I(X;Y) - \mathbb{E}\left[\log \frac{1}{N}\sum_{j=1}^N e^{\textrm{pmi}(x, y_j)}\right]. \tag{25.7.15}

Use the law of large numbers to argue that the correction tends to zero as N→∞N \to \infty when I(X;Y)I(X;Y) is finite. Evaluate the correction by Monte Carlo at ρ=0.99\rho = 0.99 and N=8N = 8, and compare it with the gap between the exact-critic value (about 1.41.4) and the truth (1.961.96) in Section 25.7.4.5.

  1. The approximation (25.7.12) replaces the negatives' share of the average by 11 and pmi(x,y+)\textrm{pmi}(x, y^+) by II. Use Jensen's inequality to show that the first replacement lowers the estimate and the second raises it. Which of the two wins in the table of Section 25.7.4.3?
  1. In-batch negatives and the symmetric loss. The cells of Section 25.7.4.5 score all N×NN \times N pairs of a batch of NN independent pairs (xi,yi)(x_i, y_i) and use row ii's off-diagonal entries as the negatives of anchor xix_i.

    1. Show that each row satisfies the hypotheses of the InfoNCE proposition: its candidates yjy_j, j≠ij \neq i, are draws from PYP_Y that are independent of (xi,yi)(x_i, y_i). Conclude that the mean row loss L\mathcal{L} certifies I(X;Y)≥log⁡N−LI(X; Y) \geq \log N - \mathcal{L} in expectation.
    2. The rows share candidates, so their losses are dependent. Does this affect the validity of the bound, the expectation of the mean row loss, or its variance?
    3. CLIP uses the symmetric loss, the mean of the row-wise and the column-wise cross-entropies. Show that it bounds I(X;Y)I(X; Y) in the same way, with the same ceiling log⁡N\log N.
    4. A joint critic T(x,y)T(x, y), a network applied to the concatenated pair, needs N2N^2 network evaluations for the scores of a batch, where the separable critic g(x)⊤h(y)g(x)^\top h(y) needs 2N2N. Evaluate both counts for CLIP's batches of N=32,768N = 32{,}768. A separable critic cannot represent every function of the pair. Show that the pmi of the Gaussian pair is separable with embeddings of three dimensions, and that two suffice for InfoNCE.
  2. Negative sampling as shifted PMI. ● Skip-gram with negative sampling, the training method of word2vec, scores a center word ww and a context word oo by the inner product s(w,o)=uo⊤vws(w, o) = \mathbf{u}_o^\top \mathbf{v}_w of their vectors. It learns to tell the pairs that occur in a corpus from pairs whose context word is one of KK noise words drawn from a distribution PP. Let p(w,o)p(w, o) be the frequency of the pair among all (center, context) pairs of the corpus, with marginals p(w)p(w) and p(o)p(o). Averaged over the corpus, the loss is

ℓ=−∑w,op(w,o)log⁡σ(s(w,o))−K∑wp(w)∑oP(o)log⁡σ(−s(w,o)),(25.7.16)\ell = -\sum_{w, o} p(w, o) \log \sigma\big(s(w, o)\big) - K \sum_{w} p(w) \sum_{o} P(o) \log \sigma\big(-s(w, o)\big), \tag{25.7.16}

where σ(s)=1/(1+e−s)\sigma(s) = 1/(1 + e^{-s}) is the sigmoid. Assume that the embeddings have enough dimensions for every score s(w,o)s(w, o) to be chosen independently.

  1. Show that ℓ\ell is minimized at s∗(w,o)=log⁡p(w,o)p(w) P(o)−log⁡Ks^*(w, o) = \log \frac{p(w, o)}{p(w)\, P(o)} - \log K, which equals pmi(w,o)−log⁡K\textrm{pmi}(w, o) - \log K when PP is the unigram distribution p(o)p(o) (Levy and Goldberg, 2014).
  2. word2vec draws noise words with probability proportional to their count raised to the power 0.750.75. Show that s∗s^* then differs from pmi(w,o)−log⁡K\textrm{pmi}(w, o) - \log K by a term that depends on oo alone. For which context words is this term negative? How does it act on pairs of rare words, such as the "sri lanka" of Exercise 1 of Section 25.6?
  3. Compare s∗s^* with the optimal InfoNCE critic of Exercise 5b. Why does the binary classification of negative sampling fix the additive term that InfoNCE leaves free?
  1. [extended] Compression phase at small scale. ●● Shwartz-Ziv and Tishby (2017) studied fully connected tanh networks of widths 12-10-7-5-4-3-2 on the 40964096 binary input patterns of 1212 bits. For each hidden layer ZZ they binned every unit's activation into 3030 equal intervals of [−1,1][-1, 1] and computed I(X;Z)I(X;Z) and I(Y;Z)I(Y;Z) from the binned values. Section 25.7.2.5 describes the debate about the compression phase they reported.
    1. Let XX be uniform on the 40964096 patterns and let ZbinZ_{\textrm{bin}} be the binned layer of a deterministic network. Show that the binned estimate of I(X;Z)I(X;Z) equals H(Zbin)H(Z_{\textrm{bin}}) and never exceeds ln⁡4096≈8.32\ln 4096 \approx 8.32 nats. When does it decrease during training?
    2. Fix a random vector w∈R12\mathbf{w} \in \mathbb{R}^{12} and let Y=1Y = 1 when w⊤x\mathbf{w}^\top \mathbf{x} exceeds its median over the 40964096 patterns. Train the tanh network, with a softmax over its two output units, by SGD with the cross-entropy loss on a random 85%85\% of the patterns. Plot the trajectory of every hidden layer in the information plane (I(X;Z),I(Y;Z))\big(I(X;Z), I(Y;Z)\big) over training.
    3. Repeat (b) with ReLU hidden units, binning each unit into 3030 equal intervals between 00 and its largest activation over the run.
    4. Record the fraction of tanh units with ∣z∣>0.99|z| > 0.99 during training. Does the decrease of the binned I(X;Z)I(X;Z) in (b) track this fraction? Which conclusions about compression survive the change of activation in (c) (Saxe et al., 2018)?

Discussions