AI Logic

Architectures

CLIP

Updated:

The architecture of CLIP. On the left, the training flow (the outputs of the image encoder and text encoder are mapped into a shared space by linear projection and normalization, and a symmetric cross-entropy over the N×N similarity matrix predicts the pairs on the diagonal). On the right, the zero-shot classification flow (class names are turned into prompt sentences and passed through the text encoder, and the class with the highest similarity to the image embedding is selected)

Background and Overview

CLIP (Contrastive Language-Image Pre-training) is a model that uses 400 million images and their captions collected from the internet to jointly train an image encoder and a text encoder with contrastive learning that predicts which image goes with which text. It was published in 2021 by Radford et al. at OpenAI. After training, it can classify a dataset's images without ever training on them, simply by turning class names into sentences and passing them through the text encoder (zero-shot classification).

Earlier image recognition models were trained to predict a fixed list of classes, such as the 1000 classes of ImageNet. With this kind of supervision, labeled data must be collected again every time a new kind of object needs to be recognized. Meanwhile, the internet holds huge amounts of images paired with captions, and text can express far broader concepts than "one of 1000 classes."

CLIP carried out this text-supervised learning at large scale. There are three key points.

  • A dataset of 400 million pairs (WIT): image-text pairs were collected using 500,000 search queries derived from sources such as English Wikipedia, capped at 20,000 pairs per query to reduce imbalance.
  • A contrastive objective: instead of generating the caption word by word, the model only has to predict which text in the mini-batch goes with which image. In the paper's comparison, this learns several times more efficiently than predicting the text.
  • Zero-shot classification: after training, a sentence such as "A photo of a {class name}." is created for each class and passed through the text encoder, and the result serves directly as the weights of a classifier.

The largest model (ViT-L/14@336px) reached 76.2% accuracy on ImageNet without using a single ImageNet training image, matching the original ResNet-50 trained on 1.28 million labeled images. It was also shown to be far more robust than ImageNet-trained models on images that look different from ImageNet, such as paintings and sketches.

Theory: Contrastive Learning of Images and Text

CLIP's training forms N×NN \times N combinations from the NN image-text pairs in a mini-batch, raising the similarity of the NN true pairs and lowering the remaining N2−NN^2 - N. In the figure at the top of this article, the left shows the training flow and the right shows the zero-shot classification flow.

Training procedure (Section 2.3 and the pseudocode in Figure 3 of the paper)

  1. Encode each side: the NN images go through the image encoder and the NN paired texts through the text encoder, giving features If∈RN×diI_f \in \mathbb{R}^{N \times d_i} and Tf∈RN×dtT_f \in \mathbb{R}^{N \times d_t}.
  2. Map into a shared space: linear projections WiW_i and WtW_t bring each to the same dimension ded_e, and the results are normalized to unit length (L2 normalization). Let the image embeddings be uiu_i and the text embeddings vjv_j.
  3. Compute the similarity of every combination: an N×NN \times N matrix of cosine similarities is built and divided by a learned temperature τ\tau.
  4. Compute a symmetric cross-entropy: cross-entropy is computed row-wise (from the image's view, which of the NN texts is its pair) and column-wise (from the text's view, which of the NN images is its pair), and the two are averaged. The correct answers lie on the diagonal.

In equations:

sij=ui⊤vjτ,L=12N∑i=1N(−log⁡exp⁡(sii)∑j=1Nexp⁡(sij)  −  log⁡exp⁡(sii)∑j=1Nexp⁡(sji))s_{ij} = \frac{u_i^{\top} v_j}{\tau}, \qquad \mathcal{L} = \frac{1}{2N} \sum_{i=1}^{N} \left( -\log \frac{\exp(s_{ii})}{\sum_{j=1}^{N} \exp(s_{ij})} \; - \; \log \frac{\exp(s_{ii})}{\sum_{j=1}^{N} \exp(s_{ji})} \right)

The first term is the loss of choosing the text given the image, and the second is the loss of choosing the image given the text. Both take the form of InfoNCE, which picks the one positive out of the positive and N−1N-1 negatives, and CLIP applies it in both directions between images and text. The paper also explains that this batch construction and objective were introduced in metric learning as the multi-class N-pair loss and became popular as InfoNCE.

The temperature τ\tau is learned too

The temperature sets the range of the logits fed into the softmax. Rather than tuning τ\tau as a hyperparameter, CLIP learns it as a log-parameterized scalar tt (1/τ=et1/\tau = e^{t}). It is initialized to the equivalent of τ=0.07\tau = 0.07 and clipped so that the logits are not scaled by more than 100 (Section 2.5 of the paper). Without this cap, training became unstable.

Why it is more efficient than generating text

The first approach tried, generating captions word by word from images, made the task of predicting the exact words too hard, because captions for the same image vary widely in wording. In Figure 2 of the paper, a Transformer language model that generates captions improves ImageNet zero-shot accuracy 3 times more slowly than a simple baseline that predicts the bag of words in the caption (ignoring word order), and swapping prediction for contrastive learning makes it a further 4 times more efficient. With contrastive learning, the model only has to identify which text as a whole is the pair, so the task is easier and the model can focus on learning image features.

In contrastive learning, more negatives make the task harder and lead to better features. CLIP's mini-batch is extremely large, at 32,768 pairs, so each image must pick the correct text out of more than 30,000. As an analogy, it is like a game of Concentration in which 30,000 pairs of photo and caption cards are shuffled together and the correct pairs must be found.

Architecture

CLIP's architecture connects two encoders, one for images and one for text, to the same embedding space through linear projections (Section 2.4 of the paper). Neither encoder uses pre-trained weights; both are trained together from scratch.

Image encoder

  • ResNet family: based on ResNet-50, it adds the ResNet-D improvements and blur pooling (anti-aliasing), and replaces the final global average pooling with attention pooling (a single layer of multi-head attention whose query is the global average). Larger models scale width, depth, and resolution in equal proportion, following the same idea as EfficientNet (RN50x4, RN50x16, RN50x64).
  • ViT family: almost the same as ViT, with an extra layer normalization added before the Transformer, after the patch and position embeddings are summed.

Text encoder

A Transformer with the same modifications as GPT-2. The base size is 12 layers, width 512, and 8 heads (63 million parameters). Text is lowercased, split into tokens with BPE (a vocabulary of about 49,000), and truncated to a maximum length of 76. [SOS] and [EOS] are added before and after the text, and the output at the [EOS] position of the last layer, after layer normalization and a linear projection, becomes the text embedding. Self-attention uses a mask that prevents attending to later tokens.

Projection

Only a linear projection is used, not the nonlinear projection (MLP) used in SimCLR and similar methods. The paper reports no difference in training efficiency between the two.

Model list (Section 2.5 and Tables 19 and 20 in the appendix of the paper; zero-shot ImageNet from Table 11)

ModelImage encoderEmbedding dimensionInput resolutionText encoder widthImageNet (zero-shot)
RN50ResNet-50102422451259.6%
RN101ResNet-10151222451262.2%
RN50x6464× the compute of ResNet-501024448102473.6%
ViT-B/32ViT-B, patch 3251222451263.2%
ViT-B/16ViT-B, patch 1651222451268.6%
ViT-L/14ViT-L, patch 1476822476875.3%
ViT-L/14@336pxViT-L, patch 1476833676876.2%

Training setup (Section 2.5 and Table 18 in the appendix of the paper)

All models are trained for 32 epochs. The optimizer is Adam with decoupled weight decay (the same as AdamW; weight decay 0.2), and the learning rate is decayed with a cosine schedule after 2000 iterations of warmup. The only data augmentation is a random square crop from resized images. To save memory, mixed-precision training and gradient checkpointing are used, and the similarity matrix is also computed in shards across GPUs. The largest ResNet, RN50x64, took 18 days on 592 V100 GPUs, and the largest ViT took 12 days on 256 V100 GPUs. ViT-L/14@336px is ViT-L/14 trained for one additional epoch at 336×336.

How Zero-Shot Classification Works

CLIP uses the ability it acquired in pre-training, judging whether an image and a text belong together, directly for classification (Section 3.1.2 of the paper).

  1. Create a sentence for each class: each class name in the dataset is inserted into a template sentence (prompt) such as "A photo of a {class name}."
  2. Compute text embeddings: the sentences, one per class, are passed through the text encoder to produce normalized embeddings. These are computed once and reused for predictions on every image.
  3. Compute the image embedding: the image to classify is passed through the image encoder.
  4. Select by similarity: the cosine similarity between the image embedding and each class's text embedding is computed, divided by the temperature, and passed through a softmax; the class with the highest probability is the prediction.

This has the same form as a linear classifier with no bias, whose inputs and weights are both normalized to unit length. The paper notes that the text encoder can be viewed as "a network that generates the weights of a linear classifier from descriptions of the classes." To change the list of classes, only the sentences need to be rewritten.

Prompt engineering

Feeding only the class name to the text encoder sometimes works poorly. Pre-training text is usually a full sentence rather than a single word, and a single word can be ambiguous, as in ImageNet, where both the bird and the construction machine appear as "crane."

  • Use a template sentence: simply using "A photo of a {class name}." raises ImageNet accuracy by 1.3 points.
  • Add task-specific context: adding context, such as "a type of pet" for pet breeds or "a satellite photo of" for satellite images, improves results.
  • Average multiple sentences: on ImageNet, averaging the embeddings of 80 different sentences, such as "A photo of a big {class name}." and "A photo of a small {class name}.", adds another 3.5 points. Once the averaged embedding is computed, prediction costs the same as with a single sentence.

Together, these raise ImageNet accuracy by almost 5 points. The paper states that this is about as effective as quadrupling the compute.

Experimental Results

Zero-shot classification

On ImageNet, accuracy jumped from 11.5% for the previous zero-shot work (Visual N-Grams) to 76.2% (Table 1 of the paper). Across 27 datasets, zero-shot CLIP beat a linear classifier trained with labeled data on ResNet-50 features on 16 of them (Figure 5 of the paper).

Dataset (zero-shot CLIP vs. ResNet-50 + linear classifier)Difference (points)
Stanford Cars (car models)+28.9
Food101 (dishes)+22.5
Kinetics700 (actions in video)+14.5
UCF101 (actions in video)+7.7
MNIST (handwritten digits)−10.0

On the other hand, zero-shot performance was much worse on satellite images (EuroSAT), lymph node tumor detection, counting objects, traffic signs, and the distance to the nearest car.

Compared with methods that use a few labeled examples, zero-shot CLIP is about as accurate as a linear classifier trained on the same CLIP features with 4 examples per class (Figure 6 of the paper). The paper attributes this to text conveying the class directly, which carries more information than a few example images.

Linear probing

With the image encoder frozen and only a linear classifier trained, ViT-L/14@336px reaches 85.4% on ImageNet (Table 10 of the paper). On 21 of 27 datasets, it outperforms the features of Noisy Student EfficientNet-L2, the most accurate ImageNet model at the time, with especially large gaps in optical character recognition, geolocation, and action recognition in videos.

Robustness to images that look different (compared with ResNet-101, which has the same ImageNet accuracy of 76.2%; Figure 13 of the paper)

DatasetResNet-101 trained on ImageNetZero-shot CLIP
ImageNet76.276.2
ImageNetV264.370.1
ImageNet-R (paintings, sculptures, etc.)37.788.9
ObjectNet32.672.3
ImageNet Sketch (sketches)25.260.2
ImageNet-A (hard natural images)2.777.1

Zero-shot CLIP narrows the gap between accuracy on ImageNet and accuracy on images that look different (the robustness gap) by up to 75%. However, training a linear classifier on CLIP features with ImageNet raises ImageNet accuracy by 9.2 points to 85.4%, while the average over the 7 datasets with different-looking images drops slightly.

Practical Considerations

Keep the following points in mind when using CLIP.

  • Accuracy depends on the prompt: rather than using the class name alone, insert it into a template sentence such as "A photo of a {class name}." and add task-specific context. Averaging the embeddings of multiple sentences makes it more stable.
  • It can only choose among the classes provided: zero-shot classification just picks from the given list of classes. It cannot freely generate captions for images.
  • It is weak on kinds of images absent from the pre-training data: on handwritten digits (MNIST), it reaches only 88%, losing even to a simple logistic regression on raw pixels, because the pre-training data contained almost no images like MNIST. For specialized images such as medical or satellite images, consider learning from even a few examples or fine-tuning.
  • It struggles with fine-grained distinctions and counting: on tasks such as flower species, aircraft models, or the number of objects in an image, it falls far behind task-specific models.
  • Where to get it in PyTorch: pre-trained weights can be loaded from OpenAI's official implementation (clip.load in openai/CLIP) or from CLIPModel and CLIPProcessor in Hugging Face transformers.

CLIP is trained on unfiltered images and text collected from the internet, so it learns social biases as they are. Chapter 7 of the paper also reports that the rate at which images of people's faces are misclassified into crime-related classes or non-human (animal) classes differs across racial and age groups. Avoid using it as is for classifying or surveilling people, and if it is used, check for bias on each task.

Comparison with Other Methods

CLIP is pre-training supervised by text, unlike both image-only self-supervised learning and supervised learning with labels. Comparing them from the same perspective gives the following.

MethodSupervisory signalTraining dataHandling new classesUse after training
Supervised (ResNet, ViT, etc. on ImageNet)Labels from a fixed set of classesHuman-labeled imagesRetrain on labeled dataDirect classification, fine-tuning
SimCLR, MoCoTwo views of the same image (InfoNCE)Unlabeled imagesRequires a linear classifier or fine-tuningLinear probing, fine-tuning
MAE, BEiTPredicting masked patchesUnlabeled imagesRequires fine-tuningFine-tuning
CLIPText paired with the image (bidirectional InfoNCE)400 million image-caption pairsJust rewrite the text (zero-shot)Zero-shot classification, linear probing, image-text retrieval

The difference from SimCLR and similar methods is how positives are formed. SimCLR uses two differently augmented versions of the same image as a positive pair, while CLIP uses the text paired with the image. Although the loss has the same InfoNCE form, the resulting space is tied to text, so classes can be specified in text.

Rough guidelines for choosing:

  • No labeled data, or classes change often: CLIP's zero-shot classification fits. New classes can be added just by rewriting text.
  • Comparing images and text in the same space (e.g., retrieval): CLIP embeddings can be used directly for finding images from text or choosing the text that matches an image.
  • High accuracy needed on specialized images: zero-shot is often not enough, so train a linear classifier on CLIP features, or fine-tune a supervised or self-supervised pre-trained model.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F

"""
1) A small implementation of CLIP's symmetric contrastive loss (pseudocode in Figure 3 of the paper)
2) An example of zero-shot classification with pre-trained CLIP (Hugging Face transformers)
"""


class CLIPHead(nn.Module):
  """Maps the features of the two encoders into a shared space with linear projections and computes the symmetric cross-entropy"""

  def __init__(self, d_img=768, d_txt=512, d_embed=512):
    super().__init__()
    self.W_i = nn.Linear(d_img, d_embed, bias=False)     # image → embedding (no nonlinear MLP)
    self.W_t = nn.Linear(d_txt, d_embed, bias=False)     # text → embedding
    # The temperature τ is learned in log space: 1/τ = exp(t). Initialized to τ = 0.07
    self.t = nn.Parameter(torch.tensor(1 / 0.07).log())

  def forward(self, I_f, T_f):
    """I_f: [N, d_img] image features, T_f: [N, d_txt] text features (the i-th items form a pair)"""
    I_e = F.normalize(self.W_i(I_f), dim=-1)              # L2 normalization
    T_e = F.normalize(self.W_t(T_f), dim=-1)
    scale = self.t.exp().clamp(max=100.0)                 # keep the logit scale from exceeding 100
    logits = scale * I_e @ T_e.t()                        # [N, N] cosine similarity / τ
    labels = torch.arange(logits.shape[0], device=logits.device)   # correct answers are on the diagonal
    loss_i = F.cross_entropy(logits, labels)              # from the image's view, which text is the pair
    loss_t = F.cross_entropy(logits.t(), labels)          # from the text's view, which image is the pair
    return (loss_i + loss_t) / 2


head = CLIPHead()
I_f = torch.randn(8, 768)    # in practice, the output of the image encoder (ResNet, ViT)
T_f = torch.randn(8, 512)    # in practice, the output of the text encoder (Transformer at the [EOS] position)
loss = head(I_f, T_f)
loss.backward()


# ---- Zero-shot classification with pre-trained CLIP ----
# from PIL import Image
# from transformers import CLIPModel, CLIPProcessor
# model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32").eval()
# processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
# classes = ["dog", "cat", "car"]
# texts = [f"A photo of a {c}." for c in classes]          # insert into the prompt
# inputs = processor(text=texts, images=Image.open("x.jpg"), return_tensors="pt", padding=True)
# with torch.no_grad():
#   probs = model(**inputs).logits_per_image.softmax(dim=-1)   # [1, number of classes]
# print(classes[probs.argmax().item()])

FAQ

Q. What is CLIP's zero-shot classification?
A.

It means classifying a dataset's images without training on a single one of them. Class names are inserted into sentences such as "A photo of a {class name}." and passed through the text encoder, and the class with the highest cosine similarity to the image embedding is selected. With this method, CLIP's largest model reached 76.2% on ImageNet, matching a ResNet-50 trained on 1.28 million labeled images.

Q. How does CLIP's loss relate to InfoNCE?
A.

CLIP's loss applies InfoNCE in both directions between images and text. For the NN pairs in a mini-batch, it computes the cross-entropy of predicting which of the NN texts is the pair from the image's view, and the cross-entropy of predicting which of the NN images is the pair from the text's view, and averages them. The differences are that the positive is the paired text rather than another view of the same image, and that the temperature τ\tau is also learned.

Q. Why use a mini-batch as large as 32,768?
A.

In contrastive learning, the other pairs in the mini-batch serve as negatives, so a larger mini-batch means more negatives and a harder discrimination task. CLIP makes each image pick the correct text out of more than 30,000. This requires a lot of memory, so it uses techniques such as mixed-precision training, gradient checkpointing, and computing the similarity matrix in shards across GPUs.

References

  1. Radford, A., Kim, J. W., Hallacy, C., Ramesh, A., Goh, G., Agarwal, S., Sastry, G., Askell, A., Mishkin, P., Clark, J., Krueger, G., & Sutskever, I. (2021). Learning Transferable Visual Models From Natural Language Supervision. arXiv:2103.00020.
  2. openai/CLIP (official implementation and pre-trained weights).
  3. van den Oord, A., Li, Y., & Vinyals, O. (2018). Representation Learning with Contrastive Predictive Coding (InfoNCE). arXiv:1807.03748.
  4. Dosovitskiy, A., et al. (2021). An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale. ICLR 2021. arXiv:2010.11929.