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
- Builds on
- 36 concepts →
- Quiz
- 5 questions ↓
The full path from zero — 36 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Tensors and Shapes
- Supervised Learning
- Images as Data
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Convolutional Neural Networks
- Word Embeddings
- Vanishing and Exploding Gradients
- Normalization Layers: BatchNorm and LayerNorm
- Image Classification
- LSTMs and GRUs
- Residual Connections
- Sequence-to-Sequence Models
- Attention
- Self-Attention and Multi-Head Attention
- Positional Encodings
- The Transformer
- BERT and Encoder Models
- Vision Transformers
- Sentence Embeddings
- 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.
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 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 (512 for CLIP ViT-B/32, 768 for ViT-L/14), and each vector is normalised to length 1. Call them (image ) and (caption ). 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 matrix of logits:
(tau) is a temperature. Dividing by a small , such as 0.07, stretches the similarities apart so that the softmax that follows can become confident. CLIP learns during training (it learns , called the logit scale, capped at 100).
Now treat each row as a classification problem: image must pick out its own caption, column , from the candidates. That is ordinary softmax cross-entropy:
Read the fraction as "the probability the model gives to the correct caption for image ". Do the same down each column (each caption must pick out its image) to get , and average the two:
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 (logit scale 100) the logits are 31, 24, 12 and 10. The softmax probability of the correct caption is , so the loss for this row is about . With 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:
- Write a caption for each class, such as "a photo of a dog", "a photo of a cat".
- Encode the captions with the text encoder to get , and the image with the image encoder to get .
- Compute the cosine similarity of with each , multiply by the logit scale, and apply softmax. The highest-probability class wins.
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 . 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
- Multimodal LLMs connect a CLIP-style image encoder to a language model so it can talk about images.
- Text-to-Image in Practice and Latent Diffusion and Stable Diffusion models use CLIP-style text encoders to steer generation.
- Vector Databases and Embeddings and Semantic Search apply the same retrieval ideas to images.
- Video–text models extend contrastive training to clips and captions, and audio–text versions (CLAP) do the same for sound.
- Open-vocabulary detection and Image Segmentation use CLIP-like embeddings to find objects named in free text.
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
- In the worked example, compute the probability of the correct caption with . How does it compare with and ?
- In the toy experiment, change the temperature to 1.0 and retrain. What happens to the retrieval accuracy after 300 steps?
- 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_logitswith a learnable scale and bias, and compare retrieval accuracy with the CLIP loss.Hint for 1: with the logits are 6.2, 4.8, 2.4 and 2.0. The correct one gets about 0.78.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Learning Transferable Visual Models From Natural Language Supervision
CLIP: images and text in one embedding space, trained on 400M image–caption pairs.
Transformers documentation: CLIP
How to load CLIP models and processors in Hugging Face Transformers, with examples of zero-shot classification and computing image and text embeddings.
OpenCLIP
Open-source implementation of CLIP with many pretrained image–text models trained on public datasets, plus training code and benchmark results.
Sigmoid Loss for Language Image Pre-Training
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.
LAION-5B: An open large-scale dataset for training next generation image-text models
Describes the 5.85-billion-pair image–text dataset collected from the web and filtered with CLIP, used to train open CLIP and diffusion models.
A Simple Framework for Contrastive Learning of Visual Representations
SimCLR: two augmented views, a shared encoder and the InfoNCE loss. Shows which augmentations matter and why big batches help.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/vision/clip.md