6.5.4 · D4Research Frontiers & Practice

Exercises — Self-supervised and contrastive learning (SimCLR, CLIP)

2,126 words10 min readBack to topic

A quick reminder of the two tools we will use over and over, stated in plain words:


Level 1 — Recognition

Problem 1.1 (L1)

Classify each training setup as supervised, unsupervised, or self-supervised: (a) A model predicts the rotation angle applied to an unlabelled image. (b) A model is trained on images each tagged by a human with "cat" or "dog". (c) A model groups 10,000 unlabelled images into clusters, no target given.

Recall Solution 1.1

(a) Self-supervised — the rotation angle is a pseudo-label the data generated itself (a pretext task). (b) Supervised — human labels. (c) Unsupervised — finds structure with no labels or pseudo-labels. See Supervised learning fundamentals and Representation learning.

Problem 1.2 (L1)

In SimCLR, a batch has real images. How many augmented views are created, and how many negatives does each view see?

Recall Solution 1.2

Each image is augmented twice, so views . For any anchor view, everything except itself and its one positive partner is a negative:


Level 2 — Application

Problem 2.1 (L2)

Two normalized embeddings point as and (both length 1). Compute and describe the geometry.

Recall Solution 2.1

Dot product . Lengths are both , so . Geometrically the arrows are perpendicular (90°) — see the right-angle pair in the figure above. Zero similarity = "the model considers these unrelated." Related idea: Metric learning and embedings.

Problem 2.2 (L2)

An anchor has cosine similarity with its positive and with each of three negatives. With temperature , compute the InfoNCE loss .

Recall Solution 2.2

Divide each similarity by (i.e. multiply by 2): positive logit , each negative logit . (natural log). A loss near means the model already assigns probability to the right partner.

Problem 2.3 (L2)

Recompute Problem 2.2 but with . Does the loss go up or down? Explain in one line.

Recall Solution 2.3

Divide by (multiply by 10): positive logit , negatives each. Loss dropped sharply. Smaller sharpens the softmax, so a modest similarity gap ( vs ) becomes a huge probability gap — the model looks far more confident.


Level 3 — Analysis

Problem 3.1 (L3)

Two embeddings are not normalized: , . Show that raw dot product and cosine similarity tell different stories, and say which one contrastive learning uses and why.

Recall Solution 3.1

Dot product — large, but that mostly reflects lengths (, ). Cosine similarity is exactly : the arrows point the same direction (). Contrastive learning uses cosine so that "meaning = direction," not magnitude — otherwise a model could cheat by simply scaling embeddings longer to inflate similarity. See Representation learning.

Problem 3.2 (L3)

In SimCLR with batch , each sample contrasts against how many negatives? Why does the paper push batch size so high, and what breaks if the batch is tiny (say )?

Recall Solution 3.2

Negatives . Large batches supply a rich, diverse set of negatives, so the softmax denominator samples many hard comparisons — a strong learning signal. With you get only negatives; the task "pick the right partner out of 3" is nearly trivial, gradients are weak, and representations collapse toward being unable to separate classes. This is why SimCLR needs 4096–8192 (and large-batch tricks from Batch normalization and training techniques).

Problem 3.3 (L3)

Given the similarity matrix below (rows = images, columns = captions), CLIP wants the diagonal to dominate. Compute the image-to-text loss for row 1 with .

Recall Solution 3.3

Row 1 logits: , , . With : The diagonal being higher than off-diagonals gives a low per-row loss — exactly what CLIP's row-wise softmax rewards. See Multi-modal learning.


Level 4 — Synthesis

Problem 4.1 (L4)

Design the CLIP total loss for a batch of with similarity matrix (temperature ): Compute , , and .

Recall Solution 4.1

Image-to-text (softmax across each row): Row 1: . Row 2: same by symmetry . Average .

Text-to-image (softmax down each column): is symmetric, so columns match rows and .

Both directions agree because is symmetric — a clean illustration of the "symmetric dance."

Problem 4.2 (L4)

You have image . Sketch (in words + one formula chain) the full SimCLR forward path for one view, from raw image to the vector on which loss is computed. Name every function and space, and explain why the projection head exists.

Recall Solution 4.2

Chain: augment encode project.

  • : a random augmentation drawn from crop/color/blur (Data augmentation techniques).
  • : base encoder (ResNet or Vision transformers (ViT)) giving representation .
  • : small MLP projection head; loss is applied to , but is kept for downstream tasks (Transfer learning and fine-tuning).
  • Why the head? Empirically transfers better than . The head can absorb information useful only for the contrastive pretext task (e.g. invariance to exact color jitter) so that stays richer for classification. Loss on , transfer on .

Problem 4.3 (L4)

Explain how CLIP does zero-shot classification of a new image into classes {cat, dog, car} without any training on those labels. Give the exact scoring rule.

Recall Solution 4.3

Build a caption per class: "a photo of a cat", etc. Encode each with the text encoder to get . Encode the image with . Predict: The class whose caption embedding is closest in direction to the image embedding wins — no gradient step needed. This is exactly Zero-shot and few-shot learning powered by the shared embedding space.


Level 5 — Mastery

Problem 5.1 (L5)

Edge case — the collapse. Suppose an encoder maps every input to the same vector . Show what the InfoNCE loss becomes with one positive and negatives, and explain why the temperature/normalization does not save you, and what actually prevents collapse.

Recall Solution 5.1

If all embeddings are identical, every similarity is (each vector with itself, normalized). Every logit equals , so numerator and each of the denominator terms are all : This is a constant floor — for , . The loss is not zero, so gradients still exist pushing away from collapse; but the positive term gets no advantage over negatives, so a naive optimizer can sit near this plateau. What genuinely prevents collapse is that positives (augmented views) share content negatives don't, so a non-collapsed solution achieves loss below . Strong augmentation + many diverse negatives make that lower solution reachable.

Problem 5.2 (L5)

Limiting behaviour of . Take one positive with similarity and one negative with . Find and . Interpret each limit.

Recall Solution 5.2

  • : , so and . Tiny temperature makes the softmax infinitely sharp: any positive-negative gap becomes "perfect confidence," loss vanishes. Danger: overconfident, sensitive to noise.
  • : , so and . Huge temperature flattens the softmax to a uniform guess — the model can't tell positive from negative, maximal confusion (for one negative, chance , loss ). This is why practical : sharp enough to learn, not so sharp it overfits noise.

Problem 5.3 (L5)

Full worked InfoNCE with the parent's numbers. From the parent's SimCLR example: anchor cat₁ has positive cat₂ with , and six negatives with similarities , . Compute exactly.

Recall Solution 5.3

Multiply every similarity by : positive logit ; negative logits . This matches the parent note's "" estimate (it rounded the negative sum). Exact value .


Recall Self-test recap

Cosine similarity ignores what and keeps what? ::: Ignores magnitude, keeps direction (angle). Where does the positive term appear in InfoNCE? ::: In BOTH numerator and denominator. Negatives per SimCLR anchor for batch ? ::: . Which vector transfers downstream in SimCLR, or ? ::: (before the projection head). As with a positive-negative gap, the loss tends to? ::: (infinitely sharp softmax). CLIP's zero-shot rule? ::: Pick the class whose caption embedding has max cosine similarity to the image embedding.