Advanced level · Module 5: Attention Mechanisms and Vision Transformers · Lesson 2 of 3
How Vision Transformers See Images
Learners follow an image through a Vision Transformer: patches, linear embeddings, position embeddings, a class token and transformer encoder layers.
In this lesson you will
- Describe each step of a Vision Transformer
- Compute patch counts and sequence lengths
Key concepts
image patches (16×16)patch embeddingposition embeddingclass tokentransformer encoder
The lesson
A Vision Transformer (ViT) cuts the image into fixed-size patches (for example 16 × 16 pixels), flattens and linearly projects each patch into a vector, adds position embeddings so the model knows where each patch came from, and prepends a learnable class token.
The sequence passes through transformer encoder layers with multi-head self-attention, so every patch can attend to every other patch from the first layer. The class token's final vector feeds the classifier.
A 224 × 224 image with 16 × 16 patches gives 196 patches plus the class token, a sequence of 197. Attention cost grows with the square of sequence length, which makes high-resolution ViTs expensive.
Step by step
- Compute the number of patches for 224 × 224 and 384 × 384 images.
- Implement patch extraction with tensor reshaping.
- Inspect the structure of torchvision's vit_b_16.
- Read the ViT paper abstract and summarise its main finding about data size.
Practice activity
Write an annotated walkthrough of a ViT forward pass with verified shapes.
Expected result: Correct shapes at each step and a clear explanation.
Check your understanding
-
How many 16×16 patches does a 224×224 image have?
Show answer
196.
-
Why are position embeddings needed?
Show answer
Self-attention does not know where each patch came from.
Further learning
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.