Vision Transformers
Patch embedding, positional encodings, ViT vs CNN inductive bias, DeiT, Swin windows and CLIP contrastive pretraining on image–text pairs.
From MAE to a sequence of patches
The masked autoencoder of Self-supervised learning needed an encoder that sees an image as a set of patches and can drop most of them. That encoder is the Vision Transformer (ViT): cut the image into patches, turn each into a vector, and process the sequence with the Transformer encoder that the NLP course builds for text. Almost nothing in it is specific to images — strength and weakness at once.
A convolutional network builds assumptions into every layer: locality, weight sharing, translation equivariance (see Convolution). Those are an inductive bias: they restrict the functions the network can learn to ones plausible for images, so a CNN learns from few examples. The price is slow travel of information — distant pixels interact only after depth grows the receptive field. Self-attention makes the opposite choice: every token attends to every other in one layer, with weights from content. Nothing tells the layer that neighbours are related; it must learn that from data.
Patch embedding and the class token
Key idea. Treat an image like a sentence. Cut it into a grid of patches, map each flattened patch with one shared linear layer , add a learned position vector, prepend a class token, and run a standard pre-norm Transformer encoder. The class token’s output is the image representation.
For there are patches. The input sequence is
Each block is multi-head self-attention then an MLP, each with layer norm before it and a residual around it. A linear head on classifies.
The patch embedding is exactly a convolution with kernel and stride . A RGB image with gives patches of values and tokens — “an image is worth words”. Halving to yields tokens and attention about times more expensive.
Position embeddings
Attention treats its input as a set. Without positions, permuting patch tokens permutes patch outputs the same way, and the class token’s output does not change at all: a bag-of-patches classifier that cannot tell a digit from the same patches rearranged.
ViT adds learned absolute position embeddings, one vector per index, initialized at random. They carry no two-dimensional structure at the start; after training, nearby patches get similar embeddings. Ablations on ViT-B/16: no positions , learned 1-D , 2-D or relative about under a 5-shot probe. Positions matter; the encoding recipe hardly does. To fine-tune at higher resolution, is kept, the sequence grows, and the embeddings are interpolated in 2-D onto the new grid — together with the cut into patches, the only place the model is told that the input is two-dimensional.
Inductive bias and data
A ViT has much less image-specific structure than a CNN. Only the MLPs are local and shared; attention is global, and all spatial relations must be learned. Trained on ImageNet’s million images, ViTs trailed ResNets of similar size: for ViT-B/16, and the larger ViT-L/16 did worse. With ImageNet-21k the sizes matched; only with JFT-300M did scale pay off — ViT-H/14 reached after fine-tuning. In the authors’ words, “large scale training trumps inductive bias”.
The same trade-off on digits: a tiny ViT (, , blocks) and a 7-layer residual CNN, same AdamW recipe. Test accuracy with / / training images: ViT / / , CNN / / . Both fit training almost perfectly; the gap is generalization — nine points with little data, two with more.
DeiT and Swin windows
DeiT closed much of the ImageNet gap with training, not architecture: strong augmentation, stochastic depth, AdamW, epochs — for ViT-B on ImageNet-1k alone. A distillation token sits beside the class token; its head learns the teacher’s hard label on the augmented view while the class token learns the true label. With a convolutional teacher, DeiT-B reached , above the teacher: the student inherits part of the inductive bias through predictions. Distillation in general returns in Model compression.
Swin restores locality and hierarchy for dense tasks. Attention runs inside non-overlapping windows (); stages merge groups of tokens so feature maps sit at , , , of the input, like a ResNet backbone. Global attention cost becomes for windows — at Swin-T’s first stage, about cheaper. Alternate blocks shift the windows by so information crosses the old borders.
CLIP: image and text
Contrastive learning needs two views that share content. CLIP takes an image and its web caption as the two views. An image encoder and a text encoder map a batch of pairs to normalized embeddings; the matrix of cosine similarities, divided by a temperature, is trained with symmetric cross-entropy — each image picks its caption among , each caption its image.
A trained CLIP classifies zero-shot: encode prompts A photo of a {label}. and pick the prompt nearest the image embedding. Similarities , , at become logits , , and a confident softmax. ViT-L/14 at resolution reached top-1 on ImageNet zero-shot — the accuracy of the original supervised ResNet-50 — without using ImageNet’s training labels. The same embeddings feed semantic search and condition text-to-image diffusion models in Generative Models.
CNN or ViT, and what comes next
Neither family dominates. Little data and no pretraining favour CNNs; large data or a strong checkpoint favour ViTs. Global attention is quadratic, so high-resolution dense tasks favour CNNs or Swin-style windows. Attention links distant patches in one layer; a CNN needs depth. CNNs forgive a sloppy recipe; ViTs need careful rates, warm-up, decay and augmentation.
CNNs and ViTs alike reach high accuracy on test images drawn like their training images. The next topic shows how fragile that accuracy is: a perturbation of the pixels too small to see, aimed by the network’s own gradient, flips almost any trained classifier — and training on such perturbations is the main defence.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Go deeper — optional
Code and labs do not count toward the main percentage or the certificate.
- ViT: patch embedding dimensionsoptional
Count patches, CLS token, and projection parameters for ViT-B/16. Self-check in the notebook.
~15 min · easier on a computer · Vision Transformers topic read.
Self-check in the notebook — not part of mastery or the certificate.
Answers are saved on the server and tied to this browser until you sign in.