# An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale

Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner and 6 more · arXiv · 2020-10-22

- **Problem** Transformers have become the standard in language processing, but computer vision still relies mainly on convolutional networks, and it is unclear whether a plain Transformer can classify images well.
- **Method** Splits each image into fixed-size patches, maps them linearly to vectors, adds a class token and position embeddings, and runs the sequence through a standard Transformer encoder that is pre-trained on large supervised datasets and then fine-tuned.
- **Results** Reached 88.55 ± 0.04 accuracy on ImageNet with ViT-H/14 pre-trained on JFT-300M, as the mean over three fine-tuning runs.

## Why use a plain Transformer on images

In language processing the usual recipe is to learn broadly from a large body of text first and then adapt the same network to a narrower task. Vision research still builds mostly on convolutional networks. Attention has been added to them, or used to replace parts of them. Designs that drop convolutions entirely look efficient in theory, but their specialized attention patterns have not scaled well on modern hardware accelerators.

The authors ask whether a standard Transformer, changed as little as possible, can work on images once each image is cut into patches and every patch is handled like a token. Trained on mid-sized data such as ImageNet without strong regularization, this setup lands a few percentage points below ResNets of comparable size. The authors attribute this to Transformers lacking inductive biases such as translation equivariance and locality, which hurts generalization when training data is insufficient.

With pre-training on 14M-300M images the picture changes, and the authors find that large-scale training outweighs the inductive bias.

## Turning an image into a token sequence

An image of height H, width W and C channels is reshaped into a sequence of flattened 2D patches, each of size P by P. The number of patches is N = HW/P², and N also sets the effective input length for the Transformer. Formally, \\(x \\in \\mathbb{R}^{H\\times W\\times C}\\) becomes \\(x\_p \\in \\mathbb{R}^{N\\times(P^2\\cdot C)}\\), so each row of \\(x\_p\\) is one flattened patch.

Figure 1 summarizes this path from patches to the encoder and the classification head.

A trainable linear projection E maps each flattened patch to D dimensions, and the outputs are the patch embeddings. The latent width D stays constant through all layers. A learnable class embedding is prepended to the sequence, and learnable position embeddings are added to every entry, giving the input sequence below. The position embeddings are learned in one dimension, since the authors found no significant gain from more advanced 2D-aware variants.

During pre-training the head is an MLP with one hidden layer, and during fine-tuning it is a single linear layer.

## Encoder layers and where image structure enters

The encoder alternates multiheaded self-attention (MSA) blocks and MLP blocks, with layer normalization placed before each block and a residual connection after each one. \\\[ z'\_\\ell = MSA(LN(z\_{\\ell-1})) + z\_{\\ell-1}, \\quad \\ell = 1 \\ldots L \\\] \\\[ z\_\\ell = MLP(LN(z'\_\\ell)) + z'\_\\ell, \\quad \\ell = 1 \\ldots L \\\]

In ViT only the MLP layers are local and translation-equivariant, while self-attention is global. The two-dimensional structure enters at two points: the cut into patches at the start, and the interpolation of position embeddings when the input resolution changes during fine-tuning.

As an alternative to raw patches, the input sequence can be built from CNN feature maps, with the patch embedding projection E applied to patches taken from the feature map. A 1x1 patch size on the feature map flattens its spatial dimensions and projects them to the Transformer width. In the hybrid models of the experiments, the intermediate feature maps of a ResNet are fed into ViT with a patch size of one pixel on that map.

## Fine-tuning, resolution and training settings

For a downstream task the pre-trained prediction head is removed and a zero-initialized feedforward layer of size D×K is attached, where K is the number of downstream classes. Fine-tuning at a higher resolution keeps the patch size, so the sequence gets longer. The pre-trained position embeddings are then 2D-interpolated according to each patch's location in the original image.

All models, including the ResNets, are trained with Adam using beta1 = 0.9, beta2 = 0.999, a batch size of 4096 and a weight decay of 0.1, with a linear learning rate warmup and decay. Fine-tuning uses SGD with momentum and a batch size of 512 for all models. For the ImageNet results in Table 2, ViT-L/16 was fine-tuned at resolution 512 and ViT-H/14 at 518, with Polyak averaging at a factor of 0.9999.

A name such as ViT-L/16 gives the size and the patch size, and because the sequence length goes with the inverse square of the patch size, smaller patches cost more compute. The CNN baseline is ResNet (BiT), a ResNet with Group Normalization in place of Batch Normalization and standardized convolutions.

## Benchmark results against CNN baselines

ViT-H/14 pre-trained on JFT-300M reached 88.55 ± 0.04 on ImageNet, 90.72 ± 0.05 on ImageNet ReaL, 94.55 ± 0.04 on CIFAR-100 and 77.63 ± 0.23 on the VTAB suite. These are means and standard deviations over three fine-tuning runs, and the pre-training cost was 2.5k TPUv3-core-days.

ViT-L/16 pre-trained on JFT-300M reached 87.76 ± 0.03 on ImageNet, 93.90 ± 0.05 on CIFAR-100 and 76.28 ± 0.46 on VTAB, at 0.68k TPUv3-core-days. BiT-L, pre-trained on the same dataset, is listed at 87.54 ± 0.02 on ImageNet and at 9.9k TPUv3-core-days. The text says ViT-L/16 on JFT-300M outperforms BiT-L on all tasks, but the VTAB entries in Table 2 are 76.28 for ViT-L/16 and 76.29 for BiT-L.

ViT-L/16 pre-trained on ImageNet-21k reached 85.30 ± 0.02 on ImageNet, 93.25 ± 0.05 on CIFAR-100 and 72.72 ± 0.21 on VTAB, at 0.23k TPUv3-core-days. The authors estimate that this model could be trained on a standard cloud TPUv3 with 8 cores in about 30 days.

The authors describe Noisy Student as the state of the art on ImageNet at the time, and BiT-L as the best on the other datasets reported. All models were trained on TPUv3 hardware, and cost is counted as the number of cores, two per chip, times training days.

Figure 2 splits VTAB into Natural, Specialized and Structured groups and compares ViT-H/14 with BiT, VIVI and S4L. ViT-H/14 outperforms BiT-R152x4 and the other methods on the Natural and Structured tasks, while the top two models are similar on the Specialized tasks.

## How pre-training dataset size changes the picture

The first series pre-trains on ImageNet, ImageNet-21k and JFT-300M, with weight decay, dropout and label smoothing tuned to help the smaller datasets. On ImageNet, ViT-Large models underperform ViT-Base models despite moderate regularization. With ImageNet-21k their performance is similar, and only JFT-300M shows the full benefit of the larger models.

Early stopping is used, the best validation accuracy during training is reported, and few-shot linear accuracy stands in for full fine-tuning to save compute. The authors read this as evidence that a convolutional inductive bias helps on smaller datasets, while learning patterns directly from data is enough, and even beneficial, on larger ones.

## Performance against pre-training compute

The scaling study pre-trains 7 ResNets, 6 Vision Transformers and 5 hybrids on JFT-300M, mostly for 7 epochs, with a few of the larger models pre-trained for 14 epochs.

Vision Transformers dominate ResNets on the performance-compute trade-off, using 2-4× less compute to reach the same average transfer performance over five datasets. Performance is plotted against total pre-training compute in exaFLOPs, and the figure shows Vision Transformers generally above ResNets at the same budget.

Vision Transformers do not appear to saturate within the range tried, which the authors take as motivation for future scaling efforts.

## What the learned representations encode

The top principal components of the learned RGB embedding filters of ViT-L/32 look like plausible basis functions for the fine structure within a patch. The figure also shows the cosine similarity of position embeddings for ViT-L/32, and the attention distance per head and layer for ViT-L/16.

The learned position embeddings encode distance within the image, so closer patches have more similar embeddings. Patches in the same row or column also have similar embeddings. A sinusoidal structure is sometimes visible for larger grids. The authors connect this 2D topology encoding to the lack of gains from hand-crafted 2D-aware embedding variants.

Attention distance is the average distance in image space across which a head integrates information, computed from its attention weights, and it is analogous to receptive field size in CNNs. Some heads already attend to most of the image in the lowest layers, while other heads keep small attention distances in the low layers. This localized attention is less pronounced in hybrid models, and attention distance grows with network depth.

## Self-supervised pre-training

A preliminary branch applies masked patch prediction, modelled on the masked language modeling task used in BERT, to ViT-B/16 before fine-tuning on ImageNet. ViT-B/16 reaches 79.9% accuracy on ImageNet with this self-supervised pre-training, about 2% above training from scratch and about 4% below supervised pre-training. Contrastive pre-training was left to future work.

## Limitations

The authors note that pre-training efficiency may depend on the training schedule, optimizer and weight decay as well as on the architecture, so the compute comparisons do not isolate architecture alone. The 30-day training estimate for ViT-L/16 on ImageNet-21k is the authors' own estimate.

Experiments cover ImageNet, CIFAR-10 and CIFAR-100, Oxford-IIIT Pets, Oxford Flowers-102 and the 19-task VTAB suite. Detection and segmentation were not tested, and the authors list them as challenges for ViT. The self-supervised experiment is preliminary, and the gap to large-scale supervised pre-training is still large. Few-shot and low-data results are described as promising, and further analysis of few-shot properties is left to future work.

## Paper info

- **Authors**: Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, Neil Houlsby
- **Venue**: arXiv · Preprint
- **First published**: 2020-10-22
- **Added**: 2026-10-20
- **Updated**: 2021-6-3
- **Version**: v2
- **arXiv**: 2010.11929
- **Category**: cs.CV · cs.AI · cs.LG
- **Original paper terms**: [arXiv non-exclusive 1.0](https://arxiv.org/licenses/nonexclusive-distrib/1.0/)
- **What we show**: Paper info and commentary

[Original paper ↗](https://arxiv.org/abs/2010.11929v2) · [PDF ↗](https://arxiv.org/pdf/2010.11929v2)

AI commentary is a separate explanation from the original paper and may contain errors. The original paper and figures follow each source's terms of use and any rights noted separately.

## Quote from the paper

Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, Neil Houlsby (2020). An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale. arXiv:2010.11929v2. https://arxiv.org/abs/2010.11929v2

**BibTeX**

```
@misc{dosovitskiy2020image,
  title = {{An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale}},
  author = {Alexey Dosovitskiy and Lucas Beyer and Alexander Kolesnikov and Dirk Weissenborn and Xiaohua Zhai and Thomas Unterthiner and Mostafa Dehghani and Matthias Minderer and Georg Heigold and Sylvain Gelly and Jakob Uszkoreit and Neil Houlsby},
  year = {2020},
  eprint = {2010.11929},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2010.11929v2}
}
```

## Other paper commentary

- [Deep Residual Learning for Image Recognition](https://refivu.com/en/papers/19d6446d-fd9a-4e80-b535-a4e333cad216-deep-residual-learning-for-image-recognition.md)
- [ArcFace: Additive Angular Margin Loss for Deep Face Recognition](https://refivu.com/en/papers/c413067c-e2eb-43a0-8011-b952f120296a-arcface-additive-angular-margin-loss-for-deep-face.md)
- [Memory as Dynamics: Learning Reliability-Guided Predictive Models for Online Video Perception](https://refivu.com/en/papers/9edb7769-5017-4985-b695-21eab77d07d7-memory-as-dynamics-learning-reliability-guided-predictive.md)
- [Breaking Semantic Artifacts for Generalized AI-generated Image Detection](https://refivu.com/en/papers/4e046749-44ad-45fe-a59b-ca849df10c45-breaking-semantic-artifacts-for-generalized-ai-generated.md)
- [Demographic Encoding is Not Exposure: Fairness and Privacy in Chest X-ray Foundation Models](https://refivu.com/en/papers/d91f434f-7371-40be-9129-9d3da0b4398c-demographic-encoding-is-not-exposure-fairness-and-privacy.md)
- [Token Pruning Needs a Protected Sink Token: Coherent Spatial Aggregation in Vision Transformers](https://refivu.com/en/papers/ccf2a0da-8ba4-468b-bb16-97b8206e5236-token-pruning-needs-a-protected-sink-token-coherent.md)
- [RoBERTa: A Robustly Optimized BERT Pretraining Approach](https://refivu.com/en/papers/3dc17b50-5c0f-4503-a368-4b0d9e86745c-roberta-a-robustly-optimized-bert-pretraining-approach.md)
- [Auto-Encoding Variational Bayes](https://refivu.com/en/papers/90411040-94ff-4aca-9d04-a1a99cad3eb4-auto-encoding-variational-bayes.md)
- [Deep contextualized word representations](https://refivu.com/en/papers/13952ebe-dec9-4497-bba2-03f142631507-deep-contextualized-word-representations.md)
- [XLNet: Generalized Autoregressive Pretraining for Language Understanding](https://refivu.com/en/papers/b3e5ce04-f8db-4e06-9f54-1aba7291fad5-xlnet-generalized-autoregressive-pretraining-for-language.md)
- [Distributed Representations of Words and Phrases and their Compositionality](https://refivu.com/en/papers/3b76539e-2654-42d7-9073-06bc84af912a-distributed-representations-of-words-and-phrases-and-their.md)
- [Neural Machine Translation by Jointly Learning to Align and Translate](https://refivu.com/en/papers/d3733cd4-18bb-4ef7-881b-d6d27baee015-neural-machine-translation-by-jointly-learning-to-align.md)

## Terms in this paper

- [Accuracy](https://refivu.com/en/terms/1995c0cd6282-accuracy)
- [Transformer](https://refivu.com/en/terms/48e8be2570bc-transformer)
- [ADAM](https://refivu.com/en/terms/0e9ad0199e08-adam)
- [self-attention](https://refivu.com/en/terms/426589b81077-self-attention)
- [ResNet](https://refivu.com/en/terms/ca7e0121c7a8-resnet)
- [CIFAR-100](https://refivu.com/en/terms/5afa3b877d18-cifar-100)
- [Fine-tuning](https://refivu.com/en/terms/66a12665f507-fine-tuning)
- [Vision Transformer (ViT)](https://refivu.com/en/terms/5676f2cc1c70-vision-transformer-vit)
- [LayerNorm](https://refivu.com/en/terms/71749b6cdbf4-layernorm)
- [image recognition](https://refivu.com/en/terms/b92f065c611b-image-recognition)
- [position embeddings](https://refivu.com/en/terms/340cd7d12eb0-position-embeddings)
- [pre-training](https://refivu.com/en/terms/02e8737d8b92-pre-training)
- [JFT-300M](https://refivu.com/en/terms/62360c0882e3-jft-300m)
- [multiheaded self-attention](https://refivu.com/en/terms/02f3bd8d8a1d-multiheaded-self-attention)
- [self-supervised pre-training](https://refivu.com/en/terms/d7035ec5cc95-self-supervised-pre-training)

---

AI-written text can contain mistakes. [Refivu](https://refivu.com/en/papers/8a112940-90e3-4c6b-8fa0-d576b3ebd5d1-an-image-is-worth-16x16-words-transformers-for)
