Module contents
Lesson 22 of 24Core 110 min

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 log⁡N\log N, yet methods using it work with NN 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:

  1. Augmentations define what is “the same.” Changing augmentations changes what the representation retains, visible in a toy model.
  2. NT-Xent is InfoNCE on a matrix of 2N×2N2N \times 2N similarities, and a projection head can preserve information in the representation before it.
  3. Temperature distributes the gradient among negatives, concentrating it on the hardest.
  4. On the hypersphere, the loss asymptotically decomposes into alignment and uniformity (Wang and Isola), providing metrics without training a probe.
  5. Negatives can come from the batch (SimCLR, batch-proportional memory) or from a queue with a momentum encoder (MoCo).
  6. Hard negatives and false negatives are two sides of the same problem, and bias corrections exist.
  7. What makes good views (the InfoMin principle) and shortcuts exploited by contrastive tasks.
  8. With labels, supervised contrastive loss generalizes NT-Xent.
  9. 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 c∈[−1,1]2c \in [-1, 1]^2 and style factor s∈[−1,1]2s \in [-1, 1]^2. What is observed is x=Q [c; s]∈R4\vb{x} = \mat{Q}\,[c;\, s] \in \R^4 with Q\mat{Q} a fixed rotation, so no axis of x\vb{x} “is” content. An augmentation adds normal noise with standard deviation σc\sigma_c to content and σs\sigma_s 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.

InteractiveWhat the representation retains
Content plane cc: both views of each example
Style plane ss: both views of each example
How much of each factor the embedding retains (nearest-neighbor regression, held-out data)
0100020003000−0.4−0.200.20.40.60.81training steps
  • content cc
  • style ss
  • view 1 (filled) and view 2 (hollow)
0.10
1.00
Training steps0
Content retained (R2R^2)0.00
Style retained (R2R^2)0.00
Augmentations change style, so the representation retains content.
Each color is an example with its two views (filled and empty) in the content and style planes. Below is how much of each factor can be read from the embedding (R2R^2 of neighbor regression; below 0 is worse than predicting the mean). Initially, augmentations change style (σs=1\sigma_s = 1) and barely touch content (σc=0.1\sigma_c = 0.1). Press “Perturb content”: which line rises now? Press “Perturb both” and “No augmentations.” While training runs, move σs\sigma_s from 1 to 0: when does style begin to be retained?

After 3000 steps with the figure’s seed: if augmentations change style (σc=0.1\sigma_c = 0.1, σs=1\sigma_s = 1), the probe recovers content well (R2=0.99R^2 = 0.99) and style poorly (R2=−0.16R^2 = -0.16); reversed (σc=1\sigma_c = 1, σs=0.1\sigma_s = 0.1), it recovers style (0.99) and fails on content (−0.19-0.19). If both factors are perturbed equally (0.60.6, 0.60.6), 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 σc=σs=0.1\sigma_c = \sigma_s = 0.1 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 [−1,1][-1, 1] has variance 1/31/3 per coordinate between examples; augmentation adds noise with variance σ2\sigma^2. The signal-to-noise ratio 1/3σ2\frac{1/3}{\sigma^2} is 33 for σ=0.1\sigma = 0.1 and 0.33 for σ=1\sigma = 1: 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 NN examples and generate two views of each: 2N2N views. An encoder ff (here a convolutional network) maps them to representations h=f(⋅)\vb{h} = f(\cdot), and a projection head gg maps them to z=g(h)\vb{z} = g(\vb{h}), normalized to length 1. For each view ii, its partner is p(i)p(i) (with numbering 1,…,2N1, \dots, 2N where ii and i+Ni + N are views of the same example, p(i)=i±Np(i) = i \pm N). With sik=⟨zi,zk⟩s_{ik} = \inner{\vb{z}_i}{\vb{z}_k}:

This is the previous lesson’s InfoNCE loss with a matrix of 2N×2N2N \times 2N 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 P\mat{P} the row-wise softmax of S=ZZ⊤/τ\mat{S} = \mat{Z}\mat{Z}\T/\tau with the diagonal masked, and M=2NM = 2N,

∂L∂za=1Mτ[∑k(Pak+Pka)zk−2zp(a)].\pd{\mathcal{L}}{\vb{z}_a} = \frac{1}{M\tau}\Big[\sum_{k}\big(P_{ak} + P_{ka}\big)\vb{z}_k - 2\vb{z}_{p(a)}\Big].

Each vector receives force in two ways, as an anchor (weights PakP_{ak}) and as a negative for other anchors (weights PkaP_{ka}), and is attracted to its partner with constant strength 2. Before differentiating through normalization z=u/∥u∥\vb{z} = \vb{u}/\norm{\vb{u}}, project the gradient onto the sphere’s tangent plane, (I−zz⊤)/∥u∥(\mat{I} - \vb{z}\vb{z}\T)/\norm{\vb{u}}: the radial component is lost on normalization.

The projection head

The loss is applied to z\vb{z}, but what is used afterward is h\vb{h}.

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 z\vb{z} can discard information useful for another task, such as color or orientation, while h\vb{h} 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 h\vb{h} and 25.6% from z\vb{z}. 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 h\vb{h} 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 kk-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.

[ ]Augmentations, encoder, projection head, and NT-Xent from scratchLocal GPU
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, hist
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Miniature SimCLR: linear probe before and after the headLocal GPU
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}")
This cell needs the local lab (PyTorch with your GPU). Start it with 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 kk of anchor aa receives force proportional to its softmax weight,

wak=esak/τ∑j≠aesaj/τ.w_{ak} = \frac{e^{s_{ak}/\tau}}{\sum_{j \neq a} e^{s_{aj}/\tau}}.

Wang and Liu (2021) call this relative penalty and observe that, for an anchor, negative weights form a Boltzmann distribution with temperature τ\tau. Two limits:

  • With τ→0\tau \to 0, weight concentrates on candidates most similar to the anchor, shared among ties. The loss multiplied by τ\tau tends to max⁡(0,max⁡ksak−sa,p(a))\max(0,\max_k s_{ak} - s_{a,p(a)}), 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 τ→∞\tau \to \infty, full-softmax weights tend to 1/(2N−1)1/(2N - 1), including the positive. When normalized only among negatives, each receives 1/(2N−2)1/(2N - 2) 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 es/τe^{s/\tau}. In uniform-sphere mode, similarity has density ∝(1−s2)(d−3)/2\propto (1 - s^2)^{(d-3)/2}: 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.

InteractiveTemperature distributes the gradient
Where the 1022 negatives are: % of negatives per unit of similarity
050100150200positive
Where repulsion acts: % of weight mass wjw_j per unit of similarity
−1−0.500.510100200positive
cosine similarity to the anchor
  • negatives
  • positive similarity
Negative similarities
0.200
0.80
32
Positive weight w+w_+0.035
Moment-equivalent count (approx.) out of 1022494.8
Mass on the 10 hardest negatives6.7 %
Weighted mean similarity0.153
Above, a similarity distribution of 1022 expected negatives; below, their weight mass. Lower τ\tau to 0.05 and observe the distribution. In measured mode, compare the aggregated mass of same-class negatives with their numerical fraction; your chosen positive remains hypothetical.

In the sphere model with d=32d = 32, a positive at s+=0.8s_+ = 0.8, and 1022 expected negatives: with τ=0.2\tau = 0.2 the moment equivalent is 494.8 of 1022 and 6.7% of weight falls on the 10 expected hardest negatives; with τ=0.05\tau = 0.05 they are 1.5 and 75.3%; with τ=1\tau = 1 they are 990.7 and 1.5%. The figure calculates the continuous distribution’s moment ratio, an approximation to effective number (∑jwj)2/∑jwj2(\sum_j w_j)^2/\sum_j w_j^2 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 d=128d = 128 similarities of two uniform vectors concentrate around 0 (standard deviation ≈1/d\approx 1/\sqrt{d}), and for the same τ\tau weights spread more: with τ=0.1\tau = 0.1 the equivalent is 475.4, versus 89.0 with d=32d = 32. 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 τ\tau gives more uniform embeddings but less tolerance for semantically similar examples; high τ\tau 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 τ=0.07\tau = 0.07, 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 τ=0.1\tau = 0.1 with ℓ2\ell_2 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 τ=10\tau = 10 and 100100) 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 (Lalign=0\mathcal{L}_{\mathrm{align}} = 0) with any encoder giving both views the same output, for example a constant encoder, which has the worst possible uniformity (Luniform=0\mathcal{L}_{\mathrm{uniform}} = 0). 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 S2S^2, where the similarity ss of two uniform points is uniform in [−1,1][-1, 1] (Archimedes) and ∥f(x)−f(y)∥2=2−2s\norm{f(x) - f(y)}^2 = 2 - 2s, this gives E e−t(2−2s)=1−e−4t4t\E\, e^{-t(2 - 2s)} = \frac{1 - e^{-4t}}{4t}. With t=2t = 2, the minimum is log⁡1−e−88=−2.080\log\frac{1 - e^{-8}}{8} = -2.080. For other dimensions similarity has density ∝(1−s2)(d−3)/2\propto (1 - s^2)^{(d-3)/2} and the minimum follows from a one-dimensional integral.

The connection with contrastive loss is asymptotic in the number of negatives.

Proof

Subtract log⁡M\log M inside the expectation: LM−log⁡M=E[−s+/τ+log⁡1M(es+/τ+∑iesi−/τ)]\mathcal{L}_M - \log M = \E\big[-s^+/\tau + \log\frac1M\big(e^{s^+/\tau} + \sum_i e^{s_i^-/\tau}\big)\big], with s+=f(x)⊤f(y)s^+ = f(x)\T f(y) and si−=f(xi−)⊤f(x)s_i^- = f(x_i^-)\T f(x). Exponents lie in [−1/τ,1/τ][-1/\tau, 1/\tau], so the logarithm’s argument, 1M∑iesi−/τ+1Mes+/τ\frac1M\sum_i e^{s_i^-/\tau} + \frac1M e^{s^+/\tau}, lies between e−1/τe^{-1/\tau} and 2e1/τ2e^{1/\tau}: bounded and away from 0. Conditioned on the anchor, 1M∑iesi−/τ\frac1M\sum_i e^{s_i^-/\tau} averages independent bounded variables; by the strong law of large numbers it converges to Ex−ef(x−)⊤f(x)/τ\E_{x^-}e^{f(x^-)\T f(x)/\tau}. The function log⁡\log is continuous and quantities are bounded away from 0, so dominated convergence moves the limit inside the expectation, yielding L∞\mathcal{L}_\infty.

For unit vectors, ∥f(x)−f(y)∥2=2−2f(x)⊤f(y)\norm{f(x) - f(y)}^2 = 2 - 2f(x)\T f(y). Then −1τE[f(x)⊤f(y)]=12τE∥f(x)−f(y)∥2−1τ-\frac1\tau\E[f(x)\T f(y)] = \frac{1}{2\tau}\E\norm{f(x) - f(y)}^2 - \frac1\tau, and ef(x)⊤f(x−)/τ=e1/τe−t∥f(x)−f(x−)∥2e^{f(x)\T f(x^-)/\tau} = e^{1/\tau}e^{-t\norm{f(x) - f(x^-)}^2} with t=12τt = \frac{1}{2\tau}, so the second term is 1τ+Exlog⁡Ex−e−t∥f(x)−f(x−)∥2\frac1\tau + \E_x\log\E_{x^-}e^{-t\norm{f(x) - f(x^-)}^2}. The two constants ∓1τ\mp\frac1\tau cancel, giving equality.

Finally, log⁡\log is concave, and Jensen’s inequality gives Exlog⁡Y(x)≤log⁡ExY(x)\E_x\log Y(x) \le \log\E_x Y(x) with Y(x)=Ex−e−t∥f(x)−f(x−)∥2Y(x) = \E_{x^-}e^{-t\norm{f(x) - f(x^-)}^2}; the right-hand side is Luniform(f;t)\mathcal{L}_{\mathrm{uniform}}(f; t). Since log⁡\log is strictly concave, equality holds if and only if Y(x)Y(x) 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 Exlog⁡Ex−\E_x\log\E_{x^-} (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 (f(x)=f(y)f(x) = f(y) almost surely), and, if perfectly uniform encoders exist, these minimize the second. Uniformity Luniform\mathcal{L}_{\mathrm{uniform}} 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 O(M−1/2)\bigO(M^{-1/2}).

The next cell checks the theorem with an explicit encoder on the circle (d=2d = 2), where all limiting expectations are calculated by quadrature. Data have von Mises angles (concentration κ\kappa; κ=0\kappa = 0 is uniform), and positives are the anchor plus normal noise with standard deviation 0.3 radians.

[ ]Check the Wang and Isola theorem on the circleBrowser
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 κ=0\kappa = 0 (uniform data on the circle), the limit L∞\mathcal{L}_\infty and bound 12τLalign+Luniform\frac{1}{2\tau}\mathcal{L}_{\mathrm{align}} + \mathcal{L}_{\mathrm{uniform}} coincide (−1.0880), and loss with MM negatives, minus log⁡M\log M, approaches that value as MM grows (from −0.228-0.228 with M=2M = 2 to −1.087-1.087 with M=512M = 512). With κ=1\kappa = 1 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 S2S^2. Each augmentation adds normal noise with standard deviation σ\sigma and the views are positive pairs. The loss is NT-Xent with parameter β\beta weighting the negative term: ℓa=−sa,p(a)/τ+βlog⁡∑k∉{a,p(a)}esak/τ\ell_a = -s_{a,p(a)}/\tau + \beta\log\sum_{k \notin \{a, p(a)\}}e^{s_{ak}/\tau}. With β=0\beta = 0 there is only alignment; with β=1\beta = 1 it is NT-Xent without the positive in the denominator. Measure alignment and uniformity with t=2t = 2 over the 120 points.

InteractiveTraining on the sphere
  • group 1
  • group 2
  • group 3
  • group 4
  • group 5
  • group 6
  • segment from z(x)z(x) to zz of an augmented view
Training trajectory with uniformity on the horizontal axis and alignment on the vertical. The lower left is the target. The lower right is collapse.
−2−1.5−1−0.5000.10.20.3uniformcollapseuniformity (lower is better)
0.300
1.00
0.25
Training steps0
Alignment E∥z−z′∥2\mathbb{E}\|z - z'\|^20.180
Uniformity (population reference −2.080-2.080)−1.596
Mean norm ∥zˉ∥\|\bar z\| (1 = collapse)0.029
Group recovered by 5 nearest neighbors75.8 %
The 120 embeddings on the unit sphere, colored by group; each segment connects a point embedding to an augmented-view embedding. Below is the training trajectory in the (uniformity, alignment) plane. Set negative weight β\beta to 0: what happens to mean norm ∥zˉ∥\|\bar z\| and 5-neighbor accuracy? Return it to 1, lower τ\tau to 0.05 and raise it to 1: how does achieved uniformity change? Increase σ\sigma to 0.5: what happens to alignment?

With the figure’s seed and 3000 steps, initial values (τ=0.3\tau = 0.3, β=1\beta = 1, σ=0.25\sigma = 0.25) give alignment 0.124, uniformity −1.991-1.991, and 85% 5-neighbor accuracy recovering the group. The population minimum in S2S^2 is −2.080-2.080; an estimate with distinct pairs from a finite sample does not have exactly the same bound because it excludes diagonal pairs. With β=0\beta = 0, all points collapse: alignment 0.000, uniformity −0.000-0.000, 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 τ=0.05\tau = 0.05 uniformity stays at −1.700-1.700 and with τ=1\tau = 1 at −1.873-1.873, versus −1.991-1.991 with τ=0.3\tau = 0.3: in this model there is an intermediate temperature, and with σ=0.5\sigma = 0.5 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 Lalign\mathcal{L}_{\mathrm{align}} and Luniform\mathcal{L}_{\mathrm{uniform}} 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: 2(N−1)2(N - 1). 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: K=65536K = 65536 keys of 128 numbers in float32 occupy 32 MiB and are not backpropagated. The oldest queue keys are K/BK/B steps old (256 steps for K=65536K = 65536 and B=256B = 256). From one step to the next, θk\theta_k advances fraction 1−m1-m of its distance to θq\theta_q. Averaging scale 1/(1−m)1/(1-m) approximates, when mm is close to 1, the exact exponential decay constant −1/log⁡m-1/\log m. With m=0.999m = 0.999 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 θq\theta_q changes also matters. If minibatch noise in θq\theta_q is independent at each step, with standard deviation ν\nu, stationary noise in θk\theta_k has variance ν2∑j(1−m)2m2j=ν2(1−m)/(1+m)\nu^2\sum_j(1-m)^2m^{2j}=\nu^2(1-m)/(1+m). With m=0.999m = 0.999 the standard deviation is divided by 1.999/0.001≈44.7\sqrt{1.999/0.001}\approx44.7. The price is lag: for a sustained linear trend, the moving-average weights’ mean age is m/(1−m)m/(1-m) 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 θq(t)=θ0+v t u+ν ξt\theta_q(t) = \theta_0 + v\,t\,\vb{u} + \nu\,\xi_t, with systematic trend speed vv along fixed direction u\vb{u} and minibatch noise ν ξt\nu\,\xi_t 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 aa steps ago and what fkf_k would produce today for the same point) and trend fidelity (mean cosine between the key produced by fkf_k and what the noiseless trend encoder θ0+v t u\theta_0 + v\,t\,\vb{u} 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.

InteractiveQueue and momentum in MoCo
One encoder parameter (coordinate along the trend) at m=0.00m = 0.00: queries θq\theta_q and keys θk\theta_k
160018002000220024001.522.53queue window (256 steps)training step
Queue consistency: cosine between the key stored aa steps ago and the one the key encoder produces now
0501001502002500.20.40.60.81trend fidelitykey age a (steps)
  • query θq\theta_q
  • key θk\theta_k (momentum)
  • queue consistency
0.00
65.5 k
0.15
1.0
Approximate timescale 1/(1−m)1/(1-m)1 steps
Age of the oldest key K/BK/B256 steps
Queue consistency (mean cosine)0.591
Key trend fidelity (mean cosine)0.767
Above, an encoder parameter (its coordinate along the trend): queries in blue and keys in red; the orange band is the queue age window. Below, saved-key consistency by age. With K=65536K = 65536, batch B=256B = 256, noise ν=0.15\nu = 0.15, and speed v=1v = 1: start at m=0m = 0 and increase to 0.999. How do queue consistency and trend fidelity change? Raise it to 0.9999: what breaks? Reduce noise to 0: what role does momentum play then?

With initial values (K=65536K = 65536, B=256B = 256, ν=0.15\nu = 0.15, v=1v = 1, 2500-step trajectory), the readings are:

mm00.90.990.9990.9999
queue consistency0.5910.9440.9970.9991.000
trend fidelity0.7670.9700.9980.9660.800

With m=0m = 0, queue keys were encoded with parameters differing due to noise at each step: the oldest key matches what fkf_k would produce today with cosine only 0.2, and such negatives do not define a consistent dictionary. Raising mm 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 m=0.99m = 0.99, and the cost of lag depends on speed: with v=0.3v = 0.3 fidelity with m=0.999m = 0.999 is 0.994, and with v=3v = 3 is 0.936. With ν=0\nu = 0 keys are equally consistent for any mm (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 K=4096K = 4096 and ResNet-50 measures the real result of that tradeoff: with m=0m = 0 training fails (“loss oscillates and does not converge”), and with m=0.9,0.99,0.999,0.9999m = 0.9, 0.99, 0.999, 0.9999 linear accuracy is 55.2, 57.8, 59.0, and 58.9% (He et al., ablation table). The paper’s defaults are K=65536K = 65536, m=0.999m = 0.999, τ=0.07\tau = 0.07, and batch 256 on 8 GPUs. Against a memory bank with the same loss and K=65536K = 65536 (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 CC balanced classes, fraction 1/C1/C of those negatives shares the anchor’s class. That fraction does not decrease as batch size grows: with C=10C = 10 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 R32\R^{32}, and measures two things: the share of repulsion received by false negatives, and the bias they introduce in the negative term.

[ ]False negatives and bias-corrected estimatorBrowser
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 τ=0.5\tau = 0.5, 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 τ+\tau^+ is the probability that two examples share a class, the marginal distribution decomposes into p(x′)=τ+px+(x′)+τ−px−(x′)p(x') = \tau^+p_x^+(x') + \tau^-p_x^-(x'), with τ−=1−τ+\tau^- = 1 - \tau^+, px+p_x^+ the distribution of examples in the class of xx and px−p_x^- that of the others. Rearranging,

Ex−∼px−[ef(x)⊤f(x−)/t]=1τ−(Ex′∼p[ef(x)⊤f(x′)/t]−τ+Ev∼px+[ef(x)⊤f(v)/t]).\E_{x^- \sim p_x^-}\big[e^{f(x)\T f(x^-)/t}\big] = \frac{1}{\tau^-}\Big(\E_{x' \sim p}\big[e^{f(x)\T f(x')/t}\big] - \tau^+\E_{v \sim p_x^+}\big[e^{f(x)\T f(v)/t}\big]\Big).

The naive batch average estimates the first term in parentheses, and overestimates the true-negative term by τ+(Ep+−Ep−)\tau^+\big(\E_{p^+} - \E_{p^-}\big), which is positive if same-class examples resemble the anchor more. Their estimator, with NN negatives ui∼pu_i \sim p and MM positives vi∼px+v_i \sim p_x^+, is

g(x,{ui},{vi})=max⁡{1τ−(1N∑i=1Nef(x)⊤f(ui)/t−τ+1M∑i=1Mef(x)⊤f(vi)/t),  e−1/t},g(x, \{u_i\}, \{v_i\}) = \max\Big\{\frac{1}{\tau^-}\Big(\frac1N\sum_{i=1}^{N}e^{f(x)\T f(u_i)/t} - \tau^+\frac1M\sum_{i=1}^{M}e^{f(x)\T f(v_i)/t}\Big),\; e^{-1/t}\Big\},

where e−1/te^{-1/t} is the term’s theoretical minimum (the dot product of unit vectors is at least −1-1, with t>0t>0 the temperature), and loss is −log⁡ef(x)⊤f(x+)/tef(x)⊤f(x+)/t+Ng-\log\frac{e^{f(x)\T f(x^+)/t}}{e^{f(x)\T f(x^+)/t} + N g}. In practice τ+\tau^+ is a hyperparameter (their paper uses τ+=0.01\tau^+ = 0.01 on ImageNet-100) and the positive sample consists of the anchor’s own views (M=1M = 1). 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 τ+=0.01\tau^+ = 0.01). Robinson et al. (2021) go a step further: instead of removing false negatives, they weight negatives by difficulty, with proposal qβ(x−)∝eβf(x)⊤f(x−)p(x−)q_\beta(x^-) \propto e^{\beta f(x)\T f(x^-)}p(x^-) giving more weight to those close to the anchor, and with β=0\beta = 0 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 I(v1;v2)I(v_1; v_2) while maintaining I(v1;y)=I(v2;y)=I(x;y)I(v_1; y) = I(v_2; y) = I(x; y). 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 σs\sigma_s 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 τ+=0.1\tau^+ = 0.1 (the true Fashion-MNIST prior, with 10 balanced classes). All are evaluated by linear probe and kk-NN on h\vb{h} and by alignment and uniformity. Two design cautions: training losses are not comparable (they depend on τ\tau 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.

[ ]Ablations: temperature, batch, augmentations, head, and biasLocal GPU
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)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Negative similarities and false-negative repulsionLocal GPU
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()}))
This cell needs the local lab (PyTorch with your GPU). Start it with 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, P(i)P(i) is only the other view and Loutsup\mathcal{L}^{\mathrm{sup}}_{\mathrm{out}} is NT-Xent: SupCon is a general case, checked by the lab cell. By Jensen’s inequality, Lin≤Lout\mathcal{L}_{\mathrm{in}} \le \mathcal{L}_{\mathrm{out}}, yet the second works much better: in their table 1 (ResNet-50, ImageNet, batch 6144), Lout\mathcal{L}_{\mathrm{out}} gives 78.7% top-1 accuracy and Lin\mathcal{L}_{\mathrm{in}} 67.4%. The authors conjecture that factor 1/∣P(i)∣1/\abs{P(i)} inside the logarithm only adds a constant to the gradient of Lin\mathcal{L}_{\mathrm{in}}, while Lout\mathcal{L}_{\mathrm{out}} 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, K=4096K = 4096, 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.

[ ]Minimal MoCo versus SimCLR with small batchesLocal GPU
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")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]SupCon versus cross-entropy with few labelsLocal GPU
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}")
This cell needs the local lab (PyTorch with your GPU). Start it with 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 2N2N 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.

[ ]One augmentation per tensor or per imageLocal GPU
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])))
This cell needs the local lab (PyTorch with your GPU). Start it with 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

NumericNegatives per anchor in SimCLR
In SimCLR with a batch of N=512N = 512 images (and therefore 2N2N views), how many negatives does each anchor have?
NumericTemperature and a negative’s weight
With τ=0.1\tau = 0.1, an anchor has two negatives, one with cosine similarity 0.60.6 and another with 0.40.4. How many times more gradient does the first receive than the second? (Forces are wj/τw_j/\tau, and wjw_j is the softmax weight.)
NumericQueue age versus averaging scale
MoCo with a queue of K=65536K = 65536 keys, batches of B=256B = 256 and momentum m=0.999m = 0.999. What fraction of the approximate scale 1/(1−m)1/(1 - m) is the age of the oldest queue key?
NumericMinimum uniformity on $S^2$
For the sphere S2⊂R3S^2 \subset \R^3, what is the minimum value of Luniform(f;t)\mathcal{L}_{\mathrm{uniform}}(f; t) with t=1t = 1? (Two independent uniform points on S2S^2 have cosine similarity ss uniform in [−1,1][-1, 1], and ∥f(x)−f(y)∥2=2−2s\norm{f(x) - f(y)}^2 = 2 - 2s.)
QuizWhy evaluation uses the layer before the head
SimCLR discards projection head gg after pretraining and evaluates the preceding representation h\vb{h} with a linear probe. Why does it often work better than z=g(h)\vb{z} = g(\vb{h}) on downstream tasks?
QuizFalse negatives with large batches
You train NT-Xent on 10 balanced classes with batches of 4096 images. Which statement about false negatives is correct?
QuizLowering temperature
In NT-Xent with N=512N = 512 (1022 negatives per anchor), you lower τ\tau from 0.5 to 0.05 with everything else unchanged. What do you expect of gradient distribution across negatives and false negatives?
QuizBatchNorm and the contrastive task
Which statements about BatchNorm in contrastive pretraining are correct? (There may be several.)

More than one answer may be correct.

QuizSupCon with unique labels
You apply supervised contrastive loss Loutsup\mathcal{L}^{\mathrm{sup}}_{\mathrm{out}} to a batch of NN examples with two views each, but all different labels (each example is its own class). What do you obtain?
QuizWhat can you conclude from this table?
In the MoCo v2 table, MoCo v2 with 800 epochs and batch 256 reaches 71.1% top-1 accuracy, and SimCLR with 200 epochs and batch 8192 reaches 66.6%. A reader concludes MoCo v2 is 4.5 points better. Which response is correct?
ProofFrom loss to alignment and uniformity
Prove: With unit-output ff, τ>0\tau > 0 and LM\mathcal{L}_M the contrastive loss with MM negatives (positive in denominator): lim⁡M→∞(LM−log⁡M)=12τLalign(f;2)+Exlog⁡Ex−e−t∥f(x)−f(x−)∥2\lim_{M \to \infty}(\mathcal{L}_M - \log M) = \frac{1}{2\tau}\mathcal{L}_{\mathrm{align}}(f; 2) + \E_x\log\E_{x^-}e^{-t\norm{f(x) - f(x^-)}^2} with t=12τt = \frac{1}{2\tau}, and this is at most 12τLalign(f;2)+Luniform(f;t)\frac{1}{2\tau}\mathcal{L}_{\mathrm{align}}(f; 2) + \mathcal{L}_{\mathrm{uniform}}(f; t).
0
Let s+=f(x)⊤f(y)s^+ = f(x)\T f(y) with (x,y)∼ppos(x, y) \sim p_{\mathrm{pos}} and si−=f(xi−)⊤f(x)s_i^- = f(x_i^-)\T f(x) with xi−∼iidpdatax_i^- \iid p_{\mathrm{data}} independent of the pair. Then LM=E[−s+/τ+log⁡(es+/τ+∑i=1Mesi−/τ)]\mathcal{L}_M = \E\big[-s^+/\tau + \log\big(e^{s^+/\tau} + \sum_{i=1}^{M}e^{s_i^-/\tau}\big)\big].

Step 1 of 4. Subtract log⁡M\log M and write LM−log⁡M=E[−s+/τ+log⁡(1M∑i=1Mesi−/τ+1Mes+/τ)]\mathcal{L}_M - \log M = \E\big[-s^+/\tau + \log\big(\frac1M\sum_{i=1}^{M}e^{s_i^-/\tau} + \frac1Me^{s^+/\tau}\big)\big]. Why does it converge to −1τE[s+]+Exlog⁡Ex−ef(x−)⊤f(x)/τ-\frac1\tau\E[s^+] + \E_x\log\E_{x^-}e^{f(x^-)\T f(x)/\tau}?

CodeStable NT-Xent with masked diagonal
Implement 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 L=12N∑i[log⁡∑k≠ieSik−Si,p(i)]\mathcal{L} = \frac{1}{2N}\sum_i\big[\log\sum_{k \neq i}e^{S_{ik}} - S_{i,p(i)}\big] with S=z^z^T/τS = \hat z\hat z^{\mathsf{T}}/\tau and z^\hat z the normalized rows. Exclude the denominator diagonal and use stable log-sum-exp (with τ=0.001\tau = 0.001 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])
Shift+Enter to run

Summary

Key idea
Contrastive representation learning is InfoNCE with views as positives and the rest of the batch or a queue as negatives. Augmentations induce invariances, the projection head can preserve information in h\vb{h}, and temperature distributes gradients among negatives. In the many-negative limit, loss combines alignment with conditional energy bounded above by uniformity.
  • 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. 2N2N views, one positive and 2(N−1)2(N-1) negatives per anchor, with the diagonal masked. Each vector’s gradient sums its roles as anchor and negative.
  • Projection head. Loss applies to z=g(h)\vb{z} = g(\vb{h}) and h\vb{h} is evaluated. SimCLR: +3% over a linear head and more than +10% over none, with h\vb{h} better predicting the applied transformation.
  • Temperature. Each negative’s weight is normalized es/τe^{s/\tau}: low τ\tau concentrates gradients on hard negatives (which tend to be false negatives), high τ\tau spreads them. An intermediate value depends on dimension and model.
  • Alignment and uniformity. With M→∞M \to \infty, LM−log⁡M→12τLalign+Exlog⁡Ex−e−t∥⋅∥2\mathcal{L}_M - \log M \to \frac{1}{2\tau}\mathcal{L}_{\mathrm{align}} + \E_x\log\E_{x^-}e^{-t\norm{\cdot}^2}, 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 θk←mθk+(1−m)θq\theta_k \leftarrow m\theta_k + (1 - m)\theta_q. Momentum provides consistency (less noise) in exchange for lag; MoCo with m=0m = 0 fails to converge and works with 0.999.
  • False negatives. Fraction 1/C1/C 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 h\vb{h}, not z\vb{z}; normalize positives and negatives with the same statistics; compare with equal budgets.