Chapter 5: Contrastive Learning & CLIP
Master the contrastive learning paradigm that revolutionized vision-language models. From the theoretical foundations of noise contrastive estimation through the full CLIP training pipeline, zero-shot transfer, and scaling variants like ALIGN and Florence, to the fundamental limitations that motivate generative approaches.
- Topics
- 6
- Videos
- 6
- Min read
- 42
Chapter Overview
Contrastive learning is the engine that powers modern vision-language alignment. Rather than learning to generate text from images (expensive, slow), contrastive methods learn a shared embedding space where matched image-text pairs are close and unmatched pairs are far apart. This elegant formulation scales to billions of pairs scraped from the web.
CLIP (Contrastive Language-Image Pre-training), published by OpenAI in January 2021, demonstrated that a model trained on 400 million image-text pairs could match or exceed supervised models on dozens of classification benchmarks -- without seeing a single labeled example from those datasets. This "zero-shot" capability fundamentally changed how we think about visual recognition.
The key insight is deceptively simple: instead of training a classifier with a fixed set of classes, train an image encoder and a text encoder to agree on which images go with which captions. At inference time, you can classify images into any set of categories just by computing similarities with text descriptions of those categories.
This chapter builds the full picture:
- Contrastive learning foundations: Why pulling positives together and pushing negatives apart produces useful representations
- InfoNCE loss: The mathematical core of CLIP, connecting contrastive learning to mutual information
- CLIP training at scale: How 400M web-scraped pairs, dual encoders, and massive batch sizes come together
- Zero-shot transfer: Using language as a flexible classifier interface
- Scaling variants: ALIGN (1.8B noisy pairs), Florence (hierarchical features), EVA-CLIP
- Fundamental limitations: Why contrastive models fail at compositionality and what this means for VLMs
Chapter Roadmap
Click any topic to jump in
Contrastive Foundations
How pulling positives together and pushing negatives apart creates structured embedding spaces — the core paradigm behind vision-language alignment.
InfoNCE Loss
The mathematical objective connecting contrastive learning to mutual information estimation, with temperature as the key control parameter.
CLIP Training
Scaling contrastive learning to 400M web-scraped pairs with dual encoders and massive batch sizes — from theory to breakthrough.
What CLIP enables vs. how others scale the idea
Zero-Shot Transfer
Using text prompts as flexible classifiers — matching supervised models on dozens of benchmarks without a single labeled example.
Scaling Variants
How ALIGN, Florence, and EVA-CLIP push the recipe further with noisier data, hierarchical features, and efficient initialization.
Fundamental Limitations
Why contrastive models fail at compositionality, negation, and attribute binding — the failures that motivate generative approaches.
Topics
6 topics in this chapter
Suppose you have 400 million images scraped from the web, each with whatever alt-text its author typed, and no class labels at all. How do you turn that into an image encoder whose features know what a golden retriever or a diagram of a cell looks like? The previous chapter built bridges that hand an already-trained vision encoder to a language model; this chapter steps back and asks where that encoder's language-aware features came from. For CLIP, SigLIP and the vision towers of most VLMs, the answer is contrastive learning. Instead of predicting a label, the model learns to tell which caption belongs to which image. Positive pairs (an image and its own caption) are pulled together, and every other pairing in the batch acts as a negative that is pushed apart. This topic defines positive and negative pairs, the cosine similarity that scores them, and noise contrastive estimation, the older statistical idea that makes the trick principled. Later topics turn these pieces into the InfoNCE loss, the CLIP training pipeline, zero-shot classification, the ALIGN, Florence and EVA-CLIP variants, and the limits of the approach.
Definition
Contrastive learning trains encoders and so that a similarity score is high for positive pairs, such as an image and its own caption, and low for negative pairs, such as the same image with the other captions in its batch. No labels are needed: the pairing itself is the supervision, and the embeddings learn whatever distinctions the negatives force.
In this topic
- 1Positive and Negative Pairs
- 2Representation Learning via Similarity
- 3Noise Contrastive Estimation (NCE)
Positive and Negative Pairs
What counts as similar has to be decided before any learning happens. In image-text contrastive learning a positive pair is an image and the caption it was posted with; a negative pair is that image with any other caption in the batch. With batch size , each image has 1 positive and negatives, and the whole batch has positives and negatives. Negatives are what rule out the trivial solution of mapping everything to one point. Their count is not the whole story, though: most random negatives are easy, a dog photo against a stock-chart caption, so bigger batches help mainly because they contain more hard negatives.
Each anchor's loss is an -way classification, so a model that knows nothing scores nats: 1.39 for and 10.40 for . Doubling raises that ceiling by nats, one bit. That is the precise sense in which more negatives add a bit: the InfoNCE bound on mutual information can never exceed , so a small batch caps how much the loss can certify, however good the encoder is. It does not mean each doubling adds a bit of representational capacity.
In a batch of 4 image-text pairs (I1-T1, I2-T2, I3-T3, I4-T4), how many positive pairs and negative pairs exist? Why does this ratio matter?
Representation Learning via Similarity
Once pairs are defined, the model needs a score for how alike two embeddings are. CLIP uses cosine similarity, the formula's : the dot product of and after each is scaled to unit length, which equals the cosine of the angle between them and lies in . Normalizing removes vector length from the comparison, so the model cannot raise a score just by inflating magnitudes, and every embedding lives on the unit hypersphere. A raw dot product is unbounded and lets length dominate. Euclidean distance between unit vectors carries the same information, since .
On the unit sphere in dimensions, random directions are nearly orthogonal: for 2,000 random unit vectors the mean absolute cosine between pairs is 0.035, and the largest among about two million pairs is 0.22. Room is not the constraint; the loss decides how the space is used. Wang and Isola (2020) split the contrastive objective into alignment (positives close together) and uniformity (embeddings spread evenly over the sphere) and showed that both properties track downstream accuracy.
Two image embeddings: u = [0.6, 0.8, 0.0] and v = [0.8, 0.6, 0.0]. Compute their cosine similarity. What does this tell us about their relationship?
Noise Contrastive Estimation (NCE)
NCE reframes density estimation as a binary classification problem: distinguish real data from noise. Given a data sample , the model must classify whether came from the true data distribution or a noise distribution . This avoids computing the intractable normalizing constant of the full distribution. In the contrastive learning context, NCE provides the theoretical foundation: matching pairs are 'real data' and non-matching pairs are 'noise'. The model learns to distinguish them, and the learned representations capture the statistical structure of the data.
Gutmann and Hyvärinen showed NCE is consistent for any number of noise samples : with enough data it recovers the true density, including . What controls is statistical efficiency, since the estimator's variance approaches that of maximum likelihood as grows. InfoNCE borrows the idea but changes the question from 'data or noise?' for one sample to 'which of these candidates is the real partner?', a categorical classification rather than a binary one.
Why is NCE more practical than maximum likelihood estimation (MLE) for learning representations in high-dimensional spaces?
Theory Exercise
Problem:
A contrastive model is trained with batch size 256. After training, you find that for a given image, 15 text captions have similarity > 0.8 (including the correct one). The correct caption has similarity 0.85, but 3 incorrect captions have similarity 0.82-0.84. What does this indicate about the learned representation, and how would you improve it?
Hints:
- Think about what high similarity among multiple non-matching texts means
- Consider the role of negative examples and batch size
- Think about hard negative mining strategies
The previous topic supplied the ingredients: positive pairs, in-batch negatives and a cosine similarity score. You still need a single number to minimize, one that rewards a high score for the true caption relative to every wrong caption in the batch. InfoNCE, introduced by van den Oord et al. in Contrastive Predictive Coding (2018), does exactly that. It treats each image as an -way classification problem whose classes are the captions in the batch, and applies ordinary cross-entropy to the softmax of the scaled similarities. CLIP uses it in both directions, images choosing captions and captions choosing images, and averages the two. This topic works through the loss on a three-pair example. It then examines the temperature that divides every similarity before the softmax: CLIP learns it, starting from 0.07, and the released models end at the clamp value of 0.01. Finally it covers the link to mutual information: is a lower bound on the information shared by the two views, which is why batch size matters, and why that bound can never exceed .
Definition
InfoNCE is the cross-entropy of identifying the true partner among candidates: the loss averages of the softmax probability given to the correct pair, where each logit is a similarity divided by a temperature . Minimizing it maximizes , a lower bound on the mutual information between the two views.
In this topic
- 1The InfoNCE Objective
- 2Temperature Parameter
- 3Connection to Mutual Information
The InfoNCE Objective
How do you turn 'match the right caption' into a loss? InfoNCE treats each image in a batch of pairs as an -way classification problem whose correct class is caption . The logits are scaled cosine similarities: is image 's embedding, is caption 's embedding, and is the temperature. A softmax over gives the probability that caption is the partner, and the loss is the negative log of the correct one, averaged over . CLIP adds the mirror loss, captions choosing images, and averages the two. A model that knows nothing scores .
InfoNCE provides a lower bound: . Minimizing the loss maximizes a lower bound on mutual information between image and text representations. The bound tightens as batch size increases — this is the information-theoretic reason large batches are essential, not just a computational convenience.
For a batch of N=3 with similarities sim(I1,T1)=2.0, sim(I1,T2)=0.5, sim(I1,T3)=0.3, compute the InfoNCE loss for image I1 with temperature 0.5.
Temperature Parameter
The temperature in InfoNCE controls the sharpness of the softmax distribution. Low temperature (): the distribution becomes peaked, focusing entirely on the highest-similarity pair. Gradients are concentrated on hard negatives, but training can be unstable. High temperature (): the distribution becomes uniform, treating all negatives equally. Training is stable but the model cannot learn fine-grained distinctions. CLIP uses as a learnable parameter initialized to , allowing the model to find the optimal sharpness during training.
The gradient of the loss with respect to a negative's similarity is , where is that negative's softmax probability. At low the softmax puts nearly all its mass on the highest-scoring negatives, so learning focuses on hard negatives; at high the mass spreads and easy negatives dilute the signal. CLIP stores as the parameter, initialized to , and clips the logit scale at 100 to prevent instability. Trained CLIP models sit at that clip.
Given similarities [0.9, 0.8, 0.1] for a correct match, compute the softmax probabilities at temperatures 0.07, 0.5, and 2.0. What pattern do you observe?
Connection to Mutual Information
Why should matching captions teach anything general? Mutual information measures how much knowing an image reduces uncertainty about its caption . Van den Oord et al. showed that , in nats, so driving the loss down certifies more shared information. The bound has two catches. It can never exceed , about 10.4 nats at , however good the encoders are. And Poole et al. (2019) show it is loose whenever the true information is large. Larger batches raise the ceiling, which is part of why CLIP used them.
Because , the bound is at most : InfoNCE can certify at most 15 bits at , even if the true mutual information between an image and its caption is far larger. McAllester and Stratos (2020) proved that any distribution-free high-confidence lower bound of this kind is limited to roughly . By the data processing inequality , so the bound really concerns the encoders' outputs. In practice the loss is more valuable as a training signal than as an estimator.
A CLIP model achieves InfoNCE loss of 2.5 with batch size 32,768. What is the lower bound on mutual information? What happens if we reduce batch size to 256?
Theory Exercise
Problem:
Derive the gradient of InfoNCE loss with respect to the similarity of the positive pair. Show that the gradient depends on the probability assigned to the positive pair, and explain what this means for the learning dynamics when the model is very confident vs very uncertain.
Hints:
- Start from the cross-entropy formulation
- Use the softmax derivative: d/ds_i softmax(s_j) = softmax(s_j)(delta_ij - softmax(s_i))
- Consider what happens when p_positive approaches 1 vs 1/N
Related Problems on PixelBank
InfoNCE tells you what to minimize; CLIP (Radford et al., 2021) showed what happens when you minimize it at web scale. Three choices made it work. The data: 400 million image-text pairs collected by searching for 500,000 queries built from Wikipedia and WordNet, with at most 20,000 pairs per query to keep the distribution balanced. The architecture: two separate encoders, an image tower (a ResNet or Vision Transformer) and a 12-layer text transformer, each followed by a linear projection into a shared embedding space, with no cross-attention between them. The objective: the symmetric InfoNCE loss from the previous topic over a batch of 32,768 pairs, so every image is scored against 32,768 captions. Both encoders were trained from scratch, with no ImageNet or language-model initialization, and the largest ViT took 12 days on 256 V100 GPUs. This topic examines the dataset and its noise, why the image tower carries most of the parameters, and how a 32,768 by 32,768 similarity matrix is computed across hundreds of GPUs without ever sitting on one of them.
Definition
The CLIP training pipeline jointly trains an image encoder and a text encoder from scratch on web image-text pairs. Each encoder's output is linearly projected into a shared space, and a symmetric InfoNCE loss is minimized over every image-caption pairing in a very large batch (32,768). The result is two encoders whose embeddings are directly comparable by cosine similarity.
In this topic
- 1WebImageText (WIT) Dataset
- 2Dual Encoder Architecture
- 3Batch-Level Contrastive Objective
WebImageText (WIT) Dataset
CLIP was trained on a proprietary dataset of 400 million (image, text) pairs collected from the internet. The data was curated using a query list of 500,000 concepts drawn from Wikipedia and WordNet. For each concept, up to 20,000 image-text pairs were collected, ensuring broad coverage. The text is not clean captions but natural alt-text, titles, and descriptions -- noisy but diverse. This 'natural language supervision' signal is weaker per-sample than manually annotated labels but astronomically more abundant.
The 20,000-pair cap is a crude balancing step: no single query can contribute more than 20,000 / 400M = 0.005 percent of the data, so common concepts cannot crowd out rare ones as much as raw web frequencies would. Noise does not cancel exactly, since a mismatched pair teaches a wrong association. It is tolerable because a wrong caption is usually unrelated to the many other images like it, so its gradients point in inconsistent directions across the dataset, while correct associations repeat and accumulate.
A WIT-like dataset has 400M pairs, but approximately 30% of the text descriptions are noisy (e.g., 'Click here for details', 'IMG_2034.jpg', or unrelated text). Why does CLIP still work well despite this noise?
Dual Encoder Architecture
CLIP uses two separate encoders: a Vision Transformer (ViT) or Modified ResNet for images and a Transformer for text. Each encoder independently processes its input and produces a fixed-size embedding vector. A learned linear projection maps each encoder's output to the shared embedding space where cosine similarities are computed. The encoders never see each other's inputs directly -- there is no cross-attention. This separation enables efficient inference: image and text embeddings can be precomputed and cached independently.
The dual encoder's computational advantage is for encoding images and texts, versus for cross-attention models. Representations are independent — the image embedding doesn't depend on which text it will be compared to. At inference, this enables pre-computing and caching all class text embeddings once, making classification cost equivalent to a single forward pass.
CLIP ViT-L/14 pairs a 303M-parameter image encoder with a 123M-parameter text transformer (12 layers, width 768), and the smallest CLIP's text encoder has 63M parameters. Why does the image side get the larger share, and what did the CLIP authors find about scaling the text side?
Batch-Level Contrastive Objective
CLIP computes the contrastive loss across the entire batch simultaneously. With batch size , each forward pass creates a similarity matrix (over 1 billion entries). The loss is computed as symmetric cross-entropy: each image must identify its correct text among 32,767 distractors, and vice versa. This requires distributing the computation across hundreds of GPUs, with all-gather operations to synchronize embeddings. The computational cost is for the similarity matrix, where is the embedding dimension.
The similarity matrix yields scores per step from encoder passes, so the training signal grows quadratically while encoder compute grows linearly. Memory is the catch: at the full matrix has 1.07 billion entries, 4.3 GB in fp32. CLIP never builds it on one device. The paper shards the computation so each GPU computes only the similarities its local batch needs: its 128 images against all 32,768 captions, about 4.2 million entries, and the same for its 128 captions.
CLIP training uses 256 V100 GPUs with batch size 32,768. Each GPU processes 128 pairs locally. Explain the communication pattern needed to compute the full contrastive loss.
Theory Exercise
Problem:
You want to replicate CLIP training but only have 8 GPUs (A100 80GB) instead of 256 V100s. The effective batch size drops from 32,768 to 1,024. Based on the mutual information bound, estimate how much performance you might lose. Then propose two strategies to recover performance without more GPUs.
Hints:
- Use the MI bound: I(X;Y) >= log(N) - L
- Think about gradient accumulation
- Consider memory-efficient approaches to increase effective negatives
A conventional classifier ends in a weight matrix with one row per class, fixed at training time; adding a class means collecting labels and retraining. CLIP removes that matrix. Because its image and text embeddings share one space, the text encoder can write the classifier on demand: embed 'a photo of a dog' and 'a photo of a cat', and assign the image to whichever caption it is closer to. The previous topic produced the two aligned encoders; this one shows how they classify without any task-specific training. The best CLIP reaches 76.2 percent zero-shot top-1 on ImageNet, matching the original supervised ResNet-50 without using any of its 1.28 million labelled images. The catch is that the prompt is now part of the model. Writing 'a photo of a {label}.' instead of the bare label adds 1.3 points on ImageNet, and averaging 80 templates adds another 3.5, almost 5 points together. This topic covers prompts as classifiers, prompt engineering and prompt ensembling, and where zero-shot transfer still falls short, such as satellite imagery and counting.
Definition
Zero-shot transfer applies a model to a task without any training examples from that task. For CLIP, each class is described by a text prompt , and an image is assigned to the class whose prompt embedding has the highest cosine similarity with . The text embeddings act as classifier weights that can be rewritten for any label set.
In this topic
- 1Text Prompt as Classifier
- 2Prompt Engineering
- 3Prompt Ensembling
Text Prompt as Classifier
In zero-shot CLIP, classification works by: (1) encode the image, (2) encode text descriptions of each class (e.g., 'a photo of a dog', 'a photo of a cat'), (3) compute cosine similarity between the image embedding and each text embedding, (4) predict the class with highest similarity. The text prompts effectively define the classification head. The model has 'seen' concepts like dogs and cats during pretraining (via image-text pairs mentioning them) but has never been trained as a classifier with explicit labels.
Zero-shot classification works because CLIP's embedding space is a metric space where distances encode semantic relationships. A text prompt maps to a class prototype: . This is nearest-centroid classification in embedding space — no retraining needed because the shared space already encodes visual-semantic relationships.
You need to classify satellite images into 'urban', 'forest', 'water', and 'agricultural' categories using CLIP. CLIP was never trained on satellite imagery. Design text prompts and explain why this might still work.
Prompt Engineering
Why does 'a photo of a dog' beat 'dog'? CLIP's text encoder learned from captions, and single words are rare as captions. Bare labels can also be ambiguous ('crane': bird or machine). Wrapping the label in a template such as 'a photo of a {label}.' moves it toward the caption distribution and adds 1.3 points on ImageNet. Domain context helps further: the CLIP authors used 'a photo of a {label}, a type of pet.' for Oxford Pets and 'a satellite photo of a {label}.' for satellite datasets. The cost: templates are tuned by hand per dataset.
Different prompts for the same class map to different points in text embedding space, creating a variance cloud. Prompts closer to the centroid of CLIP's training distribution generalize better. Domain-specific prompts like 'a satellite image of' shift the class prototype toward the relevant submanifold of image space, reducing the distribution gap between training and test domains.
On Oxford-IIIT Pets (37 cat and dog breeds) the CLIP authors used the template 'a photo of a {label}, a type of pet.' instead of 'a photo of a {label}.'. Explain why the suffix should help on this dataset, and why the same suffix would be a bad choice on ImageNet.
Prompt Ensembling
Ensembling attacks the same problem statistically. Instead of trusting one template, embed each label with templates ('a photo of a {label}', 'a blurry photo of a {label}', 'a sculpture of a {label}' and so on), average the normalized text embeddings, and renormalize to get one prototype per class. With classes that is text-encoder passes, all done once offline. On ImageNet the CLIP authors ensembled 80 templates and gained 3.5 points over the single default prompt, almost 5 points together with prompt engineering. Averaging in embedding space rather than over probabilities keeps inference at one matrix multiply per image.
Averaging unit vectors and renormalizing gives a direction that keeps what the templates agree on, the label's meaning, and shrinks what they disagree on, wording quirks. If template errors were independent, their variance would fall as . They are not, since all templates share the label and the encoder's biases, so gains flatten quickly: 80 templates bought 3.5 points. Because the average is taken before the softmax, inference costs the same as a single prompt.
You have 3 templates and 1000 ImageNet classes. How many text encoding forward passes are needed? How can you make this efficient at inference time?
Theory Exercise
Problem:
A researcher claims that CLIP's zero-shot performance on ImageNet (76.2% top-1) proves that contrastive learning is superior to supervised learning for image classification. Critically evaluate this claim. What confounding factors exist? Design an experiment to fairly compare the two approaches.
Hints:
- Consider the difference in training data scale and diversity
- Think about what 'zero-shot' really means -- is CLIP truly zero-shot on ImageNet?
- Consider the compute budget comparison
CLIP left two questions open. Was its careful data collection essential, or would more and dirtier data do as well? And could one contrastively trained backbone serve detection, video and retrieval, not just whole-image classification? Three follow-ups answered in different ways. ALIGN (Google, 2021) skipped most curation: 1.8 billion alt-text pairs with only simple frequency and size filters, an EfficientNet-L2 image encoder and a BERT-Large text encoder, trained on 1,024 TPUv3 cores at batch 16,384, reaching 76.4 percent zero-shot on ImageNet. Florence (Microsoft, 2021) trained a hierarchical CoSwin-H image encoder on 900 million pairs and attached adapters for objects, video and vision-language tasks, reporting 83.74 percent zero-shot ImageNet top-1. EVA-CLIP (2023) attacked cost: start the image tower from a masked-image-modeling model, use the LAMB optimizer, and randomly drop half the image tokens, reaching 82.0 percent with 9 billion samples seen. The previous topic showed how CLIP classifies with prompts; this one compares what each variant changed and what the change bought.
Definition
ALIGN, Florence and EVA-CLIP are contrastive image-text models in CLIP's dual-encoder family that each change one main ingredient: ALIGN the data (1.8B lightly filtered pairs), Florence the image backbone and its task adapters (a hierarchical encoder extended to detection and video), and EVA-CLIP the training recipe (MIM-initialized encoders, LAMB, token dropping) for cheaper scaling.
In this topic
- 1ALIGN: Scaling with Noisy Data
- 2Florence: Hierarchical Features
- 3EVA-CLIP: Efficient Scaling
ALIGN: Scaling with Noisy Data
Is careful curation necessary? ALIGN tested the opposite bet. Its 1.8 billion pairs came from alt-text with only simple filters: drop images under 200 pixels on the short side or with aspect ratio above 3, drop alt-texts shared by more than 10 images (such as '1920x1080'), and drop texts with rare tokens or fewer than 3 or more than 20 words. There was no balanced query list like CLIP's. With an EfficientNet-L2 image tower, a BERT-Large text tower and batch 16,384, ALIGN reached 76.4 percent zero-shot on ImageNet, roughly CLIP's level. The lesson is that scale can substitute for curation, not that noise is harmless.
Model noise as dilution: if each pair is correct with probability , useful signal scales with , so billion needs only to match a perfectly clean 400M set. The model is crude in two ways. Wrong pairs are not neutral: a mismatched caption is a false positive that pulls unrelated embeddings together. And noise is not uniform: the filters ALIGN did apply, such as removing texts shared by many images, target the most systematic noise, the kind that would otherwise repeat and be learned.
CLIP uses 400M carefully filtered pairs. ALIGN uses 1.8B minimally filtered pairs. ALIGN's individual pair quality is lower, but it still matches CLIP. Quantitatively, why does 4.5x more data compensate for lower quality?
Florence: Hierarchical Features
Florence asked whether one contrastive model can be the foundation for every vision task, not just whole-image classification. Its image encoder, CoSwin-H, is a hierarchical Swin-style transformer that outputs feature maps at several resolutions, a pyramid in which early stages keep spatial detail and later ones summarize. Pretraining uses the UniCL contrastive objective on FLD-900M, 900 million image-text pairs, with 893M parameters (637M image, 256M language) trained for 10 days on 512 A100s. Breadth then comes from adapters: a Dynamic Head for object detection, a Video CoSwin adapter for video, and a METER adapter for vision-language tasks. CLIP's single pooled vector offers no such pyramid.
A hierarchical encoder downsamples in stages, for example strides 4, 8, 16 and 32, so a 384 px input gives maps of 96, 48, 24 and 12 cells per side. Early maps have small receptive fields and keep where things are; late maps have large receptive fields and encode what they are. A plain ViT keeps one stride-14 or stride-16 grid throughout, so multi-scale tasks must rebuild a pyramid from it. That structural difference, not a separate loss per level, is what makes Florence easy to extend to detection.
Florence claims to unify image classification, object detection, and visual grounding under one pretrained model. How do hierarchical features enable this? What would CLIP need to do for object detection?
EVA-CLIP: Efficient Scaling
Can CLIP training be made cheaper without losing accuracy? EVA-CLIP (Sun et al., 2023) combines several changes. The image encoder starts from EVA, a model pretrained by masked image modeling to reconstruct CLIP features, rather than from random weights. Training uses the LAMB optimizer, designed for very large batches. Half of the image tokens are randomly dropped during training, which roughly halves image-tower compute and allows a batch twice as large in the same memory; FlashAttention speeds up the rest. The 5.0B EVA-02-CLIP-E/14+ reached 82.0 percent zero-shot ImageNet top-1 after 9 billion samples, and the 430M L/14+ reached 80.4 percent after 6 billion.
Token dropping changes the cost arithmetic directly. For image tokens, a ViT layer's MLPs and projections scale with and its attention scores with ; keeping 50 percent of the tokens halves the first and quarters the second, roughly halving tower time. The model sees incomplete images during training, which acts like augmentation, and is evaluated on full images. EVA-CLIP reports that MIM initialization, LAMB and dropping together let a 430M model reach 80.4 percent zero-shot after 6 billion samples.
EVA-CLIP pretrains the vision encoder with masked image modeling before contrastive learning. Why does this two-stage approach help compared to contrastive-only training?
Theory Exercise
Problem:
You are designing a contrastive VLM for a domain with 50M image-text pairs (medical imaging). Compare three strategies: (A) Train from scratch with CLIP's recipe, (B) Fine-tune CLIP on your data, (C) Use ALIGN's approach with 500M weakly-related medical web data. Analyze the tradeoffs considering data efficiency, compute cost, and expected performance.
Hints:
- Think about domain shift between web data and medical images
- Consider what CLIP's pretrained features already know about medical images
- Factor in the cost of data collection for each approach
By now contrastive models look close to magical: they classify unseen categories, retrieve images from free text and supply the vision encoder of most VLMs. Their failures are just as systematic, and they come from the objective itself. The InfoNCE loss only asks the model to rank the true caption above the other captions in the batch, and random web captions almost never differ only in word order, an attribute swap or a negation, so nothing forces the text encoder to care about those. With the released CLIP ViT-B/32 text encoder, 'a horse riding an astronaut' and 'an astronaut riding a horse' have cosine similarity 0.95, and 'a room with furniture' versus 'a room with no furniture' 0.97, both higher than 'a photo of a dog' versus 'a photo of a cat' at 0.93. This topic examines three failures, bag-of-words behaviour, negation blindness and attribute binding, as measured by ARO, NegBench and Winoground. It also covers the partial fix of hard negatives, as in NegCLIP, and why these limits pushed the field toward the generative VLMs of the next chapter.
Definition
The limitations of contrastive pre-training are systematic errors that follow from training with only a global image-caption matching score: insensitivity to word order and relations (bag-of-words behaviour), to negation, and to which attribute belongs to which object. They appear whenever a test demands distinctions that random in-batch negatives almost never required.
In this topic
- 1The Bag-of-Words Problem
- 2Negation Blindness
- 3Attribute Binding Failures
The Bag-of-Words Problem
CLIP's text encoder is a transformer with positional embeddings, so it can represent word order; the problem is that training rarely requires it. A random negative caption differs from the true one in its content words, so matching on which objects and attributes are mentioned already wins nearly every batch. Yuksekgonul et al. (ARO) measured the consequence. Asked to pick the real caption over four word-shuffled versions, CLIP succeeds only 46 percent of the time on COCO and 59 percent on Flickr30k, and on Visual Genome Relation, a two-way choice, it scores 63 percent. They call this bag-of-words behaviour.
The loss depends on the text only through one vector , read at the end-of-text token. If for nearly every training batch some function of the multiset of words already ranks the true caption first, gradient descent has no reason to make sensitive to order; order-sensitivity is never penalized, so it is only weakly learned. ARO's remedy follows directly: add batches where order matters, with hard negatives made by shuffling words. NegCLIP did this and raised COCO Order from 46 to 86 percent.
CLIP is tested on 'a horse riding an astronaut' vs 'an astronaut riding a horse'. Despite the captions being semantically opposite, CLIP assigns similar scores to both. Why?
Negation Blindness
Negation is the clearest case of a distinction training never asked for. Alt-text describes what is in a picture; captions like 'a street with no cars' are rare, and when they occur the image usually still has something to do with cars. So the text encoder learns that 'cars' signals cars and gives 'no' little weight. Measured directly, CLIP ViT-B/32 rates 'a room with furniture' and 'a room with no furniture' at cosine similarity 0.97. NegBench (Alhamoud et al., 2025) found CLIP-style models often perform at chance on negated queries; fine-tuning on synthetic negated captions raised recall by 10 percent and multiple-choice accuracy by 28 percent.
Measured with CLIP ViT-B/32's text encoder, the embeddings of 'a room with furniture' and 'a room with no furniture' have cosine 0.968, while 'a photo of a dog' and 'a photo of a car', which differ in the object, are at 0.878. Negation moves the embedding less than swapping the noun does. Since the loss only penalizes failures that occur in training batches, and negated captions are rare in alt-text, nothing pushes that gap open. NegBench narrows it by adding millions of synthetic negated captions.
Design a test to measure CLIP's negation understanding. Create 5 image-text pairs where negation changes the correct match.
Attribute Binding Failures
Attribute binding refers to correctly associating adjectives with their nouns: in 'a red car and a blue truck', 'red' binds to 'car' and 'blue' binds to 'truck'. CLIP frequently confuses these bindings because its global embedding merges all attributes and objects into one vector. The Winoground benchmark specifically tests this: it presents two images and two captions where the same entities appear with swapped attributes, and CLIP performs near chance level.
Binding needs structure: 'a red car and a blue truck' asserts red(car) and blue(truck). A single pooled vector could in principle encode that, but the contrastive loss only rewards it when a batch contains the swapped caption, which random negatives almost never provide. So the learned behaves roughly like a function of the set of words, red, blue, car and truck, and both captions land in nearly the same place. Winoground's low image score shows the image encoder has the same problem.
On Winoground a model earns the text score for an example if each image prefers its own caption, the image score if each caption prefers its own image, and the group score only if both hold. Chance is 25, 25 and 16.67 percent. CLIP ViT-B/32 scores 30.75, 10.50 and 8.00. How can a model fall below chance, and what does the gap between its text and image scores reveal?
Theory Exercise
Problem:
Propose a modified training objective that addresses CLIP's compositionality failures while retaining the efficiency of contrastive learning. Your proposal should handle attribute binding, negation, and word order. Discuss the tradeoffs your approach introduces.
Hints:
- Think about hard negative mining with compositionally similar captions
- Consider adding an auxiliary loss that explicitly tests word order
- Look at how NegCLIP and ARO benchmarks address this