AI Logic

Architectures

Vision Transformer (ViT)

Updated๏ผš

Structure of ViT. The left shows the overall flow (split the image into 196 patches of 16ร—16, embed them with a linear layer, add the [class] token and position embeddings, pass them through L encoder layers, and classify the [class] output with an MLP head); the right shows the inside of an encoder layer (self-attention and an MLP with layer normalization placed before each, each with a residual connection)

Background and overview

ViT (Vision Transformer) is an image classification model that cuts an image into small patches such as 16ร—16, lines up the patches like the words of a sentence, and feeds them directly into the encoder of a Transformer. Dosovitskiy et al. at Google published it in 2020. The title of the paper, "An Image is Worth 16x16 Words", expresses this idea.

At the time, image recognition was dominated by convolutional neural networks (CNNs) such as ResNet. There had been studies applying self-attention to images, but most combined it with CNNs or used specialized attention patterns designed for images, which were hard to run at scale. ViT aimed to use the Transformer from natural language processing as unchanged as possible, limiting image-specific design to the step that cuts the image into patches.

The main results of the paper are as follows.

  • When trained on ImageNet (about 1.3 million images) alone, it was a few points less accurate than ResNets of similar size.
  • When pre-trained on large datasets of 14 million (ImageNet-21k) to 300 million (JFT-300M) images and then fine-tuned, it matched or exceeded the best CNNs of the time. The largest model reached 88.55% accuracy on ImageNet and 94.55% on CIFAR-100.
  • The pre-training compute needed to reach the same accuracy was roughly 2โ€“4 times less than for ResNet.

This work showed that "with enough data, a model can learn from the data even without image-specific mechanisms (inductive biases)", and it led to the widespread use of Transformers in image recognition as well.

Architecture

Like BERT, ViT uses only the Transformer encoder. The difference is the input: instead of words, it lines up image patches. In the figure at the head of the article, the left shows the overall flow and the right shows the inside of one encoder layer.

An image flows in the following order (for ViT-B/16 with a 224ร—224 input).

  1. Split into patches: cut an image xโˆˆRHร—Wร—C\boldsymbol{x} \in \mathbb{R}^{H \times W \times C} with height HH, width WW, and CC channels into N=HW/P2N = HW/P^2 patches of size Pร—PP \times P, and flatten each patch into a vector of length P2CP^2 C. Cutting a 224ร—224 image into 16ร—16 patches gives 14 ร— 14 = 196 patches, each with 16 ยท 16 ยท 3 = 768 dimensions.
  2. Embed: map each patch to a DD-dimensional vector (768 for ViT-B) with a learnable matrix EE (patch embedding).
  3. Prepend the [class] token: add one learnable vector xclass\boldsymbol{x}_{\text{class}} at the start. It plays the same role as BERT's [CLS], and the output at this position is used at the end as the representation of the whole image.
  4. Add position embeddings: add a position embedding EposE_{\text{pos}} learned for each position in the patch sequence (numbers 0โ€“196).
  5. Pass through the encoder: pass through LL Transformer encoder layers.
  6. Classify: apply layer normalization to the output at the [class] position of the last layer and feed it to the classification head. The head is an MLP with one hidden layer during pre-training and a single linear layer during fine-tuning.

As equations (Eqs. (1)โ€“(4) of the paper), where zโ„“\mathbf{z}_\ell is the output of layer โ„“\ell, MSA is multi-head self-attention, and LN is layer normalization:

z0=[xclass;ย xp1E;ย xp2E;ย โ‹ฏโ€‰;ย xpNE]+Epos,EโˆˆR(P2C)ร—D,ย EposโˆˆR(N+1)ร—D\mathbf{z}_0 = [\boldsymbol{x}_{\text{class}};\ \boldsymbol{x}_p^1 E;\ \boldsymbol{x}_p^2 E;\ \cdots;\ \boldsymbol{x}_p^N E] + E_{\text{pos}}, \qquad E \in \mathbb{R}^{(P^2 C) \times D},\ E_{\text{pos}} \in \mathbb{R}^{(N+1) \times D} zโ„“โ€ฒ=MSA(LN(zโ„“โˆ’1))+zโ„“โˆ’1,zโ„“=MLP(LN(zโ„“โ€ฒ))+zโ„“โ€ฒ,โ„“=1,โ€ฆ,L\mathbf{z}'_\ell = \mathrm{MSA}(\mathrm{LN}(\mathbf{z}_{\ell-1})) + \mathbf{z}_{\ell-1}, \qquad \mathbf{z}_\ell = \mathrm{MLP}(\mathrm{LN}(\mathbf{z}'_\ell)) + \mathbf{z}'_\ell, \qquad \ell = 1, \ldots, L y=LN(zL0)\boldsymbol{y} = \mathrm{LN}(\mathbf{z}_L^0)

Inside an encoder layer

Each layer alternates self-attention by multi-head attention with a position-wise MLP (two layers with GELU activation). Unlike the original Transformer and BERT, layer normalization is placed before each block, and the input is added after the block (Pre-LN). Since self-attention looks at every pair of patches, information from the entire image can be gathered from the very first layer.

Model sizes

Following BERT, the paper used the following three sizes (Table 1 of the paper). The number after the name is the patch size: ViT-L/16 means "Large with 16ร—16 patches".

ModelLayers LLHidden size DDMLP sizeHeadsParameters
ViT-Base1276830721286M
ViT-Large241024409616307M
ViT-Huge321280512016632M

Smaller patches make the sequence longer (the length is inversely proportional to the square of the patch size) and increase the computation.

Splitting into patches and applying a linear layer is the same computation as a convolution whose kernel size and stride equal the patch size (16ร—16, stride 16). The ViT in PyTorch's torchvision is also implemented with an nn.Conv2d of this form. The paper also tried a "hybrid" that feeds intermediate feature maps of a ResNet instead of patches.

Training: pre-training and fine-tuning

Like BERT, ViT is used in two stages: pre-train on a large dataset, then fine-tune on the target data.

Pre-training

ItemValue (pre-training on JFT-300M and ImageNet-21k)
OptimizationAdam (ฮฒ1=0.9\beta_1 = 0.9, ฮฒ2=0.999\beta_2 = 0.999), batch size 4096
Weight Decay0.1 (JFT-300M), 0.03 (ImageNet-21k)
Learning rateLinear decay after a warmup of 10,000 iterations
Image size224ร—224

The paper trained all ResNets with the same Adam settings as well, and reports that in this setting Adam worked slightly better than SGD. When training from scratch on ImageNet alone, strong regularization is essential: the paper trains for 300 epochs with weight decay 0.3, dropout 0.1, a cosine learning rate decay, and gradient clipping at a norm of 1.

Fine-tuning

  1. Remove the pre-trained classification head and replace it with a zero-initialized linear layer (Dร—KD \times K, where KK is the number of target classes).
  2. Train on images at a higher resolution than pre-training (384ร—384 by default). The patch size stays the same, so the sequence becomes longer.
  3. With a longer sequence, the learned position embeddings no longer fit, so they are interpolated in 2D according to their location in the original image.

Fine-tuning uses SGD with momentum 0.9, batch size 512, cosine learning rate decay, and no weight decay.

The 2D structure of images is manually injected into ViT in only two places: cutting the image into patches and this interpolation of the position embeddings. All other spatial relationships between patches are learned from data.

Why it gets stronger with large data

The key to understanding ViT's behavior is inductive bias (assumptions about the data built into the model's structure in advance).

  • CNNs make many assumptions about images: convolutions in a CNN build into every layer the assumptions that only nearby pixels matter (locality), that pixels are arranged in a 2D grid, and that the same features appear even if an object shifts (translation equivariance). Thanks to these assumptions, CNNs learn efficiently even with little data.
  • ViT makes few assumptions: in ViT, only the position-wise MLP is local, and self-attention looks at the whole image from the start. The position embeddings also carry no 2D position information at initialization. Therefore, all spatial relationships between patches must be learned from data.

This difference causes the results to reverse depending on the amount of data. The paper compared subsets of 9 million to 90 million images drawn from JFT-300M and showed that with little data ViT overfits more than ResNets of comparable compute, while with more data ViT does better (for example, ViT-B/32 is much worse than ResNet-50 with 9 million images but better with 90 million or more). The paper summarizes this as "large scale training trumps inductive bias".

As an everyday analogy, a CNN is like a student who starts studying after being told "looking nearby is enough", while ViT is like a student who is told nothing and discovers the tricks by solving a huge number of problems. With few problems the former has the advantage, but with enough problems the latter, not bound by the tricks it was taught, can find better approaches.

The paper also examined the inside of a trained ViT.

  • Position embeddings learn the 2D arrangement: patches closer together had more similar position embeddings, and patches in the same row or column were also similar. This is thought to be why hand-crafted 2D-aware embeddings did not improve accuracy.
  • Some heads attend to the whole image from shallow layers: the "attention distance" computed from the attention weights corresponds to the receptive field of a CNN. Even in the lowest layer, some heads attend to most of the image, while others attend only to a narrow region; the latter may play a role similar to the early convolutions of a CNN. The attention distance increased with depth.

Experimental results

Comparison with the best CNNs of the time (accuracy %, average over three fine-tuning runs; Table 2 of the paper)

DataViT-H/14 (JFT)ViT-L/16 (JFT)ViT-L/16 (I21k)BiT-L (ResNet152x4, JFT)Noisy Student (EfficientNet-L2)
ImageNet88.5587.7685.3087.5488.4/88.5
ImageNet ReaL90.7290.5488.6290.5490.55
CIFAR-1099.5099.4299.1599.37โ€”
CIFAR-10094.5593.9093.2593.51โ€”
Oxford-IIIT Pets97.5697.3294.6796.62โ€”
Oxford Flowers-10299.6899.7499.6199.63โ€”
VTAB (19 tasks)77.6376.2872.7276.29โ€”
Pre-training compute (TPUv3 core-days)2500680230990012300

ViT-L/16 pre-trained on JFT-300M outperformed BiT-L (a large ResNet) pre-trained on the same data on every task, with about 1/15 of the pre-training compute. ViT-L/16 pre-trained on the public ImageNet-21k could also be trained in about 30 days on an 8-core TPUv3 and gave good results on many tasks.

Effect of pre-training dataset size (accuracy % when fine-tuned on ImageNet; Table 5 of the paper)

Pre-training dataViT-B/16ViT-L/16
ImageNet (about 1.3M images)77.9176.53
ImageNet-21k (about 14M images)83.9785.15
JFT-300M (about 300M images)84.1587.12

When pre-trained on ImageNet alone, the larger ViT-L/16 does worse than ViT-B/16. As the dataset grows, the advantage of larger models appears.

Comparison of position embeddings (ViT-B/16, ImageNet 5-shot linear evaluation accuracy; Table 8 of the paper)

Position embeddingAccuracy
None (treated as a bag of patches)0.614
1D (sequence index)0.642
2D (row and column indices)0.640
Relative position0.640

Accuracy drops sharply without position information, but how it is added makes almost no difference.

Self-supervised learning: the paper also tried pre-training that mimics BERT's masked language modeling, masking some patches and predicting their mean color. ViT-B/16 reached 79.9% accuracy on ImageNet, 2 points higher than training from scratch but 4 points short of large-scale supervised pre-training.

Practical notes

Keep the following points in mind when using ViT.

  • Do not train from scratch on small data: because ViT has few inductive biases, training from scratch on data the size of ImageNet tends to give lower accuracy than a ResNet of similar size. As a rule, fine-tune weights pre-trained on a large dataset.
  • Interpolate the position embeddings when changing the input resolution: there is one position embedding per patch, so changing the image size breaks the count. Interpolate in 2D as in the paper (torchvision provides interpolate_embeddings).
  • Smaller patches increase computation sharply: the computation of self-attention grows with the square of the sequence length. Going from 16 to 8 pixel patches makes the sequence 4 times longer and the attention computation roughly 16 times larger.
  • Check the assumptions behind library weights: ViT_B_16_Weights.IMAGENET1K_V1 in PyTorch's torchvision was trained on ImageNet alone with a modified DeiT recipe and reaches 81.1% top-1 at 224ร—224. IMAGENET1K_SWAG_E2E_V1 was pre-trained on a different large dataset and takes 384ร—384 inputs (per the official documentation). For preprocessing, use weights.transforms() attached to the weights.

Figures such as the paper's 88.55% on ImageNet were obtained with pre-training on a private dataset of 300 million images (JFT-300M), fine-tuning at high resolution (512, 518), and averaging of weights during training. Public data or torchvision weights will not reproduce the same numbers, so align the pre-training data and resolution when comparing.

Comparison with other models

ViT differs greatly from CNNs in treating an image as a "sequence of patches". Comparing them from the same viewpoints gives the following.

ModelHow the input is handledHow information is mixed across patchesAssumptions about imagesGood fit
ResNet (CNN)As a grid of pixelsConvolution (nearby only)Many (locality, translation)Small to medium datasets
ViTA sequence of patches such as 16ร—16Self-attention (global)FewWhen large-scale pre-training is possible
MLP-MixerA sequence of patchesMLP along the patch axisFewLarge-scale pre-training, like ViT
BERTA sequence of wordsSelf-attention (global)โ€”Understanding text (the basis of ViT's architecture)

After ViT, many models were proposed to address its weaknesses in data requirements and computation. DeiT showed that with training techniques and knowledge distillation, a competitive ViT can be trained on ImageNet alone. Methods that pre-train ViT on unlabeled data, such as MAE and DINO, have also become widespread.

Rough guidelines for choosing are as follows.

  • Weights pre-trained on large-scale data are available: fine-tuning ViT is a strong option. The larger the data, the more it tends to outgrow CNNs.
  • Little data, training from scratch: choose a CNN such as ResNet, or DeiT, which is easier to train on ImageNet alone.
  • Limited compute: consider larger patches (such as /32) or a lightweight CNN (MobileNet, EfficientNet, etc.).

PyTorch example

Show code
python
import torch
import torch.nn as nn
from PIL import Image
from torchvision.models import vit_b_16, ViT_B_16_Weights

"""
Examples of loading torchvision's pretrained ViT-B/16 to classify an image, and of tracing by hand
the flow patch embedding -> [class] and position embeddings -> encoder -> head
"""

weights = ViT_B_16_Weights.IMAGENET1K_V1       # same as ViT_B_16_Weights.DEFAULT. Input is 224x224
model = vit_b_16(weights=weights)
model.eval()                                   # disable dropout

preprocess = weights.transforms()              # resize to 256, center-crop 224x224, normalize with mean and std
image = Image.open("cat.jpg").convert("RGB")
x = preprocess(image).unsqueeze(0)             # [1, 3, 224, 224]
with torch.no_grad():
  probs = model(x).softmax(dim=1)              # [1, 1000]
top5 = probs.topk(5, dim=1)
for p, i in zip(top5.values[0], top5.indices[0]):
  print(f"{weights.meta['categories'][i]}: {p.item():.3f}")

# Trace the inner flow by hand (Eqs. (1)-(4) of the paper)
with torch.no_grad():
  patches = model.conv_proj(x)                 # 16x16 conv with stride 16 = linear projection of patches: [1, 768, 14, 14]
  tokens = patches.flatten(2).transpose(1, 2)  # sequence of 196 patches: [1, 196, 768]
  cls = model.class_token.expand(1, -1, -1)    # learnable [class] token: [1, 1, 768]
  z0 = torch.cat([cls, tokens], dim=1)         # [1, 197, 768]
  zL = model.encoder(z0)                       # add position embeddings, pass through 12 encoder layers and the final LN
  logits = model.heads(zL[:, 0])               # only the output at the [class] position goes to the classification head: [1, 1000]

# To fine-tune for 10-class classification: replace the head with a zero-initialized linear layer (Section 3.2 of the paper)
model.heads.head = nn.Linear(768, 10)
nn.init.zeros_(model.heads.head.weight)
nn.init.zeros_(model.heads.head.bias)
model.train()
optimizer = torch.optim.SGD(model.parameters(), lr=0.003, momentum=0.9)   # the paper fine-tunes with SGD, momentum 0.9

FAQ

Q. Should I use ViT or a CNN?
A.

If weights pre-trained on large-scale data are available, ViT is a strong choice, and the larger the data, the more it tends to outgrow CNNs. If data is scarce and you train from scratch, CNNs such as ResNet, which carry assumptions about images (such as locality), are more stable. In the paper, too, ViT pre-trained on ImageNet alone was a few points below ResNets of similar size.

Q. What does the "16" in ViT-B/16 mean?
A.

It is the patch size. ViT-B/16 is a "Base-sized model that splits the image into 16ร—16 patches". A 224ร—224 image becomes 14ร—14=19614 \times 14 = 196 patches. Smaller patches make the sequence longer, which tends to improve accuracy but increases computation.

Q. Can I classify with the overall average instead of the [class] token?
A.

Yes. The appendix of the paper reports that classifying with global average pooling over the patch outputs instead of the [class] token gives almost the same accuracy if the learning rate is adjusted. The [class] token was adopted to stay as close as possible to the original Transformer (BERT).

References

  1. Dosovitskiy, A., Beyer, L., Kolesnikov, A., Weissenborn, D., Zhai, X., Unterthiner, T., Dehghani, M., Minderer, M., Heigold, G., Gelly, S., Uszkoreit, J., & Houlsby, N. (2021). An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale. ICLR 2021. arXiv:2010.11929.
  2. Vaswani, A., et al. (2017). Attention Is All You Need. NeurIPS 2017. arXiv:1706.03762.
  3. Touvron, H., et al. (2021). Training data-efficient image transformers & distillation through attention. ICML 2021. arXiv:2012.12877.
  4. PyTorch. torchvision.models.vit_b_16 (ViT_B_16_Weights).