TExcelTAD

Contrastive Learning: SimCLR and the NT-Xent Loss

Masked modelling needs something to predict: a hidden word, a hidden patch. Contrastive learning uses a different pretext task: take two random distortions of the same input and train the network to recognise that they belong together, out of a batch full of distortions of other inputs. Nothing is reconstructed. The network only has to produce an embedding in which "two views of the same thing" are close and "views of different things" are far apart. SimCLR (Chen et al., 2020) made this recipe simple and strong for images, and the same loss trains CLIP's image-text embeddings and most modern retrieval models.

Contrastive and triplet losses introduced the loss family with labelled pairs. Here the pairs come from augmentation, so no labels are needed.

The SimCLR recipe

x tt' x_i x_j encoder f encoder f shared weights h_i h_j head g head g z_i z_j pulltogether keep h discard g every other view in the batch is a negative: pushed away from z_i
  1. Sample a batch of NN unlabelled inputs.
  2. Apply two random augmentations t,t′t, t' to each, giving 2N2N views. Views ii and jj from the same input are a positive pair; the other 2N−22N - 2 views are negatives for both.
  3. Pass every view through the encoder ff (a ResNet in the paper) to get h=f(x~)\mathbf{h} = f(\tilde{\mathbf{x}}), then through a small projection head gg (an MLP) to get z=g(h)\mathbf{z} = g(\mathbf{h}).
  4. Compute the NT-Xent loss on the z\mathbf{z} and update ff and gg.
  5. After pretraining, throw gg away and use h\mathbf{h} as the feature, with a linear probe or fine-tuning.

The augmentations decide what the model learns to ignore. For photos, SimCLR found random crops plus colour distortion essential: crops alone let the network match views by their colour histogram, a shortcut. Whatever the augmentation changes, the embedding becomes invariant to; so never augment away something the downstream task needs (a colour jitter is wrong if the task is ripeness of fruit).

The NT-Xent loss

NT-Xent is the normalised temperature-scaled cross-entropy. With cosine similarity sim⁡(u,v)=u⊤v/(∥u∥∥v∥)\operatorname{sim}(\mathbf{u}, \mathbf{v}) = \mathbf{u}^\top \mathbf{v} / (\lVert \mathbf{u} \rVert \lVert \mathbf{v} \rVert) and temperature τ>0\tau > 0, the loss for anchor ii with positive jj is

ℓi,j=−log⁡exp⁡(sim⁡(zi,zj)/τ)∑k=12N1[k≠i]exp⁡(sim⁡(zi,zk)/τ)\ell_{i,j} = -\log \frac{\exp\big(\operatorname{sim}(\mathbf{z}_i, \mathbf{z}_j) / \tau\big)}{\sum_{k=1}^{2N} \mathbb{1}_{[k \ne i]} \exp\big(\operatorname{sim}(\mathbf{z}_i, \mathbf{z}_k) / \tau\big)}

and the batch loss averages it over all 2N2N anchors, each view once as anchor: L=12N∑k=1N(ℓ2k−1,2k+ℓ2k,2k−1)L = \frac{1}{2N} \sum_{k=1}^{N} (\ell_{2k-1,2k} + \ell_{2k,2k-1}). Read as classification, each anchor must pick out its partner among 2N−12N - 1 candidates with a softmax over similarities: it is cross-entropy with the positive as the correct class (softmax and cross-entropy). This form is also called InfoNCE.

Three facts follow from the formula and are worth checking in code:

  • If all embeddings are equal, every similarity is 1 and the softmax is uniform: L=log⁡(2N−1)L = \log(2N - 1). That is the loss of a model that has learned nothing.
  • The temperature sets how sharp the softmax is. A small τ\tau magnifies differences in similarity, so the loss concentrates on the hardest negatives (those most similar to the anchor); a large τ\tau treats all negatives alike. SimCLR used τ\tau between 0.1 and 0.5.
  • More negatives make the task harder and the signal richer, which is why SimCLR needed batches of 4,096 and MoCo keeps a queue of past embeddings instead.

From scratch: NT-Xent in NumPy, checked three ways

The first function is the formula written literally, with loops. The second is vectorised and also returns the gradient with respect to the raw (unnormalised) embeddings. With S=ZZ⊤/τS = Z Z^\top / \tau for the normalised rows ZZ and PP the row-wise softmax over k≠ik \ne i, the gradient of the loss is G=(P−Y)/(2N)G = (P - Y)/(2N) with respect to SS, where YY marks the positives, so (G+G⊤)Z/τ(G + G^\top) Z / \tau with respect to ZZ; the last line carries it back through the normalisation z=u/∥u∥\mathbf{z} = \mathbf{u} / \lVert \mathbf{u} \rVert. A finite-difference check confirms the gradient.

python · try it yourself
import numpy as np

def nt_xent_loop(Z, tau):
    """Literal definition: 2N rows, row i and row (i + N) mod 2N are a positive pair."""
    n2 = len(Z); N = n2 // 2
    Z = Z / np.linalg.norm(Z, axis=1, keepdims=True)
    total = 0.0
    for i in range(n2):
        j = (i + N) % n2
        num = np.exp(Z[i] @ Z[j] / tau)
        den = sum(np.exp(Z[i] @ Z[k] / tau) for k in range(n2) if k != i)
        total += -np.log(num / den)
    return total / n2

def nt_xent(U, tau):
    """Vectorised loss and its gradient with respect to the raw embeddings U."""
    n2 = len(U); N = n2 // 2
    norms = np.linalg.norm(U, axis=1, keepdims=True)
    Z = U / norms
    S = Z @ Z.T / tau
    np.fill_diagonal(S, -np.inf)                            # k != i
    pos = (np.arange(n2) + N) % n2
    P = np.exp(S - S.max(1, keepdims=True)); P /= P.sum(1, keepdims=True)   # softmax over 2N - 1
    loss = -np.log(P[np.arange(n2), pos]).mean()
    G = P.copy(); G[np.arange(n2), pos] -= 1; G /= n2        # dL/dS
    gZ = (G + G.T) @ Z / tau                                 # dL/dZ, since S = Z Z^T / tau
    gU = (gZ - Z * (Z * gZ).sum(1, keepdims=True)) / norms   # back through the normalisation
    return loss, gU

rng = np.random.default_rng(0)
N, dim, tau = 4, 8, 0.5
U = rng.normal(size=(2 * N, dim))
loss, grad = nt_xent(U, tau)
print(f"loop {nt_xent_loop(U, tau):.6f}  vectorised {loss:.6f}")

eps, num = 1e-6, np.zeros_like(U)                       # finite differences, one entry at a time
for idx in np.ndindex(U.shape):
    Up, Um = U.copy(), U.copy(); Up[idx] += eps; Um[idx] -= eps
    num[idx] = (nt_xent(Up, tau)[0] - nt_xent(Um, tau)[0]) / (2 * eps)
print("gradient matches finite differences to 1e-8:", bool(np.abs(grad - num).max() < 1e-8))

print(f"all embeddings equal: {nt_xent(np.ones((2 * N, dim)), tau)[0]:.4f}   log(2N - 1) = {np.log(2 * N - 1):.4f}")
base = rng.normal(size=(N, dim))
aligned = np.vstack([base, base + 0.05 * rng.normal(size=(N, dim))])   # views nearly identical
for t in (0.05, 0.1, 0.5, 1.0):
    print(f"tau = {t:4}: random embeddings {nt_xent(U, t)[0]:7.4f}   aligned pairs {nt_xent(aligned, t)[0]:.4f}")
loop 2.102901  vectorised 2.102901
gradient matches finite differences to 1e-8: True
all embeddings equal: 1.9459   log(2N - 1) = 1.9459
tau = 0.05: random embeddings 10.3775   aligned pairs 0.0014
tau =  0.1: random embeddings  5.4490   aligned pairs 0.0368
tau =  0.5: random embeddings  2.1029   aligned pairs 0.7607
tau =  1.0: random embeddings  1.9511   aligned pairs 1.2341

The loop and the vectorised version agree to six decimals, and the analytic gradient matches the numerical one. With all eight embeddings equal the loss is exactly log⁡7≈1.9459\log 7 \approx 1.9459. The temperature table shows its two sides. For aligned pairs, a small τ\tau drives the loss towards 0 (0.0014 at τ=0.05\tau = 0.05), because a similarity near 1 against similarities near 0 becomes a huge margin once divided by 0.05. For random embeddings the same small τ\tau is punishing (10.3775), because any negative that happens to be more similar than the positive dominates the softmax. That sensitivity to hard negatives is what a low temperature buys, and also why too low a temperature makes training unstable.

Training an encoder with NT-Xent

Now the whole recipe on the 8 x 8 digits, all in NumPy: an encoder ff (64 to 64 ReLU units) and a projection head gg (64 to 32, linear), 600 steps of gradient descent on batches of 64 images (128 views), τ=0.1\tau = 0.1. The augmentation shifts each image by up to one pixel, blanks 20 % of its pixels and adds a little noise. No labels are used until the linear probe, which is trained on h\mathbf{h} with 20, 50 or 200 labels and averaged over 5 random labelled subsets. The test set (540 images) never enters pretraining. An untrained encoder of the same shape is the control: it shows how much of any gain comes from training rather than from the architecture.

python · try it yourself
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression

def nt_xent(U, tau):
    """NT-Xent loss and its gradient with respect to U (rows i and i + N are pairs)."""
    n2 = len(U); N = n2 // 2
    norms = np.linalg.norm(U, axis=1, keepdims=True)
    Z = U / norms
    S = Z @ Z.T / tau
    np.fill_diagonal(S, -np.inf)
    pos = (np.arange(n2) + N) % n2
    P = np.exp(S - S.max(1, keepdims=True)); P /= P.sum(1, keepdims=True)
    loss = -np.log(P[np.arange(n2), pos]).mean()
    G = P.copy(); G[np.arange(n2), pos] -= 1; G /= n2
    gZ = (G + G.T) @ Z / tau
    return loss, (gZ - Z * (Z * gZ).sum(1, keepdims=True)) / norms

X, y = load_digits(return_X_y=True)
X = X / 16.0
X_pool, X_test, y_pool, y_test = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)
rng = np.random.default_rng(0)

def augment(X):
    """A random view: shift by up to 1 pixel (zero fill), blank 20 % of pixels, add noise."""
    n, ar = len(X), np.arange(8)
    padded = np.pad(X.reshape(n, 8, 8), ((0, 0), (1, 1), (1, 1)))
    oy, ox = rng.integers(0, 3, n), rng.integers(0, 3, n)
    out = padded[np.arange(n)[:, None, None], (oy[:, None] + ar)[:, :, None], (ox[:, None] + ar)[:, None, :]]
    out = out.reshape(n, 64) * (rng.random((n, 64)) > 0.2)
    return out + rng.normal(0, 0.1, out.shape)

H, P, tau, lr, B = 64, 32, 0.1, 0.5, 64
W1 = rng.normal(0, np.sqrt(2 / 64), (64, H)); b1 = np.zeros(H)    # encoder f
W2 = rng.normal(0, np.sqrt(1 / H), (H, P))                        # projection head g
W1_init, b1_init = W1.copy(), b1.copy()
for step in range(1, 601):
    xb = X_pool[rng.choice(len(X_pool), B, replace=False)]
    v = np.vstack([augment(xb), augment(xb)])              # 2B views, rows i and i + B are pairs
    a = v @ W1 + b1; h = np.maximum(0, a)
    loss, gu = nt_xent(h @ W2, tau)
    gh = gu @ W2.T * (a > 0)
    W2 -= lr * h.T @ gu
    W1 -= lr * v.T @ gh; b1 -= lr * gh.sum(0)
    if step in (1, 100, 300, 600):
        print(f"step {step:3d}: NT-Xent {loss:.3f}  (log(2B - 1) = {np.log(2 * B - 1):.3f})")

feats = {"raw pixels": lambda X: X,
         "random encoder": lambda X: np.maximum(0, X @ W1_init + b1_init),
         "contrastive encoder": lambda X: np.maximum(0, X @ W1 + b1)}
for n_lab in (20, 50, 200):
    row = []
    for name, f in feats.items():
        accs = []
        for seed in range(5):
            idx = np.random.default_rng(seed).choice(len(y_pool), n_lab, replace=False)
            accs.append(LogisticRegression(max_iter=3000).fit(f(X_pool[idx]), y_pool[idx]).score(f(X_test), y_test))
        row.append(f"{name} {np.mean(accs):.3f}")
    print(f"{n_lab:3d} labels: " + " | ".join(row))
step   1: NT-Xent 5.511  (log(2B - 1) = 4.844)
step 100: NT-Xent 4.001  (log(2B - 1) = 4.844)
step 300: NT-Xent 3.445  (log(2B - 1) = 4.844)
step 600: NT-Xent 3.221  (log(2B - 1) = 4.844)
 20 labels: raw pixels 0.550 | random encoder 0.497 | contrastive encoder 0.590
 50 labels: raw pixels 0.791 | random encoder 0.747 | contrastive encoder 0.819
200 labels: raw pixels 0.930 | random encoder 0.883 | contrastive encoder 0.923

The loss starts above log⁡(2B−1)=log⁡127≈4.844\log(2B - 1) = \log 127 \approx 4.844: at τ=0.1\tau = 0.1 the random initial similarities, divided by 0.1, already spread the softmax, and the true partner is often not the most similar view. Training brings it to 3.221. The probe numbers show what that bought. Against the untrained encoder of the same shape, the contrastive one is better at every label count (0.590 against 0.497 with 20 labels, 0.923 against 0.883 with 200), so the gain comes from training, not from the architecture. Against raw pixels it wins with few labels (0.590 against 0.550 with 20, 0.819 against 0.791 with 50) and loses slightly with 200 (0.923 against 0.930). That is the typical pattern of pretrained features: they matter most when labels are scarce. A one-layer encoder on 64 clean pixels is also a tiny version of the method; SimCLR's ResNet-50 on ImageNet reached linear-probe accuracy close to a supervised network, which is where contrastive learning earns its reputation.

The same loss in PyTorch

In PyTorch the loss is usually written as a cross-entropy over the similarity matrix, with the diagonal masked out and the partner's index as the target. Run on the same 8 embeddings as the NumPy check, it gives the same number.

python · try it yourself
import numpy as np
import torch
import torch.nn.functional as F

def nt_xent_torch(z, tau):
    n2 = z.shape[0]; N = n2 // 2
    z = F.normalize(z, dim=1)
    sim = z @ z.T / tau
    sim.fill_diagonal_(float("-inf"))                    # an anchor is never its own candidate
    target = (torch.arange(n2) + N) % n2                 # index of each row's partner
    return F.cross_entropy(sim, target)

rng = np.random.default_rng(0)
U = torch.tensor(rng.normal(size=(8, 8)), requires_grad=True)
loss = nt_xent_torch(U, 0.5)
loss.backward()
print(f"PyTorch NT-Xent {loss.item():.6f}")
print("gradient shape", tuple(U.grad.shape), "| row sums of grad . u are 0:",
      bool(torch.allclose((U.grad * U).sum(1), torch.zeros(8, dtype=U.dtype), atol=1e-12)))
PyTorch NT-Xent 2.102901
gradient shape (8, 8) | row sums of grad . u are 0: True

The value equals the NumPy one. The last line checks a property of the gradient: because the loss depends only on the direction of each embedding, the gradient for each row is orthogonal to that row (scaling u\mathbf{u} does not change the loss). The NumPy formula's last step, subtracting z(z⋅g)\mathbf{z} (\mathbf{z} \cdot \mathbf{g}), enforces exactly that.

Variants

Method What changes Why
SimCLR the recipe above, negatives from the batch simple; needs large batches
MoCo negatives from a queue of past batches, encoded by a slowly moving (EMA) copy of the encoder many negatives with small batches
BYOL, SimSiam no negatives at all: predict one view's embedding from the other's, with a stop-gradient or an EMA target no large batches; collapse avoided by the asymmetry
CLIP the positive pair is an image and its caption, encoded by two different networks joint image-text space, zero-shot classification
Supervised contrastive all examples of the same class are positives uses labels when you have them

Pitfalls

  • Representation collapse. If every input maps to the same point, the positive-pair similarity is perfect. The negatives in the denominator prevent this; methods without negatives need their asymmetry (stop-gradient, EMA) for the same job. A loss stuck at log⁡(2N−1)\log(2N - 1) is the warning sign.
  • Augmentations that leak a shortcut or remove the signal. Two crops of a photo can be matched by colour alone unless colour is also distorted; flipping text images left to right destroys what an OCR task needs.
  • Probing the projection head. The features before gg transfer better than z\mathbf{z}; gg is trained to throw away whatever the augmentation changes, which may be useful downstream.
  • False negatives. Two different photos of the same dog are treated as negatives. With few classes and large batches this matters; supervised contrastive learning or debiased losses address it.
  • Too small a batch. With few negatives the task is too easy and the features weak. Use a memory queue (MoCo) or a negative-free method if memory is limited.

Practice

  1. With a batch of N=256N = 256 images, how many candidates does each anchor see in the softmax, and what loss does a model that has learned nothing get?
  2. In the NumPy check, why does the loss for aligned pairs go down as τ\tau goes down, while the loss for random embeddings goes up?
  3. You pretrain on retinal scans with random rotations, crops and colour jitter. The downstream task grades disease severity, which shows as colour changes in the vessels. What is wrong?
Answers
  1. 2N−1=5112N - 1 = 511 candidates (every view except itself); the loss of a collapsed or untrained model is about log⁡511≈6.24\log 511 \approx 6.24.
  2. Dividing by a small τ\tau magnifies every similarity difference. For aligned pairs the positive is clearly the most similar, so the softmax puts nearly all its mass on it and the loss goes to 0. For random embeddings some negative is often more similar than the positive, and the magnified gap makes the loss large.
  3. Colour jitter teaches the encoder to ignore colour, which is the signal the downstream task needs. Remove colour jitter (or keep it very mild) and choose augmentations that change only what the task should ignore.

Test yourself

In SimCLR, what is a positive pair?

  1. Two images of the same class
  2. Two random augmentations of the same input
  3. An image and its label
  4. The anchor and its nearest neighbour in the dataset

A batch has N=4N = 4 inputs. What is the NT-Xent loss when all 8 embeddings are identical?

  1. 0
  2. log⁡4\log 4
  3. log⁡7\log 7
  4. log⁡8\log 8

What does lowering the temperature τ\tau do?

  1. Makes all negatives count equally
  2. Sharpens the softmax, so the loss focuses on the hardest negatives
  3. Removes the need for augmentations
  4. Increases the batch size

After SimCLR pretraining, which representation is usually used for the downstream task?

  1. z\mathbf{z}, the projection head's output
  2. h\mathbf{h}, the encoder's output before the projection head
  3. The augmented images
  4. The similarity matrix