Skip to content
LearnAI

7.2CLIP & contrastive learning

How 400 million image–caption pairs taught one model to put pictures and words in the same space, and why that unlocked zero-shot vision.

⏱ 13 minIntermediate

Labels are expensive, captions are everywhere

The Vision Transformer lesson ended on a problem: ViTs are hungry for data. The classic way to feed them is labeled datasets such as ImageNet, where people sorted images into 1,000 fixed categories. Labeling is slow, the categories are frozen, and a model trained to say “golden retriever” has no way to say “a golden retriever wearing sunglasses on a skateboard”.

Meanwhile, the web is full of images that already come with text: alt text, captions, titles. That text is noisy, but it is free and it describes far more than 1,000 categories. In 2021, Radford and colleagues at OpenAI built CLIPCLIPOpenAI's 2021 model that learns a shared embedding space for images and text by contrasting matching and non-matching pairs. (Contrastive Language–Image Pre-training) on this insight. They collected about 400 million image–text pairs from the internet and asked a simple question of each batch: which caption goes with which image?

The answer to that question, learned at scale, turns out to be one of the most reused building blocks in multimodal AI. CLIP-style encoders give vision-language models their eyes, and CLIP’s text encoder steered early text-to-image models such as Stable Diffusion.

ANALOGY· Matching name tags at a party

Picture a party game. Thirty-two guests arrive, and thirty-two name tags are dumped on a table. Each guest must grab the tag that describes them. A tag that says “tall woman, red scarf, laughs loudly” is useless for anyone else, so guests learn to read tags for the details that set them apart from everyone else in the room.

The guests are images and the tags are captions. The room is a training batch. Pulling a guest toward their own tag and away from the other 31 is contrastive learning. After many parties, everyone has learned a shared language of distinguishing features: the embedding space.

The setup: two encoders, one space

CLIP has two separate networks:

  • An image encoder (a ResNet or a ViT) that turns an image into a vector.
  • A text encoder (a Transformer) that turns a caption into a vector.

Each output passes through a linear projection into the same dimension, then gets normalized to unit length. Now an image vector and a text vector can be compared with a dot productDot productMultiply two vectors element by element and add up the results. It is large when the vectors point in similar directions., which for unit vectors is exactly their cosine similarityCosine similarityThe dot product of two vectors divided by the product of their lengths: the cosine of the angle between them, from −1 to 1.: 1 when they point the same way, 0 when unrelated, −1 when opposite.

Take a batch of NN pairs. Encode all NN images and all NN captions, then compute every image–caption similarity. That gives an N×NN \times N similarity matrix. The NN entries on the diagonal are the true pairs; the N2−NN^2 - N entries off the diagonal are mismatches. CLIP used batches of 32,768, so each image had to beat 32,767 wrong captions.

Training is contrastive learningContrastive learningLearning representations by pulling matching pairs together and pushing non-matching pairs apart. with the InfoNCE lossInfoNCE lossA contrastive loss: a softmax cross-entropy that asks each item to pick its true partner out of a batch of candidates. CLIP averages it over both directions (image→text and text→image).. Read each row of the matrix as a softmaxSoftmaxA function that turns a vector of scores into probabilities by exponentiating each score and dividing by the total. classification problem: “out of these NN captions, which is mine?” The loss is the cross-entropyCross-entropy lossThe negative log-probability the model assigned to the correct answer. It is low when the model is confidently right. of picking the diagonal entry. Do the same down each column (“out of these NN images, which is mine?”) and average the two directions. That’s the symmetric InfoNCE loss.

Temperature: how sharp is the softmax?

Cosine similarities live between −1 and 1. Fed straight into a softmax, that range is too narrow: even a perfect match at 1.0 against mismatches at 0.0 would get only a modest probability. So CLIP divides the similarities by a temperature τ\tau before the softmax, the same temperatureTemperatureA sampling knob that divides logits before softmax. Low values make output more deterministic; high values make it more random. knob you met in sampling. CLIP learns τ\tau during training. It starts at 0.07, and the learned scale 1/τ1/\tau is capped at 100 so training stays stable.

A small τ\tau makes the softmax peaky. The model is punished hard for any wrong caption that comes close, which forces fine distinctions. A large τ\tau makes everything mushy: even a perfectly arranged space can’t reach low loss.

INTERACTIVEA toy CLIP, trained live
step 0loss 6.307chance-level loss 1.792image→text top-1: 0/6
dogcatcartreepizzaguitar🐶🐱🚗🌳🍕🎸inner ring: images · outer ring: captionscaptions (text encoder)dogcatcartreepizzaguitar🐶🐱🚗🌳🍕🎸−.63.11.61.99.90−.97−.99−.80−.37.62.09−.28−.12.63.94.77.99−.951.00.67.18−.76−.28.46.711.00.85−.04.51−.34.36.92.99.38.82−.70
Matrix shows
Outlined diagonal = matching pairs. Training raises the diagonal and lowers everything else.
Zero-shot: classify image
"a photo of a dog"
0%
"a photo of a cat"
1%
"a photo of a car"
8%
"a photo of a tree"
55%
"a photo of a pizza"
36%
"a photo of a guitar"
0%
Prediction for 🐶: tree (55%) · image at 46°, its caption at 175°. Lower τ sharpens these probabilities without moving any point.
Six images (inner ring) and six captions (outer ring) live in a 2D shared space; only the direction from the center matters. Press Train to run real InfoNCE gradient steps: matching pairs rotate together and mismatches spread apart. Watch the diagonal of the similarity matrix light up, then try the temperature slider and the zero-shot panel.

Things to try:

  1. Press Train at τ = 0.20. Training happens in two phases. First, each image snaps onto its caption: the diagonal hits 1.00 and top-1 accuracy reaches 6/6, but pairs are clumped together and the loss is still high. Then the clumped pairs push each other apart until they are spread evenly around the circle, and the loss drops to about 0.15. Matching alone isn’t enough; the loss also rewards keeping different things far apart.
  2. Set τ to 1.0 and train. The pairs still align, but the loss stalls around 1.0. With cosine similarities in [−1, 1] and no sharpening, the softmax can never be confident. That is why CLIP learns a small temperature.
  3. Set τ to 0.03, scramble and train. Low temperature gives huge gradients to the closest mistakes. In this tiny 2D world, pairs can get “stuck” on the wrong side of each other, a local minimum. Real embedding spaces have hundreds of dimensions, which leaves far more room to slide past.
  4. Zero-shot. After training, pick an image. The bars are a softmax over “a photo of a …” prompts. Then drag the temperature slider without training: the points don’t move, but the probabilities sharpen or flatten.
  5. Switch the matrix to “row softmax”. Each row now shows the probabilities the image→text loss actually uses.

Zero-shot classification

Here’s the payoff. Suppose you want to classify an image into dog, cat or car, and you never trained a classifier. With CLIP:

  1. Write one text prompt per class: “a photo of a dog”, “a photo of a cat”, “a photo of a car”.
  2. Encode each prompt with the text encoder. These vectors are your classifier weights.
  3. Encode the image, compute its cosine similarity with each prompt vector, divide by τ\tau and take a softmax.

That’s zero-shot classificationZero-shot classificationClassifying into labels the model was never explicitly trained on, e.g. by comparing an image embedding with text embeddings of prompts like "a photo of a {label}".. The labels can be anything you can describe in words, and changing them takes seconds. The CLIP paper reported that its best model matched the accuracy of the original ResNet-50 on ImageNet (about 76%) without using any of ImageNet’s 1.28 million labeled training images.

Prompt wording matters. The CLIP authors found that a photo of a {label} beat the bare label, partly because web captions rarely consist of a single word. Averaging the embeddings of many templates (a photo of a small {label}, a blurry photo of a {label}, …), called prompt ensembling, helped further.

SigLIP: a sigmoid instead of a softmax

The softmax in InfoNCE couples the whole batch: to normalize one row, you need every caption in it. With batches of tens of thousands spread over many accelerators, that means a lot of communication. SigLIPSigLIPA CLIP-style image-text model trained with a pairwise sigmoid loss instead of a batch-wide softmax. Its image encoders are widely reused in vision-language models. (Zhai et al., 2023) replaces it with an independent binary question for every image–caption pair: “is this a match, yes or no?” Each cell of the N×NN \times N matrix gets its own sigmoid and its own binary cross-entropy, with a learned temperature and bias.

No row-wide normalization means the loss can be computed in chunks, and the authors found it works well at smaller batch sizes too. SigLIP encoders, such as SigLIP So400m/14 and the later SigLIP 2, are among the most common vision backbones in today’s open vision-language models.

The modality gap

If you plot real CLIP embeddings, you find something surprising: image vectors and text vectors don’t mingle. They occupy two separate regions, two “cones” of the sphere, even though matching pairs are closer than mismatched ones. Liang et al. (2022) named this the modality gapModality gapThe observation that in CLIP-like models, image embeddings and text embeddings occupy separate regions of the shared space even when matching pairs align well.. They traced it to how the two encoders start out at random initialization, preserved by contrastive training at low temperature.

The gap explains a practical quirk. A typical cosine similarity between a CLIP image and its correct caption is well below 1, often only around 0.3. What matters for retrieval and classification is the ranking, not the absolute value. It is also a warning: mixing image and text vectors in the same vector indexVector databaseA store optimized for finding the vectors nearest to a query vector, usually with approximate nearest-neighbor indexes. (as in vector search) can give odd results, because a text query is closer to other texts than to any image.

MATH CORNER · optionalSymmetric InfoNCE, with a 2×2 example

Let uiu_i be the normalized image embeddings and vjv_j the normalized text embeddings in a batch of NN pairs. The logits are sij=ui⊤vj/τs_{ij} = u_i^\top v_j / \tau. The image→text and text→image losses are

LI→T=−1N∑i=1Nlog⁡esii∑jesij,LT→I=−1N∑j=1Nlog⁡esjj∑iesij,\mathcal{L}_{I\to T} = -\frac{1}{N}\sum_{i=1}^{N} \log \frac{e^{s_{ii}}}{\sum_{j} e^{s_{ij}}}, \qquad \mathcal{L}_{T\to I} = -\frac{1}{N}\sum_{j=1}^{N} \log \frac{e^{s_{jj}}}{\sum_{i} e^{s_{ij}}},

and CLIP minimizes L=12(LI→T+LT→I)\mathcal{L} = \tfrac{1}{2}(\mathcal{L}_{I\to T} + \mathcal{L}_{T\to I}). The gradient with respect to each logit is wonderfully simple:

∂L∂sij=12N[(pijrow−1i=j)+(pijcol−1i=j)],\frac{\partial \mathcal{L}}{\partial s_{ij}} = \frac{1}{2N}\Big[(p^{\text{row}}_{ij} - \mathbb{1}_{i=j}) + (p^{\text{col}}_{ij} - \mathbb{1}_{i=j})\Big],

where prowp^{\text{row}} and pcolp^{\text{col}} are the row-wise and column-wise softmaxes. Matching pairs get pushed up by how far they are from probability 1; mismatches get pushed down by how much probability they stole. The demo above implements exactly this.

Worked example (N=2N = 2, τ=0.1\tau = 0.1). Cosine similarities:

caption 1caption 2
image 10.80.3
image 20.20.6

Divide by τ\tau: row 1 logits are [8,3][8, 3] and row 2 logits are [2,6][2, 6].

  • Row 1: p=e8/(e8+e3)=1/(1+e−5)≈0.9933p = e^8/(e^8+e^3) = 1/(1+e^{-5}) \approx 0.9933, loss −ln⁡0.9933≈0.0067-\ln 0.9933 \approx 0.0067.
  • Row 2: p=1/(1+e−4)≈0.9820p = 1/(1+e^{-4}) \approx 0.9820, loss ≈0.0181\approx 0.0181.
  • Column 1 (logits 8 vs 2): p=1/(1+e−6)≈0.9975p = 1/(1+e^{-6}) \approx 0.9975, loss ≈0.0025\approx 0.0025.
  • Column 2 (logits 3 vs 6): p=1/(1+e−3)≈0.9526p = 1/(1+e^{-3}) \approx 0.9526, loss ≈0.0486\approx 0.0486.

LI→T=(0.0067+0.0181)/2=0.0124\mathcal{L}_{I\to T} = (0.0067 + 0.0181)/2 = 0.0124 and LT→I=(0.0025+0.0486)/2=0.0256\mathcal{L}_{T\to I} = (0.0025 + 0.0486)/2 = 0.0256, so L≈0.019\mathcal{L} \approx 0.019. The weakest link is caption 2, which image 1 (0.3) and image 2 (0.6) compete for. Now set τ=1\tau = 1: row 1 becomes [0.8,0.3][0.8, 0.3], p≈0.62p \approx 0.62, loss ≈0.47\approx 0.47, about 70 times higher than before for exactly the same geometry. Temperature decides how demanding the objective is.

SigLIP instead uses, for each cell, −log⁡σ(zij(t ui⊤vj+b))-\log \sigma\big(z_{ij}(t\, u_i^\top v_j + b)\big) with zij=+1z_{ij} = +1 on the diagonal and −1-1 elsewhere, and learned scale tt and bias bb.

In code

The core of CLIP’s training loop fits in a few lines. This follows the pseudo-code in the CLIP paper:

import torch, torch.nn.functional as F

def clip_loss(img_feats, txt_feats, logit_scale):
    # img_feats, txt_feats: (N, d) from the two encoders + projections
    u = F.normalize(img_feats, dim=-1)
    v = F.normalize(txt_feats, dim=-1)
    logits = logit_scale.exp() * u @ v.T        # (N, N); logit_scale = log(1/τ), learned
    labels = torch.arange(len(u), device=u.device)  # the diagonal is the right answer
    loss_i2t = F.cross_entropy(logits, labels)      # each row: pick my caption
    loss_t2i = F.cross_entropy(logits.T, labels)    # each column: pick my image
    return (loss_i2t + loss_t2i) / 2

# Zero-shot classification with a trained model
@torch.no_grad()
def zero_shot(image_emb, text_encoder, labels, tau=0.01):
    prompts = [f"a photo of a {c}" for c in labels]
    T = F.normalize(text_encoder(prompts), dim=-1)  # (C, d) = classifier weights
    sims = F.normalize(image_emb, dim=-1) @ T.T     # cosine similarity per label
    return (sims / tau).softmax(dim=-1)
COMMON MISCONCEPTIONS
  • “CLIP was trained to classify images.” It was trained only to match images with their own captions inside a batch. Classification is something you get for free afterwards, by turning labels into text prompts.
  • “A cosine similarity of 0.3 means a bad match.” In CLIP’s space, correct image–caption pairs often score around 0.3 because of the modality gap. Only relative scores are meaningful.
  • “Bigger negatives-per-batch is just an engineering detail.” The number of negatives shapes what CLIP learns. With 32,767 wrong captions per image, it must capture fine distinctions. SigLIP’s pairwise sigmoid loss is one way to reduce how much the method depends on huge batches.
  • “Zero-shot means the model has never seen anything like the class.” CLIP has almost certainly seen many images of dogs with captions mentioning dogs on the web. “Zero-shot” means no task-specific labeled training, not that the concept is new.

Check your understanding

0/5 answered
  1. Q1.In a CLIP batch of N = 1,024 image–caption pairs, how many negative captions does each image get contrasted against?

  2. Q2.What does lowering the temperature τ in the InfoNCE loss do?

  3. Q3.How does CLIP classify an image into labels it was never explicitly trained on?

  4. Q4.What is the main change SigLIP makes to CLIP's training objective?

  5. Q5.The 'modality gap' refers to…

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.