Exercise: contrastive learning

Goal

By the end of this exercise you should be able to:

  • compute the InfoNCE loss of a small batch by hand, and say what the temperature does,
  • predict which property of an image the features will ignore, from the augmentations,
  • explain collapse and why the negatives prevent it,
  • name the pitfalls: false negatives, batch effects, a low loss that means nothing,
  • derive the gradient of InfoNCE and of the normalisation (math).

The questions under By hand and Explore are for everyone. The Math questions (derive, prove) are for students who want the full treatment.

Background

Word Meaning
View a randomly augmented copy of an image (rotated, shifted, brightened, noisy, …)
Embedding the encoder’s output, scaled to length 1; similarity = dot product = cosine
Positive pair the two views of the same image; every other view in the batch is a negative
InfoNCE for each view, a softmax over the similarities / τ to all views of the other set; loss −ln p(partner)
Temperature τ divides the similarities: small τ = sharp softmax, large τ = flat
Collapse every image gets the same embedding: the views agree perfectly, and nothing is learnt

By hand

B1. Three unit embeddings \mathbf a = (0.6, 0.8), \mathbf b = (0.8, 0.6), \mathbf c = (-0.6, 0.8). Compute the three cosine similarities. Which two are the most alike?

B2. A view has cosines 0.9 with its partner and 0.1 and -0.5 with two other views. (a) τ = 0.5: compute the scores, the softmax probabilities and the loss -\ln p_\text{partner}. (b) τ = 0.1: the same. Why is the loss almost 0? (c) In the gradient, each negative pushes with the weight p_j. How much harder does the closer negative push than the farther one, at τ = 0.5 and at τ = 0.1?

B3. (a) All N embeddings are the same vector. What is the InfoNCE loss? Evaluate it for N = 3 and N = 64. (b) The loss “only pull the views together”, -\text{mean}\cos(\mathbf z_i, \mathbf z_i'): what is it for the same collapsed embeddings? What does this tell you?

B4. Which augmentations would you use, and which would you avoid, to learn features for: (a) telling mitotic from interphase cells in a nuclear stain recorded with different exposure times; (b) comparing the expression level of a fluorescent reporter between conditions; (c) the direction in which cells migrate, from phase-contrast images?

B5. A batch of 64 cells, about a third of each of three phenotypes. For one cell, roughly what fraction of its 63 negatives have the same phenotype? What does the loss do with them?

B6. Training curves: a run without any augmentation reaches a loss of 2.46, a run with strong augmentations 3.34 (64 cells, τ = 0.2). Which encoder gives the better features? What does the loss value tell you?

B1. \mathbf a\cdot\mathbf b = 0.48 + 0.48 = 0.96; \mathbf a\cdot\mathbf c = -0.36 + 0.64 = 0.28; \mathbf b\cdot\mathbf c = -0.48 + 0.48 = 0. \mathbf a and \mathbf b are the most alike (16° apart); \mathbf b and \mathbf c are at right angles.

B2. (a) Scores 1.8, 0.2, -1.0; e^{1.8} = 6.05, e^{0.2} = 1.22, e^{-1} = 0.37, sum 7.64; probabilities 0.792, 0.160, 0.048; loss -\ln 0.792 = 0.233. (b) Scores 9, 1, -5: the partner’s e^9 = 8103 dwarfs e^1 = 2.7 and e^{-5} = 0.007: p = 0.99966, loss 0.0003. Once the partner is clearly the closest, a small τ is satisfied. (c) τ = 0.5: 0.160/0.048 = 3.3 times harder. τ = 0.1: 3.4\cdot10^{-4}/8\cdot10^{-7} \approx 400 times: at small τ only the hardest negatives matter.

B3. (a) Every score is the same, every probability 1/N: loss \ln N, \ln 3 = 1.10 and \ln 64 = 4.16: the worst possible value, the same as guessing. (b) -1, the best possible value. Pulling alone rewards collapse; the negatives (the denominator) make it the worst solution.

B4. (a) Rotations, flips, shifts, blur, noise, and intensity gain (exposure must not matter); mitosis is visible in the shape of the chromatin. (b) Geometric augmentations and noise, but no intensity augmentation: intensity is the readout; also no per-image normalisation. (c) No rotations or flips (the direction is the answer); shifts, intensity, noise and blur are fine.

B5. About 21/63 \approx 1/3 (one third minus the cell itself). They are false negatives: the loss pushes them away from the cell as if they were different. It still works because each cell’s partner is pulled much harder, but cells of one phenotype are spread out more than they need to be.

B6. The augmented run: without augmentation the two views are identical, the task is trivial and is solved by any pixel detail (in the demo: shape 58 % against 100 %). The loss value only says how well the network solves the made-up task, which depends on the augmentations, the batch size and τ; it says nothing about how useful the features are. Evaluate the features with a probe or nearest neighbours.

Math questions

B7. (math) With \mathcal L_i = -s_{ii} + \ln\sum_j e^{s_{ij}}, s_{ij} = \mathbf z_i^\top\mathbf z_j'/\tau, show that \partial\mathcal L_i/\partial\mathbf z_i = \frac1\tau\big(\sum_j p_{ij}\mathbf z_j' - \mathbf z_i'\big) and \partial\mathcal L_i/\partial\mathbf z_j' = \frac1\tau(p_{ij} - [i = j])\mathbf z_i.

B8. (math) Show that for unit vectors the InfoNCE loss of one anchor is at least \ln\big(1 + (N - 1)e^{-2/\tau}\big), and that collapse gives exactly \ln N. What is the lower bound for N = 64, τ = 0.2? Why can the demo’s loss not reach it?

B9. (math) \mathbf z = \mathbf u/\|\mathbf u\|. Show that the Jacobian is \partial\mathbf z/\partial\mathbf u = (I - \mathbf z\mathbf z^\top)/\|\mathbf u\|, so that \partial\mathcal L/\partial\mathbf u = (\mathbf g - \mathbf z(\mathbf z^\top\mathbf g))/\|\mathbf u\| for \mathbf g = \partial\mathcal L/\partial\mathbf z. Why does a gradient along \mathbf z do nothing?

B7. (math) \partial\mathcal L_i/\partial s_{ij} = p_{ij} - [i = j] (softmax and cross-entropy, as in the backprop unit). s_{ij} depends on \mathbf z_i through \mathbf z_j'/\tau and on \mathbf z_j' through \mathbf z_i/\tau. Chain rule: \partial\mathcal L_i/\partial\mathbf z_i = \sum_j (p_{ij} - [i = j])\mathbf z_j'/\tau, and \partial\mathcal L_i/\partial\mathbf z_j' = (p_{ij} - [i = j])\mathbf z_i/\tau.

B8. (math) \mathcal L_i = \ln\big(1 + \sum_{j\neq i} e^{s_{ij} - s_{ii}}\big) and s_{ij} - s_{ii} \geq (-1 - 1)/\tau = -2/\tau, because cosines lie in [-1, 1]. Equality needs the partner at cosine 1 and every negative at cosine −1. Collapse: all s_{ij} = 1/\tau, loss \ln N. For N = 64, τ = 0.2: \ln(1 + 63e^{-10}) = 0.0029. On a circle, 64 cells cannot all be opposite one another: most negatives must be near each embedding, and the loss stops at about 2.46 (no augmentation) or higher.

B9. (math) \partial z_k/\partial u_l = \delta_{kl}/\|\mathbf u\| - u_k u_l/\|\mathbf u\|^3 = (\delta_{kl} - z_k z_l)/\|\mathbf u\|. So \partial\mathcal L/\partial\mathbf u = (I - \mathbf z\mathbf z^\top)\mathbf g/\|\mathbf u\|. If \mathbf g = c\mathbf z: (I - \mathbf z\mathbf z^\top)c\mathbf z = c(\mathbf z - \mathbf z) = 0. A change of \mathbf u along \mathbf z only changes the length, which the normalisation removes.

Explore: views pulled together, pushed apart

64 synthetic cells (round, elongated, or a dividing pair, at any orientation and brightness) are embedded on the unit circle by a tiny encoder (256 pixels → 16 → 2), trained with InfoNCE on two new random views of every cell at each step. Big dots: the clean cells; small dots joined by a line: the two views of the last step. The colours are labels the training never sees; the readout scores the embedding by leave-one-out 5-nearest-neighbour accuracy. train 600 steps takes a few seconds.

E1. Preset all augmentations: shape survives. Before training, read the loss of the first step and compare with \ln 64. Train 600 steps. Describe the embedding, coloured by shape and then by brightness. Read the two accuracies.

E2. Preset no brightness augmentation. Train, colour by brightness, then by shape. What has the network learnt now, and why?

E3. Preset no augmentation: trivial. Train. What happens to the loss, and how are the cells arranged? Compare the shape accuracy with E1.

E4. Preset no negatives: collapse. Train and describe what happens. Then, in the same preset, switch the negatives on and train another 600 steps: does the embedding recover?

E5. Presets τ = 1: a weak push and τ = 0.05. Compare the arrangement, the accuracies and the length of the mean embedding with E1 (τ = 0.2).

E6. Back to E1’s preset, but lower the augmentation strength to 0.3 before training. What changes in the views (thumbnails), the accuracies and the loss? Which property comes back, and why?

E1. The first loss is close to \ln 64 = 4.16: an untrained network cannot tell the partner apart (the curve starts near 4.2). After 600 steps the loss is about 3.34; the cells form three tight clusters, one per shape: shape accuracy 100 %. Coloured by brightness, every cluster is mixed: 64 % (chance 50 %). Length of the mean embedding 0.52.

E2. Coloured by brightness, the circle is ordered from dim to bright (brightness accuracy 95 %); coloured by shape it is mixed (83 %). Without the gain augmentation, brightness is a property that survives every view and differs between cells: the easiest way to find the partner among 64, so the network uses it.

E3. The loss drops at once to about 2.46 and stays there: the two views are identical, so finding the partner is trivial. The cells spread evenly around the circle (mean length 0.00) in an order set by pixel details: shape accuracy 58 % against 100 % with augmentations. The lowest loss gives the worst features.

E4. All cells move into one point: the loss is −1 (perfect agreement), the mean length 1.00, and the accuracies are meaningless (33 % for shape: all neighbours are tied). With the negatives switched on again, the push spreads the cells out and the clusters come back: after 200 more steps shape accuracy is 100 % again (mean length 0.68), after 600 the embedding looks like E1 (0.53). The network was not destroyed, only squeezed.

E5. τ = 1: the clusters are looser and overlap (shape 73 %, brightness 78 %, mean length 0.35): every negative pushes about as much as every other, and the pull is weak. τ = 0.05: shape still 100 %, but the cells crowd into one part of the circle (mean length 0.84) and the curve is jumpier: only the nearest negatives push, very hard.

E6. The views look much more like the original (the thumbnails): rotations of at most ±54°, gains between 0.7 and 1.4. The shape clusters are still clean (100 %), but brightness comes back: 91 % instead of 64 %, the cells are spread around the whole circle (mean length 0.15) and the loss ends lower (2.96). A gain of at most 1.4 is too small to hide a brightness range of 0.35 to 1: weak augmentations leave the property in.

Code

Write the algorithms of this unit yourself, in Rust. Setup, and how to run and check your code: coding exercises: getting started. Your code goes in selfsup/src/contrastive/exercise.rs.

Embeddings are Vec<f32> of length 1; a batch is a Vec of them: a[i] and b[i] are the two views of image i.

C1. dot(a, b): the dot product. The check is B1.

C2. info_nce(a, b, tau): the loss in one direction, and the probabilities.

for every i:
    s[j] = dot(a[i], b[j]) / tau  for all j
    p[i][j] = exp(s[j] − max s) / sum over k of exp(s[k] − max s)
    loss += −ln p[i][i]
loss = loss / n

The checks are B2 and B3(a).

C3. info_nce_grad(a, b, tau): the gradients with respect to all a[i] and all b[j] (B7): g = (p[i][j] − [i = j]) / (n · tau), add g · b[j] to grad_a[i] and g · a[i] to grad_b[j]. The check compares with finite differences.

C4. unit_backward(u, dz): the gradient back through the normalisation (B9): (\mathbf g - \mathbf z(\mathbf z^\top\mathbf g))/\|\mathbf u\|.

Then cargo run -p selfsup -- contrastive and open the pictures in out/contrastive/. The program trains the toy of the demo (its own random numbers) with your loss and gradients, 600 steps, in four settings, and prints the loss at the start and the end, the 5-NN accuracies for shape and brightness, and the length of the mean embedding.

C5. Compare “all augmentations” with “no brightness augmentation”. Which property does each embedding keep? Look at the pictures (coloured by shape).

C6. “No augmentation”: compare its final loss and its shape accuracy with “all augmentations”. What does this say about using the loss to choose a method?

C7. “No negatives”: what are the final loss and the length of the mean embedding? Explain with B3.

The model solution is selfsup/src/contrastive/solution.rs in the download.

C5. All augmentations: shape 100 %, brightness 59 % (chance 50 %): three clusters by shape, brightness forgotten. Without the brightness augmentation: shape 84 %, brightness 75 %: the embedding now keeps brightness and loses part of the shape. (The demo’s run gives 100 / 64 % and 83 / 95 %; the random views differ, the pattern is the same.)

C6. No augmentation ends at 2.464, the lowest loss of all (all augmentations: 3.339), but its shape accuracy is the worst of the trained ones with negatives (66 %). With identical views the task is trivial; the loss measures the made-up task, not the features.

C7. −1.000 and 1.00: every cell has the same embedding, the views agree perfectly (B3b), and the accuracies are those of a tie (59 % and 56 %, meaningless).

Where this leads

The next unit removes the negatives (and with them the false negatives and the need for big batches) with a student, a teacher and a moving average, and looks at the large pretrained models built this way. The same “pull towards the real samples, push away from the others” field returns, in a generative model, in the drifting unit of the diffusion day.