AI Logic

Self-Supervised Learning

SimCLR

Updated:

SimCLR training flow. The left side shows an image passing through two data augmentations, an encoder, and a projection head into the NT-Xent loss; the right side shows the similarity matrix among 2N features, with positives, negatives, and self-pairs color-coded

Background and Overview

SimCLR is a self-supervised learning method that uses only unlabeled images and learns so that "two views created from the same image end up close, while views of different images end up far apart." It was proposed by Chen et al. at Google in 2020. The name stands for "A Simple Framework for Contrastive Learning of Visual Representations."

Building an image recognition model normally requires people to label a large number of images ("dog," "cat," and so on), which takes time and money. Instead of labels, SimCLR relies on the fact that "cropping an image or changing its colors does not change what it shows." For example, if the network learns to tell that a crop of the top-left of a dog photo and a grayscale crop of the bottom-right of the same photo are "the same," while a photo of a different cat is "different," it acquires features that capture object shape and texture and are not swayed by color or position. Learning by comparing pairs to pull together with pairs to push apart is called contrastive learning (see contrastive loss for the idea behind the loss).

After training, the features produced by the encoder are used for downstream tasks such as classification and detection. The paper evaluates the features of a ResNet-50 trained on ImageNet by adding just one linear classifier on top (linear evaluation), reaching a top-1 accuracy of 69.3%. A ResNet-50 four times wider (4Γ—) reaches 76.5%, on par with a ResNet-50 trained in the usual supervised way with labels (76.3%).

What sets SimCLR apart is that it achieves high performance using only a combination of simple componentsβ€”data augmentation, a projection head, and large batchesβ€” without special machinery such as a memory bank storing past features or a dedicated network architecture.

Training Procedure and Loss

SimCLR training repeats the following steps, as in Algorithm 1 of the paper.

  1. Sample a minibatch of NN images.
  2. Apply random data augmentation twice, independently, to each image to create two views x~i,x~j\tilde{\boldsymbol{x}}_i, \tilde{\boldsymbol{x}}_j. This yields 2N2N images.
    • The default augmentations are random cropping with resizing back to the original size (including horizontal flips), color distortion, and Gaussian blur.
  3. Pass them through the encoder ff (e.g., ResNet-50) to obtain the representation h=f(x~)\boldsymbol{h} = f(\tilde{\boldsymbol{x}}). h\boldsymbol{h} is the output after average pooling (length 2048 for ResNet-50).
  4. Pass it through the projection head gg to obtain z=g(h)=W(2)Οƒ(W(1)h)\boldsymbol{z} = g(\boldsymbol{h}) = W^{(2)} \sigma(W^{(1)} \boldsymbol{h}). gg is an MLP with one hidden layer, Οƒ\sigma is ReLU, and the output has 128 dimensions.
  5. Compute the cosine similarity si,ks_{i,k} for every pair among the 2N2N vectors z\boldsymbol{z}.
  6. Compute the NT-Xent loss and update the weights of ff and gg.

The loss in steps 5–6 is written as follows.

sim(u,v)=u⊀vβˆ₯uβˆ₯βˆ₯vβˆ₯,β„“i,j=βˆ’log⁑exp⁑(sim(zi,zj)/Ο„)βˆ‘k=12N1[kβ‰ i]exp⁑(sim(zi,zk)/Ο„)\mathrm{sim}(\boldsymbol{u}, \boldsymbol{v}) = \frac{\boldsymbol{u}^\top \boldsymbol{v}}{\|\boldsymbol{u}\| \|\boldsymbol{v}\|}, \qquad \ell_{i,j} = -\log \frac{\exp(\mathrm{sim}(\boldsymbol{z}_i, \boldsymbol{z}_j)/\tau)}{\sum_{k=1}^{2N} \mathbb{1}_{[k \neq i]} \exp(\mathrm{sim}(\boldsymbol{z}_i, \boldsymbol{z}_k)/\tau)}

Here (i,j)(i, j) are two views created from the same image (a positive pair), Ο„\tau is a constant called the temperature, and 1[kβ‰ i]\mathbb{1}_{[k \neq i]} excludes k=ik = i (the view itself). Besides the positive, the denominator contains the other 2(Nβˆ’1)2(N-1) views in the minibatch (negatives). In other words, β„“i,j\ell_{i,j} is the cross-entropy of a classification problem: "pick out your own partner from 2Nβˆ’12N - 1 candidates." The final loss is the average of β„“\ell computed in both directions, (i,j)(i, j) and (j,i)(j, i), over all positive pairs. The paper calls this loss NT-Xent (normalized temperature-scaled cross-entropy). Its form is the same as InfoNCE.

Another feature of SimCLR is that it does not prepare negatives separately. It simply uses the other images in the same minibatch as negatives. With a batch size of 4096, each positive pair has 8190 negatives.

After training, the projection head gg is discarded and the representation h\boldsymbol{h} before it is used for downstream tasks. In the paper, h\boldsymbol{h} outperformed z\boldsymbol{z} by more than 10% in linear evaluation. The likely reason is that z\boldsymbol{z} is trained to be invariant to data augmentation, so it discards information that is useful for downstream tasks, such as color and orientation.

What Drives Performance

The paper examines the factors that affect SimCLR's performance one by one. The main results are as follows.

FactorResult in the paperPractical guideline
Combination of data augmentationsThe combination of random cropping and color distortion is especially important. Either one alone performs much worseWith cropping alone, the partner can be identified from the color distribution alone. Always include color distortion
Projection headA nonlinear projection head is about 3% better than a linear projection and more than 10% better than no projectionAttach a 2-layer MLP and discard it after training
Batch size and training lengthLarger batches and longer training are better. Contrastive learning benefits more from large batches and long training than supervised learning doesDefaults: batch size 4096, 100 epochs (the paper's best results use 1000 epochs)
Temperature Ο„\tau and normalizationβ„“2\ell_2-normalizing z\boldsymbol{z} and choosing an appropriate temperature helps greatly (Ο„=0.1\tau = 0.1 was best among those compared)Do not use a plain dot product without normalization or temperature

To keep training stable with large batches, LARS is used for optimization. The default settings are a learning rate of 4.84.8 (=0.3Γ—batchΒ size/256= 0.3 \times \text{batch size} / 256), weight decay of 10βˆ’610^{-6}, a linear increase of the learning rate over the first 10 epochs (warmup), followed by cosine decay.

Because SimCLR draws its negatives from the minibatch, a smaller batch size means fewer negatives and lower performance. The paper's setting (batch size 4096, ResNet-50) takes about 1.5 hours for 100 epochs on a 128-core TPU. With only one or two GPUs, consider MoCo, which stores negatives in a queue, or methods that use no negatives at all.

Comparison with Other Self-Supervised Methods

After SimCLR, several methods were proposed based on the same idea of "pulling two views together" but without relying on large batches or negatives. The table below compares them from the same perspectives.

MethodNegativesMechanism preventing collapse (all images mapping to the same feature)Suitable conditions
SimCLRUsed (within the same minibatch)Pushes away from negativesEnough compute to run large batches
MoCoUsed (queue of past features)Pushes away from negatives; the queue side uses a momentum-updated encoderMany negatives are wanted, but the batch cannot be made large
BYOLNot usedA predictor and a momentum-updated target networkAvoid the effort of collecting negatives
SimSiamNot usedA predictor and stopping the gradient on one side (stop-gradient)Keep the mechanism as simple as possible
Barlow TwinsNot usedPushes the cross-correlation matrix of the two views' features toward the identity matrixRely on neither large batches nor a predictor

SimCLR is the simplest of the methods that use negatives, which makes it a good starting point for understanding the basics of contrastive learning. When compute is limited, however, other methods may be easier to work with.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms, models
from torch.utils.data import DataLoader
from tqdm import tqdm

"""
Train SimCLR on CIFAR-10 images only (no labels),
then freeze the encoder and evaluate it with a linear classifier (linear evaluation)
"""

# Hyperparameters
batch_size = 256      # Batch size (larger means more negatives; the paper's default is 4096)
epochs = 100          # Number of pretraining epochs
learning_rate = 1e-3  # Learning rate (the paper uses LARS; Adam here for simplicity)
temperature = 0.5     # Temperature Ο„ of NT-Xent
proj_dim = 128        # Output dimension of the projection head

device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'

# Data augmentation (for CIFAR-10; no Gaussian blur because the images are small)
augment = transforms.Compose([
  transforms.RandomResizedCrop(32),
  transforms.RandomHorizontalFlip(),
  transforms.RandomApply([transforms.ColorJitter(0.4, 0.4, 0.4, 0.1)], p=0.8),
  transforms.RandomGrayscale(p=0.2),
  transforms.ToTensor(),
])


class TwoViews:
  """Create two views of one image with independent data augmentations"""
  def __init__(self, transform):
    self.transform = transform

  def __call__(self, x):
    return self.transform(x), self.transform(x)


pretrain_dataset = datasets.CIFAR10(root='./data', train=True, download=True, transform=TwoViews(augment))
pretrain_loader = DataLoader(pretrain_dataset, batch_size=batch_size, shuffle=True, drop_last=True)


# Encoder f (ResNet-18 adapted to small images) and projection head g
def make_encoder():
  net = models.resnet18(num_classes=10)
  net.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
  net.maxpool = nn.Identity()
  net.fc = nn.Identity()  # Output is the representation h after average pooling (512-dim)
  return net


class SimCLR(nn.Module):
  def __init__(self, feat_dim=512, proj_dim=128):
    super().__init__()
    self.encoder = make_encoder()
    self.projector = nn.Sequential(   # g(h) = W2 ReLU(W1 h)
      nn.Linear(feat_dim, feat_dim),
      nn.ReLU(),
      nn.Linear(feat_dim, proj_dim),
    )

  def forward(self, x):
    h = self.encoder(x)
    return self.projector(h)


def nt_xent(z1, z2, tau):
  """NT-Xent loss. z1[k] and z2[k] are positives; the other 2(N-1) are negatives"""
  n = z1.size(0)
  z = F.normalize(torch.cat([z1, z2]), dim=1)  # [2N, d], normalized to unit length
  sim = z @ z.t() / tau                         # cosine similarity / Ο„
  sim.fill_diagonal_(float('-inf'))             # exclude self-similarity
  # Target (partner) for row i: the first half points to the same index in the second half, and vice versa
  target = torch.cat([torch.arange(n, 2 * n), torch.arange(0, n)]).to(z.device)
  return F.cross_entropy(sim, target)           # average over both (i,j) and (j,i)


# Pretraining (no labels used)
model = SimCLR(proj_dim=proj_dim).to(device)
optimizer = optim.Adam(model.parameters(), lr=learning_rate)

for epoch in tqdm(range(epochs)):
  model.train()
  for (x1, x2), _ in pretrain_loader:
    x1, x2 = x1.to(device), x2.to(device)
    loss = nt_xent(model(x1), model(x2), temperature)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

# Linear evaluation: discard the projection head, freeze the encoder, and train only a linear layer
plain = transforms.ToTensor()
train_loader = DataLoader(datasets.CIFAR10('./data', train=True, transform=plain), batch_size=256, shuffle=True)
test_loader = DataLoader(datasets.CIFAR10('./data', train=False, transform=plain), batch_size=256)

encoder = model.encoder.eval()
classifier = nn.Linear(512, 10).to(device)
clf_optimizer = optim.Adam(classifier.parameters(), lr=1e-3)
criterion = nn.CrossEntropyLoss()

for epoch in range(10):
  for images, labels in train_loader:
    images, labels = images.to(device), labels.to(device)
    with torch.no_grad():
      h = encoder(images)
    loss = criterion(classifier(h), labels)
    clf_optimizer.zero_grad()
    loss.backward()
    clf_optimizer.step()

correct = 0
total = 0
with torch.no_grad():
  for images, labels in test_loader:
    images, labels = images.to(device), labels.to(device)
    predicted = classifier(encoder(images)).argmax(dim=1)
    total += labels.size(0)
    correct += (predicted == labels).sum().item()

print(f"Linear Eval Accuracy: {100 * correct / total:.2f}%")

FAQ

Q. If the projection head is discarded, why train with it?
A.

The loss works to remove information that changes under data augmentation (such as color and orientation). With a projection head attached, the head takes on this job of "removing information," so the representation h before it retains information useful for downstream tasks. In the paper, using h was more than 10% better than using z in linear evaluation.

Q. Why does performance drop with a small batch size?
A.

SimCLR uses the other images in the same minibatch as negatives. With batch size N there are 2(Nβˆ’1) negatives, so a small batch means fewer candidates to compare against, and the discrimination task becomes too easy. In the paper as well, performance improved as the batch size grew from 256 to 8192, especially when training was short.

Q. Which data augmentations should be used?
A.

The paper's defaults are random cropping and resizing (including horizontal flips), color distortion (brightness, contrast, saturation, hue, and grayscale conversion), and Gaussian blur. The combination of cropping and color distortion is particularly important: without color distortion, the partner can be identified from the color distribution alone, and good features are not learned.

References

  1. Chen, T., Kornblith, S., Norouzi, M., & Hinton, G. (2020). A Simple Framework for Contrastive Learning of Visual Representations. Proceedings of the 37th International Conference on Machine Learning (ICML), PMLR 119, 1597–1607.
  2. You, Y., Gitman, I., & Ginsburg, B. (2017). Large Batch Training of Convolutional Networks. arXiv:1708.03888.
  3. He, K., Fan, H., Wu, Y., Xie, S., & Girshick, R. (2020). Momentum Contrast for Unsupervised Visual Representation Learning. CVPR 2020.
  4. Grill, J.-B., et al. (2020). Bootstrap Your Own Latent: A New Approach to Self-Supervised Learning. NeurIPS 2020.
  5. Chen, X., & He, K. (2021). Exploring Simple Siamese Representation Learning. CVPR 2021.
  6. Zbontar, J., Jing, L., Misra, I., LeCun, Y., & Deny, S. (2021). Barlow Twins: Self-Supervised Learning via Redundancy Reduction. ICML 2021.