CS 460G · Week 13 → Lecture 3 · Fall 2026

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 2021 ViT-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

QuestionShort 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}
z_0 = \left[\,x_{\text{class}};\; x_p^{1}E;\; x_p^{2}E;\; \dots;\; x_p^{N}E\,\right] + E_{pos}
$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.
QuantityDeck's exampleViT-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 patch7687683072
Patches $N$6419649
Tokens into the encoder6519750

🔲 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:

The classification path · slides 14, 16–19
z_L = \mathrm{Encoder}^{(L)}\!\left(z_0\right), \qquad \hat{y} = \mathrm{MLP}\!\left(z_L^{0}\right)
$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 — ViT architecture
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:

GELU · slide 27
\mathrm{GELU}(x) = x\,\Phi(x)
\mathrm{GELU}(x) \approx 0.5\,x\left(1 + \tanh\!\left(\sqrt{\tfrac{2}{\pi}}\;u\right)\right)
u = x + 0.044715\,x^{3}
$\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 depthWhat it representsHow you can tell
Lower layersGlobal and local features togetherAttention distances are short and long; heads respond to both neighbours and far patches
Higher layersGlobal features onlyAttention spreads across the whole image; there is no residual local structure
Position embeddingsThe grid itselfSimilarity 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:

CNNVision Transformer
Shape of the stackHierarchical: resolution down, channels upIsotropic: every block has the same resolution and the same channel count
Why that shapeObjects occur at various scales — build a pyramidScale is handled by attention, not by pooling
LocalityBuilt in (small kernels)Learned (attention can look anywhere)
Inductive biasStrong: locality + translation equivarianceAlmost none
Data appetiteWorks from small/medium datasetsNeeds large-scale pretraining or heavy augmentation
Compute at high resolutionGrows linearly with pixelsGrows quadratically (tokens²) — the reason for windowed attention
The two follow-up papers in the deck are the punchline Swin (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

ModelLayersHidden $D$MLPHeadsParams
ViT-Base1276830721286 M
ViT-Large241024409616307 M
ViT-Huge321280512016632 M
Where the 86 M actually lives · derived for this page
\text{params} \approx L\left(4D^{2} + 2D\,D_{\text{mlp}}\right)
+ \;P^{2}C\,D + (N+1)D + 2D
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

TaskHow the Transformer is usedDeck's example
Chest X-ray classificationViT applied directly to radiographs, multi-label pulmonary diseaseUsman et al., JDI 2022 (slide 33)
Hybrid CNN–ViTCNN features concatenated at every encoder layer — local detail from the CNN, global context from attentionOkolo et al., CMPB 2022 (slide 34)
Object detectionDETR: CNN backbone + Transformer encoder-decoder, predicting a set of boxes directly (no anchors, no NMS)Pereira et al. 2024 (slide 35)
Encoding / decodingFully Transformer-based encoder-decoder for image-to-imageStrudel et al. 2021 (slide 36)
SegmentationSeveral schemes: ViT encoder + decoder head, or patch-level token classificationLi 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.

✓Cheat sheet

ThingFormula / numberReading
Patches$N=HW/P^2$224² with P=16 → 196 patches
Patch vector$P^2C$16·16·3 = 768 numbers per patch
Sequence$[\,x_{\text{cls}};\,x_p^1E;\dots;x_p^NE\,]+E_{pos}$$N+1$ tokens of dimension $d$
Classification$\hat{y}=\mathrm{MLP}(z_L^{0})$Only the [CLS] row is used
Attention cost$(N+1)^2$ per headQuadratic in patches → why P and resolution matter
GELU$x\Phi(x)$Smooth ReLU; tanh approximation with $\sqrt{2/\pi}$
Stack shapeIsotropicSame resolution and width in every block (vs CNN's pyramid)
ViT-B/L/H86 / 307 / 632 M$L(4D^2+2DD_{\text{mlp}})$ dominates; FFN ≈ 2/3

!Exam traps, collected

WrongRight
“ViT convolves, then attends.”The patch embedding is a linear projection of flattened patches (a strided convolution at most). There is no convolutional stack.
“Positional encodings are concatenated.”They are added, so they must have the same width $d$.
“The [CLS] token is just padding.”It is a learnable vector whose final state is the image representation — drop it and you have to pool instead.
“Bigger patches are always cheaper and just as good.”Cheaper (fewer tokens, quadratic saving) but each patch loses detail; P=32 costs accuracy against P=16.
“ViT beats CNNs because attention is better.”At small data CNNs win. ViT wins at scale, and its advantage shrinks to noise with strong augmentation.
“Every block halves the resolution.”ViT is isotropic: every block keeps the same resolution and width. That is the CNN/ViT structural difference.
GELU written with $\tfrac{2}{\pi}$The standard constant is $\sqrt{2/\pi}$. The deck's slide 27 prints it without the root.
Reading map for the deck
Every number on this page, and where it comes from

▦All 41 slides