Contrastive learning & CLIP
Learn embeddings from pairs: pull matching items (image and caption, query and answer) together and push everything else in the batch apart. CLIP did this for images and text, enabling zero-shot classification and cross-modal search.
Analogy: A seating chart learned at a party: couples keep being pushed to the same table and strangers to different ones, until where you sit says who you are.
How it works
- InfoNCE is cross-entropy over similarities: the positive is the correct class among N−1 negatives.
- A low temperature τ lets the hardest negatives dominate the gradient; too low makes training unstable.
- Other items in the batch are free negatives, so bigger batches help; mined hard negatives add the most signal.
- Zero-shot classification embeds prompts like "a photo of a {label}" and picks the one closest to the image.
- The same recipe trains text embedding models on query–passage pairs and powers text-to-image search.
Check yourself
Answer to mark it learned; your answers aren't scored.
You upgrade the CLIP text encoder that embeds search queries to a newer checkpoint. Overnight, text-to-image search returns near-random photos. The 5M image vectors in the index were left as they were. What's the cause?
Go deeper
Full explanation
Contrastive learning trains an encoder from pairs instead of labels: given items that should match (two crops of one photo, an image and its caption, a question and the passage that answers it), it pulls their embeddings together and pushes everything else apart. The geometry of the space is what the model learns.
InfoNCE, the standard loss, is cross-entropy over similarities: score an anchor against its positive and N−1 negatives, divide by a temperature τ, softmax, and treat the positive as the correct class. A low τ sharpens the softmax so the hardest negatives dominate the gradient; too low and training gets unstable.
In-batch negatives make it cheap: in a batch of N pairs, the other N−1 items are free negatives, so bigger batches give more and harder negatives (SimCLR used up to 8,192; CLIP 32,768). Mined hard negatives (close but wrong) add the most signal.
CLIP (OpenAI, 2021) trained an image encoder and a text encoder on ~400M web image–text pairs with a symmetric InfoNCE over the N×N similarity matrix. The result is one shared space where an image lands near its description. Zero-shot classification embeds prompts like "a photo of a {label}" and picks the closest one, with no task-specific training.
The same recipe trains text Choosing an embedding model on query–passage pairs and powers Multimodal models search: embed images once, query them with text.
Code CLIP-style symmetric InfoNCE and zero-shot classification
import torch
import torch.nn.functional as F
def info_nce(a, b, logit_scale):
"""Symmetric InfoNCE (CLIP loss). a[i] and b[i] are a positive pair."""
a, b = F.normalize(a, dim=-1), F.normalize(b, dim=-1) # dot = cosine
logits = logit_scale.exp().clamp(max=100) * a @ b.T # (N, N), scale = 1/tau
targets = torch.arange(len(a), device=a.device) # positives on the diagonal
# Each row is an N-way classification: 1 positive, N-1 in-batch negatives for free
return (F.cross_entropy(logits, targets) + F.cross_entropy(logits.T, targets)) / 2
logit_scale = torch.nn.Parameter(torch.tensor(1 / 0.07).log()) # CLIP init tau = 0.07, learned
# One training step on N (image, caption) pairs
img_emb = image_encoder(images) # ViT + projection -> (N, 512)
txt_emb = text_encoder(captions) # transformer + projection -> (N, 512)
loss = info_nce(img_emb, txt_emb, logit_scale)
loss.backward() # updates both encoders and the temperature
# Zero-shot classification: the classes are just text prompts
labels = ["dog", "cat", "pickup truck"]
with torch.no_grad():
cls = F.normalize(text_encoder([f"a photo of a {l}" for l in labels]), dim=-1)
img = F.normalize(image_encoder(new_image), dim=-1)
probs = (100 * img @ cls.T).softmax(dim=-1) # argmax = predicted classReal example
A marketplace has 5M product photos with poor titles and wants text search over them. You embed every photo once with a CLIP image encoder (512-d for ViT-B/32: 5M × 512 × 4 bytes ≈ 10 GB in float32) into a vector index. At query time you embed "red running shoes, white sole" with the text encoder and run ANN search: cross-modal search with zero labels. The same vectors auto-tag the catalog against ~200 category prompts. Off-the-shelf CLIP confuses near-identical products, so you fine-tune on (query, clicked photo) pairs from search logs with in-batch negatives and compare recall@10 before and after.
Trade-offs +3 · −3
+ You gain
- Learns from naturally paired data (captions, clicks, query–answer logs) instead of manual labels.
- One reusable embedding space serves search, clustering, dedup and zero-shot classification.
- Aligns modalities: text can search images, and vice versa, in a single index.
− You pay
- Quality hinges on negatives: needs large batches (SigLIP's sigmoid loss eases this) or a hard-negative mining pipeline.
- False negatives: duplicates or paraphrases in the batch get pushed apart.
- CLIP-style models are weak at counting, spatial relations and reading text in images, and inherit web-data biases.
Use it when
You have or can mine pairs that should match (captions, clicks, query–answer logs, augmentations) and need embeddings for retrieval, dedup, zero-shot tagging or cross-modal search.
Avoid it when
A fixed label set with plenty of labeled data: a supervised classifier is simpler. Tasks that need reasoning over the image (counting, reading charts): use a multimodal LLM.
Numbers to know 4
- CLIP: ~400M image–text pairs, batch 32,768, learned temperature initialized at τ = 0.07 (logit scale capped at 100).
- CLIP zero-shot ImageNet: 76.2% top-1, matching the original ResNet-50 without any of its 1.28M labeled training images.
- SimCLR: a batch of 8,192 gives 16,382 negatives per positive pair (two augmented views per image).
- Sentence-Transformers' MultipleNegativesRankingLoss is InfoNCE with in-batch negatives; default scale 20, i.e. τ = 0.05.
Common pitfalls 4
- Small batches with no hard negatives: the task is too easy and embeddings stay coarse.
- Duplicates in a batch act as false negatives; dedup or mask them.
- Treating raw cosine scores as probabilities or reusing one threshold across domains; calibrate per use case.
- Mixing vectors from different models or versions: the spaces aren't aligned, so re-embed everything on upgrade.
Interview questions 3
Answer out loud first, then reveal.
Explain InfoNCE and the role of temperature.Show answer
InfoNCE turns representation learning into classification: for each anchor, which of the N candidates is its positive? I compute cosine similarities, divide by τ and apply cross-entropy with the positive as the target. Minimizing it pulls the positive closer and pushes negatives away, weighted by how close they are. Temperature controls that weighting: a low τ makes the softmax peaky, so the hardest negatives dominate, which is good for fine distinctions but unstable and sensitive to false negatives. CLIP avoids hand-tuning by learning τ, starting at 0.07.
How does CLIP do zero-shot classification, and where does it fail?Show answer
Both encoders map into one space, so I turn each class into text, like "a photo of a {label}", embed those prompts once and assign the image to the closest prompt by cosine similarity. No training, and a new class is just a new string. It fails where web captions are thin: counting, spatial relations, specialized domains like medical or satellite imagery, and it can be fooled by text in the image, such as a handwritten "iPod" label on an apple. There I'd fine-tune on in-domain pairs, train a linear probe or call a multimodal LLM.
You're fine-tuning an embedding model on your domain. How do you choose negatives?Show answer
I start with in-batch negatives, which are free and diverse, using the largest batch that fits in memory. Then I add hard negatives mined with BM25 or the current model: passages that rank high but aren't labeled relevant. They carry most of the signal, but they also hide false negatives, so I drop candidates a cross-encoder scores as relevant and dedup each batch. I judge success by recall@k and nDCG on a held-out set, not by the training loss.