Symmetric contrastive loss and its gradient with respect to the similarity matrix

HardLossesPro

Image-text models trained by contrast use a symmetric loss: each image must pick its own caption among all captions in the batch, and each caption must pick its own image. To write the backward pass by hand you need the gradient with respect to the similarity matrix.

Write clip_loss_and_grad(S, temperature) where S is an (n, n) similarity matrix (row i is image i, column j is text j; the matching pair is on the diagonal) and temperature > 0.
- L = S / temperature.
- loss_rows = mean over i of cross-entropy of row L[i, :] with target i.
- loss_cols = mean over j of cross-entropy of column L[:, j] with target j.
- loss = 0.5 * (loss_rows + loss_cols).
Return (loss as a float, dS as an (n, n) array of dloss/dS).
Use stable softmaxes: temperature can be 0.01 with entries of S up to 10.

Signaturedef clip_loss_and_grad(S, temperature)

Example

for n = 1 the loss is 0.0 and dS is [[0.0]].

Understand the idea

In contrastive image-text training each image must pick its own caption out of the whole batch, and each caption must pick its own image. That is a cross-entropy over each row of the scaled similarity matrix and another over each column, averaged. Since softmax cross-entropy has gradient softmax minus one-hot, the gradient has a neat form. Worked example: n = 2, S = [[1, 0], [0, 1]], temperature 1. Each row softmax is [0.7311, 0.2689], so each row loss is -ln 0.7311 = 0.3133; columns match by symmetry, so loss = 0.3133. Gradient: row part (P_row - I) / n gives -0.1345 on the diagonal and 0.1345 off it; the column part is the same, and their average keeps those values. Rule: L = S / tau; dL_rows = (row_softmax(L) - I) / n; dL_cols = (column_softmax(L) - I) / n; dS = 0.5 * (dL_rows + dL_cols) / tau. Forgetting the 1 / tau factor makes the gradient 100 times too small at tau = 0.01. Used in CLIP-style multimodal pretraining.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: n = 1clip_loss_and_grad([[0.7]], 0.1)
  • Sample 2: random 4x4 T=0.5clip_loss_and_grad(_S, 0.5)