Repository navigation
Module 17
⬅️ Module 16 · 🗺️ Curriculum · 🏠 Home · Module 18 ➡️
Level: Advanced · Prerequisites: Modules 03, 11, 14, 16 · Time: about 8–9 hours
On this page: Overview and learning goals · Beginner: the big picture · Core concepts and derivations · Worked example · Implementation · Advanced topics · Pitfalls and best practices · Conceptual questions and answers · Sources and further reading
Self-supervised learning (SSL) creates a training signal from the data itself. Contrastive learning — the dominant approach — pulls together representations of two views of the same example (positives) and pushes apart different examples (negatives). It powers image encoders (SimCLR, MoCo), multimodal models (CLIP) and text/audio embedding models.
After this module you should be able to:
- define pretext tasks, positives/negatives and the InfoNCE/NT-Xent loss and its role as a mutual-information bound;
- explain temperature, batch size/negatives, projection heads and the memory queue/momentum encoder;
- explain how BYOL/SimSiam avoid collapse without negatives;
- evaluate representations with linear probes and recognise failure modes.
Take a photo, produce two random crops/colour changes of it, and ask the network to recognise that they came from the same photo while distinguishing them from other photos. To succeed, the encoder must keep what is invariant to the augmentations (object identity) and discard nuisance (exact crop, colour).
flowchart LR
X["Image x"] --> A1["Augmentation t1"] --> E1["Encoder f"] --> P1["Projection head g"] --> Z1["z_i"]
X --> A2["Augmentation t2"] --> E2["Encoder f (shared)"] --> P2["Projection head g"] --> Z2["z_j"]
Z1 --> L["Contrastive loss: maximise sim(z_i,z_j), minimise sim with other images"]
Z2 --> L
Figure 17.1 — SimCLR-style pipeline (after Chen et al. 2020). Original diagram.
Classic SSL tasks: predict rotation, solve jigsaw puzzles, colourise, inpaint, predict the next token or masked tokens (language), predict the next patch/frame. Their value is how much transferable structure they force the encoder to learn.
Pair loss (Hadsell et al. 2006):
For an anchor
This is exactly softmax cross-entropy where the "class" is which candidate is the true positive — an
Mutual-information bound (van den Oord et al. 2018):
Small
-
SimCLR (Chen et al. 2020): strong augmentation (random crop, colour jitter, blur), nonlinear projection head
$g$ (loss applied after$g$ , features taken before$g$ ), large batches (thousands) for negatives. -
MoCo (He et al. 2020): a FIFO queue of past key embeddings supplies many negatives with small batches; the key encoder is a momentum average of the query encoder,
$\theta_k\leftarrow m\theta_k+(1-m)\theta_q$ with$m\approx0.999$ , keeping keys consistent. -
CLIP (Radford et al. 2021): symmetric InfoNCE between image and text embeddings in a batch of
$B$ pairs; the$B\times B$ similarity matrix has positives on the diagonal. Enables zero-shot classification by comparing an image with text prompts. - Supervised contrastive (Khosla et al. 2020) treats all same-class samples as positives.
Without negatives, a trivial solution maps everything to one point (collapse). BYOL (Grill et al. 2020) predicts the output of a momentum "target" network from an "online" network with a predictor head and stop-gradient; SimSiam (Chen & He 2021) shows stop-gradient + predictor suffice; DINO self-distils with centring and sharpening; Barlow Twins/VICReg decorrelate feature dimensions. Explanations of why collapse is avoided involve asymmetry, normalisation and implicit variance regularisation.
Standard protocols: linear probe (frozen features + logistic regression), k-NN, semi-supervised fine-tuning with 1–10% labels, and transfer to detection/segmentation. Check robustness to distribution shift and whether invariances learned (e.g. colour invariance) hurt downstream tasks.
Anchor with candidate cosine similarities
Bound: with
import numpy as np
def info_nce(z1, z2, tau=0.1):
"""Symmetric InfoNCE; z1[i] and z2[i] are the two views of example i; rows are L2-normalised."""
S = z1 @ z2.T / tau # (B, B) similarities
def ce(S):
S = S - S.max(1, keepdims=True); logp = S - np.log(np.exp(S).sum(1, keepdims=True))
return -np.mean(np.diag(logp))
return 0.5 * (ce(S) + ce(S.T))
rng = np.random.default_rng(0); a = rng.normal(size=(8, 16)); a /= np.linalg.norm(a, axis=1, keepdims=True)
print(info_nce(a, a), info_nce(a, np.roll(a, 1, axis=0))) # aligned views -> low loss; mismatched -> high# MoCo-style momentum update (PyTorch)
with torch.no_grad():
for pk, pq in zip(key_encoder.parameters(), query_encoder.parameters()):
pk.mul_(0.999).add_(pq, alpha=0.001)- Masked modelling (BERT, MAE, BEiT) and next-token prediction are generative SSL; contrastive and generative SSL are converging in multimodal models.
- Theory: InfoNCE and spectral contrastive losses relate to spectral clustering of an augmentation graph (HaoChen et al. 2021); bounds on MI estimation have high variance for large MI (McAllester & Stratos 2020).
- Augmentation design defines the invariances; learning them (e.g. view generators) is an active area.
- Multimodal alignment (CLIP, ALIGN), retrieval embeddings, and dense contrastive losses for detection/segmentation.
- Scaling: larger models and data improve SSL; data curation matters (DINOv2).
- Using the projection-head output rather than the backbone features for downstream tasks (usually worse).
- Too-weak augmentations → trivial shortcuts (e.g. colour histogram matching).
- Batch-norm information leakage between views within a batch (MoCo shuffles BN across GPUs).
- Not normalising embeddings, or mis-tuning temperature.
- Ignoring false negatives in datasets with few classes or duplicates.
Q1. Why is InfoNCE a classification loss?
Show answer
It is softmax cross-entropy over
Q2. What does temperature do?
Show answer
It scales the logits: low
Q3. How does MoCo get many negatives with a small batch?
Show answer
A queue stores embeddings from previous batches as negatives; a slowly updated momentum encoder keeps those stored keys consistent with current ones.
Q4. How do BYOL/SimSiam avoid collapse without negatives?
Show answer
Asymmetry — a predictor on one branch, stop-gradient and (for BYOL) a momentum target — together with normalisation prevents the trivial constant solution in practice.
Q5. Why use a projection head and discard it later?
Show answer
The contrastive loss encourages invariance to augmentations, discarding information (e.g. colour) possibly useful downstream; the head absorbs this loss of information so the backbone features stay richer.
Q6. State the InfoNCE mutual information bound.
Show answer
Q7. What are false negatives?
Show answer
Other samples in the batch that actually share the semantic class (or are duplicates) but are treated as negatives, pushing similar items apart.
Q8. How does CLIP enable zero-shot classification?
Show answer
Embed class names as text prompts ("a photo of a {class}") and pick the class whose text embedding has the highest similarity to the image embedding.
- Hadsell, R., Chopra, S., & LeCun, Y. (2006). Dimensionality reduction by learning an invariant mapping. CVPR.
- Schroff, F., Kalenichenko, D., & Philbin, J. (2015). FaceNet. CVPR. arXiv:1503.03832.
- van den Oord, A., Li, Y., & Vinyals, O. (2018). Representation learning with contrastive predictive coding. arXiv:1807.03748.
- Chen, T., Kornblith, S., Norouzi, M., & Hinton, G. (2020). A simple framework for contrastive learning of visual representations. ICML. arXiv:2002.05709.
- He, K., Fan, H., Wu, Y., Xie, S., & Girshick, R. (2020). Momentum contrast for unsupervised visual representation learning. CVPR. arXiv:1911.05722.
- Grill, J.-B., et al. (2020). Bootstrap your own latent. NeurIPS. arXiv:2006.07733.
- Chen, X., & He, K. (2021). Exploring simple Siamese representation learning. CVPR. arXiv:2011.10566.
- Radford, A., et al. (2021). Learning transferable visual models from natural language supervision (CLIP). ICML. arXiv:2103.00020.
- Caron, M., et al. (2021). Emerging properties in self-supervised vision Transformers (DINO). ICCV. arXiv:2104.14294.
- Khosla, P., et al. (2020). Supervised contrastive learning. NeurIPS.
- Wang, T., & Isola, P. (2020). Understanding contrastive representation learning through alignment and uniformity on the hypersphere. ICML.
- HaoChen, J. Z., Wei, C., Gaidon, A., & Ma, T. (2021). Provable guarantees for self-supervised deep learning with spectral contrastive loss. NeurIPS.
⬅️ Module 16 · 🗺️ Curriculum · 🏠 Home · Module 18 ➡️
🏠 Home · 🗺️ Curriculum · 🧭 Learning paths · ❓ Question bank · 📖 Glossary · 📚 References · ✏️ Contributing
🏠 Home · 🗺️ Curriculum · 🧭 Learning paths
❓ Question bank · 📖 Glossary · 📚 References
Jump to module:
01 02 03 04 05 06 07 08 09 10 11 12
13 14 15 16 17 18 19 20 21 22 23 24