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
- 3
- Min read
- 34
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
Contrastive learning is a self-supervised paradigm that learns representations by comparing data points. The core idea: given an anchor sample, pull representations of positive pairs (semantically similar) closer while pushing negative pairs (semantically different) apart. This creates a structured embedding space without explicit labels.
In the vision-language context, positive pairs are matched image-text pairs from the training data, and negative pairs are all other combinations within a batch. The quality of learned representations depends critically on having enough negative examples -- this is why CLIP uses batch sizes of 32,768.
In this topic
- 1Positive and Negative Pairs
- 2Representation Learning via Similarity
- 3Noise Contrastive Estimation (NCE)
Positive and Negative Pairs
In contrastive learning, every training step requires defining what counts as a positive pair (should be similar) and a negative pair (should be different). For vision-language models, a positive pair is an image paired with its correct caption. Every other image-caption combination in the batch forms a negative pair. With a batch size of , each anchor has positive and negatives. The ratio of negatives to positives is crucial: too few negatives leads to representation collapse (everything maps to the same point); too many creates computational challenges.
The ratio of negatives to positives directly controls the tightness of learned embeddings. With negatives, the variational lower bound on mutual information is . CLIP uses batch sizes of 32,768 not just for more data, but to tighten the bound on — doubling batch size adds exactly 1 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
Contrastive methods learn by optimizing a similarity function between representations. The most common choice is cosine similarity: . This normalizes vectors to the unit hypersphere, making the similarity range . Alternatives include dot product (unbounded, sensitive to magnitude) and Euclidean distance (used in some metric learning formulations). Cosine similarity is preferred because it decouples direction (semantic meaning) from magnitude (confidence).
Cosine similarity constrains embeddings to the unit hypersphere . The capacity of this surface grows exponentially with dimension: in , roughly nearly-orthogonal vectors can coexist. This means the embedding space can represent billions of distinct concepts without interference — the geometric reason high-dimensional contrastive learning works.
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.
NCE converts intractable density estimation into tractable logistic regression. The normalizing constant becomes a learnable parameter rather than a computed quantity. As noise samples , the NCE objective converges to maximum likelihood, but any finite gives an efficient approximation with bounded error .
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
InfoNCE (Information Noise Contrastive Estimation) is the loss function that powers CLIP and most modern contrastive learning systems. It connects contrastive learning to information theory: minimizing InfoNCE maximizes a lower bound on the mutual information between the two modalities. Understanding its derivation, the role of temperature, and its connection to cross-entropy reveals why it works so well.
In this topic
- 1The InfoNCE Objective
- 2Temperature Parameter
- 3Connection to Mutual Information
The InfoNCE Objective
Given a batch of image-text pairs, InfoNCE treats each pair as a -way classification problem: the correct text for image is class . The probability is computed via softmax over scaled cosine similarities. The loss is the average cross-entropy over all samples, applied symmetrically for both image-to-text and text-to-image directions.
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.
Temperature controls softmax entropy. At , the distribution becomes a hard argmax (only the most similar pair contributes gradient). At , it becomes uniform (all pairs contribute equally). The optimal balances ignoring hard negatives ( too high) against gradient instability ( too low). CLIP parameterizes it as to ensure positivity.
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
InfoNCE provides a lower bound on the mutual information between the two modalities: . This means minimizing the contrastive loss maximizes a lower bound on how much information the image representation captures about the text (and vice versa). The bound tightens with larger batch sizes , which is why CLIP benefits enormously from large batches -- it can capture more mutual information.
InfoNCE loss equals the negative NCE lower bound on . By the data processing inequality, for encoders . Training maximizes the left side, learning representations that preserve maximal mutual information between modalities. The gap between sides measures how much information the encoders discard.
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
CLIP's training pipeline combines three breakthroughs: a massive web-scraped dataset (400M image-text pairs), a dual-encoder architecture with separate vision and text transformers, and a batch-level contrastive objective computed across 32,768 pairs simultaneously. Understanding how these components interact -- and the engineering required to make them work at scale -- is essential for anyone building or fine-tuning vision-language models.
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.
Web-scraped data follows a long-tailed distribution where common concepts appear in millions of pairs and rare concepts in tens. Effective vocabulary of visual concepts scales as — quadrupling data doubles concept coverage. The 400M scale ensures even tail concepts have sufficient representation for the contrastive signal to learn meaningful distinctions.
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's largest model uses ViT-L/14 (image encoder with 304M parameters) and a text transformer with 63M parameters. Why is the image encoder so much larger than the text encoder?
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.
In a batch of pairs, the loss creates an similarity matrix and applies cross-entropy along both axes — equivalent to classification problems each over classes. The gradient from every sample provides supervision for every other sample, giving learning signal from data. This quadratic scaling is why large batches are so effective.
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
CLIP's most remarkable capability is zero-shot classification: classifying images into categories the model has never been explicitly trained on, using only natural language descriptions. Instead of learning a fixed set of class logits, CLIP uses text embeddings as dynamic class prototypes. This means any classification task can be performed by simply writing text descriptions of the categories -- no fine-tuning, no labeled data, no retraining.
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
The choice of text prompt dramatically affects zero-shot performance. Simple class names ('dog') underperform compared to contextualized prompts ('a photo of a dog'). This is because CLIP was trained on natural text, not isolated words. The context 'a photo of' bridges the distribution gap between class labels and web captions. Prompt ensembling averages predictions across multiple prompt templates ('a photo of a dog', 'a good photo of a dog', 'a drawing of a dog'), further improving robustness by up to 3-5% on benchmarks.
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.
For ImageNet zero-shot classification, CLIP uses 80 prompt templates. The template 'a photo of a {class}, a type of pet' improves accuracy on pet breeds by 4% over 'a photo of a {class}'. Why does domain-specific context help?
Prompt Ensembling
Instead of using a single text prompt per class, prompt ensembling generates multiple prompts from different templates and averages the resulting text embeddings. Given templates and classes, this creates text embeddings. The averaged embedding per class is more robust to prompt wording choices. CLIP uses 80 templates including 'a photo of a {class}', 'a blurry photo of a {class}', 'a sculpture of a {class}', etc. This provides a consistent 2-5% accuracy improvement across benchmarks.
Averaging prompt embeddings computes the centroid on the unit hypersphere: . This reduces variance by while preserving the semantic direction. It's a bias-variance tradeoff: individual prompts may be more precisely targeted, but the ensemble is robust to phrasing artifacts.
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's success sparked a wave of contrastive VLM research. ALIGN (Google, 2021) showed that noisier data at even larger scale (1.8B pairs) could match CLIP without careful curation. Florence (Microsoft, 2021) introduced hierarchical visual features for multi-level understanding. EVA-CLIP (2022-2023) pushed efficiency and scale further with improved training recipes. Each variant addresses a different limitation of the original CLIP, collectively defining the frontier of contrastive vision-language pretraining.
In this topic
- 1ALIGN: Scaling with Noisy Data
- 2Florence: Hierarchical Features
- 3EVA-CLIP: Efficient Scaling
ALIGN: Scaling with Noisy Data
ALIGN (A Large-scale ImaGe and Text) used 1.8 billion image-text pairs with minimal filtering -- only a basic frequency-based filter to remove rare texts and near-duplicate images. Despite the noise (many pairs are weakly correlated), ALIGN matched CLIP's performance by relying on sheer scale. The key insight: for contrastive learning, data quantity can compensate for data quality because the loss function only needs relative rankings, not exact correspondences.
If each noisy pair has probability of being correct, effective dataset size is . With 1.8B pairs at ~50% quality, ALIGN's effective clean data is ~900M — exceeding CLIP's 400M curated pairs. Contrastive learning is inherently noise-robust: random mismatches become easy negatives that barely affect gradient direction, so noise degrades signal linearly rather than catastrophically.
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 extends contrastive learning with a hierarchical approach to visual representation. Instead of a single global embedding per image, Florence learns representations at multiple granularity levels: scene-level (coarse), object-level (medium), and region-level (fine). This enables the model to perform diverse downstream tasks from image classification (scene-level) to object detection (region-level) without task-specific architectures. Florence also uses a unified adapter framework for efficient fine-tuning across tasks.
Florence combines features from multiple encoder depths. Early layers capture spatial frequencies cycles/pixel (texture, edges), while deeper layers capture semantics. Concatenating across scales creates a representation spanning multiple abstraction levels — enabling both fine-grained (texture transfer) and coarse-grained (scene classification) tasks from one model.
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
EVA-CLIP achieves CLIP-level performance with significantly less compute by using better training recipes. Key innovations: (1) Masked image modeling (MIM) pretraining of the vision encoder before contrastive training, so it starts from a stronger initialization. (2) LAMB optimizer for more stable large-batch training. (3) Progressive training: start with low resolution and small model, gradually increase both. EVA-CLIP-18B is the largest open CLIP model with 18 billion parameters, achieving state-of-the-art zero-shot performance.
Initializing with a masked image modeling (MIM) pretrained encoder places the model near a good basin on the loss landscape. Contrastive fine-tuning then needs only small parameter updates — reducing the effective optimization distance. In practice, this means EVA-CLIP converges in fewer steps and reaches better optima than training from scratch, despite using identical architecture and data.
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
Despite CLIP's impressive zero-shot capabilities, contrastive pre-training has fundamental limitations that motivate the move toward generative VLMs. These are not minor issues fixable with more data or bigger models -- they are structural problems inherent to how contrastive objectives learn. Understanding these limitations is essential for knowing when to use (and when not to use) contrastive models.
In this topic
- 1The Bag-of-Words Problem
- 2Negation Blindness
- 3Attribute Binding Failures
The Bag-of-Words Problem
Contrastive models treat text more like a bag of words than an ordered sequence for alignment purposes. The caption 'a red car on a blue road' and 'a blue car on a red road' produce nearly identical text embeddings because they contain the same words. The global pooling that produces a single embedding discards word order and compositional structure. This means CLIP cannot reliably distinguish images where the same objects are present but in different configurations.
Contrastive loss optimizes global similarity , which is invariant to word permutation. 'Dog chases cat' and 'cat chases dog' produce nearly identical text embeddings because the loss never requires distinguishing them — both correctly match an image containing a dog and a cat. The objective has no compositional structure.
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
CLIP struggles with negation: 'a photo with no people' and 'a photo with people' produce similar embeddings. The contrastive objective does not explicitly learn logical operators like negation because web captions rarely use negation ('no people in this image' is uncommon vs 'people in this image'). Negation requires understanding what is absent, while contrastive learning is optimized for identifying what is present.
For text encoder , . Negation words are low-frequency tokens receiving small attention weights, so the representation is dominated by content words. The contrastive loss provides no mechanism to specifically penalize this — negated descriptions almost never appear as hard negatives in web data.
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 requires compositional structure: 'red car, blue sky' needs independent associations (red→car) and (blue→sky). Global contrastive matching collapses this to a set . The model learns rather than — a fundamental limitation of bag-level similarity.
On the Winoground benchmark, CLIP ViT-B/32 achieves only 10% group accuracy (random baseline: 25%). This is worse than random. How is this possible, and what does it 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