Vision Transformers — an image is worth 16×16 words
Same attention, different input. Chop the image into square patches, flatten each one into a vector,
treat the vectors as tokens, prepend a learnable [CLS] token, and run a plain Transformer encoder.
No convolution, no hierarchy, no locality baked in — which is exactly why it needs a lot of data.
Every formula below is real LaTeX, rendered in your browser.
41 slides3 interactive widgetsDosovitskiy et al. ICLR 2021ViT-B/L/H
Read W13L2 first. This page reuses attention, multi-head and the encoder block without re-deriving
them. If $QK^\top/\sqrt{d_k}$ is not yet familiar, start with
the Transformers page.
16×16
pixels per “word”
64
patches in the deck's 128² example
768
numbers per patch (16·16·3)
+1
[CLS] token, for the whole image
One sentence that governs the lecture. A ViT is a Transformer whose tokens happen to be image
patches: cut the image into a grid, flatten and linearly project each patch to a $d$-dimensional vector,
add positional embeddings, and let self-attention over patches do what convolution used to do. The
classification comes from one extra token, [CLS], whose final state is the image representation.
The consequence is a model with almost no built-in spatial inductive bias — it must learn that
neighbours matter, which is why it wins at scale and loses on small datasets.
0Orientation in 60 seconds
Question
Short answer
How do you feed an image to a Transformer?
Split it into $P\times P$ patches; flatten each patch to $P^2C$ numbers; project to $d$ dimensions. Patches become tokens.
How many tokens is an image?
$N = HW/P^2$, plus one for [CLS]. The deck's 128×128 image with 16×16 patches gives $8\times8=64$.
Where does the classification come from?
From the final state of the [CLS] token — a learnable vector that attends to every patch and aggregates the image.
What replaces the missing sense of space?
Positional embeddings — 1-D in the original ViT, added to the patch embeddings just like word positions.
Why does it need so much data?
Attention has almost no inductive bias (no locality, no translation equivariance). On small datasets a CNN wins; on large ones the ViT catches up and passes it.
What is the standard activation?
GELU — a smooth version of ReLU, $x\Phi(x)$.
1From pixels to tokens
Slide 12 states the whole idea in five words — “An image → 16×16 words!” — and slide 15 spells out
the three operations: split into $P\times P$ patches, embed each patch into a vector, add 1-D positional
encodings. Formally, for a patch size $P$, $C$ channels, $H\times W$ image:
Patch embedding · slides 14–15
N = \frac{HW}{P^{2}}, \qquad x_p^{i} \in \mathbb{R}^{P^{2}C}
$E \in \mathbb{R}^{(P^2C)\times d}$ is the linear projection. The bracket is a sequence of
$N+1$ tokens of dimension $d$ — exactly the shape a Transformer encoder expects. $E_{pos}$ is added, not concatenated.
Quantity
Deck's example
ViT-B/16 (224²)
ViT-B/32 (224²)
Image
$128\times128\times3$
$224\times224\times3$
$224\times224\times3$
Patch
$16\times16\times3$
$16\times16\times3$
$32\times32\times3$
Numbers per patch
768
768
3072
Patches $N$
64
196
49
Tokens into the encoder
65
197
50
🔲 Widget 1 — cut an image into tokens
Set the image size and the patch size. The grid, the patch vector length and the attention
matrix are all recomputed — the last line is the $n^2$ bill from W13L2.
…
2The [CLS] token and the encoder
Slides 16–19 zoom in on the one token that is not a patch. It is a learnable vector prepended to
the sequence, and only its final representation is used for the prediction:
$z_L^{0}$ is the first row of the final sequence — the [CLS] token, which never was a
patch and has attended to all of them. The other $N$ rows are discarded at classification time.
Analogy
[CLS] is an empty chair at the head of the table. It has no content of its own, but it listens to every
patch and writes the minutes; at the end you read the minutes, not the patches. (In BERT the same token is
used for sentence-level tasks; the ViT inherits the trick.)
Slide 14. The whole model in one figure (Dosovitskiy et al. 2021): patches → linear projection → “patch + position embedding” → a stack of $L$ encoder blocks (Norm → Multi-Head Attention → ⊕ → Norm → MLP → ⊕) → MLP head on the [CLS] row. tap to open full size
What is genuinely different from a CNN here
In a CNN, locality is architecture: a 3×3 kernel can only see 3×3 pixels, and you must stack layers
to widen the receptive field. In a ViT, locality is learned: at layer 1 every patch can already attend
to every other patch. That is more flexible and far less constrained — the source of both its ceiling and
its data hunger.
3GELU — the activation the paper uses
ViTs replace ReLU with the Gaussian Error Linear Unit. It weights an input by the probability that a
standard Gaussian is below it, which gives a smooth, slightly non-monotonic curve:
$\Phi$ is the standard normal CDF. The tanh form is the fast approximation used in practice —
it is what torch.nn.GELU(approximate='tanh') computes. Unlike ReLU, GELU is differentiable
everywhere and allows a little negative signal through ($\mathrm{GELU}(-1)\approx-0.16$).
A typo worth knowing — the slide drops a square root
Slide 27 prints the approximation as $0.5x\left(1+\tanh\left(\tfrac{2}{\pi}(x+0.044715x^3)\right)\right)$ —
the constant 2/π, without the root. Every reference implementation, including the PyTorch page the
slide itself links, uses $\sqrt{2/\pi}\approx0.7979$, not $0.6366$. With the printed version the
curve saturates too slowly and is off by ~2.5 % at $x=2$. Widget 2 plots all three so you can see which one
hugs the true GELU — and in an exam write the $\sqrt{\,}$.
📈 Widget 2 — GELU, ReLU, and the two approximations
Exact $\mathrm{GELU}(x)=x\Phi(x)$ computed from the error function, the correct tanh
approximation, and the one printed on the slide.
…
4What the layers actually learn
Slide 29 makes two claims that are worth keeping, because they are what “it works” means mechanistically:
the position embeddings learn the grid, and the depth is used differently at the bottom than at the
top.
Layer depth
What it represents
How you can tell
Lower layers
Global and local features together
Attention distances are short and long; heads respond to both neighbours and far patches
Higher layers
Global features only
Attention spreads across the whole image; there is no residual local structure
Position embeddings
The grid itself
Similarity between position vectors falls off with distance in the image, i.e. the model rebuilt 2-D layout from 1-D encodings
That last row is the interesting one: the ViT is given only a 1-D index for each patch, yet it recovers
the 2-D neighbourhood structure — the paper shows this by correlating position-embedding similarity with
grid distance. Nothing in the architecture told it that patch 3 is above patch 11.
5CNNs vs ViTs — and the two roads that met in the middle
Slide 30 puts the difference in one line each. It is the cleanest statement in the deck:
CNN
Vision Transformer
Shape of the stack
Hierarchical: resolution down, channels up
Isotropic: every block has the same resolution and the same channel count
Why that shape
Objects occur at various scales — build a pyramid
Scale is handled by attention, not by pooling
Locality
Built in (small kernels)
Learned (attention can look anywhere)
Inductive bias
Strong: locality + translation equivariance
Almost none
Data appetite
Works from small/medium datasets
Needs large-scale pretraining or heavy augmentation
Compute at high resolution
Grows linearly with pixels
Grows quadratically (tokens²) — the reason for windowed attention
The two follow-up papers in the deck are the punchlineSwin (slide 31) pushes Transformers toward ConvNets: attention inside local windows, shifted
between layers, with a hierarchical pyramid. ConvNeXt (slide 32) pushes ConvNets toward
Transformers: a modernised ResNet with depthwise convolutions, GELU, LayerNorm and the same training recipe.
Both land in the same place — which tells you the architecture was never the only variable; the training
recipe and the scale were doing half the work.
6The variants, and where the parameters go
Model
Layers
Hidden $D$
MLP
Heads
Params
ViT-Base
12
768
3072
12
86 M
ViT-Large
24
1024
4096
16
307 M
ViT-Huge
32
1280
5120
16
632 M
Where the 86 M actually lives · derived for this page
Plug ViT-B ($L{=}12$, $D{=}768$, $D_{\text{mlp}}{=}3072$): $12\times(2.36\text{M}+4.72\text{M}) = 85.0$ M,
plus ≈1 M of embeddings and norms → 86 M, matching the published number. The FFN is two thirds
of the model — the attention is not where the weights are.
🧮 Widget 3 — the parameter budget
Pick a published preset or move the sliders. The bars split the total into attention, FFN and
embeddings, using the formula above.
…
7Where ViTs are actually used
Task
How the Transformer is used
Deck's example
Chest X-ray classification
ViT applied directly to radiographs, multi-label pulmonary disease
Usman et al., JDI 2022 (slide 33)
Hybrid CNN–ViT
CNN features concatenated at every encoder layer — local detail from the CNN, global context from attention
Okolo et al., CMPB 2022 (slide 34)
Object detection
DETR: CNN backbone + Transformer encoder-decoder, predicting a set of boxes directly (no anchors, no NMS)
Pereira et al. 2024 (slide 35)
Encoding / decoding
Fully Transformer-based encoder-decoder for image-to-image
Strudel et al. 2021 (slide 36)
Segmentation
Several schemes: ViT encoder + decoder head, or patch-level token classification
Li et al., MedIA 2022 (slide 37)
The pattern behind those five rows
ViTs are rarely used alone outside classification at scale. The winning recipes either
(a) keep a CNN to produce local features and let attention mix them, or (b) let attention do everything but
train on far more data than the task itself provides. Both are the same trade: inductive bias vs data.