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").
Contrastive learning. CPC, SimCLR, MoCo and CLIP train encoders with the InfoNCE loss.
It is a softmax cross-entropy over a batch, and logN minus the loss is a lower bound on the
mutual information between two views. The logN 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 2JS−log4, 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 is the natural log, so every value in this lesson is in nats
(divide by log2≈0.693 for bits). PyTorch and NumPy losses are in nats too.
Picture 1: a classifier learns the density ratio #
Take two distributions P and Q with densities p and q. Draw samples of both. Give every
sample of P the label 1 and every sample of Q the label 0, with equal numbers of each.
Now ask: what is the best possible classifier? Bayes' rule answers this in three steps.
The two classes are equally likely, so Pr(label 1)=Pr(label 0)=21.
Bayes' rule: Pr(1∣x)=21p(x)+21q(x)21p(x)=p(x)+q(x)p(x),
and Pr(0∣x)=p(x)+q(x)q(x).
The logit (log-odds) is the log of their ratio:
logPr(0∣x)Pr(1∣x)=logq(x)p(x).
So the best classifier's logit is the log density ratiologr(x), with 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) and Q=N(0,1). The constants of the two Gaussian
densities cancel:
logr(x)=−2(x−1)2+2x2=2−x2+2x−1+x2=x−21.
The log ratio is a straight line: a logistic regression on x can represent it exactly. If the
class sizes differ, nP=nQ, the logit becomes logr(x)+log(nP/nQ): a constant shift.
Interactive figure: loading…
Press "Draw samples and fit the classifier". The blue density is P
(label 1) and the orange one is Q (label 0). The lower chart shows the
true log ratio logp(x)/q(x) (dark line) and the logit of a logistic classifier
fitted on the features 1,x,x2 (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 x 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 P (label 1) and 1000 samples of Q (label 0). At a point x its best possible output is Pr(1∣x)=0.8. What is p(x)/q(x)?
Why.
With equal class sizes, Pr(1∣x)=p/(p+q), so p/q=Pr(1∣x)/Pr(0∣x)=0.8/0.2=4. The output 0.8 is a probability, not the ratio itself; 0.25 is q/p, the ratio upside down.
The second picture is about convex functions. A convex function f lies above each of its
tangent lines. In fact f is the upper envelope of its tangent lines: at every point u,f(u) equals the highest tangent line at that point.
Name each line by its slope t. Write the line as u↦tu−f∗(t), so −f∗(t) is the
point where the line crosses the vertical axis. For the line to be a tangent line, f∗(t) must be
supu[tu−f(u)]: the largest gap between the line tu and the graph of f. Then:
for every slope t and every point u:f(u)≥tu−f∗(t) (the line is below f);
for the best slope, t=f′(u), the line touches f at u and the two sides are equal.
Now the key step. In a divergence, u will be the density ratio r(x) at a point x. We may
choose a different slope at every point: a function T(x). However badly we choose it, the line
stays below f:
f(r(x))≥T(x)r(x)−f∗(T(x))(every x).
In section 3 we average this over Q, and the unknown ratio r(x) disappears. What remains is
a lower bound made of two averages over samples. The function T is the critic.
Interactive figure: loading…
Move the slope t. The dark curve is the generator f (here f(u)=ulogu of KL). The
magenta line with slope t stays below the curve; it touches it at the
yellow dot and crosses the vertical axis at −f∗(t). The
aqua segment at the ratio u 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 f rebuilt as
the envelope of its lines. Switch to TV and notice the kink at u=1.
Notation.P and Q are distributions on the same space, with densities (or probability mass
functions) p and q. Unless we say otherwise, we assume p(x)>0 only where q(x)>0. Then
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) (or T(x,y) for pairs). In this lesson the letter f is always
a convex generator, and critics are always called T.
The average is under the second argument Q, and the ratio has p on top. The generator
says how much a ratio u is penalized; u=1 (no difference) costs f(1)=0.
Theorem (non-negativity).Df(P∥Q)≥0, and Df(P∥P)=0.
Proof.
The ratio has average 1 under Q:EQ[r]=∫q(x)q(x)p(x)dx=∫p(x)dx=1.
Jensen's inequality for the convex f (lesson 03):
EQ[f(r)]≥f(EQ[r]).
With step 1, the right side is f(1)=0. If P=Q, then r=1 everywhere and
Df=EQ[f(1)]=0.■
If f is strictly convex at u=1, then Df=0 only when P=Q. Every f-divergence also
satisfies the data processing inequality of lesson 07.
Three facts that prevent confusion.
The generator is not unique.f(u) and f(u)+c(u−1) give the same divergence for every
constant c, because EQ[r−1]=0. For example, ulogu−u+1 also gives KL,
and it is ≥0 for every u. Tables in papers differ by such terms and by constant factors.
Swapping the arguments.Df(Q∥P)=Df~(P∥Q) with f~(u)=uf(1/u).
For f(u)=ulogu this gives f~(u)=−logu: the reverse KL.
Points outside the support. A point with q(x)=0<p(x) contributes
p(x)limu→∞f(u)/u. This is +∞ for KL and χ2, but finite for TV, Hellinger
and JS. A point with p(x)=0<q(x) contributes q(x)f(0), which is +∞ for reverse KL.
The six standard generators.M=21(P+Q) is the mixture. The last two columns are
explained below (conjugate and optimal critic).
Divergence
Df(P∥Q)
Generator f(u)
Conjugate f∗(t)
Optimal critic T∗=f′(r)
KL
∫plogqp
ulogu
et−1
1+logr
reverse KL
∫qlogpq
−logu
−1−log(−t), for t<0
−1/r
total variation (TV)
21∫∣p−q∣
21∣u−1∣
t, for ∣t∣≤21
21sign(r−1)
Pearson χ2
∫q(p−q)2
(u−1)2
t+4t2, for t≥−2
2(r−1)
squared Hellinger H2
∫(p−q)2
(u−1)2
1−tt, for t<1
1−1/r
Jensen–Shannon (JS)
21KL(P∥M)+21KL(Q∥M)
21[ulogu−(u+1)log2u+1]
−21log(2−e2t), for t<21log2
21log1+r2r
Two inequalities link these divergences:
KL(P∥Q)≤log(1+χ2(P∥Q)). Proof: KL=EP[logr]≤logEP[r]
(Jensen, log is concave), and EP[r]=EQ[r2]=1+χ2.
Pinsker's inequality:TV(P,Q)≤KL(P∥Q)/2, with KL in nats (no proof here).
Definition. The convex conjugate (or Fenchel conjugate) of f is
f∗(t)=u≥0sup[tu−f(u)].
It is the largest gap between the line tu and the graph of f. As a supremum of functions that
are affine in t,f∗ is convex.
Example (KL), step by step.f(u)=ulogu.
Maximize g(u)=tu−ulogu. Its derivative is t−logu−1.
Set it to zero: logu=t−1, so u=et−1.(g is concave, so this is the maximum.)
Insert this u:f∗(t)=tet−1−et−1(t−1)=et−1.
Fenchel–Young inequality. For all u≥0 and all t:f(u)≥tu−f∗(t). Equality holds
exactly when t is a slope of f at u(t=f′(u) when f is differentiable). This is
picture 2 in one line.
Fenchel–Moreau theorem. If f is convex and lower semicontinuous (its epigraph is a closed
set), then f∗∗=f, that is, f(u)=supt[tu−f∗(t)]:f is the envelope of its tangent
lines. All generators in the table have this property.
Theorem (variational lower bound). Let f be a convex, lower semicontinuous generator with
f(1)=0, and let p>0 only where q>0. For every critic T whose values lie where
f∗ is finite (and with finite expectations):
Df(P∥Q)≥Ex∼P[T(x)]−Ex∼Q[f∗(T(x))].
Equality holds when T(x) is a slope of f at r(x) for (Q-almost) every x, for example
T∗(x)=f′(r(x)). Hence Df(P∥Q)=supT{EP[T]−EQ[f∗(T)]}.
Proof.
Fenchel–Young at u=r(x) and t=T(x):f(r(x))≥T(x)r(x)−f∗(T(x)) for every x.
Multiply by q(x)≥0 and integrate over x. The left side becomes ∫qf(r)=Df(P∥Q).
On the right, q(x)r(x)=p(x). So ∫qTr=∫pT=EP[T], and
∫qf∗(T)=EQ[f∗(T)]. This gives the bound.
Step 1 is an equality at x exactly when T(x) is a slope of f at r(x). For
T∗=f′(r) this holds at every x, so the bound is an equality. ■
What the theorem gives you in practice.
Only samples are needed. Replace EP and EQ by averages over samples of
P and of Q. No density is evaluated.
Any critic is safe. With a restricted family of critics T (for example a neural
network), supT∈T≤Df. The gap is how well T can represent
T∗=f′(r).
The best critic knows the density ratio:r=(f′)−1(T∗). Training the critic is
density-ratio estimation, as in picture 1.
Quick check
For the KL generator f(u)=ulogu, what is the optimal critic T∗(x)?
Why.
T∗=f′(r)=logr+1. The tempting answer logr is the optimal critic of the Donsker–Varadhan bound (next part), which ignores constant shifts; the bound with f∗(t)=et−1 does not, and logr gives KL−e−1 there.
NWJ bound. Put f(u)=ulogu and f∗(t)=et−1 into the theorem. This gives the bound of
Nguyen, Wainwright and Jordan (2010):
KL(P∥Q)≥EP[T]−EQ[eT−1],T∗=1+logr.
Check at T∗:EP[1+logr]−EQ[elogr]=1+KL−EQ[r]=1+KL−1=KL.
Donsker–Varadhan (DV) bound.
KL(P∥Q)≥EP[T]−logEQ[eT].
Proof (DV is NWJ with the best constant shift).
Apply NWJ to the shifted critic T+c, with a constant c:KL≥EP[T]+c−ec−1EQ[eT].
Maximize the right side over c. Its derivative is 1−ec−1EQ[eT], which is zero at
c=1−logEQ[eT].
Insert this c:EP[T]+1−logEQ[eT]−1=EP[T]−logEQ[eT].■
So for the same critic, DV ≥ NWJ. DV does not change when you add a constant to T, and its
optimal critics are logr+c for any constant c.MINE (Belghazi et al., 2018) maximizes DV
with a neural critic.
Mutual information is a KL divergence (lesson 07):
I(X;Y)=KL(p(x,y)∥p(x)p(y)).
So put P=p(x,y) (the joint) and Q=p(x)p(y) (the product of the marginals) into NWJ
and DV. The density ratio is p(x)p(y)p(x,y)=epmi(x,y), where
pmi(x,y)=logp(x)p(y)p(x,y)=logp(y)p(y∣x) is the
pointwise mutual information. The critic is a function T(x,y) of a pair.
Where do the samples come from? Take a batch of N pairs (x1,y1),…,(xN,yN) drawn
from p(x,y) and form the score matrixSij=T(xi,yj).
The diagonal Sii uses true pairs: these are positive pairs, samples of P=p(x,y).
An off-diagonal entry Sij,i=j, pairs xi with the y of another example. Since
the examples are independent, (xi,yj) is a sample of Q=p(x)p(y): a negative pair.
NWJ and DV average the diagonal for EP and the off-diagonal for EQ.
Why these estimates are noisy when the MI is large. At the optimal NWJ critic, the Q-term
averages eT∗−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,
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−1: about 164 at
I=2.55 nats, and about 1.3×1010 at I=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. By Jensen, E[logm^]≤logE[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 ρ and d. Each magenta dot is the estimate
from one batch of N correlated Gaussian pairs, with the optimal critic. The
violet line is the true MI, I=−2dlog(1−ρ2), and the
dashed line is logN. Use "Try": at low MI the three estimators agree. At high MI, notice that
InfoNCE has a small spread but stops below logN, 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
i, it asks a classification question: which of the N candidates y1,…,yN is the
true partner of xi? A softmax over the row turns the scores into probabilities, and the loss
is the cross-entropy of the correct answer j=i:
LInfoNCE=N1i=1∑N−log∑j=1NeSijeSii.
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) is darker when the softmax of row
i gives more probability to candidate yj; the framed diagonal holds the true partners. The
bars compare the true MI (violet) with the
InfoNCE boundlogN−L (magenta) and the ceiling logN
(dashed). Raise ρ to 0.99 and d to 10: the bound stops at logN. Then increase N.
Choose the constant critic: the rows become uniform and the bound is 0.
Theorem (InfoNCE bound). Let (x,y1)∼p(x,y), and let y2,…,yN∼p(y) be
independent of each other and of (x,y1). For any critic T, let
LInfoNCE=E[−log∑j=1NeT(x,yj)eT(x,y1)].
Then
I(X;Y)≥logN−LInfoNCE,
and the bound never passes the ceiling: logN−LInfoNCE≤logN.
Why it is true, in one picture. Hide the true partner at a random position c among N
candidates. Guessing c at random costs logN nats of cross-entropy. A good critic lowers the
loss, and the saving logN−L is information about c. But the only thing that
reveals c is the dependence between x and its partner, so the saving cannot exceed I(X;Y).
And a cross-entropy is never negative, so the saving cannot exceed logN.
Proof of the InfoNCE bound (five steps)
A classification game. Put the positive at a uniformly random position
c∈{1,…,N} instead of position 1. The softmax treats all positions alike, so the
loss does not change. Write D=(x,y1,…,yN). The softmax
q(c=i∣D)=eT(x,yi)/∑jeT(x,yj) is a classifier that guesses c from D,
and L is its cross-entropy.
Cross-entropy ≥ entropy (lesson 04), for each
D:L≥H(c∣D). Since c is uniform, H(c)=logN. So
logN−L≤H(c)−H(c∣D)=I(c;D).
Chain rule for mutual information:I(c;D)=I(c;y1:N)+I(c;x∣y1:N). Without
x, the yj are independent draws of p(y) whatever c is, so I(c;y1:N)=0.
I(c;x∣y1:N)=H(x∣y1:N)−H(x∣c,y1:N). Given c and all the y's,
x depends only on its partner yc, and (x,yc)∼p(x,y). So
H(x∣c,y1:N)=H(X∣Y). Conditioning reduces entropy, so
H(x∣y1:N)≤H(X). Together: I(c;x∣y1:N)≤H(X)−H(X∣Y)=I(X;Y).
(For continuous x the same steps hold with differential entropies.)
Steps 2–4 give logN−L≤I(X;Y). A cross-entropy is ≥0, so also
logN−L≤logN.■
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). So the optimal critic is
T∗(x,y)=logp(y)p(y∣x)+a(x)=pmi(x,y)+a(x),
for any function a(x) of x alone: it adds the same number to a whole row, and the softmax
removes it. With T∗ the bound tends to I(X;Y) as N→∞. For a finite N it stays
below I, and never above logN.To certify I nats you need N≥eI.
Bias and variance, side by side.
Bound
Bias
Variance
Ceiling
InfoNCE
below I for finite N, even with T∗
low: the softmax normalizes inside each row
logN
NWJ
none at T∗: the sample mean is unbiased for the bound
at least eI−1 per negative pair (e2I−1 for Gaussians)
none
DV / MINE
the 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 N
samples can show at most O(logN).
Answers to section 1. (1) At most log256=5.55 nats, whatever the critic. The true value
is 30 nats, but the bound cannot see more than logN; you would need N≥e30≈1013.
(2) With equal numbers of each, the best classifier's logit is the log density ratio between true
pairs p(x,y) and shuffled pairs p(x)p(y): the pointwise mutual informationpmi(x,y). Its average over true pairs is I(X;Y).
Quick check
A contrastive model uses batches of N=128 pairs. What is the largest value that logN−LInfoNCE can take, whatever the true mutual information?
Why.
The loss is a cross-entropy, so it is ≥0, and the bound is at most log128=4.85 nats. 7 is log2128: the same ceiling in bits, not nats. A better critic cannot pass the ceiling; only a larger N can.
Quick check
For the optimal InfoNCE critic T∗(x,y)=pmi(x,y), you add 5∥x∥2 to every score. What happens to the InfoNCE loss?
Why.
5∥xi∥2 is the same for every entry of row i, and a softmax does not change when you add a constant to all its logits. Any function a(x) can be added to the optimal critic. Adding something that depends on y, such as 5∥y∥2, would change the loss.
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τ:
T(x,y)=τcos(g(x),h(y)),cos(a,b)=∥a∥∥b∥a⊤b.
CPC (van den Oord et al., 2018) introduced the name InfoNCE and the bound
I≥logN−L, with a log-bilinear critic z⊤Wc.
SimCLR (Chen et al., 2020) uses two augmentations of each image and the other 2N−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 N) and the column loss (each caption picks its image),
21(Limg→text+Ltext→img).
Why large batches? The ceiling logN is one reason: with N=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 generatorG with distribution Q against a discriminatorD(x)∈(0,1)
that tells real samples (from the data P) from generated ones. The value function is
V(D,G)=Ex∼P[logD(x)]+Ex∼Q[log(1−D(x))].
The discriminator maximizes V. 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)+q(x)p(x).
Theorem (GAN value at the optimal discriminator).V(D∗,G)=2JS(P∥Q)−log4.
Proof. Write M=21(P+Q), so p+q=2m.
V(D∗,G)=∫plogp+qp+∫qlogp+qq.
logp+qp=log2mp=logmp−log2, and the same for q.
So V=KL(P∥M)−log2+KL(Q∥M)−log2=2JS(P∥Q)−log4.■
So the generator, facing an optimal discriminator, minimizes the Jensen–Shannon divergence. The
minimum −log4 is reached exactly when Q=P (then D∗=21 everywhere). When P and Q
hardly overlap, JS is close to its maximum log2 and hardly changes when Q 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 p is blue, the generator density
q is orange, and the dark curve is the optimal discriminator
D∗=p/(p+q). The lower chart shows the GAN value at D∗ as a function of the generator mean
μ (magenta), with the current μ as a yellow dot.
Notice: the integral V(D∗,G) and 2JS−log4 agree to 4 digits. Move μ 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=P. What is the value V(D∗,G) at the optimal discriminator?
Why.
With Q=P,D∗=p/(2p)=21 everywhere, so V=log21+log21=−log4. This equals 2JS−log4 with JS=0. The value 0 is the other end: it is reached when the supports do not overlap and JS=log2.
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)): a network Vω with a real output, followed by an output
activation gf that maps R into the domain of f∗ (for example gf(v)=1−e−v<1
for squared Hellinger). Training solves the saddle-point problem
θminωmaxEx∼P[Tω(x)]−Ex∼Qθ[f∗(Tω(x))].
The inner max estimates Df(P∥Qθ) by the variational bound; the outer min moves
Qθ to reduce it.
The original GAN is one case, with fGAN(u)=ulogu−(u+1)log(u+1) and
fGAN∗(t)=−log(1−et) for t<0. Write the critic as T=logD with
D∈(0,1). Then −fGAN∗(T)=log(1−D), and the bound
EP[T]−EQ[fGAN∗(T)] is exactly V(D,G). The optimal critic
T∗=fGAN′(r)=log1+rr gives D∗=p+qp, and
DfGAN(P∥Q)=2JS−log4. Here fGAN(1)=−log4=0; this
is why the minimum is −log4 and not 0.
TV is also an integral probability metric. Its conjugate is f∗(t)=t on ∣t∣≤21, so
the theorem gives TV(P,Q)=sup∣T∣≤1/2(EP[T]−EQ[T]).
Replace the constraint "∣T∣≤21" by "T 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.
(a) Six f-divergences of one pair.P=(21,21) and Q=(41,43) on two
points. The ratios are r=p/q=(2,32), so every f-divergence is
Df=41f(2)+43f(32).
Reverse KL:41(−log2)+43(−log32)=−0.1733+0.3041=0.1308 nats. Not equal to KL.
TV:41⋅21∣2−1∣+43⋅21∣32−1∣=81+81=41.
χ2:41(2−1)2+43(32−1)2=41+121=31=0.3333.
Squared Hellinger:(1/2−1/4)2+(1/2−3/4)2=0.0429+0.0253=0.0681
(or 0.0341 with the factor 21).
JS:M=(83,85),KL(P∥M)=0.0323,KL(Q∥M)=0.0354, so
JS=21(0.0323+0.0354)=0.0338 nats, far below its maximum log2=0.693.
Checks: KL=0.1438≤log(1+χ2)=log34=0.2877, and Pinsker:
TV=0.25≤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)).
NWJ is EP[T]−EQ[eT−1] and DV is EP[T]−logEQ[eT].
Critic T
NWJ
DV
1+logr=(1.693,0.595)
1.1438−1=0.1438
1.1438−loge=0.1438
logr=(0.693,−0.405)
0.1438−e−1=−0.2240
0.1438−log1=0.1438
(0,0)
0−e−1=−0.3679
0−log1=0
For the first row: EP[T]=21(1.693)+21(0.595)=1.1438, and
EQ[eT−1]=EQ[r]=41⋅2+43⋅32=1. Every value is
≤KL=0.1438. NWJ needs the exact constant in 1+logr; DV ignores constants.
(c) The GAN on this pair.D∗=p/(p+q)=(3/41/2,5/41/2)=(32,52). Then
and 2JS−log4=0.0676−1.3863=−1.3187. The two agree.
(d) InfoNCE by hand. A batch of N=3 pairs has the score matrix
S=301121011.
The row loss is ℓi=−Sii+log∑jeSij.
Row 1: log(e3+e1+e0)=log23.80=3.1698, so ℓ1=3.1698−3=0.1698.
The softmax is (0.844,0.114,0.042): the critic picks the right partner with probability 0.844.
Row 2: log(e0+e2+e1)=log11.107=2.4076, so ℓ2=2.4076−2=0.4076.
Row 3: all scores are equal, so the softmax is uniform and ℓ3=log3=1.0986. This row
gives no information: its saving log3−ℓ3 is 0.
L=31(0.1698+0.4076+1.0986)=0.5587, and the bound is
log3−0.5587=1.0986−0.5587=0.5399 nats. Adding any constant to a whole row (a function
a(xi)) gives the same number. The bound can never pass log3=1.0986.
NumPy and SciPy check the numbers above, and a small simulation shows the logN ceiling. The
notebook for this lesson has these cells and the exercises.
importnumpyasnpfromscipy.specialimportlogsumexp,rel_entrfromscipy.spatial.distanceimportjensenshannonp,q=np.array([0.5,0.5]),np.array([0.25,0.75])r=p/qgens={"KL":lambdau:u*np.log(u),"reverse KL":lambdau:-np.log(u),"TV":lambdau:0.5*np.abs(u-1),"chi2":lambdau:(u-1)**2,"Hellinger2":lambdau:(np.sqrt(u)-1)**2,"JS":lambdau:0.5*(u*np.log(u)-(u+1)*np.log((u+1)/2))}forname,fingens.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.0338print(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 notT=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 4D=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-entropiesdefinfonce_bound(S):N=S.shape[0]returnnp.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 = pmidefpmi_scores(x,y,rho):v=1-rho**2diff=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,128x=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, so we square it. logsumexp computes
log∑jeSij without overflow, even for scores near 1000.
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))/τ 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 logN, NWJ and DV are very noisy at high MI.
GANs and f-GANs. The discriminator is a critic of a variational bound on
2JS−log4; f-GAN does the same for any f. See the
generative models track.
Density-ratio estimation. A probabilistic classifier between two data sets gives logr as
its logit. Uses: importance weights under covariate shift, and classifier two-sample tests:
the best balanced accuracy is 21(1+TV), so a test accuracy a shows
TV≥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) and shuffled pairs. Its logit estimates logp(x)p(x∣θ), the
pmi of this lesson with P=p(θ,x) and Q=p(θ)p(x). Multiplied by the prior, the
ratio gives the posterior: p(θ∣x)=p(θ)epmi(θ,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.
Reading logN−L as the mutual information. It is a lower bound, capped at
logN. A value near logN says "at least this much", not "exactly this much".
Swapping P and Q.Df(P∥Q) averages under Q and uses r=p/q. With
f(u)=ulogu you get KL(P∥Q), not KL(Q∥P).
Using the DV critic in NWJ. NWJ is not invariant to constant shifts: T=logr is optimal
for DV but gives KL−e−1 in NWJ. The NWJ optimum is 1+logr.
Ignoring the domain of f∗. Reverse KL needs T<0, squared Hellinger T<1, TV
∣T∣≤21, the GAN generator T<0. Outside, f∗(t)=+∞ and the bound is
−∞. 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.f and f+c(u−1) give the same
divergence, and factors of 21 (JS, Hellinger) differ between papers. Check f(1)=0, or
compute Df(P∥P)=0.
Forgetting the class sizes. With nP=nQ the classifier's logit is
logr(x)+log(nP/nQ), not logr(x).
Show that the Pearson χ2(P∥Q) equals VarQ(r).Answerχ2=EQ[(r−1)2], and EQ[r]=1. So it is the variance of r under Q.
Derive f∗ and the optimal critic for f(u)=(u−1)2, and write the variational bound.AnswerThe derivative of tu−(u−1)2 is t−2(u−1), zero at u=1+t/2 (this needs u≥0, so t≥−2). Then f∗(t)=t(1+t/2)−t2/4=t+t2/4.T∗=f′(r)=2(r−1). Bound: χ2(P∥Q)≥EP[T]−EQ[T+T2/4].
P=N(μ,1) and Q=N(0,1). Give the KL, the optimal NWJ critic, and the
variance of eT∗−1 under Q. About how many samples of Q give a standard error of 0.1
on the Q-term when KL=5 nats?AnswerKL=μ2/2.logr(x)=μx−μ2/2, so T∗(x)=1+μx−μ2/2.VarQ(r)=χ2=eμ2−1=e2KL−1. For KL=5:e10−1≈22,025. The standard error of a mean of n samples is 22,025/n, which is 0.1 for n≈2.2×106.
You classify samples of P against samples of Q (equal priors). What is the best possible
accuracy? What is it for P=(21,21) and Q=(41,43)?AnswerPredict P where p>q. The accuracy is 21∑xmax(p,q)=21(1+TV), because max(p,q)=2p+q+2∣p−q∣. Here 21(21+43)=0.625=21(1+0.25).
A contrastive model with batch size 1024 reports logN−L=6.85 nats. What can you
conclude about I(X;Y)?Answerlog1024=6.93. You can conclude I≳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 N or another estimator is needed to say more.
Why is DV ≥ NWJ for the same critic T? When are they equal?AnswerDV(T)=maxcNWJ(T+c)≥NWJ(T+0). They are equal when the best shift is c=1−logEQ[eT]=0, that is, when EQ[eT]=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.
What is the logit of the best classifier between samples of P (label 1) and Q (label 0), with equal class sizes?
The log density ratio logp(x)/q(x). With class sizes nP=nQ, add log(nP/nQ).
Define the f-divergence Df(P∥Q).
Ex∼Q[f(p(x)/q(x))], with f convex and f(1)=0.
Give the generators of KL and of total variation.
KL: f(u)=ulogu. TV: f(u)=21∣u−1∣.
State the variational lower bound for an f-divergence.
For every critic T:Df(P∥Q)≥EP[T]−EQ[f∗(T)], with f∗(t)=supu[tu−f(u)].
What is the optimal critic in the variational bound, and why?
T∗=f′(p/q): the slope of f at the density ratio, where the tangent line touches f (Fenchel–Young is an equality).
Write the Donsker–Varadhan bound on KL.
KL(P∥Q)≥EP[T]−logEQ[eT], tight for T=log(p/q)+c.
Why do NWJ and MINE estimates of MI get very noisy when the MI is large?
The Q-term averages the density ratio r over negative pairs, and VarQ(r)=χ2≥eI−1.
State the InfoNCE bound and its ceiling.
I(X;Y)≥logN−LInfoNCE, and logN−LInfoNCE≤logN because a cross-entropy is ≥0.
What is the optimal InfoNCE critic?
T∗(x,y)=logp(y)p(y∣x)+a(x): the pointwise mutual information plus any function of x alone.
What is the GAN value V(D∗,G) at the optimal discriminator D∗=p/(p+q)?
2JS(P∥Q)−log4; its minimum −log4 is reached at Q=P.
"How does contrastive learning relate to mutual information?" — The InfoNCE loss is a softmax
cross-entropy that picks the positive among N candidates; logN−L is a lower bound
on I(X;Y) between the two views, capped at logN.
"Why do contrastive methods need many negatives?" — The bound cannot exceed logN; to certify
I nats you need N≥eI. 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); the generator then minimizes 2JS−log4.
"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)] with convex f,f(1)=0: KL
(ulogu), reverse KL (−logu), TV (21∣u−1∣),χ2((u−1)2).
"Why can GAN training stall?" — When the supports hardly overlap, JS is close to log2 and flat,
so the generator gets almost no gradient. Non-saturating losses and Wasserstein critics help.
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
Poole, Ozair, van den Oord, Alemi, Tucker, On Variational Bounds of Mutual Information
(2019): §2.2 (DV, MINE, NWJ), §2.3 (InfoNCE and its logK ceiling), and Figures 2–3 (bias and
variance on correlated Gaussians).