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.
Sample a minibatch of N images.
Apply random data augmentation twice, independently, to each image to create two views x~iβ,x~jβ. This yields 2N images.
The default augmentations are random cropping with resizing back to the original size (including horizontal flips), color distortion, and Gaussian blur.
Pass them through the encoder f (e.g., ResNet-50) to obtain the representation h=f(x~). h is the output after average pooling (length 2048 for ResNet-50).
Pass it through the projection head g to obtain z=g(h)=W(2)Ο(W(1)h). g is an MLP with one hidden layer, Ο is ReLU, and the output has 128 dimensions.
Compute the cosine similarity si,kβ for every pair among the 2N vectors z.
Compute the NT-Xent loss and update the weights of f and g.
Here (i,j) are two views created from the same image (a positive pair), Ο is a constant called the temperature, and 1[kξ =i]β excludes k=i (the view itself). Besides the positive, the denominator contains the other 2(Nβ1) views in the minibatch (negatives). In other words, βi,jβ is the cross-entropy of a classification problem: "pick out your own partner from 2Nβ1 candidates." The final loss is the average of β computed in both directions, (i,j) and (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 g is discarded and the representation h before it is used for downstream tasks. In the paper, h outperformed z by more than 10% in linear evaluation. The likely reason is that 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.
Factor
Result in the paper
Practical guideline
Combination of data augmentations
The combination of random cropping and color distortion is especially important. Either one alone performs much worse
With cropping alone, the partner can be identified from the color distribution alone. Always include color distortion
Projection head
A nonlinear projection head is about 3% better than a linear projection and more than 10% better than no projection
Attach a 2-layer MLP and discard it after training
Batch size and training length
Larger batches and longer training are better. Contrastive learning benefits more from large batches and long training than supervised learning does
Defaults: batch size 4096, 100 epochs (the paper's best results use 1000 epochs)
Temperature Ο and normalization
β2β-normalizing z and choosing an appropriate temperature helps greatly (Ο=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.8 (=0.3ΓbatchΒ size/256), weight decay of 10β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.
Method
Negatives
Mechanism preventing collapse (all images mapping to the same feature)
Suitable conditions
SimCLR
Used (within the same minibatch)
Pushes away from negatives
Enough compute to run large batches
MoCo
Used (queue of past features)
Pushes away from negatives; the queue side uses a momentum-updated encoder
Many negatives are wanted, but the batch cannot be made large
Pushes the cross-correlation matrix of the two views' features toward the identity matrix
Rely 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.