An Image is Worth 16x16 Words

The paper showed that a standard Transformer encoder can be applied to image classification by treating fixed-size image patches as tokens.

Metadata

FieldValue
PaperAn Image is Worth 16x16 Words: Transformers for Image Recognition at Scale
AuthorsAlexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, Neil Houlsby
Year2020 preprint; 2021 conference
VenueICLR 2021
arXiv2010.11929
OpenReviewYicbFdNTTy
Statusverified

Question

Before ViT, attention was often combined with convolutional vision models or used inside otherwise convolutional architectures. The question was whether an image classifier could remove convolutional inductive bias almost entirely and rely on a Transformer over image patches.

The deeper architecture question is about representation units. CNNs treat images as dense grids and build locality, translation sharing, and hierarchy into the model. ViT asks whether an image can instead be treated like a sequence of visual tokens, with the Transformer learning the useful interactions from data.

This changes the vision modeling contract:

Main Claim

With enough pretraining data, a pure Transformer encoder over patch tokens can match or exceed strong convolutional image classifiers after transfer.

Narrowed claim:

where each is a flattened image patch projected into a token embedding.

The important qualifier is “with enough pretraining data.” ViT does not claim that patch Transformers are always better than CNNs in small-data settings.

Architecture Contract

ItemContract
Inputimage tensor
Tokenizationsplit image into fixed-size non-overlapping patches
Token embeddingflatten each patch and linearly project to model dimension
Position signallearned positional embedding
BackboneTransformer encoder
Readoutclass token representation
Natural task in paperimage classification and transfer

For an image:

with patch size , the number of patches is:

Each flattened patch has dimension:

and is projected into a token:

where:

The sequence length seen by the Transformer is because of the class token.

Method

ViT splits the image into patches, linearly embeds each patch, adds positional embeddings, prepends a class token, and feeds the sequence to a Transformer encoder.

The patch embedding step is:

where is a flattened patch and is a learned projection.

The Transformer encoder then applies standard self-attention and feed-forward blocks:

The image-level representation is taken from the final class token:

and classification is:

Patch Embedding as Convolution

The patch projection can be viewed as a convolution with kernel size , stride , and output channels .

This view is useful because ViT is not completely free of image assumptions. It still chooses a patch grid and a fixed patch size. What it removes is the deep convolutional hierarchy inside the backbone.

Design ChoiceConsequence
large patch sizeshorter sequence, less fine spatial detail
small patch sizelonger sequence, higher attention cost
learned positional embeddingscaptures training-resolution positions
class tokencreates a sequence-level readout
pure Transformer encoderweak local inductive bias compared with CNNs

Inductive Bias Tradeoff

CNNs build in locality and translation sharing:

ViT uses global self-attention over patch tokens:

This gives every patch a direct path to every other patch, but it does not force nearby pixels or patches to be treated as special.

ModelBuilt-in BiasData Need
CNNlocality, weight sharing, hierarchylower
ViTglobal token mixing, weak image-specific biashigher
Hybrid ViTconvolutional stem plus Transformermiddle

The paper’s central lesson is not “inductive bias is bad.” It is that enough data and scale can compensate for weaker hand-designed vision bias.

Complexity

Self-attention cost depends on the number of patches:

where:

So patch size directly controls attention cost:

but larger patches may lose fine spatial information.

Transformer Encoder Contract

The patch sequence is processed by a standard pre-normalization Transformer encoder. For one block, let

The self-attention sublayer is:

For heads, the head outputs are concatenated before the output projection:

The feed-forward sublayer is applied independently to each token:

With pre-normalization and residual paths, one block is:

This is the reusable architecture, while the image-specific part is the conversion of into . A paper note should keep these two contracts separate. Otherwise, later changes to patch embedding or positional encoding can be mistaken for changes to attention itself.

Multi-Head Shape Trace

Let the model width be and the per-head width be . For one input sequence:

TensorShapeMeaning
class token plus patch tokens
per headprojected token features
pairwise token scores
row-normalized attention weights
head outputweighted value mixture
concatenated outputall head channels
MLP hiddenper-token channel expansion

The class token participates in the same attention operation as patch tokens. Its final representation is used as the global readout in the canonical setup:

This means the class token is not a separate pooling operation outside the Transformer. It is a learned query-like participant in every layer and can gather information from all patches.

Parameter and FLOP Decomposition

Ignoring biases, one attention block with model width and MLP expansion width has approximate parameter count:

because the projections and output projection each have roughly parameters. The MLP contributes:

For tokens, the dominant attention computation is approximately:

where the first term represents projections and the second represents score/value interactions. The MLP computation is approximately:

Since

the patch size changes both the input representation and the quadratic attention term. Halving in each spatial direction multiplies by four and can multiply the pairwise term by sixteen.

ChangeSequence effectMain cost effect
increase image resolution grows quadratically with image sideattention pair cost grows sharply
decrease patch sizemore tokens preserve finer detailsame quadratic penalty
increase model width token representation becomes richerprojection and MLP costs grow with
increase depth repeated refinementcost roughly scales with number of blocks

This is why later hierarchical models such as Swin Transformer alter the interaction pattern rather than simply making global ViT larger.

Patch Size Is an Information and Systems Choice

Patch size is often described as a hyperparameter, but it defines the basic visual unit:

For a fixed image size, smaller patches provide more tokens and a finer spatial lattice. Larger patches reduce the sequence length but force the first projection to summarize more local variation.

Patch choiceBenefitRisk
large lower attention and memory costsmall objects and boundaries are compressed early
small finer spatial representationquadratic token interaction and larger activation memory
variable patch sizepossible multi-scale efficiencypositional and batching contract becomes more complex

The first patch projection is also where the model commits to a stride. There is no later operation that can recover spatial information that was discarded by an overly coarse non-overlapping patchification.

Positional Embedding Contract

Self-attention by itself is permutation-equivariant over the token sequence. If the patch tokens are permuted and no position signal changes, the attention computation has no way to distinguish their spatial locations. ViT therefore adds a learned position matrix:

where

The class-token row and patch-token rows have different semantic roles. When transferring to another resolution, the patch-token grid changes from to a new grid. A common adaptation is to interpolate the patch portion of while preserving the class-token row.

The interpolation is an engineering operation, not a new learned architecture claim. Record it in the transfer protocol because a checkpoint used at a new resolution is not identical to the original training setup.

Class Token Versus Global Average Pooling

The canonical ViT reads the class token, but the same encoder can expose a pooled representation:

The choice changes the readout contract without changing the internal attention blocks.

ReadoutInterpretationEvaluation question
class tokenlearned global collectordoes a dedicated token gather useful evidence?
global average poolingsymmetric aggregation of patch featuresdoes the patch representation already contain enough global information?
dense patch featurespreserve spatial outputscan the backbone support localization or segmentation?

When comparing two ViT implementations, do not call them the same model if one changes the readout, fine-tuning head, or pooling normalization without recording it.

Model Variants and Scaling

ViT is a family, not one fixed model. A variant is determined by at least:

Here is patch size, model width, depth, number of heads, feed-forward width, and sequence length. Two experiments both labeled “ViT-B” can still differ in image resolution, patch size, pretraining data, or fine-tuning recipe.

Scaling axisWhat increasesWhat it tests
width and head dimensionsfeature capacity and matrix efficiency
depthnumber of encoder blocksiterative token interaction and abstraction
resolution and therefore fine detail versus quadratic cost
patch granularity and input compression and spatial fidelity
pretraining dataexamples and diversitywhether weak image bias can be learned from data

The paper’s central comparison is therefore a joint scaling statement. A small-data, low-resolution, shallow ViT is not an adequate proxy for the regime in which the paper’s main claim was established.

What the Paper Actually Compares

The strongest interpretation of the paper’s evidence is:

It does not isolate every possible difference between CNNs and Transformers. The comparison includes choices about model scale, pretraining data, compute, augmentation, and transfer protocol.

Comparison questionEvidence needed
Can patch tokens support image classification?matched classification evaluation
Does ViT transfer to smaller datasets?same downstream protocol and data budget
Is the result due to attention rather than scale?parameter/FLOP/data-matched controls
Does ViT provide a general vision backbone?dense prediction or localization evaluation
Does patchification preserve small objects?resolution and object-size stratification

This boundary matters when using ViT as a baseline for scientific images. A result on image classification should not automatically be described as a result on dense spatial reasoning.

Training Recipe and Data Regime

ViT’s apparent data hunger is part of its architectural story. A CNN starts with locality and weight sharing; a patch Transformer must learn more of the useful spatial structure from examples. The comparison can be expressed as:

For a fair reproduction, capture:

VariableWhy it matters
pretraining dataset sizecompensates for weaker hand-designed locality
label quality and duplicateschanges the amount of usable supervision
optimizer and scheduleaffects large Transformer convergence
augmentation and regularizationaffects small-data generalization
weight decay and dropoutchanges the effective capacity
fine-tuning resolutionchanges positional embedding and token count
initialization and warmupcan affect stability at scale

Comparing ViT with a CNN trained using a stronger or weaker recipe can answer a recipe question rather than an architecture question.

Transfer and Resolution Changes

Suppose a checkpoint was trained with patch grid and is transferred to grid . The token projection and Transformer width may remain unchanged, while the positional table must be adapted:

The transfer contract should state:

  1. original image resolution and patch size;
  2. target image resolution and patch size;
  3. whether patch size is unchanged;
  4. positional interpolation method;
  5. whether the classification head is replaced;
  6. whether all layers or only the head are fine-tuned.

If changes, the first projection itself no longer has the same input shape . That is a different adaptation problem from changing only the image resolution.

Dense Prediction Boundary

The original ViT setup is naturally a classification model:

Dense prediction requires patch-level or multi-scale features:

The vanilla architecture has no native hierarchy of resolutions. Later designs address this in different ways:

DesignAdded structure
hierarchical Transformerprogressively merges tokens and restricts interaction windows
decoder bridgereshapes tokens and upsamples them for dense outputs
feature pyramid adapterprojects selected layers into multi-scale maps
hybrid stemadds convolutional locality before global token mixing

Therefore, a ViT classification result and a ViT detection result should not be treated as the same architecture contract.

Ablation Matrix

AblationHold fixedMain question
patch sizedata and model budgethow much spatial detail is lost or gained?
class token versus poolingencoder and recipewhich global readout is more robust?
positional embeddingpatch sequence and encoderhow much does explicit spatial identity matter?
pretraining scalearchitecturecan data substitute for convolutional bias?
model width/depthdata and recipewhere does ViT scaling saturate?
hybrid stemtoken count and encoderdoes early local processing improve sample efficiency?
fine-tuning resolutioncheckpoint and downstream datahow robust is position adaptation?
regularizationarchitecture and datais the observed gap optimization or representation?

For each row, check whether the change also alters parameters, FLOPs, sequence length, or activation memory. A patch-size ablation is rarely a pure representation ablation because it changes the attention budget at the same time.

Failure Modes

  • Small-data overclaim: a ViT trained from scratch on a small dataset is not a direct test of the paper’s large-pretraining regime.
  • Patch aliasing: fixed non-overlapping patches can discard boundaries, textures, or small objects before the first Transformer layer.
  • Quadratic scaling: global attention becomes expensive as resolution or patch density grows.
  • Position mismatch: using learned positional embeddings at a new grid without a documented adaptation can invalidate transfer comparisons.
  • Backbone/head confusion: a dense-prediction result may owe substantial performance to the decoder or feature pyramid.
  • Recipe mismatch: optimizer, augmentation, regularization, and pretraining data can dominate the comparison with CNNs.
  • Representation shortcut: global token mixing can exploit dataset-specific correlations that do not transfer under distribution shift.

Transfer to Scientific and Biological Data

ViT is useful for any domain where a structured object can be converted into meaningful patches, but patchification must preserve the task’s symmetries and resolution requirements.

Scientific inputViT-style tokenizationMain question
microscopy imagenon-overlapping image patchesare cellular boundaries smaller than the patch?
protein contact/distance mapsquare map patchesdoes patch order preserve pairwise residue semantics?
voxelized molecular field3D patch or projection tokenshow are rotations and translations handled?
molecular surface rasterlocal surface patchesis orientation encoded or normalized?
protein sequencesequence tokens, not image patchesshould sequence order and residue identity be modeled directly?
molecular graphgraph tokens or graph-to-set adapterdoes a grid tokenization destroy adjacency?

For coordinate-based molecular inputs, vanilla ViT is not translation- or rotation-equivariant by construction. If the target should respect those transformations, compare it with a geometric architecture such as EGNN or a suitable SE(3)-equivariant model. A ViT baseline can still be informative, but its symmetry assumptions must be stated.

Reproduction Specification

Before reproducing or adapting ViT, record:

FieldRequired value
image shape
patch shape and stride
token count plus class token policy
model width
depthnumber of encoder blocks
heads and per-head width
MLP width and activation
normalizationaxes, placement, epsilon
position signallearned, fixed, relative, or interpolated
readoutclass token, pooling, or dense features
pretrainingdataset, objective, duration, and checkpoint
transfertarget resolution, head, and fine-tuning policy
systemprecision, batch size, memory optimization, and hardware

Minimum shape checks:

  1. Patchification produces exactly patches.
  2. The patch projection produces width .
  3. The class token and positional table have compatible sequence length.
  4. Each attention head has the declared .
  5. The residual stream preserves through every block.
  6. The classifier reads the documented representation.
  7. Resolution transfer changes only the declared components.

One-Line Comparison With ConvNeXt

The cleanest comparison is:

Both can use residual blocks, LayerNorm-like normalization, GELU, large-scale pretraining, and modern regularization. The difference that remains is the spatial mixing operator and the resulting inductive bias.

Data Scale and Transfer

ViT is a data-scale paper as much as an architecture paper.

Training RegimeReading
small or mid-sized labeled dataCNN inductive bias can be stronger
large-scale supervised pretrainingViT becomes competitive or better
transfer to downstream datasetstests representation reuse rather than only ImageNet fitting

The paper’s architecture claim should therefore be tied to pretraining scale:

This is the same broad pattern later seen in language and multimodal foundation models.

Evidence

ClaimEvidence in paperCaveat
Pure Transformer vision models can perform stronglyimage classification transfer results after large-scale pretrainingdepends heavily on pretraining data scale
Patch tokenization is a viable image representationcomparison against strong CNN baselineslocal inductive bias is weaker than CNNs
Data scale changes architecture rankingsmaller-data settings favor stronger inductive biasnot all domains have large pretraining data

Benchmark Reading

ViT evidence should be read through three axes.

AxisWhat to check
pretraining datasethow large and how close to downstream evaluation
transfer protocolwhether the same backbone transfers cleanly
baseline strengthwhether CNN baselines have comparable data and training recipe

The headline result is not just ImageNet accuracy. It is that a generic Transformer encoder can become a high-quality vision backbone after large-scale pretraining.

Benchmark Card

FieldValue
Main taskimage classification
Input/output unitimage to class label
Main routepatch tokens to Transformer encoder
Main comparisonconvolutional vision backbones and hybrid models
Not directly testeddense segmentation as the core task, molecular graphs, protein structure

Ablation Reading

AxisWhat it testsReading
patch sizetoken granularity and attention costarchitecture quality depends on representation unit
model sizewhether Transformer scaling helps visionlarger models need enough data
pretraining dataset sizedata-scale dependencecore to the paper’s conclusion
hybrid vs pure ViTvalue of convolutional image biasCNN stems can help, especially under lower data
positional embeddingsspatial information injectionimage token order is not inherent to attention

The most important ablation lesson is that architecture and data scale interact. ViT’s weakness under smaller data is not an implementation footnote; it is part of the paper’s claim.

Relation to Other Architecture Papers

PaperWhat Changes
[[papers/architectures/alexnetAlexNet]]
[[papers/architectures/deep-residual-learningResNet]]
ViTreplaces convolutional backbone with patch-token Transformer
[[papers/architectures/emerging-properties-in-self-supervised-vision-transformersDINO]]
[[papers/architectures/masked-autoencoders-are-scalable-vision-learnersMAE]]
[[papers/architectures/swin-transformerSwin Transformer]]

ViT is the cleanest baseline for asking whether an image can be treated as a token sequence.

Implementation Notes

  • Patch embedding fixes the granularity of visual tokens; changing patch size changes sequence length and compute.
  • Positional embeddings may need interpolation when transferring to different image resolutions.
  • Strong augmentation and regularization matter; weak recipes can make ViT look worse than it is.
  • The class token is a readout convention, not a law; later models use pooling or dense readouts.
  • For dense prediction, plain ViT needs adaptation because it lacks a native feature pyramid.
  • Data leakage or near-duplicate pretraining images can distort transfer claims.

Limitations

  • ViT trades convolutional locality for data-hungry global token mixing.
  • The paper’s headline strength depends on large-scale pretraining and transfer.
  • Patch size, positional embedding, augmentation, regularization, and pretraining dataset all affect the architecture claim.
  • Dense prediction and small-data vision require additional adaptations.
  • Attention cost is quadratic in the number of patches.
  • Patch tokenization can discard fine spatial detail when patches are too large.
  • The paper does not prove that convolutional bias is unnecessary in all vision tasks.

Why It Matters

ViT made Transformer encoders a general vision backbone and clarified when architectural inductive bias can be replaced by data scale.

The reusable pattern is:

This pattern matters beyond images. It is the same abstraction used when turning molecules, protein sequences, point clouds, or multimodal inputs into token-like units. The hard part is choosing tokens that preserve the right structure.

Connections