Sub topic 8
Contrastive learning and in-batch negatives
This chapter assumes you know what a dual encoder is, that embeddings are L2-normalized vectors, and that cross-entropy over softmax logits trains a classifier. The next chapter derives the symmetric loss step by step. This chapter covers the idea behind it: what a contrastive objective asks of the model, where the negative examples come from, and what goes wrong with them in practice.
What "contrastive" means
A contrastive objective doesn't ask the model to predict a label or to reconstruct an input. It asks the model to arrange embeddings so that pairs that belong together score higher than pairs that don't.
Each training example is an anchor with one positive: an image and its own caption. Every other pairing of that anchor is a negative. The model never learns what "dog" means as a category. It learns that this image should be closer to this caption than to the other captions it sees alongside it.
This is why the training data needs no class labels. A web caption is a weak label, but it identifies a positive pair, and that is all the objective requires.
Where the negatives come from
An explicit negative sampler would need a separate pool of captions, extra encoder passes, and a way to choose them. CLIP avoids this by using the other items in the same batch.
Take a batch of B image-text pairs. The encoders produce B image embeddings and B text embeddings. Multiplying them gives a B x B similarity matrix. Entry (i, j) is the similarity between image i and text j.
- The diagonal entries (i, i) are the B positive pairs.
- Every off-diagonal entry is a negative pair. Each image has B - 1 negative texts, and each text has B - 1 negative images.
These are called in-batch negatives. They cost almost nothing, because the embeddings were already computed for the positives. The only added work is one matrix multiplication.
Turning the matrix into a classification problem
Read one row of the matrix. Image i is compared with B texts, and exactly one of them is correct. That is a B-way classification problem whose correct class index is i. Softmax cross-entropy over the row trains the model to give the matching caption the highest score.
Read one column and you get the same problem in the other direction: given text j, pick the right image among B. CLIP averages both directions, which is why the loss is called symmetric. The code is in the previous reference implementation (clip_loss). The point here is that the label for every row is simply its own index, torch.arange(B).
Two consequences follow from this view.
- The task gets harder as B grows, because each anchor must beat more distractors. Random embeddings would score 1/B accuracy.
- The loss is only informative if the negatives are real negatives. The next sections cover both points.
Seeing the effect of batch size
The script below builds synthetic paired embeddings. Each pair shares a hidden "concept" vector plus independent noise. It then measures how often each image's best-scoring text is the right one. The noise level is fixed, so any change in accuracy comes from the number of distractors.
import torch
import torch.nn.functional as F
torch.manual_seed(0)
def in_batch_stats(image_emb, text_emb):
image_emb = F.normalize(image_emb, dim=-1)
text_emb = F.normalize(text_emb, dim=-1)
sim = image_emb @ text_emb.t() # (B, B)
b = sim.size(0)
labels = torch.arange(b)
acc = (sim.argmax(dim=1) == labels).float().mean().item()
pos = sim.diag().mean().item()
neg = (sim.sum() - sim.diag().sum()).item() / (b * b - b)
return acc, pos, neg
dim = 64
for batch in (8, 64, 512, 4096):
concept = torch.randn(batch, dim)
image_emb = concept + 0.8 * torch.randn(batch, dim)
text_emb = concept + 0.8 * torch.randn(batch, dim)
acc, pos, neg = in_batch_stats(image_emb, text_emb)
print(f"B={batch:5d} top-1={acc:.3f} mean pos={pos:.3f} mean neg={neg:.3f}")The mean positive similarity stays roughly constant, and the mean negative similarity stays near zero. Top-1 accuracy falls as B grows, because the model must separate each positive from more negatives. A larger batch therefore gives a stricter training signal from the same encoders.
Why large batches help, and what they cost
With more negatives per anchor, the model sees more of the ways a caption can almost fit an image. It also has to learn finer distinctions, such as telling "a husky" from "a wolf" when both appear in the batch. CLIP trained with a batch of 32,768 pairs.
| Batch size B | Negatives per anchor | Similarity matrix entries | Chance top-1 |
|---|---|---|---|
| 256 | 255 | 65,536 | 0.39% |
| 4,096 | 4,095 | 16,777,216 | 0.024% |
| 32,768 | 32,767 | 1,073,741,824 | 0.003% |
The matrix grows with B squared. In half precision, a 32,768 x 32,768 matrix takes about 2 GB, and the gradient needs the same again. Real implementations avoid materializing it on one device. Each GPU computes embeddings for its slice of the batch, gathers the embeddings from all other GPUs, and computes only its own rows of the matrix.
Large batches also change how you tune training. Learning rate, warmup, and the temperature interact with B. A recipe that works at B = 32,768 may behave poorly at B = 512, and reducing the batch can hurt the final model even if you train longer.
False negatives
The objective assumes that every off-diagonal pair is a non-match. Web data breaks this assumption in three ways.
- Two images in a batch may both show a golden retriever on grass, each with a caption like "a dog in the park". Image A is then scored against caption B as a negative, although it describes image A just as well.
- Duplicate or near-duplicate pairs end up in the same batch.
- Very generic captions such as "photo" or "image" match almost anything.
The loss then pushes apart pairs that should be close. A bigger batch makes this more likely, because the chance of a semantically matching item grows with B. CLIP's loss does nothing about it. The model's noise tolerance and the diversity of the data keep it manageable.
If you train on a narrow dataset, you can mask known false negatives when you have a group ID, such as a product or class ID, for each example.
import torch
import torch.nn.functional as F
def masked_clip_loss(image_emb, text_emb, logit_scale, group_ids):
# group_ids: (batch,) integer tensor; equal ids mean "same concept"
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()
same_group = group_ids[:, None] == group_ids[None, :]
eye = torch.eye(logits.size(0), dtype=torch.bool, device=logits.device)
ignore = same_group & ~eye # same concept but not the labeled pair
logits = logits.masked_fill(ignore, float("-inf"))
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) / 2Setting a logit to negative infinity gives it zero softmax probability, so that pair contributes no gradient. The diagonal is never masked, so each row keeps its positive. This is an extension for curated data, not part of the original CLIP recipe.
Common errors
- Unnormalized embeddings. Without normalization, the model can lower the loss by growing vector lengths instead of improving direction. Normalize before the matrix product.
- Wrong labels after shuffling. The labels
arange(B)are valid only if image i and text i in the batch are a pair. If you shuffle the text tensor alone, every pair becomes a negative and the loss never drops. - Computing the loss on a tiny batch. Evaluating or debugging with B = 4 gives a loss that looks easy and says little about the training regime. Compare runs at the same B.
- Comparing losses across batch sizes. A loss of 2.0 at B = 64 and 2.0 at B = 4096 mean different things, since a random model scores log B in each case.
Exercise
A model scores random guesses on a contrastive task with batch size B = 1,024. What cross-entropy loss do you expect per direction at initialization, and why does doubling the batch to 2,048 raise it?
Show answer
With random, uninformative logits, every one of the B candidates gets equal probability 1/B, so the cross-entropy is log B. For B = 1,024 that is ln(1024), about 6.93. Doubling B to 2,048 gives ln(2048), about 7.62. The loss is higher because the correct item must be picked from twice as many candidates, so the task is harder even though the model is unchanged.