Contrastive Vision–Language Models
CLIP and zero-shot classification.
CLIP was trained only to tell which caption in a batch belongs to which image. At the optimum of that game its similarity score is a pointwise mutual information, and zero-shot classification is Bayes' rule with the class prior left out. Taking the objective seriously explains CLIP's strengths, its sensitivity to prompts and to label frequencies, its indifference to word order, and what changes when the softmax is replaced by a sigmoid.
What you’ll learn
- Characterize the population minimizers of the symmetric contrastive loss, derive zero-shot classification as a Bayes classifier without its prior, and correct it under label shift.
- Explain the roles of temperature and batch size, and derive the optimum of SigLIP's sigmoid loss, including why its bias settles near .
- Compare zero-shot, linear-probe and fine-tuned transfer, and assess claims of effective robustness and where it comes from.
- Prove that contrastive training without order-sensitive negatives gives no incentive to encode word order, and connect this to compositionality benchmarks, hard negatives and the modality gap.
What the symmetric loss learns
One direction. is InfoNCE with the image as anchor. Given and candidate captions, the posterior probability that candidate is the true one is proportional to , and a cross-entropy is minimized exactly by the true posterior (Self-Supervised & Contrastive Learning). The softmax of equals that posterior for every candidate set if and only if
The other direction. With captions as anchors, the same argument shows that is minimized if and only if
Both. minimizes both terms at once, so the minimum of the sum is the sum of the two minima, attained only where both conditions hold. Negatives come from the marginals, so the critic is evaluated on all of , and there forces a single constant:
Two lessons follow. The prior is a free parameter. Zero-shot CLIP implicitly treats classes as equally likely. If the target prior is known, adding is the Bayes-optimal correction; if not, it can be estimated from unlabeled target images by expectation–maximization on the classifier's outputs (Saerens, Latinne & Decaestecker, 2002). The prompt chooses the likelihood. The score measures how typical is of web images captioned , which need not resemble the task's images; prompt engineering ("a satellite photo of a …") moves toward them, and prompt ensembling averages over caption styles. Real critics are far from optimal, and learned scores retain frequency effects: across many concepts, zero-shot accuracy grows roughly log-linearly with how often the concept appears in the pretraining data (Udandarao et al., 2024).
A zero-shot classifier with a near-optimal critic is deployed where 90% of the images belong to class A and 10% to class B. How should its logits be adjusted?
- Multiply class A's logit by 9
- Lower the temperature
- No adjustment: the contrastive loss already accounts for class frequencies
- Add to A's logit and to B's, or equivalently to A's alone
Show the answer
D. Add to A's logit and to B's, or equivalently to A's alone
Under the optimal critic the logits are up to terms independent of , so the Bayes classifier adds . PMI divides out the frequency of captions by design, so the deployment prior has to be put back explicitly.
Temperature, batch size and the sigmoid loss
The logits are cosines divided by , so they lie in ; a PMI landscape spanning many nats needs a small , which is why CLIP learns it, starting from 0.07 with capped at 100. Batch size matters twice. Statistically, the InfoNCE bound on mutual information saturates at , about 10.4 nats for (Self-Supervised & Contrastive Learning), and more negatives include harder ones. Computationally, each row's softmax needs all logits of that row, so with the batch spread over many accelerators, every device must gather every other device's embeddings.
How many image–text similarity scores does one CLIP training batch of 32,768 pairs compute, in billions?
Show the answer
1.07
, of which only 32,768 are positives. Each is one -dimensional dot product, cheap next to the encoders, but the softmax couples all the scores in a row, and that coupling is what the sigmoid loss removes.
SigLIP (Zhai et al., 2023) replaces the softmax by an independent binary decision for every pair, labeled on the diagonal and off it, with a learnable scale and bias . No normalization couples the scores, so devices can process blocks of the similarity matrix and pass text embeddings around instead of gathering everything. Zhai et al. found the sigmoid loss better than the softmax loss at small batch sizes, with the benefit of larger batches saturating around 32k.
Each image meets one positive caption and negatives. Pairs labeled come from and pairs labeled from , at odds of , so the true conditional probability of a positive label is
Logistic loss is minimized by the true conditional log-odds, so the optimal logit is
The PMI again, now with no free constant: the offset encodes the class imbalance. A typical negative pair has , so if negative similarities sit near 0 the bias must sit near for . That is why SigLIP initializes : from the first step, the model predicts the base rate of positives instead of spending early updates learning it.
Transfer and robustness, measured carefully
| Protocol | Labeled target data | What it measures |
|---|---|---|
| Zero-shot | none: class names and prompts only | how well language specifies the task in the shared space |
| Linear probe | a labeled training set; features frozen | what is linearly decodable from the image features |
| Fine-tuning | a labeled training set; all weights updated | the best adapted accuracy, at a cost in generality |
The CLIP paper reported three results that shaped the field. Linear probes on CLIP features beat probes on the best ImageNet-pretrained features on most of the datasets studied. Zero-shot classification matched, on average, a linear probe trained on about four labeled examples per class, because a class name states directly what a handful of images leaves ambiguous. And zero-shot models showed much higher effective robustness: on natural distribution shifts of ImageNet (fresh test photos, sketches, renditions, adversarially filtered photos), their accuracy sat far above the line that relates in- and out-of-distribution accuracy for ImageNet-trained models (Taori et al., 2020; Distribution Shift & Robustness).
The robustness claims have three limits.
- Adaptation erodes it. Fitting a logistic-regression probe on ImageNet raised in-distribution accuracy but gave back much of the effective robustness, the CLIP paper's own result, and full fine-tuning behaves similarly. Averaging the zero-shot and fine-tuned weights recovers much of it (WiSE-FT; Wortsman et al., 2022).
- The data, not the language, is the main source. Controlled experiments that varied the training distribution, the use of language supervision and the loss found that robustness tracks the diversity of the pretraining images (Fang et al., 2022).
- It is not adversarial robustness. Small perturbations fool CLIP like any other network, and typographic attacks, text written on an object, exploit its ability to read (Goh et al., 2021).
Word order, hard negatives and the modality gap
Define on bags by for in the support; injectivity makes this well defined. Then agrees with on every caption that can occur:
Every batch's loss depends on the text encoder only through its values on the batch's captions, all drawn from the support, so the two encoders have identical losses, batch by batch:
The objective therefore cannot prefer an order-sensitive encoder to an order-blind one on such data; which one training finds is up to the architecture's inductive biases. Web data violate the hypothesis only rarely, and the training signal for word order comes only from batches in which two captions with the same words but different meanings meet, which almost never happens. Benchmarks built from exactly such pairs expose the blindness: on Winoground, whose image–caption pairs use the same words in different orders, CLIP-style models scored near chance (Thrush et al., 2022), and the ARO benchmark found similar failures on relations, attributes and order (Yuksekgonul et al., 2023).
The proposition also says how to fix it: put order-sensitive pairs into the batch. NegCLIP (Yuksekgonul et al., 2023) adds, for each caption, a negative made by swapping its words or phrases, plus nearest-neighbor images as hard image negatives. The loss can then be lowered only by representations that tell the swaps apart, and scores on order-sensitive benchmarks rose substantially. Such fixes target the benchmark's perturbations, and whether they yield general compositional understanding is debated.
A second geometric quirk: image and text embeddings occupy separate regions of the unit sphere, the modality gap (Liang et al., 2022). Random initialization already places each encoder's outputs in a narrow cone, and contrastive training at low temperature tends to preserve the offset between the two cones. Shifting the embeddings to change the gap alters zero-shot accuracy and some fairness measures, so the gap is not innocuous, and why it persists at scale is not fully understood.
Key takeaways
- The symmetric contrastive loss is minimized exactly by ; each direction alone leaves a per-anchor function free.
- Zero-shot classification is , Bayes' rule without the class prior: add under label shift, and choose prompts so that resembles the task's images.
- The sigmoid loss's optimal logit is , which explains SigLIP's bias initialization at , and it removes the softmax's all-to-all coupling across devices.
- Zero-shot transfer and effective robustness are real but limited: adaptation erodes robustness, data diversity explains most of it, and adversarial and typographic attacks still work.
- Without order-sensitive negatives the loss cannot reward encoding word order; Winoground and ARO expose the blindness, and hard negatives partly repair it.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
At the population optimum of the symmetric contrastive loss, with an unrestricted critic, what is ?
- plus a constant
- The joint density
- 1 for matching pairs and for all others
Show the answer
B. plus a constant
Each direction's InfoNCE is minimized by the PMI plus a function of its anchor; requiring both pins that function to a constant. Logits enter through exponentials, so the optimum is a log density ratio, the quantity that decides which candidate is the true partner.
A SigLIP model is trained with batch size . If the similarities of typical negative pairs sit near 0, what value does the optimum push the bias toward?
- 0
Show the answer
C.
The optimal logit is , and a typical negative has , so : about for , matching the paper's initialization at . The bias encodes the base rate of positives among all pairs.
Why did adding word-swapped captions as negatives (NegCLIP) improve scores on order-sensitive benchmarks?
- It made the text encoder larger
- It made the loss depend on distinguishing captions with the same bag of words, which ordinary web batches almost never require
- It removed the temperature from the loss
- It trained on more images
Show the answer
B. It made the loss depend on distinguishing captions with the same bag of words, which ordinary web batches almost never require
If no batch ever contains two captions with the same words, an order-blind encoder achieves the same loss as an order-aware one, so nothing pushes training toward order. Swapped-caption negatives create exactly the comparisons that make order matter to the loss.
Controlled experiments by Fang et al. (2022) asked where CLIP's effective robustness comes from. What did they find?
- Mainly from the diversity of the training images
- Mainly from language supervision itself
- Mainly from the contrastive loss
- From the very large batch size
Show the answer
A. Mainly from the diversity of the training images
Varying the training distribution, the use of language and the objective separately, they found robustness tracked the diversity of the pretraining data, not the use of text supervision or the contrastive loss. It is also lost partly when the model is adapted to ImageNet, consistent with the data explanation.
Further reading
- A. Radford et al., "Learning transferable visual models from natural language supervision," ICML (2021).
- C. Jia et al., "Scaling up visual and vision-language representation learning with noisy text supervision," ICML (2021).
- X. Zhai, B. Mustafa, A. Kolesnikov & L. Beyer, "Sigmoid loss for language image pre-training," ICCV (2023).
- M. Yuksekgonul, F. Bianchi, P. Kalluri, D. Jurafsky & J. Zou, "When and why vision-language models behave like bags-of-words, and what to do about it?," ICLR (2023).
- Z. Gan, L. Li, C. Li, L. Wang, Z. Liu & J. Gao, "Vision-language pre-training: basics, recent advances, and future trends," Foundations and Trends in Computer Graphics and Vision (2022).