Foundations to Frontier
Tests
E. Deep Learning › E16 Self-Supervised and Contrastive Learning

SimCLR

SimCLR (Chen, Kornblith, Norouzi and Hinton, ICML 2020) learns visual representations without labels by contrasting augmented views. Two random augmentations of each image (cropping, colour distortion) pass through an encoder and a small projection head. The NT-Xent loss pulls the two views together and pushes them away from every other view in the batch. Its lessons: strong augmentations, a nonlinear projection head, large batches (more negatives) and a well-chosen temperature. This page covers the contrastive set-up, NT-Xent, temperature and batch size, and linear-probe evaluation. In the exercises you implement NT-Xent, then train SimCLR on a synthetic world where style variation hides class content. Raw features gave probe accuracy 0.52 and SimCLR 0.78 at temperature 0.05. A high temperature (1.0) was worst on all three seeds, and a small batch (16) was slightly worse than 64.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Two views of the same thing should look alike

Labels are expensive, but unlabelled images are everywhere. SimCLR learns from them with a simple game. Take an image, make two altered copies of it (crop it differently, change its colours), and train a network so that the two copies end up with similar codes while copies of other images end up far away. To win, the network must ignore the alterations and capture what the image actually shows. The demo shows the core loss: the softmax probability given to the true partner among the candidates.

Self-supervised learning lab
Probability on the positive (green): 0.571; InfoNCE loss 0.560. Low τ sharpens the softmax and focuses on the hardest negatives; high τ treats all negatives alike.
Why engineers care

Satellite, inspection and robot cameras produce vast unlabelled imagery. Self-supervised pre-training on it gives features that need far fewer labels for downstream tasks.

📝 Quick check (Level 0)
0/3 answered
  1. 1. SimCLR learns from…
  2. 2. Two altered copies of the same image should get…
  3. 3. Copies of other images act as…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Pipeline: image → two augmentations → encoder f (ResNet) → projection head g (MLP) → z; the representation used afterwards is f’s output, not z.
  • NT-Xent loss: for a positive pair (i, j) among 2B views, ℓ_i = −log [exp(sim(z_i, z_j)/τ) / Σ_(k ≠ i) exp(sim(z_i, z_k)/τ)], with cosine similarity.
  • Negatives: each anchor has 2B − 2 negatives, 126 for B = 64 and 8190 for SimCLR’s B = 4096.
  • Collapse check: if all embeddings are identical, every candidate is equally likely and the loss is ln(2B − 1), ln 3 for B = 2.
  • Temperature: τ ≈ 0.1 is typical. Smaller τ sharpens the softmax and weights hard negatives more.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Negatives per anchor for B = 64:
  2. 2. NT-Xent when all embeddings coincide (B = 2):
  3. 3. The representation used downstream comes from…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

SimCLR in code

Exercise 1.

  • NT-Xent was near zero when each view matched its partner, large when partners were swapped, and exactly ln 3 for identical embeddings.
  • Negatives per anchor were 2B − 2.

Practice.

  • Augmentations are critical: random resized crop plus colour jitter and grayscale, with blur for ImageNet.
  • Use a 2–3 layer MLP projection head, LARS or AdamW, long training, and a large batch (or a memory bank or queue; see MoCo).
  • Evaluate with a linear probe on frozen features, and with few-label fine-tuning.
z1, z2 = proj(enc(aug(x))), proj(enc(aug(x)))          # two views of the same batch
z = F.normalize(torch.cat([z1, z2]), dim=-1)
sim = z @ z.T / tau; sim.fill_diagonal_(float("-inf"))
B = x.shape[0]; targets = torch.cat([torch.arange(B, 2 * B), torch.arange(B)])
loss = F.cross_entropy(sim, targets)                    # NT-Xent
🐍 Exercise 1: NT-Xent
Implement cosine similarities, the NT-Xent loss and the number of negatives.
📝 Quick check (Level 2)
0/3 answered
  1. 1. The most important augmentation pair in SimCLR:
  2. 2. Self-supervised features are evaluated by…
  3. 3. Without huge batches, use…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Invariance by construction.

  • The positive pair differs only by augmentation, so the loss rewards features that are invariant to the augmentations and discriminative between images.
  • What counts as “content” is defined by the augmentations: choose them to destroy nuisance (lighting, viewpoint) but preserve what downstream tasks need.

Alignment and uniformity. Wang and Isola (2020) showed that the contrastive loss balances alignment (positives close) against uniformity (embeddings spread evenly on the sphere). Negatives provide the uniformity pressure that prevents collapse.

Temperature and batch size.

  • τ controls how strongly the loss concentrates on hard negatives. Too high, and all negatives are treated alike, giving weak, uniform gradients. Too low risks over-penalising semantically similar negatives.
  • More negatives give a tighter bound on the mutual information between views and a better estimate of uniformity, hence SimCLR’s large batches.
📝 Quick check (Level 3)
0/3 answered
  1. 1. Augmentations define…
  2. 2. Negatives provide…
  3. 3. A high temperature makes the loss…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

How do temperature and batch size matter?

History.

  • T. Chen, S. Kornblith, M. Norouzi and G. Hinton, “A simple framework for contrastive learning of visual representations” (ICML 2020).
  • Earlier: InstDisc (2018), CPC (2018).
  • SimCLR v2 (2020) added bigger models and distillation for semi-supervised learning.

Exercise 2.

  • World: observations mix 8 content dimensions (10 classes) with 10 strong style dimensions. An augmentation redraws the style and keeps the content.
  • Training: SimCLR (encoder 32 → 64 → 16, projection head 16 → 32 → 16), 800 steps, batch 64 at τ = 0.05, 0.2 or 1.0, plus batch 16 at τ = 0.05.
  • Evaluation: a nearest-centroid probe with 500 labelled and 500 test images.
features probe accuracy
raw observations 0.522
random encoder 0.320
SimCLR, τ = 0.05 0.782
SimCLR, τ = 0.2 0.774
SimCLR, τ = 1.0 0.738
SimCLR, τ = 0.05, batch 16 0.772
  • SimCLR learns the content: with no labels at all, it lifted probe accuracy from 0.52 to 0.78 by learning to ignore the style that augmentations change.
  • High temperature is consistently worse: τ = 1.0 gave the lowest accuracy on all three seeds (0.74, 0.75, 0.70), while τ = 0.05 and 0.2 were within noise of each other.
  • Fewer negatives hurt a little: batch 16 was below batch 64 on all three seeds (0.77/0.74/0.72 against 0.78/0.77/0.76). With only 10 classes, many “negatives” share the anchor’s class, which limits the benefit of more negatives.
🐍 Exercise 2 (research): how do temperature and batch size matter?
Train SimCLR at three temperatures and two batch sizes on a style-dominated world and compare probe accuracy.

Contrastive learning in AI, robotics and aerospace

  • Remote sensing: pre-training on unlabelled satellite imagery, using seasonal or sensor variation as augmentation.
  • Robot perception: learning features from unlabelled video, with different viewpoints or times as positive pairs.
  • Design lesson: choose augmentations that change only what downstream tasks should ignore, and evaluate with a linear probe on a held-out labelled set.

References

  1. T. Chen, S. Kornblith, M. Norouzi and G. Hinton (2020). “A simple framework for contrastive learning of visual representations.” Proc. ICML.
  2. T. Wang and P. Isola (2020). “Understanding contrastive representation learning through alignment and uniformity on the hypersphere.” Proc. ICML.
  3. A. van den Oord, Y. Li and O. Vinyals (2018). “Representation learning with contrastive predictive coding.” arXiv:1807.03748.