Estimating Mutual Information from Samples histograms & ranks · KSG nearest neighbors · McAllester–Stratos ceiling · DV & NWJ bounds · InfoNCE
Why InfoNCE Reports at Most ln N Nats
Motivation: Contrastive Learning vs. Measurement
In self-supervised contrastive learning (SimCLR, CLIP, CPC), a network scores an anchor view x against its positive partner y^+ and N - 1 negative distractors using the N-way cross-entropy loss \mathcal{L}_{\textrm{NCE}} \ge 0:
\hat{I}_{\textrm{NCE}} = \log N - \mathcal{L}_{\textrm{NCE}} \le \log N
The \log N batch-size ceiling: With N = 128 candidates, \hat{I}_{\textrm{NCE}} can never exceed \ln 128 = 4.85\text{ nats}, even if the two views share 50\text{ nats} of information—identifying 1 partner out of 128 candidates demonstrates at most \ln 128\text{ nats}.
Two distinct paradigms for sample-based MI:
Direct nonparametric counting (Histograms & KSG): Counts points in bins or adaptive neighbor boxes; accurate in 1\text{--}2 dimensions for small I, but breaks down in high dimensions.
Variational lower bounds (Barber–Agakov, DV, NWJ, InfoNCE): Trains an auxiliary decoder or critic T(x, y) to maximize a guaranteed population lower bound on I(X; Y).
Benchmark: The Gaussian Pair and Exp-PMI Tails
Ground Truth & Heavy-Tailed Ratios
To test estimators against an exact ground truth, we use the standard bivariate Gaussian pair (X, Y) with correlation \rho, where I(X; Y) = -\tfrac12\log(1 - \rho^2) and the pointwise mutual information is quadratic:
Two fundamental identities: Under joint draws (x, y) \sim P_{X,Y}, \mathbb{E}_{P_{X,Y}}[\textrm{pmi}(x, y)] = I(X; Y). Under independent draws (x, y) \sim P_X \otimes P_Y (formed by rolling y by one index), \mathbb{E}_{P_X \otimes P_Y}[e^{\textrm{pmi}(x, y)}] = 1, but its variance \textrm{Var}_{P_X \otimes P_Y}(e^{\textrm{pmi}}) = e^{2I} - 1 explodes with I.
I(X;Y) = 0.830 nats, mean pmi over pairs = 0.833
mean exp(pmi) over independent pairs = 0.994
Plug-In Histograms: Two Competing Biases
Coarse Binning vs. Finite-Sample Noise
Partitioning each axis into b equal-width bins and applying discrete MI to the b \times b empirical frequency table triggers two opposing errors plus a hard \log b ceiling:
Downward data-processing bias (coarse bins): By DPI, I(X_{\textrm{bin}}; Y_{\textrm{bin}}) \le I(X; Y). When bin width (\approx 9/b) exceeds the conditional spread \sqrt{1 - \rho^2}(0.14 at \rho = 0.99), binning destroys fine dependence.
Upward finite-sample bias (fine bins): Empirical cell frequencies fluctuate randomly around independence, and since D_{\textrm{KL}} \ge 0, sampling noise always masquerades as positive mutual information.
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
Coordinate Sensitivity and Rank-Based Binning
Fixing Grid Distortion in 1D
Although true I(X; Y) is invariant to any bijection X \mapsto \phi(X), cubing X \mapsto X^3 stretches the sample range to \pm 90 and packs 90\% of points into 2–3 equal-width bins. Binning sorted ranks restores exact invariance under monotone maps:
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
Why Histograms Stop at d = 2: For two d-dimensional vectors with b = 10 bins per axis, the joint grid has b^{2d} = 10^{2d} cells (10^{10} cells at d = 5), leaving almost every cell empty.
The KSG Adaptive Nearest-Neighbor Estimator
Local Chebyshev Boxes & Strips
The Kraskov–Stögbauer–Grassberger (KSG) estimator replaces fixed grids with local boxes adapted to sample density:
Joint Chebyshev (\ell_\infty) box: Around point i, find distance r_i to its m-th nearest neighbor under \max(\|x - x_i\|_\infty, \|y - y_i\|_\infty), enclosing fraction \approx m/n of joint mass.
Marginal strips at the exact same radius r_i: Count points n_x^{(i)} with \|x_j - x_i\|_\infty < r_i and n_y^{(i)} with \|y_j - y_i\|_\infty < r_i. Side lengths (2r_i) cancel in the ratio \frac{m/n}{(n_x/n)(n_y/n)}.
Because every point strictly inside the joint \ell_\infty box of half-width r_i satisfies both \|x_j - x_i\|_\infty < r_i and \|y_j - y_i\|_\infty < r_i, both marginal strips hold at least m - 1 points (n_x^{(i)}, n_y^{(i)} \ge m - 1). Since \psi is increasing:
\hat{I}_{\textrm{KSG}} \le \psi(m) + \psi(n) - 2\psi(m) = \psi(n) - \psi(m) \approx \log\frac{n}{m} \quad (\text{attained when } Y = X)
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) -1return n_x, n_ydef 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)returnfloat(digamma(m) + digamma(len(x))- (digamma(n_x +1) + digamma(n_y +1)).mean())
Why KSG Breaks Down in Higher Dimensions
The Curse of Dimensionality
On d independent copies of the \rho = 0.9 Gaussian pair (true I = 0.830\,d\text{ nats}), KSG (n = 2{,}000, m = 5) is accurate at d \le 2 but stalls below 3\text{ nats} for d \ge 8—well below its 6.09-nat sample ceiling:
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
Geometric failure of local constancy: Capturing fraction m/n = 0.0025 of samples in 2d dimensions requires a box spanning (m/n)^{1/(2d)} of each axis (5\% at d = 1, jumping to 83\% at d = 16), smearing out the 7\%-wide conditional band.
The McAllester–Stratos Distribution-Free Limit
Four-Step Collision Proof
Theorem (McAllester & Stratos, 2020): Any distribution-free estimator B(S_n) satisfying \Pr(B(S_n) \le I(X; Y)) \ge 0.95 for all distributions is capped at \mathcal{O}(\log n)(\approx 2\log n).
Birthday collision proof: On M = n^2 uniform symbols (H = 2\log n), all n draws are distinct with probability > 1/2, forcing any label-invariant bound to output \le 2\log n on every collision-free sample.
Resolving the Deep Network Compression Debate
What Binned Activations Actually Measure
In a deterministic network, binned activations Z_{\textrm{bin}} = f_{\textrm{bin}}(X) have H(Z_{\textrm{bin}} \mid X) = 0, so:
Saturation vs. true MI: As weights grow, \tanh(z) saturates near \pm 1, collapsing inputs into the two extreme histogram bins and lowering H(Z_{\textrm{bin}}), whereas ReLU does not saturate and true unbinned I(X; Z) never drops.
Variational Lower Bounds: Estimation as Optimization
Poole et al. Unified Framework
Barber–Agakov (BA): Uses a normalized decoder q(x \mid y) to certify I(X; Y) \ge H(X) + \mathbb{E}[\log q(x \mid y)].
Donsker–Varadhan (DV / MINE) & NWJ: Use an unconstrained scalar critic T(x, y)(T^* = \textrm{pmi} + c), but suffer from \textrm{Var}_Q(e^{\textrm{pmi}}) = e^{2I} - 1.
InfoNCE (Contrastive): Normalizes e^{T(x,y)} across N in-batch candidates, trading a smooth \log N ceiling for low variance.
The Barber–Agakov Variational Decoder Bound
Reconstruction Certifies Information
Replacing the unknown true posterior p(x \mid y) in I(X; Y) = H(X) - H(X \mid Y) = H(X) + \mathbb{E}[\log p(x \mid y)] with any tractable decoder q(x \mid y) yields the Barber–Agakov bound (2003):
Exact slack: Subtracting the bound from I(X; Y) leaves \mathbb{E}_{y \sim P_Y}\big[D_{\textrm{KL}}(p(\cdot \mid y) \,\|\, q(\cdot \mid y))\big] \ge 0, which vanishes if and only if q(x \mid y) = p(x \mid y).
Penalty of a fixed-variance MSE decoder: On our unit-variance Gaussian pair (h(X) = \tfrac12\log(2\pi e)), a fixed-variance Gaussian decoder q(x \mid y) = \mathcal{N}(x; ay, 1) certifies \tfrac12 - \tfrac12\mathbb{E}[(X - aY)^2] = \rho^2/2 at a^* = \rho—capturing only 0.405 of 0.830\text{ nats} at \rho = 0.9 and never exceeding 0.5\text{ nats} as \rho \to 1.
The Donsker–Varadhan (DV) and MINE Critic Bound
Exponential Tilting Without H(X)
With tilted density \tilde{q}(x) = q(x)e^{T(x)} / Z(Z = \mathbb{E}_Q[e^T]), the DV gap equals D_{\textrm{KL}}(P \| \tilde{Q}) \ge 0:
MINE specialization: Setting P = P_{X,Y} and Q = P_X \otimes P_Y attains I(X; Y) at T^*(x, y) = \textrm{pmi}(x, y) + c.
NWJ linearization: Applying \log Z \le Z/e gives \mathbb{E}_P[T] - e^{-1}\mathbb{E}_Q[e^T] (unbiased on minibatches, tight at T^* = 1 + \textrm{pmi}).
The NWJ Bound: Unbiased Batch Estimates
Linearizing the Logarithm
In Donsker–Varadhan, the outer logarithm in -\log \mathbb{E}_Q[e^T] makes minibatch estimates \overline{T} - \log \overline{e^T}biased upward (by Jensen’s inequality, \mathbb{E}[\log \overline{e^T}] < \log \mathbb{E}[e^T]). Applying the tangent inequality \log Z \le Z/e (tight at Z = e) linearizes the second term into the NWJ bound (Nguyen, Wainwright & Jordan, 2010):
Connection to §37.3 f-GAN duality: Writing e^{-1}\mathbb{E}_Q[e^T] = \mathbb{E}_Q[e^{T-1}] shows that NWJ is identically the Fenchel–Young critic bound \mathbb{E}_P[T] - \mathbb{E}_Q[f^*(T)] for f(u) = u\log u(f^*(t) = e^{t-1}).
Pinned additive constant: Unlike DV, shifting T changes \log Z - Z/e; NWJ attains equality I(X; Y) uniquely at T^*(x, y) = 1 + \textrm{pmi}(x, y) (where Z = \mathbb{E}_Q[e^{1+\textrm{pmi}}] = e).
Unbiased but heavy-tailed: Because no \log wraps the expectation, minibatch averages of NWJ are strictly unbiased, yet suffer from the explosive variance \textrm{Var}_Q(e^{\textrm{pmi}}) = e^{2I} - 1.
InfoNCE: Contrastive Retrieval as an MI Bound
In-Batch Softmax Classification
Instead of averaging an unnormalized exponential e^{T(x, y)}, InfoNCE (van den Oord et al., 2018) normalizes e^{T}within a bag of N candidates—one positive partner y_1 = y^+ drawn from p(y \mid x) and N - 1 negatives y_{2:N} drawn i.i.d. from P_Y:
Why it works: Independent negatives add zero MI (I(X; V) = I(X; Y_1)), and by permutation symmetry of p(v) = \prod_j p_Y(y_j), q(v \mid x) = p(v)\frac{N e^{T(x,y_1)}}{\sum_j e^{T(x,y_j)}} integrates to 1.
Why InfoNCE Bends Smoothly Below Its ln N Ceiling
Exact Critic Slack Analysis
InfoNCE is minimized by any critic T^*(x, y) = \textrm{pmi}(x, y) + c(x). Substituting T = \textrm{pmi} into \hat{I}_{\textrm{NCE}} = \log N - \mathcal{L}_{\textrm{NCE}} reveals its exact population slack:
Smooth-minimum approximation: In the denominator average, the N - 1 independent negatives each have expectation \mathbb{E}[e^{\textrm{pmi}(x, y_j)}] = 1, while a typical positive pair contributes \frac{1}{N}e^{\textrm{pmi}(x, y^+)} \approx \frac{e^I}{N}: \hat{I}_{\textrm{NCE}} \approx I - \log\!\left(1 + \frac{e^I}{N}\right) = -\log\!\left(e^{-I} + \frac{1}{N}\right)
Why InfoNCE bends early: Right at I = \log N (where e^I/N = 1), the positive and the N-1 negatives contribute equally to the denominator, leaving \hat{I}_{\textrm{NCE}} \approx \log N - \ln 2 (falling 0.69\text{ nats} below the ceiling).
Simulating the Smooth InfoNCE Ceiling Across N
Batch Sizes N = 16, 128, 1024
Sweeping true I(X; Y) \in [0.25, 7] with the exact critic T^* = \textrm{pmi} for N \in \{16, 128, 1024\} confirms that every curve follows the smooth minimum -\log(e^{-I} + 1/N) within 0.1\text{ nat}:
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
Starved vs. Hit Batches in DV and NWJ Bounds
Why Unnormalized Critics Explode Above ln N
Rare-pair lottery under P_X \otimes P_Y: A plausible pair (\textrm{pmi} \approx I, weight e^I) occurs by chance with probability \sim e^{-I}, so a batch of N negatives sees N e^{-I} hits on average.
Starved vs. hit batches (I > \log N \implies N e^{-I} < 1): Most batches are starved(\overline{e^{\textrm{pmi}}} \ll 1), causing DV and NWJ to overshoot I wildly, while rare hit batches explode with standard deviation \sqrt{(e^{2I}-1)/N}.
Comparing DV, NWJ, and InfoNCE on Exact Critics
200-Batch Quartile Experiment
Evaluating 200 batches of size N = 128 with exact critics shows DV and NWJ destabilizing once I > 3, while InfoNCE maintains an interquartile range under 0.1\text{ nat}:
Comparing DV, NWJ, and InfoNCE on Exact Critics (cont.)
200-Batch Quartile Experiment
The medians and interquartile ranges behind the plot; the last two columns give the share of batches whose mismatched pairs have mean e^{\textrm{pmi}} < 0.1, and the share holding a mismatched pair with e^{\textrm{pmi}} \ge N:
In practice \textrm{pmi}(x, y) is unknown. Systems like SimCLR and CLIP train a separable dual-encoder criticT(x, y) = g(x)^\top h(y) with embeddings g, h : \mathcal{X} \to \mathbb{R}^d, computing all N \times N in-batch scores via one matrix product (2N encoder passes instead of N^2):
Training a Dual-Encoder Contrastive Critic (cont.)
Separable Inner-Product Architecture
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 netdef 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]).Tdef 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()
Training the Dual-Encoder Critic With InfoNCE
Separable Inner-Product Architecture
opt = torch.optim.Adam([*g.parameters(), *h.parameters()], lr=1e-3)N =128for step inrange(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()
Disentangling Critic Error from Bound Slack
Learned vs. Exact Critic Across Batch Sizes
Evaluating our trained dual-encoder critic alongside the exact \textrm{pmi} critic on held-out batches at \rho = 0.99(I = 1.96\text{ nats}) separates network approximation error from bound slack:
Bound slack vs. temperature ceiling: The learned critic matches the exact critic within 0.02\text{ nats} at every N, proving that the \approx 1.4\text{ nat} reading at N = 8(\ln 8 = 2.08 > 1.96) is pure smooth-minimum slack. Moreover, for cosine similarity T(x, y) = \mathrm{sim}(z_x, z_y)/\tau \in [-1/\tau, 1/\tau], the score gap is at most 2/\tau, imposing a second ceiling \hat{I}_{\textrm{NCE}} < 2/\tau.
Practical Guidelines for MI Estimation & Learning
When to Count vs. When to Bound
How should you choose and interpret a mutual information estimator in research and engineering?
Low dimension (d \le 2) and moderate dependence (I \lesssim 4\text{ nats}): Use KSG nearest neighbors (or rank histograms in 1D) for direct, tuning-free nonparametric measurement within \sim 0.1\text{ nat}.
High-dimensional representations (d \gg 2): Direct estimation is impossible due to the \mathcal{O}(\log n) McAllester–Stratos barrier and exponential box growth. Use InfoNCE with large negative pools N and interpret \log N - \mathcal{L}_{\textrm{NCE}} strictly as a certified lower bound.
Avoid unnormalized exponential critics (DV / NWJ) when I \gtrsim \log N - 2: Their apparent ability to report values above \log N on minibatches is an artifact of starved-batch upward bias and \mathcal{O}(e^I/\sqrt{N}) variance.
More MI is not always a better representation (Tschannen et al., 2020): Downstream linear-probe accuracy depends heavily on encoder inductive biases and critic temperature \tau, often peaking under looser MI bounds.
Concept Check: KSG, Temperature, and Bound Slack
Check Your Understanding
Test your grasp of mutual information estimation and contrastive bounds:
KSG on deterministic copies: You run KSG with m = 5 neighbors on n = 2{,}000 samples of a continuous pair where Y = X \sim \mathcal{N}(0, 1) (true I(X; Y) = \infty). What numerical value does KSG return and why?
Cosine temperature ceiling: In SimCLR with batch size N = 256 and cosine critic T(x, y) = \mathrm{sim}(z_x, z_y)/\tau where \mathrm{sim} \in [-1, 1], what is the maximum possible \hat{I}_{\textrm{NCE}} with an unconstrained critic versus at temperature \tau = 0.5?
Diagnosing a contrastive shortfall: On a dataset where true I(X; Y) = 1.96\text{ nats}, your trained InfoNCE critic at N = 8(\ln 8 = 2.08\text{ nats}) reports \hat{I}_{\textrm{NCE}} = 1.40\text{ nats}. Why does it fall 0.56\text{ nats} short even though \ln 8 > 1.96?
Concept Check: KSG, Temperature, and Bound Slack (cont.)
Check Your Understanding
Answers:
KSG ceiling: When Y = X, the joint Chebyshev distance equals the marginal distance, so every marginal strip holds only the m - 1 = 4 points inside the box, returning \psi(2000) - \psi(5) = 6.09\text{ nats} \approx \ln(400).
Temperature vs. batch ceiling: An unconstrained critic is capped at \ln 256 = 5.55\text{ nats}. With \mathrm{sim} \in [-1, 1] and \tau = 0.5, scores differ by at most 2/\tau = 4, so \mathcal{L}_{\textrm{NCE}} \ge \ln(1 + 255 e^{-4}) = 1.74 and \hat{I}_{\textrm{NCE}} \le 5.55 - 1.74 = 3.81 < 2/\tau = 4\text{ nats} (temperature binds before batch size).
Smooth-minimum slack: Even with the exact critic T^* = \textrm{pmi}, the positive sits inside its own denominator alongside N-1 negatives averaging 1, giving -\ln(e^{-1.96} + 1/8) = 1.33\text{ nats}—the shortfall is intrinsic bound slack, not critic failure.
Summary: Mutual Information Estimators & Bounds
Key Takeaways
Estimator / Bound
Mathematical Formula
Ceiling / Variance Scaling
Best Regime & Primary Pitfall
Histogram / Ranks
\sum_{i,j} \hat{p}_{ij}\log\frac{\hat{p}_{ij}}{\hat{p}_i\hat{p}_j} on b \times b grid
\le \log b; b^{2d} cells in \mathbb{R}^{2d}
1D rank histograms are coordinate-invariant; fails for d > 2