Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

~7 min readOpenAI · 2021

CLIP,
explained.

Vision models and language models each lived in their own universe, unable to talk. This 2021 paper built a shared one — a single map where a photo of a golden retriever and the words "a photo of a dog" land in the same neighborhood. That bridge between pixels and language is what lets you type a sentence and get back a picture.

The delta

What changes here: the label set stops being fixed

Rung 1, so the comparison is against supervised image classification. A classifier is trained against a fixed list of categories, and that list is the ceiling on what it can ever say — recognising a new kind of thing means new labelled data and a new output layer. The labels are also expensive, which caps the data.

The change is to supervise with language instead of labels. Train an image encoder and a text encoder together on image-caption pairs so that a picture and its own caption land close together in one shared space, and mismatched pairs land apart — the contrastive objective from the vision ladder, with a caption in place of a second crop. The supervision now comes from text that already existed alongside the images, so the training set is roughly 400 million pairs scraped from the web rather than a hand-annotated corpus.

What falls out is the property that made it famous. Because the "labels" are arbitrary sentences, classification becomes a retrieval: write out candidate class names as short phrases, encode them, and pick whichever is nearest the image. You can classify into categories that were never a training target, define new ones at inference time by typing them, and — stated in units — match a strong supervised model on ImageNet without training on ImageNet at all. The fixed output layer is gone, replaced by a text encoder.

01

Two separate worlds

Before CLIP, a vision model was trained on a fixed list of labels — say, the 1,000 categories of ImageNet — and could only ever recognize those. Ask it about anything outside its list and it was helpless. Worse, building it meant an army of humans hand-labeling millions of images into rigid buckets.

Meanwhile language models understood rich, open-ended text. The two never met. What if a model could learn about images the way a person browsing the web does — from pictures paired with the captions people wrote for them?

02

The idea: one shared space

CLIP — Contrastive Language-Image Pre-training — trains two encoders at once: one that turns an image into a vector, one that turns text into a vector. The goal is to align them so that a picture and its matching description land at nearly the same spot in a single shared embedding space.

Once images and words live on the same map, you can measure how well any picture matches any sentence just by checking how close their vectors are. Pixels and language become directly comparable.

03

How: contrastive learning at scale

Take a batch of image-caption pairs. Embed every image and every caption. Now train so each image is closest to its own caption and far from every other caption in the batch — pull the true pairs together, push the impostors apart.

Match each image to its caption (diagonal = correct pairs)
"a dog"
"a car"
"a tree"
🐕 image
✓
·
·
🚗 image
·
✓
·
🌳 image
·
·
✓

Done across 400 million image-caption pairs scraped from the web — natural-language supervision, no hand-labeling — the two encoders converge into one aligned space. The scale of that freely-available data is what made it work.

The objective is precise. For a batch of N pairs, embed the images and captions, L2-normalize, and form the N×N cosine-similarity matrix scaled by a learned temperature. The correct match for row i is column i — the diagonal — so it's just cross-entropy, run both directions:

One batch of N pairs supplies N positives and N²−N negatives for free — which is why a huge batch is part of the recipe.

Pull the true pair together, push all N−1 impostors in the row apart, symmetrically for columns. That's the entire training signal — and the runnable version below builds the matrix, computes the loss, and does zero-shot classification with it.

04

The payoff: zero-shot classification

Here's the trick that stunned people. Because CLIP compares images to text, you can classify an image into categories it was never trained on — just describe them. Want to tell cats from dogs? Embed the phrases "a photo of a cat" and "a photo of a dog," embed the image, and pick whichever text is closest.

Worth knowing

CLIP matched the accuracy of a fully supervised ImageNet-trained ResNet-50 without training on a single ImageNet label — recognizing the classes purely from their text descriptions. Change the label set by just typing new words.

06

Why it still matters

CLIP became the connective tissue of multimodal AI. Text-to-image models lean on it to steer generation — measuring how well an emerging image matches the prompt, so a diffusion model can be nudged toward your words. It powers multimodal search ("find photos that look like this sentence"), content moderation, and image captioning, and its contrastive recipe seeded a wave of vision-language models.

Its lasting idea is simple and profound: put different kinds of data into one shared space and comparison becomes trivial. Once images and words share a map, the boundary between seeing and reading starts to dissolve.

How it works

How CLIP was trained and turned into a classifier

CLIP is two encoders, one similarity matrix and one loss, trained from scratch on 400 million image–text pairs from the web. The paper's real work is in the details: how the data was gathered, how a batch of 32,768 pairs is scored, and how the trained model becomes an ImageNet classifier without seeing a single ImageNet label.

Class names: dog, cat, airplane … a photo of a dog. a photo of a big dog. … 80 templates per class Text encoder (63M Transformer) Normalize, average over templates one unit vector w per class Image to classify Image encoder (ViT or ResNet) x: unit-length image vector Zero-shot: pick the class with max w · x W stacks one w per class, built once same cost per image as one prompt
Zero-shot CLIP is a linear classifier whose weights are written by the text encoder. The template ensemble is averaged before any image arrives, so it adds no cost per image.

Training

  1. Collect the pairs. The dataset, called WIT (WebImageText), was built by searching for image–text pairs whose text contains one of 500,000 queries: every word that appears at least 100 times in English Wikipedia, plus bi-grams with high pointwise mutual information, Wikipedia article titles above a search-volume threshold and WordNet synsets. At most 20,000 pairs were kept per query, so common concepts could not swamp rare ones.
  2. Encode each image. Eight image encoders were trained: five ResNets (ResNet-50, ResNet-101 and three scaled-up versions using about 4, 16 and 64 times the compute of ResNet-50), with an attention-pooling layer replacing global average pooling, and three Vision Transformers (ViT-B/32, ViT-B/16, ViT-L/14). The only data augmentation is a random square crop of the resized image.
  3. Encode each caption. A 63-million-parameter Transformer with 12 layers, width 512 and 8 attention heads reads lower-cased byte-pair-encoded text (a 49,152-token vocabulary, at most 76 tokens). Its top-layer activation at the end-of-text token, layer-normalized, is the text feature. Self-attention is masked left to right so that a pretrained language model could be dropped in later.
  4. Project and normalize. One linear projection per encoder, with no nonlinear head, maps into the shared space, and every vector is scaled to unit length, so a dot product is a cosine.
  5. Score the batch. Every image is compared with every caption in a batch of 32,768, the scores are multiplied by a learned scale that starts at 1/0.07 and is capped at 100, and the symmetric cross-entropy in the next section is applied. Each GPU computes only the similarities its own slice of the batch needs.
  6. Run. Every model trains for 32 epochs with Adam and decoupled weight decay, a cosine learning-rate schedule, mixed precision and gradient checkpointing. The largest ResNet took 18 days on 592 V100 GPUs and the largest Vision Transformer 12 days on 256. The best model, ViT-L/14@336px, adds one epoch at 336-pixel resolution.

From a trained model to a classifier

The paper treats the text encoder as a generator of classifier weights. Each class name is written into a prompt, encoded and normalized; the resulting vectors, one per class, are the weight matrix of a linear classifier over image embeddings, and the predicted class is the one with the largest scaled dot product. Nothing is trained, so changing the label set means editing a list.

Two refinements matter. Prompt engineering: the template “A photo of a {label}.” beat the bare class name by 1.3 points on ImageNet, and dataset-specific context helped further, such as “a type of pet” for Oxford Pets or “a satellite photo of” for remote sensing. Ensembling: for ImageNet the authors averaged the normalized embeddings of 80 templates, such as “a photo of a big …” and “a photo of a small …”, which added another 3.5 points. Averaging in embedding space leaves one vector per class, so the ensemble costs nothing extra per image.

The second evaluation is a linear probe: a logistic regression trained on frozen image features with each dataset's own labels, the standard test of representation quality.

The math

CLIP's symmetric contrastive loss and zero-shot weights

L = ½ · [ −(1/N) Σi log ( es·⟨ui, vi⟩ / Σj es·⟨ui, vj⟩ ) − (1/N) Σi log ( es·⟨ui, vi⟩ / Σj es·⟨uj, vi⟩ ) ]
s = e^t = 1/τ, τ0 = 0.07, s ≤ 100 · wc = normalize( Σk=1…K normalize( ftext(templatek(c)) ) )
  • ui, vj — unit-length image and text embeddings, so ⟨ui, vj⟩ is a cosine between −1 and 1
  • first term — each image picks its own caption out of N; second term — each caption picks its own image
  • s — the logit scale; the network learns t = log s, which keeps s positive
  • wc — the zero-shot weight vector for class c, averaged over K prompt templates

At the extremes: if s were near 0, every logit would be near 0, every row of the softmax would be uniform, and the loss would sit at ln N whatever the embeddings, about 10.4 nats at N = 32,768, with almost no gradient. As s grows, small cosine differences become large logit differences: at s = 100 a cosine gap of 0.05 is a logit gap of 5, a factor of e^5 ≈ 148 in probability, so the softmax concentrates on the hardest negatives. The cap at 100 exists because the paper found that letting the scale grow further made training unstable.

The evidence

What CLIP was tested on, and what it showed

The eight models were evaluated two ways: zero-shot, with classifiers written from class names, on more than 30 datasets, and with linear probes on 27. Robustness was measured on natural distribution shifts of ImageNet.

MeasurementResult
Zero-shot ImageNet top-1, best CLIP (ViT-L/14@336px)76.2%, matching the original ResNet-50 without its 1.28 million labeled images
Previous zero-shot ImageNet result (Visual N-Grams)11.5%
Zero-shot CLIP vs a linear probe on ResNet-50 featuresCLIP wins on 16 of 27 datasets
Probe on CLIP's own features that zero-shot matchesmedian 5.4 labeled examples per class (mean 20.8); 16 on ImageNet
ModelImageNetIN-V2IN-AIN-RObjectNetIN-Sketch
Noisy Student EfficientNet-L288.380.284.974.768.547.6
Linear probe on CLIP features85.475.975.384.266.257.4
Zero-shot CLIP76.270.177.288.972.360.2

The last two rows use the same frozen image features. Fitting them to ImageNet's labels adds 9.2 points on ImageNet and helps on ImageNetV2, a re-collection of ImageNet, but loses on the other four shifted sets, so the robustness comes from defining classes in language rather than from the features alone. Overall, zero-shot CLIP closes up to 75% of the gap between ImageNet accuracy and accuracy under distribution shift.

Two ablations explain the design. A Transformer trained to predict each caption word for word learned ImageNet classes three times more slowly than a model predicting the caption's bag of words, and switching that to the contrastive objective gave a further fourfold gain. Across 36 datasets, prompt engineering and ensembling added almost 5 points on average, similar to the gain from 4 times more compute.

The failures are reported too: 88% on handwritten MNIST digits, below a logistic regression on raw pixels; weak results on satellite images, tumor detection, counting and traffic signs; and an estimated thousandfold increase in compute before zero-shot CLIP would reach the overall state of the art.

Since then

What the authors admit, and what happened next

The paper is unusually thorough about its own weaknesses. Performance is poor on fine-grained distinctions, on counting, on abstract or systematic tasks, and on anything far from what web captions describe — the model learned the distribution of things people photograph and write about, which is not the distribution of things one might want recognised. Results are also sensitive to prompt wording, so a reported zero-shot number embeds prompt engineering, and the paper says so.

"Zero-shot" deserves the scrutiny it later received: with 400 million uncurated pairs, whether a category was genuinely unseen is unanswerable, so the term means "no task-specific training" rather than "no exposure". And because the supervision is uncurated web text, the space encodes the associations of that text, which the paper examines directly rather than leaving to critics.

How it held up: as the substrate for nearly everything multimodal. A shared image-text space is the text conditioning in latent diffusion, the backbone of cross-modal retrieval, and — most consequentially — the visual encoder that rungs 2 and 3 attach to a language model. This rung aligned the two modalities; the rest of the ladder is about what you can then build on top of that alignment.

SOLVE IT YOURSELF

Build the contrastive matrix and classify zero-shot

CLIP's training signal is one similarity matrix, and its magic trick is what you can do with it afterward. This embeds three images and three captions in a shared space, builds the N×N cosine matrix (watch the diagonal dominate), and computes the symmetric contrastive loss — tiny when captions are aligned, huge when they're shuffled. Then the payoff: zero-shot classification, picking an image's label by nearest text, with no training on those labels. Change the embeddings and re-run.

YOUR TASK

Write the body of clip_loss. Everything else in the file is already written; this is the function the paper is about. Press ▶ Run to check it against the 5 assertions below — they start red.

WHAT IT HAS TO SATISFY — 5 ASSERTIONS
  1. Each image's top match is its own caption (the diagonal)
  2. Misaligned captions cost more contrastive loss
  3. Zero-shot picks the right label with no training
  4. Softmax over a row is a probability distribution
  5. A higher logit scale (a lower temperature) sharpens the match probability
CPython · WebAssembly
Questions

Questions people ask about CLIP

How does CLIP prompt ensembling work?

For each class, CLIP's authors wrote the class name into many context templates, such as “a photo of a big dog” and “a photo of a small dog”, encoded every filled-in template with the text encoder, normalized each embedding and averaged them into a single vector per class. Because the averaging happens in embedding space rather than over predicted probabilities, the ensemble costs nothing at test time: there is still one weight vector and one dot product per class. On ImageNet the paper used 80 templates, which added about 3.5 points of top-1 accuracy on top of the 1.3 points gained from the single template “A photo of a {label}.” Across 36 datasets, prompt engineering and ensembling together added almost 5 points on average.

What is the CLIP loss function, exactly?

CLIP trains with a symmetric cross-entropy over a batch similarity matrix, a form of the InfoNCE contrastive loss. For N image–caption pairs, both encoders' outputs are linearly projected, scaled to unit length and multiplied, giving an N by N matrix of cosine similarities that is multiplied by a learned scale. Each row is an N-way classification whose correct answer is the image's own caption; each column is the same problem from the caption's side; the two cross-entropies are averaged. The scale is learned as a logarithm, starts at 1/0.07 (about 14.3) and is capped at 100 for stability. With the paper's batch of 32,768, every image is contrasted with 32,767 wrong captions at each step.

How is SigLIP different from CLIP?

SigLIP, published by Google researchers (Zhai and colleagues) in 2023, keeps CLIP's two encoders and its batch of image–caption similarities but swaps the softmax for a sigmoid. Each image–caption cell becomes its own yes-or-no classification: the matching pair is a positive, every other pairing is a negative, and a learned bias, started at a large negative value because negatives vastly outnumber positives, sits next to the learned temperature. Since no cell has to be normalized against the rest of its row or column, the loss needs no global view of the batch, which saves memory and makes it work well at small batch sizes; the SigLIP paper also suggests that around 32k is enough. CLIP's softmax ties every row together, one reason its recipe leans on very large batches.

Why did CLIP use a contrastive objective instead of predicting captions?

The authors tried the generative route first. A Transformer language model trained jointly with an image encoder to predict each image's exact caption learned to recognize ImageNet classes three times more slowly than a simpler baseline that predicted only a bag-of-words encoding of the same caption. Swapping that prediction objective for the contrastive one, which only asks which caption in the batch belongs to the image, gave a further fourfold improvement in zero-shot ImageNet efficiency. The reason is that exact wording is far harder to predict than it is worth: a picture can be described in countless ways, while matching only needs the right caption to outrank the others in the batch.

Is zero-shot CLIP better than a linear probe on CLIP features?

Not on in-distribution accuracy. A logistic regression trained on the best CLIP model's frozen features reaches 85.4% on ImageNet against 76.2% zero-shot, and zero-shot CLIP matches the average score of a probe trained on four labeled examples per class. The case for zero-shot is that it needs no labels and holds up better under distribution shift: on ImageNet-R the zero-shot classifier scores 88.9% against the probe's 84.2%, and on ObjectNet 72.3% against 66.2%. The paper also flags a counter-intuitive drop when moving from zero-shot to just a few labeled examples, because one example cannot say which visual attribute defines its class.

Why does CLIP use prompts like 'a photo of a dog' instead of the bare class name?

The paper gives two reasons. A lone word is ambiguous: ImageNet contains both construction cranes and the bird, and in Oxford Pets a boxer is a dog breed, not an athlete, so a little context steers the text encoder toward the intended sense. And CLIP's training captions were sentences, rarely single words, so a bare label is unusual input for the text encoder. The template “A photo of a {label}.” added 1.3 points on ImageNet, and dataset-specific context helped further, such as “a type of pet” or “a type of food”. The catch, which the paper acknowledges, is that this tuning was done while checking validation results, so reported zero-shot accuracy includes some prompt engineering.

Check yourself

4 questions to test what you just read

Work each one out before you open it — a number, a prediction or a reason, not a definition. Producing the answer is what makes it stick. Your progress is kept on this device.

A training batch holds 32,768 pairs. How many similarity scores does one step compute, and how many negatives does each image's row contain?

Show answer

32,768² = 1,073,741,824, about 1.07 billion scores per step, and each row holds 32,767 negatives next to its one positive. A matrix that size is why the computation is sharded: each GPU scores only the pairs its own slice of the batch needs.

At the start of training the embeddings are close to random, so every cosine is near zero. What loss should the first step show, and does the initial scale of 1/0.07 change it?

Show answer

Each row's softmax is close to uniform over 32,768 captions, so each direction's loss is about ln 32,768 ≈ 10.4 nats, and so is their average. The scale does not change this: 14.3 times a logit near 0 is still near 0. It starts to matter only once some similarities pull away from the rest.

You build a zero-shot ImageNet classifier with the paper's 80 templates. How many text-encoder passes does that take, and how much work per test image compared with a single template?

Show answer

1,000 classes × 80 templates = 80,000 passes, done once. Per test image the cost is exactly that of one template: one image-encoder pass and 1,000 dot products, because the 80 embeddings per class were averaged into a single vector before any image arrived.

A linear probe on CLIP features beats zero-shot CLIP by 9.2 points on ImageNet. On which shifted test sets would you expect it to win and to lose, and why?

Show answer

It wins on ImageNetV2 (75.9 vs 70.1), a re-collection of ImageNet itself, and loses on ImageNet-A, ImageNet-R, ObjectNet and ImageNet Sketch by 1.9 to 6.1 points. The probe learns whatever predicts ImageNet's labels, including cues specific to ImageNet's photos. The zero-shot classifier defines each class in language, which knows nothing about how ImageNet's pictures look.

Where this sits

One model, many senses

Joining text to images, audio, video and finally to a robot arm. Starts with the contrastive objective the whole field standardised on.

  1. 1CLIP2021
  2. 2Flamingo2022
  3. 3LLaVA2023
  4. 4wav2vec 2.02020
  5. 5Whisper2022
  6. 6V-JEPA2024
  7. 7RT-22023
  8. 8Genie2024

All 110 papers, in 19 ladders →

Finished this one? 0 / 110 Paper Breakdowns done
NextFlamingo Next on the “One model, many senses” ladder · rung 2 of 8

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Paper Breakdowns