Contrastive Learning with SimCLR from Scratch Guide
In computer vision, supervised representation learning relies heavily on large annotated datasets like ImageNet. However, manually labeling millions of images is expensive, time-consuming, and prone to human annotation bias. Self-supervised learning solves this challenge by allowing models to extract powerful visual features from unlabeled data without human supervision.
SimCLR (Simple Framework for Contrastive Learning of Visual Representations) is a breakthrough framework that simplifies self-supervised visual representation learning. By maximizing agreement between differently augmented views of the same image via contrastive loss, SimCLR achieves performance comparable to fully supervised models.
Core SimCLR Architecture & Augmentation Pipeline
The SimCLR training pipeline relies on four distinct architectural components designed to map input images into a discriminative embedding space:
- Stochastic Data Augmentation Module: Transforms any given image randomly into two correlated views ($x_i$ and $x_j$) using a composition of augmentations, including random cropping, color distortion, and Gaussian blur.
- Base Encoder (ResNet): A standard backbone network (e.g., ResNet-50) extracts representation vectors $h$ from the augmented image views.
- Non-Linear Projection Head (MLP): A multi-layer perceptron maps representations $h$ to a lower-dimensional latent space $z$ where the contrastive loss is applied.
- NT-Xent Loss Function: Evaluates cosine similarity across positive pairs against all negative pairs within a mini-batch to pull matching views together and push apart non-matching representations.
PyTorch Implementation of NT-Xent Loss & SimCLR Loop
Here is a complete PyTorch training script implementing the normalized temperature-scaled cross entropy (NT-Xent) loss and SimCLR training step:
import torch
import torch.nn as nn
import torch.nn.functional as F
class NTXentLoss(nn.Module):
def __init__(self, batch_size, temperature=0.5):
super(NTXentLoss, self).__init__()
self.batch_size = batch_size
self.temperature = temperature
self.criterion = nn.CrossEntropyLoss(reduction="sum")
self.similarity_f = nn.CosineSimilarity(dim=2)
def forward(self, z_i, z_j):
# 1. Concatenate projections from both augmentation views
2 * self.batch_size
z = torch.cat([z_i, z_j], dim=0)
# 2. Compute similarity matrix
sim = self.similarity_f(z.unsqueeze(1), z.unsqueeze(0)) / self.temperature
# Mask out self-similarities
sim_i_j = torch.diag(sim, self.batch_size)
sim_j_i = torch.diag(sim, -self.batch_size)
positive_samples = torch.cat([sim_i_j, sim_j_i], dim=0)
# Create negative mask
mask = torch.eye(2 * self.batch_size, dtype=torch.bool, device=z.device)
negative_mask = ~mask
# Exclude positive pairs from negatives
negatives = sim[negative_mask].view(2 * self.batch_size, -1)
# 3. Combine positive and negative logits
logits = torch.cat([positive_samples.unsqueeze(1), negatives], dim=1)
labels = torch.zeros(2 * self.batch_size, dtype=torch.long, device=z.device)
# 4. Compute cross-entropy loss
loss = self.criterion(logits, labels) / (2 * self.batch_size)
return loss
if __name__ == "__main__":
# Mock batch test for NT-Xent loss
batch_size = 16
loss_fn = NTXentLoss(batch_size=batch_size, temperature=0.5)
z_i = torch.randn(batch_size, 128)
z_j = torch.randn(batch_size, 128)
loss = loss_fn(z_i, z_j)
print(f"Computed NT-Xent Contrastive Loss: {loss.item():.4f}")
Contrastive Learning Best Practices
When training self-contrastive representation models from scratch, follow these engineering guidelines:
- Large Batch Sizes: SimCLR heavily relies on large mini-batch sizes (e.g., 256 to 4096) to provide a rich set of negative samples for contrastive comparison.
- Color Distortion is Crucial: Empirical studies show that color jittering/distortion is the most critical augmentation; without it, models shortcut learning by exploiting simple color histograms.
- Projection Head Design: Always include a non-linear projection MLP during pre-training and discard it during downstream fine-tuning to retain richer linear representations.