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.
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.
Vision Transformer (ViT)
- 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.
- 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.
- 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.
- Transformer encoder: L layers of multi-head self-attention + MLP with Layer normalization and residual connections, exactly as in BERT.
- 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
- 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
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.
- 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.
- 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ᵢⱼ
- 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
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.
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(...)- 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.
- 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 used | How |
|---|---|
| Text-to-image | Its text encoder turns prompts into the embeddings that diffusion models cross-attend to (Stable Diffusion 1.x, SDXL, SD3). |
| Vision-language models | Its image encoder supplies visual tokens to LLMs (LLaVA uses CLIP ViT-L/14). |
| Search and retrieval | Text→image and image→image search with a Vector database. |
| Data filtering and evaluation | Filtering web datasets (e.g. LAION) and scoring prompt–image agreement (CLIP score). |
▸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
References
- [1]An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale (ViT)PaperDosovitskiy et al.2020arxiv.org
- [2]Learning Transferable Visual Models From Natural Language Supervision (CLIP)PaperRadford et al.2021arxiv.org
- [3]Attention Is All You NeedPaperVaswani et al.2017arxiv.org
- [4]CLIP — Transformers documentationDocsHugging Facehuggingface.co