Vision Transformers,
one piece at a time
Francesco Pelosin
Interactive theory before the lab: play with the widgets, then go and build Multi-Head Attention for the MAE in the Colab notebook.
Roadmap
- Why ViT? — why it exists, what it does
- ViT: the big picture
- Linear embedder — patches and the projection E
- The [CLS] token — one extra vector that will speak for the whole image
- Positional embedding — why? how? learned?
- Multi-Head Attention — Q/K/V, split, scores, softmax, recombine
- LayerNorm & the MLP head
→ The lab: a Masked Autoencoder
How to use this
- ← → (or a presenter clicker) to move; the tabs on top jump to a section.
- 🧭 The panel on the right always shows where we are inside the ViT. Click a block to jump there; O hides / shows it.
- Shapes follow the lab config:
IMAGE_SIZE=128,PATCH_SIZE=16,EMBED_DIM=256,NUM_HEADS=8, batch = 1.
A Transformer that reads images
✨ What can one patch see?
Why does it exist?
For ~10 years, computer vision meant CNNs: small filters sliding over the image, with built-in assumptions (nearby pixels matter; a cat is a cat anywhere in the image). Meanwhile, in language, the Transformer (2017) took over: one generic architecture in which every word can look at every other word — and it kept improving with more data and compute.
ViT (Dosovitskiy et al., Google, 2020) asked: can the very same Transformer read images, with almost nothing image-specific?
What does it do?
Cut the image into patches → turn each patch into a vector (a “word”) → add where it came from → run a standard Transformer encoder → read the answer from one special token.
Why is it important?
- With enough data — or self-supervised pre-training such as MAE, today's lab — it matches or beats CNNs.
- ✨ Every patch can look at the whole image from the very first layer. A CNN can't: its small filters see only a neighbourhood, and the view grows one layer at a time. 👆 click me
- One architecture for text, images, audio, video: the backbone of CLIP, DINO, MAE, SAM and of the “eyes” of multimodal LLMs.
| NLP Transformer | Vision Transformer |
|---|---|
| a sentence | an image |
| a word (token) | a 16×16 patch |
| embedding lookup table | linear projection of the patch pixels |
| position of the word | position of the patch |
| [CLS] token (BERT) → label | [CLS] token → label (“pizza”) |
An image is worth 16×16 words
The whole model on one page. Click any block to see what it does — a small drawing plus the code. Change the config to see how the shapes scale; the lab itself always uses the our lab config.
Cut the image into a sequence
Why patches and not pixels?
Attention compares every token with every other token, so its cost grows with n². One token per pixel: 128 × 128 = 16,384 tokens → ≈ 268 million scores per head per layer. With 16 × 16 patches (the lab): 64 tokens → 4,096 scores. Patches shorten the sequence by P² while each token still carries local detail.
Step 2 — each patch becomes a vector
⚠ In the code, this Linear layer is written as a Conv2d — it is exactly the same computation
| Linear view (the idea) | Conv2d view (the code) | |
|---|---|---|
| operation | flatten each patch, multiply by E | 256 filters of 16×16×3, stride 16 |
| weights | E: (768, 256) | (256, 3, 16, 16) = E reshaped |
| parameters | 196,608 + 256 (bias) = 196,864 in both | |
| output | (1, 64, 256) | (1, 256, 8, 8) → rearrange → (1, 64, 256) |
Why identical? With kernel = stride = 16 the windows never overlap: each output position is the dot product of one whole patch with each of the 256 filters — one row of E each. Conv2d just does “cut + flatten + multiply” in one fast call.
self.proj = nn.Conv2d(3, 256, kernel_size=16, stride=16) x = self.proj(x) # (1, 256, 8, 8) x = rearrange(x, 'b c h w -> b (h w) c') # (1, 64, 256)
The [CLS] token: one extra vector in front of the embeddings
nn.Parameter of shape (1, 1, 256), and it is concatenated in front of the 64 patch embeddings along the sequence
dimension: (1, 64, 256) → (1, 65, 256). It is randomly initialised (trunc_normal_, std 0.02), it is the
same for every image, and it is not the label.self.cls_token = nn.Parameter(torch.zeros(1, 1, 256)) nn.init.trunc_normal_(self.cls_token, std=0.02) # random cls = self.cls_token + self.pos_embed[:, :1, :] # (1, 1, 256) cls = cls.expand(x.shape[0], -1, -1) # one per image x = torch.cat([cls, x], dim=1) # (B, 65, 256)
🧙 Why? What is this sorcery? ✨click to reveal
A peek into the future: section 5 (attention) explains the mechanics. For now, just the idea in two steps.
Why? Attention sees a set of patches, not an image
Self-attention is permutation-equivariant: shuffle its input tokens and you get exactly the same output vectors, shuffled the same way. A summary such as the [CLS] output does not change at all.
How is it added? One vector per position, summed
self.pos_embed = nn.Parameter(torch.zeros(1, 65, 256)) x = torch.cat([cls, x], dim=1) # (B, 65, 256) x = x + self.pos_embed # same P for all images
Here P is the fixed 2D sin-cos so that you can see a pattern; in the notebook pos_embed is learned.
How is P computed? Many recipes, two common ones
Other recipes exist (relative positions, RoPE which rotates q and k, …). They all do the same job: give every position its own, recognisable vector.
Multi-head attention: the whole picture
nn.Linear(256, 768).nn.Linear(256, 256) mixes the heads. Same shape in and out.Inside one head: how much does each query “like” each key?
One row per query
Row i of S holds the scores of query i against every key: how well what token i is looking for matches what each token contains. The [CLS] row is how [CLS] reads the image.What does a dot product measure?
Multiply element by element and add up. Large and positive: the two vectors point the same way, the query found what it looks for. Negative: they point in opposite directions.All pairs in one product
Q·Kᵀ gives the whole n × n grid at once, one grid per head. Lab: 65² = 4,225 scores per head, 8 heads, in every block.q @ k.transpose(-2, -1): (b, h, n, d)·(b, h, d, n) → (b, h, n, n)Watch: 3Blue1Brown, Visualizing attention, a transformer's heart.
Softmax, then a weighted sum of the values
Softmax in one line: exp of every score, then divide by the row's total, so each query spreads exactly 100% of its attention over the keys. The ÷√d keeps the scores in a sane range (lab: d = 32, so ÷ 5.66; self.scale = head_dim ** -0.5).
Each output is a weighted average of the value vectors, weighted by its row of A. Pepperoni p1 mostly copies the values of p1 and p2: after attention it “knows” there is another pepperoni. And the [CLS] output is the same sum whatever the order of the tokens (§4): that is why positions are needed.
The result: every head looks for something
Each head scores every (query, key) pair with its own rule, softmax turns the scores into weights, and the output is the weighted average of the values. Trained ViTs do learn heads that look like these (local, row/column, colour/texture, object parts), but these three are hand-written. Multi-head = several such “questions” asked in parallel, then merged by WO. Set the multiplier to 0: every patch gets the same weight.
How is it normalised? LayerNorm — and where it sits
What it does: every token is shifted and scaled to mean 0, std 1 over its own 256 features, then γ and β let the model choose a new scale and offset. Multiply a token by 10 or add 5: the output does not change (try it).
Why LayerNorm and not BatchNorm? LN uses only the token itself: it doesn't depend on the other images in the batch (in our lab the batch is a single image!), behaves the same in training and testing (no running statistics), and works for any number of tokens.
The MLP head: where the [CLS] token finally goes
x = self.encoder_norm(x) # (1, 65, 256) final LN z = x[:, 0] # (1, 256) [CLS] only logits = self.head(z) # (1, 1000) Linear(256, 1000)
- The [CLS] output is the input of the MLP head. This is the whole reason [CLS] exists: one vector that summarises the image, ready for a classifier.
- How is it normalised? By the final LayerNorm (
encoder_norm): the head always receives a token with a controlled scale. - Which head? ViT pre-training used an MLP with one hidden layer; for fine-tuning, a single Linear layer. K = number of classes.
- [CLS] or mean? Both work (ViT paper, appendix): [CLS] is the BERT tradition, global average pooling (GAP) the CNN one.
Put it together
NUM_HEADS from 8 to 16. The number of parameters of MultiHeadAttention…Why? Count the weights: the only learned layers are qkv = nn.Linear(D, 3D) and out_proj = nn.Linear(D, D).
The number of heads h appears nowhere in this count. h only decides how the 3D outputs are cut: 8 heads × d = 32 features, or 16 heads × d = 16 features, the same 256 numbers either way (the rearrange has no weights).
What does change with 16 heads: twice as many attention matrices, 16 × (n × n) scores instead of 8 × (n × n), each dot product over only d = 16 features (so the scale becomes 1/\sqrt{16}). More, thinner “questions”, at the same parameter cost.
Masked Autoencoders (MAE): what are they for, and why?
An MAE (He et al., 2021) is a way to pre-train a ViT without labels: hide most of the patches, let the ViT encoder see only the visible ones, and ask a small decoder to paint the missing pixels back.
🎯 What for?
To learn good image features from unlabelled images. After pre-training the decoder is thrown away; the encoder becomes the backbone: add an MLP head and fine-tune on a small labelled set, or use it for detection and segmentation (SAM's image encoder is an MAE-pre-trained ViT).🧩 Why mask so much?
Images are very redundant: with a few patches hidden, the model could fill them in from the neighbours. Hiding 75% makes the task hard enough that the model has to understand what is in the image (a pizza has round slices of salami…), not just copy nearby pixels.⚡ Why a ViT?
A ViT works on a set of tokens, so “hide 75%” simply means: give the encoder fewer tokens (17 instead of 65, as drawn above). The heavy encoder runs on ¼ of the sequence, which makes pre-training about 3× faster. Positions are added before dropping, so every kept patch still knows where it came from.What a ViT learns without labels
DINO is a cousin of MAE: another way to pre-train a ViT without labels. Shown here: the attention of the [CLS] query in the heads of the last layer of a ViT (8 × 8 patches) trained without any labels: the heads find the object on their own and outline it. Figure 1 of DINO: Caron et al., Emerging Properties in Self-Supervised Vision Transformers (2021). DINOv3 (Siméoni et al., 2025) scales the same recipe up.
Your mission 🎯
BuildMultiHeadAttention line by line: for each line, pick the right operation, and the line writes itself. Then paste the finished code into the Colab notebook and train. In the lab the MAE overfits our single pizza. The encoder sees n = 17 tokens and the decoder 65, so your attention must work for any n. Everything you need is in §5, and in the cheat sheet on the next slide.
Cheat sheet (lab config, ViT with n = 65)
| step | what | shape |
|---|---|---|
| image | normalised RGB | (1, 3, 128, 128) |
| patch embed | Conv2d(3, 256, 16, stride=16) + 'b c h w -> b (h w) c' | (1, 64, 256) |
| + [CLS] | torch.cat([cls, x], dim=1) | (1, 65, 256) |
| + positions | x + pos_embed (learned, added) | (1, 65, 256) |
| qkv | nn.Linear(256, 768) | (1, 65, 768) |
| split heads | 'b n (three h d) -> three b h n d' | 3 × (1, 8, 65, 32) |
| scores | Q Kᵀ · d−½ (d = 32) | (1, 8, 65, 65) |
| softmax | over the keys (last axis): every row sums to 1 | (1, 8, 65, 65) |
| weighted sum | A · V | (1, 8, 65, 32) |
| merge heads | 'b h n d -> b n (h d)' | (1, 65, 256) |
| out_proj | nn.Linear(256, 256) | (1, 65, 256) |
| block | x + MHA(LN(x)); x + MLP(LN(x)) | (1, 65, 256) |
| head | final LN → x[:, 0] → nn.Linear(256, K) | (1, K) |
Play it again
- 🎬 ViT in a nutshell: the whole pipeline in a 60 s film.
- 🎮 Patch Quest: be Imma, the image, and walk through the ViT; every chapter replays a slide of this lesson.
- 🧩 Build MultiHeadAttention, one line at a time, then go to the Colab notebook.
References & further reading
- Dosovitskiy et al., An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale (ICLR 2021): the ViT paper.
- Vaswani et al., Attention Is All You Need (NeurIPS 2017): the Transformer and its attention.
- He et al., Masked Autoencoders Are Scalable Vision Learners (CVPR 2022): the MAE of the lab.
- Caron et al., Emerging Properties in Self-Supervised Vision Transformers (DINO, ICCV 2021) and Siméoni et al., DINOv3 (2025): what real ViT heads learn without labels.
- 3Blue1Brown, Visualizing attention, a transformer's heart: the best visual intuition for Q, K and V.
- Interactive: Transformer Explainer · LLM Visualization