Lesson 5.7advanced2 h 30 min

Vision Transformers

Patches as tokens — and what happens when you remove the convolutional prior

In 2020 the Vision Transformer showed that a plain transformer encoder, fed 16×1616\times16 image patches as tokens, matches or beats the best CNNs — given enough data. ViTs now sit inside CLIP, SAM, DINOv2 and every frontier multimodal model, so understanding patch embedding, attention over patches and the data/inductive-bias trade-off is essential for 5.8 Self-supervised and contrastive learning, 8.10 Multimodal models and for appreciating what convolutions were doing all along. The full attention mathematics arrives in 7.2 Scaled dot-product and multi-head attention, fully derived; here you need the mechanism, the shapes and the design space.

You'll be able to

  • Compute the token sequence shape and parameter count of a ViT patch embedding
  • Explain self-attention over patches at the level needed to read ViT, and where the quadratic cost comes from
  • Contrast CNN and ViT inductive biases and explain DeiT's data-efficiency fix
  • Describe Swin's windowed/shifted attention and hierarchical features
  • Choose between convnets, ViTs and hierarchical transformers for a given constraint

Key ideas

  1. Patchify: N = HW/P² tokens, each P²C → D via a linear map that equals a conv with kernel = stride = P; ViT-B/16 has 196 patches + [CLS] of width 768.
  2. Each layer: pre-norm multi-head self-attention + MLP with residuals — the same encoder as text transformers; cost O(N²D).
  3. ViT removes convolutional inductive biases, so it needs more data: it trails ResNets on ImageNet-1K alone but wins with ImageNet-21K/JFT pretraining.
Show 4 more key ideas
  1. DeiT recovered data efficiency with heavy augmentation/regularization and a distillation token from a CNN teacher (81.8% / 83.4% on ImageNet-1K).
  2. Swin builds a hierarchy: 7×7 windowed attention (linear cost), shifted windows for cross-window flow, patch merging between stages — a drop-in backbone for detection/segmentation.
  3. Position embeddings are learned or relative; interpolate them when changing resolution.
  4. In 2026 the best transferable vision encoders are pretrained ViTs (DINOv2, CLIP); convnets remain strong for small data and edge latency.

Suggested path through this lesson