Self-supervised and contrastive learning
Learning representations without labels — SimCLR, MoCo, BYOL, DINO, MAE
Labels are expensive; pixels are free. Self-supervised learning (SSL) turns unlabeled images into training signal, and since 2020 it has produced the best general-purpose visual features: DINOv2 embeddings power retrieval, depth and segmentation out of the box. The core loss, InfoNCE, is the same one that trains CLIP (8.10 Multimodal models) and every text embedding model behind RAG (9.2 Embeddings deep dive), and masked image modeling is the visual twin of BERT's masked language modeling (7.5 Encoder-only: BERT and friends (and sentence embeddings)). Learn the mechanism once here and you will recognize it across the rest of the path.
You'll be able to
- Define pretext tasks and explain why augmentation-based positives work
- Derive the InfoNCE / NT-Xent loss as a softmax classifier over candidates and explain the role of temperature
- Contrast contrastive (SimCLR, MoCo), non-contrastive (BYOL, DINO) and masked (MAE) approaches and why the latter two avoid collapse
- Evaluate representations with linear probing, kNN and fine-tuning
- Implement NT-Xent in PyTorch
Key ideas
- Self-supervision creates labels from the data (augmented views, masked patches); at scale it yields better transferable features than supervised ImageNet pretraining.
- NT-Xent/InfoNCE is cross-entropy over a softmax of scaled cosine similarities: pick the positive view among 2N−1 candidates; it lower-bounds mutual information, so more negatives help.
- Temperature τ controls focus on hard negatives: τ = 0.1 turns (0.8, 0.2, 0.1) into near-certainty, τ = 1 leaves it ambiguous; typical τ ≈ 0.1–0.5.
Show 4 more key ideas
- SimCLR needs crop + color distortion, a discarded projection head and big batches; MoCo replaces big batches with a momentum encoder and a queue of negatives.
- BYOL/SimSiam/DINO avoid collapse without negatives via predictor + stop-gradient + EMA teacher (DINO adds centering and sharpening); DINO attention maps segment objects for free.
- MAE masks 75% of patches, encodes only visible ones (3–4× cheaper) and reconstructs pixels; masked modeling fine-tunes best, joint-embedding probes best.
- Evaluate with linear probe, kNN, fine-tuning and transfer — the same protocol used for text embeddings.
Suggested path through this lesson
Supervision from the data itself
A pretext task is a problem whose labels come for free: predict the rotation applied to an image, solve a jigsaw of its patches, colorize a grayscale version, inpaint a missing region. Solving it well requires understanding content, so the learned features transfer. Early pretext tasks lagged supervised pretraining; two families closed and then reversed the gap — contrastive/joint-embedding methods (two views of the same image should have similar embeddings) and masked image modeling (reconstruct hidden patches). The philosophy matches language modeling (7.6 Decoder-only: GPT and autoregressive generation): predict part of the data from the rest, at scale.
Contrastive learning and InfoNCE
Take a mini-batch of images and create two random augmentations of each (random crop + resize, flip, color distortion, blur) — views. An encoder (ResNet or ViT) maps each view to a representation , and a small projection head maps it to . Define cosine similarity (1.1 Vectors, dot products and norms). For a positive pair — the two views of one image — the NT-Xent (normalized temperature-scaled cross-entropy) loss is
Read it as a softmax classifier: among the other views, pick the one that came from the same image. The other views are negatives. This is a cross-entropy loss (1.9 Information theory: entropy, cross-entropy and KL divergence) over a -way classification whose "logits" are scaled similarities, so everything you know about softmax and cross-entropy applies. It is also an estimator of mutual information: van den Oord et al. showed , which is why more negatives (larger batches) help — the bound gets tighter.
Temperature. sharpens or flattens the distribution. Worked: one positive with , two negatives with and .
- : softmax of gives , loss .
- : logits give , loss .
Small makes the loss focus on hard negatives (the gradient weight of negative is ), which drives uniformity on the sphere; too small and training becomes unstable or over-emphasizes false negatives (two different photos of dogs). SimCLR used –; CLIP learns .
import torch, torch.nn.functional as F
def nt_xent(z1, z2, tau=0.1):
z = F.normalize(torch.cat([z1, z2]), dim=1) # (2N, d), unit vectors
sim = z @ z.T / tau # cosine similarities / tau
sim.fill_diagonal_(float("-inf")) # exclude self-similarity
n = z1.shape[0]
targets = torch.cat([torch.arange(n, 2*n), torch.arange(0, n)]) # index of each positive
return F.cross_entropy(sim, targets) # softmax over 2N-1 candidates
SimCLR and MoCo
SimCLR (2020) is exactly the recipe above and found the details that matter: composition of crop and color distortion is essential (otherwise the model matches color histograms), a nonlinear projection head helps but is discarded after training (the representation before it transfers better), and large batches (4,096–8,192) with many negatives help. Linear probe on ImageNet: 69.3% with ResNet-50, 76.5% with a 4×-wide ResNet-50, matching supervised accuracy. MoCo removed the big-batch requirement: negatives come from a queue of past embeddings produced by a momentum encoder whose weights are an exponential moving average of the online encoder, with , keeping the queue consistent. MoCo v3 adapted the idea to ViTs.
Non-contrastive methods: no negatives, no collapse?
Why not just pull positives together? Because the trivial solution — map every image to the same vector — gives zero loss (collapse). Negatives prevent it in contrastive methods; BYOL (2020) showed you can avoid it differently: an online network with an extra predictor head learns to predict the output of a slowly-moving target network (EMA weights) on the other view, with a stop-gradient on the target. The asymmetry (predictor + EMA + stop-gradient) empirically prevents collapse; SimSiam showed even the EMA is optional if the stop-gradient stays. DINO (2021) frames this as self-distillation: a student ViT matches the softmax output of an EMA teacher over the other view, with centering (subtract a running mean so no single dimension dominates) and sharpening (low teacher temperature) jointly preventing collapse. Its striking discovery: the self-attention maps of a DINO ViT's [CLS] token segment the main object without any labels. DINOv2 (2023) scaled this with a curated 142 M-image dataset, a ViT-g teacher distilled into smaller models, and became the default frozen backbone — its features give state-of-the-art linear probes for classification, depth estimation and segmentation without fine-tuning.
Masked image modeling
MAE (2021) ports BERT to pixels with two twists. Mask a large fraction (75%) of patches — images are redundant, so a small mask would be trivially solved by interpolation. Run the encoder on the visible patches only (so it processes 25% of tokens: 3–4× cheaper), then a lightweight decoder takes encoded patches plus mask tokens and reconstructs normalized pixel values with an MSE loss on masked patches. MAE pretraining made ViT-H reach 87.8% ImageNet top-1 with ImageNet-1K data only and transfers excellently when fine-tuned, though its linear-probe accuracy is lower than DINO's. Rule of thumb: masked modeling → best after fine-tuning; joint-embedding → best frozen (linear probe / kNN). Many modern recipes combine both (DINOv2 adds an iBOT-style masked objective).
Evaluating representations
- Linear probe: freeze the encoder, train logistic regression (3.3 Logistic regression and softmax classification) on features. Measures linear separability.
- kNN classifier: no training at all (3.4 k-Nearest Neighbors); DINO reports it routinely.
- Fine-tuning: the ceiling, but conflates pretraining quality with the recipe.
- Transfer to detection/segmentation and robustness sets. The same protocol evaluates text embedding models in 9.2 Embeddings deep dive (MTEB is a linear-probe-and-retrieval suite).
Where this shows up later
- CLIP applies InfoNCE across images and captions — 8.10 Multimodal models; text embedding models for RAG train with in-batch negatives — 9.2 Embeddings deep dive.
- Masked language modeling (BERT) is MIM's older sibling — 7.5 Encoder-only: BERT and friends (and sentence embeddings); the ViT encoders here are reused by SAM — 5.6 Segmentation.
- Interpretability of what emerges without labels — 8.11 Interpretability: what is happening inside; representation learning foundations — 4.10 Autoencoders, embeddings and representation learning.
Common pitfalls (4)
- Using only crops without color distortion in contrastive learning — the model shortcuts by matching color histograms.
- Treating the projection head output as the representation; features before the head transfer better in SimCLR-style training.
- Mistaking a collapsed model for a trained one: check that embedding variance is not tiny and that a kNN probe beats chance.
- Small masking ratios in MAE make the task trivial (interpolation) and the features weak — 75% is not a typo.
Recap: all 7 key points
- Self-supervision creates labels from the data (augmented views, masked patches); at scale it yields better transferable features than supervised ImageNet pretraining.
- NT-Xent/InfoNCE is cross-entropy over a softmax of scaled cosine similarities: pick the positive view among 2N−1 candidates; it lower-bounds mutual information, so more negatives help.
- Temperature τ controls focus on hard negatives: τ = 0.1 turns (0.8, 0.2, 0.1) into near-certainty, τ = 1 leaves it ambiguous; typical τ ≈ 0.1–0.5.
- SimCLR needs crop + color distortion, a discarded projection head and big batches; MoCo replaces big batches with a momentum encoder and a queue of negatives.
- BYOL/SimSiam/DINO avoid collapse without negatives via predictor + stop-gradient + EMA teacher (DINO adds centering and sharpening); DINO attention maps segment objects for free.
- MAE masks 75% of patches, encodes only visible ones (3–4× cheaper) and reconstructs pixels; masked modeling fine-tunes best, joint-embedding probes best.
- Evaluate with linear probe, kNN, fine-tuning and transfer — the same protocol used for text embeddings.
Watch
The two-view pipeline, the NT-Xent loss, the augmentation ablations and why the projection head is discarded.
Read
Exercises
- Temperature by hand
With similarities positive 0.7 and negatives 0.5, 0.3, 0.0, compute the NT-Xent loss for . Then compute the gradient weight on each negative (, normalized) and describe how the focus shifts to the hardest negative as shrinks.
- SimCLR on CIFAR-10 in a notebook
Implement the two-view pipeline with
torchvision.transforms.v2, a ResNet-18 encoder, a 2-layer projection head and thent_xentfunction from the notes. Train for 50–100 epochs on a free GPU, then run a kNN probe () and a linear probe on frozen features. Expected: kNN accuracy well above the ~45% a randomly initialized encoder gives (SimCLR papers report ~80–90% with long training); check that removing color jitter hurts. - Frozen DINOv2 features vs supervised
Extract DINOv2 ViT-S/14 features and ImageNet-supervised ResNet-50 features for a small dataset of your choice; fit logistic regression on each. Compare accuracy and visualize both embedding spaces with PCA/UMAP (3.12 Dimensionality reduction: PCA, t-SNE and UMAP). Expected: DINOv2 features cluster classes more cleanly on most natural-image datasets.
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →