CLIP: How Contrastive Language–Image Pre-training Enables Powerful Zero-Shot Vision
From the publisher’s feed, collected in the ZeroLabs newsroom.
Paper-explained series 8CLIP trains an image encoder and a text encoder jointly on large (image, text) pairs to predict correct pairings, enabling the text encoder to synthesize powerful zero-shot linear classifiers without task-specific training.TL;DRCLIP demonstrates that predicting which caption goes with which image is a scalable way to learn state-of-the-art image representations from scratch on a dataset of 400 million (image, text) pairs. This approach is highly impactful because it enables zero-shot transfer across over 30 different computer vision datasets. The headline results show that CLIP matches the zero-shot accuracy of the original ResNet-50 on ImageNet without needing to use any of the 1.28 million training examples it was trained on. Furthermore, zero-shot transfer performance scales smoothly as a predictable function of model compute.Motivation & ContextState-of-the-art computer vision systems are traditionally trained to predict a fixed set of predetermined object categories. This restricted form of supervision limits their generality, as additional labeled data is needed to specify any other visual concept. Prior works have explored learning from natural language and metadata. For instance, Mori et al. (1999) explored training a model to predict nouns and adjectives in text documents paired with images. Joulin et al. (2016) used YFCC100M metadata for bag-of-words classification, and Li et al. (2017) predicted phrase n-grams. More recently, models like VirTex, ICMLM, and ConVIRT demonstrated the potential of masked language modeling and contrastive objectives to learn image representations.Learning from natural language is attractive due to scale and expressivity. It does not require annotations to be in a classic “machine learning compatible format” , meaning models can learn passively from the vast amount of text on the internet. Furthermore, it connects the representation to language, enabling flexible zero-shot transfer. This raises the central question for CLIP: Could scalable pre-training methods which learn directly from web text result in a similar breakthrough in computer vision as seen in natural language processing?High-level Summary of CLIPCLIP jointly trains an image encoder and a text encoder to predict the correct pairings of a batch of (image, text) training examples. It does this by learning a multi-modal embedding space where it maximizes the cosine similarity of the image and text embeddings for the real pairs in the batch, while minimizing the cosine similarity for the incorrect pairings.Pseudocode for CLIP Core Algorithm:# extract feature representations of each modalityI_f = image_encoder(I) T_f = text_encoder(T) # joint multimodal embeddingI_e = l2_normalize(np.dot(I_f, W_i), axis=1)T_e = l2_normalize(np.dot(T_f, W_t), axis=1)# scaled pairwise cosine similaritieslogits = np.dot(I_e, T_e.T) * np.exp(t)# symmetric loss functionloss = (cross_entropy_loss(logits, labels, axis=0) + cross_entropy_loss(logits, labels, axis=1)) / 2Detailed Walk through1. Dataset construction — WIT (WebImageText)CLIP was trained on a newly constructed dataset of 400 million image–text pairs called WebImageText (WIT), built from publicly available internet data. Instead of randomly scraping captions, the authors first created a structured list of 500,000 base queries representing objects, actions, attributes, proper nouns, and abstract concepts. They then collected image–text pairs where the accompanying text contained at least one of these queries. This approach ensured broad semantic coverage across diverse concepts rather than relying on narrow, manually labeled categories like those found in datasets such as MS-COCO or Visual Genome, which contain only around 100,000 training images each. Even large-scale resources like YFCC100M shrink significantly after filtering for usable English text, making them far smaller than what CLIP required.To prevent the dataset from reflecting the internet’s extreme popularity bias, CLIP enforced a maximum of 20,000 image–text pairs per query. Web data follows a heavy-tailed distribution, where a few concepts appear overwhelmingly often while most remain rare. Without this cap, dominant topics would flood the dataset and weaken long-tail representation. By limiting over represented queries and ensuring wide concept diversity, CLIP effectively trained on a balanced projection of the internet’s semantic space — a design decision that proved critical for its strong zero-shot generalization across a wide range of tasks.2. Model architectureCLIP does not:Predict captions (like traditional image captioning)Predict labels (like ImageNet classification)Reconstruct textInstead, it solves a simpler but powerful problem:Given a batch of images and a batch of texts, match each image to the correct text.Let’s dive deeper :-Step 1: Start With a Batch of N PairsSuppose your training batch contains: N (image, text) pairsExample with N=4:Image: I_1, I_2, I_3, I_4Text: T_1, T_2, T_3, T_4Each I_k matches exactly one T_k.Step 2: Encode Images and TextsCLIP uses:image encoder → produces image embeddingsImage encoders: CLIP evaluates two different architectures: ResNet-50 and Vision Transformer (ViT). The ResNet utilizes ResNet-D improvements and replaces the global average pooling layer with an attention pooling mechanism. The ViT closely follows the original implementation but adds an additional layer normalization to the combined patch and position embeddings.text encoder → produces text embeddingsText encoder: The text encoder is a Transformer. The base size is a 63 million parameter, 12-layer, 512-wide model with 8 attention heads. It operates on a lower-cased byte pair encoding (BPE) representation with a 49,152 vocab size. The sequence is bracketed with [SOS] and [EOS] tokens, and the activations of the highest layer at the [EOS] token are treated as the feature representation. It utilizes masked self-attention.For each pair:v_i = ImageEncoder(I_i)t_i = TextEncoder(T_i)Note: Each embedding is a vector in the same embedding space.Step 3: Create All N × N Similarity ScoresNow we compute cosine similarities between:Every image embeddingEvery text embeddingThis produces an N×N matrix:S_ij=cos(v_i,t_j)So for each image v_i, we compute similarity with: t_1,t_2,t_3,…,t_NWhere:The diagonal entries (s₁₁, s₂₂, s₃₃, s₄₄) are correct pairs.All others are incorrect pairings.There are:N correct matchesN² — N incorrect matchesAlthough CLIP compares each batch’s N images against N² possible image–text pairings, it does not suffer from class imbalance between positive and negative pairs because the problem is formulated as multiclass classification, not binary classification. For each image, the model predicts the correct caption among N candidates using a softmax over similarity scores, meaning there is exactly one correct class and N−1 alternatives. This symmetric cross-entropy formulation inherently normalizes the contribution of positives and negatives, so the large number of mismatched pairs does not overwhelm training. Instead, the many “negatives” actually strengthen representation learning by providing richer contrastive signal within each batch, especially at the very large batch sizes used in CLIP.Step 4: Turn Matching Into a Classification ProblemInstead of manually pushing embeddings together/apart with triplet loss, CLIP reframes matching as classification.For each image I_i: Among all N texts, which one is the correct match?That becomes an N-way classification problem.We apply softmax over each row:Where:τ is a learnable temperature parameter.It controls how sharp the similarity distribution is.Then we use cross-entropy loss to make sure I_i assigns highest probability to T_i.Step 5: Symmetric Objective (Bidirectional)CLIP does something powerful:It doesn’t only ask: “Given image, predict correct text.”It also asks: “Given text, predict correct image.”So it computes cross-entropy loss twice:Image → Text (row-wise softmax)Text → Image (column-wise softmax)Final loss:This symmetry improves alignment quality.Step 6: What Is Being Maximized and Minimized?The objective does two things simultaneously:Maximize similarity: Between real pairs (v_i, t_i)Minimize similarity: Between incorrect pairs (v_i, t_j) where i≠jStep 7: Why This Works So WellThis loss is extremely efficient because:Every other example in the batch becomes a negative sample.With batch size N = 32,768 (as in CLIP), each example gets 32,767 negatives.No need for memory banks or complex sampling strategies.This large-batch contrastive setup dramatically improves representation learning.To put it bluntly, During training:Randomly sample 32,768 pairs.Send them to GPUs.Compute embeddings.Compute contrastive loss.Update parameters.Repeat with a new random batch.The next batch will be a different random 32K subset.Over 32 epochs, the model eventually sees nearly the entire dataset many times.When we say language is “infinite,” it can sound puzzling that CLIP only compares 32,768 text candidates at a time. The key is that CLIP does not train against the space of all possible sentences — it trains on a fixed dataset of 400 million image–text pairs. At each optimization step, the model simply samples a minibatch of 32,768 aligned pairs from this dataset. It then computes a 32,768 × 32,768 similarity matrix and learns to identify the correct image–text matches within that batch. Over many iterations and epochs, the model is exposed to a vast variety of captions, gradually shaping a shared embedding space. It never needs to enumerate “all possible descriptions” of an image; it only needs enough diverse examples to learn consistent semantic alignment.The large batch size is not about covering infinite language — it is about maximizing contrastive signal. With a batch of 32,768, each image is effectively contrasted against 32,767 mismatched captions in the same step. These serve as strong, diverse negative examples, improving the quality and stability of representation learning. Over time, repeated random sampling across the 400M dataset acts as a stochastic approximation of the full data distribution. In other words, CLIP does not compare an image with every possible caption; it learns a geometry where related images and texts naturally cluster together, enabling zero-shot classification over any finite set of prompts at inference time.3. Geometric InterpretationAfter training:Images and corresponding texts lie close in a shared embedding space.The space becomes semantically structured.Example:The embedding for “a red sports car” will be:Near red sports car imagesNear similar phrasesBut far from unrelated concepts like “snowy mountain”This shared space is what enables zero-shot classification.4. Training recipe & practical detailsThe models were trained using the Adam optimizer with decoupled weight decay regularization. A very large minibatch size of 32,768 was used. To save memory and accelerate training, mixed-precision and gradient checkpointing were utilized. The temperature parameter τ is directly optimized during training as a log-parameterized multiplicative scalar. Models were trained for 32 epochs. The largest ResNet model (RN50x64) took 18 days to train on 592 V100 GPUs, while the largest ViT took 12 days on 256 V100 GPUs. The highest performing model, ViT-L/14@336px, was pre-trained at a higher 336 pixel resolution for one additional epoch.How CLIP is Used — Zero-Shot ClassificationCLIP performs zero-shot classification by treating the text encoder as a hypernetwork that generates the weights of a linear classifier based on text specifying the visual concepts. For each dataset, the names of all the classes are embedded. The cosine similarity between the image embedding and text embeddings is calculated, scaled by a temperature parameter, and normalized via a softmax into a probability distribution.One of the most surprising findings in the CLIP paper is that zero-shot performance depends heavily on how we phrase class labels. Instead of feeding the text encoder a raw label like “dog” or “car,” the authors wrap each class name inside a natural language template such as:“A photo of a {label}.”This seemingly small change significantly improves accuracy. The reason is subtle but important: during pre-training, CLIP mostly sees full sentences paired with images, not isolated single words. Feeding it just “dog” creates a distribution mismatch between training and inference. By embedding class names inside natural-sounding phrases, we better align zero-shot evaluation with the data distribution the model was trained on. Even this single prompt template boosts ImageNet zero-shot accuracy by over one percentage point.The authors push this idea further with prompt ensembling. Instead of using one template, they generate many variations — for example, “A photo of a small {label},” “A blurry photo of a {label},” or “A close-up photo of a {label}.” Each variation produces a slightly different text embedding. Rather than selecting one, they average these embeddings in the shared representation space to create a more robust classifier weight for that class. This process reduces sensitivity to wording and captures a richer semantic description of each concept. Remarkably, ensembling across dozens of prompts improves performance by several additional percentage points — without retraining the model. In CLIP, language literally generates the classifier, so the way we phrase a concept directly shapes how well the model recognizes it.7. Experiments & Key ResultsEvaluation Suite: CLIP was benchmarked on over 30 existing computer vision datasets spanning tasks such as OCR, action recognition in videos, geo-localization, and fine-grained object classification.Zero-Shot ImageNet: Zero-shot CLIP matches the accuracy of the original ResNet-50 on ImageNet (76.2%) without using any labeled training data. It also boasts a 95% top-5 accuracy, matching Inception-V4.Scaling Behaviour: The average zero-shot error is well modeled by a log-log linear trend across a 44x range of compute spanning 5 different CLIP models.Representation Learning: Fitting a linear classifier on CLIP’s representations outperforms using the Noisy Student EfficientNet-L2 on 21 out of 27 datasets. Furthermore, CLIP vision transformers are about 3x more compute efficient than CLIP ResNets. Top wins include OCR (SST2, HatefulMemes), geo-localization (Country211, SUN397), and video activity recognition (Kinetics700, UCF101).Zero-Shot vs Few-Shot: Zero-shot CLIP roughly matches the performance of a 4-shot logistic regression classifier trained on the same feature space. On ImageNet, it matches a 16-shot linear classifier. The estimated effective data efficiency of zero-shot transfer averages 20.8 examples per class.Robustness: Zero-shot CLIP models are much more robust to distribution shifts than standard ImageNet models. They reduce the size of the gap between ImageNet accuracy and accuracy under distribution shift by up to 75%.8. Analysis & InterpretationCLIP excels in areas with wide concept coverage. For instance, it significantly outperforms a ResNet-50 on video action recognition tasks (Kinetics700 and UCF101) because natural language provides wider supervision for visual concepts involving verbs. It also improves the most on tasks requiring OCR and geo-localization.However, there are notable limitations. Zero-shot CLIP is quite weak on several specialized, complex, or abstract tasks such as satellite image classification (EuroSAT and RESISC45), lymph node tumor detection (PatchCamelyon), and counting objects in synthetic scenes (CLEVRCounts). It is also sensitive to truly out-of-distribution data; for example, on handwritten MNIST digits, a simple baseline of logistic regression on raw pixels outperforms zero-shot CLIP. Additionally, because the image-text pairs are unfiltered and uncurated, CLIP models learn many social biases. Lack of scale-based data augmentation also slightly hurts its performance on low-resolution datasets like CIFAR10.Link to original paper: https://arxiv.org/abs/2103.00020Huge kudos to Alec Radford and the entire OpenAI team for this incredible milestone! Proving that a model can match the performance of a fully supervised ResNet-50 on ImageNet without ever seeing a single crowd-sourced label is a paradigm shift. Thank you for championing a more scalable, expressive, and adaptable approach to multi-modal AI!Next time we will talk about SigLIP, CLIP 2, SigLIP 2, … Brace yourself 🙃Until next time folks…El Psy CongrooCLIP: How Contrastive Language–Image Pre-training Enables Powerful Zero-Shot Vision was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.