Skip to content

Module 17

Anurag Prasad edited this page Nov 8, 2026 · 8 revisions

Module 17 — Self-Supervised, Contrastive and Metric Learning

⬅️ 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


Overview and learning goals

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.

Beginner: the big picture

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
Loading

Figure 17.1 — SimCLR-style pipeline (after Chen et al. 2020). Original diagram.

Core concepts and derivations

Pretext tasks

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.

Positive and negative pairs, metric learning

Pair loss (Hadsell et al. 2006): $y,d^2+(1-y)\max(0,m-d)^2$. Triplet loss (FaceNet, Schroff et al. 2015): for anchor $a$, positive $p$, negative $n$: $\ L=\max\bigl(0,\ d(a,p)-d(a,n)+m\bigr)$, which requires hard-negative mining to be effective. Siamese networks share weights between branches (Bromley et al. 1993). Embeddings are usually $\ell_2$-normalised so similarity is cosine.

InfoNCE / NT-Xent loss

For an anchor $\mathbf{z}_i$ with its positive $\mathbf{z}_i^+$ and $N-1$ negatives $\mathbf{z}_k$, with similarity $s(\mathbf{u},\mathbf{v})=\mathbf{u}^\top\mathbf{v}/(\lVert\mathbf{u}\rVert\lVert\mathbf{v}\rVert)$ and temperature $\tau$:

$$ \mathcal{L}_i=-\ln\frac{\exp\bigl(s(\mathbf{z}_i,\mathbf{z}_i^+)/\tau\bigr)}{\exp\bigl(s(\mathbf{z}_i,\mathbf{z}_i^+)/\tau\bigr)+\sum_{k}\exp\bigl(s(\mathbf{z}_i,\mathbf{z}_k)/\tau\bigr)} . $$

This is exactly softmax cross-entropy where the "class" is which candidate is the true positive — an $N$-way classification. SimCLR's NT-Xent uses a batch of $2B$ views, treating the other $2B-2$ views as negatives.

Mutual-information bound (van den Oord et al. 2018): $I(\mathbf{x};\mathbf{c})\ge\ln N-\mathcal{L}_{\text{InfoNCE}}$, so minimising the loss maximises a lower bound on mutual information; the bound saturates at $\ln N$, so more negatives allow tighter bounds.

Temperature, batch size, hard negatives and sampling bias

Small $\tau$ sharpens the distribution and emphasises hard negatives (more discriminative but risks overweighting false negatives and unstable training); large $\tau$ treats all negatives alike. Uniformly sampled negatives may include same-class images (false negatives). Wang & Isola (2020) decompose the objective into alignment (positives close) and uniformity (embeddings spread over the hypersphere).

SimCLR, MoCo and CLIP

  • 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.

Non-contrastive methods and collapse

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.

Evaluation and transfer

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.

Worked example

Anchor with candidate cosine similarities $(0.9,,0.2,,0.1)$ — the first is the positive — and $\tau=0.5$: logits $(1.8,0.4,0.2)$; $\exp=(6.050,1.492,1.221)$; sum $=8.763$; $p_{+}=0.690$; $\mathcal{L}=-\ln0.690=0.371$. With $\tau=0.1$: logits $(9,2,1)$, $p_+\approx0.9988$, $\mathcal{L}\approx0.001$ — a sharper temperature lowers the loss on easy negatives; its gradient concentrates on the hardest negatives.

Bound: with $N=3$ candidates, $\ln3-\mathcal{L}=1.099-0.371=0.728$ nats lower-bounds the mutual information.

Implementation

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)

Advanced topics

  • 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).

Pitfalls and best practices

  • 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.

Conceptual questions and answers

Q1. Why is InfoNCE a classification loss?

It is softmax cross-entropy over $N$ candidates where the correct "class" is the true positive; logits are similarities divided by $\tau$.

Q2. What does temperature do?

It scales the logits: low $\tau$ sharpens the softmax, focusing gradients on hard negatives; high $\tau$ spreads weight over all negatives.

Q3. How does MoCo get many negatives with a small batch?

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?

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?

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.

$I(X;C)\ge\ln N-\mathcal{L}_{\text{InfoNCE}}$; it cannot exceed $\ln N$, so large $N$ is needed to capture large MI.

Q7. What are false negatives?

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?

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.

Sources and further reading

  • 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 ➡️

🎓 Deep Learning Hub

🏠 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

Part 1 · Mathematical foundations
Part 2 · Neural network fundamentals
Part 3 · Training deep networks
Part 4 · Core architectures
Part 5 · Representation and generative learning
Part 6 · Specialised, modern and responsible deep learning
Reference and meta

Clone this wiki locally