Foundations to Frontier
Tests
E. Deep Learning › E16 Self-Supervised and Contrastive Learning

CLIP

CLIP (Contrastive Language–Image Pre-training; Radford and colleagues, OpenAI, ICML 2021) learns a shared embedding space for images and text from 400 million image–caption pairs collected from the web. An image encoder and a text encoder are trained with a symmetric contrastive loss, so each image picks out its own caption from a large batch and vice versa. Afterwards, any class can be recognised zero-shot: embed a prompt such as "a photo of a dog" and pick the class whose prompt is closest to the image. This page covers the dual encoders, the symmetric InfoNCE loss, the learnable temperature, prompts and zero-shot transfer. In the exercises you implement the loss and zero-shot prediction, then train CLIP on synthetic image–caption pairs from 40 concepts. It classified 20 never-seen concepts zero-shot with 0.73 accuracy (chance 0.05), and a larger batch helped.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Match pictures with their captions

CLIP learns from pictures and the captions people wrote for them. One network reads images, another reads text, and both produce vectors. Training asks each picture to be closest to its own caption among all the captions in a batch, and each caption to its own picture. Afterwards you can recognise new kinds of things just by writing their names: turn “a photo of a runway” into a vector and find the images closest to it. The demo shows how the size of the batch sets the difficulty of the matching game.

Self-supervised learning lab
With N = 32 pairs, guessing gives accuracy 0.0313 and loss ln N = 3.47. Larger batches give more negatives per step; CLIP used N = 32,768.
Why engineers care

CLIP-style models let engineers search imagery with words, label data quickly, and recognise categories nobody trained a classifier for, from inspection photos to satellite scenes and robot camera views.

📝 Quick check (Level 0)
0/3 answered
  1. 1. CLIP trains on…
  2. 2. Zero-shot classification uses…
  3. 3. CLIP has…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Embeddings: I = normalise(f(images)), T = normalise(g(texts)); logits S = IᵀT·e^s with a learnable scale e^s = 1/τ, initialised at 1/0.07 ≈ 14.3 and capped at 100.
  • Loss: ½[CE(S, identity) + CE(Sᵀ, identity)], cross-entropy over rows and over columns.
    • At chance it equals ln N: ln 32,768 ≈ 10.4 for CLIP’s batch of 32,768, which gives 32,767 negatives per image.
  • Zero-shot: embed a prompt such as “a photo of a dog.” for each class and predict argmax_k cos(I, T_k). Chance is 1/K, 0.05 for 20 classes.
  • Prompt engineering: templates and ensembles of templates (for example “a satellite image of a runway.”) improve accuracy by several points.
📝 Quick check (Level 1)
0/3 answered
  1. 1. CLIP loss at chance for N = 4:
  2. 2. Initial logit scale 1/0.07 ≈
  3. 3. Negatives per image with batch 32,768:

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

CLIP in code

Exercise 1.

  • The CLIP loss was near 0 for perfectly matched embeddings and ln 4 for uninformative logits.
  • Zero-shot prediction picked the nearest prompt.

Practice.

  • Use open_clip or Hugging Face CLIPModel; encode the prompts once per class set.
  • For domain imagery, try domain prompts and template ensembles, or fine-tune with a small labelled set (linear probe or WiSE-FT weight interpolation).
  • CLIP inherits biases and gaps from web data. Evaluate on your own domain before relying on zero-shot outputs.
I = F.normalize(img_enc(images), dim=-1); T = F.normalize(txt_enc(texts), dim=-1)
logits = logit_scale.exp().clamp(max=100) * I @ T.T
labels = torch.arange(len(I))
loss = (F.cross_entropy(logits, labels) + F.cross_entropy(logits.T, labels)) / 2
# zero-shot: class_emb = F.normalize(txt_enc(["a photo of a " + c for c in classes]), dim=-1)
🐍 Exercise 1: CLIP loss and zero-shot
Implement CLIP's similarity logits, the symmetric loss and zero-shot prediction.
📝 Quick check (Level 2)
0/3 answered
  1. 1. An open-source CLIP implementation:
  2. 2. Prompt ensembles…
  3. 3. Before trusting zero-shot outputs…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Language as supervision.

  • Captions describe images with open-ended concepts. Aligning images with text teaches the image encoder a space organised by those concepts.
  • The text encoder can embed new concept names, so classification needs no new training: classes are defined at test time by text.

Why zero-shot generalises. If new concepts are combinations of features both encoders have learned (shape, colour, context), their prompt embeddings land near the corresponding images. This works best for concepts well represented on the web, and poorly for specialised domains (medical, rare industrial parts).

Scale. Contrastive alignment benefits from many negatives (large batches) and huge, diverse data. CLIP’s zero-shot ImageNet accuracy matched a supervised ResNet-50 without using any ImageNet labels, and its robustness to distribution shift was markedly higher.

📝 Quick check (Level 3)
0/3 answered
  1. 1. In CLIP, classes are defined at test time by…
  2. 2. Zero-shot works poorly for…
  3. 3. CLIP's zero-shot ImageNet accuracy matched…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Can a contrastive image–text model recognise unseen concepts?

History.

  • A. Radford et al., “Learning transferable visual models from natural language supervision” (CLIP, ICML 2021).
  • C. Jia et al., “Scaling up visual and vision-language representation learning with noisy text supervision” (ALIGN, ICML 2021).
  • Follow-ups include SigLIP (2023, sigmoid loss) and open CLIP models trained on LAION.

Exercise 2.

  • World: 60 concepts, each an 8-D content code. Images mix content with 10 strong style dimensions (32-D); captions mix it with 4 weak wording dimensions (24-D).
  • Training: CLIP on (image, caption) pairs from 40 concepts only, with two MLP encoders (to 16-D), symmetric InfoNCE (τ = 0.1), 1000 steps, batch 16 or 64.
  • Test: zero-shot classification with noise-free concept prompts, on the 40 seen and the 20 unseen concepts.
batch zero-shot, 40 seen concepts zero-shot, 20 unseen concepts
16 0.644 0.748
64 0.710 0.732

Chance: 0.025 (40-way), 0.05 (20-way).

  • Zero-shot transfer works: images of 20 concepts never seen in training were classified at 0.73, 15 times chance, purely by matching to their text prompts. Both encoders learned to map the shared content code, so new concepts land in the right place.
  • A larger batch helps on seen concepts: 64 beat 16 on all three seeds (0.71/0.67/0.67 against 0.64/0.61/0.64). On unseen concepts the gain held on two of three seeds (seed 0: 0.73 vs 0.75).
  • Note: 20-way is easier than 40-way, so the unseen and seen numbers are not directly comparable.
🐍 Exercise 2 (research): can a contrastive image–text model recognise unseen concepts?
Train CLIP on pairs from 40 concepts and test zero-shot classification on seen and unseen concepts, with batch 16 and 64.

CLIP in AI, robotics and aerospace

  • Open-vocabulary perception: robots that find “the red toolbox” without a trained detector for it.
  • Data curation: searching large image archives (satellite, inspection) with text queries.
  • Design lesson: language supervision gives open-ended categories, but zero-shot quality depends on how well your domain’s concepts are represented in the training pairs.

References

  1. A. Radford et al. (2021). “Learning transferable visual models from natural language supervision.” Proc. ICML.
  2. C. Jia et al. (2021). “Scaling up visual and vision-language representation learning with noisy text supervision.” Proc. ICML.
  3. X. Zhai, B. Mustafa, A. Kolesnikov and L. Beyer (2023). “Sigmoid loss for language image pre-training.” Proc. ICCV.