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

    Information Theory · Lesson 8 · Information-theoretic objectives in ML

    Critics and variational bounds: f-divergences, InfoNCE and contrastive learning

    Advanced 90 min 5 interactive figures 4 videos Colab notebook

    Before this lesson: lesson 03 (Jensen's inequality, KL divergence), lesson 04 (cross-entropy, softmax cross-entropy), lesson 06 (differential entropy, Gaussians) and lesson 07 (mutual information as a KL divergence, pointwise mutual information). Logistic regression (ML fundamentals track, in preparation) helps; convex functions are in optimization lesson 02. This lesson defines the convex conjugate it needs. Time: about 90 minutes, plus the notebook. This is the hardest lesson of the track. Take a break after the variational bound (section 3, before "KL: the NWJ and DV bounds").


    Why this matters #

    • Contrastive learning. CPC, SimCLR, MoCo and CLIP train encoders with the InfoNCE loss. It is a softmax cross-entropy over a batch, and log⁡N\log N minus the loss is a lower bound on the mutual information between two views. The log⁡N\log N ceiling is one reason these methods use very large batches (CLIP used 32,768 pairs per batch).
    • GANs. The discriminator of a GAN is a classifier between real and generated samples. At its optimum the GAN objective is 2 JS−log⁡42\,\mathrm{JS} - \log 4, a Jensen–Shannon divergence. f-GAN uses the same recipe for any f-divergence.
    • Estimating mutual information. MINE, NWJ and InfoNCE estimate the mutual information between high-dimensional variables, where the tables of lesson 07 are hopeless.
    • Density-ratio estimation. A classifier between two data sets gives importance weights for covariate shift, two-sample tests, and neural ratio estimation in simulation-based inference.

    As in the whole track, log⁡\log is the natural log, so every value in this lesson is in nats (divide by log⁡2≈0.693\log 2 \approx 0.693 for bits). PyTorch and NumPy losses are in nats too.

    1. Predict first #

    2. The picture #

    Picture 1: a classifier learns the density ratio #

    Take two distributions PP and QQ with densities pp and qq. Draw samples of both. Give every sample of PP the label 11 and every sample of QQ the label 00, with equal numbers of each. Now ask: what is the best possible classifier? Bayes' rule answers this in three steps.

    1. The two classes are equally likely, so Pr⁡(label 1)=Pr⁡(label 0)=12\Pr(\text{label } 1) = \Pr(\text{label } 0) = \tfrac12.
    2. Bayes' rule: Pr⁡(1∣x)=12p(x)12p(x)+12q(x)=p(x)p(x)+q(x)\Pr(1 \mid x) = \dfrac{\tfrac12 p(x)}{\tfrac12 p(x) + \tfrac12 q(x)} = \dfrac{p(x)}{p(x) + q(x)}, and Pr⁡(0∣x)=q(x)p(x)+q(x)\Pr(0 \mid x) = \dfrac{q(x)}{p(x) + q(x)}.
    3. The logit (log-odds) is the log of their ratio: log⁡Pr⁡(1∣x)Pr⁡(0∣x)=log⁡p(x)q(x)\log\dfrac{\Pr(1 \mid x)}{\Pr(0 \mid x)} = \log\dfrac{p(x)}{q(x)}.

    So the best classifier's logit is the log density ratio log⁡r(x)\log r(x), with r(x)=p(x)/q(x)r(x) = p(x)/q(x). This is the density-ratio trick. A logistic regression or a neural network trained with cross-entropy (lesson 04) approaches this classifier when it has enough data and capacity. It never needs the densities, only samples.

    Example. P=N(1,1)P = \mathcal{N}(1, 1) and Q=N(0,1)Q = \mathcal{N}(0, 1). The constants of the two Gaussian densities cancel:

    log⁡r(x)=−(x−1)22+x22=−x2+2x−1+x22=x−12.\log r(x) = -\frac{(x-1)^2}{2} + \frac{x^2}{2} = \frac{-x^2 + 2x - 1 + x^2}{2} = x - \frac12 .

    The log ratio is a straight line: a logistic regression on xx can represent it exactly. If the class sizes differ, nP≠nQn_P \ne n_Q, the logit becomes log⁡r(x)+log⁡(nP/nQ)\log r(x) + \log(n_P/n_Q): a constant shift.

    Interactive figure: loading…

    Press "Draw samples and fit the classifier". The blue density is PP (label 1) and the orange one is QQ (label 0). The lower chart shows the true log ratio log⁡p(x)/q(x)\log p(x)/q(x) (dark line) and the logit of a logistic classifier fitted on the features 1,x,x21, x, x^2 (dashed). Notice that the two curves agree between the dashed grey lines, where both classes have samples. Try "different widths": the true log ratio becomes a parabola. With 30 samples per class, look at how the fit goes wrong far from the data.

    A function of xx that we learn from samples, and whose best value is a function of the density ratio, is called a critic. The classifier's logit is our first critic. The rest of the lesson shows how to turn any critic into a number that bounds a divergence.

    Quick check

    A classifier is trained on 1000 samples of PP (label 1) and 1000 samples of QQ (label 0). At a point xx its best possible output is Pr⁡(1∣x)=0.8\Pr(1 \mid x) = 0.8. What is p(x)/q(x)p(x)/q(x)?

    Picture 2: tangent lines give lower bounds #

    The second picture is about convex functions. A convex function ff lies above each of its tangent lines. In fact ff is the upper envelope of its tangent lines: at every point uu, f(u)f(u) equals the highest tangent line at that point.

    Name each line by its slope tt. Write the line as u↦tu−f∗(t)u \mapsto tu - f^*(t), so −f∗(t)-f^*(t) is the point where the line crosses the vertical axis. For the line to be a tangent line, f∗(t)f^*(t) must be sup⁡u [ tu−f(u) ]\sup_u\,[\,tu - f(u)\,]: the largest gap between the line tutu and the graph of ff. Then:

    • for every slope tt and every point uu: f(u)≥tu−f∗(t)f(u) \ge tu - f^*(t) (the line is below ff);
    • for the best slope, t=f′(u)t = f'(u), the line touches ff at uu and the two sides are equal.

    Now the key step. In a divergence, uu will be the density ratio r(x)r(x) at a point xx. We may choose a different slope at every point: a function T(x)T(x). However badly we choose it, the line stays below ff:

    f(r(x))  ≥  T(x) r(x)−f∗(T(x))(every x).f\big(r(x)\big) \;\ge\; T(x)\, r(x) - f^*\big(T(x)\big) \qquad \text{(every } x\text{)}.

    In section 3 we average this over QQ, and the unknown ratio r(x)r(x) disappears. What remains is a lower bound made of two averages over samples. The function TT is the critic.

    Interactive figure: loading…

    Move the slope tt. The dark curve is the generator ff (here f(u)=ulog⁡uf(u) = u\log u of KL). The magenta line with slope tt stays below the curve; it touches it at the yellow dot and crosses the vertical axis at −f∗(t)-f^*(t). The aqua segment at the ratio uu is the gap: it is never negative. Press "Use the best slope at u" and the gap becomes 0. Press "Show many tangent lines" to see ff rebuilt as the envelope of its lines. Switch to TV and notice the kink at u=1u = 1.

    3. Definitions and main results #

    Notation. PP and QQ are distributions on the same space, with densities (or probability mass functions) pp and qq. Unless we say otherwise, we assume p(x)>0p(x) > 0 only where q(x)>0q(x) > 0. Then r(x)=p(x)/q(x)r(x) = p(x)/q(x) is finite, and it is called the likelihood ratio or density ratio. A critic is a function T(x)T(x) (or T(x,y)T(x, y) for pairs). In this lesson the letter ff is always a convex generator, and critics are always called TT.

    f-divergences #

    Definition. Let f:[0,∞)→Rf: [0, \infty) \to \mathbb{R} be convex with f(1)=0f(1) = 0. This ff is the generator. The f-divergence of PP from QQ is

    Df(P ∥ Q)=Ex∼Q[f(p(x)q(x))]=∫q(x) f(p(x)q(x))dx.\begin{aligned} D_f(P\,\|\,Q) &= \mathbb{E}_{x \sim Q}\left[f\left(\frac{p(x)}{q(x)}\right)\right] \\ &= \int q(x)\, f\left(\frac{p(x)}{q(x)}\right) dx . \end{aligned}

    The average is under the second argument QQ, and the ratio has pp on top. The generator says how much a ratio uu is penalized; u=1u = 1 (no difference) costs f(1)=0f(1) = 0.

    Theorem (non-negativity). Df(P ∥ Q)≥0D_f(P\,\|\,Q) \ge 0, and Df(P ∥ P)=0D_f(P\,\|\,P) = 0.

    Proof.

    1. The ratio has average 1 under QQ: EQ[r]=∫q(x)p(x)q(x) dx=∫p(x) dx=1\mathbb{E}_Q[r] = \int q(x)\frac{p(x)}{q(x)}\,dx = \int p(x)\,dx = 1.
    2. Jensen's inequality for the convex ff (lesson 03): EQ[f(r)]≥f(EQ[r])\mathbb{E}_Q[f(r)] \ge f(\mathbb{E}_Q[r]).
    3. With step 1, the right side is f(1)=0f(1) = 0. If P=QP = Q, then r=1r = 1 everywhere and Df=EQ[f(1)]=0D_f = \mathbb{E}_Q[f(1)] = 0. ■\blacksquare

    If ff is strictly convex at u=1u = 1, then Df=0D_f = 0 only when P=QP = Q. Every f-divergence also satisfies the data processing inequality of lesson 07.

    Three facts that prevent confusion.

    1. The generator is not unique. f(u)f(u) and f(u)+c(u−1)f(u) + c(u - 1) give the same divergence for every constant cc, because EQ[r−1]=0\mathbb{E}_Q[r - 1] = 0. For example, ulog⁡u−u+1u\log u - u + 1 also gives KL, and it is ≥0\ge 0 for every uu. Tables in papers differ by such terms and by constant factors.
    2. Swapping the arguments. Df(Q ∥ P)=Df~(P ∥ Q)D_f(Q\,\|\,P) = D_{\tilde f}(P\,\|\,Q) with f~(u)=u f(1/u)\tilde f(u) = u\,f(1/u). For f(u)=ulog⁡uf(u) = u\log u this gives f~(u)=−log⁡u\tilde f(u) = -\log u: the reverse KL.
    3. Points outside the support. A point with q(x)=0<p(x)q(x) = 0 < p(x) contributes p(x)lim⁡u→∞f(u)/up(x)\lim_{u\to\infty} f(u)/u. This is +∞+\infty for KL and χ2\chi^2, but finite for TV, Hellinger and JS. A point with p(x)=0<q(x)p(x) = 0 < q(x) contributes q(x)f(0)q(x)f(0), which is +∞+\infty for reverse KL.

    The six standard generators. M=12(P+Q)M = \tfrac12(P + Q) is the mixture. The last two columns are explained below (conjugate and optimal critic).

    Divergence Df(P ∥ Q)D_f(P\,\Vert\,Q) Generator f(u)f(u) Conjugate f∗(t)f^*(t) Optimal critic T∗=f′(r)T^* = f'(r)
    KL ∫plog⁡pq\int p\log\frac{p}{q} ulog⁡uu\log u et−1e^{t-1} 1+log⁡r1 + \log r
    reverse KL ∫qlog⁡qp\int q\log\frac{q}{p} −log⁡u-\log u −1−log⁡(−t)-1-\log(-t), for t<0t<0 −1/r-1/r
    total variation (TV) 12∫∣p−q∣\frac12\int\lvert p-q\rvert 12∣u−1∣\frac12\lvert u-1\rvert tt, for ∣t∣≤12\lvert t\rvert\le\frac12 12sign⁡(r−1)\frac12\operatorname{sign}(r-1)
    Pearson χ2\chi^2 ∫(p−q)2q\int\frac{(p-q)^2}{q} (u−1)2(u-1)^2 t+t24t + \frac{t^2}{4}, for t≥−2t \ge -2 2(r−1)2(r-1)
    squared Hellinger H2H^2 ∫(p−q)2\int(\sqrt p-\sqrt q)^2 (u−1)2(\sqrt u-1)^2 t1−t\frac{t}{1-t}, for t<1t<1 1−1/r1 - 1/\sqrt r
    Jensen–Shannon (JS) 12KL(P∥M)+12KL(Q∥M)\frac12\mathrm{KL}(P\Vert M)+\frac12\mathrm{KL}(Q\Vert M) 12[ulog⁡u−(u+1)log⁡u+12]\frac12\big[u\log u-(u+1)\log\frac{u+1}2\big] −12log⁡(2−e2t)-\frac12\log(2-e^{2t}), for t<12log⁡2t<\frac12\log 2 12log⁡2r1+r\frac12\log\frac{2r}{1+r}

    Two inequalities link these divergences:

    • KL(P ∥ Q)≤log⁡(1+χ2(P ∥ Q))\mathrm{KL}(P\,\|\,Q) \le \log\big(1 + \chi^2(P\,\|\,Q)\big). Proof: KL=EP[log⁡r]≤log⁡EP[r]\mathrm{KL} = \mathbb{E}_P[\log r] \le \log\mathbb{E}_P[r] (Jensen, log⁡\log is concave), and EP[r]=EQ[r2]=1+χ2\mathbb{E}_P[r] = \mathbb{E}_Q[r^2] = 1 + \chi^2.
    • Pinsker's inequality: TV(P,Q)≤KL(P ∥ Q)/2\mathrm{TV}(P, Q) \le \sqrt{\mathrm{KL}(P\,\|\,Q)/2}, with KL in nats (no proof here).

    The convex conjugate #

    Definition. The convex conjugate (or Fenchel conjugate) of ff is

    f∗(t)=sup⁡u≥0 [ tu−f(u) ].f^*(t) = \sup_{u \ge 0}\,\big[\,tu - f(u)\,\big].

    It is the largest gap between the line tutu and the graph of ff. As a supremum of functions that are affine in tt, f∗f^* is convex.

    Example (KL), step by step. f(u)=ulog⁡uf(u) = u\log u.

    1. Maximize g(u)=tu−ulog⁡ug(u) = tu - u\log u. Its derivative is t−log⁡u−1t - \log u - 1.
    2. Set it to zero: log⁡u=t−1\log u = t - 1, so u=et−1u = e^{t-1}. (gg is concave, so this is the maximum.)
    3. Insert this uu: f∗(t)=tet−1−et−1(t−1)=et−1f^*(t) = t e^{t-1} - e^{t-1}(t - 1) = e^{t-1}.

    Fenchel–Young inequality. For all u≥0u \ge 0 and all tt: f(u)≥tu−f∗(t)f(u) \ge tu - f^*(t). Equality holds exactly when tt is a slope of ff at uu (t=f′(u)t = f'(u) when ff is differentiable). This is picture 2 in one line.

    Fenchel–Moreau theorem. If ff is convex and lower semicontinuous (its epigraph is a closed set), then f∗∗=ff^{**} = f, that is, f(u)=sup⁡t [tu−f∗(t)]f(u) = \sup_t\,[tu - f^*(t)]: ff is the envelope of its tangent lines. All generators in the table have this property.

    The variational representation #

    Theorem (variational lower bound). Let ff be a convex, lower semicontinuous generator with f(1)=0f(1) = 0, and let p>0p > 0 only where q>0q > 0. For every critic TT whose values lie where f∗f^* is finite (and with finite expectations):

    Df(P ∥ Q)  ≥  Ex∼P[T(x)]−Ex∼Q[f∗(T(x))].D_f(P\,\|\,Q) \;\ge\; \mathbb{E}_{x\sim P}[T(x)] - \mathbb{E}_{x\sim Q}\big[f^*(T(x))\big].

    Equality holds when T(x)T(x) is a slope of ff at r(x)r(x) for (QQ-almost) every xx, for example T∗(x)=f′(r(x))T^*(x) = f'(r(x)). Hence Df(P ∥ Q)=sup⁡T {EP[T]−EQ[f∗(T)]}D_f(P\,\|\,Q) = \sup_T\,\big\{\mathbb{E}_P[T] - \mathbb{E}_Q[f^*(T)]\big\}.

    Proof.

    1. Fenchel–Young at u=r(x)u = r(x) and t=T(x)t = T(x): f(r(x))≥T(x) r(x)−f∗(T(x))f(r(x)) \ge T(x)\,r(x) - f^*(T(x)) for every xx.
    2. Multiply by q(x)≥0q(x) \ge 0 and integrate over xx. The left side becomes ∫q f(r)=Df(P ∥ Q)\int q\,f(r) = D_f(P\,\|\,Q).
    3. On the right, q(x) r(x)=p(x)q(x)\,r(x) = p(x). So ∫q T r=∫p T=EP[T]\int q\,T\,r = \int p\,T = \mathbb{E}_P[T], and ∫q f∗(T)=EQ[f∗(T)]\int q\,f^*(T) = \mathbb{E}_Q[f^*(T)]. This gives the bound.
    4. Step 1 is an equality at xx exactly when T(x)T(x) is a slope of ff at r(x)r(x). For T∗=f′(r)T^* = f'(r) this holds at every xx, so the bound is an equality. ■\blacksquare

    What the theorem gives you in practice.

    • Only samples are needed. Replace EP\mathbb{E}_P and EQ\mathbb{E}_Q by averages over samples of PP and of QQ. No density is evaluated.
    • Any critic is safe. With a restricted family of critics T\mathcal{T} (for example a neural network), sup⁡T∈T≤Df\sup_{T\in\mathcal{T}} \le D_f. The gap is how well T\mathcal{T} can represent T∗=f′(r)T^* = f'(r).
    • The best critic knows the density ratio: r=(f′)−1(T∗)r = (f')^{-1}(T^*). Training the critic is density-ratio estimation, as in picture 1.
    Quick check

    For the KL generator f(u)=ulog⁡uf(u) = u\log u, what is the optimal critic T∗(x)T^*(x)?

    KL: the NWJ and Donsker–Varadhan bounds #

    NWJ bound. Put f(u)=ulog⁡uf(u) = u\log u and f∗(t)=et−1f^*(t) = e^{t-1} into the theorem. This gives the bound of Nguyen, Wainwright and Jordan (2010):

    KL(P ∥ Q)  ≥  EP[T]−EQ[eT−1],T∗=1+log⁡r.\mathrm{KL}(P\,\|\,Q) \;\ge\; \mathbb{E}_P[T] - \mathbb{E}_Q\big[e^{T-1}\big], \qquad T^* = 1 + \log r .

    Check at T∗T^*: EP[1+log⁡r]−EQ[elog⁡r]=1+KL−EQ[r]=1+KL−1=KL\mathbb{E}_P[1 + \log r] - \mathbb{E}_Q[e^{\log r}] = 1 + \mathrm{KL} - \mathbb{E}_Q[r] = 1 + \mathrm{KL} - 1 = \mathrm{KL}.

    Donsker–Varadhan (DV) bound.

    KL(P ∥ Q)  ≥  EP[T]−log⁡EQ[eT].\mathrm{KL}(P\,\|\,Q) \;\ge\; \mathbb{E}_P[T] - \log\mathbb{E}_Q\big[e^{T}\big].

    Proof (DV is NWJ with the best constant shift).

    1. Apply NWJ to the shifted critic T+cT + c, with a constant cc: KL≥EP[T]+c−ec−1 EQ[eT]\mathrm{KL} \ge \mathbb{E}_P[T] + c - e^{c-1}\,\mathbb{E}_Q[e^T].
    2. Maximize the right side over cc. Its derivative is 1−ec−1 EQ[eT]1 - e^{c-1}\,\mathbb{E}_Q[e^T], which is zero at c=1−log⁡EQ[eT]c = 1 - \log\mathbb{E}_Q[e^T].
    3. Insert this cc: EP[T]+1−log⁡EQ[eT]−1=EP[T]−log⁡EQ[eT]\mathbb{E}_P[T] + 1 - \log\mathbb{E}_Q[e^T] - 1 = \mathbb{E}_P[T] - \log\mathbb{E}_Q[e^T]. ■\blacksquare

    So for the same critic, DV ≥\ge NWJ. DV does not change when you add a constant to TT, and its optimal critics are log⁡r+c\log r + c for any constant cc. MINE (Belghazi et al., 2018) maximizes DV with a neural critic.

    Bounds on mutual information #

    Mutual information is a KL divergence (lesson 07):

    I(X;Y)=KL(p(x,y) ∥ p(x)p(y)).I(X;Y) = \mathrm{KL}\big(p(x,y)\,\|\,p(x)p(y)\big).

    So put P=p(x,y)P = p(x, y) (the joint) and Q=p(x)p(y)Q = p(x)p(y) (the product of the marginals) into NWJ and DV. The density ratio is p(x,y)p(x)p(y)=epmi⁡(x,y)\frac{p(x,y)}{p(x)p(y)} = e^{\operatorname{pmi}(x,y)}, where pmi⁡(x,y)=log⁡p(x,y)p(x)p(y)=log⁡p(y∣x)p(y)\operatorname{pmi}(x, y) = \log\frac{p(x,y)}{p(x)p(y)} = \log\frac{p(y \mid x)}{p(y)} is the pointwise mutual information. The critic is a function T(x,y)T(x, y) of a pair.

    Where do the samples come from? Take a batch of NN pairs (x1,y1),…,(xN,yN)(x_1, y_1), \dots, (x_N, y_N) drawn from p(x,y)p(x, y) and form the score matrix Sij=T(xi,yj)S_{ij} = T(x_i, y_j).

    • The diagonal SiiS_{ii} uses true pairs: these are positive pairs, samples of P=p(x,y)P = p(x,y).
    • An off-diagonal entry SijS_{ij}, i≠ji \ne j, pairs xix_i with the yy of another example. Since the examples are independent, (xi,yj)(x_i, y_j) is a sample of Q=p(x)p(y)Q = p(x)p(y): a negative pair.

    NWJ and DV average the diagonal for EP\mathbb{E}_P and the off-diagonal for EQ\mathbb{E}_Q.

    Why these estimates are noisy when the MI is large. At the optimal NWJ critic, the QQ-term averages eT∗−1=re^{T^* - 1} = r over negative pairs. One sample of it has variance

    VarQ(r)=EQ[r2]−1=χ2(P ∥ Q)  ≥  eKL(P∥Q)−1=eI−1,\mathrm{Var}_Q(r) = \mathbb{E}_Q[r^2] - 1 = \chi^2(P\,\|\,Q) \;\ge\; e^{\mathrm{KL}(P\|Q)} - 1 = e^{I} - 1,

    by the first inequality of the f-divergence part. So the variance grows exponentially with the mutual information. For correlated Gaussian pairs it is exactly e2I−1e^{2I} - 1: about 164 at I=2.55I = 2.55 nats, and about 1.3×10101.3 \times 10^{10} at I=11.6I = 11.6 nats. The average is dominated by rare negative pairs with a huge ratio, which most batches never see.

    Two more warnings. The bounds hold for the expectations; a value computed on one batch is a noisy estimate and can lie above the true MI. And the DV estimate puts the sample average inside a log⁡\log. By Jensen, E[log⁡m^]≤log⁡E[m^]\mathbb{E}[\log \hat m] \le \log \mathbb{E}[\hat m], so the DV estimate is biased upward and can overshoot the true value. MINE's estimate is therefore neither an upper nor a lower bound (Poole et al., 2019, section 2.2).

    Interactive figure: loading…

    Change the true MI with ρ\rho and dd. Each magenta dot is the estimate from one batch of NN correlated Gaussian pairs, with the optimal critic. The violet line is the true MI, I=−d2log⁡(1−ρ2)I = -\frac{d}{2}\log(1 - \rho^2), and the dashed line is log⁡N\log N. Use "Try": at low MI the three estimators agree. At high MI, notice that InfoNCE has a small spread but stops below log⁡N\log N, while NWJ and DV are not capped but spread widely, and their mean is often above the truth.

    InfoNCE: a bound from an N-way classification game #

    InfoNCE (van den Oord et al., 2018) uses the same score matrix in a different way. For each row ii, it asks a classification question: which of the NN candidates y1,…,yNy_1, \dots, y_N is the true partner of xix_i? A softmax over the row turns the scores into probabilities, and the loss is the cross-entropy of the correct answer j=ij = i:

    LInfoNCE=1N∑i=1N−log⁡eSii∑j=1NeSij.\mathcal{L}_{\text{InfoNCE}} = \frac{1}{N}\sum_{i=1}^{N} -\log\frac{e^{S_{ii}}}{\sum_{j=1}^N e^{S_{ij}}} .

    This is exactly cross_entropy(S, labels = [0, 1, ..., N-1]), the softmax cross-entropy of lesson 04, with the row of scores as logits.

    Interactive figure: loading…

    Each row is a classification over the batch. Cell (i,j)(i, j) is darker when the softmax of row ii gives more probability to candidate yjy_j; the framed diagonal holds the true partners. The bars compare the true MI (violet) with the InfoNCE bound log⁡N−L\log N - \mathcal{L} (magenta) and the ceiling log⁡N\log N (dashed). Raise ρ\rho to 0.99 and dd to 10: the bound stops at log⁡N\log N. Then increase NN. Choose the constant critic: the rows become uniform and the bound is 0.

    Theorem (InfoNCE bound). Let (x,y1)∼p(x,y)(x, y_1) \sim p(x, y), and let y2,…,yN∼p(y)y_2, \dots, y_N \sim p(y) be independent of each other and of (x,y1)(x, y_1). For any critic TT, let

    LInfoNCE=E[−log⁡eT(x,y1)∑j=1NeT(x,yj)].\mathcal{L}_{\text{InfoNCE}} = \mathbb{E}\left[-\log\frac{e^{T(x, y_1)}}{\sum_{j=1}^N e^{T(x, y_j)}}\right].

    Then

    I(X;Y)  ≥  log⁡N−LInfoNCE,I(X;Y) \;\ge\; \log N - \mathcal{L}_{\text{InfoNCE}},

    and the bound never passes the ceiling: log⁡N−LInfoNCE≤log⁡N\log N - \mathcal{L}_{\text{InfoNCE}} \le \log N.

    Why it is true, in one picture. Hide the true partner at a random position cc among NN candidates. Guessing cc at random costs log⁡N\log N nats of cross-entropy. A good critic lowers the loss, and the saving log⁡N−L\log N - \mathcal{L} is information about cc. But the only thing that reveals cc is the dependence between xx and its partner, so the saving cannot exceed I(X;Y)I(X;Y). And a cross-entropy is never negative, so the saving cannot exceed log⁡N\log N.

    Proof of the InfoNCE bound (five steps)
    1. A classification game. Put the positive at a uniformly random position c∈{1,…,N}c \in \{1, \dots, N\} instead of position 1. The softmax treats all positions alike, so the loss does not change. Write D=(x,y1,…,yN)D = (x, y_1, \dots, y_N). The softmax q(c=i∣D)=eT(x,yi)/∑jeT(x,yj)q(c = i \mid D) = e^{T(x, y_i)}/\sum_j e^{T(x, y_j)} is a classifier that guesses cc from DD, and L\mathcal{L} is its cross-entropy.
    2. Cross-entropy ≥\ge entropy (lesson 04), for each DD: L≥H(c∣D)\mathcal{L} \ge H(c \mid D). Since cc is uniform, H(c)=log⁡NH(c) = \log N. So log⁡N−L≤H(c)−H(c∣D)=I(c;D)\log N - \mathcal{L} \le H(c) - H(c \mid D) = I(c; D).
    3. Chain rule for mutual information: I(c;D)=I(c;y1:N)+I(c;x∣y1:N)I(c; D) = I(c; y_{1:N}) + I(c; x \mid y_{1:N}). Without xx, the yjy_j are independent draws of p(y)p(y) whatever cc is, so I(c;y1:N)=0I(c; y_{1:N}) = 0.
    4. I(c;x∣y1:N)=H(x∣y1:N)−H(x∣c,y1:N)I(c; x \mid y_{1:N}) = H(x \mid y_{1:N}) - H(x \mid c, y_{1:N}). Given cc and all the yy's, xx depends only on its partner ycy_c, and (x,yc)∼p(x,y)(x, y_c) \sim p(x, y). So H(x∣c,y1:N)=H(X∣Y)H(x \mid c, y_{1:N}) = H(X \mid Y). Conditioning reduces entropy, so H(x∣y1:N)≤H(X)H(x \mid y_{1:N}) \le H(X). Together: I(c;x∣y1:N)≤H(X)−H(X∣Y)=I(X;Y)I(c; x \mid y_{1:N}) \le H(X) - H(X \mid Y) = I(X;Y). (For continuous xx the same steps hold with differential entropies.)
    5. Steps 2–4 give log⁡N−L≤I(X;Y)\log N - \mathcal{L} \le I(X;Y). A cross-entropy is ≥0\ge 0, so also log⁡N−L≤log⁡N\log N - \mathcal{L} \le \log N. ■\blacksquare

    The optimal critic. Step 2 is tight when the softmax equals the true posterior of the position. That posterior is p(c=i∣D)∝p(yi∣x)/p(yi)p(c = i \mid D) \propto p(y_i \mid x)/p(y_i). So the optimal critic is

    T∗(x,y)=log⁡p(y∣x)p(y)+a(x)=pmi⁡(x,y)+a(x),T^*(x, y) = \log\frac{p(y \mid x)}{p(y)} + a(x) = \operatorname{pmi}(x, y) + a(x),

    for any function a(x)a(x) of xx alone: it adds the same number to a whole row, and the softmax removes it. With T∗T^* the bound tends to I(X;Y)I(X;Y) as N→∞N \to \infty. For a finite NN it stays below II, and never above log⁡N\log N. To certify II nats you need N≥eIN \ge e^{I}.

    Bias and variance, side by side.

    Bound Bias Variance Ceiling
    InfoNCE below II for finite NN, even with T∗T^* low: the softmax normalizes inside each row log⁡N\log N
    NWJ none at T∗T^*: the sample mean is unbiased for the bound at least eI−1e^{I} - 1 per negative pair (e2I−1e^{2I} - 1 for Gaussians) none
    DV / MINE the log⁡\log of a sample mean is biased upward high none

    This is a general limit, not a weakness of one method. McAllester and Stratos (2020) prove that any distribution-free lower bound on mutual information that holds with high confidence from NN samples can show at most O(log⁡N)O(\log N).

    Answers to section 1. (1) At most log⁡256=5.55\log 256 = 5.55 nats, whatever the critic. The true value is 30 nats, but the bound cannot see more than log⁡N\log N; you would need N≥e30≈1013N \ge e^{30} \approx 10^{13}. (2) With equal numbers of each, the best classifier's logit is the log density ratio between true pairs p(x,y)p(x,y) and shuffled pairs p(x)p(y)p(x)p(y): the pointwise mutual information pmi⁡(x,y)\operatorname{pmi}(x, y). Its average over true pairs is I(X;Y)I(X;Y).

    Quick check

    A contrastive model uses batches of N=128N = 128 pairs. What is the largest value that log⁡N−LInfoNCE\log N - \mathcal{L}_{\text{InfoNCE}} can take, whatever the true mutual information?

    Quick check

    For the optimal InfoNCE critic T∗(x,y)=pmi⁡(x,y)T^*(x, y) = \operatorname{pmi}(x, y), you add 5∥x∥25\|x\|^2 to every score. What happens to the InfoNCE loss?

    Contrastive learning #

    In contrastive representation learning the critic is built from two encoders. Two views of the same example (two augmentations of an image in SimCLR, an image and its caption in CLIP, a context and a future frame in CPC) form a positive pair. The critic is a cosine similarity divided by a temperature τ\tau:

    T(x,y)=cos⁡(g(x),h(y))τ,cos⁡(a,b)=a⊤b∥a∥ ∥b∥.T(x, y) = \frac{\cos\big(g(x), h(y)\big)}{\tau}, \qquad \cos(a, b) = \frac{a^\top b}{\|a\|\,\|b\|} .
    • CPC (van den Oord et al., 2018) introduced the name InfoNCE and the bound I≥log⁡N−LI \ge \log N - \mathcal{L}, with a log-bilinear critic z⊤Wcz^\top W c.
    • SimCLR (Chen et al., 2020) uses two augmentations of each image and the other 2N−22N - 2 views of the batch as negatives (the NT-Xent loss).
    • CLIP (Radford et al., 2021) uses a symmetric loss: the average of the row loss (each image picks its caption among NN) and the column loss (each caption picks its image), 12(Limg→text+Ltext→img)\tfrac12\big(\mathcal{L}_{\text{img}\to\text{text}} + \mathcal{L}_{\text{text}\to\text{img}}\big).

    Why large batches? The ceiling log⁡N\log N is one reason: with N=4096N = 4096 the bound stops at 8.3 nats. More negatives also make the classification task harder and the gradient less noisy.

    A caution. A high InfoNCE bound does not by itself explain why the features are good. Tschannen et al. (2020) show encoders with the same or higher MI bound and worse downstream accuracy: the architecture of the critic and the augmentations matter as much as the bound. Augmentations, temperature, collapse and the practice of contrastive learning are in deep learning lesson 14.

    GANs: the discriminator is a density-ratio classifier #

    A GAN trains a generator GG with distribution QQ against a discriminator D(x)∈(0,1)D(x) \in (0, 1) that tells real samples (from the data PP) from generated ones. The value function is

    V(D,G)=Ex∼P[log⁡D(x)]+Ex∼Q[log⁡(1−D(x))].V(D, G) = \mathbb{E}_{x\sim P}[\log D(x)] + \mathbb{E}_{x\sim Q}[\log(1 - D(x))] .

    The discriminator maximizes VV. This is the cross-entropy of picture 1 with a minus sign, so the best discriminator is the Bayes classifier with equal priors:

    D∗(x)=p(x)p(x)+q(x).D^*(x) = \frac{p(x)}{p(x) + q(x)} .

    Theorem (GAN value at the optimal discriminator). V(D∗,G)=2 JS(P ∥ Q)−log⁡4V(D^*, G) = 2\,\mathrm{JS}(P\,\|\,Q) - \log 4.

    Proof. Write M=12(P+Q)M = \frac12(P + Q), so p+q=2mp + q = 2m.

    1. V(D∗,G)=∫plog⁡pp+q+∫qlog⁡qp+qV(D^*, G) = \int p \log\frac{p}{p+q} + \int q\log\frac{q}{p+q}.
    2. log⁡pp+q=log⁡p2m=log⁡pm−log⁡2\log\frac{p}{p+q} = \log\frac{p}{2m} = \log\frac{p}{m} - \log 2, and the same for qq.
    3. So V=KL(P ∥ M)−log⁡2+KL(Q ∥ M)−log⁡2=2 JS(P ∥ Q)−log⁡4V = \mathrm{KL}(P\,\|\,M) - \log 2 + \mathrm{KL}(Q\,\|\,M) - \log 2 = 2\,\mathrm{JS}(P\,\|\,Q) - \log 4. ■\blacksquare

    So the generator, facing an optimal discriminator, minimizes the Jensen–Shannon divergence. The minimum −log⁡4-\log 4 is reached exactly when Q=PQ = P (then D∗=12D^* = \frac12 everywhere). When PP and QQ hardly overlap, JS is close to its maximum log⁡2\log 2 and hardly changes when QQ moves: the generator gets almost no gradient. This is one cause of unstable GAN training, and a motivation for the non-saturating loss and for Wasserstein GANs.

    Interactive figure: loading…

    Move the generator. The data density pp is blue, the generator density qq is orange, and the dark curve is the optimal discriminator D∗=p/(p+q)D^* = p/(p+q). The lower chart shows the GAN value at D∗D^* as a function of the generator mean μ\mu (magenta), with the current μ\mu as a yellow dot. Notice: the integral V(D∗,G)V(D^*, G) and 2 JS−log⁡42\,\mathrm{JS} - \log 4 agree to 4 digits. Move μ\mu to 6: the curve is flat and the slope is almost 0.

    Quick check

    The generator of a GAN produces exactly the data distribution, Q=PQ = P. What is the value V(D∗,G)V(D^*, G) at the optimal discriminator?

    f-GAN, and why TV leads to Wasserstein GANs

    f-GAN (Nowozin, Cseke and Tomioka, 2016) trains a generator with any f-divergence. The critic is Tω(x)=gf(Vω(x))T_\omega(x) = g_f(V_\omega(x)): a network VωV_\omega with a real output, followed by an output activation gfg_f that maps R\mathbb{R} into the domain of f∗f^* (for example gf(v)=1−e−v<1g_f(v) = 1 - e^{-v} < 1 for squared Hellinger). Training solves the saddle-point problem

    min⁡θ max⁡ω  Ex∼P[Tω(x)]−Ex∼Qθ[f∗(Tω(x))].\min_\theta\, \max_\omega\; \mathbb{E}_{x\sim P}[T_\omega(x)] - \mathbb{E}_{x\sim Q_\theta}\big[f^*(T_\omega(x))\big].

    The inner max estimates Df(P ∥ Qθ)D_f(P\,\|\,Q_\theta) by the variational bound; the outer min moves QθQ_\theta to reduce it.

    The original GAN is one case, with fGAN(u)=ulog⁡u−(u+1)log⁡(u+1)f_{\text{GAN}}(u) = u\log u - (u+1)\log(u+1) and fGAN∗(t)=−log⁡(1−et)f^*_{\text{GAN}}(t) = -\log(1 - e^t) for t<0t < 0. Write the critic as T=log⁡DT = \log D with D∈(0,1)D \in (0, 1). Then −fGAN∗(T)=log⁡(1−D)-f^*_{\text{GAN}}(T) = \log(1 - D), and the bound EP[T]−EQ[fGAN∗(T)]\mathbb{E}_P[T] - \mathbb{E}_Q[f^*_{\text{GAN}}(T)] is exactly V(D,G)V(D, G). The optimal critic T∗=fGAN′(r)=log⁡r1+rT^* = f'_{\text{GAN}}(r) = \log\frac{r}{1+r} gives D∗=pp+qD^* = \frac{p}{p+q}, and DfGAN(P ∥ Q)=2 JS−log⁡4D_{f_{\text{GAN}}}(P\,\|\,Q) = 2\,\mathrm{JS} - \log 4. Here fGAN(1)=−log⁡4≠0f_{\text{GAN}}(1) = -\log 4 \ne 0; this is why the minimum is −log⁡4-\log 4 and not 0.

    TV is also an integral probability metric. Its conjugate is f∗(t)=tf^*(t) = t on ∣t∣≤12|t| \le \frac12, so the theorem gives TV(P,Q)=sup⁡∣T∣≤1/2 (EP[T]−EQ[T])\mathrm{TV}(P, Q) = \sup_{|T| \le 1/2}\,\big(\mathbb{E}_P[T] - \mathbb{E}_Q[T]\big). Replace the constraint "∣T∣≤12|T| \le \frac12" by "TT is 1-Lipschitz" and you get the Wasserstein-1 distance of WGAN. Unlike JS, it keeps changing when two non-overlapping distributions move apart. GAN training in practice is in the generative models track.

    4. Worked example #

    (a) Six f-divergences of one pair. P=(12,12)P = (\tfrac12, \tfrac12) and Q=(14,34)Q = (\tfrac14, \tfrac34) on two points. The ratios are r=p/q=(2,23)r = p/q = (2, \tfrac23), so every f-divergence is Df=14f(2)+34f(23)D_f = \tfrac14 f(2) + \tfrac34 f(\tfrac23).

    • KL: 14⋅2log⁡2+34⋅23log⁡23=12log⁡2+12log⁡23=12log⁡43=0.1438\tfrac14 \cdot 2\log 2 + \tfrac34 \cdot \tfrac23\log\tfrac23 = \tfrac12\log 2 + \tfrac12\log\tfrac23 = \tfrac12\log\tfrac43 = 0.1438 nats.
    • Reverse KL: 14(−log⁡2)+34(−log⁡23)=−0.1733+0.3041=0.1308\tfrac14(-\log 2) + \tfrac34(-\log\tfrac23) = -0.1733 + 0.3041 = 0.1308 nats. Not equal to KL.
    • TV: 14⋅12∣2−1∣+34⋅12∣23−1∣=18+18=14\tfrac14 \cdot \tfrac12|2 - 1| + \tfrac34 \cdot \tfrac12|\tfrac23 - 1| = \tfrac18 + \tfrac18 = \tfrac14.
    • χ2\chi^2: 14(2−1)2+34(23−1)2=14+112=13=0.3333\tfrac14(2-1)^2 + \tfrac34(\tfrac23 - 1)^2 = \tfrac14 + \tfrac1{12} = \tfrac13 = 0.3333.
    • Squared Hellinger: (1/2−1/4)2+(1/2−3/4)2=0.0429+0.0253=0.0681(\sqrt{1/2} - \sqrt{1/4})^2 + (\sqrt{1/2} - \sqrt{3/4})^2 = 0.0429 + 0.0253 = 0.0681 (or 0.03410.0341 with the factor 12\tfrac12).
    • JS: M=(38,58)M = (\tfrac38, \tfrac58), KL(P ∥ M)=0.0323\mathrm{KL}(P\,\|\,M) = 0.0323, KL(Q ∥ M)=0.0354\mathrm{KL}(Q\,\|\,M) = 0.0354, so JS=12(0.0323+0.0354)=0.0338\mathrm{JS} = \tfrac12(0.0323 + 0.0354) = 0.0338 nats, far below its maximum log⁡2=0.693\log 2 = 0.693.

    Checks: KL=0.1438≤log⁡(1+χ2)=log⁡43=0.2877\mathrm{KL} = 0.1438 \le \log(1 + \chi^2) = \log\tfrac43 = 0.2877, and Pinsker: TV=0.25≤0.1438/2=0.268\mathrm{TV} = 0.25 \le \sqrt{0.1438/2} = 0.268.

    (b) The KL bounds with three critics. A critic on two points is a pair T=(T(1),T(2))T = (T(1), T(2)). NWJ is EP[T]−EQ[eT−1]\mathbb{E}_P[T] - \mathbb{E}_Q[e^{T-1}] and DV is EP[T]−log⁡EQ[eT]\mathbb{E}_P[T] - \log\mathbb{E}_Q[e^{T}].

    Critic TT NWJ DV
    1+log⁡r=(1.693,0.595)1 + \log r = (1.693, 0.595) 1.1438−1=0.14381.1438 - 1 = 0.1438 1.1438−log⁡e=0.14381.1438 - \log e = 0.1438
    log⁡r=(0.693,−0.405)\log r = (0.693, -0.405) 0.1438−e−1=−0.22400.1438 - e^{-1} = -0.2240 0.1438−log⁡1=0.14380.1438 - \log 1 = 0.1438
    (0,0)(0, 0) 0−e−1=−0.36790 - e^{-1} = -0.3679 0−log⁡1=00 - \log 1 = 0

    For the first row: EP[T]=12(1.693)+12(0.595)=1.1438\mathbb{E}_P[T] = \tfrac12(1.693) + \tfrac12(0.595) = 1.1438, and EQ[eT−1]=EQ[r]=14⋅2+34⋅23=1\mathbb{E}_Q[e^{T-1}] = \mathbb{E}_Q[r] = \tfrac14 \cdot 2 + \tfrac34 \cdot \tfrac23 = 1. Every value is ≤KL=0.1438\le \mathrm{KL} = 0.1438. NWJ needs the exact constant in 1+log⁡r1 + \log r; DV ignores constants.

    (c) The GAN on this pair. D∗=p/(p+q)=(1/23/4,1/25/4)=(23,25)D^* = p/(p+q) = (\tfrac{1/2}{3/4}, \tfrac{1/2}{5/4}) = (\tfrac23, \tfrac25). Then

    V(D∗,G)=12log⁡23+12log⁡25+14log⁡13+34log⁡35=−1.3187,V(D^*, G) = \tfrac12\log\tfrac23 + \tfrac12\log\tfrac25 + \tfrac14\log\tfrac13 + \tfrac34\log\tfrac35 = -1.3187,

    and 2 JS−log⁡4=0.0676−1.3863=−1.31872\,\mathrm{JS} - \log 4 = 0.0676 - 1.3863 = -1.3187. The two agree.

    (d) InfoNCE by hand. A batch of N=3N = 3 pairs has the score matrix

    S=(310021111).S = \begin{pmatrix} 3 & 1 & 0 \\ 0 & 2 & 1 \\ 1 & 1 & 1 \end{pmatrix}.

    The row loss is ℓi=−Sii+log⁡∑jeSij\ell_i = -S_{ii} + \log\sum_j e^{S_{ij}}.

    • Row 1: log⁡(e3+e1+e0)=log⁡23.80=3.1698\log(e^3 + e^1 + e^0) = \log 23.80 = 3.1698, so ℓ1=3.1698−3=0.1698\ell_1 = 3.1698 - 3 = 0.1698. The softmax is (0.844,0.114,0.042)(0.844, 0.114, 0.042): the critic picks the right partner with probability 0.844.
    • Row 2: log⁡(e0+e2+e1)=log⁡11.107=2.4076\log(e^0 + e^2 + e^1) = \log 11.107 = 2.4076, so ℓ2=2.4076−2=0.4076\ell_2 = 2.4076 - 2 = 0.4076.
    • Row 3: all scores are equal, so the softmax is uniform and ℓ3=log⁡3=1.0986\ell_3 = \log 3 = 1.0986. This row gives no information: its saving log⁡3−ℓ3\log 3 - \ell_3 is 0.

    L=13(0.1698+0.4076+1.0986)=0.5587\mathcal{L} = \tfrac13(0.1698 + 0.4076 + 1.0986) = 0.5587, and the bound is log⁡3−0.5587=1.0986−0.5587=0.5399\log 3 - 0.5587 = 1.0986 - 0.5587 = 0.5399 nats. Adding any constant to a whole row (a function a(xi)a(x_i)) gives the same number. The bound can never pass log⁡3=1.0986\log 3 = 1.0986.

    5. In code #

    NumPy and SciPy check the numbers above, and a small simulation shows the log⁡N\log N ceiling. The notebook for this lesson has these cells and the exercises.

    import numpy as np
    from scipy.special import logsumexp, rel_entr
    from scipy.spatial.distance import jensenshannon
    
    p, q = np.array([0.5, 0.5]), np.array([0.25, 0.75])
    r = p / q
    gens = {"KL": lambda u: u * np.log(u), "reverse KL": lambda u: -np.log(u),
            "TV": lambda u: 0.5 * np.abs(u - 1), "chi2": lambda u: (u - 1) ** 2,
            "Hellinger2": lambda u: (np.sqrt(u) - 1) ** 2,
            "JS": lambda u: 0.5 * (u * np.log(u) - (u + 1) * np.log((u + 1) / 2))}
    for name, f in gens.items():
        print(name, round(np.sum(q * f(r)), 4))
    # KL 0.1438, reverse KL 0.1308, TV 0.25, chi2 0.3333, Hellinger2 0.0681, JS 0.0338
    print(rel_entr(p, q).sum(), jensenshannon(p, q) ** 2)   # 0.1438 0.0338 (SciPy agrees)
    
    # NWJ and DV with the critic T = log r: DV is tight, NWJ is not
    T = np.log(r)
    print(p @ T - q @ np.exp(T - 1), p @ T - np.log(q @ np.exp(T)))   # -0.2240  0.1438
    
    # GAN value at the optimal discriminator = 2 JS - log 4
    D = p / (p + q)
    print(p @ np.log(D) + q @ np.log(1 - D), 2 * jensenshannon(p, q) ** 2 - np.log(4))  # -1.3187 -1.3187
    
    # InfoNCE from a score matrix: log N - mean of the row cross-entropies
    def infonce_bound(S):
        N = S.shape[0]
        return np.log(N) - np.mean(-np.diag(S) + logsumexp(S, axis=1))
    
    S = np.array([[3., 1, 0], [0, 2, 1], [1, 1, 1]])
    print(infonce_bound(S))                                   # 0.5399
    
    # Correlated Gaussians in d dimensions: true MI = -d/2 log(1 - rho^2); optimal critic = pmi
    def pmi_scores(x, y, rho):
        v = 1 - rho**2
        diff = y[None, :, :] - rho * x[:, None, :]
        return (-0.5 * (diff**2).sum(-1) / v - 0.5 * x.shape[1] * np.log(v)
                + 0.5 * (y**2).sum(-1)[None, :])
    
    rng = np.random.default_rng(0)
    d, rho, N = 10, 0.95, 128
    x = rng.standard_normal((N, d))
    y = rho * x + np.sqrt(1 - rho**2) * rng.standard_normal((N, d))
    print(-d / 2 * np.log(1 - rho**2), np.log(N), infonce_bound(pmi_scores(x, y, rho)))
    # 11.64 (true MI)  4.852 (log N)  4.851 (InfoNCE: stuck just below log N)
    

    jensenshannon returns JS\sqrt{\mathrm{JS}}, so we square it. logsumexp computes log⁡∑jeSij\log\sum_j e^{S_{ij}} without overflow, even for scores near 1000.

    6. Where it shows up #

    • Contrastive pretraining. CPC (audio, images), SimCLR and MoCo (images), CLIP (image–text), and contrastive sentence embeddings all minimize an InfoNCE loss. The learned critic cos⁡(g(x),h(y))/τ\cos(g(x), h(y))/\tau is used later for zero-shot classification and retrieval: CLIP picks the caption with the largest score, which is the softmax classifier of this lesson.
    • Mutual information estimation. MINE (DV), NWJ and InfoNCE estimate the MI between high-dimensional variables, for example between layers of a network or between a representation and a label. Know their biases: InfoNCE is capped at log⁡N\log N, NWJ and DV are very noisy at high MI.
    • GANs and f-GANs. The discriminator is a critic of a variational bound on 2 JS−log⁡42\,\mathrm{JS} - \log 4; f-GAN does the same for any ff. See the generative models track.
    • Density-ratio estimation. A probabilistic classifier between two data sets gives log⁡r\log r as its logit. Uses: importance weights under covariate shift, and classifier two-sample tests: the best balanced accuracy is 12(1+TV)\frac12(1 + \mathrm{TV}), so a test accuracy aa shows TV≥2a−1\mathrm{TV} \ge 2a - 1 (up to the noise of the test).
    • ML for science. Neural ratio estimation in simulation-based inference (Hermans et al., 2020, building on the classifier trick of Cranmer et al., 2015) trains a classifier between simulator pairs (θ,x)(\theta, x) and shuffled pairs. Its logit estimates log⁡p(x∣θ)p(x)\log\frac{p(x \mid \theta)}{p(x)}, the pmi of this lesson with P=p(θ,x)P = p(\theta, x) and Q=p(θ)p(x)Q = p(\theta)p(x). Multiplied by the prior, the ratio gives the posterior: p(θ∣x)=p(θ) epmi⁡(θ,x)p(\theta \mid x) = p(\theta)\,e^{\operatorname{pmi}(\theta, x)}. Checking an emulator: to compare a generative model of weather fields or seismic waveforms with the simulator, train a classifier between their samples; an accuracy near 50% means a small TV, as far as the classifier can tell. Cross-modal contrastive models such as AstroCLIP align galaxy images with spectra by a CLIP-style InfoNCE loss.

    7. Common mistakes #

    • Reading log⁡N−L\log N - \mathcal{L} as the mutual information. It is a lower bound, capped at log⁡N\log N. A value near log⁡N\log N says "at least this much", not "exactly this much".
    • Swapping PP and QQ. Df(P ∥ Q)D_f(P\,\|\,Q) averages under QQ and uses r=p/qr = p/q. With f(u)=ulog⁡uf(u) = u\log u you get KL(P ∥ Q)\mathrm{KL}(P\,\|\,Q), not KL(Q ∥ P)\mathrm{KL}(Q\,\|\,P).
    • Using the DV critic in NWJ. NWJ is not invariant to constant shifts: T=log⁡rT = \log r is optimal for DV but gives KL−e−1\mathrm{KL} - e^{-1} in NWJ. The NWJ optimum is 1+log⁡r1 + \log r.
    • Ignoring the domain of f∗f^*. Reverse KL needs T<0T < 0, squared Hellinger T<1T < 1, TV ∣T∣≤12|T| \le \frac12, the GAN generator T<0T < 0. Outside, f∗(t)=+∞f^*(t) = +\infty and the bound is −∞-\infty. f-GAN uses an output activation to stay inside.
    • Treating a one-batch estimate as a bound. Only the expected value is a bound. A minibatch DV estimate is biased upward; an NWJ estimate is unbiased but very noisy. Both can lie above the true value.
    • Comparing generator tables without checking conventions. ff and f+c(u−1)f + c(u - 1) give the same divergence, and factors of 12\frac12 (JS, Hellinger) differ between papers. Check f(1)=0f(1) = 0, or compute Df(P ∥ P)=0D_f(P\,\|\,P) = 0.
    • Forgetting the class sizes. With nP≠nQn_P \ne n_Q the classifier's logit is log⁡r(x)+log⁡(nP/nQ)\log r(x) + \log(n_P/n_Q), not log⁡r(x)\log r(x).

    8. Check yourself #

    1. Show that the Pearson χ2(P ∥ Q)\chi^2(P\,\|\,Q) equals VarQ(r)\mathrm{Var}_Q(r).
      Answerχ2=EQ[(r−1)2]\chi^2 = \mathbb{E}_Q[(r - 1)^2], and EQ[r]=1\mathbb{E}_Q[r] = 1. So it is the variance of rr under QQ.
    2. Derive f∗f^* and the optimal critic for f(u)=(u−1)2f(u) = (u - 1)^2, and write the variational bound.
      AnswerThe derivative of tu−(u−1)2tu - (u-1)^2 is t−2(u−1)t - 2(u - 1), zero at u=1+t/2u = 1 + t/2 (this needs u≥0u \ge 0, so t≥−2t \ge -2). Then f∗(t)=t(1+t/2)−t2/4=t+t2/4f^*(t) = t(1 + t/2) - t^2/4 = t + t^2/4. T∗=f′(r)=2(r−1)T^* = f'(r) = 2(r - 1). Bound: χ2(P ∥ Q)≥EP[T]−EQ[T+T2/4]\chi^2(P\,\|\,Q) \ge \mathbb{E}_P[T] - \mathbb{E}_Q[T + T^2/4].
    3. P=N(μ,1)P = \mathcal{N}(\mu, 1) and Q=N(0,1)Q = \mathcal{N}(0, 1). Give the KL, the optimal NWJ critic, and the variance of eT∗−1e^{T^* - 1} under QQ. About how many samples of QQ give a standard error of 0.1 on the QQ-term when KL=5\mathrm{KL} = 5 nats?
      AnswerKL=μ2/2\mathrm{KL} = \mu^2/2. log⁡r(x)=μx−μ2/2\log r(x) = \mu x - \mu^2/2, so T∗(x)=1+μx−μ2/2T^*(x) = 1 + \mu x - \mu^2/2. VarQ(r)=χ2=eμ2−1=e2 KL−1\mathrm{Var}_Q(r) = \chi^2 = e^{\mu^2} - 1 = e^{2\,\mathrm{KL}} - 1. For KL=5\mathrm{KL} = 5: e10−1≈22,025e^{10} - 1 \approx 22{,}025. The standard error of a mean of nn samples is 22,025/n\sqrt{22{,}025/n}, which is 0.1 for n≈2.2×106n \approx 2.2 \times 10^6.
    4. You classify samples of PP against samples of QQ (equal priors). What is the best possible accuracy? What is it for P=(12,12)P = (\tfrac12, \tfrac12) and Q=(14,34)Q = (\tfrac14, \tfrac34)?
      AnswerPredict PP where p>qp > q. The accuracy is 12∑xmax⁡(p,q)=12(1+TV)\frac12\sum_x \max(p, q) = \frac12(1 + \mathrm{TV}), because max⁡(p,q)=p+q2+∣p−q∣2\max(p, q) = \frac{p+q}{2} + \frac{|p-q|}{2}. Here 12(12+34)=0.625=12(1+0.25)\frac12(\frac12 + \frac34) = 0.625 = \frac12(1 + 0.25).
    5. A contrastive model with batch size 1024 reports log⁡N−L=6.85\log N - \mathcal{L} = 6.85 nats. What can you conclude about I(X;Y)I(X;Y)?
      Answerlog⁡1024=6.93\log 1024 = 6.93. You can conclude I≳6.85I \gtrsim 6.85 nats (up to estimation noise), nothing more. The bound is near its ceiling, so the true MI may be much larger. A larger NN or another estimator is needed to say more.
    6. Why is DV ≥\ge NWJ for the same critic TT? When are they equal?
      AnswerDV(T)=max⁡cNWJ(T+c)≥NWJ(T+0)\mathrm{DV}(T) = \max_c \mathrm{NWJ}(T + c) \ge \mathrm{NWJ}(T + 0). They are equal when the best shift is c=1−log⁡EQ[eT]=0c = 1 - \log\mathbb{E}_Q[e^T] = 0, that is, when EQ[eT]=e\mathbb{E}_Q[e^T] = e.
    Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
    1. What is the logit of the best classifier between samples of PP (label 1) and QQ (label 0), with equal class sizes?

    2. Define the f-divergence Df(P ∥ Q)D_f(P\,\|\,Q).

    3. Give the generators of KL and of total variation.

    4. State the variational lower bound for an f-divergence.

    5. What is the optimal critic in the variational bound, and why?

    6. Write the Donsker–Varadhan bound on KL.

    7. Why do NWJ and MINE estimates of MI get very noisy when the MI is large?

    8. State the InfoNCE bound and its ceiling.

    9. What is the optimal InfoNCE critic?

    10. What is the GAN value V(D∗,G)V(D^*, G) at the optimal discriminator D∗=p/(p+q)D^* = p/(p+q)?

    Open the review →

    9. Interview angle #

    • "How does contrastive learning relate to mutual information?" — The InfoNCE loss is a softmax cross-entropy that picks the positive among NN candidates; log⁡N−L\log N - \mathcal{L} is a lower bound on I(X;Y)I(X;Y) between the two views, capped at log⁡N\log N.
    • "Why do contrastive methods need many negatives?" — The bound cannot exceed log⁡N\log N; to certify II nats you need N≥eIN \ge e^{I}. More negatives also make the task harder and the gradient less noisy.
    • "What is the optimal discriminator of a GAN, and what does the generator minimize?" — D∗=p/(p+q)D^* = p/(p+q); the generator then minimizes 2 JS−log⁡42\,\mathrm{JS} - \log 4.
    • "How do you estimate KL or MI when you only have samples?" — Train a critic and maximize a variational bound (NWJ, DV/MINE, InfoNCE), or train a classifier and use its logit as the log density ratio.
    • "What is an f-divergence? Name four." — EQ[f(p/q)]\mathbb{E}_Q[f(p/q)] with convex ff, f(1)=0f(1) = 0: KL (ulog⁡uu\log u), reverse KL (−log⁡u-\log u), TV (12∣u−1∣\frac12|u - 1|), χ2\chi^2 ((u−1)2(u - 1)^2).
    • "Why can GAN training stall?" — When the supports hardly overlap, JS is close to log⁡2\log 2 and flat, so the generator gets almost no gradient. Non-saturating losses and Wasserstein critics help.

    10. Practice #

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

    1. Compute six f-divergences from their generators for P=(12,12)P = (\frac12, \frac12), Q=(14,34)Q = (\frac14, \frac34) and check them against SciPy.
    2. Write infonce_lower_bound(scores) with logsumexp, and show that it never passes log⁡N\log N.
    3. Write nwj_lower_bound and dv_lower_bound from a score matrix, and compare the bias and variance of the three bounds on correlated Gaussians.
    4. Estimate a log density ratio with scikit-learn's LogisticRegression on quadratic features and compare it with the true one.
    5. Learn a quadratic critic T(x,y)=a x⊤y−b ∥y∥2T(x, y) = a\,x^\top y - b\,\|y\|^2 by gradient steps on the InfoNCE loss, and compare (a,b)(a, b) with the optimal critic.

    11. Watch and read #

    The tangent-line argument of section 3, step by step, with a check on several critics.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    How SimCLR builds positive pairs with augmentations and uses the InfoNCE (NT-Xent) loss.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    The symmetric contrastive loss over an image–text similarity matrix, and zero-shot classification.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    The f-GAN talk: divergences, the variational bound with a critic, and output activations.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play