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 :
Evaluating requires one network pass; evaluating partition function requires an integral over the entire space. Maximum likelihood needs it: the gradient of is
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 words: with on the order of , every example pays 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 sums 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 samples from unknown density and generate samples from a chosen noise density that can be sampled and evaluated. Mix them, label data and noise . Priors are and , so Bayes’ rule gives the probability that point is data:
The Bayes classifier logit is . Since and are known, learning the classifier learns . 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: enters the logit without a learned coefficient. Parameter is not tied to : nothing in forces ; the next theorem says optimum achieves it automatically. No integral: each step evaluates at points.
Why it works
As with fixed , converges to its population version
First consider an unrestricted model: log density is any function .
Proof
Write both expectations as one integral. With ,
Maximize pointwise. For and , function on has derivative and second derivative : strictly concave with unique maximum . Since is bijective (), the maximum in is
where (where , decreases and its supremum occurs at limit , i.e., ). If vanished where , would grow without bound toward : would be undetermined, requiring the assumption.
∎Notice what was not imposed: normalization. The maximum integrates to 1 because it equals , not by constraint. For a parametric model, Gutmann and Hyvärinen (2012) assume the family contains truth and prove (theorem 2) in probability under three conditions: (a) positive wherever is; (b) converges uniformly to on in probability; (c) matrix , with and , has full rank. These are maximum-likelihood conditions plus support. In particular converges to : normalization is learned as another parameter. Exercises reconstruct the population proof.
Choosing noise
Consistency holds for almost any ; efficiency does not. Gutmann and Hyvärinen’s (2012) theorem 3 gives asymptotic covariance of , with three useful corollaries:
- More noise, less noise dependence. As , no longer depends on (corollary 5) and for normalized models equals inverse Fisher information: NCE is asymptotically as efficient as maximum likelihood (corollary 6).
- Noise equals data. If , is times limit covariance (corollary 7): for normalized models, gives twice inverse Fisher, only 1.1 times.
- Practical recipe: analytically evaluable , 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.
Readings for the selector’s four noise types and :
- Similar noise (). Orange overlaps truth, versus , 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 RMSE 0.080. With they fall to 0.0015 and 0.065; with rise to 0.0097 and 0.117.
- Too narrow (). Classifier accuracy 89.3% and 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 (). 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 , less than one-third, inform shape.
- Shifted (). Classifier accuracy 98.5% and fitting diverges: 14 of 20 runs give . Almost no noise appears at , so model can grow there without loss noticing. Theorem support condition (a) fails in practice, though not theory: 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 :
using polar coordinates and substitution (so ). Closed form checks the result; NCE does not use it. Exact sampling follows the same substitution: is normal with mean and deviation truncated to , with uniform angle. First the cleanest case: energy shape is known and only parameter is . NCE is logistic regression with one variable (constant) and offset.
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, versus : log error 0.041, 4% in . Now the full problem: family contains truth at and . In two dimensions grid quadrature can check normalization, impossible in high dimensions.
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 ( and versus and ) and model integral 1.027 without imposing 1. Narrow noise () barely reaches the ring and integral falls to 0.431: fit is good where noise exists and poor elsewhere. Very wide noise () gives 0.829: almost all noise is trivially classified. The final cell measures 25 repetitions comparing NCE against naive importance sampling on the same noise samples.
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 (), RMSE is 0.034 at and 0.018 at ; narrow 0.253 and 0.116; wide 0.137 and 0.045. Increasing always helps, more with worse noise, as corollary 5 predicts. Importance sampling teaches another lesson: with narrow noise, naive estimator bias underestimates 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 (): it also uses ring data. With good noise both are similar.
Negative sampling: NCE without normalization
word2vec skip-gram learns vector per word and per context, score . Softmax modeling of normalizes over the vocabulary. Mikolov et al. (2013) replace it with negative sampling (NEG): for each observed pair draw contexts from noise and maximize
The paper suggests from 5 to 20 for small datasets and from 2 to 5 for large; best noise was unigram to power , . 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 negatives per positive, NCE logit is ; NEG uses only . NEG is NCE with for every , an equality that does not hold. Apply the earlier pointwise argument to cell with and : optimum satisfies , i.e., . For NCE with this gives
the conditional log-probability, normalized without explicit normalization. For NEG, however,
pointwise mutual information shifted by . 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.
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 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 candidates
Instead of classifying points individually as data or noise, present one datum and noise samples and identify the datum. For representation learning the datum is a pair: anchor and positive (another image view, next word, caption); negatives are independent of . A critic scores combinations and softmax regression over candidates estimates the positive position.
This is contrastive predictive coding (CPC) loss. An encoder produces at each signal step (audio, image patches), an autoregressive model summarizes past as context , and at each offset log-bilinear critic finds true 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,
The temperature controls how force is distributed across the candidates. Write for anchor and the candidates (positive ), and softmax weights. Differentiating ,
A gradient descent step pulls the positive toward the anchor with a force of and pushes each negative with : 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.
At initially, positive gets only and negative 1, closer to anchor, gets 0.662: 96.7% of all negative weight. The effective number of negatives, calculated over the six negatives, is 1.07: for practical purposes the loss sees just one negative. Raising equalizes weights (3.89 effective at , 5.69 at ) and anchor force falls 2.77 to 0.64 to 0.28: hard and easy negatives become indistinguishable. Lowering sends all weight to the closest candidate. If negative, , 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 and write . The joint density of all the candidates when the positive appears at position is
and the final product does not depend on . Because the position is uniformly distributed, Bayes’ rule gives the following posterior probability
Softmax ratio is a position distribution and expected cross-entropy. By Gibbs’ inequality, for each cross-entropy is at least entropy of , with equality exactly when . Minimum is attained exactly when for almost every .
Characterize those . If , factor cancels in numerator and denominator, making the posterior. Conversely if , ratio between positions 1 and 2 gives for almost every , so does not depend on : it is function .
∎The optimal critic as density ratio explains everything at once. NCE’s optimal logit was data/noise ratio. InfoNCE “noise” is marginal product and “data” the joint, so the critic learns pointwise mutual information up to an function. This is word2vec PMI without shift. It explains van den Oord et al.’s log-bilinear critic: need not be a density, only proportional to a ratio.
There are two practical consequences. First, what does not depend on cannot be learned: critic term is invisible, so InfoNCE does not provide normalized . Second, the critic family limits what the model can represent: cosine critic has , so learned ratio lies in up to a common factor; with a positive can never be over 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 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 and critic , .
Take and independent of everything else; write , . Since is independent of , chain rule gives . Apply NWJ to with critic
The first NWJ term is . Under product the candidates in the second term are exchangeable (all from independent of ), so
Subtracting gives . The second inequality is immediate: the positive is one denominator summand, so each softmax ratio is at most 1 and .
∎Historically, van den Oord et al.’s original derivation used an approximation (replace negative sum by times its expectation, improving as 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
The second inequality bites: however good the critic, : InfoNCE cannot certify more than 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 , making any shortfall from the bound’s fault, not training’s.
At () the readings tell the story. InfoNCE tracks the diagonal to (1.960 at ), then 3.681 at and 4.605 at . It hugs its ceiling: 4.814 at and 4.847 at , 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 , 10.17 at ), but batch deviation grows 0.07 at to 1.32 at . To recover 90% of 4 nats needs candidates (3.68 nats), 6 needs 512 (5.47), and 8 exceeds 1024 (6.67): required grows exponentially in , score matrix cost as .
Lab: InfoNCE as a mutual-information estimator
Now train the critic. Gaussians in with independent coordinates, each correlated , so , and CPC bilinear critic . Handwrite its gradient: with and row softmax , and by chain rule .
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 nats while truth is 4 and ceiling . The critic, not bound, is responsible. Optimal-critic theorem reveals what is missing. For these Gaussians,
and at and , , and . Term is invisible to InfoNCE, but is not: it depends on candidate and does not cancel in softmax. A bilinear critic cannot penalize long candidates; increasing favors both positive and long negatives pointing along , and training stops at (diagonal 0.95–1.08), far from . Add one parameter to include the optimal critic.
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 the trained critic is within 0.02 nats of optimum up to (3.446 versus 3.454), and 0.17 away at (4.586 versus 4.755): training loss. The optimal critic itself falls below as information nears : 3.454 at , 4.398 at , 4.755 at , always below 4.85. Bound loss cannot be fixed by training. Pure bilinear suffers both and does not exceed 2.297.
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 ceiling, demonstrated by its optimal critic (within this quadratic family): 4.01, 6.04, 8.01 at , 6, 8. Batch spread costs: 0.10 at to 0.91 at , variance growing with as studied in information theory. But a critic trained 300 steps falls short: 3.37, 4.41, 4.57, even below . Would more training help?
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 is 6.62 versus optimum ) and with setbacks: at step 1250 it fell to 2.65. NWJ gradient contains evaluated on marginal-product pairs, the terms whose variance explodes with ; 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 and joint and marginal-product samples; their treatment of normalization differs.
| Bound | Expression | Practical bias and variance |
|---|---|---|
| DV (Donsker–Varadhan; MINE) | Tightest for given , but log of a batch mean is biased: estimated thus it is neither lower nor upper bound | |
| NWJ | Unbiased on batch; high variance when is large and batch small | |
| InfoNCE | Low variance; bias from ceiling | |
| (Poole et al.) | interpolates between previous two | is NWJ, InfoNCE; ceiling becomes |
Poole et al. (2019) introduce the last continuous bias–variance family; in their experiments best 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 samples cannot exceed : 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:
- Information can be maximal and constant as representation improves. With bijective encoders (invertible normalizing flows), 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.
- 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.)
- InfoNCE is metric learning. With a symmetric separable critic its loss matches Sohn’s (2016) -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 over pairs is uniform on symmetric -neighbor graph edges (always ): .
- Noise. is approximately uniform over pairs, with noise samples per edge (default ).
- Model. with t-SNE’s Cauchy kernel and parameter .
With learned , NCE loss is
They call this NC-t-SNE: learned approximately converges to t-SNE’s partition function and the embedding resembles t-SNE. Fixing to instead gives fixed-normalization negative sampling (Neg-t-SNE). Original word2vec negative sampling with classifier and no constant corresponds to : then . UMAP appears here: their lemma 3 proves UMAP loss (with ) equals that negative sampling with model , since classifier then equals UMAP similarity . The kernel is not Cauchy, but UMAP embeddings empirically resemble Neg-t-SNE with . This contrastive reading of neighbor embeddings reduces the t-SNE–UMAP difference to one number: normalization.
What a fixed does
The calculation is one line. With the classifier is and expected loss . Differentiating with respect to ,
Compare t-SNE KL with , derivative , and t-SNE with exaggeration , proportional to . Except factor damping nearby pairs, negative sampling with fixed is t-SNE with normalization replaced by a constant, and at stationary embedding behaves like exaggeration
Large means weak repulsion: compact groups eventually merge; small 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 , 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 to while grows as . With and ratio is 70–140.
Reference-run figures (optimization amplifies JavaScript-engine rounding, so your browser may differ in second or third digit):
- NCE learns t-SNE partition. Learned is about 3350, exact t-SNE on the same data 3241 (unordered pairs; double for ordered). Around , outside – above: ratio depends on dataset size and structure, here only 410 points. Both preserve similar fractions of 15 neighbors (0.657, 0.667). Negative sampling with is slightly more compact than t-SNE (maximum coordinate 29.5 versus 35.7): at factor matters; Damrich et al. observe contrastive versions approach t-SNE much more at .
- Toward UMAP repulsion fades. At , is five times but equivalent exaggeration only 2.05: contraction raises from 3198 to 8164, geometry absorbing some increase. Neighbor preservation falls 0.656 to 0.541, scale 29.5 to 16.7. UMAP reference with preserves 0.435, between dial (0.475) and (0.416): kernel differs from and optimization clips steps as umap-learn does, but compact attached subgroups match the paper qualitatively.
- Beyond UMAP subgroups merge. At 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 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- negative sampling.
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. What is the posterior ?
Step 1 of 4. How do you rewrite so you can optimize it?
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 with , and its gradient G with respect to z1, of shape (B, d). Use stable log-sum-exp (with unit vectors and 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, GSummary
- NCE is logistic regression of data against noise with logit . Its optimum is without imposing normalization, provided noise covers the support of the data. Noise similar to the data and large make it efficient; distant noise makes it a trivial task that teaches nothing.
- Negative sampling removes from the logit: it no longer needs noise probabilities, but learns instead of a normalized probability.
- InfoNCE is cross-entropy over 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 .
- Optimal critic and bound. The minimum is attained with , and for every (an NWJ with a multi-sample critic). The bound saturates at ; NWJ does not saturate but pays in variance, and McAllester and Stratos proved that no distribution-free lower bound exceeds .
- 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 resembles t-SNE, and UMAP is negative sampling with an enormous , equivalent to t-SNE with exaggeration.