Compute CLIP's symmetric image-text contrastive loss
CLIP-style training puts a batch of matching image and caption embeddings in one space. Each image should pick its own caption out of the batch, and each caption should pick its own image.
Write clip_loss(img, txt, temperature). img and txt are (n, d); row i of each is a matching pair. Steps:
1. L2-normalise every row of both.
2. logits = img_n @ txt_n.T / temperature, shape (n, n).
3. loss_i2t = mean cross-entropy of each row with target i (softmax over columns).
4. loss_t2i = mean cross-entropy of each column with target i (softmax over rows).
Return (loss_i2t + loss_t2i) / 2 as a float. Use a numerically stable log-softmax.
def clip_loss(img, txt, temperature)Example
img = txt = [[1, 0], [0, 1]], temperature 1. Each row is [1, 0] or [0, 1], so each cross-entropy is log(1 + e^-1) = 0.31326 and the loss is 0.31326.
Understand the idea
CLIP puts images and captions in one space. In a batch, image i should match caption i better than all others, and caption i should match image i better than all other images. You first L2-normalise every row so dot products become cosine similarities, divide by a temperature, then score both directions with cross-entropy. Worked example, temperature 1: img = [[3, 0], [0, 2]] normalises to [[1, 0], [0, 1]]; txt = [[1, 1], [0, 1]] normalises to [[0.7071, 0.7071], [0, 1]]. Logits = [[0.7071, 0], [0.7071, 1]]. Image to text (rows): row 0 loss log(1 + e^-0.7071) = 0.4008, row 1 loss 0.5574, mean 0.4791. Text to image (columns): column 0 is [0.7071, 0.7071], loss log 2 = 0.6931; column 1 is [0, 1], loss 0.3133; mean 0.5032. Final loss = (0.4791 + 0.5032) / 2 = 0.4912. Rule: logits = norm(img) @ norm(txt)^T / T, average of row cross-entropy and column cross-entropy with target i, using a stable log-softmax. This is the pretraining loss behind CLIP and many image search models.