Skip to content
BIASED

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 P×PP \times P patches, map each flattened patch with one shared linear layer EE, 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 x∈RH×W×Cx \in \mathbb R^{H \times W \times C} there are N=HW/P2N = HW / P^2 patches. The input sequence is

z0=[ xclass;  xp1E;  … ;  xpNE ]+Epos.z_0 = \big[\, x_{\mathrm{class}};\; x_p^1 E;\; \dots;\; x_p^N E \,\big] + E_{\mathrm{pos}}.

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 LN⁡(zL0)\operatorname{LN}(z_L^0) classifies.

The patch embedding is exactly a convolution with kernel and stride PP. A 224×224224 \times 224 RGB image with P=16P = 16 gives N=196N = 196 patches of 768768 values and 197197 tokens — “an image is worth 16×1616 \times 16 words”. Halving PP to 88 yields 785785 tokens and attention about (785/197)2≈15.9(785/197)^2 \approx 15.9 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 0.6140.614, learned 1-D 0.6420.642, 2-D or relative about 0.6400.640 under a 5-shot probe. Positions matter; the encoding recipe hardly does. To fine-tune at higher resolution, PP 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 1.31.3 million images, ViTs trailed ResNets of similar size: 77.9%77.9\% 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 88.55%88.55\% after fine-tuning. In the authors’ words, “large scale training trumps inductive bias”.

The same trade-off on digits: a tiny ViT (P=4P = 4, D=32D = 32, 33 blocks) and a 7-layer residual CNN, same AdamW recipe. Test accuracy with 100100 / 300300 / 10781078 training images: ViT 0.8430.843 / 0.9250.925 / 0.9670.967, CNN 0.9370.937 / 0.9760.976 / 0.9870.987. 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, 300300 epochs — 81.8%81.8\% 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 83.4%83.4\%, 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 M×MM \times M windows (M=7M = 7); stages merge 2×22 \times 2 groups of tokens so feature maps sit at 1/41/4, 1/81/8, 1/161/16, 1/321/32 of the input, like a ResNet backbone. Global attention cost 4hwC2+2(hw)2C4hwC^2 + 2(hw)^2 C becomes 4hwC2+2M2hwC4hwC^2 + 2M^2 hw C for windows — at Swin-T’s first stage, about 13.8×13.8\times cheaper. Alternate blocks shift the windows by ⌊M/2⌋\lfloor M/2 \rfloor 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 NN pairs to normalized embeddings; the N×NN \times N matrix of cosine similarities, divided by a temperature, is trained with symmetric cross-entropy — each image picks its caption among NN, 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 0.300.30, 0.250.25, 0.200.20 at 1/τ=1001/\tau = 100 become logits 3030, 2525, 2020 and a confident softmax. ViT-L/14 at resolution 336336 reached 76.2%76.2\% 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.

Full notes

Answers are saved on the server and tied to this browser until you sign in.