v9.1.1
Menu

Chapter 5: Contrastive Learning & CLIP

Week 5-6

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

Explainer video
1
Contrastive Foundations

How pulling positives together and pushing negatives apart creates structured embedding spaces — the core paradigm behind vision-language alignment.

Positive and Negative PairsRepresentation Learning via SimilarityNoise Contrastive Estimation (NCE)
Mathematical formalization
2
InfoNCE Loss

The mathematical objective connecting contrastive learning to mutual information estimation, with temperature as the key control parameter.

The InfoNCE ObjectiveTemperature ParameterConnection to Mutual Information
Theory applied at scale
3
CLIP Training

Scaling contrastive learning to 400M web-scraped pairs with dual encoders and massive batch sizes — from theory to breakthrough.

WebImageText (WIT) DatasetDual Encoder ArchitectureBatch-Level Contrastive Objective
Two directions from CLIP

What CLIP enables vs. how others scale the idea

4
Zero-Shot Transfer

Using text prompts as flexible classifiers — matching supervised models on dozens of benchmarks without a single labeled example.

Text Prompt as ClassifierPrompt EngineeringPrompt Ensembling
5
Scaling Variants

How ALIGN, Florence, and EVA-CLIP push the recipe further with noisier data, hierarchical features, and efficient initialization.

ALIGN: Scaling with Noisy DataFlorence: Hierarchical FeaturesEVA-CLIP: Efficient Scaling
Shared failure modes across all variants
6
Fundamental Limitations

Why contrastive models fail at compositionality, negation, and attribute binding — the failures that motivate generative approaches.

The Bag-of-Words ProblemNegation BlindnessAttribute Binding Failures

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 ff and gg so that a similarity score s(f(x),g(y))s(f(x), g(y)) 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

  1. 1Positive and Negative Pairs
  2. 2Representation Learning via Similarity
  3. 3Noise Contrastive Estimation (NCE)
1 of 3
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 NN, each image has 1 positive and N−1N-1 negatives, and the whole batch has NN positives and N2−NN^2 - N 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.

Mathematical Intuition

Each anchor's loss is an NN-way classification, so a model that knows nothing scores ln⁡N\ln N nats: 1.39 for N=4N = 4 and 10.40 for N=32,768N = 32{,}768. Doubling NN raises that ceiling by ln⁡2\ln 2 nats, one bit. That is the precise sense in which more negatives add a bit: the InfoNCE bound on mutual information can never exceed ln⁡N\ln N, 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.

Example:

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?

2 of 3
Representation Learning via Similarity

sim(u,v)=u⋅v∥u∥⋅∥v∥=cos⁡(θ)\text{sim}(\mathbf{u}, \mathbf{v}) = \frac{\mathbf{u} \cdot \mathbf{v}}{\|\mathbf{u}\| \cdot \|\mathbf{v}\|} = \cos(\theta)

Once pairs are defined, the model needs a score for how alike two embeddings are. CLIP uses cosine similarity, the formula's sim(u,v)\text{sim}(\mathbf{u}, \mathbf{v}): the dot product of u\mathbf{u} and v\mathbf{v} after each is scaled to unit length, which equals the cosine of the angle θ\theta between them and lies in [−1,1][-1, 1]. 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 ∥u−v∥2=2−2cos⁡θ\|\mathbf{u} - \mathbf{v}\|^2 = 2 - 2\cos\theta.

Mathematical Intuition

On the unit sphere in d=512d = 512 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.

Example:

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?

3 of 3
Noise Contrastive Estimation (NCE)

log⁡pd(x)pd(x)+k⋅pn(x)\log \frac{p_d(x)}{p_d(x) + k \cdot p_n(x)}

NCE reframes density estimation as a binary classification problem: distinguish real data from noise. Given a data sample xx, the model must classify whether xx came from the true data distribution pdp_d or a noise distribution pnp_n. 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.

Mathematical Intuition

Gutmann and Hyvärinen showed NCE is consistent for any number of noise samples kk: with enough data it recovers the true density, including ln⁡Z\ln Z. What kk controls is statistical efficiency, since the estimator's variance approaches that of maximum likelihood as kk grows. InfoNCE borrows the idea but changes the question from 'data or noise?' for one sample to 'which of these NN candidates is the real partner?', a categorical classification rather than a binary one.

Example:

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