Skip to main content
illumin8
Courses
Week 3: Contrastive Vision–Language Learning (CLIP)
Physical AI
01Week 1: Modern Vision Backbones
02Week 2: Self-Supervised Representation Learning for Vision
03Week 3: Contrastive Vision–Language Learning (CLIP)
04Week 4: Beyond CLIP — Captioning and Grounding
05Week 5: BLIP, BLIP-2, and Related Models
06Week 6: LLaVA and Multimodal Instruction Tuning
07Week 7: Alternative VLM Architectures
08Week 8: Fine-Tuning and Parameter-Efficient Methods
09Week 9: Evaluation and Robustness
10Week 10: ControlNet and Controlled Generation
11Week 11: Multimodal Agents and Tool Use
12Week 12: Vision-Language Models for Robotics
13Week 13: Bias, Fairness, and Safety in VLMs
14Week 14: Vision-Language Capstone
Week 3

Week 3: Contrastive Vision–Language Learning (CLIP)

✦Learning Outcomes
  • Compare dual-encoder vs. fusion architectures for vision-language tasks
  • Analyze CLIP's zero-shot capabilities and limitations
  • Apply CLIP embeddings for image-text retrieval and classification
◆Prerequisites
  • Week 2: Representation Learning - Contrastive learning fundamentals
  • Understanding of ViT architecture from Week 1

Purpose of this lecture

Before 2021, the dominant paradigm in computer vision was modular and rigidly supervised: researchers manually labeled images into a fixed ontology (e.g., 1,000 ImageNet classes) and trained a model to classify inputs exclusively into those buckets. This produced strong discriminative models that were entirely blind to the richness of natural language. If a model was trained to recognize "dog," it had no inherent understanding of the phrases "a brown puppy," "canine," or "playing fetch."

CLIP (Contrastive Language–Image Pretraining; Radford et al., 2021) shattered this paradigm. By replacing human-annotated class labels with noisy, web-scraped natural language captions, CLIP solved the image-language alignment problem at internet scale. It established a joint embedding space where images and text coexist mathematically, enabling zero-shot generalization to entirely new visual concepts without any task-specific fine-tuning. Just as ImageNet became the universal starting point for traditional vision, CLIP pretraining became the universal starting point for modern multimodal AI.

This lecture rigorously derives the CLIP architecture, its symmetric contrastive objective, how zero-shot classification mathematically emerges from vector similarity, and the structural limitations that motivated all subsequent Vision-Language Models (VLMs).


Architecture: Dual encoders and the joint space

Unlike standard VLMs that fuse vision and text early via cross-attention, CLIP uses a strict dual-encoder architecture. It processes images and text entirely independently, only bringing their representations together at the very end via a dot product.

  1. Image Encoder (fθf_\thetafθ​): A Vision Transformer (ViT-B/32, ViT-L/14, etc.) or a ResNet processes the image xxx. The global image representation is extracted from the final layer (typically the [CLS] token for ViT or an attention-pooled feature map for ResNet). This output is linearly projected to a joint dimension ddd (e.g., d=512d=512d=512).
  2. Text Encoder (gϕg_\phigϕ​): A standard transformer processes the text sequence ttt. The original CLIP uses a GPT-style (causal) architecture with masked self-attention. The text is tokenized (using Byte Pair Encoding), capped at a maximum sequence length of 76 tokens, and appended with an [EOS] (End of Sequence) token. The final layer's hidden state corresponding to the [EOS] token is extracted, representing the aggregated context of the entire sentence. This is also linearly projected to dimension ddd.

Both resulting vectors are strictly L2L_2L2​-normalized to project them onto the surface of a unit hypersphere:

z^x=fθ(x)∥fθ(x)∥2,z^t=gϕ(t)∥gϕ(t)∥2\hat{z}_x = \frac{f_\theta(x)}{\|f_\theta(x)\|_2}, \quad \hat{z}_t = \frac{g_\phi(t)}{\|g_\phi(t)\|_2}z^x​=∥fθ​(x)∥2​fθ​(x)​,z^t​=∥gϕ​(t)∥2​gϕ​(t)​

Because they are normalized, their dot product directly computes the cosine similarity between the image and the text:

sim(x,t)=z^x⋅z^t∈[−1,1]\text{sim}(x, t) = \hat{z}_x \cdot \hat{z}_t \in [-1, 1]sim(x,t)=z^x​⋅z^t​∈[−1,1]

This dual-encoder separation is highly computationally efficient at inference time. Text embeddings for a million concepts can be pre-computed and cached offline, allowing new images to be matched against them via a fast matrix multiplication.


The Symmetric InfoNCE Objective

The training procedure requires aligning these modalities so that a picture of a dog and the phrase "a photo of a dog" point to the exact same geometric region on the hypersphere.

Given a batch of NNN image-text pairs {(xi,ti)}i=1N\{(x_i, t_i)\}_{i=1}^N{(xi​,ti​)}i=1N​, we pass all images through the vision encoder and all texts through the text encoder to obtain NNN image embeddings and NNN text embeddings.

We then compute an N×NN \times NN×N similarity matrix SSS, where each entry Si,jS_{i,j}Si,j​ represents the scaled cosine similarity between the iii-th image and the jjj-th text:

Si,j=z^xi⋅z^tjτS_{i,j} = \frac{\hat{z}_{x_i} \cdot \hat{z}_{t_j}}{\tau}Si,j​=τz^xi​​⋅z^tj​​​

Here, τ\tauτ is a highly critical, learnable temperature parameter. A small temperature (e.g., τ=0.01\tau=0.01τ=0.01) acts as a multiplier that sharply exaggerates differences in similarity scores, forcing the softmax function to become extremely confident.

The model must learn to maximize the similarities along the diagonal (where image xix_ixi​ matches text tit_iti​) and minimize the off-diagonal similarities (where image xix_ixi​ is mismatched with text tjt_jtj​). To prevent one modality from dominating the gradient updates, CLIP uses a Symmetric InfoNCE loss:

LCLIP=12(LI→T+LT→I)\mathcal{L}_\text{CLIP} = \frac{1}{2}\left(\mathcal{L}_{I \to T} + \mathcal{L}_{T \to I}\right)LCLIP​=21​(LI→T​+LT→I​)

The Image-to-Text loss applies softmax across the rows, forcing the image to identify its correct caption among N−1N-1N−1 distractors:

LI→T=−1N∑i=1Nlog⁡exp⁡(Si,i)∑j=1Nexp⁡(Si,j)\mathcal{L}_{I \to T} = -\frac{1}{N} \sum_{i=1}^N \log \frac{\exp(S_{i,i})}{\sum_{j=1}^N \exp(S_{i,j})}LI→T​=−N1​i=1∑N​log∑j=1N​exp(Si,j​)exp(Si,i​)​

The Text-to-Image loss applies softmax across the columns, forcing the text to identify its correct image among N−1N-1N−1 distractors:

LT→I=−1N∑i=1Nlog⁡exp⁡(Si,i)∑j=1Nexp⁡(Sj,i)\mathcal{L}_{T \to I} = -\frac{1}{N} \sum_{i=1}^N \log \frac{\exp(S_{i,i})}{\sum_{j=1}^N \exp(S_{j,i})}LT→I​=−N1​i=1∑N​log∑j=1N​exp(Sj,i​)exp(Si,i​)​

This loss is equivalent to a massive NNN-way classification task. To provide enough "hard negatives" (distractor texts that might look similar to the true text but are actually wrong), NNN must be enormous. OpenAI trained CLIP using an unprecedented batch size of N=32,768N = 32,768N=32,768, requiring highly optimized, distributed matrix multiplications across thousands of GPUs.


Web-scale data and the open-source reproduction (LAION)

The original CLIP was trained on a proprietary dataset of 400 million image-text pairs (WebImageText), sourced via extensive web scraping. These pairs included raw HTML alt-text attributes and adjacent forum captions. This data is profoundly noisy—captions are often misspelled, multilingual, or tangentially related to the image (e.g., a photo of a dog captioned "missing my best friend").

Prior supervised learning dogmas assumed this noise would poison the network. CLIP proved the scale-beats-cleanliness hypothesis: given a large enough batch size and 400M pairs, the random noise cancels out in expectation, leaving behind a robust semantic gradient.

Because OpenAI did not release the training data, the open-source community reproduced it via LAION-400M and later LAION-5B (Schuhmann et al., 2022). To build these datasets, researchers parsed the massive CommonCrawl dump (containing billions of raw HTML images). They used the frozen weights of the original OpenAI CLIP to score every raw image-text pair they found on the internet. If the cosine similarity z^x⋅z^t\hat{z}_x \cdot \hat{z}_tz^x​⋅z^t​ fell below a certain threshold (e.g., 0.28), the pair was discarded as garbage.

This created a feedback loop: an early CLIP model was used to curate a massive, high-quality open dataset, which was then used to train the OpenCLIP variants (Ilharco et al., 2021) that ultimately surpassed the original OpenAI model.


Zero-shot classification as nearest-neighbor search

The most profound downstream capability of the joint embedding space is zero-shot classification: predicting the class of an image from a set of categories the model was never explicitly trained to recognize.

Instead of outputting probabilities over a fixed 1,000-class classifier head, the classification process is recast as a similarity search:

  1. Construct Prompts: For a new dataset with KKK classes (e.g., dog, cat, car), wrap each class label in a natural language template to create KKK text strings tkt_ktk​: "a photo of a {class}."
  2. Encode Text: Pass all KKK strings through the text encoder to yield KKK frozen reference vectors z^tk\hat{z}_{t_k}z^tk​​.
  3. Encode Image: Pass the target image xxx through the image encoder to yield z^x\hat{z}_xz^x​.
  4. Predict: Compute the cosine similarity between the image and all KKK text vectors. The predicted class is simply the arg⁡max⁡\arg\maxargmax:
k^=arg⁡max⁡k(z^x⋅z^tk)\hat{k} = \arg\max_k (\hat{z}_x \cdot \hat{z}_{t_k})k^=argkmax​(z^x​⋅z^tk​​)

The Importance of Prompt Engineering

A raw label like "boxer" is highly ambiguous in natural language—it could refer to a dog breed, a human athlete, or someone packing cardboard. By querying the model with "a photo of a boxer, a type of dog," the text encoder generates an embedding that disambiguates the context, heavily shifting the vector away from sports and towards canines.

Furthermore, researchers use prompt ensembling: querying the text encoder with 80 different phrasing variations ("a close-up photo of a {class}", "a blurry photo of a {class}", "a sketch of a {class}") and averaging the resulting text embeddings. This mathematically widens the "cone of acceptance" for that class in the embedding space, making the classifier vastly more robust to visual domain shifts (like sketches or night-time photos) than a standard supervised ResNet.


Structural Limitations of CLIP

While CLIP excels at global semantic matching, its dual-encoder design and contrastive objective enforce mathematical constraints that dictate its failure modes:

  1. The "Bag of Concepts" Failure: CLIP operates largely as a "bag of words" and "bag of patches." If you prompt it with "a red cube and a blue sphere," its text embedding is mathematically almost identical to "a blue cube and a red sphere." Because the InfoNCE loss never explicitly penalized the model for getting spatial relationships wrong, CLIP cannot bind specific attributes to specific objects.
  2. Spatial Blindness (No Grounding): CLIP pools its entire visual feature map into a single 1×d1 \times d1×d vector to match the text. Therefore, it mathematically destroys all (x,y)(x, y)(x,y) coordinate information. You cannot ask a standard CLIP model "where is the dog?" because it has no mechanism to map the word "dog" back to specific image patches.
  3. Lack of Generative Capacity: CLIP can only measure the distance between an image and a provided text string. Because it lacks a causal language decoder head, it is impossible for CLIP to look at an image and generate a caption from scratch.

These exact limitations define the architecture of the next generation of VLMs (like BLIP and LLaVA), which discard the strict dual-encoder separation in favor of cross-attention and autoregressive text generation.


Key takeaways

CLIP mathematically bridges vision and language by projecting both modalities into a shared unit hypersphere. The model is trained using a Symmetric InfoNCE loss over massive batches of noisy, web-scraped image-text pairs, treating alignment as an NNN-way classification task. This joint space enables zero-shot classification (recasting classification as a nearest-neighbor search against text embeddings) and cross-modal retrieval. While the global contrastive objective creates incredibly robust semantic representations, it fundamentally destroys spatial localization and relational binding, necessitating the development of more complex, generative Vision-Language architectures.


Conceptual questions

  1. InfoNCE Gradient Analysis: The symmetric InfoNCE loss forces an image to match its text among N−1N-1N−1 distractors. Mathematically analyze the derivative of the cross-entropy loss with respect to the similarity scores Si,jS_{i,j}Si,j​. Explain how the gradient magnitude scales based on the "hardness" of the negative examples. Why would a batch consisting of 32,768 images of visually identical golden retrievers provide a stronger learning signal than a batch of 32,768 completely unrelated objects?
  2. Temperature Dynamics: The temperature parameter τ\tauτ scales the logits Si,j=(z^x⋅z^t)/τS_{i,j} = (\hat{z}_x \cdot \hat{z}_t)/\tauSi,j​=(z^x​⋅z^t​)/τ. During the early epochs of CLIP training, the learned τ\tauτ value typically drops dramatically (e.g., from 0.07 to 0.01). What mathematical effect does a smaller τ\tauτ have on the softmax distribution? Why is this sharpening behavior critical for the network to continue learning when the dot products between normalized vectors are bounded strictly between [−1,1][-1, 1][−1,1]?
  3. The LAION Curation Paradox: OpenCLIP models are trained on datasets like LAION-5B, which were curated by throwing away image-text pairs that scored poorly on the original OpenAI CLIP model. Describe the mathematical and semantic risks of this "recursive curation." If the original CLIP model was systematically blind to text printed on physical signs (OCR), what happens to the representation of text-in-images in the LAION dataset, and how does this impact the OpenCLIP model trained on it?
  4. SigLIP vs. InfoNCE: Standard CLIP requires massive batches because the softmax denominator ∑j=1Nexp⁡(Si,j)\sum_{j=1}^N \exp(S_{i,j})∑j=1N​exp(Si,j​) requires all NNN embeddings to reside in GPU memory simultaneously. SigLIP replaces this with a pairwise sigmoid loss, treating every pair independently: LSigLIP=−∑i,j[yijlog⁡σ(Sij−b)+… ]\mathcal{L}_\text{SigLIP} = -\sum_{i,j} [y_{ij} \log \sigma(S_{ij} - b) + \dots]LSigLIP​=−∑i,j​[yij​logσ(Sij​−b)+…]. Prove how this mathematical change breaks the dependency on batch-wide normalization, allowing engineers to train world-class vision encoders across fragmented, smaller GPU clusters.
  5. Architectural Debugging (Attribute Binding): You are tasked with using a frozen CLIP ViT-L/14 model to sort physical robotics components on an assembly line. The objects are "a metallic gear," "a plastic gear," "a metallic bracket," and "a plastic bracket." During testing, the model consistently confuses the metallic gear with the metallic bracket. Using your knowledge of how CLIP aggregates visual tokens and text tokens into single global vectors, diagnose exactly why this "attribute-noun binding" failure occurs, and propose a downstream architectural fix that doesn't involve retraining CLIP.
✦Solutions
  1. InfoNCE gradient hardness. The gradient w.r.t. each logit is proportional to (softmax probability − target), so hard negatives — those with high similarity — receive the largest probability mass and therefore the largest repulsive gradient. A batch of near-identical golden retrievers makes every negative a hard negative (high cosine similarity), forcing fine-grained discrimination; a batch of unrelated objects gives easy negatives (similarity near zero) that contribute almost no gradient.
  2. Temperature dynamics. A smaller τ\tauτ sharpens the softmax by amplifying logit differences. Because normalized dot products are bounded in [−1,1][-1,1][−1,1], the raw logit range is too compressed for cross-entropy to produce confident targets or large gradients; dividing by a small τ\tauτ rescales those bounded similarities into a usable dynamic range, which is why the learned temperature shrinks early in training.
  3. LAION curation paradox. Filtering pairs by the original CLIP keeps only what CLIP already scores as aligned, so any concept CLIP is blind to — e.g. text rendered in images (OCR) — is systematically discarded. The dataset under-represents text-in-images, and OpenCLIP trained on it inherits and reinforces the same OCR blindness: the bias is self-amplifying.
  4. SigLIP. The sigmoid loss scores each pair independently as a binary cross-entropy on σ(Sij−b)\sigma(S_{ij}-b)σ(Sij​−b), with no softmax denominator summing over all NNN embeddings. Removing batch-wide normalization makes the loss decompose over pairs, so it can be sharded or accumulated across smaller/fragmented GPUs without holding all embeddings in memory at once.
  5. Attribute binding. CLIP pools all tokens into a single global vector, collapsing the scene into a bag of concepts — "metallic" and "gear" lose their binding, so two metallic objects share the dominant "metallic" feature and get confused. A fix without retraining: isolate each object first (detector crops or region proposals) and classify each crop separately, rather than relying on one global vector for a compositional scene.

Looking ahead

CLIP establishes a mathematically elegant joint embedding space but remains completely unable to generate language or localize it to specific image regions. The next lecture examines the architectural components required to move beyond perception into generation.

Week 4: Beyond CLIP — Captioning and Grounding. We introduce encoder-decoder architectures for image captioning, derive the role of cross-attention in binding specific words to spatial image features, and examine grounding tasks that reconnect language to precise (x,y)(x, y)(x,y) coordinate bounding boxes.


Further reading

  • Radford, A., et al. (2021). Learning Transferable Visual Models From Natural Language Supervision. ICML. (The foundational CLIP paper).
  • Schuhmann, C., et al. (2022). LAION-5B: An open large-scale dataset for training next generation image-text models. NeurIPS.
  • Zhai, X., et al. (2023). Sigmoid Loss for Language Image Pre-Training. ICCV. (SigLIP, replacing softmax with pairwise sigmoid loss).
← Previous
Week 2: Self-Supervised Representation Learning for Vision
Next →
Week 4: Beyond CLIP — Captioning and Grounding
On this page
  • Purpose of this lecture
  • Architecture: Dual encoders and the joint space
  • The Symmetric InfoNCE Objective
  • Web-scale data and the open-source reproduction (LAION)
  • Zero-shot classification as nearest-neighbor search
  • The Importance of Prompt Engineering
  • Structural Limitations of CLIP
  • Key takeaways
  • Conceptual questions
  • Looking ahead
  • Further reading