Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.An image as a sentence of patches
A Vision Transformer cuts a picture into a grid of small squares, treats each square like a word and feeds the “sentence” of squares to a Transformer. Attention lets any patch look at any other, so global context is available from the first layer. Unlike a CNN, a ViT is not told that nearby pixels belong together or where each patch sits. It learns that from data and from position embeddings, which is why it needs lots of training images. The demo counts patches and attention cost for different patch sizes.
ViT backbones power modern perception: satellite imagery, inspection cameras and vision–language models for robots all build on them.
- 1. ViT treats an image as…
- 2. ViT learns spatial structure from…
- 3. ViT beats CNNs most clearly when…
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.By hand
- Patching:
- a 224 × 224 × 3 image with 16 × 16 patches gives 14 × 14 = 196 patches of 768 values each;
- the patch embedding is linear, equivalent to a 16 × 16 convolution with stride 16, with 590,592 parameters for d = 768;
- adding a class token gives 197 tokens.
- Position embeddings:
- learned 1-D embeddings, one per token (197 × 768);
- for fine-tuning at 384 × 384 the grid grows from 14 × 14 to 24 × 24, and the embeddings are interpolated in 2-D.
- Encoder: standard pre-LN Transformer layers. The class token’s final state, or the mean of all tokens, goes to an MLP head.
- Sizes:
- ViT-B/16: 12 layers, d = 768, 86,567,656 parameters with a 1000-class head;
- ViT-L/16: 24 layers, d = 1024, about 304 M;
- ViT-H/14: 632 M.
- Cost: attention over 197 tokens is 38,809 scores per head. Patch size 8 gives 785 tokens and 616,225 scores, about 16 times more.
- 1. Tokens for a 224 image with 16-pixel patches (with class token):
- 2. Patch embedding parameters (16 × 16 × 3 → 768):
- 3. Halving the patch size multiplies attention cost by about…
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.ViT in code
Exercise 1.
- Patchifying a 4 × 4 image with 2 × 2 patches produced patches row by row.
- Token and parameter counts matched ViT-B/16: 197 tokens and 86,567,656 parameters.
Practice.
- Use
timm(vit_base_patch16_224) or Hugging FaceViTForImageClassification. Fine-tune with a higher resolution and interpolated position embeddings for better accuracy. - Training from scratch on modest data needs strong augmentation and regularisation (RandAugment, Mixup, CutMix, stochastic depth), as in DeiT (E12-23), or a hybrid CNN stem.
- Self-supervised pre-training (MAE, DINO; E16) gives strong ViT backbones without labels.
import timm
model = timm.create_model("vit_base_patch16_224", pretrained=True, num_classes=5) # new head for 5 defect types
x = torch.randn(8, 3, 224, 224)
logits = model(x) # patches → tokens → encoder → class token → head- 1. A common ViT library:
- 2. For a higher fine-tuning resolution, position embeddings are…
- 3. Training ViT from scratch on modest data needs…
Level 3: Advanced
★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.Theory
Inductive bias.
- CNNs build in locality (small kernels) and translation equivariance (shared weights), strong priors that help with little data.
- ViT builds in almost none: patches interact globally from the first layer, and spatial relations must be learned through position embeddings.
- With enough data this flexibility pays off. Dosovitskiy et al. found ViT trailed ResNets on ImageNet-1k alone but outperformed them when pre-trained on ImageNet-21k or JFT-300M.
Position embeddings.
- Self-attention over patch tokens is permutation-equivariant (E12-2), and mean or class-token pooling is invariant.
- Without position embeddings, a ViT sees a bag of patches: it can answer “how many” but not “where”.
- Learned 1-D embeddings end up encoding 2-D structure: nearby patches get similar embeddings.
What attention sees. Attention distance grows with depth: some heads attend locally in early layers, others globally even in the first layer, a mix CNNs cannot express early.
- 1. CNN inductive biases include…
- 2. Without position embeddings a ViT can answer…
- 3. ViT outperformed ResNets when pre-trained on…
Level 4: Expert
★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.What do position embeddings give a ViT?
History.
- A. Dosovitskiy, L. Beyer, A. Kolesnikov, D. Weissenborn, X. Zhai, T. Unterthiner, M. Dehghani, M. Minderer, G. Heigold, S. Gelly, J. Uszkoreit and N. Houlsby, “An image is worth 16x16 words: Transformers for image recognition at scale” (ICLR 2021).
- DeiT (2021) made ViT data-efficient, Swin (2021) added hierarchy and windows, and MAE (2022) made self-supervised ViT pre-training simple.
Exercise 2.
- Images: 16 × 16 noise images with bright 4 × 4 squares, cut into 16 patches of 4 × 4.
- Tasks:
- count: are there 3 squares or 1?
- layout: is the single square in the top half?
- Model: a one-layer ViT (d = 32, 4 heads, mean pooling), with or without learned position embeddings, trained for 300 steps (gradients checked numerically).
| task | without position embeddings | with position embeddings |
|---|---|---|
| count | 0.998 | 1.000 |
| layout | 0.510 | 0.994 |
- Counting needs no positions. Mean-pooled attention over patches is permutation-invariant, and counting is too.
- Layout is impossible without position embeddings: shuffling patches does not change the model’s output, so top and bottom cannot be told apart (chance 0.5).
- With learned position embeddings, the same model solves the layout task. This is the information a CNN gets for free from its structure and a ViT must learn.
ViT in AI, robotics and aerospace
- Remote sensing: ViTs pre-trained on large satellite archives segment and classify land use, damage and ships.
- Inspection: fine-tuned ViTs detect surface defects from few labelled images, given good pre-training.
- Robotics: vision–language–action models use ViT encoders to turn camera images into tokens for policies.
References
- A. Dosovitskiy et al. (2021). “An image is worth 16x16 words: Transformers for image recognition at scale.” Proc. ICLR.
- H. Touvron et al. (2021). “Training data-efficient image Transformers and distillation through attention.” Proc. ICML.