AI
CLIP Model: How AI Links Images and Text
The CLIP model explained: architecture, contrastive training, zero-shot classification, CLIP embeddings with Python code, uses, SigLIP and limits.
The CLIP model (Contrastive Language-Image Pre-training) is a neural network from OpenAI that learns to connect images and text by placing both in the same embedding space, where a photo and a caption that describes it end up close together. Trained on 400 million image-text pairs from the internet, CLIP can classify images into categories it was never explicitly trained on, just by comparing an image with text labels such as "a photo of a dog". Since its release in 2021 it has become a building block of image search, content moderation, dataset filtering, text-to-image generators and vision language models.
This guide explains what the CLIP model is, the CLIP model architecture, how contrastive training works, zero-shot classification with a worked example, CLIP embeddings and how to use them in Python, what CLIP is used for, OpenAI CLIP vs SigLIP and other successors, and CLIP's limitations.
What Is the CLIP Model?
OpenAI introduced CLIP in January 2021 in the paper "Learning Transferable Visual Models From Natural Language Supervision" by Alec Radford and colleagues. The idea was to stop training vision models on fixed lists of labelled categories and learn instead from the natural-language captions that already accompany images online.
CLIP has two parts:
- an image encoder that turns an image into a vector of numbers (an embedding), and
- a text encoder that turns a piece of text into a vector of the same size.
Training pushes matching image and text vectors together and non-matching ones apart. Afterwards, the similarity between any image and any text can be measured with a simple cosine similarity. That single capability, "how well does this text describe this image?", turns out to be remarkably flexible.
Note that "open clip vs closed clip" searches are mostly about hardware clips, not AI. In AI, "OpenCLIP" is an open-source reimplementation of CLIP, covered below.
CLIP Model Architecture
The CLIP model architecture is a dual encoder: two separate networks that meet only at the end.
Image encoder. OpenAI trained two families: modified ResNets (convolutional networks, with variants called RN50, RN101, RN50x4, RN50x16 and RN50x64) and Vision Transformers (ViT-B/32, ViT-B/16 and ViT-L/14, plus a higher-resolution ViT-L/14 at 336 pixels). The ViTs split an image into patches, 32 or 14 pixels square depending on the model, and process them with a transformer.
Text encoder. A transformer similar to GPT-2's design processes the text using a byte-level BPE tokenizer with a 49,152-token vocabulary. The paper caps text length at 76 tokens, plus start and end tokens, which is why CLIP-based tools truncate long prompts.
Projection into a shared space. Each encoder's output is projected by a learned linear layer into a common embedding space and normalised to unit length. For ViT-B/32 the shared embeddings have 512 dimensions; for ViT-L/14, 768.
Temperature. A learned scaling factor (often called the logit scale) sharpens the similarity scores before they're turned into probabilities.
| Model | Image encoder | Embedding size | Notes |
|---|---|---|---|
| CLIP RN50 | ResNet-50 (modified) | 1,024 | Smallest ResNet variant |
| CLIP RN50x64 | ResNet scaled up about 64× in compute | 1,024 | Largest ResNet; 18 days on 592 V100 GPUs to train |
| CLIP ViT-B/32 | Vision Transformer, 32-pixel patches | 512 | Popular default for fast embeddings |
| CLIP ViT-B/16 | Vision Transformer, 16-pixel patches | 512 | More accurate than B/32, slower |
| CLIP ViT-L/14 | Large Vision Transformer, 14-pixel patches | 768 | Best original model; 12 days on 256 V100 GPUs |
| CLIP ViT-L/14@336px | ViT-L/14 fine-tuned at 336-pixel resolution | 768 | Highest accuracy in the paper |
How CLIP Is Trained: Contrastive Learning
CLIP's training task is a matching game. Take a batch of N image-caption pairs. Encode all N images and all N captions, then compute the cosine similarity of every image with every caption, giving an N × N grid. The N correct pairs sit on the diagonal; everything else is a mismatch. The loss rewards high similarity on the diagonal and low similarity elsewhere, in both directions (each image should pick its own caption, and each caption its own image).
The paper's pseudo-code, slightly simplified:
I_e = l2_normalize(image_encoder(images) @ W_i) # N image embeddings
T_e = l2_normalize(text_encoder(texts) @ W_t) # N text embeddings
logits = (I_e @ T_e.T) * exp(t) # N x N scaled similarities
labels = arange(N) # correct pair for each row is on the diagonal
loss = (cross_entropy(logits, labels, axis=0) + cross_entropy(logits, labels, axis=1)) / 2Two details made it work at scale:
- Huge batches. CLIP used a minibatch size of 32,768, so each image had to be matched against tens of thousands of captions, which forces fine-grained distinctions.
- A huge, varied dataset. OpenAI built a dataset of 400 million image-text pairs collected from the internet, covering an enormous range of concepts.
Why contrastive learning instead of captioning?
The authors first tried training a model to generate each image's exact caption. It learned slowly: they report that a transformer captioning model learned 3× slower than a baseline that only predicted a bag of words from the caption, and switching to the contrastive objective improved efficiency another 4×. Predicting exact wording is hard and unnecessary; recognising which caption belongs with which image is enough to learn useful visual concepts.
OpenAI CLIP Zero-Shot Classification
The best-known capability of OpenAI CLIP is zero-shot classification: classifying images into categories without any training examples for those categories.
- Write each class as a text prompt, such as "a photo of a dog", "a photo of a cat", "a photo of a horse".
- Encode the prompts with the text encoder and the image with the image encoder.
- Compute the cosine similarity between the image and each prompt.
- Pick the prompt with the highest similarity, or turn the scaled similarities into probabilities with a softmax.
The paper reports that zero-shot CLIP matched the accuracy of the original ResNet-50 on ImageNet (76.2%) without using any of the 1.28 million labelled training examples that ResNet-50 learned from. Prompt wording matters: simply using "A photo of a {label}." instead of the bare label improved ImageNet accuracy by 1.3%, and averaging over many prompt templates helps further. Our zero shot learning guide explains the broader idea and other zero-shot methods.
Worked example: classifying one image
Suppose CLIP produces these cosine similarities between one image and three prompts, and the model's logit scale is 100 (a typical learned value):
| Prompt | Cosine similarity | Scaled logit (× 100) | Softmax probability |
|---|---|---|---|
| "a photo of a golden retriever" | 0.29 | 29 | about 88.1% |
| "a photo of a labrador" | 0.27 | 27 | about 11.9% |
| "a photo of a cat" | 0.20 | 20 | about 0.01% |
The raw similarities look close together (0.29 vs 0.27), but after scaling by the temperature, a gap of 0.02 becomes a gap of 2 in the logits, which the softmax turns into an 88% versus 12% split. That's why CLIP's probabilities are often very confident, and why they should be read as relative scores among the labels you supplied, not as calibrated certainty. If the true answer isn't among your prompts, CLIP will still pick one.
How Well Does CLIP Work? Benchmarks and Robustness
CLIP's headline numbers come from the original paper, evaluated across more than two dozen datasets:
- Prompt ensembling: averaging over 80 different prompt templates added another 3.5% on ImageNet compared with the single default prompt.
- Against supervised baselines: zero-shot CLIP beat a fully supervised linear classifier trained on ResNet-50 features on 16 of 27 datasets.
- Against few-shot learning: zero-shot CLIP matched the average performance of a 4-shot linear classifier trained on its own features.
Its most striking result was robustness. Models trained on ImageNet often collapse on images drawn differently from ImageNet's photos. The paper compared a ResNet-101 trained on ImageNet with zero-shot CLIP at the same 76.2% ImageNet accuracy:
| Test set | ImageNet-trained ResNet-101 | Zero-shot CLIP |
|---|---|---|
| ImageNet | 76.2% | 76.2% |
| ImageNetV2 (new photos, same process) | 64.3% | 70.1% |
| ImageNet Sketch (drawings) | 25.2% | 60.2% |
| ImageNet-R (renditions such as art and cartoons) | 37.7% | 88.9% |
| ObjectNet (unusual poses and backgrounds) | 32.6% | 72.3% |
| ImageNet-A (naturally hard examples) | 2.7% | 77.1% |
The authors report that zero-shot CLIP reduces this "robustness gap" by up to 75%. Learning from varied internet images and captions, rather than one curated label set, made CLIP's features far less tied to one kind of photograph.
CLIP Embeddings
CLIP embeddings are the vectors CLIP produces for images and text. Because both live in the same space, you can compare anything with anything: image to text, text to image, image to image, or text to text.
Typical properties:
- Fixed size: 512 or 768 numbers for the common models, regardless of image size or text length.
- Normalised: CLIP's projections are normalised to unit length, so cosine similarity equals the dot product.
- Semantic: images of the same concept land near each other even if they look different, and near text that describes them.
That makes CLIP embeddings useful for search and organisation:
- Text-to-image search: embed every image in a collection once, store the vectors in a vector database, then embed a text query and return the nearest images.
- Image-to-image search and deduplication: find visually or semantically similar photos.
- Clustering and tagging: group large photo libraries by content, or tag them by comparing with label prompts.
- Filtering: keep only images whose similarity to a description is above a threshold.
Our embeddings guide covers how vector similarity search works and how to store embeddings at scale.
Using CLIP in Python
The Hugging Face Transformers library includes the original OpenAI CLIP checkpoints. Zero-shot classification:
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")
image = Image.open("pet.jpg")
labels = ["a photo of a dog", "a photo of a cat", "a photo of a horse"]
inputs = processor(text=labels, images=image, return_tensors="pt", padding=True)
outputs = model(**inputs)
probs = outputs.logits_per_image.softmax(dim=1) # probability for each label
print(dict(zip(labels, probs[0].tolist())))Getting embeddings for search:
import torch
with torch.no_grad():
img_emb = model.get_image_features(**processor(images=image, return_tensors="pt"))
txt_emb = model.get_text_features(**processor(text=["a dog on a beach"], return_tensors="pt", padding=True))
img_emb = img_emb / img_emb.norm(dim=-1, keepdim=True) # normalise before comparing
txt_emb = txt_emb / txt_emb.norm(dim=-1, keepdim=True)
similarity = (img_emb @ txt_emb.T).item() # cosine similarityFor production search, embed your images in batches on a GPU, store the vectors, and only embed the query text at search time.
Linear Probes and Fine-Tuning
Zero-shot use is only one option. When you have labelled examples, two approaches usually beat it:
- Linear probe: freeze CLIP's image encoder, extract embeddings for your labelled images, and train a simple classifier such as logistic regression on top. It's fast, cheap and needs little data. In the paper, linear probes on CLIP's features outperformed the best ImageNet model of the time, Noisy Student EfficientNet-L2, on 21 of 27 datasets.
- Fine-tuning: update some or all of CLIP's weights on your task. It can raise accuracy further, but it can also erode CLIP's robustness to unusual inputs, so test on images that differ from your training set. Techniques that interpolate between the original and fine-tuned weights are a common way to keep both.
A practical path: start zero-shot to see whether CLIP understands your domain at all, move to a linear probe once you have a few hundred labelled images, and fine-tune only if that isn't enough.
What CLIP Is Used For
| Application | How CLIP is used | Examples |
|---|---|---|
| Zero-shot image classification | Compare images with text labels | Sorting photos, quick prototypes without labelled data |
| Image and video search | Text and image embeddings in a vector database | Photo library search, stock image search |
| Text-to-image generation | CLIP's text encoder turns prompts into conditioning | Stable Diffusion 1.x used CLIP ViT-L/14's text encoder; DALL-E 2 was built around CLIP embeddings |
| Vision language models | CLIP's image encoder supplies visual features to a language model | Early open VLMs such as LLaVA used a CLIP ViT-L/14 vision encoder |
| Dataset curation | Filter web image-text pairs by CLIP similarity | Open datasets such as LAION were filtered using CLIP scores |
| Evaluation | Score how well generated images match their prompts | The CLIPScore metric |
| Content moderation and safety | Compare images with descriptions of unwanted content | Flagging images for human review |
| Robotics and open-vocabulary detection | Match detected regions or scenes with text | Detecting objects named in free text |
CLIP in Stable Diffusion and ComfyUI
If you use image generation tools, you've used CLIP without noticing. In Stable Diffusion 1.x, a CLIP text encoder turns your prompt into the embeddings that guide the image. In ComfyUI, the "CLIP" output of a checkpoint loader is that text encoder, and the "CLIP Text Encode" node converts your prompt into conditioning for the sampler. The community setting "CLIP skip" uses an earlier layer of the text encoder, which some models were trained with. Later image models swapped in other or additional text encoders, such as OpenCLIP models or large language model encoders, but the role is the same: translating words into something the image model understands.
OpenAI CLIP vs SigLIP and Other Successors
OpenAI released its CLIP weights and code but not its 400-million-pair dataset, which inspired open and improved successors. OpenAI CLIP vs SigLIP is the comparison most developers face today.
| Model | Developer | Key change | Why it matters |
|---|---|---|---|
| CLIP | OpenAI (2021) | Contrastive softmax loss on 400M private image-text pairs | The original; still widely used and supported everywhere |
| OpenCLIP | LAION and academic collaborators | Open-source training code; models trained on open datasets such as LAION-2B | Reproducible, larger models with open data |
| MetaCLIP | Meta (2023) | Recreated CLIP's data curation from public sources | Showed data curation, not just model size, drives quality |
| EVA-CLIP | BAAI | Improved training recipes and initialisation | Strong accuracy for the compute used |
| SigLIP | Google (2023) | Replaces the batch-wide softmax with a pairwise sigmoid loss | Works well with smaller batches and scales efficiently; popular as a VLM vision encoder |
| SigLIP 2 | Google (2025) | Adds captioning and self-supervised objectives, better localisation and multilingual support | A common default vision encoder in newer open models |
The practical difference between OpenAI CLIP and SigLIP: CLIP's softmax loss compares each image with every caption in the batch at once, so it benefits from enormous batches. SigLIP treats each image-caption pair as an independent yes-or-no question with a sigmoid loss, which removes the need for batch-wide normalisation, trains efficiently at more modest batch sizes and tends to perform better at the same compute. For new projects, SigLIP-family models are often the better default; OpenAI CLIP remains the most widely supported baseline, and many existing tools depend on it.
Why CLIP Mattered: A Short History
Before CLIP, most vision models were trained to predict a fixed list of categories, such as ImageNet's 1,000 classes, and had to be retrained to recognise anything new. Researchers had tried learning from text before: the CLIP paper builds on work such as VirTex, which learned visual features by generating captions, and ConVIRT, which applied contrastive image-text learning to medical images. What CLIP changed was scale and simplicity: a plain contrastive objective, a much larger and more varied dataset, and evaluation that showed the result transferred to dozens of tasks without retraining.
Google published a similar dual-encoder model, ALIGN, shortly afterwards, trained on a larger but noisier set of image-text pairs, which reinforced the lesson that scale could compensate for messy data. From there, CLIP-style encoders became standard parts of text-to-image generators, multimodal search and the vision side of vision language models.
How to Choose a CLIP Model
- Speed vs accuracy: ViT-B/32 is fast and fine for search over large collections; ViT-L/14 and larger OpenCLIP or SigLIP models are more accurate but slower and heavier.
- Compatibility: if a tool or pipeline was built on a specific CLIP model, keep that model; embeddings from different models can't be mixed.
- Language: the original CLIP was trained mostly on English text; for other languages, choose a multilingual model such as SigLIP 2 or a multilingual CLIP variant.
- Licence and data: check model licences, and prefer models trained on documented data if provenance matters to you.
- Resolution and fine detail: higher input resolutions (such as 336 pixels) help with small objects and text in images.
- Your own test: run a few hundred of your real images through two or three candidates and compare results before committing.
Limitations and Biases
The CLIP paper is unusually candid about weaknesses:
- Systematic and abstract tasks. CLIP struggles with counting objects and other systematic tasks, and its zero-shot performance on some specialised datasets is weak.
- Out-of-distribution data. It reached only 88% accuracy on handwritten MNIST digits, which simple models handle easily, because such images were rare in its training data.
- Fine-grained categories. Telling apart similar car models, aircraft variants or flower species can be hard, though performance varies widely by dataset.
- Typographic attacks. OpenAI's follow-up research on CLIP's "multimodal neurons" showed that writing a word on an object can override the image: a printed label can make CLIP misread what it sees.
- Social bias. Trained on internet data, CLIP inherits stereotypes; the paper documents biased associations in classification experiments involving people.
- Short text. The text encoder sees at most 76 tokens plus start and end markers, so long descriptions are truncated.
- No generation. CLIP scores and embeds; it doesn't write captions or answer questions by itself. Vision language models add a language model on top for that; our vision language model guide explains how they build on encoders like CLIP.
Common Mistakes When Using CLIP
- Using bare labels as prompts instead of templates like "a photo of a {label}".
- Forgetting to normalise embeddings before comparing them, when a library doesn't do it for you.
- Treating softmax outputs as calibrated confidence; they only rank the labels you provided.
- Mixing embeddings from different CLIP models, which live in different spaces and can't be compared.
- Relying on CLIP alone for safety-critical decisions, given typographic attacks and bias.
FAQ
What does CLIP stand for?
Contrastive Language-Image Pre-training. "Contrastive" refers to the training method of pulling matching image-text pairs together and pushing mismatched pairs apart.
Is CLIP open source?
OpenAI released CLIP's model weights and code, but not its training dataset. Fully open alternatives such as OpenCLIP provide training code and models trained on public datasets.
What is CLIP used for?
Zero-shot image classification, image and video search, filtering and curating datasets, scoring generated images, guiding text-to-image models, and supplying visual features to vision language models.
What is the difference between CLIP and SigLIP?
Both learn a shared image-text space. CLIP uses a contrastive softmax loss over the whole batch; SigLIP uses a pairwise sigmoid loss, which trains efficiently with smaller batches and often performs better for the same compute.
Can CLIP describe an image in words?
Not by itself. CLIP can score how well given text matches an image, but it can't generate new text. Captioning and visual question answering need a vision language model, which often uses a CLIP-like encoder inside.