Vision Transformers
Patches as tokens, and what inductive bias buys.
A vision transformer throws away almost everything convolution assumes about images: cut the picture into patches, treat them as words, and let attention learn which patches matter to which. Trained on enough data it matches or beats convolutional networks, and the reasons say something general about inductive bias: what it buys, what it costs, and how data can replace it.
What you’ll learn
- Define the ViT architecture, show that patch embedding is a strided convolution, and compute its token count and cost.
- Prove that self-attention without position information is permutation-equivariant, and sketch why attention with relative positions can express any convolution.
- Prove that invariance shrinks a hypothesis class's VC dimension, and weigh the evidence on inductive bias versus data scale.
- Explain masked autoencoders and DINO as self-supervised pretraining for vision transformers.
Patches as tokens
The patch embedding is a convolution in disguise: applying the same linear map to every non-overlapping patch is a convolution with output channels, kernel size and stride , and that is how it is implemented. For images and there are patch tokens plus the class token. The paper's three sizes were ViT-Base (12 layers, , 86 million parameters), ViT-Large (24 layers, , 307 million) and ViT-Huge (32 layers, , 632 million); Attention & Transformers covers the block itself.
Per layer, the projections and the MLP (of width ) cost about multiply–adds and the attention scores and weighted sums about . For ViT-B/16 at , with and , the quadratic term is only about 4% of a layer, and the whole network costs about 17.5 billion multiply–adds per image. Attention's share grows with resolution.
A ViT on images: you halve the patch size from 16 to 8. By what factor does the cost of computing the attention scores grow? Ignore the class token.
Show the answer
16 ×
goes from 196 to 784, four times as many tokens, and costs : a factor of 16, while the projections and MLP grow only fourfold. Small patches buy resolution at a quadratic price, which is why hierarchical and windowed designs exist.
What attention assumes, and what it can express
Permuting the tokens permutes the rows and columns of the score matrix together:
A row-wise softmax commutes with permuting the rows and permuting the entries of every row in the same way, , and :
So without a ViT sees an image as a bag of patches: shuffling the patches shuffles the patch outputs, and the class token's output, which attends to all of them, does not change at all. All two-dimensional structure must enter through the position embeddings; ViT's learned one-dimensional embeddings turned out to encode rows and columns on their own.
A convolution, by contrast, hard-codes locality and weight sharing and is equivariant to translations; Convolutional Networks in Depth proves that the linear translation-equivariant maps are exactly the convolutions. Is attention strictly more expressive? With relative position information, yes:
Give each head one kernel offset (nine heads for a kernel), and let its attention logit from query pixel to key pixel depend only on the offset :
That is an inner product with the three-dimensional relative encoding , plus a constant the softmax ignores. As the softmax concentrates on , so head copies the pixel at offset :
The output projection sums the heads with learned matrices, which is precisely a convolution whose weight at offset is :
So the gap between ViTs and CNNs is not what they can represent but what they prefer. A CNN starts local and must build global interactions over depth; a ViT starts global and must learn locality from data. Trained ViTs partly do: in early layers some heads attend locally and others globally, and the average attention distance grows with depth (Dosovitskiy et al., 2021; Raghu et al., 2021).
You shuffle the 196 patch embeddings of an image and apply the same shuffle to their position embeddings before the transformer. What happens to the ViT's prediction?
- It changes unpredictably
- It becomes uniform over the classes
- It is unchanged only if the image is symmetric
- It is unchanged: the input is the same set of (patch + position) tokens, and the class token's output is permutation-invariant
Show the answer
D. It is unchanged: the input is the same set of (patch + position) tokens, and the class token's output is permutation-invariant
Each token is a patch embedding plus its own position embedding, so shuffling both together merely permutes the tokens. By equivariance the patch outputs are permuted, and the class token's output is unchanged. Shuffling the patches while keeping the position embeddings in place would change the input, and the prediction.
Inductive bias versus data
Dosovitskiy et al. reported a clear pattern. Trained on ImageNet's 1.3 million images alone, ViTs fell a few points short of comparable ResNets; pretrained on ImageNet-21k (14 million images) they roughly matched them; pretrained on the 300-million-image JFT dataset they surpassed them, using less pretraining compute. A weaker prior needs more data, and with enough data it can win. Why should a prior save data at all?
An invariant classifier is constant on each orbit, and every labeling of the orbits is invariant, so corresponds exactly to the labelings of . A set of orbit representatives is shattered; a set containing two points of one orbit is not, since they always share a label:
In the realizable PAC setting, examples suffice (PAC Learning & VC Dimension). Exact invariance to symmetries can therefore cut this bound on the data needed by up to a factor of , for instance the cyclic shifts of an image:
The catch is approximation: if the target is not invariant, no classifier in can represent it, however much data arrives. A strong prior is a bet that saves data when it is right and imposes a floor of error when it is wrong.
The pattern has since been qualified. DeiT (Touvron et al., 2021) trained competitive ViTs on ImageNet-1k alone with strong augmentation, regularization and distillation, and Steiner et al. (2022) found augmentation and regularization worth roughly a tenfold increase in data. In the other direction, ConvNeXt (Liu et al., 2022) modernized a ResNet with transformer-era design choices and matched hierarchical transformers such as Swin (Liu et al., 2021), which had itself reintroduced locality through windowed attention; and convolutional networks pretrained at JFT scale matched ViTs at equal compute (Smith et al., 2023). As of the mid-2020s, how much architecture matters at scale, compared with data, training recipe and compute, is contested. The clearest practical advantage of transformers is that one architecture serves text, images, audio and video.
Self-supervised ViTs: MAE and DINO
Labels are the bottleneck that self-supervised learning removes (Self-Supervised & Contrastive Learning). Two recipes are especially natural for ViTs, because patches are already tokens.
Masked autoencoders (MAE; He et al., 2022) hide a random 75% of the patches. The encoder, a ViT, processes only the visible quarter, with no mask tokens. A small decoder receives the encoded patches plus mask tokens with their position embeddings and reconstructs the pixels of the hidden patches, with a mean squared error computed on the masked patches only. Skipping the masked tokens in the encoder cut pretraining cost by a factor of three or more.
Think first Why does MAE mask 75% of the patches, when BERT masks only 15% of the words?
A word is dense with meaning, and predicting 15% of them is already hard. Neighboring image patches are highly redundant: with little masking a missing patch can be filled in by interpolating its neighbors, which teaches little. At 75% the model must infer objects and their parts. The high ratio also makes each encoder pass about four times cheaper.
DINO (Caron et al., 2021) is self-distillation with no labels. A student network sees several crops of an image, two large and several small; a teacher, whose weights are an exponential moving average of the student's, sees only the large crops. The student learns to match the teacher's output distribution over dimensions:
DINO's ViTs showed an unexpected property: the class token's attention maps segment the main object without any segmentation labels. DINOv2 (Oquab et al., 2023) scaled the recipe on curated data into general-purpose features that work frozen. Even such models have quirks: a few high-norm tokens in background patches serve the network as scratch space and disturb its attention maps, which adding extra learnable "register" tokens fixes (Darcet et al., 2024).
Key takeaways
- ViT: patch tokens from a stride- convolution, a class token, learned position embeddings and a standard transformer; attention costs per layer and the rest .
- Without position embeddings a transformer is permutation-equivariant; with relative positions, multi-head attention can express any convolution (Cordonnier et al., 2020).
- Invariance divides capacity: invariant classifiers have VC dimension equal to the number of orbits, so a correct prior saves data and a wrong one caps accuracy.
- ViTs need more data or stronger augmentation than CNNs at small scale and match or beat them at large scale; how much architecture matters at scale is contested.
- MAE (75% masking, an encoder on visible patches only) and DINO (self-distillation with centering and sharpening) pretrain ViTs without labels.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
How many tokens does ViT-B/16 process for a image, including the class token?
- 577
- 197
- 1,537
- 2,305
Show the answer
A. 577
, so patch tokens plus the class token: 577. Fine-tuning at a higher resolution than pretraining needs the learned position embeddings interpolated to the new grid, as Dosovitskiy et al. did.
Which component makes a ViT sensitive to where a patch is in the image?
- Multi-head attention
- Layer normalization
- The MLP blocks
- The position embeddings
Show the answer
D. The position embeddings
Attention, MLPs, layer normalization and residual connections are all permutation-equivariant, so without position embeddings the network sees a bag of patches.
A finite input set of images is closed under a group of 64 symmetries acting freely. What is the VC dimension of the class of all invariant binary classifiers on it?
Show the answer
C.
An invariant classifier is one label per orbit, and a free action splits points into orbits of size 64. The orbit representatives can be shattered; no larger set can.
Why does a masked autoencoder's encoder process only the visible patches?
- To make the reconstruction task easier
- It saves compute (a quarter of the tokens at 75% masking) and never trains the encoder on mask tokens that do not occur at test time
- Because transformers cannot process mask tokens
- To hide the positions of the masked patches from the decoder
Show the answer
B. It saves compute (a quarter of the tokens at 75% masking) and never trains the encoder on mask tokens that do not occur at test time
Skipping the masked tokens makes each encoder pass several times cheaper and keeps the encoder's inputs like those at fine-tuning time, when every patch is real. The light decoder, used only during pretraining, receives the mask tokens with their positions.
Further reading
- A. Dosovitskiy et al., "An image is worth 16×16 words: Transformers for image recognition at scale," ICLR (2021).
- J.-B. Cordonnier, A. Loukas & M. Jaggi, "On the relationship between self-attention and convolutional layers," ICLR (2020).
- K. He, X. Chen, S. Xie, Y. Li, P. Dollár & R. Girshick, "Masked autoencoders are scalable vision learners," CVPR (2022).
- M. Caron et al., "Emerging properties in self-supervised vision transformers," ICCV (2021).
- S. J. D. Prince, Understanding Deep Learning, ch. 12 (MIT Press, 2023).