TL;DR
The Vision Transformer (ViT) applies a standard NLP transformer to images with almost no changes. The image is cut into square patches, for example 16 by 16 pixels. Each patch is flattened and linearly projected to a vector, and those vectors are treated exactly like word tokens. When the model is pre-trained on a large dataset, it matches or beats the best convolutional networks on image classification while costing less compute to train.
Where you'll see it: the image encoder inside many vision-language models, and the template for later vision transformers used in detection, segmentation and image generation.
The problem
By 2020, transformers dominated natural language processing. Image recognition was still run by convolutional networks such as ResNets. Convolutions bake in two assumptions: nearby pixels are related, and a pattern means the same thing wherever it appears. Attempts to combine self-attention with convolutions, or to replace convolutions with local attention, had either been hard to scale on accelerators or had not reached the best image results. The open question was whether a plain transformer, with few image-specific assumptions, could compete at the top of image recognition.
Key idea
Treat an image as a sentence. A sentence is a sequence of word tokens, and a transformer does not care what the tokens mean, only how they relate. An image can be cut into a grid of patches, and each patch becomes one token. The transformer learns from data which patches should attend to which others, including distant ones, in every layer.
The catch is that the model has fewer built-in assumptions than a CNN. It has to learn locality and spatial structure from data. On small datasets this costs accuracy. On very large datasets the learned structure is enough, and the lack of built-in bias stops mattering. The paper's title states the trade in one line: at scale, a 16 by 16 patch is worth as much as a word.
flowchart LR img["image 224 x 224 x 3"] --> cut["cut into 16 x 16 patches: 196 patches"] cut --> proj["flatten and project each patch to D dimensions"] cls["learnable class token"] --> seq proj --> seq["sequence of 197 tokens + position embeddings"] seq --> enc["transformer encoder, L layers"] enc --> head["classification head on the class token"]
The method
Setup
The image is , with height , width and colour channels. It is reshaped into a sequence of flattened patches , where each patch is pixels and
Each flattened patch is mapped to a vector of size by a trainable linear projection . The output is the patch embedding. Here is the constant width of the transformer, the same at every layer. A learnable embedding called the class token is prepended to the sequence, following BERT.
Position information is added with learned position embeddings . The full input is
The encoder is a stack of blocks. Each block applies layer normalization followed by multi-head self-attention, with a residual connection, and then layer normalization followed by a two-layer MLP with a GELU non-linearity, again with a residual connection:
The image representation is the class token after the last layer, normalized: . A classifier reads . During pre-training the head has one hidden layer. During fine-tuning it is a single linear layer.
The paper's point about inductive bias is important. In a CNN, locality and translation equivariance are built into every layer. In ViT, only the MLP layers are local and translation-equivariant. Self-attention is global in every layer. The only place the 2D structure is injected is the patch extraction at the start, and the position embedding interpolation at higher resolution.
Model sizes
The variants follow BERT's naming. A model such as ViT-L/16 is the Large variant with 16 by 16 patches.
| Model | Layers | Hidden size | MLP size | Heads | Parameters |
|---|---|---|---|---|---|
| ViT-Base | 12 | 768 | 3072 | 12 | 86M |
| ViT-Large | 24 | 1024 | 4096 | 16 | 307M |
| ViT-Huge | 32 | 1280 | 5120 | 16 | 632M |
Sequence length is inversely proportional to the square of the patch size. A model with 14 by 14 patches (ViT-H/14) therefore costs more than the same model with 16 by 16 patches.
Fine-tuning at higher resolution
Pre-training uses one image size. Fine-tuning often uses a larger one, because higher resolution helps. Larger images give more patches and a longer sequence. The transformer accepts any sequence length, but the position embeddings were learned for the old grid. The paper resizes them with 2D interpolation, using each patch's location in the image. This is the only manual use of 2D structure beyond patch extraction.
Worked examples
Take a RGB image with patch size .
- Number of patches along each side: .
- Total patches: .
- Values per patch: .
- Sequence length including the class token: .
Each patch is a 768-number vector before projection. The transformer sees 197 tokens, which is about the same as a short sentence.
Self-attention cost grows with the square of the sequence length. Compare two ways of tokenizing the same image.
- Pixel tokens: . Attention compares every pair, so the number of pairs is for each head in each layer.
- Patch tokens: . The number of pairs is .
- Ratio: .
Interpretation: pixel-level global attention is out of reach on current hardware, and patching is the step that makes a vanilla transformer practical for images. This is the reason the paper says earlier attention-for-vision models needed local or sparse attention.
Results
Against the best CNNs. The largest model, ViT-H/14 pre-trained on the in-house JFT-300M dataset, reaches 88.55% top-1 on ImageNet, 90.72% on ImageNet ReaL, 94.55% on CIFAR-100 and 77.63% on the 19-task VTAB suite. The paper compares these with BiT-L, a large ResNet pre-trained on the same data, and with Noisy Student, a large EfficientNet trained semi-supervised. ViT-H/14 also edges past Noisy Student on ImageNet (88.55 against 88.4, or 88.5 for a slightly improved Noisy Student result the paper cites from later work), the state of the art there.
The paper's text and its Table 2 disagree slightly about the smaller model. The text and table caption say ViT-L/16 pre-trained on JFT-300M outperforms BiT-L on all tasks. The table agrees for most rows (for example ImageNet 87.76 against 87.54, CIFAR-100 93.90 against 93.51, Oxford-IIIT Pets 97.32 against 96.62). But on ImageNet ReaL the two tie at 90.54, and on VTAB BiT-L is ahead by a hair, 76.29 against 76.28, well inside the noise (BiT-L's spread is 1.70). So read "all tasks" as "better or tied everywhere", and trust the table for the exact numbers. ViT-L/16 needs about 0.68k TPUv3 core-days to pre-train, against 9.9k for BiT-L. ViT-H/14 needs about 2.5k core-days.
Public data. ViT-L/16 pre-trained on the public ImageNet-21k dataset reaches 85.30% on ImageNet and performs well on other tasks. The paper says it could be trained on a standard cloud TPUv3 with 8 cores in about 30 days.
Data requirements. When pre-trained on ImageNet alone, ViT-Large models underperform ViT-Base models, despite moderate regularization. With ImageNet-21k, they are similar. Only with JFT-300M do the larger models show their full benefit, and there ViT overtakes the best BiT CNNs. On random subsets of 9M, 30M and 90M images, ViT overfits more than a ResNet of comparable cost, and it is better once the data reaches 90M and above.
Compute. On a performance versus pre-training compute plot, ViT dominates ResNets. The paper estimates that ViT uses about to times less compute than ResNets to reach the same average performance over five datasets. Hybrids that feed a small CNN's features into the transformer do better at small compute budgets, but the gap vanishes for larger models.
What the model learns. The first-layer filters resemble basis functions for the fine structure within a patch. The learned position embeddings encode 2D layout: patches close together have similar embeddings, and patches in the same row or column have similar ones. Some attention heads cover most of the image even in the lowest layers, and the mean attention distance grows with depth.
Self-supervision. Masked patch prediction, modelled on BERT's masked language modelling, gives ViT-B/16 79.9% on ImageNet. That is a gain of about 2 points over training from scratch and about 4 points behind supervised pre-training. The paper presents this as a preliminary result.
Why it mattered
ViT showed that the convolution was not required to reach the top of image recognition, provided the training data was large enough. It also showed that a transformer used for language could be reused for images with the same code and the same training recipe. Later work extended the architecture to detection, segmentation, video and self-supervised pre-training. Many vision-language models use a ViT as their image encoder. The results also changed how people think about inductive bias: a model with fewer built-in assumptions can win when it sees enough data.
Tradeoffs and failure modes
| Situation | What goes wrong | Better choice |
|---|---|---|
| Small labelled dataset, such as ImageNet alone | ViT overfits and underperforms ResNets | Use a CNN, or pre-train ViT on a larger dataset first |
| High-resolution input | Sequence length grows with the number of patches, and attention cost grows with its square | Use larger patches, a hybrid stem, or local attention |
| Resolution changed between pre-training and fine-tuning | Position embeddings no longer match the grid | Interpolate them, as the paper does |
| Very small models | Hybrids with a CNN front end beat pure ViT on compute | Use a hybrid model at small compute budgets |
| Pre-training without large data or self-supervision | Self-supervised ViT trails supervised pre-training by about 4 points on ImageNet in the paper | Use supervised pre-training on large data where possible |
History
Dosovitskiy and colleagues at Google Research posted the paper in October 2020, and it was published at ICLR 2021. It builds directly on the transformer of Vaswani and colleagues in 2017, and it borrows the class token from BERT. A parallel line of work, image GPT, had applied transformers to pixels and reached a maximum of 72% on ImageNet, which made the patch-based approach look like a significant improvement. The paper caught on because it matched or beat the best convolutional networks while using less compute to pre-train, and because the architecture was a plain transformer that existing NLP tooling could run.
Reading guide
Read these sections in order. The prerequisites matter for the parts shown.
- Section 1, Introduction. Needs Transformer for the NLP model it reuses, and Convolutional Neural Network for the CNN baseline it is compared against.
- Section 2, Related work. Needs Attention Mechanism for the idea of global attention, and Self-Supervised Learning for the masked prediction at the end.
- Section 3.1, Equations 1 to 4. Needs Word Embedding for the idea of learned token vectors, Positional Encoding for why position information is added, and Layer Normalization and Residual Connection for the block structure.
- Section 3.1, inductive bias paragraph. Needs Overfitting and Representation Learning to follow why less built-in bias can hurt on small data.
- Section 3.2, fine-tuning. Needs Transfer Learning and Fine-Tuning.
- Section 4.1, training setup. Needs Adam Optimizer and Momentum for the optimizer choices.
- Sections 4.2 to 4.4. Needs Masked Language Modeling for the self-supervised comparison. Needs Neural Scaling Laws for the compute-performance reading of section 4.4.
Check yourself
QuestionRecall: how is an image turned into a sequence for the transformer?Show answer
The image is cut into non-overlapping patches of pixels. Each patch is flattened and linearly projected to a vector of size . A learnable class token is prepended, and learned position embeddings are added. The result is a sequence of vectors that the transformer treats like word tokens.
QuestionComputation: how many tokens does ViT-B/32 see for a image, and how many values does each patch hold?Show answer
- Patches per side: .
- Total patches: .
- Values per patch: .
- Sequence length with the class token: .
So there are 145 tokens, and each patch is a 3072-number vector before projection.
QuestionWhy does the paper find that ViT loses to ResNets on ImageNet alone but wins on JFT-300M?Show answer
ViT has fewer built-in assumptions about images than a CNN, so it must learn locality and translation structure from data. With only about 1.3M ImageNet images, there is not enough data to learn these well, and ViT overfits. With 300M images, the learned structure is good enough that the lack of built-in bias stops costing accuracy, and the larger ViT models pull ahead. The paper summarizes this as large-scale training trumping inductive bias.
QuestionApplied: a team wants to use a ViT on medical images with 16 by 16 patches. What is the sequence length, and what is the main cost to plan for?Show answer
- Patches per side: .
- Total patches: , plus the class token for tokens.
- Attention compares every pair, so the cost per layer grows as pairs for each head.
The main cost is attention. Compared with input, which has 197 tokens, the sequence is about 21 times longer and the attention cost is about 430 times larger. The team should plan for memory and compute at this size, or consider larger patches or a local attention variant, and should expect the position embeddings to need interpolation if pre-training used a smaller resolution.
Sources
- Dosovitskiy et al., "An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale" (2020): https://arxiv.org/abs/2010.11929
- Vaswani et al., "Attention Is All You Need" (2017): https://arxiv.org/abs/1706.03762