CLIP: Contrastive Language-Image Pre‑training

Generative Models · v1.0.8

2026-11-24 16:44:03

Where we are

Where this fits

  • Earlier units: a fixed set of predetermined categories
  • Every new concept needs new labelled data
  • CLIP replaces the closed label set with the text already beside the image
  • Result: one shared embedding space, scored by a dot product

Outline of key topics

  • Natural language as supervision; the WebImageText dataset
  • The symmetric contrastive objective, and why not prediction
  • Dual encoders, and how each scales
  • Zero-shot transfer: class names as classifier weights
  • Effective robustness under natural distribution shift
  • Failures, and what CLIP enabled

Natural language as supervision

The cost of a closed label set

A fixed category set limits generality: every new concept needs new labelled data.

Natural language supervision — learn perception from the text already paired with the image.

  • Scales with the web, not an annotation budget
  • No 1-of-N gold label required
  • Binds representation to language, enabling zero-shot transfer

A closed label set bounds what a model can ever say.

Why earlier attempts underperformed

The record

  • Mori (1999): nouns and adjectives in paired documents
  • Joulin (2016): CNNs predict caption words
  • Li (2017): phrase n-grams, zero-shot by scoring class names

Li reaches 11.5% on ImageNet, against 88.4% for the state of the art.

The diagnosis: scale, not principle

  • Mahajan, Kolesnikov: billions of images, accelerator years
  • VirTex, ICMLM, ConVIRT: 100–200k images, accelerator days
  • Weakly supervised work: 1000 and 18291 classes, static softmax, no dynamic outputs

WebImageText

WIT — 400M (image, text) pairs from public internet sources.

  • 500,000 queries — Wikipedia words above 100 occurrences, high-PMI bi-grams, article names, WordNet synsets
  • Query-conditioned search — the text must contain a query; coverage broad by construction
  • Class balancing — up to 20,000 pairs per query

Word count comparable to WebText, the GPT-2 training set.

The contrastive objective

Training efficiency as the criterion

Zero-shot ImageNet accuracy against images processed.
  • Caption-predicting transformer: 3x slower than a bag-of-words baseline
  • Predictive → contrastive: a further 4x
  • Both predictive objectives chase the exact words of the text

The task

From a batch of \(N\) (image, text) pairs, predict which of the \(N \times N\) pairings occurred.

  • Maximise cosine similarity: the \(N\) real pairs
  • Minimise it: the \(N^2 - N\) wrong pairings
  • Symmetric cross-entropy over the scores

The negatives are the rest of the batch, so a larger batch is a harder task.

The embedding and the logits

Encode, project by a learned linear map, L2-normalise:

\[ \mathbf{u}_i = \frac{W_I\, f_I(x_i)}{\lVert W_I\, f_I(x_i) \rVert}, \qquad \mathbf{v}_j = \frac{W_T\, f_T(t_j)}{\lVert W_T\, f_T(t_j) \rVert} \tag{1} \]

Logits: pairwise cosine similarity, scaled by a learned temperature:

\[ s_{ij} = \class{hg-key}{\mathbf{u}_i^{\top}\mathbf{v}_j} \cdot \class{hg-alt}{\exp(t)}, \qquad \exp(t) = 1/\tau \tag{2} \]

  • blue: cosine similarity, bounded in \([-1, 1]\)
  • rust: inverse temperature, setting how peaked the softmax is

The symmetric loss

Row \(i\)’s label is column \(i\). Cross-entropy once across rows, once down columns:

\[ \begin{aligned} \mathcal{L}_{\text{image}} &= -\frac{1}{N}\sum_{i=1}^{N} \log \frac{\exp(s_{ii})}{\sum_{j} \exp(s_{ij})} \\[3pt] \mathcal{L}_{\text{text}} &= -\frac{1}{N}\sum_{j=1}^{N} \log \frac{\exp(s_{jj})}{\sum_{i} \exp(s_{ij})} \\[3pt] \mathcal{L} &= \tfrac{1}{2}\left(\mathcal{L}_{\text{image}} + \mathcal{L}_{\text{text}}\right) \end{aligned} \tag{3} \]

Averaging the two makes the loss symmetric in the modalities.

The similarity matrix

\(N\) outlined targets; \(N^2 - N\) negatives.

The temperature

  • \(\tau\) optimised directly as a log-parameterised scalar, initialised at \(0.07\)
  • Clipped at 100x — required to prevent training instability

Reference implementation

# extract feature representations of each modality
I_f = image_encoder(I)   # [n, d_i]
T_f = text_encoder(T)    # [n, d_t]

# joint multimodal embedding [n, d_e]
I_e = l2_normalize(np.dot(I_f, W_i), axis=1)
T_e = l2_normalize(np.dot(T_f, W_t), axis=1)

# scaled pairwise cosine similarities [n, n]
logits = np.dot(I_e, T_e.T) * np.exp(t)

# symmetric loss function
labels = np.arange(n)
loss_i = cross_entropy_loss(logits, labels, axis=0)
loss_t = cross_entropy_loss(logits, labels, axis=1)
loss   = (loss_i + loss_t)/2

Paper Figure 3. Labels are np.arange(n): image \(i\) belongs with text \(i\).

Simplifications

The set is large enough that over-fitting is not a concern, so Zhang et al. (2020) is simplified.

  • Both encoders from scratch — no ImageNet init, no pre-trained language model
  • Linear projection only — no non-linear head
  • Random square crop — the only augmentation
  • Temperature optimised, not tuned

Encoders and scaling

The image encoder

  • Modified ResNet — ResNet-D, antialiased rect-2 blur pooling, and attention pooling in place of global average pooling

    One layer of transformer-style multi-head QKV attention, the query conditioned on the global average-pooled image

  • Vision Transformer — Dosovitskiy et al. (2020), plus a layer norm on the combined patch and position embeddings

The text encoder

A Transformer, modified after Radford et al. (2019).

  • 63M parameters, 12 layers, 512 wide, 8 heads
  • Lower-cased BPE, vocabulary 49,152, sequence capped at 76
  • [EOS] activations at the top layer are the text feature — layer normalised, then linearly projected
  • Masked self-attention throughout, allowing later initialisation from a language model

One dot product, and nothing else

The only cross-modal interaction: a single dot product in the joint space.

  • Nothing fused early — a classifier is computed once and cached
  • Retrieval over a large corpus is one matrix product
  • ViLBERT, UNITER: three or more subsystems with dense joint attention

This is the property the next unit turns into a guidance signal.

Scaling and training

Scaling

  • Compute equally across width, depth, resolution (Tan & Le, 2019)
  • Text encoder scales in width only
  • Five ResNets, three ViTs, to RN50x64 and ViT-L/14

Training

  • 32 epochs, Adam, decoupled weight decay, cosine schedule
  • Minibatch 32,768
  • Mixed precision, gradient checkpointing, sharded similarity
  • RN50x64: 18 days on 592 V100s
  • “CLIP” means ViT-L/14@336px

Zero-shot transfer

The construction

The text encoder synthesises a classifier from the target dataset’s class names.
  • Embed image and every candidate text; cosine similarity, scale by \(\tau\), softmax
  • Cached once computed — cost amortised over the dataset

The text encoder as a hypernetwork

\[ \begin{aligned} Pr(y = c \mid x) &= \frac{\exp\!\left(\class{hg-key}{\mathbf{u}^{\top}\mathbf{w}_c} / \tau\right)} {\sum_{c'=1}^{C} \exp\!\left(\mathbf{u}^{\top}\mathbf{w}_{c'} / \tau\right)} \\[3pt] \mathbf{w}_c &= \frac{W_T\, f_T\!\left(\text{prompt}(c)\right)} {\lVert W_T\, f_T\!\left(\text{prompt}(c)\right) \rVert} \end{aligned} \tag{4} \]

Multinomial logistic regression: normalised inputs and weights, no bias, temperature scaling.

  • Image encoder: the vision backbone
  • Text encoder: a hypernetwork writing the weights \(\mathbf{w}_c\)
  • New class names, new classifier, no gradient steps

Prompt engineering

Released class names are often unhelpful.

  • Polysemy — ImageNet holds construction cranes and cranes that fly; boxer is a breed, not an athlete
  • Distribution mismatch — paired text is a sentence, rarely one word

"A photo of a {label}." — +1.3% alone. Task context adds more: a type of pet, a satellite photo of, quotes for OCR.

Prompt ensembling

\(K\) prompts combined in embedding space, not probability space:

\[ \mathbf{w}_c \;\propto\; \frac{1}{K}\sum_{k=1}^{K} \frac{W_T\, f_T\!\left(\text{prompt}_k(c)\right)} {\lVert W_T\, f_T\!\left(\text{prompt}_k(c)\right) \rVert} \tag{5} \]

  • One averaged set is cached — the ensemble costs what a single classifier costs
  • 80 prompts on ImageNet add a further 3.5%

Engineering plus ensembling: almost 5%, comparable to 4x the compute, free once cached.

How good is it

Zero-shot CLIP against a supervised ResNet-50 probe.
  • Wins on 16 of 27 datasets
  • 76.2% top-1 on ImageNet — the original ResNet-50, without its 1.28M labels
  • +14.5% on Kinetics700 action recognition
  • Weak on satellite imagery, tumour detection, counting, traffic signs

Robustness under distribution shift

Effective robustness

Effective robustness: the vertical distance above the trend. Relative robustness: any gain at all.

CLIP’s result

Zero-shot CLIP shrinks the robustness gap by up to 75%.
  • ResNet-101: five times the mistakes on the seven natural shifts
  • Nearly every model in Taori et al. (2020) saw ImageNet
  • A zero-shot model cannot exploit correlations of a distribution it never saw
  • Zero-shot CLIP closes up to 75% of the gap

The trade-off when adapting

A logistic probe on CLIP features: ImageNet +9.2%, to 85.4%, about three years of progress. Accuracy under shift slightly decreases.

  • Rises only on ImageNetV2, which followed the original creation process
  • Falls elsewhere: 4.7% ImageNet-R, 3.8% ObjectNet, 2.8% Sketch

Effective robustness follows from minimising distribution-specific training data.

Limits and what CLIP enabled

Where CLIP fails

  • Fine-grained classification — car models, flower species, aircraft variants
  • Abstract and systematic tasks — counting objects
  • Genuinely novel tasks — distance to the nearest car is near random
  • Out-of-distribution data — 88% on MNIST, below logistic regression on raw pixels; almost no MNIST-like images in pre-training

CLIP assumes a large enough dataset makes everything in-distribution; MNIST violates it.

Structural limits

  • Zero-shot chooses among given concepts — it cannot generate novel output
  • Data efficiency compensated for, not addressed: 12.8B images at one per second is 405 years
  • Overall state of the art: an estimated 1000x more compute
  • Uncurated data and open class design put the consequences with the deployer

Summary

  • Supervision scales with the web, not an annotation budget
  • The easier proxy task — which caption, not which words — bought 4x, over a baseline already 3x faster
  • The text encoder is a hypernetwork, so any list of class names is a classifier
  • How the prompt is written is part of the model
  • Not fitting a dataset is what buys robustness to its shifts
  • The failures are as informative as the successes

Where next: CLIP as a guidance signal

  • A diffusion model is steered by the gradient of any differentiable score
  • CLIP supplies that score as one dot product in a shared space

\[ \nabla_{x}\,\class{hg-key}{\mathbf{u}(x)^{\top}\mathbf{v}(\text{prompt})} \tag{6} \]

Next: CLIP Guided Image Diffusion — classifier-guided diffusion, then GLIDE, comparing CLIP guidance against classifier-free.

A CLIP score is optimisable, and a generator optimising it can find samples that score well and look wrong.