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 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
- 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.
- Each layer: pre-norm multi-head self-attention + MLP with residuals — the same encoder as text transformers; cost O(N²D).
- 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
- DeiT recovered data efficiency with heavy augmentation/regularization and a distillation token from a CNN teacher (81.8% / 83.4% on ImageNet-1K).
- 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.
- Position embeddings are learned or relative; interpolate them when changing resolution.
- 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
From pixels to tokens
A transformer consumes a sequence of vectors. ViT turns an image into one by patchifying: split an image into non-overlapping patches, flatten each into a vector of length , and project it linearly to the model width :
For ViT-B/16 at : , so patches, each a -dimensional vector, projected to . The projection is exactly a convolution with kernel size 16 and stride 16 (5.1 Convolution: the operation and its math) — K parameters. A learnable [CLS] token is prepended (197 tokens total) and a learned position embedding is added so the model knows where each patch came from (attention itself is permutation-equivariant; see 7.3 Positional information: sinusoidal, learned, RoPE, ALiBi).
Just enough attention
Each transformer layer lets every token gather information from every other token. Tokens are projected to queries, keys and values; attention weights are the softmax of scaled query–key dot products (1.1 Vectors, dot products and norms), and each output is the weighted average of values:
Several heads do this in parallel in different subspaces, a position-wise MLP follows, and both are wrapped in residual connections (5.3 Architectures: LeNet → AlexNet → VGG → Inception → ResNet → EfficientNet → ConvNeXt) with LayerNorm in front (pre-norm). That is the entire ViT encoder — identical to the text transformer encoder of 7.1 Attention Is All You Need: the big picture, which is why one architecture now serves both modalities. ViT-B/16: 12 layers, , 12 heads, MLP width 3072, 86 M parameters, 17.6 GFLOPs at . The cost of attention is : fine for 196 tokens, painful at images (4,096 tokens with ) — the motivation for Swin and for patch sizes of 14–32.
Intuition. A convolution lets a pixel see its neighbors. Attention lets a patch see every other patch from layer one, with weights it chooses per image. More flexible, but it has to learn that nearby patches usually matter most.
Inductive bias versus data
CNNs hard-wire locality, translation equivariance and a multi-scale hierarchy (5.1 Convolution: the operation and its math). ViT hard-wires almost nothing beyond the patch grid: position embeddings are learned, and only the MLP is local. The original paper's central finding follows: trained on ImageNet-1K alone (1.3 M images), ViT trails ResNets; pretrained on ImageNet-21K (14 M) it matches them; on JFT-300M it wins (ViT-H/14 at 88.55% top-1). With enough data, learned biases beat designed ones. Inspecting trained models shows why this can work: some heads in the first layer attend locally (learning convolution-like behavior) while others are already global, and "Do Vision Transformers See Like CNNs?" found ViTs keep more uniform representations across depth and integrate global information much earlier.
DeiT (2021) closed the data gap without extra images: a heavy augmentation and regularization recipe (RandAugment, mixup, CutMix, stochastic depth, repeated augmentation) plus distillation through a dedicated distillation token that learns from a strong CNN teacher (RegNetY). DeiT-B reached 81.8% top-1 (83.4% distilled) on ImageNet-1K alone — the recipe that ConvNeXt later borrowed to modernize ResNets (5.3 Architectures: LeNet → AlexNet → VGG → Inception → ResNet → EfficientNet → ConvNeXt).
Hierarchical ViTs: Swin
Classification tolerates a single grid, but detection and segmentation (5.5 Object detection, 5.6 Segmentation) want multi-scale features and high resolution. Swin Transformer restores a CNN-like pyramid: start with patches, compute attention only inside non-overlapping windows (cost linear in image size), shift the windows by half a window in alternate layers so information crosses window borders, and merge patches between stages to halve resolution and double channels. The result is a drop-in backbone for FPN-based detectors; Swin-L reached 87.3% ImageNet top-1 and 58.7 box AP on COCO at release. Relative position biases replace absolute embeddings.
Position information in two dimensions
Options: learned 1-D embeddings per patch index (ViT; they still learn a 2-D structure), 2-D sinusoidal embeddings, relative position biases added to attention logits (Swin), and 2-D rotary embeddings in recent models (7.3 Positional information: sinusoidal, learned, RoPE, ALiBi). When fine-tuning at a higher resolution than pretraining, interpolate the position embeddings to the new grid — a standard trick that works surprisingly well.
Choosing in 2026
| constraint | good default |
|---|---|
| small dataset, no large-scale pretraining available | ConvNeXt or ResNet fine-tuned (5.4 Transfer learning and training CNNs in practice) |
| best features for transfer / multimodal / retrieval | a pretrained ViT (DINOv2, CLIP/SigLIP — 5.8 Self-supervised and contrastive learning, 8.10 Multimodal models) |
| dense prediction at high resolution | Swin / hierarchical ViT or ConvNeXt with FPN |
| edge devices, strict latency | MobileNet/EfficientNet-class convnets or small distilled ViTs |
The architecture war ended in a draw on ImageNet (ConvNeXt vs Swin), but pretraining tilted the field: the strongest general-purpose vision encoders are ViTs because they scale smoothly with data and compute and share machinery with language models, making multimodal fusion natural.
import timm, torch
vit = timm.create_model("vit_base_patch16_224", pretrained=True)
x = torch.randn(1, 3, 224, 224)
tokens = vit.patch_embed(x) # (1, 196, 768): 196 patch tokens of width 768
print(tokens.shape, sum(p.numel() for p in vit.parameters()) / 1e6, "M params")
Where this shows up later
- The full transformer block and attention math — 7.1 Attention Is All You Need: the big picture, 7.2 Scaled dot-product and multi-head attention, fully derived; positional encodings — 7.3 Positional information: sinusoidal, learned, RoPE, ALiBi.
- Self-supervised ViTs (DINO, MAE) and contrastive pretraining — 5.8 Self-supervised and contrastive learning; CLIP and vision-language models — 8.10 Multimodal models.
- SAM's image encoder is a ViT — 5.6 Segmentation; Vision Transformers as diffusion backbones (DiT) — 8.9 Generative models II: Diffusion and flow matching.
Common pitfalls (4)
- Training a ViT from scratch on a small dataset and concluding transformers are bad for vision — use pretrained weights or a DeiT-style recipe.
- Forgetting that attention cost grows with the square of the token count: doubling image resolution quadruples tokens and multiplies attention cost by 16.
- Changing the input resolution without interpolating position embeddings (timm does it for you only if you ask).
- Treating [CLS] pooling as the only option — mean pooling over patch tokens is often as good or better for transfer.
Recap: all 7 key points
- 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.
- Each layer: pre-norm multi-head self-attention + MLP with residuals — the same encoder as text transformers; cost O(N²D).
- ViT removes convolutional inductive biases, so it needs more data: it trails ResNets on ImageNet-1K alone but wins with ImageNet-21K/JFT pretraining.
- DeiT recovered data efficiency with heavy augmentation/regularization and a distillation token from a CNN teacher (81.8% / 83.4% on ImageNet-1K).
- 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.
- Position embeddings are learned or relative; interpolate them when changing resolution.
- In 2026 the best transferable vision encoders are pretrained ViTs (DINOv2, CLIP); convnets remain strong for small data and edge latency.
Watch
Walks through patch embedding, the data-vs-inductive-bias result and the attention visualizations.
Read
Exercises
- Shapes and parameters of a ViT
For ViT-L/16 (, 24 layers, 16 heads, MLP 4096) at and : compute the number of tokens, the patch-embedding parameters, the per-layer parameter count () and the attention FLOPs ratio between the two resolutions. Expected: 196 vs 576 tokens; attention cost ratio .
- Patch embedding two ways
Implement patchify + linear projection with
tensor.unfold/reshape and separately withnn.Conv2d(3, D, 16, stride=16)initialized with the same weights. Verify outputs match to . - Attention maps of a pretrained ViT
Load a pretrained ViT (timm or Hugging Face), register a hook on the last layer's attention, and visualize the [CLS] token's attention over patches for 5 images as a heatmap over the image. Compare with a DINO ViT if available — DINO's maps often look like segmentations (5.8 Self-supervised and contrastive learning).
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →