◆ AI All-in-One

Level 3 In-Depth AI · Vision, Audio and Multimodal

CLIP and Contrastive Learning

CLIP learns from hundreds of millions of image–caption pairs to put pictures and text into one shared embedding space, where a photo of a dog lands near the words "a photo of a dog". That makes zero-shot classification, image search and text-guided image generation possible.

Level
●●●●● Intermediate
Reading
12 min
To learn it well
1 hour to read, an hour to practise
↗ Plan a path here

Read first

Vision TransformersSentence Embeddings

This leads to

Latent Diffusion and Stable DiffusionMultimodal LLMs
The full path from zero — 36 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. The Chain Rule
  9. Dot Product, Norms and Similarity
  10. Supervised, Unsupervised and Reinforcement Learning
  11. Gradient Descent
  12. Tensors and Shapes
  13. Supervised Learning
  14. Images as Data
  15. Linear Regression
  16. The Perceptron
  17. Logistic Regression
  18. Neural Networks
  19. Recurrent Neural Networks
  20. Backpropagation
  21. Activation Functions
  22. Convolutional Neural Networks
  23. Word Embeddings
  24. Vanishing and Exploding Gradients
  25. Normalization Layers: BatchNorm and LayerNorm
  26. Image Classification
  27. LSTMs and GRUs
  28. Residual Connections
  29. Sequence-to-Sequence Models
  30. Attention
  31. Self-Attention and Multi-Head Attention
  32. Positional Encodings
  33. The Transformer
  34. BERT and Encoder Models
  35. Vision Transformers
  36. Sentence Embeddings
  37. CLIP and Contrastive Learning

Read them roughly in this order. See it on the concept map →

Why it matters

Classic image classifiers know only the labels they were trained on. A model trained on ImageNet's 1,000 classes cannot recognise a "pangolin" or a "broken solar panel" unless someone collects and labels thousands of examples and retrains it. Labelled data is the bottleneck.

The internet, though, is full of images with text next to them: captions, alt text and article titles. In January 2021 OpenAI's CLIP (Contrastive Language–Image Pre-training) learned from 400 million such image–text pairs, with no hand-labelling at all. The result was a model that can classify images into any categories you name in plain words, a job called zero-shot classification. Without seeing a single ImageNet training example, its largest version matched the accuracy of the original supervised ResNet-50 on ImageNet.

CLIP and its descendants (OpenCLIP, SigLIP) are now infrastructure:

  • Image search by text ("red sneakers on a white background") and by image, in photo apps and shops.
  • Text-to-image generation: Stable Diffusion's original versions read the prompt through CLIP's text encoder, and DALL·E 2 generated images from CLIP embeddings (Text-to-Image in Practice).
  • Multimodal LLMs: LLaVA-style models use a CLIP or SigLIP image encoder as their "eyes" (Multimodal LLMs).
  • Data filtering and evaluation: big image datasets such as LAION were filtered by CLIP similarity between image and caption, and CLIP similarity is used to score generated images.

The intuition

Recall Sentence Embeddings: a model turns each sentence into a vector so that sentences with similar meanings end up close together. CLIP does the same thing for two kinds of input at once. It has two encoders, one for images (a vision Transformer or a ResNet) and one for text (a The Transformer), and trains them so that an image and a caption describing it get nearby vectors in the same space. That space is a shared embedding space: "a photo of a dog" and a photo of a dog become neighbours.

How do you train that without labels? Play a matching game. Take a batch of, say, 4 images and their 4 captions. Shuffle the captions, and ask the model to say which caption goes with which image. Compute the similarity of every image with every caption: a 4 × 4 grid. The correct pairs lie on the diagonal. Train the encoders to make the diagonal scores high and all the others low.

Text encoder (Transformer) a photoof a dog T1 a photoof a cat T2 a photoof a car T3 a photoof a tree T4 Imageencoder(ViT) I1 I2 I3 I4 I1·T1 = 0.31 I1·T2 = 0.24 I1·T3 = 0.12 I1·T4 = 0.10 I2·T1 = 0.25 I2·T2 = 0.30 I2·T3 = 0.11 I2·T4 = 0.12 I3·T1 = 0.09 I3·T2 = 0.10 I3·T3 = 0.29 I3·T4 = 0.13 I4·T1 = 0.11 I4·T2 = 0.12 I4·T3 = 0.14 I4·T4 = 0.28 Each cell: cosine similarity of an image embedding and a caption embedding (illustrative values).Training pushes the diagonal (true pairs) up and everything else down.
Fig. 1 The CLIP training signal. Each image (rows) and each caption (columns) is encoded into a vector, and every pair is scored by cosine similarity. True pairs lie on the diagonal. The contrastive loss pushes them up and pushes all the mismatched pairs down.

Every other caption in the batch serves as a free "wrong answer". These are called in-batch negatives. CLIP used batches of 32,768 pairs, so each image had to pick its caption out of 32,768 candidates. To win that game, the image encoder must notice everything a caption might mention (objects, colours, text in the image, style, counts) and the text encoder must learn what those words look like. This style of training, where a model learns by telling matching pairs apart from non-matching ones, is contrastive learning.

Key idea CLIP trains an image encoder and a text encoder together so that matching image–caption pairs have high cosine similarity and mismatched pairs have low similarity. Afterwards, classifying an image means asking which caption ("a photo of a {class}") it is most similar to.

How it works

The two encoders

For a batch of NN pairs, the image encoder maps each image to a vector, and the text encoder maps each caption to a vector. A final linear layer on each side projects both into the same dimension DD (512 for CLIP ViT-B/32, 768 for ViT-L/14), and each vector is normalised to length 1. Call them ui\mathbf{u}_i (image ii) and vj\mathbf{v}_j (caption jj). Because they have unit length, their dot product is their cosine similarity, a number between −1 and 1.

The similarity matrix and the loss

Collect all pairwise similarities into an N×NN \times N matrix of logits:

sij=ui⋅vjτs_{ij} = \frac{\mathbf{u}_i \cdot \mathbf{v}_j}{\tau}

τ\tau (tau) is a temperature. Dividing by a small τ\tau, such as 0.07, stretches the similarities apart so that the softmax that follows can become confident. CLIP learns τ\tau during training (it learns 1/τ1/\tau, called the logit scale, capped at 100).

Now treat each row as a classification problem: image ii must pick out its own caption, column ii, from the NN candidates. That is ordinary softmax cross-entropy:

Limage=−1N∑i=1Nlog⁡esii∑j=1NesijL_{\text{image}} = -\frac{1}{N} \sum_{i=1}^{N} \log \frac{e^{s_{ii}}}{\sum_{j=1}^{N} e^{s_{ij}}}

Read the fraction as "the probability the model gives to the correct caption for image ii". Do the same down each column (each caption must pick out its image) to get LtextL_{\text{text}}, and average the two:

L=12(Limage+Ltext)L = \tfrac{1}{2}\left(L_{\text{image}} + L_{\text{text}}\right)

This symmetric loss is a form of the InfoNCE loss used in Sentence Embeddings and in self-supervised methods such as SimCLR. In code it is just cross_entropy(logits, arange(N)) applied to the matrix and to its transpose.

Worked example. Take the dog row of the figure, with cosine similarities 0.31 (dog caption), 0.24 (cat), 0.12 (car) and 0.10 (tree). With τ=0.01\tau = 0.01 (logit scale 100) the logits are 31, 24, 12 and 10. The softmax probability of the correct caption is e31/(e31+e24+e12+e10)≈0.999e^{31} / (e^{31} + e^{24} + e^{12} + e^{10}) \approx 0.999, so the loss for this row is about −log⁡0.999≈0.001-\log 0.999 \approx 0.001. With τ=1\tau = 1 the same similarities give probabilities of roughly 0.28, 0.26, 0.23 and 0.23, and a loss of about 1.27. The small temperature turns modest differences in cosine similarity into decisive predictions.

Zero-shot classification

After training, you can classify an image into any set of classes without further training:

  1. Write a caption for each class, such as "a photo of a dog", "a photo of a cat".
  2. Encode the captions with the text encoder to get v1,…,vK\mathbf{v}_1, \dots, \mathbf{v}_K, and the image with the image encoder to get u\mathbf{u}.
  3. Compute the cosine similarity of u\mathbf{u} with each vk\mathbf{v}_k, multiply by the logit scale, and apply softmax. The highest-probability class wins.
1. Turn class names into captions “a photo of a dog” “a photo of a cat” “a photo of a car” “a photo of a tree” Textencoder T1 T2 T3 T4 2. Encode the image Imageencoder I 3. Compare and pick the best cos(I, Tₖ)× 100, softmax dog0.002 cat0.998 car0.000 tree0.000 No “cat” training labels were needed:the list of classes is chosen at test time.
Fig. 2 Zero-shot classification with CLIP. Class names become captions; the image and the captions are encoded; the caption whose embedding is most similar to the image's gives the label.

The caption wording matters. A bare label like "boxer" is ambiguous (a dog breed or an athlete?), while "a photo of a boxer, a type of dog" is not. The CLIP paper found that the template "A photo of a {label}." beat the bare label, and that averaging the text embeddings of many templates ("a blurry photo of a {label}", "a drawing of a {label}", …) helped further. This is called prompt ensembling.

The text embeddings act as the weights of a linear classifier, written in words instead of learned from examples. That is also why CLIP features make an excellent base for a linear probe: train a logistic regression on frozen image embeddings with a few labelled examples per class.

Image–text retrieval

The same embeddings support image–text retrieval. Encode a million product photos once and store the vectors in a vector database. A text query is then one text encoding plus a nearest-neighbour search. Image-to-image search ("more like this") works the same way.

Scale and successors

CLIP's ingredients were simple: a standard contrastive loss, standard encoders, and data at a scale no one had used for this before. Its largest model (ViT-L/14 at 336 pixels) reached 76.2% zero-shot top-1 on ImageNet, about the same as a ResNet-50 trained on ImageNet's 1.28 million labelled images. It was also much more robust than such models on shifted versions of ImageNet, such as sketches and renditions.

Successors scaled and refined the recipe:

  • ALIGN (Google, 2021) used 1.8 billion noisier pairs.
  • LAION-5B (2022) released 5.85 billion web pairs, and OpenCLIP trained open CLIP models on them.
  • SigLIP (2023) replaced the softmax over the whole batch with an independent sigmoid "match or not?" decision for every image–caption pair. It works well with smaller batches, and SigLIP encoders are popular in recent multimodal LLMs.

In code

The CLIP loss on random embeddings, then a toy experiment. Two linear "encoders" are trained with it to align two different noisy views of the same hidden content, the way CLIP aligns pixels and words.

import torch
import torch.nn.functional as F

def clip_loss(img_emb, txt_emb, temperature=0.07):
    """Symmetric contrastive loss: row i of each batch is a matching pair."""
    img = F.normalize(img_emb, dim=-1)                  # unit length, so dot product = cosine
    txt = F.normalize(txt_emb, dim=-1)
    logits = img @ txt.T / temperature                  # (N, N) similarity matrix
    targets = torch.arange(len(img))                    # the match for row i is column i
    loss_i2t = F.cross_entropy(logits, targets)         # each image: pick its caption
    loss_t2i = F.cross_entropy(logits.T, targets)       # each caption: pick its image
    return (loss_i2t + loss_t2i) / 2

torch.manual_seed(0)
N, D = 8, 64
print("random pairs   :", round(clip_loss(torch.randn(N, D), torch.randn(N, D)).item(), 3))  # 3.66
img = torch.randn(N, D)
print("matched pairs  :", round(clip_loss(img, img + 0.3 * torch.randn(N, D)).item(), 3))   # 0.0
print("chance level   :", round(torch.log(torch.tensor(N)).item(), 3))                      # 2.079

# Train two tiny "encoders" so that two different views of the same thing line up.
latent = torch.randn(2000, 16)                          # the hidden "content" of 2,000 items
images = latent @ torch.randn(16, 100) + 3.0 * torch.randn(2000, 100)   # view 1: "pixels"
texts = latent @ torch.randn(16, 50) + 3.0 * torch.randn(2000, 50)      # view 2: "words"
img_enc, txt_enc = torch.nn.Linear(100, 32), torch.nn.Linear(50, 32)
opt = torch.optim.Adam([*img_enc.parameters(), *txt_enc.parameters()], lr=1e-2)
for step in range(301):
    i = torch.randint(0, 1800, (256,))                  # batch from the first 1,800 items
    loss = clip_loss(img_enc(images[i]), txt_enc(texts[i]))
    opt.zero_grad(); loss.backward(); opt.step()
    if step % 100 == 0:
        with torch.no_grad():                           # retrieval on the 200 held-out items
            sim = F.normalize(img_enc(images[1800:]), dim=-1) @ F.normalize(txt_enc(texts[1800:]), dim=-1).T
            acc = (sim.argmax(1) == torch.arange(200)).float().mean()
        print(f"step {step:3d}  loss {loss.item():.3f}  image->text top-1 of 200: {acc:.2f}")

# step   0  loss 7.557  image->text top-1 of 200: 0.09
# step 100  loss 0.299  image->text top-1 of 200: 0.94
# step 200  loss 0.339  image->text top-1 of 200: 0.95
# step 300  loss 0.329  image->text top-1 of 200: 0.95

Notice that random embeddings give a loss above the chance level log⁡N\log N. The small temperature makes random similarities look confidently wrong. On held-out items, the trained encoders find the right partner out of 200 candidates 95% of the time, against 0.5% by chance.

With a real pretrained CLIP from Hugging Face (cat.jpg is any photo, weights download on first use):

import torch
from PIL import Image
from transformers import CLIPModel, CLIPProcessor

model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")

labels = ["dog", "cat", "car", "tree"]
image = Image.open("cat.jpg").convert("RGB")
inputs = processor(text=[f"a photo of a {l}" for l in labels], images=image,
                   return_tensors="pt", padding=True)
with torch.no_grad():
    probs = model(**inputs).logits_per_image.softmax(dim=1)[0]   # logit scale applied inside
print({l: round(p.item(), 3) for l, p in zip(labels, probs)})

# Embeddings for search: normalise, then compare with dot products
with torch.no_grad():
    img_vec = model.get_image_features(**processor(images=image, return_tensors="pt")).pooler_output
img_vec = img_vec / img_vec.norm(dim=-1, keepdim=True)            # (1, 512)

Common pitfalls

  • Forgetting to normalise. CLIP compares cosine similarities. Raw embedding norms vary, so always divide by the norm before taking dot products or storing vectors for search.
  • Bad class names. Ambiguous, rare or jargon labels ("crane", "jaguar", internal product codes) hurt zero-shot accuracy. Write descriptive captions and test several templates.
  • Expecting fine detail. CLIP is weak at counting ("three apples"), spatial relations ("the cup left of the plate"), reading small text, and very specialised domains such as medical scans and satellite imagery. Check on your data before relying on it.
  • Comparing scores across different queries. A cosine similarity of 0.3 is not "30% confident". Raw similarities are only meaningful relative to other candidates for the same query, or after calibration.
  • Mixing models. Embeddings from different CLIP checkpoints live in different spaces. Never compare a ViT-B/32 image vector with a ViT-L/14 text vector, and re-index everything if you change model.

Watch out CLIP learned from unfiltered web text, so it absorbed the web's biases and quirks. It can associate certain demographic groups with offensive or criminal labels, and it can be fooled by a typographic attack: an apple with a paper label reading "iPod" stuck on it was classified as an iPod. Don't use zero-shot CLIP for decisions about people without careful testing for bias.

Where it leads

A bit of history

Learning visual concepts from text is an old idea. Mori and colleagues (1999) linked image regions to words, and DeViSE (Google, 2013) mapped images into a word-embedding space. Most attempts stayed small and well below supervised accuracy. Contrastive learning matured in parallel, from van den Oord's InfoNCE loss (2018) to SimCLR (2020), which learned strong image features by contrasting augmented views.

OpenAI's CLIP (Radford and colleagues, January 2021) combined the two at scale: 400 million pairs, a simple symmetric contrastive loss and Transformers. It was released together with DALL·E. Google's ALIGN followed weeks later. LAION's open datasets (2021–2022) and OpenCLIP made the approach reproducible outside large labs. SigLIP (2023) refined the loss. Since 2023, CLIP-family encoders have become the standard "eyes" of multimodal language models.

Try it

  1. In the worked example, compute the probability of the correct caption with τ=0.05\tau = 0.05. How does it compare with τ=0.01\tau = 0.01 and τ=1\tau = 1?
  2. In the toy experiment, change the temperature to 1.0 and retrain. What happens to the retrieval accuracy after 300 steps?
  3. Harder: implement the SigLIP loss: for the logits matrix, the target is 1 on the diagonal and 0 elsewhere. Apply F.binary_cross_entropy_with_logits with a learnable scale and bias, and compare retrieval accuracy with the CLIP loss.

Hint for 1: with τ=0.05\tau = 0.05 the logits are 6.2, 4.8, 2.4 and 2.0. The correct one gets about 0.78.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. You want CLIP to sort product photos into "boxer" (the dog) and "poodle". Which prompt is likely to work best?

  2. During CLIP training, a batch has 32,768 image–caption pairs. For a given image, what are the "negatives"?

  3. Two items get cosine similarities 0.31 and 0.24 with an image. Why does CLIP divide by a small temperature (multiply by a logit scale of about 100) before the softmax?

  4. Your image search index was built with CLIP ViT-B/32. You upgrade the text encoder to ViT-L/14 for queries only. What happens?

  5. An apple with a paper label reading "iPod" is classified by CLIP as an iPod. What is this called?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Docs

Transformers documentation: CLIP

Hugging Face · Intermediate · Free

How to load CLIP models and processors in Hugging Face Transformers, with examples of zero-shot classification and computing image and text embeddings.

Tool

OpenCLIP

LAION, ML Foundations and contributors · Intermediate · Free

Open-source implementation of CLIP with many pretrained image–text models trained on public datasets, plus training code and benchmark results.

Paper

Sigmoid Loss for Language Image Pre-Training

Zhai, Mustafa, Kolesnikov & Beyer (Google) · 2023 · Advanced · Free

SigLIP replaces CLIP's softmax contrastive loss with an independent sigmoid per image–text pair, which works better at small batch sizes and scales well.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/vision/clip.md