Sub topic 2
Training data: image-text pairs from the web
Prerequisites: This chapter assumes you can read basic Python and PyTorch tensor code, you know what softmax and cross-entropy loss do, and you understand that a neural network maps an input to a vector called an embedding.
Training data: image-text pairs from the web
CLIP (Contrastive Language-Image Pretraining) learns from image-caption pairs collected from the web. Each pair is an image and a caption written for it. Because the captions are free text, CLIP needs no hand-labeled class list. Each training batch holds N pairs, and row i of the image embeddings matches row i of the text embeddings.
Contrastive learning and in-batch negatives
Contrastive learning pulls matching pairs together in the embedding space and pushes mismatched pairs apart. CLIP gets its mismatched examples for free: every other caption in the batch is a negative for a given image. A batch of 256 pairs therefore gives each image 255 negatives without any extra sampling.
The symmetric contrastive loss, step by step
- Normalize each image and text embedding to length 1.
- Compute the N by N similarity matrix. Entry (i, j) compares image i with text j.
- Treat the diagonal as the correct match. Apply cross-entropy across each row (image to text) and each column (text to image).
- Average the two losses.
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) / 2The learned temperature (logit scale)
The similarities are multiplied by exp(logit_scale) before the softmax. This value acts as the inverse of a temperature. A large scale sharpens the softmax, so the model must separate close matches more strongly. CLIP stores the scale as a learned parameter, starts it near 14 (1/0.07), and caps it at 100.
Zero-shot classification with text prompts
To classify without training, wrap each class name in a template such as "a photo of a {label}". Encode the prompts, compare them with the image, and apply a softmax over the scaled similarities.
import torch
from PIL import Image
from transformers import CLIPModel, CLIPProcessor
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
image = Image.open("photo.jpg")
labels = ["cat", "dog", "car"]
prompts = [f"a photo of a {label}" for label in labels]
inputs = processor(text=prompts, images=image, return_tensors="pt", padding=True)
with torch.no_grad():
outputs = model(**inputs)
probs = outputs.logits_per_image.softmax(dim=1)
print(dict(zip(labels, probs[0].tolist())))Exercise
A batch holds 4 image-text pairs. How many negative captions does each image get in the loss, and why?
Show answer
Three. The other three captions in the batch are the negatives. The caption at the same index is the single positive, which sits on the diagonal of the similarity matrix.