4.2 Vision Transformers
Non-overlapping patches, a linear map, positions, no causal mask.
These notes match the lecture slides. Use (slides) on the course hub for the deck.
A vision transformer (ViT) is the Week 3 block on patches instead of words. Once an image is a sequence, every later trick in this course (attention, positions, [CLS], CLIP’s image tower) applies. The recipe is patchify, linear map, positions, no causal mask. You do not train a ViT from random pixels in this hour; you learn to count tokens and reuse the stack.
1. What a vision transformer (ViT) is
A ViT treats an image as a sequence of patches. Split a image into non-overlapping patches, flatten each patch, and map it with a linear layer to width . Add a learned [CLS] if you classify from one vector, and add positions (a 1-D index, or row–column). Then run a transformer without a causal mask: every patch may look at every patch. Attention without positions is a bag of tiles.

The sequence length for a tiled image is
A CNN shares a small kernel and builds a hierarchy. A ViT sees global context in layer 1, at cost. For a 224 image and , , which is a short paragraph.
Flattening a patch is numbers. That linear map is the same as a convolution with kernel , stride , and output channels. RGB is just three extra channels in the flatten.
Do not count overlapping CNN windows and then write . ViT patches tile.
2. Why we use it
CNNs were the older default for images. ViT shows that the same block you already use for language can mix patches globally from layer 1. That matters for this course because CLIP’s image tower is often a ViT, and every later “freeze the vision encoder” sentence is freeze patch embed plus transformer.
Scale is the other reason. Dosovitskiy et al. (2021) found that ViTs need more data than ResNets if trained from scratch, and they shine when the image set is large. In this course you will almost always start from a pretrained ViT (CLIP’s image tower, or a Hugging Face checkpoint), not from random pixels. A tiny medical set is the wrong place to train a ViT from scratch.
A smaller patch gives more tokens and a heavier map. Patch size is a method knob, not a default you ignore.
3. Architecture
The boxes are the Week 3 encoder, with a patch embedding instead of a token embedding.
- Cut the image into non-overlapping patches and flatten each one.
- Map with a linear layer (for RGB, ).
- Optionally prepend a learned
[CLS]token. - Add positional embeddings. Without them, top and bottom are the same bag.
- Run encoder blocks: LayerNorm, multi-head self-attention, MLP, residuals. No causal mask.
- Classify from
[CLS]or from a mean-pool of the patch tokens, then a linear head.

Unlike GPT, a classifier ViT is bidirectional. There is no future patch to hide. Hybrid models put a small CNN stem first, then a transformer on a coarser grid. Same idea, fewer tokens.
When you later freeze “the vision encoder,” you are freezing patch embed + transformer. You are not freezing a ResNet unless the checkpoint says so.
4. How it works, step by step
Lab 4 flattens patches in numpy. No convolution is required for the cartoon. Do one flatten on the board before the lab.
- Count patches. Image , , one channel . Standard ImageNet: , , . Plus
[CLS]: 197 tokens. - Flatten one tile. Top-left patch becomes .
- Linear map. A matrix with first row all sends that tile to a 2-D token whose first coordinate is the mean .
- Add positions and
[CLS]. The transformer now sees a sequence, not a bag. - Attend without a causal mask. Every patch may look at every patch. One attention map with
[CLS]has scores per head. - Pool and classify, or pass the sequence into CLIP as the image tower.
You do not implement ViT from random init in this course. You count patches, you add positions, you reuse Week 3.
A smaller patch ( on 224) gives tokens and a heavier map. That is why 16 is the default: enough spatial pieces, still a short sequence.
5. Mathematical formulas
For patch size and image , the tiled sequence length is
when both axes divide. With a [CLS] token the transformer sees positions.
Let be the matrix of flattened patches (one row per tile). A linear patch embedding and positions give
then the usual encoder stack. The patch map is equivalent to a convolution with kernel size , stride , and output channels.
Attention cost is quadratic in the number of tokens: scores per head if you include [CLS].
6. Positive points and negative points
Positive.
- Global mixing from layer 1, with the same encoder code as language.
- A pretrained ViT (CLIP’s image tower, a Hugging Face checkpoint) is the default backbone later in the course.
- Patch size lets you trade spatial detail against sequence length.
Negative.
- Attention is quadratic in the number of patches.
- From-scratch ViTs want large image sets or a strong recipe; small medical sets prefer a pretrained tower or a CNN.
- Forgetting positions makes top and bottom indistinguishable.
- A GPT causal mask on patches hides a “future” that does not exist.
When not to. Do not train a ViT from scratch on 800 scans. Start from a pretrained tower. Do not count overlapping CNN windows and then write .
7. Teaching this note
~16 minutes. Count patches on a square image, flatten one toy patch, add [CLS]+positions, then “same block as Week 3, no causal mask.” Play the patch embedding stretch of the Umar Jamil video. Lab 4 will flatten patches in numpy; do one flatten on the board first. Do not train a ViT in this block.
8. Worked example
Image , , 1 channel. Then patches. Top-left patch
flattens to . A linear map with first row all sends it to a 2-D token whose first coordinate is the mean .

Standard ImageNet: , , . Plus [CLS]: 197 tokens. Attention map scores per head.

A smaller patch ( on 224) gives tokens and a heavier map. That is why 16 is the default: enough spatial pieces, still a short sequence.
You do not implement ViT from random init in this course. You count patches, you add positions, you reuse Week 3.
9. Where students get stuck
- Using overlapping CNN-style windows and then miscounting .
- Forgetting positions so the model cannot tell top from bottom.
- Putting a GPT causal mask on patches (there is no “next patch” to hide).
- Training a ViT from scratch on a tiny medical set.
10. Video
Watch Umar Jamil: Vision Transformer / VLM walkthrough.
Pause on image patches as tokens, the linear patch embedding, and positional encodings. That is the ViT; CLIP/BLIP wrap extra towers around it.
11. Practice
-
Count tokens for a image, patch .
-
Why add positions if attention already sees all patches?
-
A medical image dataset with 800 scans: from-scratch ViT or a pretrained tower? Why?
-
For , , include a
[CLS]token. How many tokens enter the transformer? How many scores in one attention map? -
A RGB image, . Flatten one patch: how many numbers before the linear map? How many patches in the whole image?
-
Why does a classifier ViT not use a causal mask?
-
The patch linear map is a convolution with which kernel size and stride?