AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
◈Multimodal, Video & 3D
  1. Vision Transformers and CLIP
  2. Multimodal LLMs (Vision-Language Models)
  3. Video Generation
  4. 3D: NeRF, Gaussian Splatting and Text-to-3D
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Multimodal, Video & 3D

Vision Transformers and CLIP

How a transformer reads an image as a sequence of patches (ViT), and how CLIP learns a shared embedding space for images and text with contrastive learning, enabling zero-shot classification, retrieval and text-to-image conditioning.

Advanced~28 min·4 references
Key terms
Vision Transformer (ViT)CLIPMultimodalTransformerEmbeddingCosine similarityZero-shot

For a decade, computer vision meant CNNs. In 2020 the Vision Transformer showed that the same Transformer that powers language models can match or beat CNNs on images, given enough data. A few months later CLIP used a ViT to connect images with natural-language text in one embedding space. Together they are the backbone of today's Multimodal AI: the text encoder of Stable Diffusion, the 'eyes' of most vision-language models, and the engine behind semantic image search.

≈
An image as a sentence of tiles
Cut a photo into a grid of small square tiles, like a mosaic, and lay them out in a row. Each tile is now a 'word', and the whole image is a 'sentence' of 196 words. A transformer, which already knows how to let words in a sentence look at each other, can then let every tile look at every other tile, so that the tile with a dog's ear can directly consult the tile with its tail.

Vision Transformer (ViT)

  1. Patchify: split an H×W image into non-overlapping P×P patches. A 224×224 image with P = 16 gives (224/16)² = 14×14 = 196 patches, each with 16·16·3 = 768 values.
  2. Linear projection: flatten each patch and multiply by a learned matrix E to get a D-dimensional Embedding (D = 768 for ViT-Base). This is equivalent to a convolution with kernel size and stride P.
  3. Add a [CLS] token and position embeddings: a learned extra token whose final state summarizes the image, plus learned position embeddings so the model knows where each patch came from.
  4. Transformer encoder: L layers of multi-head self-attention + MLP with Layer normalization and residual connections, exactly as in BERT.
  5. Head: a small MLP on the final [CLS] state predicts the class (or, for CLIP, the [CLS] state is projected into the shared embedding space).
N = H·W / P² z₀ = [ x_cls ; x¹·E ; x²·E ; … ; xᴺ·E ] + E_pos y = MLP( LN( z_L⁰ ) )
ViT input sequence and output. Names like ViT-B/16 mean 'Base size, 16×16 patches'; ViT-L/14 is Large with 14×14 patches.
In words: The number of tokens is the image area divided by the patch area; the encoder's input is a learned [CLS] token followed by every flattened patch multiplied by the embedding matrix E, plus position embeddings; the class prediction is an MLP applied to the layer-normalized final [CLS] state.
Symbols(hover a symbol in the formula)
N
number of patches (tokens) per image
H·W
image height × width in pixels
P²
patch area; P is the patch side (16 for ViT-B/16)
z₀
the encoder's input sequence, (N + 1) × D
x_cls
the learned [CLS] token embedding
x¹·E
first flattened patch (P·P·3 values) times the embedding matrix
xᴺ·E
the last (N-th) patch, embedded the same way
E
patch embedding matrix, (P·P·3) × D, shared by all patches
;
stack the tokens one after another into a sequence
E_pos
learned position embeddings, (N + 1) × D, added element-wise
z_L⁰
output of the last layer L at position 0 (the [CLS] token)
LN
layer normalization
MLP
the classification head
y
class scores
▸Worked example
ViT-B/16 at 224×224: N = 224 · 224 / 16² = 50,176 / 256 = 196 patches Each patch: 16 · 16 · 3 = 768 values; E is 768 × 768 (589,824 weights) z₀: 196 patch tokens + 1 [CLS] = 197 tokens × 768; E_pos is also 197 × 768 ViT-L/14 at 224 px: (224/14)² = 256 patches; at 336 px: (336/14)² = 24² = 576 (LLaVA-1.5's visual tokens)
Loading interactive…
Walk through ViT-B/16 from pixels to class scores and tap the [CLS] token and the position embeddings. Notice that after the patch embedding the model is just the Transformer encoder from NLP; only the [CLS] state reaches the classifier head.

Data hunger. A CNN has built-in assumptions (locality, translation equivariance) that help on small datasets. ViT has almost none, so trained on ImageNet-1k alone it underperforms a ResNet. Pre-trained on 300M images (JFT-300M) it surpasses state-of-the-art CNNs at lower pre-training cost (Dosovitskiy et al.)[1]. Later work (e.g. DeiT, with strong augmentation and distillation) made ViTs competitive on ImageNet-1k alone, and self-supervised methods such as MAE and DINO pre-train ViTs without labels.

knobPatch size P
What it is
Side length of each square patch; determines how many tokens an image becomes.
↑ If you increase it
Fewer, coarser tokens (P = 32 at 224 px → 49 tokens): much cheaper, since attention cost grows with N², but small details and text in images are lost.
↓ If you decrease it
More, finer tokens (P = 14 → 256 tokens; P = 8 → 784): better accuracy and fine detail, at quadratically higher attention cost and memory.
Typical values
16 (ViT-B/16), 14 (ViT-L/14, used by CLIP and LLaVA), 32 for fast variants.
knobInput resolution
What it is
Image size fed to the ViT; with a fixed patch size it sets the token count N = (H/P)·(W/P).
↑ If you increase it
Better for small objects, documents and OCR; cost grows roughly with N² (doubling the side → 4× tokens → up to 16× attention cost). Position embeddings must be interpolated when changing resolution after pre-training.
↓ If you decrease it
Faster and lighter, fine for coarse classification, but fine-grained details vanish.
Typical values
224 px for pre-training; 336–448 px for fine-tuning and VLM vision encoders.

CLIP: connecting images and text

CLIP (Radford et al., 2021)[2] trains two encoders side by side: an image encoder (ResNet or ViT) and a text encoder (a transformer). Training data is 400 million (image, caption) pairs collected from the internet, with no hand-made labels. The objective is contrastive: in a batch of N pairs, the embedding of each image should be most similar to the embedding of its own caption, and dissimilar to the other N − 1 captions (and vice versa). After training, images and text live in one shared space, where Cosine similarity measures how well a caption describes an image.

Sᵢⱼ = ( Iᵢ · Tⱼ ) / τ L = ½ · [ CE_rows(S, diag) + CE_cols(S, diag) ]
CLIP's contrastive objective: a symmetric cross-entropy (InfoNCE) over the N × N similarity matrix.
In words: Score every image against every caption with a cosine similarity divided by a temperature, then apply cross-entropy twice: each row (image) must pick out its own caption and each column (caption) its own image; average the two directions.
Symbols(hover a symbol in the formula)
Sᵢⱼ
similarity logit between image i and caption j (one entry of the N × N matrix S)
Iᵢ
L2-normalized embedding of image i
Tⱼ
L2-normalized embedding of caption j
τ
tau: learned temperature (starts at 0.07; CLIP clips 1/τ at 100)
CE_rows
cross-entropy along each row: image i must give the highest score to caption i
CE_cols
cross-entropy along each column: caption j must give the highest score to image j
diag
the correct 'class' is on the diagonal (i = j)
½
average of the two directions
▸Worked example
N = 2 pairs, cosines: I₁·T₁ = 0.8, I₁·T₂ = 0.2, I₂·T₁ = 0.1, I₂·T₂ = 0.7 τ = 0.1 → S = [[8, 2], [1, 7]] Rows: −ln(e⁸/(e⁸ + e²)) = 0.0025; −ln(e⁷/(e¹ + e⁷)) = 0.0025 Columns: −ln(e⁸/(e⁸ + e¹)) = 0.0009; −ln(e⁷/(e² + e⁷)) = 0.0067 L = ½ · (row mean 0.0025 + column mean 0.0038) = 0.0031 With τ = 1 the same cosines give L ≈ 0.44: the low temperature sharpens the softmax.
Loading interactive…
Walk through the two towers up to the loss, then the last step for zero-shot use, and tap the similarity matrix. Notice that the encoders never see each other's input: they meet only in the N × N matrix, whose diagonal holds the true pairs.

Zero-shot classification

To classify without any training examples (Zero-shot), write one caption per class (e.g. 'a photo of a dog', 'a photo of a cat'), embed them with the text encoder, embed the image, and pick the caption with the highest similarity. The best CLIP model reaches 76.2% top-1 on ImageNet this way, matching the original ResNet-50 that was trained on its 1.28M labelled images[2]. Prompt templates matter: 'a photo of a {label}' beats the bare label, and averaging several templates helps further.

python
import torch
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 cat", "a photo of a dog", "a photo of a rabbit"]
inputs = processor(text=labels, images=image, return_tensors="pt", padding=True)

with torch.no_grad():
    out = model(**inputs)
probs = out.logits_per_image.softmax(dim=-1)[0]   # logits = cosine sim * learned scale
for label, p in zip(labels, probs):
    print(f"{label:22s} {p:.3f}")

# Embeddings for search / retrieval:
# model.get_image_features(...), model.get_text_features(...)
Zero-shot classification with CLIP in Hugging Face transformers.
knobTemperature τ (logit scale)
What it is
Divides the cosine similarities before the softmax. CLIP learns it as a parameter (stored as logit_scale = log(1/τ)).
↑ If you increase it
Higher τ → softer distribution over the batch: gentler gradients that treat all negatives more equally; too high and the model barely separates matches from non-matches.
↓ If you decrease it
Lower τ → sharper softmax that focuses on the hardest negatives; too low makes training unstable. CLIP clips the scale at 100 (τ ≥ 0.01).
Typical values
Initialized at τ = 0.07; ends near 0.01 (scale 100) in CLIP.
knobContrastive batch size
What it is
Number of image–text pairs per batch; every other pair in the batch acts as a negative example.
↑ If you increase it
More (and harder) negatives per step → better embeddings; needs many GPUs and gathering embeddings across devices.
↓ If you decrease it
Easier task with few negatives; the model learns coarser distinctions. Sigmoid-loss variants such as SigLIP cope better with smaller batches.
Typical values
32,768 in CLIP; 4k–32k in open reproductions.
Where CLIP is usedHow
Text-to-imageIts text encoder turns prompts into the embeddings that diffusion models cross-attend to (Stable Diffusion 1.x, SDXL, SD3).
Vision-language modelsIts image encoder supplies visual tokens to LLMs (LLaVA uses CLIP ViT-L/14).
Search and retrievalText→image and image→image search with a Vector database.
Data filtering and evaluationFiltering web datasets (e.g. LAION) and scoring prompt–image agreement (CLIP score).
!
Limitations and pitfalls
CLIP's embeddings capture 'what' better than 'how many' or 'where': it struggles with counting, spatial relations ('a red cube on a blue sphere' vs. the reverse) and negation. It can be fooled by typographic attacks (an apple with a paper label reading 'iPod' gets classified as an iPod) and it inherits social biases from web data[2]. Practical pitfalls: compare embeddings only after L2-normalizing, use the same model for both sides, and remember the text encoder truncates at 77 tokens.
▸Go deeper: why attention over patches works

Self-attention (Attention, Vaswani et al.)[3] lets every patch gather information from every other patch in a single layer, so ViTs have a global receptive field from layer 1, while a CNN needs many layers to see the whole image. Dosovitskiy et al. found that some ViT heads attend locally in early layers (behaving like convolutions) while others attend globally, and that learned position embeddings rediscover the 2-D grid structure on their own[1].

CLIP is an instance of contrastive representation learning: rather than predicting the exact caption (which the authors found far less efficient), it only has to tell which caption goes with which image. Open reproductions (OpenCLIP trained on LAION) and successors such as SigLIP use the same recipe. The Hugging Face CLIP documentation[4] lists the available checkpoints and APIs.

Quiz

1.
A ViT-B/16 receives a 224×224 image. How many patch tokens (excluding [CLS]) does it process?
2.
Why did the original ViT underperform ResNets when trained only on ImageNet-1k?
3.
What does CLIP's contrastive loss push the model to do?
4.
You use CLIP zero-shot with bare labels ('dog', 'cat') and accuracy is mediocre. What is the cheapest likely improvement?
5.
What happens to a ViT's attention cost if you halve the patch size at the same resolution?
Score: 0/5

References

  1. [1]
    An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale (ViT)
    PaperDosovitskiy et al.2020arxiv.org
  2. [2]
    Learning Transferable Visual Models From Natural Language Supervision (CLIP)
    PaperRadford et al.2021arxiv.org
  3. [3]
    Attention Is All You Need
    PaperVaswani et al.2017arxiv.org
  4. [4]
    CLIP — Transformers documentation
    DocsHugging Facehuggingface.co
← Previous
Music & Audio Generation: Codecs, Tokens and Diffusion
Next →
Multimodal LLMs (Vision-Language Models)