Vision transformers and CLIP¶
A vision transformer cuts an image into patches, treats each patch as a token and runs an ordinary transformer over them. CLIP then trains such an image encoder next to a text encoder so that a picture and its caption land on the same point of a shared space. Those two moves are why one architecture now reads text, pixels and sound, and why almost every image generator and vision-language model you will meet has a CLIP-style encoder inside it.
10,000 ft
For a decade, computer vision meant convolutional networks: architectures with locality and translation equivariance built in. In 2020 the Vision Transformer (ViT) showed that a plain transformer, given enough data, matches or beats them with almost no image-specific design at all. That collapsed vision and language onto one architecture, and one scaling story. In 2021 CLIP replaced fixed label sets with free text: learn from 400 million (image, caption) pairs which caption goes with which image, and you get an image encoder that can be pointed at any category by writing its name. CLIP's text encoder steers latent diffusion; its image encoder (or its successor, SigLIP) is the eye of most vision-language models; and its contrastive objective is the same one that trains the embedding models behind RAG.
2,000 ft
ViT: split a 224×224 image into a 14×14 grid of 16×16 patches; flatten each patch to a
768-vector and project it linearly; prepend a learnable [CLS] token; add learned position
embeddings; run a standard pre-norm transformer encoder; classify from the [CLS] output.
CLIP: run a ViT on a batch of \(N\) images and a text transformer on their \(N\) captions;
normalise both outputs and compute the \(N\times N\) matrix of cosine similarities; train with
cross-entropy so that each image picks out its own caption among the \(N\) (and vice versa).
Zero-shot use: embed "a photo of a {class}" for every class, embed the image, and pick the
class whose text embedding is closest.
Ground level¶
An image as a sentence of patches¶
A transformer consumes a sequence of vectors. The question ViT answers is how to turn an image into one, as cheaply and with as few assumptions as possible. Pixels as tokens are hopeless: a 224×224 image has 50,176 of them and attention cost grows with the square. ViT's answer is the patch: cut the \(H\times W\times C\) image into non-overlapping \(P\times P\) squares, flatten each into a vector of \(P^2C\) numbers, and multiply by one shared matrix \(E \in \mathbb{R}^{P^2C\times D}\).
Worked example: ViT-B/16 on a 224×224 RGB image
- Grid: \(224/16 = 14\) patches per side, so \(N = 14^2 = 196\) patch tokens.
- Each patch: \(16\times16\times3 = 768\) numbers. With \(D = 768\) the patch embedding \(E\) is a \(768\times768\) matrix (590,592 parameters with its bias).
- Add one
[CLS]token: the sequence is \(197\times768\). - Attention matrix per head per layer: \(197^2 = 38{,}809\) entries, against \(50{,}176^2 \approx 2.5\times10^9\) if every pixel were a token.
- Halve the patch size to 8 and the sequence quadruples to 784 tokens; attention cost rises about 16-fold. The "/16" or "/14" in a model name is therefore its most important cost knob.
A linear map applied to each non-overlapping patch is exactly a convolution whose kernel size and
stride both equal \(P\), and that is how every implementation writes it
(Conv2d(3, D, kernel_size=16, stride=16)). The first PCA components of the learned \(E\) look
like the smooth basis functions a CNN's first layer learns (Figure 7 of the
ViT paper).
The rest is a transformer¶
After patch embedding, ViT is the encoder of the transformer block page with nothing added:
- Prepend
[CLS], a learned vector whose final state will summarise the image (borrowed from BERT; global average pooling of the patch outputs works as well, Appendix D.3). - Add position embeddings: one learned \(D\)-vector per position, 197 of them. Self-attention is permutation-equivariant, so without them the model would see a bag of patches.
- \(L\) pre-norm blocks: LayerNorm → multi-head self-attention → residual add, then LayerNorm → two-layer MLP with GELU → residual add.
- Head: LayerNorm the final
[CLS]and apply a linear classifier.
The three sizes from the paper still name every ViT you will meet:
| Model | Layers | Width \(D\) | MLP | Heads | Params (paper) |
|---|---|---|---|---|---|
| ViT-Base | 12 | 768 | 3,072 | 12 | 86M |
| ViT-Large | 24 | 1,024 | 4,096 | 16 | 307M |
| ViT-Huge | 32 | 1,280 | 5,120 | 16 | 632M |
Nearly all parameters sit in the blocks: in ViT-B/16, the patch and position embeddings together are 0.74M of 86.6M (we count them in Build it).
Inductive bias, data, and why ViT lost before it won¶
A convolution assumes three things about images: what matters is local, the same detector is useful everywhere, and the 2-D neighbourhood structure is fixed. Those assumptions are almost always true, so a CNN does not have to learn them. ViT assumes almost none of them: only the MLP is local, attention is global from the first layer, and the position embeddings start out carrying no 2-D information at all. As the ViT authors put it, 2-D structure is used only when cutting patches and when resizing position embeddings for a new resolution.
The consequence was clear in their Figure 3. Pre-trained on ImageNet-1k (1.3M images), ViT-Large did worse than ViT-Base and both trailed comparable ResNets. On ImageNet-21k (14M images) they drew level. On JFT-300M (303M images) the larger ViTs pulled ahead: ViT-H/14 fine-tuned to 88.55% ImageNet top-1, beating the best CNNs of the time at lower pre-training cost. The lesson, stated in the abstract, is that large-scale training trumps inductive bias. Priors are a loan against data: they help when data is scarce and cap you when it is not.
Two follow-ups showed the data requirement was partly a recipe problem. DeiT (Touvron et al. 2020) trained ViT-B on ImageNet-1k alone, on a single 8-GPU machine in a few days, to 81.8% with heavy augmentation and regularisation, and to 83.4% by adding a distillation token: a second learned token, trained to match a CNN teacher's hard predictions, through which the convolutional teacher's inductive bias leaks into the student. AugReg (Steiner et al. 2021) found that the right augmentation and regularisation plus more compute gives the same accuracy as an order of magnitude more data: ImageNet-21k models matching JFT-300M ones.
Inductive bias is a prior on functions
A CNN is a ViT with most of its attention weights forced to zero (outside a local window) and tied across positions. With little data, those constraints rule out many wrong solutions and help. With a lot of data, the model could have learned the right constraints itself, and the hard-coded ones become a ceiling. The ViT result is the same lesson as the bias–variance trade-off, played out at the scale of architectures.
What a ViT learns¶
Probing trained ViTs shows the missing priors being learned rather than absent.
- Position embeddings rediscover the grid. Each learned position embedding is most similar to those of its row and column neighbours; a 2-D topology appears from 1-D learned vectors, which is why hand-built 2-D variants gave no significant gain (ViT Appendix D.4 and Figure 7).
- Some heads are local, some global, from layer one. Measuring the mean distance between a query patch and the patches it attends to, the lowest layers contain both local heads (CNN-like) and heads that already integrate across the image; deeper layers are almost all global. Raghu et al. 2021 found ViT representations more uniform across layers than ResNets', with the residual connections carrying much of that uniformity.
- Large ViTs grow "register" tokens. Darcet et al. 2023 noticed about 2% of output tokens with roughly 10× the norm of the rest, sitting in uninformative background patches. The model had commandeered them as scratch memory for global information, which corrupted attention maps and dense features. Supervised ViTs, OpenCLIP and DINOv2 all did it. The fix: append a few extra learnable tokens (registers) that are thrown away at the output, giving the model somewhere legitimate to compute.
Resolution, aspect ratio and the hierarchy question¶
A ViT trained at 224 can be fine-tuned at 384: keep the patch size, so the sequence grows from 196 to 576 tokens, and bilinearly interpolate the 14×14 grid of position embeddings to 24×24. Accuracy usually rises, because each object now covers more patches. Three lines of work loosened the fixed-grid design further. FlexiViT (Beyer et al. 2022) trains with randomly sized patches so one model can trade accuracy for speed at deployment. NaViT (Dehghani et al. 2023) packs patches from images of any resolution and aspect ratio into one sequence, with attention masked per image, instead of squashing everything to a square. That idea is now standard in vision-language models, which see documents, screenshots and panoramas. Swin (Liu et al. 2021) went the other way, putting CNN priors back: attention inside local windows that shift between layers, and patch merging to build a feature pyramid, so cost is linear in image size. Swin dominated detection and segmentation for a while; then ConvNeXt (Liu et al. 2022) modernised a plain ResNet with ViT-era training tricks and matched Swin, a reminder that the recipe mattered as much as the architecture.
Learning to see without labels¶
ViT also made image self-supervision look like language pre-training:
- MAE (He et al. 2021): mask 75% of the patches, encode only the visible 25%, and train a light decoder to reconstruct the missing pixels. Because the encoder sees a quarter of the tokens, training is 3× or more faster; a ViT-H reaches 87.8% on ImageNet-1k with no extra data. Images are redundant enough that 75% masking is needed to make the task hard (BERT masks 15% of text).
- DINO (Caron et al. 2021) and DINOv2 (Oquab et al. 2023): a student matches a momentum teacher's output on different crops of the same image. DINOv2 curated 142M images (LVD-142M) from a pool of 1.2B by retrieval against curated sets, trained a 1.1B-parameter ViT-g, and produced features that work frozen for classification, depth and segmentation. DINOv3 (Siméoni et al. 2025) scaled to a 7B-parameter ViT and introduced Gram anchoring to stop dense features degrading over long training.
These are the encoders to reach for when you need where things are (dense features). For what things are, named in words, you want CLIP.
CLIP: learn vision from the internet's captions¶
Supervised ImageNet models know 1,000 nouns. The internet has billions of images with text next to them, naming objects, styles, places, people, brands and actions. CLIP (Radford et al. 2021) built WIT, 400 million (image, text) pairs collected by searching for 500,000 queries and keeping up to 20,000 pairs per query to balance concepts, and asked what objective could learn from it.
The obvious objective, captioning (predict the text from the image), was slow. Figure 2 of the paper is the key experiment: a transformer captioner learned zero-shot ImageNet 3× slower than a model predicting only the bag of words in the caption, and swapping prediction for a contrastive objective made learning another 4× more efficient. Predicting the exact caption wastes capacity on phrasing, word order and which of many true descriptions the uploader happened to write. Recognising which caption belongs to an image, among a batch of alternatives, asks only for the information that distinguishes it.
So CLIP trains two encoders: a ViT (or a modified ResNet) for images and a 12-layer, 512-wide transformer for text. Each output is linearly projected into a shared space and L2-normalised. For a batch of \(N\) pairs, compute all \(N^2\) cosine similarities, multiply by a learned scale \(e^{t}\), and apply cross-entropy twice: each image must pick its caption out of the \(N\) (rows) and each caption its image (columns). The \(N-1\) other captions in the batch are the negatives.
The training run was large for 2021: batch size 32,768, 32 epochs over 400M pairs, temperature initialised to 0.07 and clipped so the logit scale never exceeds 100. The largest ResNet (RN50x64) took 18 days on 592 V100 GPUs; ViT-L/14 took 12 days on 256. The ViT models were about 3× more compute-efficient than the CLIP ResNets, which is why "CLIP" today usually means CLIP ViT-L/14.
Zero-shot classification is retrieval¶
A trained CLIP turns any label set into a classifier with no training. For each class, embed a sentence such as "a photo of a {class}."; stack the normalised text embeddings as the rows of a weight matrix; for an image, compute its normalised embedding and take the class with the highest cosine. The text encoder has written the weights of a linear classifier. You can cache those weights and classify millions of images with one matrix product.
Worked example: three classes, one image
An image's cosines with the prompts for fox, dog and cat are 0.31, 0.27 and 0.22. The absolute values look small and close; that is normal for CLIP, whose image and text embeddings sit in different regions of the sphere (the modality gap). What matters is the ranking and the learned scale. With CLIP's scale of 100 the logits are 31, 27 and 22, and the softmax gives 0.982, 0.018, 0.0001. At scale 10 the same cosines give 0.48, 0.32, 0.20; at scale 1, 0.35, 0.33, 0.32. The temperature does not change the decision, only the confidence, and it is learned because the right confidence depends on how separable the data has become.
The phrasing of the prompt matters, because captions on the web are sentences, not bare labels. In the paper, "A photo of a {label}." alone added 1.3 points on ImageNet over the bare class name; averaging the text embeddings of 80 templates ("a bad photo of a {label}", "a sculpture of a {label}", "a photo of the small {label}", …) added another 3.5, almost 5 points together. With both, CLIP ViT-L/14 at 336px reached 76.2% zero-shot ImageNet top-1, matching the original supervised ResNet-50 without seeing any of ImageNet's 1.28 million labelled training images. The previous zero-shot result had been 11.5%.
Robustness, and where CLIP breaks¶
The most important table in the CLIP paper is about distribution shift. Take a zero-shot CLIP and a ResNet-101 with the same 76.2% on ImageNet, then test both on other datasets of the same classes:
| Dataset | ResNet-101 | Zero-shot CLIP ViT-L/14@336 | Change |
|---|---|---|---|
| ImageNet | 76.2 | 76.2 | 0 |
| ImageNetV2 | 64.3 | 70.1 | +5.8 |
| ImageNet-R (renditions) | 37.7 | 88.9 | +51.2 |
| ObjectNet | 32.6 | 72.3 | +39.7 |
| ImageNet Sketch | 25.2 | 60.2 | +35.0 |
| ImageNet-A (adversarially filtered) | 2.7 | 77.1 | +74.4 |
(Figure 13 of the paper.) An ImageNet model learns ImageNet, including its shortcuts; CLIP never saw ImageNet, so it cannot have learned them. When the authors fitted a logistic-regression head to CLIP's features on ImageNet, ImageNet accuracy rose 9.2 points while accuracy under shift barely moved: adapting to one distribution spends robustness. Fine-tuning has the same effect, and WiSE-FT (Wortsman et al. 2021), which averages the weights of the zero-shot and fine-tuned models, recovers much of it.
CLIP has well-documented failure modes, and each teaches something about the objective:
- It reads. Trained on captions, CLIP learned to recognise rendered text, and a written label stuck onto an object can override the object itself: the typographic attack found by the authors of Multimodal Neurons in Artificial Neural Networks (Goh et al., 2021), who also found single neurons responding to a concept as photo, drawing and written word.
- It is a bag of words. To pick the right caption from a random batch you rarely need word order: "the horse is eating the grass" and "the grass is eating the horse" are never both in a batch. Yuksekgonul et al. 2022 showed that CLIP-style models often cannot tell such pairs apart, and that adding composition-aware hard negatives helps.
- It counts and locates poorly. Nothing in the loss needs how many or where; the pooled embedding throws location away. This is why vision-language models use the patch features, not the pooled vector, and why dense-feature methods such as DINOv2 and SigLIP 2 exist.
- The modality gap. Liang et al. 2022 showed that image and text embeddings occupy two separate narrow cones of the sphere, a geometry set at initialisation and preserved by the contrastive loss. Cross-modal cosines are therefore small (0.2–0.35 is typical for a correct match), and you should never compare an image–text cosine with a text–text one.
- It inherits its data. Web captions carry the biases of the web, and the CLIP paper's own bias analysis documents harmful misclassifications; see robustness, fairness and privacy.
After CLIP: data, losses and scale¶
The objective barely changed after 2021; the data and the loss's bookkeeping did.
- More, noisier data. ALIGN (Jia et al. 2021) used 1.8B alt-text pairs with minimal filtering and showed scale compensates for noise.
- Open reproductions. LAION-5B and OpenCLIP made the recipe public; Cherti et al. 2022 measured power-law scaling of zero-shot accuracy with model, data and compute, and found that the training distribution changes the scaling curve (OpenAI's data scaled better on classification, LAION's on retrieval).
- Data curation as the lever. MetaCLIP (Xu et al. 2023) reconstructed CLIP's query-balancing recipe and showed it, not the source, explains much of CLIP's quality; DataComp (Gadre et al. 2023) turned "which subset of a fixed pool trains the best CLIP" into a benchmark.
- Lock the image tower. LiT (Zhai et al. 2021) freezes a strong pre-trained image model and trains only the text side: cheaper and often better.
- Sigmoid instead of softmax. SigLIP (Zhai et al. 2023) treats each of the \(N^2\) pairs as an independent binary "match or not" problem. No normalisation across the batch means no all-gather of the full similarity matrix, so batch size is decoupled from the loss; the authors found gains saturate around a batch of 32k. With a frozen ViT-g image tower ("SigLiT"), four TPU-v4 chips reached 84.5% zero-shot ImageNet in two days. SigLIP 2 (Tschannen et al. 2025) adds a captioning decoder, self-distillation and masked prediction for better localisation and dense features, native-aspect-ratio variants, and multilingual data, in sizes B (86M), L (303M), So400m (400M) and g (1B). SigLIP-So400m is the vision tower of many open VLMs.
- Add a captioner. CoCa (Yu et al. 2022) trains a contrastive loss and a captioning loss on one model, getting both retrieval and generation.
Where these encoders end up¶
| Use | What is used | Example |
|---|---|---|
| Text conditioning for image generation | CLIP text encoder, per-token outputs | SD 1.x (CLIP ViT-L/14, 77×768), SDXL adds OpenCLIP ViT-bigG |
| The eye of a VLM | CLIP / SigLIP image encoder, patch outputs | LLaVA (CLIP ViT-L/14-336), PaliGemma (SigLIP-So400m) |
| Search and dedup | pooled, normalised embeddings | text-to-image search, near-duplicate removal |
| Data filtering | image–caption cosine ("CLIP score") | LAION kept pairs above a CLIP-similarity threshold |
| Evaluation | CLIP score between prompt and generated image | text-to-image prompt adherence |
History¶
How the ideas were found
Learning visual concepts from text is old: Mori et al. (1999) predicted caption words for image regions, and VirTex, ICMLM and ConVIRT (2020) all learned image features from text before CLIP. What changed in early 2021 was scale and the contrastive objective: Alec Radford, Jong Wook Kim and colleagues at OpenAI took ConVIRT's contrastive recipe, built for medical images, and trained it from scratch on 400M web pairs. ViT had appeared a few months earlier, in October 2020, from a Google Brain team including Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Xiaohua Zhai and Neil Houlsby. Several of them went on to LiT, SigLIP, PaLI and PaliGemma, which is why so much of the open vision-language stack traces back to one group. Earlier attempts to put attention into vision had either kept convolutions or used local attention patterns that were slow on accelerators; ViT's contribution was to do the obvious thing at scale and show that it worked.
First principles¶
Why patches? A transformer's cost is set by the number of tokens, and a token should carry roughly as much information as a word does. A 16×16 patch of a natural image is a reasonable "visual word": large enough that 200–600 of them cover an image, small enough that one linear map can encode it without losing much. Smaller patches buy accuracy at quadratic cost; larger patches lose small details. Vision-language models that must read text in images push the other way (smaller effective patches, higher resolution) for exactly this reason.
Why so few priors? Every hard-coded assumption is a bet that it holds for all data you will ever see. Locality and translation equivariance are good bets for photos, but they are wrong for some long-range relations (symmetry, counting, reading a chart's legend), and a model that cannot represent the exception cannot learn it from any amount of data. A weak-prior model must learn the regularities, which needs data, but has no ceiling imposed by them. When data became plentiful the trade flipped.
Why contrastive? Information-theoretically, a caption contains far more bits about how someone chose to describe the image than about the image. A generative captioner must model all of them. A contrastive model only needs to keep the information shared by image and text: the mutual information \(I(X;Y)\). The InfoNCE loss is a lower bound on that quantity, \(I(X;Y) \ge \log N - \mathcal{L}\) (van den Oord et al. 2018), so minimising it is maximising (a bound on) shared information and nothing else.
Why huge batches? The bound can never exceed \(\log N\): with 32,768 pairs it is capped at about 10.4 nats. A small batch also rarely contains a hard negative, so the model learns only coarse distinctions ("dog" vs "car") and never fine ones ("husky" vs "malamute"). Big batches give both a higher ceiling and harder negatives. The sigmoid loss removes the normalisation across the batch, so each pair is an independent example and the batch no longer has to live on one device.
Why does it generalise zero-shot? Because the label set is language, the training task is "classify into an open vocabulary of hundreds of millions of descriptions". ImageNet's 1,000 classes are a tiny, easy subset of that task, specified at test time in the same medium the model was trained on.
The maths¶
Patch embedding and the ViT forward pass. For an image \(\mathbf{x}\in\mathbb{R}^{H\times W\times C}\) cut into \(N = HW/P^2\) flattened patches \(\mathbf{x}_p^i \in \mathbb{R}^{P^2C}\):
These are equations (1)–(4) of the ViT paper; \(\mathbf{z}_L^0\) is the [CLS] position. Shapes for
ViT-B/16 at 224: \(\mathbf{z}_\ell \in \mathbb{R}^{197\times768}\) throughout.
Cost. Per layer, self-attention is \(O\big((N{+}1)^2 D\big)\) and the MLP \(O\big((N{+}1)D^2\big)\) (times 8, with a 4× hidden width). For ViT-B/16, \((N{+}1) = 197 < D = 768\), so the MLP dominates; at 1024×1024 with 16-pixel patches, \(N = 4096 > D\) and attention dominates. That crossover is why high-resolution VLMs tile images or merge tokens.
CLIP's symmetric InfoNCE loss. Let \(\mathbf{u}_i, \mathbf{v}_j \in \mathbb{R}^{d}\) be the L2-normalised image and text embeddings in a batch of \(N\) pairs, and \(s = e^{t}\) the learned scale. Logits \(L_{ij} = s\,\mathbf{u}_i^\top\mathbf{v}_j\). Then
The first term is cross-entropy over row \(i\) (image \(i\) choosing among captions), the second over column \(i\). With \(P^{\text{row}} = \operatorname{softmax}\) along rows and \(P^{\text{col}}\) along columns, the gradient with respect to the logits is
the familiar "predicted minus target" of softmax cross-entropy, applied in both directions. Each negative is pushed down in proportion to how much probability it currently steals, so hard negatives get the largest gradients automatically.
Derivation: InfoNCE bounds the mutual information
Take one image \(\mathbf{x}\) and a set of \(N\) captions in which exactly one, \(\mathbf{y}_1\), was drawn from \(p(\mathbf{y}\mid\mathbf{x})\) and the rest from the marginal \(p(\mathbf{y})\). The Bayes-optimal posterior that caption \(k\) is the true one is
So the best critic \(f(\mathbf{x},\mathbf{y}) = e^{L}\) is proportional to the density ratio \(p(\mathbf{y}\mid\mathbf{x})/p(\mathbf{y})\). Plugging the optimal critic into the loss,
using that \(\mathbb{E}_{p(\mathbf{y})}[p(\mathbf{y}\mid\mathbf{x})/p(\mathbf{y})] = 1\) for the negatives (the approximation is exact as \(N\to\infty\)). Any critic does at least as badly as the optimal one, so \(I(X;Y) \ge \log N - \mathcal{L}\) for every model. Two consequences: the bound saturates at \(\log N\), and the learned dot product estimates a log density ratio, \(s\,\mathbf{u}^\top\mathbf{v} \approx \log\frac{p(\mathbf{y}\mid\mathbf{x})}{p(\mathbf{y})} + \text{const}(\mathbf{x})\), which is precisely the "how much more likely is this caption given this image" score that zero-shot classification ranks by.
SigLIP's sigmoid loss. With labels \(z_{ij} = +1\) if \(i=j\) and \(-1\) otherwise, a learned scale \(t'\) and bias \(b\):
There are \(N\) positives and \(N^2 - N\) negatives, so the bias starts at \(b = -10\) (with \(e^{t'} = 10\)): every pair begins as "probably not a match". A negative with cosine 0 then costs \(-\log(1-\sigma(-10)) \approx 4.5\times10^{-5}\), so the many easy negatives do not swamp the first updates.
Zero-shot classifier. With class prompts' normalised embeddings stacked as \(W_{\text{text}}\in\mathbb{R}^{K\times d}\), the zero-shot classifier is \(p(k\mid\mathbf{x}) = \operatorname{softmax}(s\,W_{\text{text}}\,\mathbf{u}(\mathbf{x}))_k\): a linear head whose weights were produced by the text encoder. Prompt ensembling averages the rows over templates (then renormalises), which is averaging classifier weights.
Build it¶
Two programs. The first builds a ViT's token sequence and counts its parameters, so the table above stops being folklore.
import numpy as np
def vit_shapes_and_params(img=224, patch=16, ch=3, d=768, depth=12, heads=12, mlp=3072, classes=1000):
n = (img // patch) ** 2 # number of patch tokens
p = {}
p["patch_embed"] = patch * patch * ch * d + d # a linear map per patch (= conv, stride=kernel)
p["cls_token"] = d
p["pos_embed"] = (n + 1) * d # learned, one per position incl. [CLS]
block = (2 * 2 * d # two LayerNorms (scale + shift)
+ d * 3 * d + 3 * d # fused Q, K, V projections
+ d * d + d # attention output projection
+ d * mlp + mlp + mlp * d + d) # two-layer MLP
p["blocks"] = depth * block
p["final_norm"] = 2 * d
p["head"] = d * classes + classes
return n, p
def patchify(x, patch):
"""(H, W, C) image -> (N, patch*patch*C) rows, raster order."""
H, W, C = x.shape
x = x.reshape(H // patch, patch, W // patch, patch, C).transpose(0, 2, 1, 3, 4)
return x.reshape(-1, patch * patch * C)
for name, kw in [("ViT-B/16", {}), ("ViT-L/16", dict(d=1024, depth=24, heads=16, mlp=4096)),
("ViT-H/14", dict(patch=14, d=1280, depth=32, heads=16, mlp=5120))]:
n, p = vit_shapes_and_params(**kw)
print(f"{name}: {n} patches, {sum(p.values())/1e6:.1f}M params "
f"(blocks {p['blocks']/1e6:.1f}M, embeddings {(p['patch_embed']+p['pos_embed'])/1e6:.2f}M)")
rng = np.random.default_rng(0)
img = rng.random((224, 224, 3)).astype(np.float32)
tokens = patchify(img, 16)
E = rng.standard_normal((768, 768)).astype(np.float32) * 0.02 # patch embedding
z = np.vstack([np.zeros((1, 768), np.float32), tokens @ E]) # prepend [CLS]
print("patches:", tokens.shape, "-> token sequence:", z.shape)
print("first patch == top-left 16x16 block:", np.allclose(tokens[0], img[:16, :16].reshape(-1)))
print("attention matrix per head per layer:", z.shape[0] ** 2, "entries")
Output:
ViT-B/16: 196 patches, 86.6M params (blocks 85.1M, embeddings 0.74M)
ViT-L/16: 196 patches, 304.3M params (blocks 302.3M, embeddings 0.99M)
ViT-H/14: 256 patches, 632.0M params (blocks 629.7M, embeddings 1.08M)
patches: (196, 768) -> token sequence: (197, 768)
first patch == top-left 16x16 block: True
attention matrix per head per layer: 38809 entries
The counts match the paper's 86M and 632M; ViT-L comes to 304M here against the paper's 307M, the difference being the classification head the paper used. Note that 98% of the parameters are in the blocks: a ViT is a transformer with a 0.7M-parameter adapter on the front.
The second program trains a CLIP from scratch on a toy world, with the gradients written out. There are 10 hidden "concepts"; an image is a noisy rendering of its concept plus a lot of nuisance pixels, and a caption is a different noisy rendering of the same concept. Two linear encoders learn a shared 16-dimensional space with the symmetric InfoNCE loss and a learned, clipped temperature. We then classify new images zero-shot by comparing them with one clean "prompt" per concept.
import numpy as np
rng = np.random.default_rng(0)
# A toy world: 10 concepts. Images and captions are different noisy "renderings" of a concept.
C, k, d_img, d_txt = 10, 8, 32, 24
concepts = rng.standard_normal((C, k))
A_img, A_txt = rng.standard_normal((k, d_img)), rng.standard_normal((k, d_txt))
def images(c): return (concepts[c] + 0.5 * rng.standard_normal((len(c), k))) @ A_img \
+ 2.0 * rng.standard_normal((len(c), d_img)) # nuisance pixels
def captions(c): return (concepts[c] + 0.5 * rng.standard_normal((len(c), k))) @ A_txt
def l2n(x): return x / np.linalg.norm(x, axis=1, keepdims=True)
def softmax(x, ax): e = np.exp(x - x.max(ax, keepdims=True)); return e / e.sum(ax, keepdims=True)
D = 16 # shared embedding width
Wi, Wt = 0.1 * rng.standard_normal((d_img, D)), 0.1 * rng.standard_normal((d_txt, D))
log_scale = np.log(1 / 0.07) # CLIP's temperature init, learnable
def clip_step(X, Y, lr=0.05):
global Wi, Wt, log_scale
N = len(X); s = np.exp(log_scale)
U, V = X @ Wi, Y @ Wt
u, v = l2n(U), l2n(V)
L = s * u @ v.T # N x N logits, positives on the diagonal
Pi, Pt = softmax(L, 1), softmax(L, 0) # image->text rows, text->image columns
loss = -0.5 * (np.log(np.diag(Pi)).mean() + np.log(np.diag(Pt)).mean())
G = 0.5 * ((Pi - np.eye(N)) + (Pt - np.eye(N))) / N # dloss/dL
gu, gv = s * G @ v, s * G.T @ u
def back(g, x, n): # through x / ||x||
return (g - (g * x).sum(1, keepdims=True) * x) / n
Wi -= lr * X.T @ back(gu, u, np.linalg.norm(U, axis=1, keepdims=True))
Wt -= lr * Y.T @ back(gv, v, np.linalg.norm(V, axis=1, keepdims=True))
log_scale = min(log_scale - lr * (G * L).sum(), np.log(100)) # clip at 100, as CLIP does
return loss
def zero_shot_acc(n=2000):
c = rng.integers(0, C, n)
prompts = l2n(concepts @ A_txt @ Wt) # one clean "a photo of a {concept}" per class
pred = np.argmax(l2n(images(c) @ Wi) @ prompts.T, axis=1)
return (pred == c).mean()
N = 256
print(f"batch {N}: uniform guess = log N = {np.log(N):.2f}; "
f"floor with {N // C} same-concept pairs per row ~ log(N/C) = {np.log(N / C):.2f}")
print(f"before training: zero-shot acc {zero_shot_acc():.3f}")
for step in range(1500):
c = rng.integers(0, C, N)
loss = clip_step(images(c), captions(c)) # loss measured before this step's update
if step in (0, 10, 100, 1499):
print(f"step {step:4d} loss {loss:6.3f} temperature {np.exp(-log_scale):.3f}"
f" zero-shot acc {zero_shot_acc():.3f}")
Output:
batch 256: uniform guess = log N = 5.55; floor with 25 same-concept pairs per row ~ log(N/C) = 3.24
before training: zero-shot acc 0.033
step 0 loss 10.204 temperature 0.099 zero-shot acc 0.647
step 10 loss 4.223 temperature 0.127 zero-shot acc 0.814
step 100 loss 4.073 temperature 0.142 zero-shot acc 0.874
step 1499 loss 3.915 temperature 0.140 zero-shot acc 0.885
Four things to read off it. The first loss, 10.2, is far above the uniform-guess value \(\log 256 = 5.55\): random embeddings at CLIP's initial scale of 14 are confidently wrong, which is why CLIP starts at a modest temperature rather than 0.01. Zero-shot accuracy goes from below chance to 88.5% with no labels, only pairs. The loss stalls near 3.9, not 0: with 10 concepts in a batch of 256, every row has about 25 captions that are equally correct, so the best achievable loss is around \(\log 25.6 = 3.24\). These false negatives are the toy version of a batch holding several photos of dogs. And the learned temperature rises from 0.07 to 0.14: the model discovers that it cannot be sure which of 25 good captions is "the" one, and lowers its confidence to match. Real CLIP, where near-duplicates are rarer, drives the temperature down to its 0.01 floor.
Things to try
- Fewer false negatives. Set
C, k, d_img, d_txt = 1000, 32, 64, 48, so a batch rarely holds two pairs of the same concept. The floor disappears: in our run the loss fell to 0.72, the temperature fell to 0.046 and zero-shot accuracy over 1,000 classes reached 97%. - Sigmoid loss. Replace the two softmaxes by \(\sigma(z_{ij}(s\,\mathbf{u}_i^\top\mathbf{v}_j + b))\) with \(b\) initialised to \(-10\) and \(s\) to 10. The gradient is \(\sigma(\cdot) - [i{=}j]\) per cell. Compare accuracy at batch 32.
- Prompt ensembling. Instead of one clean prompt per class, average 10 noisy
captionsper class into the classifier weights. How close do you get to the clean prompt? - Modality gap. After training, compute the mean cosine between matched image and text embeddings and the mean cosine between two text embeddings of the same concept. Which is larger, and why?
- A real one. With PyTorch and
open_clip, load a ViT-B/32, embed 20 of your own photos and three label sets, and measure how much "a photo of a {}." helps over the bare label.
In practice¶
- Choosing an encoder (as of 2026). For zero-shot classification and retrieval, a SigLIP 2 or a large OpenCLIP model; for dense features (segmentation, depth, correspondences), DINOv2 or DINOv3; for the vision tower of a VLM, SigLIP-family encoders are the common default. Read the model card for its resolution, patch size and whether it supports native aspect ratios.
- Preprocessing is part of the model. Each checkpoint expects a specific resize, crop and per-channel mean/std. Using ImageNet normalisation with a CLIP checkpoint quietly costs accuracy. Always use the checkpoint's own processor.
- Normalise before you compare. CLIP-family embeddings are compared by cosine. Store them L2-normalised and use inner-product search in your vector index (vector search).
- Thresholds are not portable. A cosine of 0.28 between an image and a caption is a good match for one CLIP model and a mediocre one for another. Calibrate thresholds on your own labelled pairs.
- Fine-tune carefully. Full fine-tuning on a narrow dataset usually lifts in-distribution accuracy and lowers robustness; a linear probe or weight-space averaging with the zero-shot model (WiSE-FT) keeps more of both.
- Patch size is a budget decision. /14 and /16 are standard; /32 is 4× cheaper and fine for retrieval of whole scenes; text-heavy images (documents, charts, UIs) need small patches or high resolution.
Common misconceptions¶
\"Transformers are better than CNNs for vision\"
They are better at scale with the right recipe. With ImageNet-1k and a naive recipe the original ViT lost to ResNets; with modern training a ConvNeXt matches a Swin. What transformers really bought was one architecture across modalities, so that vision could share the language stack's tooling, scaling laws and hardware optimisations.
\"CLIP understands images the way a captioner does\"
CLIP is a retrieval model. It learns whatever distinguishes a caption from the others in a batch, which is often only the nouns. It cannot generate text, it is weak at counting, spatial relations and word order, and its scores are only meaningful as rankings.
\"Zero-shot means the model never saw the classes\"
It means the model was never trained on that benchmark's labels. CLIP's 400M web pairs almost certainly contain many images of every ImageNet class, described in words. The CLIP paper's overlap analysis found small effects from exact test-set duplicates, but "zero-shot" measures transfer of task specification, not novelty of concepts.
Check yourself¶
How many tokens does ViT-L/14 see for a 336×336 image, and how big is each attention matrix?
\(336/14 = 24\), so \(24^2 = 576\) patches plus [CLS] = 577 tokens. Each head's attention matrix
has \(577^2 = 332{,}929\) entries per layer. (This is the 576-token image that LLaVA-1.5 feeds to
its language model.)
Why is a ViT patch embedding the same thing as a convolution?
A convolution applies one shared linear map to every window of the input. With kernel size \(P\) and stride \(P\) the windows are exactly the non-overlapping patches, and the output channels are the \(D\) components of the embedding. Flattening the \(H/P\times W/P\) output grid gives the token sequence.
ViT-L trained on ImageNet-1k is worse than ViT-B. Why, and what changes with more data?
ViT has weak inductive biases, so a larger ViT has more ways to fit 1.3M images that do not generalise; regularisation helps only partly. With 14M images (ImageNet-21k) the sizes draw level, and with 300M (JFT) the larger model's capacity is used to learn the priors a CNN hard-codes and then go beyond them.
CLIP's logits are s·cos. What would happen without the learned scale s?
Cosines are bounded in \([-1, 1]\), so with \(s = 1\) the softmax over 32,768 captions could never become confident: the best possible probability for the right caption would be about \(e^1/(e^1 + 32767e^{-1}) \approx 2\times10^{-4}\). The loss would stay near \(\log N\) and give weak gradients. The scale lets the model sharpen the distribution as its embeddings become separable; CLIP caps it at 100 for stability.
Why does InfoNCE need negatives at all? Why not just maximise the cosine of matched pairs?
Maximising matched cosines alone has a trivial solution: map every image and every caption to the same vector (collapse). The negatives in the denominator force different pairs apart, so the embedding must carry information that distinguishes them. Self-supervised methods without explicit negatives (DINO, BYOL) prevent collapse with other devices: a momentum teacher, centring and sharpening.
You fit a linear probe on CLIP features using ImageNet and gain 9 points on ImageNet. What happens on ImageNet Sketch, and why?
Almost nothing, or it drops. The probe learns ImageNet-specific cues (backgrounds, photographic style) that correlate with labels on ImageNet but not under shift. The CLIP paper reports exactly this: a 9.2-point gain on ImageNet with little to no gain on the shifted datasets. Zero-shot weights, written by the text encoder, do not contain those shortcuts.
Hard: in the toy CLIP above, the learned temperature rose. Under what data would you expect it to fall, and what does that tell you about real CLIP?
The optimal confidence is set by how many captions in a batch are genuinely correct for an image. With 10 concepts in a batch of 256, about 25 captions fit each image, so the optimal softmax spreads probability over them and the model raises the temperature. With many concepts (few false negatives per batch), the right caption is unique and the model can be confident, so the temperature falls. Real CLIP's temperature drops to its 0.01 floor, which says that its 400M diverse captions rarely contain near-duplicates within a batch; deduplication and balanced sampling (the 20,000-pairs-per-query cap) are what make that true.
Hard: why does SigLIP initialise its bias at −10 and what goes wrong at 0?
With \(N\) positives and \(N^2-N\) negatives per batch, the prior probability of a match is about \(1/N\). With \(b = 0\) and small initial logits, every pair starts at \(\sigma(0) = 0.5\), so the \(N^2 - N\) negatives each contribute \(\log 2\) and dominate the loss and the gradient; the first updates push everything apart ("over-correction") instead of learning which pairs match. A bias of \(-10\) starts every pair near "not a match", so negatives are cheap and the gradient is dominated by the positives. The SigLIP paper's ablation (its Table 4) shows the \(-10\) initialisation consistently helping.
Go deeper¶
Papers
- An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale — Dosovitskiy et al., 2020. Section 3.1 is the whole model; Figure 3 (data size) and Figure 7 (what it learns) are the findings.
- Learning Transferable Visual Models From Natural Language Supervision — Radford et al., 2021 (CLIP). Long; read Sections 2–3.1 (data, objective, Figure 3's pseudocode), Figure 2 (efficiency) and Section 3.3 (robustness).
- Training data-efficient image transformers & distillation through attention — Touvron et al., 2020 (DeiT). How to train a ViT on ImageNet alone.
- Masked Autoencoders Are Scalable Vision Learners — He et al., 2021. The cleanest self-supervised ViT recipe.
- Sigmoid Loss for Language Image Pre-Training — Zhai et al., 2023 (SigLIP); and SigLIP 2 — Tschannen et al., 2025.
- Vision Transformers Need Registers — Darcet et al., 2023. A model of how to find and fix an emergent artefact.
- DINOv2 — Oquab et al., 2023. Section 3 on data curation is worth reading on its own.
- Representation Learning with Contrastive Predictive Coding — van den Oord, Li and Vinyals, 2018. Where InfoNCE and its mutual-information bound come from.
- Reproducible scaling laws for contrastive language-image learning — Cherti et al., 2022.
Videos and lectures
- Stanford CS231N, Spring 2025, Lecture 8: Attention and Transformers — Attention for vision and ViT in a university course.
- Lucas Beyer: Convergence of Vision & Language — A ViT/SigLIP co-author on how vision and language merged.
- An Image is Worth 16x16 Words (Paper Explained) and OpenAI CLIP (Paper Explained) — Yannic Kilcher. Close readings of both papers.
- How AI 'Understands' Images (CLIP) — Computerphile. The intuition in 18 minutes.
Articles and blog posts
- Multimodal Neurons in Artificial Neural Networks — Goh et al., Distill, 2021. What is inside CLIP, and typographic attacks.
Courses and books
- Dive into Deep Learning: Transformers for Vision — Zhang, Lipton, Li and Smola. A runnable ViT with commentary.
Code
- google-research/vision_transformer and google-research/big_vision — The authors' code for ViT, LiT, SigLIP and more.
- mlfoundations/open_clip — Open CLIP training and hundreds of checkpoints with their benchmark results.
- huggingface/pytorch-image-models (timm) — Read
vision_transformer.py: the whole ViT in a few hundred lines.
Where this leads¶
- Vision-language models — plug a CLIP/SigLIP encoder's patch features into a language model.
- Latent diffusion and guidance — CLIP's text encoder as the conditioning signal for image generation.
- Embeddings and vector search — the same contrastive embeddings, put to work in retrieval.
- Video and world models — patches become space-time patches.
- Mechanistic interpretability — CLIP's multimodal neurons were an early landmark.