6.5.4 · D3Research Frontiers & Practice

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

2,868 words13 min readBack to topic

This page is the "plug-in-the-numbers" companion to the parent topic. There we built the ideas: positive pairs pulled together, negative pairs pushed apart, the InfoNCE loss that scores it all. Here we grind through every kind of situation that loss can face — every sign of similarity, the perfect and the disastrous cases, the degenerate zero-negative case, the temperature limits, a real-world word problem, and an exam twist.

Before we start, one promise: we define every symbol on its first appearance, even ones the parent used. If a line uses a letter you have not met on this page, that is a bug.

Ground vocabulary (earn every symbol)

Two more words we will lean on in every example — logit and softmax — defined now so no example uses them cold:

The one-anchor InfoNCE loss we score all page long — every symbol in it (, , , , , ) was just defined above:

To keep the tables and examples short, we abbreviate the two similarities we care about:

The scenario matrix

Every situation contrastive loss can face reduces to a combination of: how similar the positive is (), how similar the worst negative is (), how many negatives there are (), and how sharp is. Here is the full grid — each example below is tagged with the cell it hits. In the " / #negatives" column, #negatives means , the count defined above.

Cell Positive sim Negative sims / #negatives What it tests
A Ideal high () low () normal , best-case loss near 0
B Confused medium one negative higher than positive normal , loss when a distractor wins
C Negative sim positive a negative with (opposite arrows) normal , the full range
D Degenerate any zero negatives () any , what happens with no contrast
E fixed gap fixed tiny, hard-negative limit
F fixed gap fixed huge, soft / uniform limit
G Word problem CLIP zero-shot pick a class from captions
H Exam twist symmetric matrix CLIP i2t + t2i full batch loss both directions

Cells A, B, C, D, E, F, G, H are each covered below.


Worked examples

Steps:

  1. Divide every similarity by (i.e. multiply by ). Why this step? sets the scale before the exponential; skipping it changes the answer entirely. We get logits (positive) and (negatives).
  2. Exponentiate each logit. ; ; ; . Why? turns similarities into positive "scores" so the softmax fraction reads as a probability.
  3. Form the probability of the positive. Numerator ; denominator . Probability . Why? This fraction is the softmax probability the model assigns to "the positive is the match."
  4. Take . . Why? Loss is the surprise of the correct choice; low surprise = low loss.

Verify: probability ✓; loss and modest ✓. Sanity: a perfect would give ; we are close-ish, consistent with a strong but not overwhelming lead.


Steps:

  1. Scale by : logits (positive), , (negatives). Why? Same reason — temperature first.
  2. Exponentiate: , , . Why? Convert to scores.
  3. Positive probability: . Why? The hard negative dominates the denominator, stealing probability mass.
  4. : . Why? High surprise → high loss → big gradient pushing that distractor away.

Verify: from Example 1 ✓ — being fooled costs more, exactly as it should. Probability means the model would not pick the positive if forced to guess ✓.


Steps:

  1. Scale by : logits , , . Why this step? Note a negative similarity gives a negative logit — of it will be tiny, contributing almost nothing.
  2. Exponentiate: , , . Why? See how the opposite-pointing negative () barely matters — that is cosine's full range doing useful work.
  3. Positive probability: . Why? This fraction is the InfoNCE numerator over its denominator — the softmax probability the model assigns to the positive being the match, exactly the fraction inside the of the loss formula.
  4. : . Why? The InfoNCE loss is of that probability; taking the negative log converts "high probability of the right choice" into "low loss," completing the formula.

Verify: (Example 1) ✓ — having a strongly repelled negative helps, because it barely competes. Cosine handled without any special case ✓.

Figure — Cell C geometry. The picture below draws the anchor (navy) and the three candidate arrows: the positive at cosine (violet), the perpendicular negative at cosine (orange), and the nearly-opposite negative at cosine (magenta). Beside each arrow is its contribution — watch the magenta arrow's contribution collapse to , which is why an opposite-pointing negative barely competes in the denominator.

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

Steps:

  1. Write the fraction with an empty sum. The denominator is . Why this step? An empty sum equals ; the denominator collapses to just the numerator.
  2. Simplify. Numerator denominator , so the fraction . Why? There is nothing to steal probability, so the positive gets all of it.
  3. . Why? Zero surprise. But learning stalls: the gradient is , the encoder can output anything.

Verify: independent of and , ✓. Mistake alert below — this is why SimCLR needs large batches: with negatives the loss is uninformative.


Steps:

  1. Write the probability. . Why this step? Dividing top and bottom by isolates the gap .
  2. Take . Then , so , giving . Why? A positive gap divided by a vanishing explodes; the exponential of vanishes.
  3. So . Why? With infinite sharpening, any lead of the positive becomes a certain win.

Numeric taste at : , .

Verify: as shrinks drops toward ✓. Caveat: this only helps if the positive actually leads; if a negative led, the same sharpening would drive loss to (the danger of small ).


Steps:

  1. Use from Example 5. Why? Same algebra, different limit.
  2. Take . Then , , so . Why? Infinite temperature erases the similarity gap; all candidates look equal.
  3. . Why? With equally likely candidates, the loss is the entropy of a fair coin.

Numeric taste at : , .

Verify: ✓. General rule: as with total candidates, , where is the total number of candidates (positive plus negatives). Here .


Steps:

  1. Scale by : logits . Why this step? CLIP's tiny temperature turns small cosine gaps into large logit gaps — that is how it makes crisp decisions.
  2. Exponentiate each logit (subtract the max first for numerical stability): , , . Why subtract the max? Softmax is unchanged if we shift all logits by a constant (the shift cancels top and bottom), but it prevents from overflowing.
  3. Form the probability of the cat caption (softmax over the three captions): . Why? This is InfoNCE with the correct caption as the positive and the other two captions as negatives — the softmax probability is the zero-shot classification confidence.
  4. Take for the loss / read off the answer. Predict cat; the associated loss would be . Why? The of the positive's probability is the InfoNCE loss; a near- probability means near- loss and a confident, correct prediction.

Verify: probabilities sum to ✓; cat's cosine lead logit gap gives -to- odds over dog, matching ✓. This is exactly transfer with no fine-tuning — pure zero-shot.


Steps:

  1. Image→text: softmax each ROW, keep the diagonal. Row 1: . Row 2: . Why rows? Image-to-text asks "for this image, which caption?" — that is a softmax distribution across captions = across the row, with the diagonal entry as the positive logit.
  2. . Why average? Each image contributes one InfoNCE term ( of its positive's probability); we mean over the images.
  3. Text→image: softmax each COLUMN, keep the diagonal. Col 1: . Col 2: . Why columns? Text-to-image asks "for this caption, which image?" — a softmax distribution down the column, again with the diagonal as positive. 3.5. (same numbering intent)
  4. . Why? Average the two column-wise InfoNCE surprises, one per caption.
  5. Total: . Why symmetric? Both directions give gradient, so neither modality is ignored (see parent note).

Verify: , , total ✓, inside the forecast band. Note because rows and columns of differ — a healthy check that the two directions really are distinct computations.


Recall

Recall What does an empty negative set do to InfoNCE loss?

Makes it exactly regardless of and — no learning signal (Cell D). ::: Loss , gradient , encoder unconstrained — a bug, not success.

Recall As

with total candidates, the loss approaches? ::: — the uniform "everyone equal" loss (Cell F).

Recall In CLIP, image→text uses a softmax over rows or columns?

Rows ::: Rows — each image is normalized across all candidate captions.

Compare-and-connect: the row/column duality here is the batch-level cousin of metric learning; the augmentation-driven positives of SimCLR come from data augmentation; and the encoders behind and are ViT and Transformers.