Contrastive representation learning: views, augmentations and negatives
Use two augmented views of one example as positive pairs and other examples in the batch as negatives. Study augmentations, projection heads, temperature, batch size, negative queues and momentum encoders. Relate the loss to alignment and uniformity on the hypersphere, and study hard and false negatives in local GPU experiments and ablations.
After this lesson you can
- Implement vectorized NT-Xent with self-similarity masked out.
- Train a small SimCLR model on a local GPU and evaluate linear probes before and after the projection head.
- Explain and measure alignment and uniformity and relate them asymptotically to the contrastive loss.
- Explain how MoCo’s negative queue and momentum encoder allow small batches.
- Analyze how temperature weights hard negatives and mitigate false negatives.
- Apply supervised contrastive loss when labels are available.
Before you start
Motivation: from InfoNCE theory to a useful encoder
The previous lesson ended with two uncomfortable facts. First, InfoNCE is a lower bound on mutual information that saturates at , yet methods using it work with in the hundreds or thousands. Second, according to Tschannen et al.’s experiments, mutual information alone does not explain why the representations turn out good. A theory of what is learned is missing; this lesson starts with the engineering of how it is achieved, because every part of a contrastive method—what counts as positive, where negatives come from, where the loss applies, and at what temperature—changes what the encoder learns and can be measured.
The starting point is the problem from the self-supervised learning lesson: expensive labels, abundant unlabeled data, and a representation evaluated with a linear probe on frozen weights. Historical pretext tasks (predicting rotation, ordering patches) made the encoder solve a hand-designed game. The contrastive approach changes the game: given a batch of images, recognize which supplied views are the same image. SimCLR, with a four-times-wide ResNet-50 and linear probe, reached 76.5% top-1 accuracy on ImageNet, on par with a supervised ResNet-50; with fine-tuning and 1% of labels, it reached 85.8% top-5 accuracy (Chen et al., 2020). This lesson builds that method, with a miniature equivalent you train on your GPU, and takes it apart piece by piece:
- Augmentations define what is “the same.” Changing augmentations changes what the representation retains, visible in a toy model.
- NT-Xent is InfoNCE on a matrix of similarities, and a projection head can preserve information in the representation before it.
- Temperature distributes the gradient among negatives, concentrating it on the hardest.
- On the hypersphere, the loss asymptotically decomposes into alignment and uniformity (Wang and Isola), providing metrics without training a probe.
- Negatives can come from the batch (SimCLR, batch-proportional memory) or from a queue with a momentum encoder (MoCo).
- Hard negatives and false negatives are two sides of the same problem, and bias corrections exist.
- What makes good views (the InfoMin principle) and shortcuts exploited by contrastive tasks.
- With labels, supervised contrastive loss generalizes NT-Xent.
- Details that ruin comparisons: BatchNorm leaking information between examples and mismatched compute budgets.
The view framework: augmentations define what is the same
A contrastive method does not use labels, but does use knowledge about which transformations leave important properties unchanged: cropping and scaling a cat photo does not turn it into a dog; changing brightness does not either. That knowledge enters through a family of augmentations.
The loss favors features shared by the two views that also help distinguish examples. A constant feature cannot rule out negatives, and strong perturbation can make a feature unreliable for recognizing the positive. However, changing a feature does not imply that all its information disappears, and stability does not guarantee the encoder retains it: architecture, capacity, and optimization also matter. Augmentations induce pressure toward certain invariances, not an exact guarantee.
The following toy model makes that logic visible. There are 600 examples with independent content factor and style factor . What is observed is with a fixed rotation, so no axis of “is” content. An augmentation adds normal noise with standard deviation to content and to style; a one-hidden-layer encoder (4 → 32 → 3 with unit output) is trained with NT-Xent in your browser on the 600 unlabeled examples. The figure measures how much of each factor can be read from the embedding with 5-nearest-neighbor regression, fitted on 400 examples and evaluated on the other 200. Those 200 are held out from the probe, but the encoder saw them without labels during pretraining.
After 3000 steps with the figure’s seed: if augmentations change style (, ), the probe recovers content well () and style poorly (); reversed (, ), it recovers style (0.99) and fails on content (). If both factors are perturbed equally (, ), values are 0.60 and 0.38. Without augmentations, the probe gives 0.65 for content and 0.63 for style: the task can use any stable feature. With it obtains 0.46 and 0.87. These numbers describe one seed and a particular probe; a failing probe does not prove absolute absence of information.
There is a simple quantitative reading. A factor uniform in has variance per coordinate between examples; augmentation adds noise with variance . The signal-to-noise ratio is 33 for and 0.33 for : the first identifies examples almost perfectly, the second barely. The encoder retains factors with high signal-to-noise ratio, which help find the positive. This model anticipates the question in lesson 24, which latent factors are identified when training with contrastive loss: here we see on a small scale that they depend on augmentations.
For real images, SimCLR augmentations are random resized cropping, horizontal flipping, color distortion (brightness, contrast, saturation, hue), and Gaussian blur—the geometric and photometric augmentations from the vision module. Chen et al. conclude that composing crop and color distortion is critical: two crops of the same image share almost the same color distribution, and an encoder can solve the task with a color histogram without learning shape. The shortcuts section returns to this.
SimCLR: encoder, projection head, and NT-Xent
The NT-Xent loss
Take a batch of examples and generate two views of each: views. An encoder (here a convolutional network) maps them to representations , and a projection head maps them to , normalized to length 1. For each view , its partner is (with numbering where and are views of the same example, ). With :
This is the previous lesson’s InfoNCE loss with a matrix of similarities, without the diagonal, with the positive in the denominator and all views as anchors. Its gradient is obtained like InfoNCE’s and is used by the interactives in this lesson. With the row-wise softmax of with the diagonal masked, and ,
Each vector receives force in two ways, as an anchor (weights ) and as a negative for other anchors (weights ), and is attracted to its partner with constant strength 2. Before differentiating through normalization , project the gradient onto the sphere’s tangent plane, : the radial component is lost on normalization.
The projection head
The loss is applied to , but what is used afterward is .
Chen et al. find that a nonlinear projection improves on a linear one by about 3 points and no projection by more than 10 points when the layer before the head is evaluated by linear probe. The authors propose can discard information useful for another task, such as color or orientation, while does not receive direct loss pressure. To examine that hypothesis they train transformation classifiers: in their table 3, rotation is predicted with 67.6% from and 25.6% from . In that ablation they added rotation to pretraining and both layers had 2048 dimensions. The result is consistent with a buffering function for the head, not a guarantee that always preserves more information for every task.
Lab: miniature SimCLR on your GPU
The lab implements all of the above on Fashion-MNIST: per-image GPU augmentations (resized crop and flip, plus contrast, gamma, and brightness), a small convolutional encoder (multichannel convolution, batch normalization), the head, and NT-Xent written by hand. The loop is the familiar training loop with epoch shuffling, Adam, and learning-rate scheduling instead of SGD momentum. The first cell checks the loss against the two-loop definition in float64; the second trains 30 epochs with batches of 512 images and evaluates with a linear probe and -NN before and after the head, and with alignment and uniformity metrics defined below. To check the flow first, set ORYON_SHORT_RUN=1 in the local process environment: 2048 training examples, 256 test examples, one epoch per training run, and eight supervised steps are used. This short test is not a performance comparison.
import math
import time
import os
from pathlib import Path
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from torchvision.datasets import FashionMNIST
torch.set_num_threads(1)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
FashionMNIST.mirrors = ["https://raw.githubusercontent.com/zalandoresearch/fashion-mnist/master/data/fashion/"]
root = Path.home() / ".cache" / "atlas-data"
tr, te = FashionMNIST(root, train=True, download=True), FashionMNIST(root, train=False, download=True)
Xtr, ytr = tr.data.float().div(255).unsqueeze(1).to(dev), tr.targets.to(dev) # 60000 x 1 x 28 x 28
Xte, yte = te.data.float().div(255).unsqueeze(1).to(dev), te.targets.to(dev) # 10000 x 1 x 28 x 28
SHORT_RUN = os.environ.get('ORYON_SHORT_RUN') == '1'
if SHORT_RUN:
Xtr, ytr, Xte, yte = Xtr[:2048], ytr[:2048], Xte[:256], yte[:256]
print('Prueba corta: 2048 imágenes de entrenamiento y 256 de test')
def make_encoder(seed):
"""Codificador convolucional pequeño: 28x28 -> 512 características."""
torch.manual_seed(seed)
def block(i, o):
return nn.Sequential(nn.Conv2d(i, o, 3, padding=1), nn.BatchNorm2d(o), nn.ReLU())
return nn.Sequential(block(1, 32), nn.MaxPool2d(2), block(32, 64), nn.MaxPool2d(2),
block(64, 128), nn.AdaptiveAvgPool2d(2), nn.Flatten()).to(dev)
def make_head(d_out=128):
"""Cabeza de proyección: MLP de una capa oculta, 512 -> 512 -> d_out."""
return nn.Sequential(nn.Linear(512, 512), nn.ReLU(), nn.Linear(512, d_out)).to(dev)
def augment(x, crop=True, flip=True, jitter=True, scale=(0.3, 1.0)):
"""Una vista aleatoria de cada imagen del lote: recorte con cambio de tamaño y volteo (geométricos) y
contraste, gamma y brillo (fotométricos). Todo en la GPU y con parámetros distintos por imagen."""
n = len(x)
u = lambda lo, hi: torch.empty(n, device=x.device).uniform_(lo, hi)
if crop or flip:
area = u(*scale) if crop else torch.ones(n, device=x.device)
ratio = torch.exp(u(math.log(3 / 4), math.log(4 / 3))) if crop else torch.ones(n, device=x.device)
sx, sy = (area * ratio).sqrt().clamp(max=1), (area / ratio).sqrt().clamp(max=1)
sign = torch.where(torch.rand(n, device=x.device) < 0.5, -1.0, 1.0) if flip else torch.ones(n, device=x.device)
theta = torch.zeros(n, 2, 3, device=x.device)
theta[:, 0, 0], theta[:, 1, 1] = sx * sign, sy
theta[:, 0, 2], theta[:, 1, 2] = (2 * torch.rand(n, device=x.device) - 1) * (1 - sx), (2 * torch.rand(n, device=x.device) - 1) * (1 - sy)
x = F.grid_sample(x, F.affine_grid(theta, list(x.shape), align_corners=False), mode="bilinear", padding_mode="zeros", align_corners=False)
if jitter:
a, g, b = u(0.5, 1.5), torch.exp(u(math.log(0.6), math.log(1.6))), u(-0.15, 0.15)
x = (a.view(-1, 1, 1, 1) * x.clamp(min=0) ** g.view(-1, 1, 1, 1) + b.view(-1, 1, 1, 1)).clamp(0, 1)
return x
def nt_xent(z, tau):
"""NT-Xent de SimCLR. z: (2N, d); z[i] y z[i + N] son las dos vistas del ejemplo i."""
z = F.normalize(z, dim=1)
n2 = z.shape[0]
sim = z @ z.T / tau
sim = sim.masked_fill(torch.eye(n2, dtype=torch.bool, device=z.device), float("-inf")) # fuera la autosimilitud
target = torch.cat([torch.arange(n2 // 2, n2), torch.arange(0, n2 // 2)]).to(z.device) # el positivo de i es i +- N
return F.cross_entropy(sim, target)
def nt_xent_naive(z, tau):
"""La definición con dos bucles, en float64, para comprobar la versión vectorizada."""
z = F.normalize(z.double(), dim=1)
n2, total = len(z), 0.0
for i in range(n2):
j = (i + n2 // 2) % n2
den = sum(math.exp(float(z[i] @ z[k]) / tau) for k in range(n2) if k != i)
total += -math.log(math.exp(float(z[i] @ z[j]) / tau) / den)
return total / n2
zt = torch.randn(12, 16, device=dev)
print(f"vectorizada {nt_xent(zt, 0.3).item():.6f} bucles {nt_xent_naive(zt, 0.3):.6f}")
@torch.no_grad()
def features(enc, X, bs=5000):
enc.eval()
return torch.cat([enc(X[i:i + bs]) for i in range(0, len(X), bs)])
def train_simclr(seed=0, epochs=30, bs=512, tau=0.2, lr=2e-3, proj=True, aug=None, loss_fn=nt_xent, log_every=0):
"""Preentrena un SimCLR en miniatura. Devuelve el codificador, la cabeza (o None) y la pérdida media por época."""
aug = aug or {}
enc, head = make_encoder(seed), (make_head() if proj else nn.Identity().to(dev))
params = [*enc.parameters(), *head.parameters()]
opt = torch.optim.Adam(params, lr=lr, weight_decay=1e-6)
steps = epochs * (len(Xtr) // bs)
sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=lr, total_steps=steps, pct_start=0.1)
g = torch.Generator(device=dev).manual_seed(seed)
hist = []
for ep in range(1, epochs + 1):
enc.train(); head.train()
tot = 0.0
for idx in torch.randperm(len(Xtr), device=dev, generator=g).split(bs)[: len(Xtr) // bs]:
x = Xtr[idx]
z = head(enc(torch.cat([augment(x, **aug), augment(x, **aug)])))
loss = loss_fn(z, tau)
opt.zero_grad(set_to_none=True)
loss.backward()
opt.step(); sched.step()
tot += loss.item()
hist.append(tot / (len(Xtr) // bs))
if log_every and ep % log_every == 0:
print(f" época {ep:3d} pérdida {hist[-1]:.4f}")
return enc, head, histnpm run lab and open the connection link.def standardize(Ztr, Zte):
mu, sd = Ztr.mean(0), Ztr.std(0) + 1e-6
return (Ztr - mu) / sd, (Zte - mu) / sd
def fit_logreg(Z, y, wd, iters=100):
"""Regresión softmax con decaimiento de pesos, ajustada con L-BFGS."""
W = torch.zeros(Z.shape[1], 10, device=dev, requires_grad=True)
b = torch.zeros(10, device=dev, requires_grad=True)
opt = torch.optim.LBFGS([W, b], lr=1.0, max_iter=iters, line_search_fn="strong_wolfe")
def closure():
opt.zero_grad()
loss = F.cross_entropy(Z @ W + b, y) + wd * (W ** 2).sum()
loss.backward()
return loss
opt.step(closure)
return W.detach(), b.detach()
def accuracy(Z, y, W, b):
return ((Z @ W + b).argmax(1) == y).float().mean().item()
def linear_probe(Ztr, ytr_, Zte, yte_, wds=(1e-4, 1e-3, 1e-2, 1e-1), seed=0):
"""Sonda lineal: el decaimiento se elige con una validación sacada del entrenamiento; el test se mira al final."""
perm = torch.randperm(len(Ztr), generator=torch.Generator().manual_seed(seed)).to(dev)
nv = max(len(Ztr) // 5, 1)
va, fi = perm[:nv], perm[nv:]
Zfit, Zval = standardize(Ztr[fi], Ztr[va])
val = {wd: accuracy(Zval, ytr_[va], *fit_logreg(Zfit, ytr_[fi], wd)) for wd in wds}
best = max(val, key=val.get)
Ztr, Zte = standardize(Ztr, Zte)
return accuracy(Zte, yte_, *fit_logreg(Ztr, ytr_, best))
def knn_eval(train_z, train_y, test_z, k=20, tau=0.07):
"""k-NN coseno con votos ponderados por exp(s / tau), como en la lección anterior."""
mu = train_z.mean(0)
A, B = F.normalize(train_z - mu, dim=1), F.normalize(test_z - mu, dim=1)
preds = []
for i in range(0, len(B), 2000):
s, idx = (B[i:i + 2000] @ A.T).topk(k, dim=1)
votes = torch.zeros(len(s), 10, device=dev).scatter_add_(1, train_y[idx], (s / tau).exp())
preds.append(votes.argmax(1))
return (torch.cat(preds) == yte).float().mean().item()
@torch.no_grad()
def align_uniform(f, n=5000, t=2.0, seed=0):
"""Alineamiento y uniformidad de Wang e Isola. f lleva un lote de imágenes a vectores (se normalizan aquí)."""
torch.manual_seed(seed)
x = Xte[:n]
a, b = F.normalize(f(augment(x)), dim=1), F.normalize(f(augment(x)), dim=1)
align = (a - b).pow(2).sum(1).mean().item() # E ||f(x) - f(y)||^2 sobre pares positivos
uniform = torch.log(torch.exp(-t * torch.pdist(a).pow(2)).mean()).item() # log E exp(-t ||f(x) - f(y)||^2) sobre pares distintos
return align, uniform
def evaluate(enc, head=None, full=True, wds=(1e-4, 1e-3, 1e-2, 1e-1)):
"""Sonda y k-NN sobre h (salida del codificador) y, con cabeza, sobre z = g(h); alineamiento y uniformidad de h y de z."""
out = {}
Htr, Hte = features(enc, Xtr), features(enc, Xte)
out["probe_h"] = linear_probe(Htr, ytr, Hte, yte, wds=wds)
out["knn_h"] = knn_eval(Htr, ytr, Hte)
enc.eval()
out["au_h"] = align_uniform(lambda x: enc(x))
if head is not None and not isinstance(head, nn.Identity):
head.eval()
with torch.no_grad():
Ztr, Zte = head(Htr), head(Hte)
if full:
out["probe_z"] = linear_probe(Ztr, ytr, Zte, yte, wds=wds)
out["knn_z"] = knn_eval(Ztr, ytr, Zte)
out["au_z"] = align_uniform(lambda x: head(enc(x)))
return out
t0 = time.time()
enc_rand = make_encoder(1) # la misma arquitectura sin entrenar, otra semilla
pix_tr, pix_te = Xtr.flatten(1), Xte.flatten(1)
res = {"píxeles (784)": {"probe_h": linear_probe(pix_tr, ytr, pix_te, yte), "knn_h": knn_eval(pix_tr, ytr, pix_te)},
"codificador aleatorio (512)": evaluate(enc_rand)}
base_epochs = 1 if SHORT_RUN else 30
enc_sc, head_sc, hist_sc = train_simclr(seed=0, epochs=base_epochs, bs=512, tau=0.2, log_every=5)
print(f"SimCLR: {base_epochs} épocas de {len(Xtr) // 512} pasos con lotes de 512 imágenes (1024 vistas) en {time.time() - t0:.0f} s")
res["SimCLR, h (antes de la cabeza)"] = ev = evaluate(enc_sc, head_sc)
print(f"\n{'representación':32s} {'sonda lineal':>12s} {'k-NN (k=20)':>12s}")
for name, r in res.items():
print(f"{name:32s} {r['probe_h']:12.4f} {r['knn_h']:12.4f}")
print(f"{'SimCLR, z (después de la cabeza)':32s} {ev['probe_z']:12.4f} {ev['knn_z']:12.4f}")
print("\nAlineamiento y uniformidad (t = 2) medidos sobre vistas aumentadas del test:")
au = res["codificador aleatorio (512)"]["au_h"]
print(f" codificador aleatorio, h : alineamiento {au[0]:.3f} uniformidad {au[1]:.3f}")
print(f" SimCLR, h : alineamiento {ev['au_h'][0]:.3f} uniformidad {ev['au_h'][1]:.3f}")
print(f" SimCLR, z : alineamiento {ev['au_z'][0]:.3f} uniformidad {ev['au_z'][1]:.3f}")npm run lab and open the connection link.Compare the results your run prints: the probe is fitted on the training set and reserves part of it for selecting regularization. Test results depend on training and seed; they do not imply the head always improves or worsens representations for every task.
Temperature: sensitivity to negative difficulty
Temperature is the hyperparameter that most changes the behavior of the loss. In the previous lesson you saw the gradient for an anchor; for a whole batch with both views as anchors, the result is the same: each negative of anchor receives force proportional to its softmax weight,
Wang and Liu (2021) call this relative penalty and observe that, for an anchor, negative weights form a Boltzmann distribution with temperature . Two limits:
- With , weight concentrates on candidates most similar to the anchor, shared among ties. The loss multiplied by tends to , with the inner maximum over negatives: a zero-margin loss with the hardest negative. Without that multiplication, the loss generally has no finite limit. Wang and Liu warn that extremely low temperatures make the loss attend only to one or two neighbors.
- With , full-softmax weights tend to , including the positive. When normalized only among negatives, each receives of that mass. The loss stops distinguishing hard from easy negatives.
To see the effect at real batch scale, many negatives must be examined at once. The following interactive models 1022 negatives from a 512-image batch and weights them with . In uniform-sphere mode, similarity has density : this is an explicit model, not a measurement. Measured mode uses 40-bin histograms calculated from the first 5000 Fashion-MNIST test images after training five models for 8 epochs, batch size 512, seed 0. The similarities cell reproduces their calculation and exports the histograms.
The histograms aggregate anchor–key pairs before weighting, so each class’s assigned mass approximates an aggregation of similarities, not the exact average of per-anchor normalized softmaxes. The positive slider represents a hypothetical similarity independent of those histograms. Measured mode uses labels only for subsequent diagnosis: pretraining does not receive them.
In the sphere model with , a positive at , and 1022 expected negatives: with the moment equivalent is 494.8 of 1022 and 6.7% of weight falls on the 10 expected hardest negatives; with they are 1.5 and 75.3%; with they are 990.7 and 1.5%. The figure calculates the continuous distribution’s moment ratio, an approximation to effective number for a particular batch. In very rare tails this approximation can even be less than 1, although the effective number of any finite batch is at least 1; do not interpret it as a literal count. With similarities of two uniform vectors concentrate around 0 (standard deviation ), and for the same weights spread more: with the equivalent is 475.4, versus 89.0 with . Suitable temperature therefore depends on how similarities are distributed, meaning dimension and structure already present in the representation, not just the number’s value.
Difficulty cuts both ways. Repelling the most similar negatives improves uniformity (nearby points separate), but those most similar to an anchor are also most likely to share its semantic class. Wang and Liu call this the uniformity–tolerance dilemma: low gives more uniform embeddings but less tolerance for semantically similar examples; high is more tolerant, but the embedding may not be uniform enough. In their CIFAR-10 experiments, linear accuracy with ordinary contrastive loss is 79.75 with , 83.27 at 0.3, 82.69 at 0.7, and 82.21 at 1.0, while their tolerance measure (mean similarity of same-class pairs) rises from 0.04 to 0.372. SimCLR on ImageNet with ResNet-50 finds its optimum at with normalization (64.4% top-1 accuracy, versus 59.7% at 0.05, 60.7% at 0.5, and 58.0% at 1), and without normalization (with and ) falls to 57.2% and 57.0%. Both results agree on one point: an intermediate value is best, and depends on dataset and model.
Alignment and uniformity on the hypersphere
What property of the representation does contrastive loss reward? Wang and Isola (2020) give a geometric answer with two measures on the hypersphere.
Alignment reaches its minimum () with any encoder giving both views the same output, for example a constant encoder, which has the worst possible uniformity (). Minimum uniformity is attained by the uniform distribution over the sphere (Wang and Isola, proposition 1: it is the unique probability measure minimizing average Gaussian energy). For sphere , where the similarity of two uniform points is uniform in (Archimedes) and , this gives . With , the minimum is . For other dimensions similarity has density and the minimum follows from a one-dimensional integral.
The connection with contrastive loss is asymptotic in the number of negatives.
Proof
Subtract inside the expectation: , with and . Exponents lie in , so the logarithm’s argument, , lies between and : bounded and away from 0. Conditioned on the anchor, averages independent bounded variables; by the strong law of large numbers it converges to . The function is continuous and quantities are bounded away from 0, so dominated convergence moves the limit inside the expectation, yielding .
For unit vectors, . Then , and with , so the second term is . The two constants cancel, giving equality.
Finally, is concave, and Jensen’s inequality gives with ; the right-hand side is . Since is strictly concave, equality holds if and only if is almost surely constant; for a uniform encoder on the sphere, rotational symmetry guarantees this.
∎Wang and Isola state the limit with the second term in the form (the logarithm of expectation conditioned on the anchor) and prove two things about it: the first term is minimized if and only if positives coincide ( almost surely), and, if perfectly uniform encoders exist, these minimize the second. Uniformity in the definition is the version with logarithm outside the expectation, easier to estimate, which bounds the second term above. The theorem’s inequality is a direct consequence made explicit here. They also prove deviation from the limit decreases as .
The next cell checks the theorem with an explicit encoder on the circle (), where all limiting expectations are calculated by quadrature. Data have von Mises angles (concentration ; is uniform), and positives are the anchor plus normal noise with standard deviation 0.3 radians.
import numpy as np
rng = np.random.default_rng(0)
tau, sigma = 0.5, 0.3 # temperatura y desajuste de los positivos (radianes)
G = 720
phi = np.linspace(-np.pi, np.pi, G, endpoint=False) # rejilla para las esperanzas exactas sobre la circunferencia
def density(kappa):
p = np.exp(kappa * np.cos(phi)) # von Mises: kappa = 0 es la uniforme
return p / p.sum()
def exact_terms(kappa):
"""Alineamiento, uniformidad (t = 1/(2 tau)) y límite de la pérdida (menos log M), todo por cuadratura."""
p, t = density(kappa), 1 / (2 * tau)
dphi = np.cos(phi[:, None] - phi[None, :]) # coseno entre dos puntos de la rejilla
align = 2 - 2 * np.exp(-sigma**2 / 2) # E ||z(x) - z(y)||^2 con y = x + N(0, sigma^2): 2 - 2 E cos(delta)
unif = np.log(p @ np.exp(-t * (2 - 2 * dphi)) @ p) # log E exp(-t ||z - z'||^2) sobre pares independientes
inner = np.exp(dphi / tau) @ p # E_{x-} exp(z(x)^T z(x-) / tau) para cada ancla x
limit = -np.exp(-sigma**2 / 2) / tau + p @ np.log(inner)
return align, unif, limit
def finite_M(kappa, M, n=1500):
"""Pérdida contrastiva de M negativos (con el positivo en el denominador) menos log M, por Monte Carlo."""
x = rng.vonmises(0.0, kappa, n)
y = x + sigma * rng.normal(size=n)
neg = rng.vonmises(0.0, kappa, (n, M))
s_pos = np.cos(y - x) / tau
s_neg = np.cos(neg - x[:, None]) / tau
loss = -s_pos + np.log(np.exp(s_pos) + np.exp(s_neg).sum(1))
return loss.mean() - np.log(M)
Ms = (2, 8, 32, 128, 512)
print(f"tau = {tau}, desajuste sigma = {sigma}: cota = align/(2 tau) + L_unif frente al límite L_inf de la pérdida")
print(f"{'kappa':>5} {'align':>7} {'L_unif':>8} {'L_inf':>8} {'cota':>8} {'hueco':>7} " + " ".join(f"M={M:<5d}" for M in Ms))
for kappa in (0.0, 1.0, 3.0):
a, u, lim = exact_terms(kappa)
bound = a / (2 * tau) + u
print(f"{kappa:5.1f} {a:7.4f} {u:8.4f} {lim:8.4f} {bound:8.4f} {bound - lim:7.4f} " + " ".join(f"{finite_M(kappa, M):7.3f}" for M in Ms))With (uniform data on the circle), the limit and bound coincide (−1.0880), and loss with negatives, minus , approaches that value as grows (from with to with ). With and 3, the bound exceeds the limit by 0.064 and 0.043: the Jensen gap appearing when the distribution is nonuniform.
Interactive: training on the sphere
The following interactive trains a small encoder (2 → 32 → 3 with unit output) in your browser, mapping 120 planar points in 6 Gaussian groups of 20 to sphere . Each augmentation adds normal noise with standard deviation and the views are positive pairs. The loss is NT-Xent with parameter weighting the negative term: . With there is only alignment; with it is NT-Xent without the positive in the denominator. Measure alignment and uniformity with over the 120 points.
With the figure’s seed and 3000 steps, initial values (, , ) give alignment 0.124, uniformity , and 85% 5-neighbor accuracy recovering the group. The population minimum in is ; an estimate with distinct pairs from a finite sample does not have exactly the same bound because it excludes diagonal pairs. With , all points collapse: alignment 0.000, uniformity , mean norm 1.00, and neighbors achieve 57%, what remains of the information when the encoder returns (almost) the same thing for everything. Negatives prevent collapse in this simulation. With uniformity stays at and with at , versus with : in this model there is an intermediate temperature, and with alignment rises from 0.124 to 0.307 because noisier pairs are harder to bring together.
Wang and Isola find both metrics accompany downstream performance: the best encoders have low alignment and uniformity together, and directly optimizing and gives comparable or better results than contrastive loss in their experiments. Use them as a diagnostic: they are cheap (no probe) and detect collapse (uniformity near 0) and overly difficult views (high alignment). Either one alone is insufficient, as just seen.
Number of negatives: large batches versus a momentum queue
SimCLR needs many negatives and takes them from the batch: . That ties negative count to GPU memory because every batch view must be backpropagated. Chen et al. train with batch sizes 256 to 8192 and default 4096 (for 100 epochs); with few epochs large batches have a clear advantage, while with longer training size differences diminish or disappear. MoCo (He et al., 2020) proposes decoupling the two numbers.
MoCo: a key queue with a momentum encoder
Think of the loss as a query looking for its match in a dictionary of keys. Keys do not need gradients, so they can come from earlier batches and be stored. This only works if they have all been encoded consistently: if each key comes from a different encoder, comparing the query to them makes no sense.
A queue is cheap: keys of 128 numbers in float32 occupy 32 MiB and are not backpropagated. The oldest queue keys are steps old (256 steps for and ). From one step to the next, advances fraction of its distance to . Averaging scale approximates, when is close to 1, the exact exponential decay constant . With the approximation gives 1000 steps, more than the queue’s 256. This favors consistency but does not guarantee keys are almost identical: how much and how changes also matters. If minibatch noise in is independent at each step, with standard deviation , stationary noise in has variance . With the standard deviation is divided by . The price is lag: for a sustained linear trend, the moving-average weights’ mean age is steps.
The following interactive isolates that tradeoff. It trains nothing: it prescribes the trajectory of a small encoder’s parameters (the 2 → 32 → 3 MLP from the other figures) as , with systematic trend speed along fixed direction and minibatch noise independent at each step and parameter, and applies the momentum update. Keys are normalized encoder outputs on 200 fixed points. It measures two things: queue consistency (mean cosine between a key saved steps ago and what would produce today for the same point) and trend fidelity (mean cosine between the key produced by and what the noiseless trend encoder would produce, which is what the query tries to match). The first measures key variance, and the second combines variance with lag. This is a stylized model, not a measurement: independent noise and linear trend are assumptions you can change with sliders.
With initial values (, , , , 2500-step trajectory), the readings are:
| 0 | 0.9 | 0.99 | 0.999 | 0.9999 | |
|---|---|---|---|---|---|
| queue consistency | 0.591 | 0.944 | 0.997 | 0.999 | 1.000 |
| trend fidelity | 0.767 | 0.970 | 0.998 | 0.966 | 0.800 |
With , queue keys were encoded with parameters differing due to noise at each step: the oldest key matches what would produce today with cosine only 0.2, and such negatives do not define a consistent dictionary. Raising averages that noise and consistency reaches almost 1. But lag appears from 0.999: fidelity falls again (0.966 at 0.999, 0.800 at 0.9999) because the key encoder has not yet followed the trend. Maximum fidelity here occurs around , and the cost of lag depends on speed: with fidelity with is 0.994, and with is 0.936. With keys are equally consistent for any (0.999: the trend shifts them all equally), and momentum only costs lag. The figure’s reading is qualitative: momentum buys consistency with lag, and the right value depends on optimizer noise and how fast the encoder changes.
MoCo’s ablation with and ResNet-50 measures the real result of that tradeoff: with training fails (“loss oscillates and does not converge”), and with linear accuracy is 55.2, 57.8, 59.0, and 58.9% (He et al., ablation table). The paper’s defaults are , , , and batch 256 on 8 GPUs. Against a memory bank with the same loss and (58.0%), MoCo achieves 60.6%. In MoCo v2 (Chen et al., 2020), adding SimCLR’s MLP head, blur, and cosine learning rate to MoCo yields 67.5% top-1 accuracy with 200 epochs and 71.1% with 800, batch 256; in the same table SimCLR with 200 epochs has 61.9% with batch 256 and 66.6% with batch 8192. This is the queue’s argument: almost the performance of a huge batch without its memory.
Hard negatives, false negatives, and bias correction
In unlabeled contrastive learning, negatives are “any other example in the batch.” If there are balanced classes, fraction of those negatives shares the anchor’s class. That fraction does not decrease as batch size grows: with and 4096 images, about one in ten of the other 4095, roughly 409, share the class, and each contributes two negative views.
The next cell builds an explicit model with 10 balanced classes on the sphere , and measures two things: the share of repulsion received by false negatives, and the bias they introduce in the negative term.
import numpy as np
rng = np.random.default_rng(0)
C, d, N, tau = 10, 32, 4096, 0.5 # 10 clases equilibradas, lotes de 4096, temperatura 0.5
means = rng.normal(size=(C, d))
means /= np.linalg.norm(means, axis=1, keepdims=True)
def sample(cls, spread=0.12):
"""Incrustaciones unitarias de la clase cls: su centro más ruido normal, normalizadas."""
z = means[cls] + spread * rng.normal(size=(len(cls), d))
return z / np.linalg.norm(z, axis=1, keepdims=True)
anchor = sample(np.zeros(1, dtype=int))[0] # un ancla de la clase 0
batch_cls = rng.integers(0, C, N) # clases de los N negativos candidatos: cada uno es de la clase 0 con prob. 1/C
batch = sample(batch_cls)
e = np.exp(batch @ anchor / tau)
same = batch_cls == 0
print(f"negativos de la misma clase: {same.sum()} de {N} ({same.mean():.3f}); esperado {N / C:.1f} +- {np.sqrt(N * 0.1 * 0.9):.1f}")
print(f"parte de la masa de los pesos exp(s/tau) que reciben los falsos negativos: {e[same].sum() / e.sum():.3f} (su fracción numérica: {same.mean():.3f})")
for t in (0.1, 0.2, 1.0):
w = np.exp((batch @ anchor - 1) / t)
print(f" con tau = {t:<4}: {w[same].sum() / w.sum():.3f}")
# Estimadores del término de los negativos verdaderos E_{x- ~ p-} exp(s/tau) (con n = 256 negativos por ancla)
true_neg = np.exp(sample(rng.integers(1, C, 200000)) @ anchor / tau).mean()
n_batch, reps, tp = 256, 400, 1 / C
naive, debiased = [], []
for _ in range(reps):
cls = rng.integers(0, C, n_batch)
u = np.exp(sample(cls) @ anchor / tau).mean() # promedio ingenuo sobre el lote (con falsos negativos)
v = np.exp(sample(np.zeros(n_batch, dtype=int)) @ anchor / tau).mean() # positivos de la clase del ancla (aquí, de verdad)
naive.append(u)
debiased.append(max((u - tp * v) / (1 - tp), np.exp(-1 / tau))) # estimador de Chuang et al. con el suelo exp(-1/tau)
for name, est in (("ingenuo", naive), ("con corrección de sesgo", debiased)):
est = np.array(est)
print(f"{name:26s} media {est.mean():7.3f} desv. típica {est.std():6.3f} sesgo relativo {(est.mean() / true_neg - 1) * 100:+6.1f} %")
print(f"valor verdadero E_(p-) exp(s/tau) = {true_neg:.3f}")In that model, 431 of 4096 candidates (10.5%) are in the anchor’s class, but receive 30.9% of weight mass with , 71.8% at 0.2, and 96.0% at 0.1. Because of the model’s very compact classes the number exceeds that of a real dataset; the lab below measures it on Fashion-MNIST.
Bias correction
Chuang et al. (2020) correct the negative term. If is the probability that two examples share a class, the marginal distribution decomposes into , with , the distribution of examples in the class of and that of the others. Rearranging,
The naive batch average estimates the first term in parentheses, and overestimates the true-negative term by , which is positive if same-class examples resemble the anchor more. Their estimator, with negatives and positives , is
where is the term’s theoretical minimum (the dot product of unit vectors is at least , with the temperature), and loss is . In practice is a hyperparameter (their paper uses on ImageNet-100) and the positive sample consists of the anchor’s own views (). The previous cell checks the algebra with true positives from the anchor’s class: the naive average over 256 negatives overestimates the true term (1.043) by 28.7%, and the corrected estimator by 0.7%, with similar standard deviation (0.067 versus 0.061).
Published results are modest and heterogeneous: Chuang et al. report a 4.26-point SimCLR improvement on STL10, and top-1 accuracy from 73.58 to 74.6% with CMC on ImageNet-100 (with ). Robinson et al. (2021) go a step further: instead of removing false negatives, they weight negatives by difficulty, with proposal giving more weight to those close to the anchor, and with recover Chuang et al.’s loss. Their reweighting is implemented in a few lines on batch loss and adds no computational cost according to the authors, who report improvements over SimCLR of 3% on CIFAR100 and 7.3% on STL10. This is the section’s tension: more weight on hard negatives helps learn fine distinctions and hurts when hard negatives are false. Without labels the cases cannot be separated with certainty; corrections use a class prior or intermediate difficulty.
Which views are good: the InfoMin principle and shortcuts
If augmentations determine what is learned, which should we choose? Tian et al. (2020) answer with the InfoMin principle: a good set of views shares the minimum information needed for the downstream task. With too much mutual information between views, the representation carries factors irrelevant to the task; with too little, what the task needs is lost. This gives an inverted-U accuracy-versus-mutual-information curve, with an optimum for many view families. Formally (their proposition 3.1), with sufficient and minimal encoders, optimal views minimize while maintaining . Applying this requires knowing the downstream task, usually unknown, which makes it difficult in practice. With their InfoMin augmentations and a linear probe on ImageNet, Tian et al. reach 73% top-1 accuracy with ResNet-50 (paper abstract, after 800 epochs).
What can be checked without that knowledge is the presence of shortcuts: features that identify the positive without being what you want to learn. SimCLR’s is color: two crops of the same image share a color histogram, while different views do not. The toy model above has the same structure: a stable factor (style when is small) suffices to identify the example, and the encoder uses it even if content is what you wanted. In images the remedy is to break the shortcut with stronger augmentation (color distortion removes the histogram cue) and use the probe and alignment and uniformity metrics to check the representation did not settle on the easy feature.
Lab: miniature SimCLR ablations
The following ablations repeat training for 8 epochs, changing one factor at a time: temperature, batch size, augmentation type, projection head, and Chuang et al.’s bias correction with (the true Fashion-MNIST prior, with 10 balanced classes). All are evaluated by linear probe and -NN on and by alignment and uniformity. Two design cautions: training losses are not comparable (they depend on and batch), and with fixed epochs a small batch gives more optimization steps, so comparison mixes two effects. The second cell measures similarities of trained models and calculates how much repulsion false negatives receive.
EPOCHS_ABL = 1 if SHORT_RUN else 8
runs = {}
def nt_xent_debiased(z, tau, tau_plus=0.1):
"""NT-Xent con la corrección de sesgo de Chuang et al. (2020): al término de los negativos se le resta la parte que
corresponde a ejemplos de la misma clase (de prior tau_plus) y se acota por su mínimo teórico n_neg * exp(-1 / tau)."""
z = F.normalize(z, dim=1)
n2 = z.shape[0]
S = z @ z.T / tau
eye = torch.eye(n2, dtype=torch.bool, device=z.device)
partner = (torch.arange(n2, device=z.device) + n2 // 2) % n2
pos = S[torch.arange(n2), partner].exp()
neg = S.masked_fill(eye, float("-inf")).exp().sum(1) - pos # suma de los 2N - 2 negativos
n_neg = n2 - 2
ng = ((neg - n_neg * tau_plus * pos) / (1 - tau_plus)).clamp(min=n_neg * math.exp(-1 / tau))
return -(pos / (pos + ng)).log().mean()
def run(name, **kw):
t = time.time()
enc, head, hist = train_simclr(seed=0, epochs=EPOCHS_ABL, **kw)
ev = evaluate(enc, head, full=False, wds=(1e-3, 1e-2, 1e-1))
runs[name] = (enc, head, ev, hist[-1])
au = ev.get("au_z", ev["au_h"])
print(f"{name:34s} {ev['probe_h']:8.4f} {ev['knn_h']:8.4f} {hist[-1]:8.3f} {au[0]:8.3f} {au[1]:9.3f} {time.time() - t:6.0f} s")
print(f"{f'ablación ({EPOCHS_ABL} épocas)':34s} {'sonda h':>8s} {'k-NN h':>8s} {'pérdida':>8s} {'alineam.':>8s} {'uniform.':>9s}")
run("referencia: tau 0.2, lote 512")
for tau in (0.05, 0.1, 0.5, 1.0):
run(f"temperatura tau = {tau}", tau=tau)
for bs in (64, 256, 1024):
run(f"lote de {bs} imágenes", bs=bs)
run("solo recorte y volteo", aug=dict(jitter=False))
run("solo contraste, gamma y brillo", aug=dict(crop=False, flip=False))
run("sin cabeza de proyección", proj=False)
run("sesgo corregido (tau+ = 0.1)", loss_fn=nt_xent_debiased)npm run lab and open the connection link.def uniform_floor(d, t=2.0):
"""Mínimo de L_uniform (uniformidad) sobre la esfera S^(d-1): la similitud s de dos puntos uniformes tiene densidad ~ (1 - s^2)^((d - 3) / 2)."""
s = np.linspace(-1, 1, 20001)[1:-1]
p = (1 - s**2) ** ((d - 3) / 2)
return float(np.log((p * np.exp(-t * (2 - 2 * s))).sum() / p.sum()))
print(f"Mínimo teórico de la uniformidad con t = 2: {uniform_floor(128):.3f} en la esfera de R^128 (salida z), {uniform_floor(512):.3f} en la de R^512 (salida h); "
f"en S^2 es {uniform_floor(3):.3f}")
@torch.no_grad()
def similarity_hists(enc, head, n=5000, bins=40):
"""Histogramas de la similitud coseno de un ancla con su positivo, con negativos de su misma clase y con negativos de otra clase."""
torch.manual_seed(0)
enc.eval(); head.eval()
x, y = Xte[:n], yte[:n]
n = len(x)
a, b = F.normalize(head(enc(augment(x))), dim=1), F.normalize(head(enc(augment(x))), dim=1)
S = a @ b.T # S[i, j]: ancla i frente a la vista del ejemplo j
eye = torch.eye(n, dtype=torch.bool, device=dev)
same = (y[:, None] == y[None, :]) & ~eye # negativos de la misma clase que el ancla
diff = y[:, None] != y[None, :] # negativos de otra clase
hist = lambda v: torch.histc(v, bins=bins, min=-1, max=1) / v.numel()
return {"pos": hist(S[eye]).cpu().numpy(), "same": hist(S[same]).cpu().numpy(), "diff": hist(S[diff]).cpu().numpy(),
"frac_same": same.sum().item() / (same.sum().item() + diff.sum().item())}
def repulsion_share(h, tau, N=512):
"""Parte del peso de los negativos (la fuerza de repulsión) que reciben los de la misma clase, con N - 1 negativos por ancla."""
s = np.linspace(-1, 1, len(h["same"]) + 1)
s = (s[:-1] + s[1:]) / 2 # centros de los intervalos
w = np.exp((s - 1) / tau)
same = h["frac_same"] * (N - 1) * (h["same"] * w).sum()
diff = (1 - h["frac_same"]) * (N - 1) * (h["diff"] * w).sum()
return same / (same + diff)
names_tau = ["temperatura tau = 0.05", "temperatura tau = 0.1", "referencia: tau 0.2, lote 512", "temperatura tau = 0.5", "temperatura tau = 1.0"]
hists = {name: similarity_hists(runs[name][0], runs[name][1]) for name in names_tau}
h = hists["referencia: tau 0.2, lote 512"]
s_mid = np.linspace(-1, 1, 41)
s_mid = (s_mid[:-1] + s_mid[1:]) / 2
mean = lambda p: float((p * s_mid).sum() / p.sum())
print(f"Fracción de negativos de la misma clase: {h['frac_same']:.3f}")
print(f"Similitud media (modelo de referencia): positivos {mean(h['pos']):.3f}, negativos de la misma clase {mean(h['same']):.3f}, de otra clase {mean(h['diff']):.3f}")
print("\nParte de la repulsión que recibe la misma clase (lote de 512), según la temperatura de la pérdida:")
print(f"{'modelo entrenado con':32s}" + "".join(f"{f'tau = {t}':>10s}" for t in (0.05, 0.1, 0.2, 0.5, 1.0)))
for name, hh in hists.items():
print(f"{name:32s}" + "".join(f"{repulsion_share(hh, t):10.3f}" for t in (0.05, 0.1, 0.2, 0.5, 1.0)))
# Exportación reproducible para contrastar una figura con estos histogramas.
import json
print("HISTOGRAMAS_JSON", json.dumps({name: {key: value.tolist() if isinstance(value, np.ndarray) else value
for key, value in hist.items()}
for name, hist in hists.items()}))npm run lab and open the connection link.Read the ablation table alongside the similarity distribution. Numbers are from your run and configuration differences do not isolate one factor when optimization step count also changes.
Supervised contrastive learning
When labels exist, instance discrimination wastes information: two distinct images of the same class are negatives for one another. Khosla et al. (2020) generalize NT-Xent with multiple positives per anchor.
With a different label per example, is only the other view and is NT-Xent: SupCon is a general case, checked by the lab cell. By Jensen’s inequality, , yet the second works much better: in their table 1 (ResNet-50, ImageNet, batch 6144), gives 78.7% top-1 accuracy and 67.4%. The authors conjecture that factor inside the logarithm only adds a constant to the gradient of , while weights each positive separately. With ResNet-200 they reach 81.4% top-1 accuracy, 0.8 points above the best published result for that architecture. They also observe that batches of 2048 suffice for nearly everything and, with a memory bank of 8192 keys and batch 256, ResNet-50 reaches 79.1%.
Lab: minimal MoCo and supervised contrastive learning
The first cell implements MoCo on the same encoder and compares it with SimCLR using the same small batch of 64 images (126 negatives), equal epochs, , and three momentum values (0, 0.99, 0.999). The second implements SupCon and compares, using the same labels and steps, end-to-end cross-entropy, SupCon followed by a linear probe, and an unlabeled SimCLR encoder with a linear probe, using 1000 and 6000 labels.
def train_moco(bs=64, K=4096, m=0.99, tau=0.2, epochs=EPOCHS_ABL, seed=0, lr=2e-3):
"""MoCo mínimo: consultas con gradiente, claves del codificador de momento (sin gradiente) y cola FIFO de K claves."""
enc_q, g_q = make_encoder(seed), make_head()
enc_k, g_k = make_encoder(seed), make_head()
enc_k.load_state_dict(enc_q.state_dict()); g_k.load_state_dict(g_q.state_dict()) # empiezan iguales
params_q = [*enc_q.parameters(), *g_q.parameters()]
params_k = [*enc_k.parameters(), *g_k.parameters()]
for p in params_k:
p.requires_grad_(False)
opt = torch.optim.AdamW(params_q, lr=lr, weight_decay=1e-5)
nb = len(Xtr) // bs
sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=lr, total_steps=epochs * nb, pct_start=0.1)
gen = torch.Generator(device=dev).manual_seed(seed)
zero = torch.zeros(bs, dtype=torch.long, device=dev) # el positivo es la columna 0
with torch.no_grad(): # cola inicial: claves de imágenes al azar
enc_k.train(); g_k.train()
queue = F.normalize(g_k(enc_k(augment(Xtr[torch.randint(len(Xtr), (K,), device=dev, generator=gen)]))), dim=1)
ptr = 0
for ep in range(epochs):
enc_q.train(); g_q.train(); enc_k.train(); g_k.train()
for idx in torch.randperm(len(Xtr), device=dev, generator=gen)[: nb * bs].split(bs):
x = Xtr[idx]
q = F.normalize(g_q(enc_q(augment(x))), dim=1)
with torch.no_grad():
for pk, pq in zip(params_k, params_q): # theta_k <- m theta_k + (1 - m) theta_q
pk.mul_(m).add_(pq.detach(), alpha=1 - m)
k = F.normalize(g_k(enc_k(augment(x))), dim=1)
logits = torch.cat([(q * k).sum(1, keepdim=True), q @ queue.T], dim=1) / tau # (bs, 1 + K)
loss = F.cross_entropy(logits, zero)
opt.zero_grad(set_to_none=True)
loss.backward()
opt.step(); sched.step()
queue[ptr:ptr + bs] = k # encolar las claves nuevas y sacar las más antiguas
ptr = (ptr + bs) % K
return enc_q, g_q, loss.item()
print(f"{'MoCo, ' + str(EPOCHS_ABL) + ' épocas, lote de 64':34s} {'sonda h':>8s} {'k-NN h':>8s} {'pérdida':>8s} {'alineam.':>8s} {'uniform.':>9s}")
ev = runs["lote de 64 imágenes"][2]
print(f"{'SimCLR, 126 negativos':34s} {ev['probe_h']:8.4f} {ev['knn_h']:8.4f} {runs['lote de 64 imágenes'][3]:8.3f} {ev['au_z'][0]:8.3f} {ev['au_z'][1]:9.3f}")
moco = {}
queue_size = 512 if SHORT_RUN else 4096
for m in (0.0, 0.99, 0.999):
t = time.time()
enc_m, head_m, last = train_moco(m=m, K=queue_size)
ev = evaluate(enc_m, head_m, full=False, wds=(1e-3, 1e-2, 1e-1))
moco[m] = (enc_m, head_m, ev)
print(f"{f'MoCo, K = {queue_size}, m = {m}':34s} {ev['probe_h']:8.4f} {ev['knn_h']:8.4f} {last:8.3f} {ev['au_z'][0]:8.3f} {ev['au_z'][1]:9.3f} {time.time() - t:6.0f} s")npm run lab and open the connection link.def supcon(z, y, tau=0.1):
"""Pérdida contrastiva supervisada L_out. z: (2N, d), filas i e i + N = dos vistas del ejemplo i; y: (2N,) etiquetas."""
z = F.normalize(z, dim=1)
n2 = len(z)
eye = torch.eye(n2, dtype=torch.bool, device=z.device)
S = (z @ z.T / tau).masked_fill(eye, float("-inf")) # A(i): todo salvo la propia vista
logp = S - torch.logsumexp(S, dim=1, keepdim=True) # log softmax por filas
pos = (y[:, None] == y[None, :]) & ~eye # P(i): las vistas con la misma etiqueta
return -(logp.masked_fill(~pos, 0.0).sum(1) / pos.sum(1)).mean()
# con una etiqueta distinta por ejemplo, SupCon coincide con NT-Xent
zt = torch.randn(12, 16, device=dev)
print(f"SupCon con etiquetas únicas {supcon(zt, torch.arange(12, device=dev) % 6).item():.6f} NT-Xent {nt_xent(zt, 0.1).item():.6f}")
def labeled_subset(n_per_class, seed=0):
g = torch.Generator().manual_seed(seed)
ytr_cpu = ytr.cpu()
return torch.cat([(ytr_cpu == c).nonzero().squeeze(1)[torch.randperm(int((ytr_cpu == c).sum()), generator=g)[:n_per_class]] for c in range(10)]).to(dev)
def train_labeled(idx, kind, steps=1500, bs=200, tau=0.1, lr=2e-3, seed=0):
"""Entrena con las etiquetas de idx: entropía cruzada de extremo a extremo o SupCon (y después sonda lineal sobre h)."""
enc = make_encoder(seed)
head = nn.Linear(512, 10).to(dev) if kind == "ce" else make_head()
opt = torch.optim.AdamW([*enc.parameters(), *head.parameters()], lr=lr, weight_decay=1e-5)
sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=lr, total_steps=steps, pct_start=0.1)
gen = torch.Generator(device=dev).manual_seed(seed)
enc.train(); head.train()
for _ in range(steps):
b = idx[torch.randint(len(idx), (bs,), device=dev, generator=gen)]
x, y = Xtr[b], ytr[b]
if kind == "ce":
loss = F.cross_entropy(head(enc(augment(x))), y)
else:
loss = supcon(head(enc(torch.cat([augment(x), augment(x)]))), torch.cat([y, y]), tau)
opt.zero_grad(set_to_none=True)
loss.backward()
opt.step(); sched.step()
return enc, head
print(f"\n{'método (mismas etiquetas, mismos pasos)':42s} {'1000 etiquetas':>15s} {'6000 etiquetas':>15s}")
rows = {"entropía cruzada de extremo a extremo": [], "SupCon + sonda lineal": [], "SimCLR sin etiquetas + sonda lineal": []}
Hte_simclr, Htr_simclr = features(enc_sc, Xte), features(enc_sc, Xtr)
for n_per in (100, 600):
idx = labeled_subset(n_per)
print(f'Objetivo {10 * n_per} etiquetas; disponibles en esta muestra: {len(idx)}')
enc_ce, head_ce = train_labeled(idx, "ce", steps=8 if SHORT_RUN else 1500)
enc_ce.eval(); head_ce.eval()
with torch.no_grad():
rows["entropía cruzada de extremo a extremo"].append((head_ce(features(enc_ce, Xte)).argmax(1) == yte).float().mean().item())
enc_sup, _ = train_labeled(idx, "supcon", steps=8 if SHORT_RUN else 1500)
rows["SupCon + sonda lineal"].append(linear_probe(features(enc_sup, Xtr[idx]), ytr[idx], features(enc_sup, Xte), yte))
rows["SimCLR sin etiquetas + sonda lineal"].append(linear_probe(Htr_simclr[idx], ytr[idx], Hte_simclr, yte))
for name, (a, b) in rows.items():
print(f"{name:42s} {a:15.4f} {b:15.4f}")npm run lab and open the connection link.Compare experiment rows with their respective budgets. SimCLR’s unlabeled pretraining uses additional unlabeled data, so sharing labels and supervised training steps does not imply equal total budget.
Details that matter
BatchNorm leaks information between examples
A batch normalization layer calculates batch mean and variance: each sample depends on the others. In a contrastive task this opens a shortcut. Chen et al. describe it for SimCLR: because both members of a positive pair are computed on the same device, the model can exploit local information leakage to improve the task without improving the representation; they fix this by aggregating BN mean and variance over all devices. He et al. observe it in MoCo: without a remedy the model appears to cheat on the pretext task and easily finds a low-loss solution; they attribute it to BN communication across samples and resolve it with shuffled BN (keys are computed under a different batch assignment than queries). The principle is general: an anchor’s positive and negatives should have seen the same normalization statistics. With one GPU and one BN over a batch’s views, statistics are shared with all batch negatives, as in our SimCLR lab; in MoCo, queued keys come from earlier batches with earlier statistics, where care is needed.
Epochs and compute budget
An accuracy number is not comparable without its budget. Factors changing between papers include epochs, batch size (and thus steps), learning rate and schedule, head, augmentations, encoder size, and evaluation protocol. The MoCo v2 table illustrates this: with 200 epochs SimCLR rises from 61.9% (batch 256) to 66.6% (batch 8192), and MoCo v2 at batch 256 gives 67.5%; with 800 epochs MoCo v2 gives 71.1%, and SimCLR with 1000 epochs and batch 4096 gives 69.3%. A fair comparison fixes the budget (epochs and steps and GPU passes) or shows the full curve, and uses the same probe for all methods.
The library version
Contrastive losses are in common libraries: Lightly implements them (with NTXentLoss and MoCo and SimCLR variants), as does PyTorch Metric Learning (with NTXentLoss and SupConLoss), while torchvision.transforms.v2 handles augmentations. The loss is the lab cell’s cross-entropy; augmentations are what most often break in practice. In torchvision.transforms.v2, a transform applied to a batched tensor sampled parameters once for the whole batch: batch views are then the same transformations of different images, with no independent per-example augmentations. The cell checks this with eight copies of the same image.
from torchvision.transforms import v2
batch = Xtr[:1].cpu().repeat(8, 1, 1, 1) # ocho copias de la misma imagen: 8 x 1 x 28 x 28
pipeline = v2.Compose([v2.RandomResizedCrop(28, scale=(0.25, 1.0), antialias=True), v2.RandomHorizontalFlip(),
v2.ColorJitter(brightness=0.4, contrast=0.5)])
distintas = lambda vistas: len({tuple(v.flatten().tolist()) for v in vistas})
torch.manual_seed(0)
print("un solo aumento sobre el tensor del lote: vistas distintas =", distintas(pipeline(batch)))
print("un aumento por imagen: vistas distintas =", distintas(torch.stack([pipeline(c) for c in batch])))npm run lab and open the connection link.With one augmentation for the whole tensor, the eight copies give one view; with one augmentation per image, eight. The solution is to apply the transform per image (slower, as in DataLoader with multiple processes), or augment on GPU with per-image parameters, as augment does in the lab.
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. Subtract and write . Why does it converge to ?
nt_xent(z, tau), which takes a matrix z of shape (2N, d) (rows i and i + N are two views of one example; they need not already be normalized) and returns mean NT-Xent loss with and the normalized rows. Exclude the denominator diagonal and use stable log-sum-exp (with logits reach 1000, and np.exp(1000) overflows).import numpy as np
def nt_xent(z, tau):
"""Pérdida NT-Xent media de un lote de 2N vistas (filas i e i + N = dos vistas del mismo ejemplo)."""
z = z / np.linalg.norm(z, axis=1, keepdims=True)
S = z @ z.T / tau
n2 = len(z)
pareja = (np.arange(n2) + n2 // 2) % n2
return np.mean(np.log(np.exp(S).sum(1)) - S[np.arange(n2), pareja])Summary
- Views. Positives are two augmentations of one example. In the model, stable and distinctive factors are easier to recover than heavily perturbed ones; a particular probe does not prove what information is retained generally. Composing crop and color distortion makes the histogram shortcut harder.
- NT-Xent. views, one positive and negatives per anchor, with the diagonal masked. Each vector’s gradient sums its roles as anchor and negative.
- Projection head. Loss applies to and is evaluated. SimCLR: +3% over a linear head and more than +10% over none, with better predicting the applied transformation.
- Temperature. Each negative’s weight is normalized : low concentrates gradients on hard negatives (which tend to be false negatives), high spreads them. An intermediate value depends on dimension and model.
- Alignment and uniformity. With , , bounded by the sum with Wang and Isola’s uniformity. Without negatives everything collapses: perfect alignment is the constant encoder.
- Negatives. SimCLR takes them from the batch; MoCo from a queue of keys from momentum encoder . Momentum provides consistency (less noise) in exchange for lag; MoCo with fails to converge and works with 0.999.
- False negatives. Fraction of the batch shares the anchor’s class and receives excess weight. Bias correction subtracts its contribution using a class prior.
- Good views and SupCon. InfoMin: share the minimum necessary. With labels, SupCon uses all same-class views as positives and contains NT-Xent as a special case.
- Rules of thumb. Evaluate , not ; normalize positives and negatives with the same statistics; compare with equal budgets.