Sub topic 9
The symmetric contrastive loss, step by step
This chapter assumes you know softmax and cross-entropy, can read PyTorch tensor code, and understand cosine similarity and normalized embeddings from earlier chapters. It builds CLIP's training loss from those pieces and then implements it.
The setup: a batch of pairs
CLIP trains on batches of N image-text pairs. Pair i is a real image with its real caption. The image encoder turns the N images into an N × D matrix of embeddings, and the text encoder does the same for the N captions.
The loss uses only the batch structure. It does not use class labels. The only supervision is that image i belongs with text i. Every other combination in the batch (image i with text j, where j ≠ i) is treated as a mismatch. These mismatches are called in-batch negatives. A batch of N pairs gives N matching pairs and N² − N negative pairs.
Step 1: Normalize
Each embedding is divided by its L2 norm, so every row has length 1. The dot product of two unit vectors is their cosine similarity, which lies in [−1, 1]. Normalizing removes vector length as a free variable. The model can only lower the loss by changing directions, not by making vectors longer.
Step 2: Build the similarity matrix
Multiply the normalized image matrix by the transposed text matrix:
S = I @ T.T shape (N, N)
S[i, j] = cosine(image_i, text_j)Row i holds the similarity of image i to every caption in the batch. Column j holds the similarity of caption j to every image. The diagonal holds the N matching pairs.
Step 3: Scale by the temperature
Cosine values live in [−1, 1]. A softmax over numbers in that range is nearly flat. For example, with N = 1000 and a true match at 0.3 against negatives near 0.0, the match gets a small probability and the loss gradient stays large forever. CLIP therefore multiplies the matrix by a scalar:
logits = exp(logit_scale) * SThe parameter logit_scale is learned. CLIP initializes it to log(1/0.07) ≈ 2.66, so the multiplier starts at about 14.3, and it clips the multiplier at 100. The next chapter covers the temperature in detail. For now, treat it as a sharpness knob for the softmax.
Step 4: Cross-entropy in two directions
Each row of logits is a vector of N scores. Apply softmax along the row to get a distribution over captions:
p(text j | image i) = exp(logits[i, j]) / sum_k exp(logits[i, k])The correct caption for image i is caption i. So the image-to-text loss is the average negative log-probability of the diagonal:
L_i2t = -(1/N) * sum_i log p(text i | image i)This is ordinary cross-entropy with the label vector [0, 1, ..., N-1]. It is also the InfoNCE loss: one positive and N − 1 negatives, scored by a softmax.
The matrix is read column-wise too. Softmax down column j gives a distribution over images for caption j:
L_t2i = -(1/N) * sum_j log p(image j | text j)Computationally this is cross-entropy on the transposed logits with the same labels. The final loss is the mean of the two:
L = (L_i2t + L_t2i) / 2That averaging is why the loss is called symmetric. Image-to-text asks, "Given this picture, which caption fits?" Text-to-image asks the reverse. Training on both pushes each matching pair together from both sides.
The whole computation in one picture
Implementation
import math
import torch
import torch.nn.functional as F
def clip_loss(image_emb, text_emb, logit_scale):
# image_emb, text_emb: (batch, dim); row i of each is a matching pair
image_emb = F.normalize(image_emb, dim=-1)
text_emb = F.normalize(text_emb, dim=-1)
logits = logit_scale.exp() * image_emb @ text_emb.t() # (batch, batch)
labels = torch.arange(logits.size(0), device=logits.device)
loss_i2t = F.cross_entropy(logits, labels)
loss_t2i = F.cross_entropy(logits.t(), labels)
return (loss_i2t + loss_t2i) / 2
torch.manual_seed(0)
n, dim = 8, 64
logit_scale = torch.tensor(math.log(1 / 0.07))
# Unrelated embeddings: the model cannot tell pairs apart.
random_loss = clip_loss(torch.randn(n, dim), torch.randn(n, dim), logit_scale)
# Perfectly aligned embeddings: text equals image.
img = torch.randn(n, dim)
aligned_loss = clip_loss(img, img.clone(), logit_scale)
print(f"random: {random_loss.item():.3f} aligned: {aligned_loss.item():.3f}")
print(f"chance level log(N) = {math.log(n):.3f}")The aligned loss comes out close to 0. The random loss comes out near or above log(N) = 2.079. Unrelated embeddings give a loss around log(N) because a uniform guess over N captions assigns each probability 1/N. With a scale of about 14, random noise can push the loss somewhat above that. Checking that a fresh model starts near log(N) is a quick sanity test for your training loop.
Details that matter
- Labels are the diagonal.
torch.arange(N)works because row i's correct column is i. If your data loader shuffles images and texts separately, the loss will still run but will train on wrong pairs. - The transposed call is not redundant. Softmax over rows and softmax over columns give different normalizers, so the two terms have different gradients.
- Batch size sets the difficulty. More negatives make the task harder and the gradient more informative. CLIP used a batch size of 32,768. Small batches work, but the loss is less demanding.
- Duplicate captions create false negatives. If two images in a batch share a near-identical caption, one of them is wrongly treated as a mismatch. Web-scale data makes this common for generic captions such as "a photo of a dog".
- Multi-GPU training needs gathered embeddings. Negatives only come from embeddings the loss can see. Real implementations gather embeddings from all devices before building the matrix. Computing the loss per device shrinks the effective batch.
- Numerical stability.
F.cross_entropyapplies log-softmax internally, so it handles large logits (up to 100 × 1) safely. Do not write softmax and log by hand.
Reading the loss as a classification problem
Each row is a classification problem with N classes, where the "classes" are the other texts in the batch. This is why the same trained model can later classify images zero-shot. At inference you replace the batch captions with prompts built from class names, and the same softmax picks the best-scoring one.
Exercise
A batch has N = 256 pairs and the model outputs identical, uninformative scores for every pair, so every row of the logits is constant. What value does each of the two cross-entropy terms take, and what is the total loss?
Show answer
Constant logits give a uniform softmax, so each probability is 1/256. Each cross-entropy term is -log(1/256) = log(256) ≈ 5.545. The average of the two identical terms is also log(256) ≈ 5.545, which is the chance-level loss.
Exercise
Why does the implementation call F.cross_entropy on logits.t() instead of reusing logits for both directions?
Show answer
Cross-entropy applies softmax along the last dimension. Using logits normalizes each row over the captions (image-to-text). Using logits.t() normalizes each column over the images (text-to-image). The two normalizers differ, so each term is a distinct loss with its own gradients.