Skip to main content
issue 2026-08-12AI Research40 minICLR 2021interactive

Vision Transformer

This research paper explains how to drop CNN inductive bias and still classify images: treat 16×16 patches like words, pre-train at scale, then transfer.

Vision Transformer turns an image into a sequence of patch tokensLeft: an image grid splits into fixed patches. Middle: each patch is linearly embedded and a class token leads the sequence with position embeddings. Right: a standard Transformer encoder classifies from the class token.ENTER · PATCHIFYIMAGE → P×P TILESPN = HW / P²RUN · EMBEDCLS + E·PATCH + E_POSCLSLEADT1T2TNLEAVE · ENCODETRANSFORMER → yENCMSA+MLP × LyLN(CLS)PATCHES LIKE WORDS · CLASS TOKEN LEADS · STANDARD ENCODERViT patch-to-token stackStacked flow: image patches enter, linear embeddings plus class token run, Transformer encoder leaves a class embedding for the label head.ENTER · EMBED · LEAVEENTER · P×P PATCH GRIDN = HW / P² tilesRUN · CLS + PATCH EMBEDSadd 1D position tableENCODER · MSA + MLP × Lglobal attention on tokensLEAVE · y = LN(CLS)linear head → class labelAN IMAGE IS A SEQUENCE OF PATCHES

For a decade, “vision backbone” meant a stack of convolutions. Local filters, shared weights, translation equivariance — the inductive biases that made ImageNet tractable. Transformers had taken over NLP, but vision papers still bolted attention onto CNN stems, or replaced only a few layers, as if pixels were too spatial to trust a plain sequence model.

Dosovitskiy et al.’s punchline is deliberately blunt: cut the image into patches and treat them like words. Linearly embed each patch, prepend a class token, add position embeddings, run a standard Transformer encoder. When you pre-train that recipe at sufficient scale, large-scale data trumps the missing CNN bias.

What this paper explains

The Vision Transformer (ViT) shows that a pure Transformer encoder — the same MSA + MLP stack used in NLP — can be a competitive image classifier when the only vision-specific step is the initial patch embedding:

  1. Split an H×WH\times W image into a grid of P×PP\times P patches (P=16P=16 in the title’s canonical setting).
  2. Flatten each patch and multiply by a learned matrix E\mathbf{E} to get a DD-dimensional embedding.
  3. Prepend a learnable class token (BERT-style) and add learnable 1D position embeddings.
  4. Run LL layers of LayerNorm → multi-head self-attention → LayerNorm → MLP, with residuals.
  5. Take the class token’s final state, LayerNorm it, and feed a classification head.

They study ViT-Base / Large / Huge variants, pre-train on ImageNet-21k or JFT-300M, fine-tune on mid-sized benchmarks, and compare against strong ResNet / BiT baselines under a compute-aware lens.

Patch embedding pipelineAn image is cut into a grid of P by P patches. Each flattened patch is multiplied by E to produce a D-dimensional token. Sequence length is N equals H W over P squared.H×W imagepatchP²·Cflatten× E(P²C)×DCLST1T2TN+ E_pos → z₀
ViT never attends pixel-to-pixel. It attends over N = HW/P² patch tokens (plus the class token), each living in the shared width D.

Prior limits

  • Pixel-level attention is quadratic and huge. Attending every pixel to every pixel on a 224×224224\times 224 image is a non-starter; something must reduce the sequence length.
  • CNN-first hybrids. Prior vision + attention work typically kept convolutional stems or hierarchical feature maps so locality stayed hard-coded.
  • Inductive bias vs data. On mid-sized ImageNet-scale training without strong regularization, Transformers lag comparable ResNets by a few percentage points — exactly what you expect when locality and translation equivariance are not baked in.
  • The open question. If you strip those biases down to “patches + positions,” can scale alone recover (and surpass) CNN accuracy?

The mechanism

Patchify. For patch size PP and channels CC, each patch is a vector in RP2C\mathbb{R}^{P^{2}\cdot C}. The number of patches — and thus the Transformer sequence length — is

N=HWP2.N=\frac{HW}{P^{2}}.

Smaller PP means a longer sequence and more compute; ViT-L/16 means the Large variant with 16×1616\times 16 patches.

Linear patch embedding + class token + positions. With projection ER(P2C)×D\mathbf{E}\in\mathbb{R}^{(P^{2}\cdot C)\times D} and position table EposR(N+1)×D\mathbf{E}_{\mathrm{pos}}\in\mathbb{R}^{(N+1)\times D}:

z0=[xclass;xp1E;xp2E;;xpNE]+Epos\mathbf{z}_{0}=[\mathbf{x}_{\mathrm{class}};\,\mathbf{x}^{1}_{p}\mathbf{E};\,\mathbf{x}^{2}_{p}\mathbf{E};\cdots;\,\mathbf{x}^{N}_{p}\mathbf{E}]+\mathbf{E}_{\mathrm{pos}}

Encoder. Pre-norm Transformer blocks (LN before MSA/MLP, residual after):

z=MSA(LN(z1))+z1,z=MLP(LN(z))+z\mathbf{z}^{\prime}_{\ell}=\operatorname{MSA}(\operatorname{LN}(\mathbf{z}_{\ell-1}))+\mathbf{z}_{\ell-1},\qquad \mathbf{z}_{\ell}=\operatorname{MLP}(\operatorname{LN}(\mathbf{z}^{\prime}_{\ell}))+\mathbf{z}^{\prime}_{\ell}

for =1L\ell=1\ldots L. The image representation is the LayerNorm’d class token:

y=LN(zL0).\mathbf{y}=\operatorname{LN}(\mathbf{z}_{L}^{0}).

Pre-training uses an MLP head on y\mathbf{y}; fine-tuning replaces it with a single linear layer (zero-initialized) for the target label set.

Where the 2D bias actually lives. Self-attention is global. The paper’s own accounting: 2D structure is injected mainly when cutting patches, and again when 2D-interpolating position embeddings to fine-tune at higher resolution (same PP, longer NN). Learnable 1D positions were enough; more elaborate 2D embeddings did not help much in their Appendix D.4 ablations.

Interactive

How big should each patch be?

Fix a 224×224 image. Slide patch size P. Sequence length is N = (H/P)² patch tokens (+1 class token). Smaller patches buy detail with a longer — and quadratically costlier — attention sequence.

P=16 is the title setting: 196 patches (+ CLS). ViT-L/16 means Large width with this patch size.

Model ladder (Table 1). ViT-Base: L=12L=12, D=768D=768, MLP 30723072, 1212 heads, 8686M params. ViT-Large: 2424 / 10241024 / 40964096 / 1616 heads / 307307M. ViT-Huge: 3232 / 12801280 / 51205120 / 1616 heads / 632632M.

Hybrid footnote. You can also form the token sequence from CNN feature-map patches (even 1×11\times 1 spatial patches). The headline result, though, is that raw image patches already work when data and compute are large.

Class token classification pathThe class token sits at position zero. After L encoder blocks its state is LayerNormed to form y, then a linear head predicts the class.CLST1T2T3T4z₀ · length N+1Encoder × L · LN → MSA → LN → MLPglobal self-attention among patchesz_L⁰CLS statey
Classification does not average patch tokens by default. ViT reads y = LN(z_L⁰) — the class token after the full encoder — then attaches a head (MLP at pre-train, linear at fine-tune).

Algorithm walkthrough

  1. Choose image size (H,W)(H,W), patch size PP, and model width DD (e.g. 224×224224\times 224, P=16P=16N=196N=196 patches + 11 class token).
  2. Extract non-overlapping patches; flatten each to P2CP^{2}\cdot C and multiply by E\mathbf{E}.
  3. Build z0\mathbf{z}_{0} with xclass\mathbf{x}_{\mathrm{class}} in front and Epos\mathbf{E}_{\mathrm{pos}} added.
  4. For each of LL layers: LN → multi-head self-attention → residual → LN → GELU MLP → residual.
  5. Read y=LN(zL0)\mathbf{y}=\operatorname{LN}(\mathbf{z}_{L}^{0}); apply the classification head.
  6. Fine-tune at higher resolution: keep PP fixed, grow NN, bilinearly interpolate the patch position embeddings on the 2D grid, replace the head, train with SGD + momentum (their fine-tune default).

The opening figure is the same pipeline in space: an image plane fractures into a patch grid; tiles lift into a token row; the class token leads them through the encoder; a label leaves the far end.

What to notice when reading

  • ViT is an interface paper as much as a model paper: keep the NLP Transformer intact; change how pixels become tokens.
  • Sequence length scales as 1/P21/P^{2} — the patch-size knob is a direct compute/accuracy trade.
  • On small data, CNNs still win; the paper’s thesis is about the large-data regime, not a blanket “convolutions are obsolete.”
  • Position embeddings learn distance structure (nearby patches often get similar embeddings) even though the architecture did not hard-code a 2D relative bias.
  • Hybrid CNN→Transformer stems are optional; do not confuse them with the pure ViT headline.

Results and evidence

Numbers below are as reported by Dosovitskiy et al. — not universal constants.

Headline transfer accuracies (abstract / intro). Their best model reaches 88.55% on ImageNet, 90.72% on ImageNet-ReaL, 94.55% on CIFAR-100, and 77.63% on the VTAB suite of 19 tasks, when pre-trained at scale (ImageNet-21k or JFT-300M) and fine-tuned.

Table 2 framing. ViT models pre-trained on JFT-300M outperform ResNet-based baselines on the reported datasets while taking substantially less computational resources to pre-train. ViT-L/16 on JFT beats BiT-L (same pre-train data) across their task suite; ViT-H/14 improves further on ImageNet, CIFAR-100, and VTAB. ViT-L/16 pre-trained on public ImageNet-21k also transfers well; they note it could be trained on a cloud TPUv3 with 8 cores in about 30 days.

Small-data caveat (intro). Trained on mid-sized ImageNet without strong regularization, ViTs land a few percentage points below ResNets of comparable size — the inductive-bias gap the rest of the paper overcomes with scale.

Scaling (Figures 3–4, Section 4.3). Large ViTs underperform BiT ResNets when pre-trained on smaller datasets, then overtake as pre-training data grows; larger ViT variants similarly overtake smaller ones once the dataset is big enough. Their slogan: large-scale training trumps inductive bias.

Controlled compute (Section 4.4). They compare architectures under pre-training compute budgets; ViT transfers strongly per FLOP relative to ResNets/hybrids in the regimes they plot — read the paper’s figures rather than treating any single FLOP number as magic.

Limitations

  • Data hunger. Without large pre-training (or heavy regularization), the missing locality bias hurts.
  • Quadratic attention cost. Global MSA over NN patches is fine at 224224518518 classification resolutions; naive ViT is not a free lunch for very high-resolution dense prediction (later hierarchical / windowed vision Transformers address this — outside this paper’s claims).
  • Pre-train compute caveats. The authors note efficiency depends on schedule, optimizer, and regularization, not architecture alone; their BiT comparisons are careful but not the final word for every hardware stack.
  • JFT-300M access. The strongest numbers use an in-house dataset; ImageNet-21k results are the reproducible public reference point.
  • Classification focus. The paper is about image recognition backbones and transfer, not detection/segmentation recipes (U-Net-style decoders, etc.).

How to read the paper

  1. Figure 1 + Equations (1)–(4) — the entire architecture fits on one page; make sure patch shape, NN, class token, and pre-norm blocks click.
  2. Inductive bias paragraph (Section 3.1) — the conceptual contrast with CNNs.
  3. Table 1 — Base/Large/Huge and the /16 vs /14 patch naming.
  4. Section 3.2 (fine-tuning / resolution) — position-embedding interpolation when NN grows.
  5. Table 2 + Figures 3–4 — transfer results and the data-scale story.
  6. Section 4.4 + appendices — compute comparisons and position-embedding ablations if you care about “why not 2D RoPE-style bias.”

Knowledge check

In ViT with non-overlapping patches, what is the Transformer sequence length before adding the class token?

Which representation does ViT use for the final image embedding fed to the classification head?

When fine-tuning ViT at a higher image resolution with the same patch size P, what must be adjusted?

Why can ViT underperform ResNets when trained only on mid-sized ImageNet without strong regularization?

Keep reading

  • Attention Is All You Need — the encoder stack ViT reuses almost unchanged.
  • BERT — the class-token pattern ViT copies for classification.
  • ResNet — the convolutional inductive-bias baseline ViT challenges at scale.
  • CLIP (Radford et al., 2021) — dual-encoder contrastive training that often starts from ViT image towers.

Sources

  • Dosovitskiy et al., An Image is Worth 16×16 Words: Transformers for Image Recognition at Scale, ICLR 2021. https://arxiv.org/abs/2010.11929
  • Vaswani et al., Attention Is All You Need, NeurIPS 2017. https://arxiv.org/abs/1706.03762
  • Devlin et al., BERT, NAACL 2019. https://arxiv.org/abs/1810.04805
  • He et al., Deep Residual Learning for Image Recognition, CVPR 2016. https://arxiv.org/abs/1512.03385
  • Kolesnikov et al., Big Transfer (BiT), ECCV 2020 — primary ResNet transfer baseline family in the ViT comparisons.