Module contents
Lesson 21 of 24Advanced 110 min

Contrastive estimation: from NCE to InfoNCE

Contrastive learning has a statistical origin in learning to distinguish observations from noise. Start with noise-contrastive estimation, move through negative sampling and derive InfoNCE. Its optimal critic is a density ratio, and its value bounds mutual information from below. Study where that bound saturates and how t-SNE and UMAP perform contrastive estimation on a neighbor graph.

After this lesson you can

  • Derive NCE from logistic regression discriminating data from noise and prove consistency when the model family contains the true distribution.
  • Derive InfoNCE as cross-entropy for identifying the positive among N candidates.
  • Prove that the optimal critic is proportional to p(y | x)/p(y) and that I(X; Y) ≥ log N − L_N.
  • Explain why the bound saturates at log N and the formal limits of estimating large mutual information.
  • Interpret t-SNE and UMAP as contrastive estimation over the edges of a neighbor graph.

Before you start

Motivation: the cost of normalization

Many models are easy to write except for one constant. A Markov random field or energy-based model defines a density through energy EθE_\theta:

pθ(x)=p~θ(x)Z(θ),p~θ(x)=e−Eθ(x),Z(θ)=∫e−Eθ(x) ⁣dx.p_\theta(\vb{x}) = \frac{\tilde p_\theta(\vb{x})}{Z(\theta)}, \qquad \tilde p_\theta(\vb{x}) = e^{-E_\theta(\vb{x})}, \qquad Z(\theta) = \int e^{-E_\theta(\vb{x})}\dd\vb{x}.

Evaluating p~θ\tilde p_\theta requires one network pass; evaluating partition function Z(θ)Z(\theta) requires an integral over the entire space. Maximum likelihood needs it: the gradient of log⁡pθ(x)\log p_\theta(\vb{x}) is

∇θlog⁡pθ(x)=∇θlog⁡p~θ(x)−Ex′∼pθ[∇θlog⁡p~θ(x′)],\grad_\theta \log p_\theta(\vb{x}) = \grad_\theta \log\tilde p_\theta(\vb{x}) - \E_{\vb{x}' \sim p_\theta}\big[\grad_\theta \log\tilde p_\theta(\vb{x}')\big],

with expectation under the model itself, estimable only by sampling it (using slow, hard-to-diagnose Markov chains). The same bottleneck appears in three platform topics:

  • Large-vocabulary language models. Next-word softmax normalizes over VV words: with VV on the order of 10510^5, every example pays VV dot products just for the denominator.
  • Self-supervised representations. Self-supervised learning wants two views of one image to be “likely together”; normalizing over all possible images is meaningless.
  • Neighbor embeddings. In t-SNE, normalization Z=∑k≠lwklZ = \sum_{k \neq l} w_{kl} sums n2n^2 pairs, making repulsion costly.

One idea addresses all three: learn to distinguish data from noise. If a classifier separates real samples from a known distribution, its optimum contains the density ratio, yielding density including its constant. The arc: noise-contrastive estimation (NCE) and consistency; word2vec negative sampling as simplified NCE losing normalization; InfoNCE, the categorical version used by CPC, SimCLR and CLIP, whose optimal critic is a density ratio and whose value bounds mutual information; limitations of that bound; and finally t-SNE and UMAP as points in the same contrastive family.

NCE: distinguish data from noise

The ideal classifier already knows the density

You have TdT_d samples x1,…,xTd\vb{x}_1, \dots, \vb{x}_{T_d} from unknown density pdp_d and generate Tn=νTdT_n = \nu T_d samples y1,…,yTn\vb{y}_1, \dots, \vb{y}_{T_n} from a chosen noise density pnp_n that can be sampled and evaluated. Mix them, label data C=1C = 1 and noise C=0C = 0. Priors are P(C=1)=1/(1+ν)\Pr(C = 1) = 1/(1 + \nu) and P(C=0)=ν/(1+ν)\Pr(C = 0) = \nu/(1 + \nu), so Bayes’ rule gives the probability that point u\vb{u} is data:

P(C=1∣u)=pd(u)pd(u)+ν pn(u)=σ(log⁡pd(u)−log⁡νpn(u)).\Pr(C = 1 \given \vb{u}) = \frac{p_d(\vb{u})}{p_d(\vb{u}) + \nu\, p_n(\vb{u})} = \sigmoid\big(\log p_d(\vb{u}) - \log \nu p_n(\vb{u})\big).

The Bayes classifier logit is log⁡pd−log⁡(νpn)\log p_d - \log(\nu p_n). Since pnp_n and ν\nu are known, learning the classifier learns log⁡pd\log p_d. Parametrize the logit with a density model and fit as logistic regression. The model need not be normalized.

The estimator

Three observations. It is logistic regression with fixed offset: −log⁡(νpn(u))-\log(\nu p_n(\vb{u})) enters the logit without a learned coefficient. Parameter cc is not tied to α\alpha: nothing in JTJ_T forces ec∫p~α=1e^{c}\int\tilde p_\alpha = 1; the next theorem says optimum achieves it automatically. No integral: each step evaluates p~α\tilde p_\alpha at Td+TnT_d + T_n points.

Why it works

As Td→∞T_d \to \infty with fixed ν\nu, JTJ_T converges to its population version

J(θ)=Ex∼pd[log⁡h(x;θ)]+ν Ey∼pn[log⁡(1−h(y;θ))].J(\theta) = \E_{\vb{x} \sim p_d}\big[\log h(\vb{x}; \theta)\big] + \nu\,\E_{\vb{y} \sim p_n}\big[\log(1 - h(\vb{y}; \theta))\big].

First consider an unrestricted model: log density is any function f=log⁡pmf = \log p_m.

Proof

Write both expectations as one integral. With s(u)=σ(f(u)−log⁡νpn(u))s(\vb{u}) = \sigmoid(f(\vb{u}) - \log \nu p_n(\vb{u})),

J(f)=∫[pd(u)log⁡s(u)+νpn(u)log⁡(1−s(u))] ⁣du.J(f) = \int \Big[p_d(\vb{u})\log s(\vb{u}) + \nu p_n(\vb{u})\log\big(1 - s(\vb{u})\big)\Big]\dd\vb{u}.

Maximize pointwise. For a=pd(u)≥0a = p_d(\vb{u}) \ge 0 and b=νpn(u)>0b = \nu p_n(\vb{u}) > 0, function g(s)=alog⁡s+blog⁡(1−s)g(s) = a\log s + b\log(1 - s) on (0,1)(0, 1) has derivative a/s−b/(1−s)a/s - b/(1 - s) and second derivative −a/s2−b/(1−s)2<0-a/s^2 - b/(1 - s)^2 < 0: strictly concave with unique maximum s∗=a/(a+b)s^* = a/(a + b). Since s↦fs \mapsto f is bijective (f=log⁡νpn+logit⁡sf = \log \nu p_n + \operatorname{logit} s), the maximum in ff is

σ(f−log⁡νpn)=pdpd+νpn  ⟺  efνpn=pdνpn  ⟺  f=log⁡pd,\sigmoid\big(f - \log\nu p_n\big) = \frac{p_d}{p_d + \nu p_n} \iff \frac{e^{f}}{\nu p_n} = \frac{p_d}{\nu p_n} \iff f = \log p_d,

where pd>0p_d > 0 (where pd=0<pnp_d = 0 < p_n, g(s)=blog⁡(1−s)g(s) = b\log(1 - s) decreases and its supremum occurs at limit s→0s \to 0, i.e., ef→0=pde^f \to 0 = p_d). If pnp_n vanished where pd>0p_d > 0, g(s)=alog⁡sg(s) = a\log s would grow without bound toward s=1s = 1: ff would be undetermined, requiring the assumption.

∎

Notice what was not imposed: normalization. The maximum integrates to 1 because it equals pdp_d, not by constraint. For a parametric model, Gutmann and Hyvärinen (2012) assume the family contains truth pd=pm(⋅ ;θ∗)p_d = p_m(\cdot\,; \theta^*) and prove (theorem 2) θ^T→θ∗\hat\theta_T \to \theta^* in probability under three conditions: (a) pnp_n positive wherever pdp_d is; (b) JTJ_T converges uniformly to JJ on θ\theta in probability; (c) matrix Iν=∫gg⊤Pν pd\mat{I}_\nu = \int \vb{g}\vb{g}\T P_\nu\, p_d, with g=∇θlog⁡pm(⋅ ;θ)∣θ∗\vb{g} = \grad_\theta \log p_m(\cdot\,; \theta)\vert_{\theta^*} and Pν=νpn/(pd+νpn)P_\nu = \nu p_n/(p_d + \nu p_n), has full rank. These are maximum-likelihood conditions plus support. In particular c^\hat c converges to −log⁡Z(α∗)-\log Z(\alpha^*): normalization is learned as another parameter. Exercises reconstruct the population proof.

Choosing noise

Consistency holds for almost any pnp_n; efficiency does not. Gutmann and Hyvärinen’s (2012) theorem 3 gives asymptotic covariance Σ\mat{\Sigma} of Td(θ^T−θ∗)\sqrt{T_d}(\hat\theta_T - \theta^*), with three useful corollaries:

  • More noise, less noise dependence. As ν→∞\nu \to \infty, Σ\mat{\Sigma} no longer depends on pnp_n (corollary 5) and for normalized models equals inverse Fisher information: NCE is asymptotically as efficient as maximum likelihood (corollary 6).
  • Noise equals data. If pn=pdp_n = p_d, Σ\mat{\Sigma} is (1+1/ν)(1 + 1/\nu) times limit ν→∞\nu \to \infty covariance (corollary 7): for normalized models, ν=1\nu = 1 gives twice inverse Fisher, ν=10\nu = 10 only 1.1 times.
  • Practical recipe: analytically evaluable log⁡pn\log p_n, easy to sample, similar to data in some respect (e.g., covariance), as abundant as computation permits.

The intuition: if noise differs greatly from data, the classifier succeeds without learning data shape. Almost any boundary separates a cloud from a distant Gaussian, and only overlap regions inform the model. The interactive shows this.

InteractiveDistinguish data from noise
Densities: data pdp_d, estimate p^=elog⁡pm\hat p = e^{\log p_m} and scaled noise νpn\nu p_n
  • data samples
  • true pdp_d
  • hatp\\hat p from NCE
  • ν pn\nu\, p_n
Classifier: probability that xx is a data point
  • h=sigma(logpm−lognupn)h = \\sigma(\\log p_m - \\log \\nu p_n) learned
  • Bayes: pd/(pd+νpn)p_d/(p_d + \nu p_n)
1.20
0.0
1
−log⁡Z-\log Z true−2.492
c^\hat c learned−2.451
Mass ∫p^\int \hat p0.988
KL⁡(pd ∥ p^)\KL(p_d \,\|\, \hat p)0.0018
Classifier accuracy72.8 %
Median KL across 20 repetitions…
Root mean squared error of c^\hat c…
Non-normalizable fits…
Data with log⁡p~(x)=0.6x+4x2−2x4\log\tilde p(x) = 0.6x + 4x^2 - 2x^4 (1000 samples, blue histogram) versus Gaussian noise N(μn,σn2)\mathcal{N}(\mu_n, \sigma_n^2) with ν⋅1000\nu \cdot 1000 samples. Model log⁡pm(x)=θ1x+θ2x2+θ3x3+θ4x4+c\log p_m(x) = \theta_1 x + \theta_2 x^2 + \theta_3 x^3 + \theta_4 x^4 + c contains the data and is NCE-fitted by Newton. Above, true and estimated densities and scaled noise; below, learned versus Bayes classifier. Readings compare c^\hat c and −log⁡Z-\log Z, summarizing error across 20 seeds. Try the selector's four noises and increase ν\nu.

Readings for the selector’s four noise types and ν=1\nu = 1:

  • Similar noise (N(0,1.22)\mathcal{N}(0, 1.2^2)). Orange overlaps truth, c^=−2.451\hat c = -2.451 versus −log⁡Z=−2.492-\log Z = -2.492, p^\hat p mass 0.988 and KL 0.0018. Classifier accuracy is only 72.8%: substantial overlap makes each sample informative. Across 20 repetitions median KL is 0.0036 and c^\hat c RMSE 0.080. With ν=10\nu = 10 they fall to 0.0015 and 0.065; with ν=0.25\nu = 0.25 rise to 0.0097 and 0.117.
  • Too narrow (σn=0.3\sigma_n = 0.3). Classifier accuracy 89.3% and c^=−2.469\hat c = -2.469 remains close, but tails with little noise are wrong: mass 0.684, KL 0.29, over 100 times similar noise. Three of 20 runs yield nonnormalizable models.
  • Too wide (σn=5\sigma_n = 5). Most noise lies far away and is easily classified (88.8%). Fitting remains stable but median KL 0.0105 is triple similar noise: only samples in [−2,2][-2, 2], less than one-third, inform shape.
  • Shifted (N(2.5,0.52)\mathcal{N}(2.5, 0.5^2)). Classifier accuracy 98.5% and fitting diverges: 14 of 20 runs give θ^4≥0\hat\theta_4 \ge 0. Almost no noise appears at x<1x < 1, so model can grow there without loss noticing. Theorem support condition (a) fails in practice, though not theory: pnp_n is positive everywhere but so tiny none appears in 1000 samples.

A recurring lesson: very high classifier accuracy indicates an overly easy task, not a good model.

Lab: the normalizing constant of a ring

A planar energy model shaped as a ring of radius RR:

E(x)=a(∥x∥2−R2)2,Z=∫R2e−E(x) ⁣dx=π∫0∞e−a(u−R2)2 ⁣du=π2πa(1+erf⁡(R2a)),E(\vb{x}) = a\big(\norm{\vb{x}}^2 - R^2\big)^2, \qquad Z = \int_{\R^2} e^{-E(\vb{x})}\dd\vb{x} = \pi\int_0^\infty e^{-a(u - R^2)^2}\dd u = \frac{\pi}{2}\sqrt{\frac{\pi}{a}}\Big(1 + \operatorname{erf}\big(R^2\sqrt a\big)\Big),

using polar coordinates and substitution u=r2u = r^2 (so r ⁣dr= ⁣du/2r\dd r = \dd u/2). Closed form checks the result; NCE does not use it. Exact sampling follows the same substitution: u=∥x∥2u = \norm{\vb{x}}^2 is normal with mean R2R^2 and deviation 1/2a1/\sqrt{2a} truncated to u>0u > 0, with uniform angle. First the cleanest case: energy shape is known and only parameter is cc. NCE is logistic regression with one variable (constant) and offset.

[ ]NCE from scratch: the constant of a ringBrowser
import numpy as np
from math import erf, pi, sqrt, log

a, R = 1.0, 1.5

def energia(X):
    """E(x) = a (|x|^2 - R^2)^2: un anillo de radio R. El modelo sin normalizar es exp(-E)."""
    q = (X ** 2).sum(1)
    return a * (q - R ** 2) ** 2

# Z en forma cerrada (coordenadas polares y u = r^2): pi * (1/2) sqrt(pi/a) (1 + erf(R^2 sqrt(a)))
logZ = log(pi ** 1.5 / (2 * sqrt(a)) * (1 + erf(R ** 2 * sqrt(a))))

def muestra_anillo(rng, n):
    """Muestreo exacto: u = |x|^2 es una normal truncada a [0, inf) y el ángulo es uniforme."""
    u = np.empty(0)
    while u.size < n:
        v = rng.normal(R ** 2, 1 / sqrt(2 * a), 2 * n)
        u = np.concatenate([u, v[v > 0]])
    ang = rng.uniform(0, 2 * pi, n)
    r = np.sqrt(u[:n])
    return np.column_stack([r * np.cos(ang), r * np.sin(ang)])

def log_ruido(X, s):
    """log de la densidad de N(0, s^2 I) en 2D."""
    return -(X ** 2).sum(1) / (2 * s * s) - np.log(2 * pi * s * s)

def nce(F, off, y, iters=60):
    """Regresión logística con desplazamiento fijo `off`: maximiza sum_t y_t G_t - log(1 + e^{G_t}),
    con G = F theta + off. Newton con búsqueda lineal hacia atrás."""
    th = np.zeros(F.shape[1])
    J = lambda t: (y * (F @ t + off) - np.logaddexp(0, F @ t + off)).sum()
    j = J(th)
    for _ in range(iters):
        h = 0.5 * (1 + np.tanh((F @ th + off) / 2))         # sigma(G), sin desbordes
        H = (F * (h * (1 - h))[:, None]).T @ F + 1e-9 * np.eye(F.shape[1])
        paso = np.linalg.solve(H, F.T @ (y - h))
        t = 1.0
        while not (J(th + t * paso) >= j) and t > 1e-6:
            t /= 2
        th = th + t * paso
        jn = J(th)
        if jn - j < 1e-10:
            break
        j = jn
    return th

def solo_c(Xd, Xn, s, nu):
    """NCE con la forma de la energía conocida: el único parámetro es c = -log Z."""
    X = np.vstack([Xd, Xn])
    y = np.r_[np.ones(len(Xd)), np.zeros(len(Xn))]
    off = -energia(X) - log_ruido(X, s) - np.log(nu)      # G = log p~ + c - log(nu p_n)
    return nce(np.ones((len(X), 1)), off, y)[0]

rng = np.random.default_rng(0)
Xd = muestra_anillo(rng, 2000)
Xn = rng.normal(0, 1.5, (2000, 2))
c = solo_c(Xd, Xn, 1.5, 1)
print(f"log Z exacto = {logZ:.4f}")
print(f"NCE con 2000 datos y 2000 de ruido N(0, 1.5^2 I): -c = {-c:.4f}  (error {-c - logZ:+.4f})")

With 2000 data and 2000 noise samples, −c^=1.7574-\hat c = 1.7574 versus log⁡Z=1.7164\log Z = 1.7164: log error 0.041, 4% in ZZ. Now the full problem: family log⁡pm=θ1∥x∥4+θ2∥x∥2+θ3x1+θ4x2+c\log p_m = \theta_1\norm{\vb{x}}^4 + \theta_2\norm{\vb{x}}^2 + \theta_3 x_1 + \theta_4 x_2 + c contains truth at θ∗=(−a,2aR2,0,0)\theta^* = (-a, 2aR^2, 0, 0) and c∗=−aR4−log⁡Zc^* = -aR^4 - \log Z. In two dimensions grid quadrature can check normalization, impossible in high dimensions.

[ ]The full model and its normalizationBrowser
def T(X):
    """Características de la familia: |x|^4, |x|^2, x1, x2 y la constante (para c)."""
    q = (X ** 2).sum(1)
    return np.column_stack([q ** 2, q, X[:, 0], X[:, 1], np.ones(len(X))])

verdad = np.array([-a, 2 * a * R ** 2, 0, 0, -a * R ** 4 - logZ])
g = np.linspace(-4, 4, 401)
dx = g[1] - g[0]
P = np.column_stack([v.ravel() for v in np.meshgrid(g, g)])

print("verdad:          ", np.round(verdad, 3))
for s in (0.3, 1.5, 6.0):
    rng = np.random.default_rng(7)
    Xd = muestra_anillo(rng, 2000)
    Xn = rng.normal(0, s, (2000, 2))
    X = np.vstack([Xd, Xn])
    y = np.r_[np.ones(2000), np.zeros(2000)]
    th = nce(T(X), -log_ruido(X, s), y)
    with np.errstate(over="ignore"):
        masa = np.exp(T(P) @ th).sum() * dx * dx            # cuadratura: solo posible en dimensión baja
    print(f"ruido s = {s}: ", np.round(th, 3), f"  integral de exp(modelo) = {masa:.3f}")

With noise width 1.5, close to the ring’s, parameters are near truth (−1.039-1.039 and 4.6814.681 versus −1-1 and 4.54.5) and model integral 1.027 without imposing 1. Narrow noise (s=0.3s = 0.3) barely reaches the ring and integral falls to 0.431: fit is good where noise exists and poor elsewhere. Very wide noise (s=6s = 6) gives 0.829: almost all noise is trivially classified. The final cell measures 25 repetitions comparing NCE against naive ZZ importance sampling Z^=1Tn∑tp~(yt)/pn(yt)\hat Z = \frac{1}{T_n}\sum_t \tilde p(\vb{y}_t)/p_n(\vb{y}_t) on the same noise samples.

[ ]Noise matters: 25 repetitionsBrowser
print("                    NCE                       muestreo de importancia")
for s in (0.3, 1.5, 6.0):
    for nu in (1, 10):
        e_nce, e_is = [], []
        for r in range(25):
            rng = np.random.default_rng(100 + r)
            Xd = muestra_anillo(rng, 1000)
            Xn = rng.normal(0, s, (nu * 1000, 2))
            e_nce.append(-solo_c(Xd, Xn, s, nu) - logZ)
            w = -energia(Xn) - log_ruido(Xn, s)                # log de los pesos p~/p_n
            e_is.append(np.log(np.mean(np.exp(w - w.max()))) + w.max() - logZ)
        e_nce, e_is = np.array(e_nce), np.array(e_is)
        print(f"s = {s:3.1f}, nu = {nu:2d}:  sesgo {e_nce.mean():+.3f}  rmse {np.sqrt((e_nce ** 2).mean()):.3f}"
              f"     sesgo {e_is.mean():+.3f}  rmse {np.sqrt((e_is ** 2).mean()):.3f}")

Numbers confirm corollaries. With similar noise (s=1.5s = 1.5), log⁡Z^\log\hat Z RMSE is 0.034 at ν=1\nu = 1 and 0.018 at ν=10\nu = 10; narrow 0.253 and 0.116; wide 0.137 and 0.045. Increasing ν\nu always helps, more with worse noise, as corollary 5 predicts. Importance sampling teaches another lesson: with narrow noise, naive estimator bias −1.788-1.788 underestimates ZZ by almost 6× because noise almost never reaches the ring and important weights do not appear. NCE with the same noise has no appreciable bias (+0.052+0.052): it also uses ring data. With good noise both are similar.

Negative sampling: NCE without normalization

word2vec skip-gram learns vector vw\vb{v}_w per word and vc′\vb{v}'_c per context, score swc=vc′⊤vws_{wc} = \vb{v}'^{\T}_c\vb{v}_w. Softmax modeling of p(c∣w)p(c \given w) normalizes over the vocabulary. Mikolov et al. (2013) replace it with negative sampling (NEG): for each observed pair (w,c)(w, c) draw kk contexts c1,…,ckc_1, \dots, c_k from noise PnP_n and maximize

log⁡σ(swc)+∑i=1kEci∼Pn[log⁡σ(−swci)].\log\sigmoid(s_{wc}) + \sum_{i=1}^{k}\E_{c_i \sim P_n}\big[\log\sigmoid(-s_{wc_i})\big].

The paper suggests kk from 5 to 20 for small datasets and kk from 2 to 5 for large; best noise was unigram to power 3/43/4, Pn(w)∝U(w)3/4P_n(w) \propto U(w)^{3/4}. Authors distinguish NCE: it requires noise samples and numerical probabilities, while NEG only samples; NCE approximately maximizes softmax log-probability, which they say is unimportant for their application.

The difference is one term. With kk negatives per positive, NCE logit is swc−log⁡(kPn(c))s_{wc} - \log(k P_n(c)); NEG uses only swcs_{wc}. NEG is NCE with kPn(c)=1k P_n(c) = 1 for every cc, an equality that does not hold. Apply the earlier pointwise argument to cell (w,c)(w, c) with a=p(w,c)a = p(w, c) and b=k p(w)Pn(c)b = k\,p(w) P_n(c): optimum satisfies σ(logit)=a/(a+b)\sigmoid(\text{logit}) = a/(a + b), i.e., logit=log⁡(a/b)\text{logit} = \log(a/b). For NCE with Pn=p(c)P_n = p(c) this gives

swcNCE−log⁡(k p(c))=log⁡p(w,c)k p(w)p(c)  ⟹  swcNCE=log⁡p(c∣w),s^{\mathrm{NCE}}_{wc} - \log\big(k\,p(c)\big) = \log\frac{p(w, c)}{k\,p(w)p(c)} \;\Longrightarrow\; s^{\mathrm{NCE}}_{wc} = \log p(c \given w),

the conditional log-probability, normalized without explicit normalization. For NEG, however,

swcNEG=log⁡p(w,c)p(w)p(c)−log⁡k=PMI⁡(w,c)−log⁡k,s^{\mathrm{NEG}}_{wc} = \log\frac{p(w, c)}{p(w)p(c)} - \log k = \operatorname{PMI}(w, c) - \log k,

pointwise mutual information shifted by log⁡k\log k. Levy and Goldberg (2014) derived this as implicit factorization: with sufficient dimension, negative-sampling skip-gram factorizes shifted PMI. The cell checks a random six-word, eight-context co-occurrence table by optimizing each cell’s expected loss.

[ ]NCE and negative sampling in a co-occurrence tableBrowser
rng = np.random.default_rng(3)
Pwc = rng.dirichlet(np.ones(48)).reshape(6, 8)          # p(w, c): 6 palabras, 8 contextos
pw, pc = Pwc.sum(1), Pwc.sum(0)
k = 5
pn = pc                                                  # ruido: la distribución de los contextos

def ajustar(desplazamiento, pasos=100):
    """Maximiza, celda a celda, la pérdida esperada con k negativos por positivo:
    p(w,c) log s(G) + k p(w) p_n(c) log s(-G), G = s_wc - desplazamiento.
    Newton por celda, con el paso recortado a 2 para que no se dispare lejos del óptimo."""
    S = np.zeros_like(Pwc)
    A, B = Pwc, k * pw[:, None] * pn[None, :]
    for _ in range(pasos):
        sg = 1 / (1 + np.exp(-(S - desplazamiento)))
        S = S + np.clip((A * (1 - sg) - B * sg) / ((A + B) * sg * (1 - sg)), -2, 2)
    return S

S_nce = ajustar(np.log(k * pn)[None, :])                 # NCE: el logit resta log(k p_n(c))
S_neg = ajustar(0.0)                                     # NEG (word2vec): el logit es s_wc sin más
pmi = np.log(Pwc / (pw[:, None] * pc[None, :]))
print("NCE: max |s - log p(c|w)|        =", f"{np.abs(S_nce - np.log(Pwc / pw[:, None])).max():.1e}")
print("NCE: sum_c exp(s_wc) por palabra =", np.exp(S_nce).sum(1).round(4))
print("NEG: max |s - (PMI - log k)|     =", f"{np.abs(S_neg - (pmi - np.log(k))).max():.1e}")
print("NEG: sum_c exp(s_wc) por palabra =", np.exp(S_neg).sum(1).round(3))

Both predictions hold to machine precision. NCE gives ∑ceswc=1\sum_c e^{s_{wc}} = 1 per word: self-normalization. NEG sums range 1.42–2.03: scores compare contexts for a word but are not probabilities. NEG learns representations, not a language probability model. Ma and Collins (2018) studied conditional variants, distinguishing binary NCE here and ranking NCE identifying the data candidate; ranking yields consistent estimates under weaker assumptions. The next section is essentially ranking.

From binary to categorical: InfoNCE

Find the positive among NN candidates

Instead of classifying points individually as data or noise, present one datum and N−1N - 1 noise samples and identify the datum. For representation learning the datum is a pair: anchor xx and positive y∼p(y∣x)y \sim p(y \given x) (another image view, next word, caption); negatives yj∼p(y)y_j \sim p(y) are independent of xx. A critic f(x,y)f(x, y) scores combinations and softmax regression over NN candidates estimates the positive position.

This is contrastive predictive coding (CPC) loss. An encoder produces ztz_t at each signal step (audio, image patches), an autoregressive model summarizes past as context ctc_t, and at each offset kk log-bilinear critic fk(zt+k,ct)=zt+k⊤Wkctf_k(z_{t+k}, c_t) = z_{t+k}\T\mat{W}_k c_t finds true zt+kz_{t+k} among negatives from other times and sequences. In LibriSpeech a CPC representation’s linear classifier reaches 64.6% phoneme classification versus 39.7% MFCC, 27.6% random encoder and 74.6% supervised; ImageNet linear accuracy 48.7%. The same loss with two augmented image views is SimCLR (next lesson’s temperature NT-Xent) and symmetrized image–text loss is CLIP.

Practical critic: cosine and temperature

Most modern methods use cosine between two embeddings divided by temperature,

f(x,y)=⟨zx,zy⟩τ,∥zx∥=∥zy∥=1.f(x, y) = \frac{\inner{\vb{z}_x}{\vb{z}_y}}{\tau}, \qquad \norm{\vb{z}_x} = \norm{\vb{z}_y} = 1.

The temperature controls how force is distributed across the candidates. Write sj=⟨za,zj⟩s_j = \inner{\vb{z}_a}{\vb{z}_j} for anchor za\vb{z}_a and the candidates (positive j=+j = +), and wj=esj/τ/∑kesk/τw_j = e^{s_j/\tau}/\sum_k e^{s_k/\tau} softmax weights. Differentiating L=−s+/τ+log⁡∑jesj/τ\mathcal{L} = -s_+/\tau + \log\sum_j e^{s_j/\tau},

∂L∂za=1τ(∑jwjzj−z+),∂L∂z+=−1−w+τza,∂L∂zj=wjτza    (j≠+).\pd{\mathcal{L}}{\vb{z}_a} = \frac{1}{\tau}\Big(\sum_j w_j \vb{z}_j - \vb{z}_+\Big), \qquad \pd{\mathcal{L}}{\vb{z}_+} = -\frac{1 - w_+}{\tau}\vb{z}_a, \qquad \pd{\mathcal{L}}{\vb{z}_j} = \frac{w_j}{\tau}\vb{z}_a \;\;(j \neq +).

A gradient descent step pulls the positive toward the anchor with a force of (1−w+)/τ(1 - w_+)/\tau and pushes each negative with wj/τw_j/\tau: each negative pushes in proportion to its softmax weight, i.e., similarity to anchor. Distant negatives receive almost no gradient. For normalized vectors only the sphere-tangent component matters; renormalization removes radial motion.

InteractiveInfoNCE as classification
  • anchor zaz_a
  • positive z+z^+
  • negatives
  • descent direction −∇L-\nabla\mathcal{L}
Softmax weights wj=esj/∑keskw_j = e^{s_j}/\sum_k e^{s_k} (the positive and the 6 negatives)
0.32+0.6610.0120.0030.0040.0050.026
0.200
Loss L=−log⁡w+\mathcal{L} = -\log w^+1.154
log⁡N−L\log N - \mathcal{L}0.792 (max. 1.946)
Positive weight w+w^+0.315
Hardest negative share0.967
Effective negatives1.07 of 6
Force on the anchor ∥∇zaL∥\|\nabla_{z_a}\mathcal{L}\|2.771
An anchor, positive and six negatives on the unit circle (N=7N = 7). Bars show softmax weights wjw_j; arrows show each point's descent direction −∇L-\nabla\mathcal{L} projected onto tangent, length relative to largest. Initially hard negative 1 is closer to anchor than positive. Lower temperature to 0.030.03: which negatives still receive force? Raise to 33: how do bars and total anchor force change? Disable normalization and lengthen anchor.

At τ=0.2\tau = 0.2 initially, positive gets only w+=0.315w_+ = 0.315 and negative 1, closer to anchor, gets 0.662: 96.7% of all negative weight. The effective number of negatives, (∑jwj)2/∑jwj2(\sum_j w_j)^2/\sum_j w_j^2 calculated over the six negatives, is 1.07: for practical purposes the loss sees just one negative. Raising τ\tau equalizes weights (3.89 effective at τ=1\tau = 1, 5.69 at τ=3\tau = 3) and anchor force falls 2.77 to 0.64 to 0.28: hard and easy negatives become indistinguishable. Lowering τ\tau sends all weight to the closest candidate. If negative, τL→max⁡jsj−s+\tau\mathcal{L} \to \max_j s_j - s_+, a zero-margin hardest-negative triplet loss; if positive, loss and gradient vanish. Temperature therefore acts as a dial between treating all negatives equally and focusing only on the worst one. Wang and Liu (2021) study this hardness sensitivity and its tradeoff with tolerating genuinely similar negatives, revisited next lesson.

The optimal critic is a density ratio

What function does an unrestricted critic learn? The answer provides the bridge between InfoNCE and everything we developed in the preceding sections.

Proof

Fix xx and write D=(x,y1,…,yN)D = (x, y_1, \dots, y_N). The joint density of all the candidates when the positive appears at position ii is

p(yi∣x)∏j≠ip(yj)=r(x,yi)∏j=1Np(yj),p(y_i \given x)\prod_{j \neq i} p(y_j) = r(x, y_i)\prod_{j=1}^N p(y_j),

and the final product does not depend on ii. Because the position is uniformly distributed, Bayes’ rule gives the following posterior probability

p(c=i∣D)=r(x,yi)∑j=1Nr(x,yj).p(c = i \given D) = \frac{r(x, y_i)}{\sum_{j=1}^N r(x, y_j)}.

Softmax ratio qf(c=i∣D)=ef(x,yi)/∑jef(x,yj)q_f(c = i \given D) = e^{f(x, y_i)}/\sum_j e^{f(x, y_j)} is a position distribution and LN(f)=ED[−∑ip(c=i∣D)log⁡qf(c=i∣D)]\mathcal{L}_N(f) = \E_D\big[-\sum_i p(c = i \given D)\log q_f(c = i \given D)\big] expected cross-entropy. By Gibbs’ inequality, for each DD cross-entropy is at least entropy of p(c∣D)p(c \given D), with equality exactly when qf(⋅∣D)=p(⋅∣D)q_f(\cdot \given D) = p(\cdot \given D). Minimum ED[H(c∣D)]\E_D[H(c \given D)] is attained exactly when qf=p(c∣D)q_f = p(c \given D) for almost every DD.

Characterize those ff. If f=log⁡r+b(x)f = \log r + b(x), factor eb(x)e^{b(x)} cancels in numerator and denominator, making qfq_f the posterior. Conversely if qf=p(c∣D)q_f = p(c \given D), ratio between positions 1 and 2 gives ef(x,y1)−f(x,y2)=r(x,y1)/r(x,y2)e^{f(x, y_1) - f(x, y_2)} = r(x, y_1)/r(x, y_2) for almost every (y1,y2)(y_1, y_2), so f(x,y)−log⁡r(x,y)f(x, y) - \log r(x, y) does not depend on yy: it is function b(x)b(x).

∎

The optimal critic as density ratio explains everything at once. NCE’s optimal logit log⁡(pd/νpn)\log(p_d/\nu p_n) was data/noise ratio. InfoNCE “noise” is marginal product p(x)p(y)p(x)p(y) and “data” the joint, so the critic learns pointwise mutual information log⁡p(x,y)p(x)p(y)\log\frac{p(x, y)}{p(x)p(y)} up to an xx function. This is word2vec PMI without shift. It explains van den Oord et al.’s log-bilinear critic: efe^{f} need not be a density, only proportional to a ratio.

There are two practical consequences. First, what does not depend on yy cannot be learned: critic term b(x)b(x) is invisible, so InfoNCE does not provide normalized p(y∣x)p(y \given x). Second, the critic family limits what the model can represent: cosine critic has ∣f∣≤1/τ\abs{f} \le 1/\tau, so learned ratio lies in [e−2/τ,e2/τ][e^{-2/\tau}, e^{2/\tau}] up to a common factor; with τ=1\tau = 1 a positive can never be over e2≈7.4e^2 \approx 7.4 times as “likely” as a negative. Exercises calculate certifiable information.

InfoNCE bounds mutual information

The bound

The optimal critic yields the property naming the loss.

This InfoNCE mutual-information bound is INCEI_{\mathrm{NCE}} seen as InfoNCE bound in information theory, proved there by decomposing information between positive index and batch. Here Poole et al.’s (2019) alternate proof places InfoNCE in the variational bound family: NWJ with a multisample critic.

Proof

Recall Nguyen–Wainwright–Jordan: for any variables (U,V)(U, V) and critic gg, I(U;V)≥Ep(u,v)[g(U,V)]−e−1Ep(u)p(v)[eg(U,V)]I(U; V) \ge \E_{p(u, v)}[g(U, V)] - e^{-1}\E_{p(u)p(v)}\big[e^{g(U, V)}\big].

Take y1∼p(y∣x)y_1 \sim p(y \given x) and y2,…,yN∼p(y)y_2, \dots, y_N \sim p(y) independent of everything else; write U=xU = x, V=(y1,…,yN)V = (y_1, \dots, y_N). Since y2:Ny_{2:N} is independent of (x,y1)(x, y_1), chain rule gives I(X;Y1,…,YN)=I(X;Y1)+I(X;Y2:N∣Y1)=I(X;Y)I(X; Y_1, \dots, Y_N) = I(X; Y_1) + I(X; Y_{2:N} \given Y_1) = I(X; Y). Apply NWJ to (U,V)(U, V) with critic

g(x,y1:N)=1+log⁡ef(x,y1)m(x),m(x)=1N∑j=1Nef(x,yj).g(x, y_{1:N}) = 1 + \log\frac{e^{f(x, y_1)}}{m(x)}, \qquad m(x) = \frac1N\sum_{j=1}^N e^{f(x, y_j)}.

The first NWJ term is 1+E[log⁡(ef(x,y1)/m(x))]=1+log⁡N−LN(f)1 + \E\big[\log\big(e^{f(x, y_1)}/m(x)\big)\big] = 1 + \log N - \mathcal{L}_N(f). Under product p(x) p(y1:N)p(x)\,p(y_{1:N}) the NN candidates in the second term are exchangeable (all from p(y)p(y) independent of xx), so

e−1E[eg]=E[ef(x,y1)m(x)]=1N∑i=1NE[ef(x,yi)m(x)]=E[1N∑ief(x,yi)m(x)]=1.e^{-1}\E\big[e^{g}\big] = \E\left[\frac{e^{f(x, y_1)}}{m(x)}\right] = \frac1N\sum_{i=1}^N \E\left[\frac{e^{f(x, y_i)}}{m(x)}\right] = \E\left[\frac{\frac1N\sum_i e^{f(x, y_i)}}{m(x)}\right] = 1.

Subtracting gives I(X;Y)≥1+log⁡N−LN(f)−1=log⁡N−LN(f)I(X; Y) \ge 1 + \log N - \mathcal{L}_N(f) - 1 = \log N - \mathcal{L}_N(f). The second inequality is immediate: the positive is one denominator summand, so each softmax ratio is at most 1 and LN(f)≥0\mathcal{L}_N(f) \ge 0.

∎

Historically, van den Oord et al.’s original derivation used an approximation (replace negative sum by N−1N - 1 times its expectation, improving as NN grows). Poole et al. note this is unnecessary and present the preceding argument as the first proof that contrastive loss is a lower bound.

The bound saturates at log⁡N\log N

The second inequality bites: however good the critic, log⁡N−LN≤log⁡N\log N - \mathcal{L}_N \le \log N: InfoNCE cannot certify more than log⁡N\log N nats. When true information is much greater, the positive is obvious, loss nearly zero and nothing remains to estimate. The interactive uses exact optimal critic f=log⁡rf = \log r, making any shortfall from II the bound’s fault, not training’s.

InteractiveThe bound that saturates at log N
Estimate versus true information, with N=128N = 128
  • True I
  • log N
InfoNCE versus NN, with I=4.0I = 4.0
  • True I
  • log N
0.99983
128
I(X;Y)=−12log⁡(1−ρ2)I(X;Y) = -\tfrac12\log(1-\rho^2)4.00 nats
log⁡N\log N4.852
InfoNCE (mean ± SD)…
NWJ (mean ± SD)…
Smallest NN with InfoNCE ≥0.9 I\ge 0.9\,I…
X∼N(0,1)X \sim \mathcal{N}(0, 1) and Y=ρX+1−ρ2 εY = \rho X + \sqrt{1 - \rho^2}\,\varepsilon with I(X;Y)=−12log⁡(1−ρ2)I(X; Y) = -\tfrac12\log(1 - \rho^2), evaluated with optimal critic. Left, InfoNCE estimate (blue) and NWJ with optimal critic 1+log⁡r1 + \log r (orange) versus true information, with one-standard-deviation batch bands; dashed violet is log⁡N\log N, gray truth. Right, InfoNCE versus NN for current ρ\rho. Raise ρ\rho with N=128N = 128 until II exceeds log⁡128=4.85\log 128 = 4.85; then find NN needed to recover 90% of 8 nats.

At N=128N = 128 (log⁡N=4.852\log N = 4.852) the readings tell the story. InfoNCE tracks the diagonal to I≈2I \approx 2 (1.960 at I=2I = 2), then 3.681 at I=4I = 4 and 4.605 at I=6I = 6. It hugs its ceiling: 4.814 at I=8I = 8 and 4.847 at I=10I = 10, with standard deviations falling (0.10 to 0.007) because the positive wins overwhelmingly. Stable but highly biased: poor as a measure. NWJ with the same perfect critic is unbiased (8.03 at I=8I = 8, 10.17 at I=10I = 10), but batch deviation grows 0.07 at I=1I = 1 to 1.32 at I=10I = 10. To recover 90% of 4 nats needs N=128N = 128 candidates (3.68 nats), 6 needs 512 (5.47), and 8 exceeds 1024 (6.67): required NN grows exponentially in II, score matrix cost as N2N^2.

Lab: InfoNCE as a mutual-information estimator

Now train the critic. Gaussians in R5\R^5 with d=5d = 5 independent coordinates, each correlated ρ\rho, so I=−d2log⁡(1−ρ2)I = -\frac{d}{2}\log(1 - \rho^2), and CPC bilinear critic f(x,y)=x⊤Wyf(x, y) = \vb{x}\T\mat{W}\vb{y}. Handwrite its gradient: with S=XWY⊤\mat{S} = \mat{X}\mat{W}\mat{Y}\T and row softmax P\mat{P}, ∂L/∂S=(P−I)/N\partial\mathcal{L}/\partial\mat{S} = (\mat{P} - \mat{I})/N and by chain rule ∂L/∂W=X⊤(∂L/∂S)Y\partial\mathcal{L}/\partial\mat{W} = \mat{X}\T(\partial\mathcal{L}/\partial\mat{S})\mat{Y}.

[ ]InfoNCE with a bilinear critic, gradients by handBrowser
def lote(rng, N, d, rho):
    """N pares (x_i, y_i): d coordenadas independientes con correlación rho."""
    X = rng.normal(size=(N, d))
    Y = rho * X + np.sqrt(1 - rho ** 2) * rng.normal(size=(N, d))
    return X, Y

def lse(S):
    """log-sum-exp por filas, estable."""
    m = S.max(1, keepdims=True)
    return (m + np.log(np.exp(S - m).sum(1, keepdims=True))).ravel()

def infonce(W, v, X, Y):
    """Valor log N - L y gradientes del crítico f(x, y) = x^T W y + v |y|^2 (v = 0: bilineal puro)."""
    N = len(X)
    q = (Y ** 2).sum(1)
    S = X @ W @ Y.T + v * q[None, :]                       # S_ij = f(x_i, y_j)
    L = np.mean(lse(S) - np.diag(S))
    G = (np.exp(S - lse(S)[:, None]) - np.eye(N)) / N      # dL/dS = (softmax - I)/N
    return np.log(N) - L, X.T @ G @ Y, G.sum(0) @ q        # valor, dL/dW, dL/dv

class Adam:
    def __init__(self, lr=0.1):
        self.lr, self.t, self.m, self.v = lr, 0, {}, {}
    def paso(self, params, grads):                         # descenso sobre la pérdida
        self.t += 1
        for k_, g in grads.items():
            self.m[k_] = 0.9 * self.m.get(k_, 0) + 0.1 * g
            self.v[k_] = 0.999 * self.v.get(k_, 0) + 0.001 * g * g
            mh = self.m[k_] / (1 - 0.9 ** self.t)
            vh = self.v[k_] / (1 - 0.999 ** self.t)
            params[k_] = params[k_] - self.lr * mh / (np.sqrt(vh) + 1e-8)

def entrenar(I, d=5, N=128, pasos=300, con_norma=False, seed=0):
    rng = np.random.default_rng(seed)
    rho = np.sqrt(1 - np.exp(-2 * I / d))                  # I = -(d/2) log(1 - rho^2)
    p = {"W": np.zeros((d, d)), "v": 0.0}
    opt = Adam()
    for _ in range(pasos):
        _, gW, gv = infonce(p["W"], p["v"], *lote(rng, N, d, rho))
        opt.paso(p, {"W": gW, "v": gv if con_norma else 0.0})
    vals = [infonce(p["W"], p["v"], *lote(rng, N, d, rho))[0] for _ in range(30)]
    return np.mean(vals), np.std(vals), p

m, sd, p = entrenar(4.0)
print(f"I verdadera = 4.00 nats, log N = {np.log(128):.2f}")
print(f"InfoNCE con crítico bilineal entrenado: {m:.3f} ± {sd:.3f}")
print("diagonal de W:", np.round(np.diag(p['W']), 2), " fuera de la diagonal, max |W_ij| =", np.abs(p['W'] - np.diag(np.diag(p['W']))).max().round(3))

Trained critic stops at 1.915±0.0951.915 \pm 0.095 nats while truth is 4 and ceiling log⁡128=4.85\log 128 = 4.85. The critic, not bound, is responsible. Optimal-critic theorem reveals what is missing. For these Gaussians,

log⁡r(x,y)=A x⊤y−B∥y∥2+g(x),A=ρ1−ρ2,B=ρ22(1−ρ2),\log r(\vb{x}, \vb{y}) = A\,\vb{x}\T\vb{y} - B\norm{\vb{y}}^2 + g(\vb{x}), \qquad A = \frac{\rho}{1 - \rho^2}, \quad B = \frac{\rho^2}{2(1 - \rho^2)},

and at I=4I = 4 and d=5d = 5, ρ=0.893\rho = 0.893, A=4.42A = 4.42 and B=1.98B = 1.98. Term g(x)g(\vb{x}) is invisible to InfoNCE, but −B∥y∥2-B\norm{\vb{y}}^2 is not: it depends on candidate and does not cancel in softmax. A bilinear critic cannot penalize long candidates; increasing W\mat{W} favors both positive and long negatives pointing along x\vb{x}, and training stops at W≈I\mat{W} \approx \mat{I} (diagonal 0.95–1.08), far from A IA\,\mat{I}. Add one parameter v∥y∥2v\norm{\vb{y}}^2 to include the optimal critic.

[ ]Saturation: five information levelsBrowser
def optimo(I, d=5, N=128, lotes=30, seed=1):
    """InfoNCE con el crítico óptimo log r = a x^T y - b |y|^2 + (términos de x)."""
    rng = np.random.default_rng(seed)
    rho = np.sqrt(1 - np.exp(-2 * I / d))
    A, B = rho / (1 - rho ** 2), rho ** 2 / (2 * (1 - rho ** 2))
    v = [infonce(A * np.eye(d), -B, *lote(rng, N, d, rho))[0] for _ in range(lotes)]
    return np.mean(v)

print(f"log N = {np.log(128):.2f}")
print("I real   bilineal   bilineal + |y|^2   crítico óptimo")
for I in (1, 2, 4, 6, 8):
    b = entrenar(I)[0]
    bq = entrenar(I, con_norma=True)[0]
    print(f"{I:5.1f}   {b:8.3f}   {bq:12.3f}       {optimo(I):10.3f}")

The table separates two error sources. With v∥y∥2v\norm{\vb{y}}^2 the trained critic is within 0.02 nats of optimum up to I=4I = 4 (3.446 versus 3.454), and 0.17 away at I=8I = 8 (4.586 versus 4.755): training loss. The optimal critic itself falls below II as information nears log⁡N\log N: 3.454 at I=4I = 4, 4.398 at I=6I = 6, 4.755 at I=8I = 8, always below 4.85. Bound loss cannot be fixed by training. Pure bilinear suffers both and does not exceed 2.297.

[ ]NWJ: the same family, another boundBrowser
def nwj(W, u, v, b, X, Y):
    """Valor de NWJ en el lote y su gradiente; f = x^T W y + u|x|^2 + v|y|^2 + b.
    Los pares cruzados (i != j) hacen de muestras del producto de marginales."""
    N = len(X)
    qx, qy = (X ** 2).sum(1), (Y ** 2).sum(1)
    F = X @ W @ Y.T + u * qx[:, None] + v * qy[None, :] + b
    fuera = ~np.eye(N, dtype=bool)
    E = np.where(fuera, np.exp(np.minimum(F - 1, 50)), 0.0) / (N * (N - 1))
    val = np.mean(np.diag(F)) - E.sum()
    G = np.eye(N) / N - E                                   # d(valor)/dF
    return val, {"W": -(X.T @ G @ Y), "u": -(G.sum(1) @ qx), "v": -(G.sum(0) @ qy), "b": -G.sum()}

def entrenar_nwj(I, d=5, N=128, pasos=300, seed=0):
    rng = np.random.default_rng(seed)
    rho = np.sqrt(1 - np.exp(-2 * I / d))
    p = {"W": np.zeros((d, d)), "u": 0.0, "v": 0.0, "b": 0.0}
    opt = Adam()
    for _ in range(pasos):
        _, g = nwj(p["W"], p["u"], p["v"], p["b"], *lote(rng, N, d, rho))
        opt.paso(p, g)                                      # descenso sobre -NWJ
    vals = [nwj(p["W"], p["u"], p["v"], p["b"], *lote(rng, N, d, rho))[0] for _ in range(30)]
    return np.mean(vals), np.std(vals)

def nwj_optimo(I, d=5, N=128, lotes=100, seed=2):
    """NWJ con su crítico óptimo 1 + log r, que está en la familia."""
    rng = np.random.default_rng(seed)
    rho = np.sqrt(1 - np.exp(-2 * I / d))
    A, B = rho / (1 - rho ** 2), rho ** 2 / (2 * (1 - rho ** 2))
    c0 = 1 - 0.5 * d * np.log(1 - rho ** 2)
    v = [nwj(A * np.eye(d), -B, -B, c0, *lote(rng, N, d, rho))[0] for _ in range(lotes)]
    return np.mean(v), np.std(v)

print("I real   NWJ entrenada       NWJ con el crítico óptimo   (media ± desv. entre lotes)")
for I in (1, 2, 4, 6, 8):
    m, sd = entrenar_nwj(I)
    mo, so = nwj_optimo(I)
    print(f"{I:5.1f}   {m:6.2f} ± {sd:.2f}       {mo:6.2f} ± {so:.2f}")

NWJ has no log⁡N\log N ceiling, demonstrated by its optimal critic (within this quadratic family): 4.01, 6.04, 8.01 at I=4I = 4, 6, 8. Batch spread costs: 0.10 at I=1I = 1 to 0.91 at I=8I = 8, variance growing with II as studied in information theory. But a critic trained 300 steps falls short: 3.37, 4.41, 4.57, even below log⁡N\log N. Would more training help?

[ ]More training does not fix NWJBrowser
rng = np.random.default_rng(0)
I, d, N = 8.0, 5, 128
rho = np.sqrt(1 - np.exp(-2 * I / d))
p = {"W": np.zeros((d, d)), "u": 0.0, "v": 0.0, "b": 0.0}
opt = Adam()
for t in range(1, 1501):
    _, g = nwj(p["W"], p["u"], p["v"], p["b"], *lote(rng, N, d, rho))
    opt.paso(p, g)
    if t % 250 == 0:
        ev = [nwj(p["W"], p["u"], p["v"], p["b"], *lote(rng, N, d, rho))[0] for _ in range(10)]
        print(f"paso {t:4d}: NWJ = {np.mean(ev):7.2f} ± {np.std(ev):.2f}   (I real = 8, diag(W) media = {np.diag(p['W']).mean():.2f})")

Only partly. At 1000 steps NWJ reaches 6.35, at 1500 6.54, crossing InfoNCE’s ceiling as expected. Slowly (diagonal W\mat{W} is 6.62 versus optimum A=24.0A = 24.0) and with setbacks: at step 1250 it fell to 2.65. NWJ gradient contains efe^{f} evaluated on marginal-product pairs, the terms whose variance explodes with II; the optimizer feels it. Poole et al.’s diagnosis: existing bounds degrade at high information, via high bias (InfoNCE) or high variance (NWJ).

InfoNCE among variational bounds

With both bounds, the map fits in a table. All use critic ff and joint and marginal-product samples; their treatment of normalization Ep(x)p(y)[ef]\E_{p(x)p(y)}[e^{f}] differs.

BoundExpressionPractical bias and variance
DV (Donsker–Varadhan; MINE)Ep[f]−log⁡Ep(x)p(y)[ef]\E_p[f] - \log\E_{p(x)p(y)}[e^f]Tightest for given ff, but log of a batch mean is biased: estimated thus it is neither lower nor upper bound
NWJEp[f]−e−1Ep(x)p(y)[ef]\E_p[f] - e^{-1}\E_{p(x)p(y)}[e^f]Unbiased on batch; high variance when II is large and batch small
InfoNCEE[log⁡ef(x,y1)1N∑jef(x,yj)]\E\big[\log\frac{e^{f(x, y_1)}}{\frac1N\sum_j e^{f(x, y_j)}}\big]Low variance; bias ≥I−log⁡N\ge I - \log N from ceiling
IαI_\alpha (Poole et al.)interpolates between previous twoα=0\alpha = 0 is NWJ, α=1\alpha = 1 InfoNCE; ceiling becomes log⁡(N/α)\log(N/\alpha)

Poole et al. (2019) introduce the last continuous bias–variance family; in their experiments best α\alpha is near 1 for small batches/information and approaches 0 as both grow. Song and Ermon (2020) prove MINE-type estimator variance can grow exponentially with true information. Is any bound immune? No. McAllester and Stratos (2020) prove any distribution-free, high-confidence mutual-information lower bound estimated with NN samples cannot exceed O(log⁡N)\bigO(\log N): InfoNCE’s ceiling reflects a general limit, not merely a design flaw. Information theory discusses the statement and intuition; practical reading rule:

Does mutual information explain empirical success?

If InfoNCE bounds mutual information and produces good representations, attributing success to maximizing information is tempting. Tschannen, Djolonga, Rubenstein, Gelly and Lucic (2020) tested this with two views of each MNIST digit (upper and lower halves), two encoders and a critic; upper-view representation quality is linear-classifier accuracy (around 85% on raw pixels). Three observations:

  1. Information can be maximal and constant as representation improves. With bijective encoders (invertible normalizing flows), I(g1(X);g2(Y))=I(X;Y)I(g_1(X); g_2(Y)) = I(X; Y) for any parameters because mutual information is invariant to invertible transformations. Yet InfoNCE or NWJ training raises estimated value and linear accuracy: estimator gradients favor linearly useful representations, unexplained by information alone. Adversarial training also found invertible equally informative encoders with worse classification.
  2. A tighter critic can yield worse representations. An MLP critic gives a higher (tighter) test NWJ bound than separable or bilinear critics, but representations barely beat pixels; the bilinear critic with lowest NWJ gives best accuracy. (InfoNCE was near theoretical maximum with all critics.)
  3. InfoNCE is metric learning. With a symmetric separable critic its loss matches Sohn’s (2016) KK-pair loss up to constants and sign, a generalized triplet loss. They also note dependent negative sampling invalidates the bound.

The authors conclude success cannot be attributed solely to mutual-information properties: encoder architecture inductive bias and estimator parametrization matter. Healthy reading: InfoNCE is a useful contrastive classification loss whose optimum is a density ratio, and its MI relationship is a capped bound, not an explanation of success. More predictive explanations (alignment and uniformity, spectral augmentation-graph view) follow.

Neighbor embeddings as contrastive estimation

t-SNE is NCE; UMAP is negative sampling

Revisit UMAP’s objective and t-SNE through this lesson. Damrich, Böhm, Hamprecht and Kobak (2023) write both as contrastive estimation on neighbor-graph edges:

  • Data. Distribution pp over pairs ijij is uniform on symmetric kk-neighbor graph edges (always k=15k = 15): p(ij)=1[ij∈kNN]/∣kNN∣p(ij) = \ind[ij \in \text{kNN}]/\abs{\text{kNN}}.
  • Noise. ξ\xi is approximately uniform over ∣X∣=(n2)\abs{X} = \binom{n}{2} pairs, with mm noise samples per edge (default m=5m = 5).
  • Model. qθ,Z(ij)=φ(ij)/Zq_{\theta, Z}(ij) = \varphi(ij)/Z with t-SNE’s Cauchy kernel φ(ij)=1/(1+∥yi−yj∥2)\varphi(ij) = 1/(1 + \norm{\vb{y}_i - \vb{y}_j}^2) and parameter ZZ.

With learned ZZ, NCE loss is

L(Y,Z)=−Eij∼p[log⁡q(ij)q(ij)+m ξ(ij)]−m Eij∼ξ[log⁡m ξ(ij)q(ij)+m ξ(ij)],\mathcal{L}(\mat{Y}, Z) = -\E_{ij \sim p}\left[\log\frac{q(ij)}{q(ij) + m\,\xi(ij)}\right] - m\,\E_{ij \sim \xi}\left[\log\frac{m\,\xi(ij)}{q(ij) + m\,\xi(ij)}\right],

They call this NC-t-SNE: learned ZZ approximately converges to t-SNE’s partition function and the embedding resembles t-SNE. Fixing ZZ to Zˉ\bar Z instead gives fixed-normalization negative sampling (Neg-t-SNE). Original word2vec negative sampling with classifier q/(q+1)q/(q + 1) and no constant corresponds to Zˉ=∣X∣/m\bar Z = \abs{X}/m: then mξZˉ=1m\xi\bar Z = 1. UMAP appears here: their lemma 3 proves UMAP loss (with a=b=1a = b = 1) equals that negative sampling with model q(ij)=1/dij2q(ij) = 1/d_{ij}^2, since classifier q/(q+1)q/(q + 1) then equals UMAP similarity 1/(1+dij2)1/(1 + d_{ij}^2). The kernel is not Cauchy, but UMAP embeddings empirically resemble Neg-t-SNE with ZˉUMAP=∣X∣/m=(n2)/m\bar Z_{\mathrm{UMAP}} = \abs{X}/m = \binom{n}{2}/m. This contrastive reading of neighbor embeddings reduces the t-SNE–UMAP difference to one number: normalization.

What a fixed Zˉ\bar Z does

The calculation is one line. With c=Zˉmξ=Zˉm/∣X∣c = \bar Z m\xi = \bar Z m/\abs{X} the classifier is hij=φij/(φij+c)h_{ij} = \varphi_{ij}/(\varphi_{ij} + c) and expected loss L=−∑ijpijlog⁡hij−m∑ijξijlog⁡(1−hij)\mathcal{L} = -\sum_{ij} p_{ij}\log h_{ij} - m\sum_{ij}\xi_{ij}\log(1 - h_{ij}). Differentiating with respect to φij\varphi_{ij},

∂L∂φij=−pijcφij(φij+c)+mξijφij+c=cφij+c(−pijφij+1Zˉ).\pd{\mathcal{L}}{\varphi_{ij}} = -p_{ij}\frac{c}{\varphi_{ij}(\varphi_{ij} + c)} + \frac{m\xi_{ij}}{\varphi_{ij} + c} = \frac{c}{\varphi_{ij} + c}\left(-\frac{p_{ij}}{\varphi_{ij}} + \frac{1}{\bar Z}\right).

Compare t-SNE KL ∑ijpijlog⁡(pijZ/φij)\sum_{ij} p_{ij}\log(p_{ij}Z/\varphi_{ij}) with Z=∑ijφijZ = \sum_{ij}\varphi_{ij}, derivative −pij/φij+1/Z-p_{ij}/\varphi_{ij} + 1/Z, and t-SNE with exaggeration ρ\rho, proportional to −pij/φij+1/(ρZ)-p_{ij}/\varphi_{ij} + 1/(\rho Z). Except factor c/(φij+c)∈(0,1)c/(\varphi_{ij} + c) \in (0, 1) damping nearby pairs, negative sampling with fixed Zˉ\bar Z is t-SNE with normalization replaced by a constant, and at stationary embedding behaves like exaggeration

ρeq=ZˉZ(Y),Z(Y)=∑ijφij.\rho_{\mathrm{eq}} = \frac{\bar Z}{Z(\mat{Y})}, \qquad Z(\mat{Y}) = \sum_{ij}\varphi_{ij}.

Large Zˉ\bar Z means weak repulsion: compact groups eventually merge; small Zˉ\bar Z means strong repulsion: larger scale and separated groups that at the extreme lose separation and overlap. These are the directions Damrich et al. describe varying Zˉ\bar Z, closely related to Böhm et al.’s exaggeration spectrum from UMAP. Why is UMAP attraction-heavy? Its constant dwarfs t-SNE’s: Böhm et al., cited by Damrich et al., give t-SNE partition typically 50n50n to 100n100n while ZˉUMAP=(n2)/m\bar Z_{\mathrm{UMAP}} = \binom{n}{2}/m grows as n2n^2. With n=70 000n = 70\,000 and m=5m = 5 ratio (n−1)/(2m⋅[50,100])(n - 1)/(2m \cdot [50, 100]) is 70–140.

InteractiveFrom UMAP to t-SNE with a dial
NCE with learned ZZ (computing the s=0s = 0 endpoint…)
Exact t-SNE
UMAP: negative sampling with q=1/d2q = 1/d^2
  • supergroup A
  • supergroup B
  • supergroup C
  • bridge from A to B
Within each supergroup, shape (circle, square, triangle) distinguishes the three subgroups.
Readouts versus ss, one mark per completed optimization (diamonds: t-SNE at s=0s = 0 and UMAP at s=1s = 1)
0.000.250.500.751.00−1.0−0.50.00.51.01.52.0t-SNEUMAP
  • neighbors preserved (15)
  • distance correlation (global)
0.00
NCE learning ZZ, iteration0 / 600
ZNCEZ_{\mathrm{NCE}} learned…
Zˉ\bar Z fixed…
Z(Y)=∑i<jφijZ(\mat{Y}) = \sum_{i<j}\varphi_{ij} at the end…
Equivalent exaggeration Zˉ/Z(Y)\bar Z / Z(\mat{Y})…
Neighbors preserved (15)…
Correlation de distancias…
410 points in R20\R^{20}: three supergroups (colors), each with three subgroups (shapes), plus 50-point bridge between two. 15-neighbor graph, m=5m = 5, Cauchy kernel, exact expected loss (no sampling), optimized for 600 iterations from identical PCA initialization. NCE first learns ZZ, setting endpoint s=0s = 0; endpoint s=1s = 1 is UMAP constant ∣X∣/m\abs{X}/m. Dial interpolates logarithmically Zˉ=ZNCE1−s ZUMAPs\bar Z = Z_{\mathrm{NCE}}^{1-s}\,Z_{\mathrm{UMAP}}^{s} and extrapolates both ways. Right references: exact t-SNE and UMAP as negative sampling with q=1/d2q = 1/d^2. Move dial (or press 'Recorrer el dial') and observe where neighbors are lost and subgroups merge.

Reference-run figures (optimization amplifies JavaScript-engine rounding, so your browser may differ in second or third digit):

  • NCE learns t-SNE partition. Learned ZZ is about 3350, exact t-SNE on the same data 3241 (unordered pairs; double for ordered). Around 8n8n, outside 50n50n–100n100n above: ratio Z/nZ/n depends on dataset size and structure, here only 410 points. Both preserve similar fractions of 15 neighbors (0.657, 0.667). Negative sampling with s=0s = 0 is slightly more compact than t-SNE (maximum coordinate 29.5 versus 35.7): at m=5m = 5 factor c/(φ+c)c/(\varphi + c) matters; Damrich et al. observe contrastive versions approach t-SNE much more at m=500m = 500.
  • Toward UMAP repulsion fades. At s=1s = 1, Zˉ\bar Z is five times ZNCEZ_{\mathrm{NCE}} but equivalent exaggeration only 2.05: contraction raises Z(Y)Z(\mat{Y}) from 3198 to 8164, geometry absorbing some Zˉ\bar Z increase. Neighbor preservation falls 0.656 to 0.541, scale 29.5 to 16.7. UMAP reference with q=1/d2q = 1/d^2 preserves 0.435, between dial s=1.25s = 1.25 (0.475) and s=1.5s = 1.5 (0.416): kernel 1/d21/d^2 differs from φ/Zˉ\varphi/\bar Z and optimization clips steps as umap-learn does, but compact attached subgroups match the paper qualitatively.
  • Beyond UMAP subgroups merge. At s=2s = 2 equivalent exaggeration is 7.6 and neighbor preservation 0.327. Subgroups in the bridged supergroup become one elongated blob continuing the bridge; other supergroups’ subgroups stick together with scattered points: fine structure yields to continuity.
  • Beyond t-SNE locality does not improve. At s=−1s = -1 embedding grows (scale 48.4) and groups separate, but neighbor preservation does not rise (0.652): t-SNE already maximized this metric. Global distance correlation varies little across dial (0.68–0.77): as in UMAP, global placement mainly depends on initialization, here the same PCA throughout.

Damrich et al.’s conclusion matches this experiment: t-SNE and UMAP are the same contrastive estimation with different normalization constants, tracing a local-discrete versus continuous-structure tradeoff. Much of the difference attributed to UMAP topology (UMAP lesson) is negative-sampling bias.

Library version

In practice InfoNCE is cross-entropy on the batch similarity matrix, with library-provided stable log-sum-exp and gradients. In PyTorch:

import torch
import torch.nn.functional as F

def info_nce(z1, z2, tau=0.1):
    """z1[i] y z2[i] son las dos vistas del ejemplo i; los demás z2[j] del lote hacen de negativos."""
    z1 = F.normalize(z1, dim=1)                  # primero normalizar, después la temperatura
    z2 = F.normalize(z2, dim=1)
    logits = z1 @ z2.T / tau                     # (B, B): fila i = ancla i, columnas = candidatos
    etiquetas = torch.arange(len(z1), device=z1.device)
    return F.cross_entropy(logits, etiquetas)    # media de -log softmax en la diagonal

def info_nce_simetrica(z1, z2, tau=0.1):
    """La versión de CLIP: identificar el texto de cada imagen y la imagen de cada texto."""
    return 0.5 * (info_nce(z1, z2, tau) + info_nce(z2, z1, tau))

With normalized vectors, info_nce exactly computes the final coding exercise’s loss and loss.backward() gives its hand-derived gradient: a solution check. NCE needs no special library: logistic regression with fixed logit offset suffices, using any offset-capable implementation (e.g., statsmodels generalized linear models). For neighbor embeddings, Damrich et al. publish a PyTorch implementation with NCE, InfoNCE and configurable-Zˉ\bar Z negative sampling.

Common mistakes

Exercises

NumericThe ceiling with 256 candidates
You train with InfoNCE using batches of N=256N = 256 candidates (one positive and 255 negatives per anchor). What is the largest mutual information, in nats, that the bound log⁡N−LN\log N - \mathcal{L}_N can certify, regardless of the critic?
NumericThe cosine critic's ceiling
With critic f=⟨zx,zy⟩/τf = \inner{\vb{z}_x}{\vb{z}_y}/\tau and unit vectors, what is the maximum value of log⁡N−LN\log N - \mathcal{L}_N with N=256N = 256 and τ=1\tau = 1, even if the true information is infinite?
NumericWhat word2vec learns
In a corpus, word ww and context cc occur together with probability p(w,c)=0.01p(w, c) = 0.01, and their marginals are p(w)=0.05p(w) = 0.05 and p(c)=0.02p(c) = 0.02. You train skip-gram with negative sampling, k=5k = 5 negatives per positive drawn from p(c)p(c). Given more than enough model capacity, what value does the score swc=vc′⊤vws_{wc} = \vb{v}'^{\T}_c\vb{v}_w converge to?
QuizTemperature and negative weights
In InfoNCE with critic ⟨za,zj⟩/τ\inner{\vb{z}_a}{\vb{z}_j}/\tau, the gradient pushes each negative jj with force wj/τw_j/\tau, where wjw_j is its softmax weight. What happens to these weights when τ→0\tau \to 0 and when τ\tau is large?
QuizNegative sampling versus NCE
In word2vec with negative sampling, score swcs_{wc} enters σ(swc)\sigma(s_{wc}) directly, whereas in NCE the logit is swc−log⁡(kPn(c))s_{wc} - \log(k P_n(c)). With enough capacity and infinite data, which statement is correct?
QuizA loss that stops decreasing
A paper trains with batches of N=1024N = 1024 and reports that log⁡N−LN\log N - \mathcal{L}_N reaches 6.90 nats on validation. What can you conclude about mutual information between the two views?
QuizNegatives from the same dataset
You train with InfoNCE on a dataset of 10 balanced classes, using the other examples in each batch as negatives for each anchor (N=4096N = 4096). Which statement is correct?
QuizWhat mutual information does not explain
Which statements follow from the experiments of Tschannen et al. (2020) and this lesson's analysis? (There may be several.)

More than one answer may be correct.

QuizFixing the normalization
You fit a neighbor embedding by negative sampling with fixed Zˉ\bar Z and obtain an embedding whose sum of similarities is Z(Y)=∑i<jφij=5000Z(\mat{Y}) = \sum_{i<j}\varphi_{ij} = 5000. If you fix Zˉ=50 000\bar Z = 50\,000, what is closest to what you obtain, according to the lesson's gradient analysis?
QuizWithout normalization
You implement InfoNCE with logits ⟨za,zj⟩/τ\inner{\vb{z}_a}{\vb{z}_j}/\tau but forget to normalize the embeddings. What can happen?
ProofThe optimal critic and the bound, via Bayes
Prove: For every critic ff, LN(f)≥ED[H(c∣D)]\mathcal{L}_N(f) \ge \E_D[H(c \given D)] with equality if and only if f=log⁡r+b(x)f = \log r + b(x), where r=p(y∣x)/p(y)r = p(y \given x)/p(y); and I(X;Y)≥log⁡N−LN(f)I(X; Y) \ge \log N - \mathcal{L}_N(f).
0
Fix an anchor xx, a uniform position cc in {1,…,N}\{1, \dots, N\} for the positive yc∼p(y∣x)y_c \sim p(y \given x) and independent negatives yj∼p(y)y_j \sim p(y). Write D=(x,y1,…,yN)D = (x, y_1, \dots, y_N) and qf(c=i∣D)=ef(x,yi)/∑jef(x,yj)q_f(c = i \given D) = e^{f(x, y_i)}/\sum_j e^{f(x, y_j)}.

Step 1 of 4. What is the posterior p(c=i∣D)p(c = i \given D)?

ProofNCE recovers the density
Prove: If pn>0p_n > 0 where pd>0p_d > 0 and there exists θ∗\theta^* with pm(⋅ ;θ∗)=pdp_m(\cdot\,; \theta^*) = p_d, then θ∗\theta^* maximizes the population NCE objective with free cc, and every maximizer θ′\theta' satisfies pm(⋅ ;θ′)=pdp_m(\cdot\,; \theta') = p_d almost everywhere. In particular, cc is at −log⁡Z-\log Z.
0
The population objective is J(θ)=Epd[log⁡h]+ν Epn[log⁡(1−h)]J(\theta) = \E_{p_d}[\log h] + \nu\,\E_{p_n}[\log(1 - h)] with h=σ(log⁡pm(⋅ ;θ)−log⁡νpn)h = \sigma(\log p_m(\cdot\,; \theta) - \log \nu p_n).

Step 1 of 4. How do you rewrite JJ so you can optimize it?

CodeStable InfoNCE and its gradient
Implement info_nce(z1, z2, tau), taking two matrices (B, d) (rows z1[i] and z2[i] are the positive pair; normally they will be normalized, but the function must not assume this) and returning (L, G): mean loss L=1B∑i[log⁡∑jeSij−Sii]\mathcal{L} = \frac1B\sum_i\big[\log\sum_j e^{S_{ij}} - S_{ii}\big] with S=z1z2T/τS = z_1 z_2^{\mathsf{T}}/\tau, and its gradient G with respect to z1, of shape (B, d). Use stable log-sum-exp (with unit vectors and τ=0.01\tau = 0.01 logits already reach 100, where np.exp overflows in float32; with vectors of norm 30 they reach 90,000 and overflow in float64 too) and do not call automatic differentiation libraries.
import numpy as np

def info_nce(z1, z2, tau):
  """Pérdida InfoNCE media y su gradiente respecto a z1."""
  S = z1 @ z2.T / tau
  L = np.mean(np.log(np.exp(S).sum(1)) - np.diag(S))
  G = np.zeros_like(z1)   # tu código: el gradiente
  return L, G
Shift+Enter to run

Summary

Key idea
Distinguishing data from noise estimates a density ratio. NCE uses it to learn unnormalized models, treating the constant as another parameter; InfoNCE turns it into identifying the positive among NN candidates, with optimal critic log⁡p(y∣x)p(y)\log\frac{p(y \given x)}{p(y)} and a mutual information bound that never exceeds log⁡N\log N.
  • NCE is logistic regression of data against noise with logit log⁡pm−log⁡(νpn)\log p_m - \log(\nu p_n). Its optimum is pm=pdp_m = p_d without imposing normalization, provided noise covers the support of the data. Noise similar to the data and large ν\nu make it efficient; distant noise makes it a trivial task that teaches nothing.
  • Negative sampling removes log⁡(kPn)\log(kP_n) from the logit: it no longer needs noise probabilities, but learns PMI⁡−log⁡k\operatorname{PMI} - \log k instead of a normalized probability.
  • InfoNCE is cross-entropy over NN candidates. Its gradient pushes each negative away in proportion to its softmax weight; temperature ranges from “everyone equally” to “only the hardest.” Normalize before dividing by τ\tau.
  • Optimal critic and bound. The minimum is attained with f=log⁡r+b(x)f = \log r + b(x), and I(X;Y)≥log⁡N−LNI(X; Y) \ge \log N - \mathcal{L}_N for every ff (an NWJ with a multi-sample critic). The bound saturates at log⁡N\log N; NWJ does not saturate but pays in variance, and McAllester and Stratos proved that no distribution-free lower bound exceeds O(log⁡N)\bigO(\log N).
  • Information does not explain everything. Tschannen et al. show improvements with constant information and tighter critics that give worse representations.
  • t-SNE and UMAP are contrastive estimation on the neighbor graph: NCE with learned ZZ resembles t-SNE, and UMAP is negative sampling with an enormous Zˉ=(n2)/m\bar Z = \binom{n}{2}/m, equivalent to t-SNE with exaggeration.