Sub topic 8
Contrastive Learning and In-Batch Negatives
This chapter assumes basic PyTorch tensor operations, embeddings, softmax, and cross-entropy loss. It also assumes that you know CLIP uses one image encoder and one text encoder. Each encoder maps its input to a vector in the same space.
The contrastive learning objective
Contrastive learning trains a model by comparing examples. A matching image and caption form a positive pair. Other captions in the same batch act as negative examples for that image. The model learns to give the positive pair a higher similarity score than the negative pairs.
Suppose a batch contains \(N\) matching image-caption pairs. The image embeddings form a matrix \(I\) with shape \(N \times d\). The text embeddings form a matrix \(T\) with the same shape. After normalization, their dot product is cosine similarity:
S_{ij} = I_i \cdot T_jThe similarity matrix \(S\) has one row per image and one column per caption. The correct caption for image \(i\) is caption \(i\), so the target labels are the diagonal positions:
[0, 1, 2, \ldots, N-1]All other positions provide in-batch negatives.
The symmetric loss
CLIP uses two classification problems:
- Image-to-text: each image must select its matching caption.
- Text-to-image: each caption must select its matching image.
For image-to-text training, apply cross-entropy to each row of the similarity matrix. For text-to-image training, transpose the matrix and apply cross-entropy again. The final loss is their average.
A learned logit scale, often represented as logit_scale, multiplies the similarities before cross-entropy. Its exponential keeps the scale positive.
import torch
import torch.nn.functional as F
def clip_loss(image_emb, text_emb, logit_scale):
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()
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
batch_size, dimension = 4, 8
images = torch.randn(batch_size, dimension)
texts = torch.randn(batch_size, dimension)
loss = clip_loss(images, texts, torch.tensor(2.0))
print(loss.item())What makes negatives useful?
A larger batch supplies more negative captions and images without requiring extra labels. This usually makes the similarity task more informative. Distributed training can gather embeddings from several devices to increase the effective batch size.
However, an off-diagonal pair is not always truly negative. Two images may show dogs, or two captions may describe the same scene. Treating such a pair as incorrect can weaken training. Duplicate data, noisy captions, and semantically similar examples create false negatives.
| Choice | Benefit | Risk |
|---|---|---|
| Larger batch | More negative comparisons | Higher memory use and more false negatives |
| Higher logit scale | Sharper separation between pairs | Unstable or overconfident training |
| Symmetric loss | Trains both retrieval directions | Requires both modalities in every batch |
Exercise
In a batch of eight image-caption pairs, how many negative captions does each image compare against?
Show answer
Seven. The matching caption is the one positive, and the other seven captions are in-batch negatives.