Search

Search papers and lessons

Vision Transformer (ViT)

Level 4 · 10 min read

A Vision Transformer cuts an image into fixed-size patches, treats each patch as a token, and runs a standard transformer over the sequence, with no convolutions.

On this page

  • Colour = topic mix
  • Calculus
  • Probability
  • Neural network basics
  • Linear algebra
  • Architectures
  • Discrete math
  • Sign in to see your progress

TL;DR

A Vision Transformer, or ViT, looks at an image as a sequence. It cuts the image into a grid of small square patches, turns each patch into a vector, and feeds the sequence to an ordinary transformer encoder. The only image-specific parts are the patch cutting and a learned position for each patch. Given enough pre-training data, it matches or beats the best convolutional networks on image classification.

The result that made it important is that the vision-specific bias of convolutions is not needed when there is enough data. The transformer learns the spatial structure from examples instead of having it built in.

Where you'll see it: image classifiers and the image encoders in vision-language models, and as the backbone of many detection and segmentation systems.

Intuition

A picture cut into words

A sentence is a row of words, and a transformer is good at relating any word to any other. An image has no words, but it can be cut into pieces. Take a 224×224224 \times 224 photo and slice it into a grid of 16×1616 \times 16 squares. That gives 14×14=19614 \times 14 = 196 pieces. Flatten each piece into a list of numbers, map it to a vector, and you have 196 tokens, each one standing for a small region of the picture.

The transformer then does what it does for text. Each patch attends to every other patch, so information can flow from the top-left corner to the bottom-right in a single layer. A convolution has to stack many layers before a pixel can be influenced by a distant one.

flowchart LR
  I[Image 224 by 224] --> C[Cut into 196 patches of 16 by 16]
  C --> E[Linear projection to D dimensions]
  E --> T[Add class token and position embeddings]
  T --> R[Transformer encoder blocks]
  R --> H[Classification head on class token]

Why this is surprising

A convolutional network has strong assumptions built in. Its filters are local, and the same filter is slid over the whole image, so it assumes that a useful pattern looks the same wherever it appears. Those assumptions help a lot on small datasets. A transformer has almost none of them. It must learn that nearby patches are related and that the same object can appear anywhere.

The paper's bet was that this is a fair trade at scale. With small data the transformer does worse than a ResNet of similar size. With very large data it catches up and then overtakes, because the learned structure is not limited by the built-in one. The architecture is kept close to the original transformer, so the large-scale tooling that already exists for language models carries over almost unchanged.

The math

Patch embedding

Definition: Patch embedding

Let an image have height HH, width WW and CC channels, and let each patch be P×PP \times P pixels. The number of patches is N=HW/P2N = HW / P^2. Flatten each patch xp(i)∈RP2C\mathbf{x}_p^{(i)} \in \mathbb{R}^{P^2 C} and map it with a learned matrix E∈RD×P2CE \in \mathbb{R}^{D \times P^2 C} and bias b\mathbf{b}:

zi0=E xp(i)+b,i=1,…,N.\mathbf{z}_i^{0} = E\,\mathbf{x}_p^{(i)} + \mathbf{b}, \qquad i = 1, \dots, N.

The model width is DD, the same in every layer.

Here HH and WW are the image height and width in pixels, CC is the number of colour channels (3 for RGB), and PP is the side of each square patch. The result zi0\mathbf{z}_i^{0} is the embedding of patch ii, a vector of length DD. The matrix EE is the whole patch-embedding layer. It is a linear map, and in practice it is implemented as a convolution with kernel size and stride both equal to PP, which does the same arithmetic.

The sequence

Two additional pieces turn the patch embeddings into an input the encoder can use. First, a learnable class token xcls\mathbf{x}_{\text{cls}} is prepended, so the sequence has N+1N + 1 entries. Second, a learnable position embedding Epos\mathbf{E}_{\text{pos}} is added to every entry, so the model can tell where each patch came from. The input is

z0=[xcls;  Exp(1);  … ;  Exp(N)]+Epos.\mathbf{z}_0 = \big[\mathbf{x}_{\text{cls}};\; E\mathbf{x}_p^{(1)};\; \dots;\; E\mathbf{x}_p^{(N)}\big] + \mathbf{E}_{\text{pos}}.

The position embeddings are plain learned vectors, one per index. The paper found that more elaborate two-dimensional position encodings gave no clear gain.

The encoder

The encoder is a stack of LL blocks. Each block applies layer normalization, multi-head self-attention, a residual addition, then layer normalization, a two-layer MLP with a GELU non-linearity, and another residual addition. Writing LN\mathrm{LN} for layer normalization and MSA\mathrm{MSA} for multi-head self-attention, one block is

zℓ′=MSA(LN(zℓ−1))+zℓ−1,zℓ=MLP(LN(zℓ′))+zℓ′.\mathbf{z}'_\ell = \mathrm{MSA}\big(\mathrm{LN}(\mathbf{z}_{\ell-1})\big) + \mathbf{z}_{\ell-1}, \qquad \mathbf{z}_\ell = \mathrm{MLP}\big(\mathrm{LN}(\mathbf{z}'_\ell)\big) + \mathbf{z}'_\ell.

The two residual additions are the residual connections that let gradients reach early layers in a deep stack. The image representation is the final state of the class token, y=LN(zL0)\mathbf{y} = \mathrm{LN}(\mathbf{z}_L^{0}), and a classification head turns it into class scores. The class token is the only part of the sequence the head reads. Every patch token contributes to it through attention.

Cost of attention

Self-attention compares every token with every other. For nn tokens the score matrix has n2n^2 entries, so the attention cost grows with the square of the number of patches. The MLP and the patch projection grow only linearly in nn. Doubling the image side quadruples the number of patches and multiplies the attention cost by sixteen.

Worked examples

Example
A 4 by 4 image with 2 by 2 patches

Take a single-channel image of size 4×44 \times 4 with patch size P=2P = 2.

  1. Number of patches: N=4⋅4/22=4N = 4 \cdot 4 / 2^2 = 4.
  2. Take the top-left patch, flattened to x=(1,0,0,1)\mathbf{x} = (1, 0, 0, 1), which is a diagonal of ones.
  3. Use a toy projection to width D=3D = 3 with E=(111110010110)E = \begin{pmatrix} 1 & 1 & 1 & 1 \\ 1 & 0 & 0 & 1 \\ 0 & 1 & 1 & 0 \end{pmatrix}. Then Ex=(1+0+0+1,  1+0+0+1,  0+0+0+0)=(2,2,0)E\mathbf{x} = (1+0+0+1,\; 1+0+0+1,\; 0+0+0+0) = (2, 2, 0).
  4. Add a position embedding for patch 1, say (0,0,1)(0, 0, 1): the result is (2,2,1)(2, 2, 1).
  5. Prepend the class token. The encoder now sees N+1=5N + 1 = 5 tokens, each of width 3.

Interpretation: the image has become a short sequence of five vectors. The transformer never sees the 4×44 \times 4 grid directly. It sees four patch tokens and one summary token, and its only knowledge of where a patch sits comes from its position embedding.

Example
ViT-Base at 224 pixels: how many tokens and how much attention

The standard ViT-Base/16 model takes 224×224224 \times 224 RGB input, so P=16P = 16 and C=3C = 3.

  1. Patches: N=224⋅224/162=50176/256=196N = 224 \cdot 224 / 16^2 = 50176 / 256 = 196.
  2. Each patch has P2C=16⋅16⋅3=768P^2 C = 16 \cdot 16 \cdot 3 = 768 values, which the projection maps to D=768D = 768.
  3. With the class token the sequence length is n=197n = 197.
  4. One attention score matrix has 1972=38809197^2 = 38809 entries. ViT-Base has 12 layers and 12 heads, so the total is 12⋅12⋅38809=558849612 \cdot 12 \cdot 38809 = 5588496 score entries for one image.
  5. Raise the resolution to 448×448448 \times 448 with the same patch size. Now N=784N = 784, n=785n = 785, and one score matrix has 7852=616225785^2 = 616225 entries. That is 616225/38809≈15.9616225 / 38809 \approx 15.9 times as many, close to the factor of 16 predicted by (784/196)2(784/196)^2.

Interpretation: doubling the image side is cheap for a convolution, which scales roughly with the number of pixels, but expensive here because attention scales with the square of the patch count. This is why ViT is usually run at a fixed resolution during pre-training, and why later work restricts attention to local windows.

Tradeoffs and failure modes

SituationWhat goes wrongBetter choice
Small labelled dataset, no pre-trainingThe model has little built-in structure and overfits or underperforms a ResNetUse a convolutional network, or pre-train on a large dataset first
Very large pre-training data availableConvolutions limit what the model can learnViT scales well and transfers strongly after pre-training
High-resolution imagesAttention cost grows with the square of the patch countWindowed attention, or a hierarchical model that shrinks the token count
Dense prediction such as segmentationA single coarse grid of patches gives poor detailHierarchical transformers or a convolutional decoder on top
Patch boundaries cut through objectsInformation that spans a boundary must be learned across tokensOverlapping patches, or a convolutional stem before the transformer

The main practical failure is treating ViT as a drop-in replacement for a CNN on a small dataset. Without large-scale pre-training it often loses, and the reported gains come from the pre-training data, not from the architecture alone.

History

Attention had been used in vision before, usually alongside convolutions. The transformer itself was introduced by Ashish Vaswani and colleagues in 2017 for machine translation. Alexey Dosovitskiy and co-authors at Google Research published the Vision Transformer in 2020, under the title "An Image is Worth 16x16 Words", and presented it at ICLR 2021. Their question was whether the standard transformer could be applied to images with almost no change. The answer was yes, provided the training data was large. Pre-training on the 300 million image JFT dataset let the largest model reach 88.55 percent top-1 accuracy on ImageNet, slightly above the best convolutional comparison in their table.

Follow-up work made ViT easier to train on smaller data. Touvron and colleagues' DeiT showed in 2020 that good results were possible on ImageNet alone with stronger augmentation and distillation. Later hierarchical designs such as the Swin Transformer restricted attention to local windows to handle high resolution. The patch-as-token idea became a common base for image encoders in multimodal systems.

Check yourself

QuestionRecall: how is an image turned into a sequence of tokens in a Vision Transformer?Show answer

The image is cut into a grid of non-overlapping square patches. Each patch is flattened and mapped by a learned linear projection to a vector of width D. A learned class token is prepended, and learned position embeddings are added. The result is a sequence of N + 1 vectors fed to a standard transformer encoder.

QuestionCompute: a 320 by 240 RGB image is split into 16 by 16 patches. How many patch tokens are there, and how many entries does one attention score matrix have, counting the class token?Show answer

The number of patches is N=320⋅240/256=300N = 320 \cdot 240 / 256 = 300. With the class token the sequence length is n=301n = 301. One score matrix has 3012=90601301^2 = 90601 entries.

QuestionWhy: a convolutional network usually beats a ViT when both are trained on a small dataset. Why?Show answer

A convolution builds in locality and translation equivariance: the same local filter is applied everywhere, and nearby pixels are combined first. These assumptions are correct for most images, so the network needs less data to learn. A ViT has to learn them from examples, and with little data it does not learn them well enough to match the convolution.

QuestionApplied: a team wants to run a ViT on 1024 by 1024 satellite images for segmentation, using 16 by 16 patches. What problem will they hit first, and what would you suggest?Show answer

The sequence has N=4096N = 4096 patches, so each attention score matrix has about 40972≈16.84097^2 \approx 16.8 million entries per head per layer, and the memory and time grow quickly. A single coarse grid of 16 by 16 patches also loses fine spatial detail needed for segmentation. Suggestions: use windowed or hierarchical attention to reduce the token count per attention operation, or put a convolutional decoder or feature pyramid on top to recover detail.

Sources