Paper notes

ViT: An Image Is Worth 16x16 Words, Fed Straight to a Transformer

ViT drops convolutions: it cuts an image into fixed-size patches, projects each into a token, adds position embeddings and feeds a standard Transformer encoder. It trails ResNets on small data but, pre-trained on JFT-300M, reaches 88.55% on ImageNet with about a quarter of BiT-L's compute.

Published Updated 12 min read

On this page
  1. Why this paper matters
  2. Method: a sequence of patches
  3. Experiments and findings
  4. Checking it with code
  5. Limitations and what to keep in mind
  6. What to take from this paper
  7. Further reading
  8. FAQ

Why this paper matters

In 2020 computer vision was still dominated by convolutional networks. Transformers had already won in language, but vision work either inserted self-attention into a convolutional network or used heavily specialized attention patterns. The ViT paper (Dosovitskiy et al., Google; posted in October 2020, ICLR 2021) took the most direct route: leave the Transformer alone and change only the input. Cut the image into patches, treat each patch as a “word”, and reuse the NLP Transformer as is.

The title, “An Image is Worth 16x16 Words”, describes that step. Most vision-language models still use some variant of ViT as the vision encoder (see Multimodal LLMs). The most important finding of the paper is not the architecture but this: once pre-training data is large enough, the lack of convolutional inductive bias stops being a problem.

Method: a sequence of patches

Take an image x∈RH×W×Cx\in\mathbb{R}^{H\times W\times C} and a patch side PP. The number of patches is N=HW/P2N=HW/P^2, which is also the effective sequence length. Each patch is flattened into a P2CP^2C-dimensional vector and mapped to the hidden size DD by a trainable linear projection EE. A learnable [class] vector is prepended (as in BERT) and position embeddings EposE_{pos} are added:

z0=[xclass; xp1E; xp2E; … ; xpNE]+Epos,E∈R(P2C)×D, Epos∈R(N+1)×Dz_0 = [x_{class};\,x_p^1E;\,x_p^2E;\,\dots;\,x_p^NE] + E_{pos},\qquad E\in\mathbb{R}^{(P^2C)\times D},\ E_{pos}\in\mathbb{R}^{(N+1)\times D}

The encoder alternates multi-head self-attention with a two-layer MLP using GELU, with LayerNorm before each block and a residual connection after it. The output at the [class] position is the image representation (a one-hidden-layer MLP head at pre-training time, a zero-initialized linear layer at fine-tuning time). Design choices worth noting:

  • Standard learnable 1D position embeddings. The authors tried 2D-aware variants and saw no significant gain (Appendix D.4).
  • Very little inductive bias. Only the MLP layers are local and translation equivariant, while self-attention is global. The 2D neighborhood structure is used in just two places: cutting the image into patches, and adjusting the position embeddings when fine-tuning at a different resolution.
  • Hybrid variant. The input sequence can instead come from the feature map of a CNN (the patch size can be 1×1).
  • Higher resolution at fine-tuning time. The patch size stays fixed, so the sequence gets longer, and the pre-trained position embeddings are 2D-interpolated according to their location in the original image.

The model sizes follow BERT, plus a new Huge:

ModelLayersHidden DDMLP sizeHeadsParams
ViT-Base1276830721286M
ViT-Large241024409616307M
ViT-Huge321280512016632M

Experiments and findings

Training setup: Adam (β1=0.9\beta_1=0.9, β2=0.999\beta_2=0.999), batch size 4096, weight decay 0.1 (which the paper found useful for the transfer of all models), and a linear warmup followed by linear decay. Fine-tuning uses SGD with momentum and batch size 512. There are three pre-training datasets: ImageNet (1.3M images), ImageNet-21k (14M images) and JFT (18k classes, 303M images).

Against the strongest convolutional networks (Table 2). Each number is the mean of three fine-tuning runs. The ImageNet results use a higher fine-tuning resolution (512 for ViT-L/16, 518 for ViT-H/14) and Polyak averaging. The baselines are BiT-L (a large ResNet pre-trained on JFT-300M) and Noisy Student (a semi-supervised EfficientNet-L2, the best ImageNet result at the time):

MetricViT-H/14 (JFT)ViT-L/16 (JFT)ViT-L/16 (I21k)BiT-L (ResNet152x4)Noisy Student
ImageNet88.5587.7685.3087.5488.4 / 88.5
ImageNet ReaL90.7290.5488.6290.5490.55
CIFAR-10094.5593.9093.2593.51none
VTAB (19 tasks)77.6376.2872.7276.29none
Pre-training compute (TPUv3-core-days)2.5k0.68k0.23k9.9k12.3k

The paper says the smaller ViT-L/16 outperforms BiT-L on all tasks (in the table, ImageNet ReaL is 90.54 for both, so that one is a tie) while using about 7% of its pre-training compute. ViT-H/14 pushes ImageNet to 88.55% at roughly a quarter of BiT-L’s compute and a fifth of Noisy Student’s. The Noisy Student numbers, 88.4 and 88.5 (the table footnote credits the latter to Touvron et al., 2020), are within 0.05 to 0.15 points of ViT-H/14 on ImageNet, so accuracy is nearly tied there and the main difference is compute. The ViT-L/16 pre-trained on the public ImageNet-21k also does well, and the paper estimates it can be trained in about 30 days on a standard cloud TPUv3 with 8 cores.

Data scale decides (Table 5, ImageNet accuracy after fine-tuning at resolution 384, no Polyak averaging). The ImageNet row had weight decay, dropout and label smoothing tuned for the small dataset.

Pre-training dataViT-B/16ViT-L/16ViT-H/14
ImageNet (1.3M)77.9176.53none
ImageNet-21k (14M)83.9785.1585.13
JFT-300M (303M)84.1587.1288.04

With the least data the larger model is worse than the smaller one, and scale only pays off as the data grows. The paper also pre-trains on random JFT subsets of 9M, 30M and 90M images plus the full set, with no extra regularization, shared hyperparameters and early stopping, reporting few-shot linear accuracy on ImageNet. ViT overfits more than a ResNet of comparable compute on the smaller subsets. ViT-B/32 is slightly faster than ResNet50 and does much worse on the 9M subset but better on the 90M-and-up subsets, and the same holds for ResNet152x2 against ViT-L/16. The paper’s reading is that the convolutional inductive bias helps on small datasets, while for large ones learning the patterns directly from data is enough, even beneficial.

Controlled scaling study (Section 4.4). Fixing the data to JFT-300M and comparing accuracy with pre-training compute, ViT dominates ResNet on the performance/compute trade-off, using roughly 2 to 4 times less compute for the same accuracy (average over five datasets). Hybrids are slightly better than pure ViT at small budgets, and the gap vanishes for larger models. ViT does not saturate within the range tried.

What the model learns (Section 4.5). The position embeddings learn 2D topology: nearby patches get similar embeddings, and patches in the same row or column are similar too. That explains why hand-crafted 2D embeddings add nothing. Some attention heads already attend to most of the image in the lowest layers, while others stay local, which the paper compares to early convolutional layers. The local heads are less pronounced in the hybrid models.

Self-supervision (Section 4.6). A preliminary experiment mimics BERT’s masked prediction on patches. ViT-B/16 reaches 79.9% on ImageNet, 2% better than training from scratch and 4% behind supervised pre-training.

Checking it with code

The code below does three things. (1) It adds up the parameters of the three models term by term following Eq. (1) to (4) and compares them with Table 1. (2) It raises the fine-tuning resolution from 224 to 384 and 512 and shows how the sequence length and attention cost grow. (3) It uses the numbers in Table 6 to estimate, on ImageNet, how much pre-training compute a ResNet needs to match each ViT’s accuracy, which checks the claim of “2 to 4 times less”.

import numpy as np


def vit_params(layers, d, mlp, patch, img=224, c=3):
    """ViT parameters (no classifier head) and token count, term by term
    following Eq. (1)-(4) of the paper."""
    n = (img // patch) ** 2  # number of patches, N = HW / P^2
    embed = patch * patch * c * d + d  # linear projection E (with bias)
    cls, pos = d, (n + 1) * d  # [class] vector and position embeddings
    attn = 4 * d * d + 4 * d  # q, k, v and output projections
    ffn = 2 * d * mlp + mlp + d  # two-layer MLP
    ln = 2 * 2 * d  # two LayerNorms per block
    return embed + cls + pos + layers * (attn + ffn + ln) + 2 * d, n


print("model       N  params  paper")
for name, cfg, paper in [("ViT-B/16", (12, 768, 3072, 16), 86),
                         ("ViT-L/16", (24, 1024, 4096, 16), 307),
                         ("ViT-H/14", (32, 1280, 5120, 14), 632)]:
    p, n = vit_params(*cfg)
    print(f"{name}  {n:4d}  {p / 1e6:5.1f}M  {paper}M")

# Higher fine-tuning resolution: same patch size, longer sequence, and the
# attention matrix grows with N^2
d, layers = 1024, 24  # ViT-L/16
for img in (224, 384, 512):
    s = (img // 16) ** 2 + 1  # patches plus [class]
    attn = layers * 2 * s * s * d  # multiply-adds of QK^T and AV
    lin = layers * 12 * s * d * d  # q/k/v/o and MLP linear layers
    print(f"L/16 @{img}: seq={s:5d} seq^2={s * s:8d} "
          f"attention {attn / 1e9:5.1f}G  linear {lin / 1e9:5.1f}G MACs")

# Paper Table 6 (pre-trained on JFT-300M; ImageNet accuracy after
# fine-tuning, pre-training compute in exaFLOPs)
resnet = [(50, 77.54), (96, 80.67), (141, 81.88), (199, 82.12),
          (563, 84.97), (1126, 85.56), (3306, 87.22)]
vit = {"B/32": (55, 80.73), "B/16": (224, 84.15), "L/32": (196, 84.37),
       "L/16 7ep": (783, 86.30), "L/16 14ep": (1567, 87.12)}
r_flops, r_acc = np.log([f for f, _ in resnet]), [a for _, a in resnet]
for name, (flops, acc) in vit.items():  # interpolate on log compute
    same = np.exp(np.interp(acc, r_acc, r_flops))
    print(f"ViT-{name:9s} {flops:5d} EF, ImageNet {acc}: "
          f"ResNet needs {same:5.0f} EF ({same / flops:.1f}x)")

Output (plain NumPy, finishes instantly):

model       N  params  paper
ViT-B/16   196   85.8M  86M
ViT-L/16   196  303.3M  307M
ViT-H/14   256  630.8M  632M
L/16 @224: seq=  197 seq^2=   38809 attention   1.9G  linear  59.5G MACs
L/16 @384: seq=  577 seq^2=  332929 attention  16.4G  linear 174.2G MACs
L/16 @512: seq= 1025 seq^2= 1050625 attention  51.6G  linear 309.5G MACs
ViT-B/32         55 EF, ImageNet 80.73: ResNet needs    98 EF (1.8x)
ViT-B/16        224 EF, ImageNet 84.15: ResNet needs   417 EF (1.9x)
ViT-L/32        196 EF, ImageNet 84.37: ResNet needs   452 EF (2.3x)
ViT-L/16 7ep    783 EF, ImageNet 86.3: ResNet needs  1820 EF (2.3x)
ViT-L/16 14ep  1567 EF, ImageNet 87.12: ResNet needs  3098 EF (2.0x)

How to read these numbers:

  1. The parameter counts mostly match; Large is off by about 1%. Base and Huge agree with Table 1 within 1% (85.8M vs 86M, 630.8M vs 632M). For Large, my count is 303.3M against the paper’s 307M, 3.7M fewer, and the paper does not explain the difference.
  2. Doubling the resolution grows attention cost quadratically. At 224 the sequence is 197 tokens (196 patches plus [class]) and at 512 it is 1,025, so the squared length grows about 27 times (38,809 vs 1,050,625), and the multiply-adds of the attention matrix products rise from 1.9G to 51.6G. At this width (D=1024D=1024) the linear layers are still the larger share (309.5G vs 51.6G at 512), so total cost grows by much less than 27 times.
  3. “2 to 4 times less compute” sits at the low end on ImageNet. Interpolating the ResNet accuracy-vs-compute curve of Table 6 on a log scale, a ResNet needs about 1.8 to 2.3 times the compute of a ViT to reach the same ImageNet accuracy. The paper’s 2 to 4 times is an average over five datasets and I only recomputed ImageNet. The two do not conflict, but this check cannot support the upper end of 4 times.

Limitations and what to keep in mind

  • It relies on a private, very large dataset. The best results come from Google’s internal JFT-300M, which outsiders cannot reproduce. The public ImageNet-21k version (ViT-L/16, 85.30%) is weaker.
  • It does not win on small data. With ImageNet alone ViT trails comparable ResNets, which the paper itself reports. Later work such as DeiT (Touvron et al., December 2020) used only ImageNet and a stronger training recipe to train the 86M-parameter reference model to 83.1%, and with distillation up to 85.2%.
  • Compute comparisons need care. The paper itself warns that pre-training efficiency also depends on the training schedule, optimizer and weight decay. The compute figures in Table 2 and the controlled study of Table 6 are two different sets of numbers.
  • Table 2 uses extra tricks. The ImageNet results use a higher fine-tuning resolution (512 or 518) and Polyak averaging, which the Table 5 numbers do not, so do not mix the two.
  • Classification only. Detection and segmentation are left as future work, and the self-supervised experiment is preliminary, with the paper calling it promising.
  • Quadratic cost in sequence length. A higher resolution means more patches and more expensive self-attention, which is the motivation for later windowed attention and dynamic-resolution designs.

What to take from this paper

  1. Treat an image as a sequence. Cut patches, project them linearly, add position embeddings, and from there it is a standard Transformer, so NLP implementations and optimizations carry over directly.
  2. Scale beats inductive bias. With little data the convolutional prior helps, with enough data learning from scratch is sufficient and can be better.
  3. Pick the architecture after looking at the data size. In Table 5 the ranking of the same models flips as pre-training data grows.
  4. An accuracy-vs-compute curve says more than a single accuracy. The paper compares ViT and ResNet with controlled curves rather than single numbers.
  5. Sequence length is the main cost. The patch side PP and the resolution together fix NN, and attention cost grows with N2N^2.

Further reading

FAQ

How does ViT turn an image into Transformer input?
It cuts an H×W×C image into N=HW/P² patches of P×P pixels, flattens each into a P²C-dimensional vector and projects it to D dimensions with one trainable linear layer. A learnable [class] vector is prepended and learnable 1D position embeddings are added, giving N+1 tokens for a standard Transformer encoder. The output at the [class] position is used for classification.
Why does ViT underperform ResNets on small datasets?
The paper's explanation is that ViT has very little image-specific inductive bias. Locality and translation equivariance, which convolutions have built in, must be learned from data. The numbers in the paper support this. Pre-trained on ImageNet alone, ViT-Large is worse than ViT-Base (76.53% vs 77.91%). On ImageNet-21k the two are close. Only on JFT-300M does the larger model fully pay off.
What do names like ViT-B/16 and ViT-L/16 mean?
Base, Large and Huge are the model sizes (Base and Large follow BERT, Huge is new in the paper). The number after the slash is the patch side length in pixels. Smaller patches mean a longer sequence (it scales with 1/P²) and more compute, so ViT-L/16 is the Large model with 16×16-pixel patches.
Is ViT cheaper to train than a convolutional network?
In a controlled study on JFT-300M the paper reports that ViT needs roughly 2 to 4 times less compute for the same accuracy (average over five datasets). Recomputing from Table 6 on ImageNet alone gives about 1.8 to 2.3 times, the low end of that range. The paper also cautions that pre-training efficiency depends on the training schedule, optimizer and weight decay, not only the architecture.