- Introduced by
- Radford, A.; Kim, J. W.; et al. (OpenAI)
- Year
- 2021
- Type
- Contrastive vision-language pretraining model
What does it do?
CLIP (Contrastive Language-Image Pretraining) is a vision-language model introduced by Radford et al. at OpenAI in 2021.
It learns aligned image and text representations by training an image encoder and a text encoder on 400 million image-text pairs with a contrastive objective. Because class names can be written as text at inference time, the trained model can classify images into categories it was never explicitly trained on, without fine-tuning.
The intuition behind the method
Imagine showing a child millions of photos each accompanied by a caption. Over time the child learns which visual concepts match which words, purely from co-occurrence. CLIP replicates this idea at scale: two neural networks — one for images, one for text — are trained simultaneously so that the representation of an image and the representation of its matching caption end up very close together in a shared vector space, while mismatched pairs are pushed far apart. Once trained, you can classify any image by encoding it and checking which text label (e.g., 'a photo of a cat') is closest in that space — no labelled training examples needed for the new task.
History
CLIP was introduced by Alec Radford, Jong Wook Kim and colleagues at OpenAI and presented at ICML 2021. It builds on earlier work in contrastive self-supervised learning (SimCLR, MoCo) and on vision-language grounding (ViLBERT). Its central finding is that contrastive pretraining on image-text pairs collected from the web can yield visual representations that transfer to new tasks without task-specific labels. Follow-on work named in this entry includes ALIGN (Google, 2021), Florence (Microsoft, 2021) and open-source implementations such as OpenCLIP. DALL-E 2 uses CLIP embeddings as its semantic target for image generation, and Stable Diffusion conditions on the outputs of the CLIP text encoder.
When to use it
Choose CLIP when labelled training data for the target task are scarce or unavailable, when the set of classes may change after deployment (open-vocabulary recognition), or when one pretrained backbone is wanted for several tasks such as image classification, image-text retrieval or visual question answering. It requires a pretrained CLIP checkpoint and class names that can be expressed as natural-language phrases. Do not rely on zero-shot CLIP when a sizeable labelled set from the target distribution is available; supervised fine-tuning on that data is usually the stronger option. The method is also not designed for dense prediction tasks such as detection or segmentation without additional adaptation.
Limitations and considerations
- Zero-shot accuracy generally trails task-specific supervised fine-tuning when labelled data for the target domain are available.
- Pretraining requires large-scale compute and a curated set of 400 million image-text pairs, so training a comparable model from scratch is rarely practical for most groups.
- It inherits biases present in web-scale training data, which can appear as demographic and cultural bias in its predictions.
- It tends to struggle with tasks that are underrepresented in natural captions, such as counting objects, reading text and spatial reasoning.
- Results are sensitive to the wording of class prompts, so differences in accuracy between deployments can reflect phrasing choices rather than the model itself.
Source conditions do not replace independent scientific review or validation by an analysis engine.
Strengths
- Zero-shot transfer: a new image classification task can be attempted with no labelled examples, only class names written as text.
- Open-vocabulary recognition: the class set can be specified or changed at inference time in natural language, without retraining the model.
- Training on diverse web-collected images and captions, rather than a fixed label set, is the stated basis for its improved robustness to distribution shift compared with ImageNet-supervised models.
- The image and text encoders can be reused as feature extractors for retrieval, ranking and other multimodal tasks.
- Performance is reported to improve with larger models and more training data, so scaling behaviour is a practical consideration when choosing a checkpoint.
Applications
- Zero-shot image classification across diverse and open-ended category sets.
- Image-text retrieval: ranking images by semantic similarity to a query sentence and vice versa.
- Visual feature extraction as a backbone for multimodal downstream tasks (visual question answering, image captioning).
- Semantic image search and content moderation in large-scale media libraries.
- Conditioning and guiding image generation models (DALL-E 2, Stable Diffusion) using CLIP embeddings.
How it works
How it works
Each image in a minibatch is passed through an image encoder, either a Vision Transformer (ViT) or a modified ResNet. The output is divided by its L2 norm so that it lies on the unit hypersphere, giving the image embedding v_i.
Formula
\mathbf{v}_i = f_\theta(\mathbf{x}_i) / \|f_\theta(\mathbf{x}_i)\|Each paired caption is tokenised and passed through a Transformer-based text encoder. Its output is likewise L2-normalised to give the text embedding u_i. The two encoders have separate parameters, but their outputs must share the same dimensionality so that they can be compared by a dot product.
Formula
\mathbf{u}_i = g_\phi(\mathbf{t}_i) / \|g_\phi(\mathbf{t}_i)\|For a minibatch of N image-text pairs, the method forms an N×N matrix S whose entry S_ij is the temperature-scaled dot product of image i and text j. Because the embeddings are normalised, the dot product is a cosine similarity, which the factor τ then scales. The diagonal entries are the N matched pairs and all off-diagonal entries are mismatched pairs. Since S_ij = τ·v_i^T u_j is scaled by τ and is generally not symmetric, S is not a pure symmetric cosine matrix. In the original work τ is learned during training, and its value controls how sharply the softmax in the loss concentrates on the best-scoring match.
Formula
S_{ij} = \tau \cdot \mathbf{v}_i^\top \mathbf{u}_jTwo cross-entropy terms are summed. The first applies a softmax across each row of S, so each image must identify its own caption among the N texts. The second applies a softmax down each column, so each text must identify its own image. Minimising this loss raises the scores of matched pairs relative to mismatched pairs in both directions, which pulls the two encoders into a shared representation space.
Formula
\mathcal{L} = -\frac{1}{N}\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]At inference time, each candidate class is written as a natural-language prompt, such as 'a photo of a {class}', and encoded by the text encoder. The query image is encoded by the image encoder, and the predicted class is the one whose text embedding has the highest cosine similarity with the image embedding. No gradient update or labelled example for the new task is needed.
Formula
\hat{y} = \arg\max_{c}\; \mathbf{v}^\top \frac{g_\phi(\text{\"a photo of a }{c}\text{\"})}{\|g_\phi(\text{\"a photo of a }{c}\text{\"})\|}Common pitfalls
- Using a bare class name as the text prompt instead of a descriptive template such as 'a photo of a {class}'. Template-based prompts usually perform better, so prompt choice should be compared as part of any evaluation.
- Evaluating zero-shot CLIP on benchmark images that may appear in its web training data and reading the score as a clean zero-shot result. Overlap between pretraining data and test sets should be checked where possible.
- Applying CLIP to specialised imagery such as satellite or medical images without domain-specific validation, and assuming zero-shot accuracy will be competitive.
- Ignoring the temperature τ when fine-tuning on a new dataset, since τ controls how sharply the loss separates matched from mismatched pairs.
- Treating cosine-similarity scores or softmax outputs as calibrated probabilities. Their absolute values depend on the temperature and the prompt set, so calibration should be checked on held-out data.
Frequently asked questions
How does CLIP classify images if it was never shown the target classes during training?
CLIP's contrastive objective aligns image and text representations in a shared space. At inference time, each candidate class label is converted into a natural-language prompt and encoded by the text encoder. The image is encoded by the image encoder, and the class whose text embedding has the highest cosine similarity to the image embedding is selected. Because the encoders learned general visual-semantic associations from 400 million diverse pairs, this generalises to unseen classes described in natural language.
What is prompt engineering in the context of CLIP, and why does it matter?
Prompt engineering refers to the choice of text template used to encode class names, for example 'a photo of a {class}' versus simply '{class}'. Radford et al. report that contextual templates improve zero-shot accuracy over bare class names, and that ensembling several templates can improve it further. The size of the gain depends on the dataset and should be measured on the target task. The sensitivity to wording reflects that the text encoder was trained on naturally occurring sentences, not isolated nouns.
Is CLIP a generative model?
No. CLIP is a discriminative contrastive model that produces matched image and text embeddings; it does not generate images or text. However, CLIP embeddings have been used to guide generative models such as DALL-E 2, which uses CLIP's embedding space as the semantic target for a diffusion-based image decoder.
When should I fine-tune CLIP rather than use it zero-shot?
Zero-shot CLIP is competitive when labelled data are absent or when the task closely resembles the diversity of web images and captions. Fine-tuning (either the full model or a linear probe) is recommended when labelled data are available for the target domain, especially for fine-grained or domain-specific tasks such as medical imaging, satellite imagery, or product recognition, where zero-shot accuracy can lag significantly behind supervised alternatives.
Related methods
Sources
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. Proceedings of the 38th International Conference on Machine Learning, PMLR 139, 8748–8763.
Open publication referenceRadford, A., et al. (2021). Learning Transferable Visual Models From Natural Language Supervision. arXiv:2103.00020.
Open publication referenceGoodfellow, I., Bengio, Y., & Courville, A. (2016). Deep Learning. MIT Press.
ISBN: 978-0-262-03561-3