Paper notes

CLIP: Contrastive Learning on 400 Million Image-Text Pairs, and a Classifier You Define in One Sentence

CLIP trains an image encoder and a text encoder with contrastive learning on 400 million image-text pairs, so a classifier can be defined by a sentence. This post walks through the method, rechecks the paper's numbers and runs zero-shot, few-shot and typographic-attack tests on CIFAR-10.

Published Updated 49 min read

On this page
  1. Why this paper is worth reading
  2. Background: fixed-label supervision has a ceiling
  3. Method
  4. Data: 400 million image-text pairs
  5. Objective: predict who goes with whom, not the words
  6. Architecture and training
  7. Zero-shot classification: write the class names as sentences
  8. The paper’s experiments and conclusions
  9. Things to keep in mind when reading the tables
  10. Hands-on check: recomputing the paper’s numbers
  11. Hands-on experiment: zero-shot, few-shot and typographic attacks on CIFAR-10
  12. What this experiment can and cannot say
  13. Limitations and what came after
  14. What to take away from this paper
  15. Further reading
  16. FAQ

Learning Transferable Visual Models From Natural Language Supervision (Radford et al., OpenAI, ICML 2021; “the CLIP paper” below) trains on one very simple task: decide which caption goes with which image. On 400 million (image, text) pairs collected from the internet (the paper calls the set WIT, WebImageText), it trains an image encoder and a text encoder from scratch so that the vectors of matching pairs are close and those of mismatched pairs are far apart. After training, a classification task can be defined in words: write each class name as a sentence (for example “a photo of a dog.”), and predict the class whose text vector is closest to the image vector. The paper evaluates on more than 30 existing datasets without training on any of them. Zero-shot ImageNet accuracy is 76.2% (Table 1, the largest model, ViT-L/14@336px), which the abstract describes as matching the original ResNet-50, and on 16 of the paper’s 27 datasets zero-shot CLIP beats a linear classifier trained on ResNet-50 features. The weaknesses are just as clear: handwritten digits (MNIST) reach only 88%, and specialized or abstract tasks such as satellite images, traffic signs and counting objects are far weaker.

After walking through the paper, this post does two things. Check: it copies numbers from the paper’s tables into a script and recomputes them, and builds the models from the hyperparameters of the paper’s Table 20 on the meta device to count parameters. The parameter count of ViT-B/32 equals that of the public weights exactly (151,277,313); the paper’s vocabulary of 49,152 does not match the 49,408 rows of the public embedding table, but split up it is 256 single characters, 48,894 merges and 2 special tokens (49,152 in all), and the public vocabulary has 256 more characters carrying an end-of-word mark; the text says errors on aYahoo drop by 95%, and Table 1 recomputes to 94.2%; zero-shot wins on 16 of 27 datasets, yet averaged over the 27 the zero-shot score (67.6) is slightly below the linear probe on ResNet-50 features (69.9). Small replication: zero-shot, few-shot linear probes and a typographic attack on CIFAR-10 with ViT-B/32. An ensemble of 8 templates I wrote reaches 89.1% zero-shot (91.3% in the paper’s Table 11, with different templates and preprocessing, so not the same setting), and single templates differ by up to 3 points; linear probes with 8 and 16 training images per class score 87.6% and 89.8%, so zero-shot sits between them; writing a wrong class name on an image drops accuracy from 90.9% to between 11.8% and 25.2%, and 74.2% to 88.2% of the predictions follow the written word. The standard error on the 10,000 test images is 0.3 points, each few-shot setting has only 5 subsets, and the typographic attack uses 1,000 images; the conclusions that can be drawn are separated from those that cannot below.

Why this paper is worth reading

  • It turns “the classes” into a sentence. Before it, the output layer of a vision classifier was a fixed set of 1,000 classes; after it, the classifier is a set of text strings, and a new label set only needs new text. Later work leans on it heavily: LLaVA’s vision encoder is CLIP’s ViT-L/14, and the DALL·E 2 paper is titled “Hierarchical Text-Conditional Image Generation with CLIP Latents”.
  • The objective fits on one page. An N×NN\times N similarity matrix inside the batch and a symmetric cross entropy are the whole thing. Like next-token prediction in language modeling, it swaps hand-made labels for data that already exists on the internet.
  • It defines “zero-shot” carefully and states its weaknesses. The paper treats zero-shot as generalization to datasets never seen, and its limitations section admits that the benchmark suite is “haphazardly assembled” and co-adapted with CLIP’s development, and that on MNIST CLIP loses to logistic regression on raw pixels.
  • Neighbors on this site. How multimodal models plug images into a language model is covered in Multimodal LLMs; CLIP’s image tower is a ViT; the recipe of attaching a CLIP encoder to a language model is LLaVA.

Background: fixed-label supervision has a ceiling

By early 2021 NLP had shown another route: models such as GPT-3 pre-train directly on web text, without task-specific architectures, and transfer zero-shot to many tasks. In computer vision the standard recipe was still to pre-train on a human-labeled dataset such as ImageNet, with an output layer fixed to a set of classes; to recognize a new class you labeled new data and trained again.

Supervising images with natural language was not a new idea. The paper’s introduction walks through two decades of work: Mori et al. (1999) trained a model to predict the nouns and adjectives of documents paired with images; Joulin et al. (2016) turned the titles, descriptions and hashtags of YFCC100M images into a bag-of-words multi-label task; Li et al. (2017) extended the targets to phrase n-grams in Visual N-Grams and transferred zero-shot, reaching only 11.5% on ImageNet. The more recent VirTex, ICMLM and ConVIRT used transformers and contrastive objectives as proofs of concept, but trained for a few accelerator days on 100,000 to 200,000 images. Another line of weak supervision (predicting ImageNet-related hashtags on Instagram, or the classes of JFT-300M) trained for accelerator years on millions to billions of images, yet limited supervision to 1,000 and 18,291 classes and used a static softmax output, which rules out zero-shot transfer. The paper’s diagnosis is that the crucial difference is scale: CLIP is a simplified ConVIRT trained from scratch, on 400 million pairs.

Method

Data: 400 million image-text pairs

The paper searches for image-text pairs using 500,000 queries. The query list is every word that occurs at least 100 times in English Wikipedia, plus bi-grams with high pointwise mutual information, plus the names of Wikipedia articles above a certain search volume, plus all WordNet synsets not yet in the list. To keep the classes roughly balanced, each query contributes at most 20,000 pairs. The resulting dataset has about the same total word count as WebText, the set GPT-2 was trained on. The paper released code and model weights; the dataset itself was not released.

Objective: predict who goes with whom, not the words

The most direct recipe, as in VirTex, trains a model to generate each image’s caption, which means predicting every word of a text that could be phrased in countless ways. Figure 2 of the paper compares the options: a 63M-parameter transformer language model (already twice the compute of its ResNet-50 image encoder) learned to recognize ImageNet classes three times more slowly than a baseline that predicts only a bag-of-words encoding of the caption, and swapping the prediction objective for the contrastive one made it a further four times more efficient. So the paper switches to an easier proxy task: predict only which text as a whole is paired with which image, not the words in it.

Given a batch of NN image-text pairs, the image encoder ff and the text encoder gg each feed a linear projection followed by L2 normalization, giving ui\mathbf u_i and vj\mathbf v_j. Their pairwise products form an N×NN\times N similarity matrix, scaled by a learnable temperature ete^{t}:

sij=et ui⊤vjLi→t=−1N∑i=1Nlog⁡esii∑j=1NesijLt→i=−1N∑j=1Nlog⁡esjj∑i=1NesijL=12(Li→t+Lt→i)\begin{aligned} s_{ij}&=e^{t}\,\mathbf u_i^{\top}\mathbf v_j\\ \mathcal L_{i\to t}&=-\frac1N\sum_{i=1}^{N}\log\frac{e^{s_{ii}}}{\sum_{j=1}^{N}e^{s_{ij}}}\\ \mathcal L_{t\to i}&=-\frac1N\sum_{j=1}^{N}\log\frac{e^{s_{jj}}}{\sum_{i=1}^{N}e^{s_{ij}}}\\ \mathcal L&=\tfrac12\bigl(\mathcal L_{i\to t}+\mathcal L_{t\to i}\bigr) \end{aligned}

The diagonal holds the NN true pairs and the other N2−NN^2-N cells are mismatches. Li→t\mathcal L_{i\to t} makes every image pick its own text out of NN texts, Lt→i\mathcal L_{t\to i} makes every text pick its own image out of NN images, and the two cross entropies are averaged. The paper notes that this “every other sample in the batch is a negative” construction was first introduced as the multi-class N-pair loss (Sohn, 2016), popularized as InfoNCE by Oord et al. (2018), and adapted to image-text pairs in medical imaging by Zhang et al. (2020).

CLIP contrastive pre-training and zero-shot classification Left: a batch holds N images and N paired texts; the image and text encoders each output N vectors, their pairwise cosine similarities form an N by N matrix whose diagonal holds the true pairs, and cross entropy is applied along the rows and along the columns. Right: zero-shot classification puts each class name into a template, encodes it with the text encoder to get one vector per class, compares those with the image vector by cosine similarity and takes the largest. Pre-training: N image-text pairs in a batch Text encoder T1 T2 T3 TN Image encoder I1 I2 I3 IN I1·T1 I1·T2 I1·T3 I1·TN I2·T1 I2·T2 I2·T3 I2·TN I3·T1 I3·T2 I3·T3 I3·TN IN·T1 IN·T2 IN·T3 IN·TN pair mismatch Each row: one image picks its text out of N texts (cross entropy) Each column: one text picks its image out of N images (cross entropy) N positives (diagonal), N²−N negatives (all other cells) logits = cosine similarity × exp(t), t is a learnable temperature loss = average of the row-wise and column-wise cross entropy Inference: zero-shot classification Class names airplane … truck Add a template a photo of a {}. Text encoder Class vectors one per class, once Image to classify Image encoder Image vector one per image cosine prediction = the class with the largest cosine
Figure 1: The CLIP training objective and zero-shot classification. During training the N pairs on the diagonal are positives and the other N²−N are negatives; at inference the class names are written as sentences, the class vectors are computed once, and a new label set only needs new text.

A few more details are in the paper:

  • No non-linear projection head. Each encoder’s output goes through a single linear projection into the shared embedding space; the paper reports no difference in training efficiency between the two versions.
  • One data augmentation. A random square crop.
  • The temperature is learned. tt is log-parameterized, initialized to the equivalent of 0.07, and ete^{t} is clipped at 100, which the paper found necessary to prevent training instability.
  • The batch is very large. 32,768, with the similarity computation sharded so that each GPU computes only the part its local batch needs.

Architecture and training

PartWhat the paper does
Image encoderTwo families: a modified ResNet (ResNet-D changes, anti-aliased blur pooling, attention pooling in place of global average pooling) and a ViT (one extra LayerNorm after the patch and position embeddings)
Text encoderA transformer with 12 layers, width 512 and 8 heads, about 63M parameters; lower-cased byte pair encoding (BPE) with a 49,152 vocabulary; maximum length 76; the sequence is bracketed by [SOS] and [EOS], the top-layer activation at [EOS] goes through a LayerNorm and a linear projection to give the text vector; masked self-attention
Model family5 ResNets (RN50, RN101, and RN50x4, RN50x16, RN50x64 with roughly 4, 16 and 64 times the compute of RN50) and 3 ViTs (B/32, B/16, L/14), scaled in width, depth and resolution together
TrainingAll from scratch for 32 epochs; Adam with decoupled weight decay and a cosine schedule; batch size 32,768; mixed precision, gradient checkpointing, half-precision Adam statistics
ScaleRN50x64 took 18 days on 592 V100 GPUs; ViT-L/14 took 12 days on 256 V100 GPUs; ViT-L/14 was then trained one more epoch at 336 pixels to give ViT-L/14@336px, which is what “CLIP” means in the paper unless stated otherwise

Zero-shot classification: write the class names as sentences

After training, for a dataset with KK classes: put each class name into a template to make a sentence, encode the KK sentences with the text encoder to get KK class vectors; for each image, compute its cosine similarity with every class vector and take the largest. The class vectors are computed once, so inference costs the same as an ordinary classifier.

The section on prompt engineering and ensembling names two practical problems:

  • Polysemy. With only the class name, the text encoder cannot tell which sense is meant: ImageNet has both construction cranes and cranes that fly, and in the Oxford-IIIT Pet dataset a boxer is a dog, not an athlete.
  • Training texts are almost never single words. The pre-training texts are mostly full sentences, so a lone word is off-distribution. The paper found “A photo of a {label}.” a good default, and that alone improves ImageNet accuracy by 1.3%; customizing the prompt to the dataset (for pets, ”…, a type of pet.”; for satellite images, “a satellite photo of a {label}.”) helps further.

The paper also ensembles: for one dataset it computes a set of class vectors from several templates (80 on ImageNet) and averages them in the embedding space rather than the probability space, so it still caches a single averaged set and the cost equals that of one template. On ImageNet the ensemble adds another 3.5% over the single default prompt, and together the two steps improve accuracy by almost 5% over class names alone; averaged over 36 datasets the gain is also close to 5 points (Figure 4).

The paper’s experiments and conclusions

Paper Table 1: zero-shot accuracy of CLIP and Visual N-Grams (%). Visual N-Grams (Li et al., 2017) was one of the few earlier zero-shot image classification results. The paper stresses that this is not a controlled comparison of methods: CLIP’s dataset is 10 times larger, its vision model needs nearly 100 times more compute per prediction, its training compute was likely over 1,000 times larger, and it uses a transformer, which did not exist when Visual N-Grams was published.

DatasetVisual N-GramsCLIP (ViT-L/14@336px)
aYahoo72.498.4
ImageNet11.576.2
SUN23.058.5

The paper’s main findings follow, with the source in parentheses:

  • Zero-shot against a fully supervised linear classifier (Figure 5). Over the 27-dataset suite, zero-shot CLIP beats a linear classifier trained on ResNet-50 features on 16 datasets, ImageNet included. The spread is large: on Stanford Cars and Food101 zero-shot leads by over 20 points, while on Flowers102 and FGVC Aircraft it trails by over 10 points. The paper suspects this comes mostly from different amounts of per-task supervision in WIT and ImageNet. Zero-shot is clearly weak on specialized, complex or abstract tasks: satellite images (EuroSAT, RESISC45), lymph node tumor detection (PatchCamelyon), counting objects in synthetic scenes (CLEVRCounts), German traffic signs (GTSRB), and estimating the distance to the nearest car (KITTI Distance).
  • Zero-shot against few-shot (Figure 6). On the 20 datasets with at least 16 examples per class, zero-shot CLIP matches the average performance of a 4-shot linear classifier trained on the same feature space, and roughly matches the best 16-shot classifier among public models (BiT-M ResNet-152x2). The paper’s explanation is that a zero-shot classifier is “communicated” through language, while few-shot learning has to infer the concept indirectly from a few images, and a single image often contains several visual concepts, so many hypotheses fit one example. It also reports a counter-intuitive result: going from zero-shot to a few-shot linear classifier first lowers performance, unlike humans, whose performance rises sharply from zero to one example.
  • Representation learning (Figures 10 and 11). Using CLIP as a feature extractor with a linear classifier on top: on the 12 datasets of Kornblith et al. the best CLIP model beats the previous best by 2.6% on average, on the paper’s 27 datasets the margin grows to 5%, and per dataset CLIP beats Noisy Student EfficientNet-L2 on 21 of 27. The paper also finds CLIP’s ViTs about 3 times more compute-efficient than its ResNets.
  • Scaling with compute (Figure 9). Across 39 evaluations on 36 datasets, average zero-shot error is well modeled by a log-log linear trend over a 44-fold range of compute spanning 5 CLIP models, while individual evaluations vary much more. The paper estimates that about 1,000 times more compute would be needed for zero-shot CLIP to reach overall state-of-the-art performance, which was infeasible on the hardware of the time.
  • Robustness to distribution shift. Zero-shot CLIP shrinks the gap between ImageNet accuracy and accuracy under natural distribution shift by up to 75%. The paper cautions that this does not show supervised training on ImageNet causes the gap: CLIP’s large, diverse data or its language supervision could also make a model more robust.
  • Data overlap. Using RN50x64, the paper checked overlap between the pre-training data and the benchmarks. Of the 35 datasets studied, 9 have no detected overlap at all; the median overlap is 2.2% and the mean 3.2%. Overall accuracy shifts by more than 0.1% on only 7 datasets, and only 2 of those are statistically significant after Bonferroni correction; the largest detected gain is 0.6% on Birdsnap, whose overlap is 12.1%.

Things to keep in mind when reading the tables

  • “CLIP” in the paper means the largest model, ViT-L/14@336px, by default; the small models (ResNet-50 and ResNet-101) are below BiT-M, trained on ImageNet-21K, in linear-probe evaluation.
  • The “27 datasets” were assembled by the authors; their limitations section says the suite is co-adapted with the development of CLIP, and that during development they repeatedly queried full validation sets, which a real zero-shot setting would not allow.
  • The zero-shot “wins” are against a linear classifier on ResNet-50 features, not against the best specialized model on each dataset; the paper itself says that on most of these datasets the baseline is well below the state of the art.

Hands-on check: recomputing the paper’s numbers

The script below downloads no dataset and trains nothing. It copies the paper’s tables into the script, builds the models from the hyperparameters of the paper’s Table 20 on the meta device to count parameters and compares the count with the public ViT-B/32 weights, then writes the pseudocode of Figure 3 as a function and compares it with the library’s loss bit by bit. Environment: Python 3.14.3, PyTorch 2.10.0, Transformers 5.3.0, run on CPU; the weights are Hugging Face’s openai/clip-vit-base-patch32 (OpenAI’s CLIP repository is MIT-licensed; the model card itself declares no license), and CIFAR-10 is uoft-cs/cifar10 (its dataset card lists the license as unknown), of which the script reads only 10 test images.

Full code (about 175 lines)
"""Checking CLIP: recompute the paper's claims from its tables and weights"""
import io
import json

import pyarrow.parquet as pq
import torch
import torch.nn.functional as F
from huggingface_hub import snapshot_download
from PIL import Image
from transformers import (CLIPConfig, CLIPModel, CLIPProcessor,
                          CLIPTextConfig, CLIPVisionConfig)
from transformers.utils import logging as hf_logging

hf_logging.set_verbosity_error()
hf_logging.disable_progress_bar()

# --- Numbers from arXiv 2103.00020, copied by table ---
PAIRS, QUERIES, CAP = 400e6, 500_000, 20_000  # section 2.2
EPOCHS, BATCH = 32, 32_768  # section 2.5
V100 = {"RN50x64": (592, 18), "ViT-L/14": (256, 12)}  # GPUs, days
# Table 20: vision (layers, width, heads, patch, input), text (layers,
# width, heads), embedding dim
HP = {
    "ViT-B/32": (12, 768, 12, 32, 224, 12, 512, 8, 512),
    "ViT-B/16": (12, 768, 12, 16, 224, 12, 512, 8, 512),
    "ViT-L/14": (24, 1024, 16, 14, 224, 12, 768, 12, 768),
    "ViT-L/14-336px": (24, 1024, 16, 14, 336, 12, 768, 12, 768)}
# Table 1: zero-shot accuracy of Visual N-Grams and CLIP
T1 = {"aYahoo": (72.4, 98.4), "ImageNet": (11.5, 76.2), "SUN": (23.0, 58.5)}
DATA = ("Food101 CIFAR10 CIFAR100 Birdsnap SUN397 Cars Aircraft VOC2007 DTD "
        "Pets Caltech101 Flowers MNIST FER2013 STL10 EuroSAT RESISC45 GTSRB "
        "KITTI Country211 PCam UCF101 Kinetics700 CLEVR HatefulMemes SST2 "
        "ImageNet").split()
ZS_L336 = ("93.8 95.7 77.5 49.5 68.4 78.8 37.2 84.3 55.7 93.5 92.8 78.3 88.3 "
           "57.7 99.4 59.6 71.7 52.3 21.9 34.9 63.0 76.9 61.3 24.8 63.3 67.9 "
           "76.2")  # Table 11, zero-shot ViT-L/14-336px
ZS_B32 = ("84.4 91.3 65.1 37.8 63.2 59.4 21.2 83.1 44.5 87.0 87.9 66.7 51.9 "
          "47.3 97.2 49.4 60.3 32.2 39.4 17.8 58.4 64.5 47.8 24.8 57.6 59.6 "
          "63.2")  # Table 11, zero-shot ViT-B/32
LP_R50 = ("71.3 91.8 74.5 52.7 60.5 49.9 48.5 83.8 72.3 92.4 90.8 90.8 98.3 "
          "54.9 96.4 96.7 83.6 70.6 67.1 11.7 82.5 71.2 46.8 43.0 56.5 55.5 "
          "74.3")  # Table 10, linear probe on an ImageNet ResNet-50
ZS_L336, ZS_B32, LP_R50 = (list(map(float, s.split()))
                           for s in (ZS_L336, ZS_B32, LP_R50))

# --- 1. Training scale ---
per_q = PAIRS / QUERIES
print(f"1. 400M pairs over 500,000 queries: {per_q:,.0f} pairs per query "
      f"on average, {per_q / CAP:.1%} of the cap of {CAP:,}")
print(f"   {EPOCHS} epochs see {PAIRS * EPOCHS / 1e9:.1f}B samples; "
      f"batch {BATCH:,}, so {PAIRS * EPOCHS / BATCH:,.0f} steps")
for name, (gpus, days) in V100.items():
    print(f"   {name}: {gpus} V100 x {days} days = {gpus * days:,} V100-days")

# --- 2. Parameters: does the paper's table match the public weights ---


def build(hp):
    lv, wv, hv, patch, res, lt, wt, ht, d = hp
    vis = CLIPVisionConfig(hidden_size=wv, intermediate_size=4 * wv,
                           num_hidden_layers=lv, num_attention_heads=hv,
                           image_size=res, patch_size=patch, projection_dim=d)
    txt = CLIPTextConfig(vocab_size=49408, hidden_size=wt,
                         intermediate_size=4 * wt, num_hidden_layers=lt,
                         num_attention_heads=ht, max_position_embeddings=77,
                         projection_dim=d)
    cfg = CLIPConfig(text_config=txt.to_dict(), vision_config=vis.to_dict(),
                     projection_dim=d)
    with torch.device("meta"):  # no memory allocated, just count
        return CLIPModel(cfg)


def count(module):
    return sum(p.numel() for p in module.parameters())


NAME = "openai/clip-vit-base-patch32"
model = CLIPModel.from_pretrained(NAME)
proc = CLIPProcessor.from_pretrained(NAME)
real = count(model)
print("\n2. Parameters (Table 20 hyperparameters, counted on the meta device)")
for name, hp in HP.items():
    n = count(build(hp))
    print(f"   {name:<15}{n:>12,}  ({n / 1e6:.1f}M)")
same = real == count(build(HP["ViT-B/32"]))
print(f"   Public ViT-B/32 weights: {real:,}, "
      f"{'equal to' if same else 'not equal to'} the count from Table 20")
tt, vv = count(model.text_model), count(model.vision_model)
emb = model.text_model.embeddings.token_embedding.weight.numel()
print(f"   Text tower {tt / 1e6:.1f}M (paper: 63M), vision tower "
      f"{vv / 1e6:.1f}M; the token table is {emb / tt:.1%} of the text tower")
print("   Vocabulary: the paper says 49,152, the public embedding table has "
      f"{model.config.text_config.vocab_size:,} rows")
snap = snapshot_download(NAME)
with open(f"{snap}/vocab.json", encoding="utf-8") as f:
    vocab = json.load(f)
with open(f"{snap}/merges.txt", encoding="utf-8") as f:
    merges = [ln for ln in f.read().split("\n")[1:] if ln]
singles = [t for t in vocab if len(t) == 1]
tails = [t for t in vocab if len(t) == 5 and t.endswith("</w>")]
specials = [t for t in vocab if t.startswith("<|")]
base = len(singles) + len(merges) + len(specials)
print(f"   Public vocabulary: {len(singles)} characters + {len(merges):,} "
      f"merges + {len(specials)} specials = {base:,}; plus {len(tails)} "
      f"end-of-word characters, {len(vocab):,} in all")
print("   Vision tower modules: "
      + ", ".join(n for n, _ in model.vision_model.named_children()))

# --- 3. Temperature ---
t = model.logit_scale.item()
print(f"\n3. Temperature: initial 1/0.07 = {1 / 0.07:.2f}; public weights "
      f"have exp(t) = {model.logit_scale.exp().item():.2f}; the paper caps it "
      "at 100")

# --- 4. Figure 3 pseudocode: the symmetric cross entropy ---
root = snapshot_download("uoft-cs/cifar10", repo_type="dataset",
                         local_files_only=True)
table = pq.read_table(f"{root}/plain_text/test-00000-of-00001.parquet")
rows = table.to_pylist()
CLASSES = ("airplane automobile bird cat deer dog frog horse ship "
           "truck").split()
pick = [next(r for r in rows if r["label"] == c) for c in range(10)]
images = [Image.open(io.BytesIO(r["img"]["bytes"])).convert("RGB")
          for r in pick]
batch = proc(text=[f"a photo of a {c}." for c in CLASSES], images=images,
             return_tensors="pt", padding=True)
with torch.no_grad():
    out = model(**batch, return_loss=True)


def clip_loss(i_e, t_e, scale):
    logits = i_e @ t_e.T * scale  # scaled pairwise cosine similarities
    labels = torch.arange(len(logits))
    return (F.cross_entropy(logits, labels)
            + F.cross_entropy(logits.T, labels)) / 2


mine = clip_loss(out.image_embeds, out.text_embeds, model.logit_scale.exp())
flat = clip_loss(out.image_embeds, out.text_embeds, 0.0)
print(f"\n4. The same 10 pairs: pseudocode loss {mine.item():.6f}, "
      f"library loss {out.loss.item():.6f}")
print(f"   difference {abs(mine - out.loss).item():.1e}; with the scale at 0 "
      f"the loss is {flat.item():.4f}, ln 10 = "
      f"{torch.log(torch.tensor(10.0)).item():.4f}")
print("   Norms of the image and text embeddings: "
      f"{out.image_embeds.norm(dim=-1).mean().item():.4f}, "
      f"{out.text_embeds.norm(dim=-1).mean().item():.4f}")

# --- 5. Table 1 ratios ---
print("\n5. Table 1, zero-shot accuracy of CLIP and Visual N-Grams")
for k, (a, b) in T1.items():
    print(f"   {k:<9}{a:>6.1f} -> {b:>5.1f}, accuracy ratio {b / a:.2f}, "
          f"error {100 - a:.1f}% -> {100 - b:.1f}%, errors cut by "
          f"{1 - (100 - b) / (100 - a):.1%}")
a, b = T1["aYahoo"]
lo = 1 - (100 - b + 0.05) / (100 - a - 0.05)
hi = 1 - (100 - b - 0.05) / (100 - a + 0.05)
print(f"   Allowing 0.05 rounding in both aYahoo numbers, the cut falls in "
      f"{lo:.1%} to {hi:.1%}; the paper's text says 95%")

# --- 6. Zero-shot CLIP against a linear probe ---
wins = [d for d, z, p in zip(DATA, ZS_L336, LP_R50) if z > p]
loss = [d for d in DATA if d not in wins]
print(f"\n6. Zero-shot ViT-L/14-336px (Table 11) against the ResNet-50 linear "
      f"probe (Table 10): wins {len(wins)} / {len(DATA)}")
print("   Datasets it loses: " + ", ".join(loss))
gap = sorted((z - p, d) for d, z, p in zip(DATA, ZS_L336, LP_R50))
print(f"   largest gap: {gap[-1][1]} {gap[-1][0]:+.1f}, smallest: "
      f"{gap[0][1]} {gap[0][0]:+.1f}")
avg = lambda xs: sum(xs) / len(xs)
print(f"   mean over the 27 datasets: zero-shot {avg(ZS_L336):.1f}, linear "
      f"probe {avg(LP_R50):.1f} (the paper does not give this mean)")
i = DATA.index("CIFAR10")
print(f"   CIFAR-10, the dataset used below: zero-shot ViT-B/32 {ZS_B32[i]}, "
      f"ViT-L/14-336px {ZS_L336[i]}")

Output:

1. 400M pairs over 500,000 queries: 800 pairs per query on average, 4.0% of the cap of 20,000
   32 epochs see 12.8B samples; batch 32,768, so 390,625 steps
   RN50x64: 592 V100 x 18 days = 10,656 V100-days
   ViT-L/14: 256 V100 x 12 days = 3,072 V100-days

2. Parameters (Table 20 hyperparameters, counted on the meta device)
   ViT-B/32        151,277,313  (151.3M)
   ViT-B/16        149,620,737  (149.6M)
   ViT-L/14        427,616,513  (427.6M)
   ViT-L/14-336px  427,944,193  (427.9M)
   Public ViT-B/32 weights: 151,277,313, equal to the count from Table 20
   Text tower 63.2M (paper: 63M), vision tower 87.5M; the token table is 40.0% of the text tower
   Vocabulary: the paper says 49,152, the public embedding table has 49,408 rows
   Public vocabulary: 256 characters + 48,894 merges + 2 specials = 49,152; plus 256 end-of-word characters, 49,408 in all
   Vision tower modules: embeddings, pre_layrnorm, encoder, post_layernorm

3. Temperature: initial 1/0.07 = 14.29; public weights have exp(t) = 100.00; the paper caps it at 100

4. The same 10 pairs: pseudocode loss 0.269214, library loss 0.269214
   difference 0.0e+00; with the scale at 0 the loss is 2.3026, ln 10 = 2.3026
   Norms of the image and text embeddings: 1.0000, 1.0000

5. Table 1, zero-shot accuracy of CLIP and Visual N-Grams
   aYahoo     72.4 ->  98.4, accuracy ratio 1.36, error 27.6% -> 1.6%, errors cut by 94.2%
   ImageNet   11.5 ->  76.2, accuracy ratio 6.63, error 88.5% -> 23.8%, errors cut by 73.1%
   SUN        23.0 ->  58.5, accuracy ratio 2.54, error 77.0% -> 41.5%, errors cut by 46.1%
   Allowing 0.05 rounding in both aYahoo numbers, the cut falls in 94.0% to 94.4%; the paper's text says 95%

6. Zero-shot ViT-L/14-336px (Table 11) against the ResNet-50 linear probe (Table 10): wins 16 / 27
   Datasets it loses: Birdsnap, Aircraft, DTD, Flowers, MNIST, EuroSAT, RESISC45, GTSRB, KITTI, PCam, CLEVR
   largest gap: Cars +28.9, smallest: KITTI -45.2
   mean over the 27 datasets: zero-shot 67.6, linear probe 69.9 (the paper does not give this mean)
   CIFAR-10, the dataset used below: zero-shot ViT-B/32 91.3, ViT-L/14-336px 95.7

Reading it line by line:

  • Training scale. 400M pairs over 500,000 queries is 800 pairs per query on average, 4.0% of the cap of 20,000: a query that hits the cap contributes 20,000 pairs, so at most 4.0% of the queries can have hit it, and the cap only affects a few popular queries. 32 epochs see 12.8B samples; with a batch of 32,768 that is 390,625 steps. On compute, RN50x64 took 592 V100s for 18 days, 10,656 V100-days; ViT-L/14 took 256 V100s for 12 days, 3,072 V100-days, less than a third of that.
  • Parameters. Building the models from the hyperparameters in the paper’s Table 20 on the meta device and counting, ViT-B/32 has 151,277,313 parameters, identical to the public weights; the text tower is 63.2M, matching the paper’s 63M, and the vision tower is 87.5M. The token embedding table is 40.0% of the text tower and everything else (including the 12 Transformer layers) makes up the other 60%. ViT-L/14 is 427.6M and the 336-pixel version 427.9M; the extra 327,680 parameters all come from position embeddings (577 positions against 257, 1,024 dimensions each).
  • Vocabulary. The paper says 49,152; the public embedding table has 49,408 rows, 256 more. The public vocabulary file has 256 single characters, 48,894 merges and 2 special tokens, which add up to exactly 49,152; on top of that come 256 single characters carrying the end-of-word mark </w>, for 49,408 in all. The two numbers do not contradict each other: the paper seems to count base characters, merges and special tokens, leaving out the word-final variants of the characters. The paper does not explain its convention, so I only list the facts.
  • Temperature. The initial value is 1/0.07 = 14.29; the learned ete^{t} in the public weights is 100.00, exactly at the cap the paper mentions, so the clamp was active at the end of training.
  • Loss. Writing Figure 3’s pseudocode as a function gives the same loss as the library’s CLIP loss on the same 10 pairs, bit for bit (difference 0.0e+00). With the scale set to 0 (all similarities equal) the loss is 2.3026, exactly ln⁡10\ln 10, the loss of a 10-way pure guess. Both embeddings have norm 1.0000, so the dot product after normalization is the cosine similarity.
  • Table 1 ratios. The paper says CLIP achieves a “95% reduction in the number of errors” on aYahoo; recomputing from Table 1 gives 94.2%, and allowing a 0.05 rounding error in both numbers only gives 94.0% to 94.4%, which cannot reach 95%. That is rounding in the text; the conclusion stands. On ImageNet accuracy is 6.63 times that of Visual N-Grams and errors drop by 73.1%; on SUN it is 2.54 times, consistent with the paper’s “more than doubles”.
  • Wins over 27 datasets. Table 11 (zero-shot, ViT-L/14@336px) against Table 10 (linear probe on ResNet-50 features): it wins 16 of 27 datasets, as the text says. The 11 it loses are Birdsnap, Aircraft, DTD, Flowers, MNIST, EuroSAT, RESISC45, GTSRB, KITTI, PCam and CLEVR. The largest gap is Cars (zero-shot higher by 28.9 points), the smallest is KITTI (lower by 45.2 points). But averaged over the 27 datasets, zero-shot scores 67.6 and the linear probe 69.9: it wins more often, yet loses by more where it loses, so the zero-shot mean is slightly lower. The paper does not give this mean; I computed it. So “beats a linear classifier on ResNet-50 features on 16 of 27 datasets” is true, but it does not mean “better on average”.
  • The dataset used below. On CIFAR-10 the paper reports zero-shot accuracy of 91.3 for ViT-B/32 and 95.7 for ViT-L/14@336px. The experiment below uses ViT-B/32 and takes the former as its reference.

Hands-on experiment: zero-shot, few-shot and typographic attacks on CIFAR-10

The script below uses CLIP ViT-B/32 on CIFAR-10 (10 classes, 32×32 images) to do four things: zero-shot classification with a comparison of prompt templates; a look at cosine similarities and what the temperature does; linear probes trained on 1 to 16 training images per class, compared with zero-shot; and finally writing words on the images to see whether the predictions follow the words.

Environment: Apple M2 Max (MPS backend), Python 3.14.3, PyTorch 2.10.0, Transformers 5.3.0, NumPy 2.4.2, Pillow 12.1.1; the model is openai/clip-vit-base-patch32 (float32) and the dataset is uoft-cs/cifar10 (10,000 test images, 50,000 training images). The whole script runs in about 3 minutes on this machine; the only randomness is the sampling in section 3 (seeds fixed), everything else is deterministic, and on other hardware or library versions individual numbers may differ slightly.

A few things about the setup should be said up front:

  • The templates are my own. The 8 templates are in TEMPLATES in the script; they are not the set the paper prepared for CIFAR-10. I did not change them after writing them; during development I ran one small trial on a 500-image subset of the test set only to check that the script ran, and did not pick templates by their results. The {} row is the bare class name. The ensemble works as in the paper: one set of class embeddings per template, averaged and then renormalized.
  • The input is an upscaled thumbnail. CLIP’s preprocessing upscales the 32×32 images to 224×224 (bicubic), so the model sees blurry pictures.
  • The few-shot probe is optimistic in one respect. The probe is an L2-regularized multinomial logistic regression (PyTorch L-BFGS) on the 768-dimensional features before the projection (I_f in the paper’s Figure 3). For each k, 5 random subsets of k training images per class are drawn (seeds 100 to 104), and the mean and sample standard deviation are reported (only 5 numbers, so the standard deviation is itself coarse). The regularization strength λ is chosen among 4 values on 1,000 validation images (100 per class, taken from the training set and not used for training); a real few-shot user has no validation set that large, so the few-shot numbers are on the optimistic side. The paper’s linear probes use scikit-learn with a grid of 96 values of λ, so the full-data probe does not have to match bit for bit.
  • How the typographic attack is done. The first 100 test images of each class (1,000 in all) are upscaled to 224×224 and given a white label bar with black text at the bottom, in 16, 24 and 32 pixel type. The text is one of three things: the true class name; another class name (fixed per image); or an unrelated word, hello. The baseline is the same upscaled image without the bar.
Full code (about 228 lines)
"""CLIP ViT-B/32 on CIFAR-10: zero-shot, few-shot probes, typographic attacks"""
import io
import sys

import numpy as np
import pyarrow.parquet as pq
import torch
import torch.nn.functional as F
from huggingface_hub import snapshot_download
from PIL import Image, ImageDraw, ImageFont
from transformers import CLIPModel, CLIPProcessor
from transformers.utils import logging as hf_logging

hf_logging.set_verbosity_error()
hf_logging.disable_progress_bar()
DEV = sys.argv[1] if len(sys.argv) > 1 else "mps"
N_TEST = int(sys.argv[2]) if len(sys.argv) > 2 else 10_000
N_TRAIN = int(sys.argv[3]) if len(sys.argv) > 3 else 50_000
NAME = "openai/clip-vit-base-patch32"
CLASSES = "airplane automobile bird cat deer dog frog horse ship truck".split()
TEMPLATES = ["a photo of a {}.", "a blurry photo of a {}.",
             "a low resolution photo of a {}.", "a photo of the {}.",
             "a close-up photo of a {}.", "a bad photo of a {}.",
             "a good photo of a {}.", "a tiny photo of a {}."]
torch.manual_seed(0)
model = CLIPModel.from_pretrained(NAME).to(DEV).eval()
proc = CLIPProcessor.from_pretrained(NAME)
SCALE = model.logit_scale.exp().item()

root = snapshot_download("uoft-cs/cifar10", repo_type="dataset",
                         local_files_only=True)


def load(split, n):
    t = pq.read_table(f"{root}/plain_text/{split}-00000-of-00001.parquet")
    t = t.slice(0, n).to_pydict()
    imgs = [Image.open(io.BytesIO(d["bytes"])).convert("RGB")
            for d in t["img"]]
    return imgs, torch.tensor(t["label"])


test_imgs, test_y = load("test", N_TEST)
train_imgs, train_y = load("train", N_TRAIN)


def feats(imgs, bs=250):
    """Returns (features before the projection I_f, normalized I_e)"""
    fs, es = [], []
    for i in range(0, len(imgs), bs):
        px = proc(images=imgs[i:i + bs], return_tensors="pt").pixel_values
        with torch.no_grad():
            f = model.vision_model(pixel_values=px.to(DEV)).pooler_output
            e = F.normalize(model.visual_projection(f), dim=-1)
        fs.append(f.cpu())
        es.append(e.cpu())
    return torch.cat(fs), torch.cat(es)


def text_emb(prompts):
    tk = proc.tokenizer(prompts, padding=True, return_tensors="pt").to(DEV)
    with torch.no_grad():
        t = model.text_model(**tk).pooler_output
    return F.normalize(model.text_projection(t), dim=-1).cpu()


def classifier(templates):
    """One class-vector set per template, averaged and renormalized (the
    paper's prompt ensembling)"""
    w = torch.stack([text_emb([t.format(c) for c in CLASSES])
                     for t in templates]).mean(0)
    return F.normalize(w, dim=-1)


def accuracy(e, y, w):
    return ((e @ w.T).argmax(1) == y).float().mean().item()


f_test, e_test = feats(test_imgs)
n = len(test_y)
print(f"{n} test images, {len(train_y)} train images, device {DEV}, "
      f"exp(t) = {SCALE:.1f}")

# --- 1. Zero-shot: prompts and ensembling ---
print("\n1. Zero-shot accuracy (test set)")
bare = accuracy(e_test, test_y, classifier(["{}"]))
single = [accuracy(e_test, test_y, classifier([t])) for t in TEMPLATES]
W_ENS = classifier(TEMPLATES)
ens = accuracy(e_test, test_y, W_ENS)
se = (ens * (1 - ens) / n) ** 0.5
print("   template ({} = class name only)    accuracy")
for t, a in [("{}", bare)] + list(zip(TEMPLATES, single)):
    print(f"   {t:<34}{a:.1%}")
print(f"   the 8 templates: mean {np.mean(single):.1%}, min "
      f"{min(single):.1%}, max {max(single):.1%}")
print(f"   8-template ensemble: {ens:.1%} (standard error {se:.1%}); "
      "paper Table 11, ViT-B/32: 91.3%")
pred = (e_test @ W_ENS.T).argmax(1)
conf = torch.zeros(10, 10, dtype=torch.long)
for a, b in zip(test_y, pred):
    conf[a, b] += 1
off = sorted(((conf[a, b].item(), CLASSES[a], CLASSES[b])
              for a in range(10) for b in range(10) if a != b), reverse=True)
print("   The three most common errors (true -> predicted): "
      + ", ".join(f"{a} -> {b} ({k})" for k, a, b in off[:3]))
print("   Per-class accuracy: "
      + " ".join(f"{c} {conf[i, i].item() / conf[i].sum().item():.0%}"
                 for i, c in enumerate(CLASSES)))

# --- 2. Temperature ---
cos = e_test @ W_ENS.T
right = cos[torch.arange(n), test_y].mean().item()
others = (cos.sum() - cos[torch.arange(n), test_y].sum()).item() / (n * 9)
print(f"\n2. Cosine similarity: to the right class {right:.3f}, to the others "
      f"{others:.3f}, gap {right - others:.3f}, times exp(t): "
      f"{(right - others) * SCALE:.1f}")
print("   scale   cross-entropy   mean top probability")
for s in (1, 10, 25, 50, 100, 200):
    p = F.softmax(s * cos, dim=1)
    nll = F.cross_entropy(s * cos, test_y).item()
    print(f"   {s:>5}  {nll:>9.3f}  {p.max(1).values.mean().item():>12.3f}")

# --- 3. Few-shot linear probes ---
f_train, e_train = feats(train_imgs)


def probe(x, y, lam):
    """Multiclass logistic regression, L2 penalty, on pre-projection features"""
    w = torch.zeros(x.shape[1], 10, requires_grad=True)
    b = torch.zeros(10, requires_grad=True)
    opt = torch.optim.LBFGS([w, b], max_iter=300,
                            line_search_fn="strong_wolfe")

    def closure():
        opt.zero_grad()
        loss = F.cross_entropy(x @ w + b, y) + lam * (w ** 2).sum()
        loss.backward()
        return loss

    opt.step(closure)
    return w.detach(), b.detach()


def norm(f):
    # a fixed scale, so lam's range does not depend on feature size
    return F.normalize(f, dim=-1) * 10


LAMS = (1e-5, 1e-4, 1e-3, 1e-2)
x_train, x_test = norm(f_train), norm(f_test)
val = torch.cat([torch.nonzero(train_y == c)[:100, 0] for c in range(10)])
pool = [torch.nonzero(train_y == c)[100:, 0] for c in range(10)]


def acc_of(x, y, w, b):
    return ((x @ w + b).argmax(1) == y).float().mean().item()


def fit(idx):
    """Pick lam on the 1000 validation images; return (lam, test accuracy)"""
    best = None
    for lam in LAMS:
        w, b = probe(x_train[idx], train_y[idx], lam)
        v = acc_of(x_train[val], train_y[val], w, b)
        if best is None or v > best[0]:
            best = (v, lam, acc_of(x_test, test_y, w, b))
    return best[1:]


print("\n3. Few-shot linear probes (k per class, 5 random subsets)")
print("   shots k    mean ± std        worst    best")
g = torch.Generator()
for k in (1, 2, 4, 8, 16):
    accs = []
    for seed in range(5):
        g.manual_seed(100 + seed)
        idx = torch.cat([p[torch.randperm(len(p), generator=g)[:k]]
                         for p in pool])
        accs.append(fit(idx)[1])
    print(f"   {k:>9}    {np.mean(accs):>8.1%} ± {np.std(accs, ddof=1):.1%}"
          f"{min(accs):>10.1%}{max(accs):>8.1%}")
print(f"   zero-shot (8-template ensemble, no training image): {ens:.1%}")
rest = torch.nonzero(~torch.isin(torch.arange(len(train_y)), val))[:, 0]
lam, full = fit(rest)
print(f"   all {len(rest)} training images (lam = {lam:g}): {full:.1%}; "
      "paper Table 10, ViT-B/32: 95.1%")

# --- 4. Typographic attack: writing on the image ---
per = 100
sel = torch.cat([torch.nonzero(test_y == c)[:per, 0] for c in range(10)])
sel_imgs = [test_imgs[i] for i in sel]
sel_y = test_y[sel]


def stamp(img, word, px):
    """Upscale to 224 and add a white strip with black text at the bottom"""
    big = img.resize((224, 224), Image.BICUBIC)
    d = ImageDraw.Draw(big)
    font = ImageFont.load_default(size=px)
    d.rectangle([0, 224 - px - 12, 224, 224], fill="white")
    d.text(((224 - d.textlength(word, font=font)) / 2, 224 - px - 6), word,
           fill="black", font=font)
    return big


def run(words, px):
    imgs = [stamp(im, w, px) if w else im.resize((224, 224), Image.BICUBIC)
            for im, w in zip(sel_imgs, words)]
    _, e = feats(imgs)
    return (e @ W_ENS.T).argmax(1)


names = [CLASSES[i] for i in sel_y]
wrong = [CLASSES[(int(c) + 1 + j % 9) % 10] for j, c in enumerate(sel_y)]
print(f"\n4. Typographic attack (first {per} test images per class, "
      f"{len(sel_y)} in all)")
print("   px    written text      accuracy  predicted as the written class")
base = (run([None] * len(sel_y), 16) == sel_y).float().mean().item()
print(f"   {'-':>4}  {'-':<16}{base:>8.1%}{'-':>10}")
for px in (16, 24, 32):
    for label, words in (("true class", names), ("wrong class", wrong),
                         ("hello", ["hello"] * len(sel_y))):
        p = run(words, px)
        acc = (p == sel_y).float().mean().item()
        goal = torch.tensor([CLASSES.index(w) if w in CLASSES else -1
                             for w in words])
        hit = f"{(p == goal).float().mean().item():.1%}"
        print(f"   {px:>4}  {label:<16}{acc:>8.1%}"
              f"{hit if label != 'hello' else '-':>10}")

Output:

10000 test images, 50000 train images, device mps, exp(t) = 100.0

1. Zero-shot accuracy (test set)
   template ({} = class name only)    accuracy
   {}                                87.3%
   a photo of a {}.                  88.3%
   a blurry photo of a {}.           88.5%
   a low resolution photo of a {}.   89.0%
   a photo of the {}.                89.0%
   a close-up photo of a {}.         86.4%
   a bad photo of a {}.              89.4%
   a good photo of a {}.             88.9%
   a tiny photo of a {}.             87.8%
   the 8 templates: mean 88.4%, min 86.4%, max 89.4%
   8-template ensemble: 89.1% (standard error 0.3%); paper Table 11, ViT-B/32: 91.3%
   The three most common errors (true -> predicted): deer -> horse (137), cat -> dog (82), frog -> cat (69)
   Per-class accuracy: airplane 90% automobile 94% bird 88% cat 85% deer 80% dog 88% frog 77% horse 98% ship 96% truck 94%

2. Cosine similarity: to the right class 0.276, to the others 0.218, gap 0.058, times exp(t): 5.8
   scale   cross-entropy   mean top probability
       1      2.251         0.106
      10      1.810         0.168
      25      1.213         0.323
      50      0.645         0.604
     100      0.360         0.842
     200      0.383         0.931

3. Few-shot linear probes (k per class, 5 random subsets)
   shots k    mean ± std        worst    best
           1       69.1% ± 2.0%     66.8%   71.1%
           2       77.4% ± 3.0%     73.9%   81.8%
           4       84.3% ± 1.2%     82.2%   85.1%
           8       87.6% ± 1.0%     86.3%   88.7%
          16       89.8% ± 0.3%     89.5%   90.3%
   zero-shot (8-template ensemble, no training image): 89.1%
   all 49000 training images (lam = 0.001): 94.7%; paper Table 10, ViT-B/32: 95.1%

4. Typographic attack (first 100 test images per class, 1000 in all)
   px    written text      accuracy  predicted as the written class
      -  -                  90.9%         -
     16  true class         99.9%     99.9%
     16  wrong class        25.2%     74.2%
     16  hello              89.0%         -
     24  true class         99.9%     99.9%
     24  wrong class        14.7%     85.3%
     24  hello              87.7%         -
     32  true class         99.9%     99.9%
     32  wrong class        11.8%     88.2%
     32  hello              85.0%         -
Few-shot linear probes and typographic attacks on CIFAR-10 Left: test accuracy of few-shot linear probes against the number of training images per class, with horizontal lines for zero-shot and for the probe trained on all training images. Right: zero-shot accuracy after writing a word on the image: the true class name, another class name or an unrelated word. Linear probe: k training images per class 50% 60% 70% 80% 90% 100% 1 2 4 8 16 training images per class, k test accuracy probe on all training images 94.7% zero-shot 89.1% blue: mean, bars ±1 std (5 subsets) Zero-shot accuracy after writing a word on the image 0% 20% 40% 60% 80% 100% 90.9 no text 99.9 89.0 25.2 16px text 99.9 87.7 14.7 24px text 99.9 85.0 11.8 32px text true class unrelated word another class
Figure 2: ViT-B/32 on the CIFAR-10 test set. Left: few-shot linear probes (k per class, 5 random subsets) with zero-shot and the all-data probe. Right: words written on a white strip at the bottom of the image at 16, 24 and 32 pixels (the first 100 images of each class, 1,000 in all). Numbers come from one complete run of this page's script.

Reading it section by section:

  • Zero-shot (section 1). The bare class name scores 87.3%; with templates, the individual templates fall between 86.4% and 89.4%, with a mean of 88.4%. The best, “a bad photo of a {}.”, and the worst, “a close-up photo of a {}.”, are 3 points apart, far more than the standard error from 10,000 test images (0.3 points), while templates that are close to each other differ by a fraction of a point, which should not be interpreted. The ensemble reaches 89.1%: less than one point above the mean of the 8 templates, but not above the best single template (89.4%). Nobody knows in advance which template is best, so the value of the ensemble is robustness: it does not depend on picking the right template, at the same cost as a single one. It is more than 2 points below the paper’s 91.3% in Table 11; the paper used its own templates for CIFAR-10, and preprocessing and implementation may differ too, and I did not chase the gap down, so I do not explain it. The three most common errors are deer predicted as horse (137 images), cat as dog (82) and frog as cat (69), all animals that look alike; horse is the best class (98%) and frog the worst (77%).
  • Temperature (section 2). The mean cosine similarity to the right class is 0.276 and to the other classes 0.218, a gap of 0.058. Fed directly to a softmax (scale 1), the 10 classes get nearly equal probability: the mean top probability is only 0.106 and the cross entropy 2.251, close to the 2.3026 of a pure guess. Multiplying by a scale is what widens the gap: at a scale of 100 (the value the public weights learned) the cross entropy falls to 0.360 and the mean top probability is 0.842, a little below the accuracy of the zero-shot ensemble (89.1%); at a scale of 200 the mean top probability, 0.931, is above the accuracy and the cross entropy rises to 0.383. So the scale at which mean confidence equals accuracy lies between 100 and 200, and at 50 the cross entropy is already much higher (0.645): the cap of 100 that the paper imposes is close to the optimum for this dataset. The temperature is a stabilizer during training and also the dial that turns scores into probabilities at inference.
  • Few-shot (section 3). With one image per class the linear probe reaches only 69.1% (standard deviation 2.0 points over 5 subsets), 20 points below zero-shot’s 89.1%. The paper also reports this counter-intuitive effect: going from zero-shot to a few-shot linear classifier can lower the score at first, and its explanation is that zero-shot specifies the concept directly in language, while few-shot learning must infer it indirectly from a few images, and since one image usually contains several concepts, many hypotheses fit the data in the one-shot case. As k grows the probe catches up: 87.6% at 8 and 89.8% at 16 (standard deviation only 0.3 points), and zero-shot’s 89.1% falls between 8 and 16 images. The paper says that zero-shot CLIP matches a 4-shot linear probe on average; that is an average over 20 datasets and this is a single dataset, so the two do not contradict each other. One possible reason is that CIFAR-10’s 10 class names are concrete and easy to put into words, so zero-shot has an easier job here than on average; that is a guess I did not test. The probe on all 49,000 training images scores 94.7%, less than half a point from the paper’s 95.1% in Table 10; the implementation and the way λ is tuned differ, so a bit-for-bit match is not expected.
  • Typographic attack (section 4). The baseline without text is 90.9% on these 1,000 images. Writing the true class name at the bottom brings accuracy to 99.9% (at all three sizes), which shows that the image encoder can read the text and that what it reads is more persuasive than the picture. Writing another class name drops accuracy to 25.2% (16 px), 14.7% (24 px) and 11.8% (32 px), and the share of predictions that follow the written wrong name is 74.2%, 85.3% and 88.2%: the larger the text, the more the model listens to it. Writing an unrelated word, hello, only lowers accuracy to 89.0%, 87.7% and 85.0%, so neither the occlusion by the bar nor the extra text as such is the main cause; the meaning of the wrong class name is. The standard error on 1,000 images is about 1 point, so the small drop for hello at 16 px is barely above noise and is not interpreted.

What this experiment can and cannot say

  • It can say: on CIFAR-10, “defining a classifier in language” does work; the choice of prompt template changes the score by a few points and the ensemble reduces the dependence on it; a linear probe needs 8 to 16 training images per class to catch up with zero-shot; and text in the image overwhelms the image content in its effect on the prediction.
  • It cannot say: whether the paper’s 91.3% or 95.1% can be reproduced bit for bit, since templates, preprocessing and probe implementation all differ from the paper; the paper’s “zero-shot is worth 4 shots” result, since there is only one dataset here; or how severe the typographic attack is on real photographs and larger models, since black text on a white bar, horizontal and centered, is the most legible way to write, and text in the wild is rarely that easy to read. The typographic attack was documented in later analysis of CLIP by Goh et al.; it is not an experiment of the CLIP paper.
  • Scale: 10,000 test images (standard error 0.3 points); only 5 subsets per few-shot setting, with λ chosen on a fairly large validation set; and 1,000 images for the typographic attack, where the same images are reused in every condition, so differences between conditions are more trustworthy than the absolute numbers in each.

Limitations and what came after

The paper’s own limitations still repay attention:

  • The weaknesses are systematic. Fine-grained classification (car models, flower species, aircraft variants), abstract and systematic tasks (counting objects), and novel tasks unlikely to be in the pre-training data (the distance to the nearest car) leave zero-shot performance near chance.
  • It is brittle outside its distribution. Zero-shot CLIP does well on digitally rendered text, which is common in the pre-training data, but reaches only 88% on handwritten MNIST digits, and the paper notes that logistic regression on raw pixels beats it; nearest-neighbor retrieval confirmed that almost no MNIST-like images are in the pre-training data. The paper’s conclusion is that CLIP does little to address the brittle generalization of deep learning, and instead hopes that a dataset large and varied enough puts everything in-distribution.
  • It can only choose among the concepts you write down. A zero-shot classifier picks from the classes you supply, unlike a captioning model that can generate new answers; the paper suggests trying joint contrastive and generative training.
  • Data efficiency is not improved. Showing the 12.8 billion images of 32 epochs at one image per second would take 405 years.
  • Social bias. The image-text pairs come from the internet, unfiltered and uncurated, and the model learns many social biases; Section 7 of the paper quantifies this with FairFace and others, and points out that the ability to define your own classes without retraining magnifies the issue, for instance by asking a model to classify “shoplifters” in department-store photos.

Later work went in three directions. Larger open data and reproducible scaling: LAION-400M (Schuhmann et al., 2021) and LAION-5B (2022) provide open image-text data, and the OpenCLIP scaling-law study (Cherti et al., 2022) trains on up to two billion pairs and finds that OpenAI’s and OpenCLIP’s models scale differently despite identical architectures, so the training distribution plays a key role. A better loss: SigLIP (Zhai et al., 2023) replaces the softmax with a pairwise sigmoid loss that needs no global normalization over the batch, so the batch size can be pushed to one million, though the authors find the gains diminish quickly and a batch size of 32k is sufficient. Combining with language models: LLaVA attaches the visual features of CLIP ViT-L/14 to an LLM through a projection and instruction-tunes the result into a model that can chat about images; the paper itself suggests combining contrastive and generative objectives. Almost simultaneously, Google’s ALIGN (Jia et al., February 2021) trained a similar dual encoder on over one billion unfiltered image and alt-text pairs, showing that scale can make up for noise.

What to take away from this paper

  1. What changed is the supervision signal, not the network. The image encoder is a ResNet or a ViT and the text encoder is a transformer; what is new is contrastive learning on image-text pairs that already exist on the internet, and writing “the classes” as sentences.
  2. Zero-shot is an interface, not a capability. The classifier is determined by the words you write, so the template, the synonyms and the choice of classes all change the result; when you evaluate it, do not credit the model for good class names and templates.
  3. Read its numbers by model and by baseline. The 16 of 27 is the largest CLIP against a linear classifier on ResNet-50 features, not against the best model on each dataset.
  4. The training distribution sets the boundary of the ability. It reads digitally rendered text but not handwritten digits; that it can “read” text inside an image is both an OCR ability and the reason why, in the experiment above, the predictions follow the written word.

Further reading

FAQ

What is CLIP and how is it trained?
CLIP (Contrastive Language-Image Pre-training) is a contrastive image-text model from OpenAI (2021). On 400 million image-text pairs collected from the internet, it trains an image encoder (a ResNet or a ViT) and a text encoder (a Transformer) from scratch: in each batch (32,768 pairs) it pulls the embeddings of the true pairs together and pushes the other, mismatched pairs in the batch apart, using a symmetric cross entropy. The two encoders map images and text into one vector space, so an image classifier can be defined in words.
How does CLIP do zero-shot classification, and do prompt templates matter?
Put each class name into a template to make a sentence (for example “a photo of a dog.”) and embed it with the text encoder; for an image, pick the class whose sentence embedding has the highest cosine similarity. The class embeddings are computed once, so inference costs the same as a normal classifier. Templates matter: the paper found that a bare label is ambiguous and differs from the training text distribution; on ImageNet “A photo of a {label}.” gains 1.3%, and averaging 80 templates in embedding space gains another 3.5%. In this post's small CIFAR-10 experiment the bare class name scores 87.3%, eight templates I wrote score between 86.4% and 89.4% each, and their ensemble scores 89.1%.
What does the temperature (scale) do in CLIP?
CLIP's embeddings are L2-normalized, so a dot product is a cosine similarity between -1 and 1, and the differences between classes are small: on CIFAR-10 this post measures a mean cosine of 0.276 for the right class against 0.218 for the others, a gap of only 0.058. Fed to a softmax as it is, the 10 classes get nearly equal probability (mean top probability 0.106), so the logits are multiplied by exp(t) to widen the gap. CLIP learns t, starting from a temperature of 0.07 (a scale of 14.29) and capping exp(t) at 100, which the paper says was needed to avoid unstable training; the public ViT-B/32 weights end up exactly at 100.
What are CLIP's main weaknesses?
The paper lists fine-grained classification (car models, flower species, aircraft variants), abstract and systematic tasks (counting objects) and novel tasks unlikely to be in the pre-training data (estimating the distance to the nearest car), where zero-shot performance is near random; fragility out of distribution (88% on handwritten MNIST, beaten by logistic regression on raw pixels); the fact that a zero-shot classifier can only choose among the classes you write down; and social biases learned from unfiltered internet image-text pairs. Text written on an image is also treated as strong evidence: in this post's CIFAR-10 experiment, writing a wrong class name on the image drops accuracy from 90.9% to between 11.8% and 25.2%, and 74.2% to 88.2% of the predictions follow the written word (this typographic attack comes from Goh et al.'s 2021 analysis, not from the CLIP paper).
How is CLIP related to multimodal LLMs such as LLaVA?
LLaVA's vision encoder is CLIP's ViT-L/14: the image goes through the frozen CLIP vision tower, which yields grid features (one vector per image patch); a trainable linear projection turns them into visual tokens in the language model's word-embedding space, and they enter the language model together with the text tokens. CLIP supplies vision features that are aligned with language, and visual instruction tuning then teaches the language model to answer questions with them. CLIP's text encoder is normally not used on this route.