🍕 ViT, hands-on
🎮 game 1 / 1
Transformers hands-on lab

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.

🎮 Patch Quest: the ViT adventure game

Roadmap

  1. Why ViT? — why it exists, what it does
  2. ViT: the big picture
  3. Linear embedder — patches and the projection E
  4. The [CLS] token — one extra vector that will speak for the whole image
  5. Positional embedding — why? how? learned?
  6. Multi-Head Attention — Q/K/V, split, scores, softmax, recombine
  7. 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.
Our running example, same size as in the lab.
0 · Why ViT?

A Transformer that reads images

click a step to jump to it

    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.
    • One architecture for text, images, audio, video: the backbone of CLIP, DINO, MAE, SAM and of the “eyes” of multimodal LLMs.
    NLP TransformerVision Transformer
    a sentencean image
    a word (token)a 16×16 patch
    embedding lookup tablelinear projection of the patch pixels
    position of the wordposition of the patch
    [CLS] token (BERT) → label[CLS] token → label (“pizza”)
    1 · ViT general architecture

    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.

    The whole ViT in 4 lines (ViT paper, eq. 1–4)
    \begin{aligned} z_0 &= [\,\cls;\ x^1E;\ x^2E;\ \dots;\ x^NE\,] + \Epos \\ z'_\ell &= \mathrm{MSA}(\mathrm{LN}(z_{\ell-1})) + z_{\ell-1}, \qquad \ell = 1 \dots L \\ z_\ell &= \mathrm{MLP}(\mathrm{LN}(z'_\ell)) + z'_\ell \\ y &= \mathrm{LN}(z_L^0) \;\rightarrow\; \text{MLP head} \end{aligned}
    2 · Linear embedder

    Cut the image into a sequence

    patch size P: hover a patch in the image or in the 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.

    2 · Linear embedder

    Step 2 — each patch becomes a vector

    hover a patch in the sequence · click to lock it
    How? The same E (the same kernel) is applied to every patch: 64 patches, one set of weights (weight sharing). So two patches get different tokens only because their pixels differ. Two salami slices look alike but are not pixel-identical, so their tokens are similar, not equal. Same recipe, slightly different ingredients.

    ⚠ In the code, this Linear layer is written as a Conv2d — it is exactly the same computation

    kernel 16×16, stride 16
    output (1, 256, 8, 8)
    Linear view (the idea)Conv2d view (the code)
    operationflatten each patch, multiply by E256 filters of 16×16×3, stride 16
    weightsE: (768, 256)(256, 3, 16, 16) = E reshaped
    parameters196,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)
    3 · The [CLS] token

    The [CLS] token: one extra vector in front of the embeddings

    It is not a patch. [CLS] never went through E and has no pixels. It is a vector that lives inside the model, an 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.

    🎯 The whole trick: block after block, [CLS] collects into one single vector everything about the image that is useful to classify it. At the end the classifier reads only this vector: if it is not in [CLS], the head cannot see it.
    ① Attend. In every block, [CLS] looks at all the other tokens, like any token does. Its output is a weighted mix of what it reads (arcs = attention weights). Block after block, it turns into a summary of this image. (here the values are simply the patch colours)
    ② Read out. After the last block, only the [CLS] output goes into the MLP head, which produces the class scores (§6). The other 64 outputs are not used for classification, so [CLS] must carry everything the head needs to name the image.
    Learned from the whole dataset. The starting vector is shared by every image, so during training the gradients from all images shape it: it learns a good question to ask any picture. Then, by interacting with the patch tokens through the blocks, its output becomes specific to the input. It ends up carrying the image's “DNA”, a compact description the head can classify.
    4 · Positional embedding

    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.

    Why does this happen? \qQ\kK\T only builds a mixing matrix A (who listens to whom, how much), and A is used just to combine the values: \text{output}_i = \sum_j a_{ij}\, \vv_j. A depends on the token contents only, never on their place, because q, k, v are computed from each token on its own. So each patch brings the same term a_j \vv_j wherever it sits, and a sum does not care about order: \mathrm{Attn}(PX) = P\,\mathrm{Attn}(X).
    Above: the [CLS] output written out term by term, for both orders. Each column is one token j: its patch, its weight aj (purple bar) and its value vj. The grey wires connect each patch to where it moved.
    So what? Without extra information, the model cannot tell the real pizza from the scrambled one. We have to tell it where every patch was: that is the positional embedding.
    4 · Positional embedding

    How is it added? One vector per position, summed

    z_0 = [\,\cls;\ x^1E;\ \dots;\ x^NE\,] \;\mathbf{+}\; \Epos, \qquad \Epos \in \mathbb{R}^{(N+1)\times D}
    click a patch
    patch token xiE
    +
    position vector pi
    =
    input to the encoder
    16 of the 256 dimensions (labels = dimension index): the bars simply add up, element by element.
    X — patch tokens (65 × 256)
    depends on the image
    +
    P — positions (65 × 256)
    the same for every image
    =
    Z — encoder input (65 × 256)
    row 0 = [CLS], highlighted row = your patch
    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
    Added, not concatenated: D stays 256. In 256 dimensions both signals survive the sum (random high-dimensional vectors are almost orthogonal).

    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.

    5 · Multi-Head Attention

    Multi-head attention: the whole picture

    heads h:
    ① Input: the 65 tokens (64 patches + [CLS]), each a 256-number vector: X is (65, 256). Tokens run along the block, features go into the depth.
    ② Three projections: \qQ = W_Q X,\ \kK = W_K X,\ \vV = W_V X. Each uses all 256 input features and gives 256 new ones per token. In code they are one nn.Linear(256, 768).
    ③ Split into heads: cut each of Q, K, V along the features into h blocks of d = 256 / h. Every head keeps all 65 tokens. Nothing is computed, it is a reshape.
    ④ Attention in every head, in parallel: Z_i = \softmax\!\left(\tfrac{\qQ_i \kK_i\T}{\sqrt{d}}\right) \vV_i. The next two slides zoom into one head.
    ⑤ Merge and project: concatenate the h outputs along the features (the inverse of the split) → (65, 256), then WO = nn.Linear(256, 256) mixes the heads. Same shape in and out.
    5 · Multi-Head Attention

    Inside one head: how much does each query “like” each key?

    S = \qQ\,\kK\T(n×d)·(d×n) → (n×n)\text{score}(i, j) = \qq_i \cdot \kk_j = \sum_{c} \qq_i[c]\, \kk_j[c]
    hover a cell · circle size = |score|, orange > 0, blue < 0

    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.
    PyTorch: q @ k.transpose(-2, -1): (b, h, n, d)·(b, h, d, n) → (b, h, n, n)
    Why isn't the diagonal 1? score(i, i) = \qq_i \cdot \kk_i is not a token compared with itself: \qq_i = W_Q x_i and \kk_i = W_K x_i are two different views made by two different matrices, and the score is a raw dot product, not a normalised similarity. So a token can like itself a lot, a little, or not at all (see p3 vs p1).
    Try it: the two pepperoni patches p1 and p2 give each other the highest scores.

    Watch: 3Blue1Brown, Visualizing attention, a transformer's heart.

    5 · Multi-Head Attention

    Softmax, then a weighted sum of the values

    A = \softmax\!\left(\frac{S}{\sqrt{d}}\right)every row sums to 1Z = A\,\vV(n×n)·(n×d) → (n×d)
    Q and K only build a mixing recipe. Q·Kᵀ → softmax gives A: how much each token listens to each other token. A is then used for one thing only, to combine the values V. A is computed from the token contents alone, so it has no idea where a token sits: shuffle the tokens and the rows and columns of A are shuffled the same way, the same pairs keep the same weights, and every output just moves with its token. That is why attention is permutation-equivariant (§4). Try it ↓
    query:

    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.

    5 · Multi-Head Attention

    The result: every head looks for something

    \mathrm{Attention}(\qQ, \kK, \vV) = \softmax\!\left(\frac{\qQ\,\kK\T}{\sqrt{d}}\right)\vV
    Head A · 🎨 similar colour
    score = colouri · colourj
    Head B · 📍 my neighbours
    score = −distance(i, j)²
    Head C · ↔ my row
    score = −(rowi − rowj)²
    Click a patch = pick the query (yellow). Bright = high attention weight.   score multiplier
    Query — “what am I looking for?”
    Key — “what do I contain?” (how others find me)
    Value — “what I hand over if you attend to me”

    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.

    6 · Normalisation & MLP head

    How is it normalised? LayerNorm — and where it sits

    Transformer block × 8 x LN MHA + LN MLP + final LN [CLS] → MLP head residual ⊕residual ⊕
    LayerNorm comes before each sub-layer (“pre-norm”), plus once at the very end: 2 × 8 + 1 = 17 LayerNorms in our encoder.
    ⊕ residual: x + f(x). The block only adds a correction; the signal (and the gradient) can flow straight through all 8 blocks.
    MLP: Linear(256 → 1024) → GELU → Linear(1024 → 256), applied to each token on its own. Attention mixes tokens; the MLP mixes features.
    \mathrm{LN}(x) = \gamma \odot \frac{x - \mu}{\sqrt{\sigma^2 + \varepsilon}} + \beta, \qquad \mu = \frac{1}{D}\sum_i x_i, \qquad \sigma^2 = \frac{1}{D}\sum_i (x_i - \mu)^2\gamma, \beta \in \mathbb{R}^D learned (start at 1 and 0)
    one token with 8 features — drag the bars!
    γ β
    LN(x)
    same colour = normalised together

    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.

    6 · Normalisation & MLP head

    The MLP head: where the [CLS] token finally goes

    z = \mathrm{LN}(z_L)_{[:,\,0]} \;\longrightarrow\; \text{logits} = z\,W_{\text{head}} + b,\ \ W_{\text{head}} \in \mathbb{R}^{D\times K} \;\longrightarrow\; p = \softmax(\text{logits})
    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.
    → The lab

    Put it together

    Complete the formula of one attention head:
    softmaxQ
    D = 256 fixed. We change 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).

    \underbrace{3D^2 + 3D}_{\texttt{qkv}} \;+\; \underbrace{D^2 + D}_{\texttt{out\_proj}} \;=\; 4D^2 + 4D \;=\; 263{,}168 \quad (D = 256)

    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.

    → The lab

    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.

    MASK_RATIO

    🎯 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

    Pairs of photos and attention maps: for a bird, a toothbrush, a palace, giraffes, a sailboat, a bicycle, a dog on an armchair and a plane, the [CLS] attention of the last-layer heads lights up exactly the object.

    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 🎯

    Build MultiHeadAttention 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.
    → The lab

    Cheat sheet (lab config, ViT with n = 65)

    stepwhatshape
    imagenormalised RGB(1, 3, 128, 128)
    patch embedConv2d(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)
    + positionsx + pos_embed (learned, added)(1, 65, 256)
    qkvnn.Linear(256, 768)(1, 65, 768)
    split heads'b n (three h d) -> three b h n d'3 × (1, 8, 65, 32)
    scoresQ Kᵀ · d−½   (d = 32)(1, 8, 65, 65)
    softmaxover the keys (last axis): every row sums to 1(1, 8, 65, 65)
    weighted sumA · V(1, 8, 65, 32)
    merge heads'b h n d -> b n (h d)'(1, 65, 256)
    out_projnn.Linear(256, 256)(1, 65, 256)
    blockx + MHA(LN(x));   x + MLP(LN(x))(1, 65, 256)
    headfinal LN → x[:, 0] → nn.Linear(256, K)(1, K)

    Play it again

    References & further reading

    🎬 ViT in a nutshell60 s · no voice-over · untrained toy weights: the class scores are illustrative