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
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

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

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

  1. 1Positive and Negative Pairs
  2. 2Representation Learning via Similarity
  3. 3Noise Contrastive Estimation (NCE)
1 of 3
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 NN, each anchor has 11 positive and N−1N-1 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.

Mathematical Intuition

The ratio of negatives to positives directly controls the tightness of learned embeddings. With kk negatives, the variational lower bound on mutual information is log⁡(k)\log(k). CLIP uses batch sizes of 32,768 not just for more data, but to tighten the bound on I(X;Y)I(X;Y) — doubling batch size adds exactly 1 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)

Contrastive methods learn by optimizing a similarity function between representations. The most common choice is cosine similarity: sim(u,v)=u⋅v∥u∥∥v∥\text{sim}(\mathbf{u}, \mathbf{v}) = \frac{\mathbf{u} \cdot \mathbf{v}}{\|\mathbf{u}\| \|\mathbf{v}\|}. This normalizes vectors to the unit hypersphere, making the similarity range [−1,1][-1, 1]. 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).

Mathematical Intuition

Cosine similarity constrains embeddings to the unit hypersphere Sd−1S^{d-1}. The capacity of this surface grows exponentially with dimension: in d=512d=512, roughly e512e^{512} 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.

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

NCE converts intractable density estimation p(x)=f(x)/Zp(x) = f(x)/Z into tractable logistic regression. The normalizing constant ZZ becomes a learnable parameter rather than a computed quantity. As noise samples k→∞k \to \infty, the NCE objective converges to maximum likelihood, but any finite kk gives an efficient approximation with bounded error O(1/k)O(1/k).

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