◆ AI All-in-One

Level 3 In-Depth AI · Vision, Audio and Multimodal

Vision Transformers

Cut an image into small square patches, treat each patch like a word, and feed the sequence to a standard Transformer. Vision Transformers need more data than CNNs, but they scale further, and they are now the image encoders inside CLIP, Segment Anything and multimodal chatbots.

Level
●●●●● Intermediate
Reading
12 min
To learn it well
1 hour to read, an afternoon to practise
↗ Plan a path here

Read first

The TransformerImage Classification

This leads to

CLIP and Contrastive LearningVideo Understanding
The full path from zero — 32 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. The Chain Rule
  9. Dot Product, Norms and Similarity
  10. Supervised, Unsupervised and Reinforcement Learning
  11. Gradient Descent
  12. Tensors and Shapes
  13. Supervised Learning
  14. Images as Data
  15. Linear Regression
  16. The Perceptron
  17. Logistic Regression
  18. Neural Networks
  19. Recurrent Neural Networks
  20. Backpropagation
  21. Activation Functions
  22. Convolutional Neural Networks
  23. Vanishing and Exploding Gradients
  24. Normalization Layers: BatchNorm and LayerNorm
  25. Image Classification
  26. LSTMs and GRUs
  27. Residual Connections
  28. Sequence-to-Sequence Models
  29. Attention
  30. Self-Attention and Multi-Head Attention
  31. Positional Encodings
  32. The Transformer
  33. Vision Transformers

Read them roughly in this order. See it on the concept map →

Why it matters

From 2012 to 2020, computer vision meant convolutional networks. Meanwhile, in language, the The Transformer took over everything. In October 2020 a Google team asked a blunt question: what if we skip convolutions altogether, cut an image into patches and hand them to an off-the-shelf Transformer, as if they were words? The paper's title gave the answer: An Image is Worth 16x16 Words. With enough training data, this vision Transformer (ViT) matched or beat the best CNNs.

ViTs matter today for three reasons:

  • They are the standard image encoder of the multimodal era. CLIP, Segment Anything (Image Segmentation) and the vision side of almost every multimodal language model are ViTs. Images and text can then share one architecture.
  • They scale. Like language models, they keep improving with more data and parameters, and they train efficiently on modern hardware.
  • They are excellent self-supervised learners. Methods such as DINO and masked autoencoders produce general-purpose visual features without any labels.

The intuition

A Transformer works on a sequence of tokens: vectors that each stand for one piece of the input. For text, a token is a word or part of one (Tokenization). For an image, the ViT's answer is: a patch, a small square of pixels, typically 16 × 16.

So you slice a 224 × 224 image into a 14 × 14 grid of patches, 196 in all, and read them in order like words in a sentence, left to right and top to bottom. Each patch is flattened into a list of numbers and turned into a token vector. A special extra token, the class token or [CLS], is added at the front as a "summary slot". The Transformer then lets every patch exchange information with every other patch through Self-Attention and Multi-Head Attention, and the final state of the class token is used to classify the image.

How a ViT reads an image. The image is cut into patches; each patch is flattened and multiplied by the same learned matrix to become a token; a [CLS] token and position embeddings are added; a standard Transformer encoder processes the sequence; and a small head classifies from the [CLS] token.

The big difference from a CNN is how context flows. A convolution looks only at a small neighbourhood, so information spreads across the image slowly, layer by layer. In a ViT, attention lets any patch draw on any other patch from the very first layer: a patch on a dog's ear can immediately consult the patch with its tail.

CNN layereach output sees only a 3 × 3 neighbourhoodcontext grows slowly, layer by layerbuilt-in bias: nearby pixels matter most ViT self-attentioneach patch can draw on every patch at onceglobal context from the first layerdarker = more attention; the weights dependon the image content (illustrative values)
Fig. 1 A CNN layer combines only a small neighbourhood, and its view of the image grows slowly with depth. Self-attention lets each patch combine information from all patches at once, with weights that depend on the image content.

Key idea A ViT = patchify (cut into 16 × 16 squares) + linear embedding (one shared matrix) + position embeddings + a standard Transformer encoder. It has fewer built-in assumptions about images than a CNN, so it needs more data, but it keeps improving as data and model size grow.

How it works

Step 1: patch embedding

Take an image of height HH, width WW and CC channels, and a patch size PP. There are N=HW/P2N = HW/P^2 patches. For ViT-B/16 ("Base", patch size 16) on a 224 × 224 RGB image, N=2242/162=196N = 224^2 / 16^2 = 196. Each patch is flattened to a vector xp\mathbf{x}_p of length P2C=16×16×3=768P^2 C = 16 \times 16 \times 3 = 768.

The patch embedding multiplies every flattened patch by the same learned matrix E\mathbf{E} (and adds a bias) to get a DD-dimensional token:

zi=E xp,i+b,i=1,…,N\mathbf{z}_i = \mathbf{E}\,\mathbf{x}_{p,i} + \mathbf{b}, \qquad i = 1, \dots, N

For ViT-B, D=768D = 768, so E\mathbf{E} is 768×768768 \times 768. This is exactly a convolution with a 16 × 16 kernel and stride 16 (each output position sees one patch, with no overlap), and that is how it is implemented in practice.

Step 2: class token and position embeddings

Attention by itself has no idea of order. Shuffle the patches and it computes the same thing. So the ViT adds a learned position embedding pi\mathbf{p}_i, one vector per slot, to each token (Positional Encodings covers the options). It also puts the learned class token zcls\mathbf{z}_{\text{cls}} in front:

Z0=[zcls; z1; … ; zN]+[p0; p1; … ; pN]\mathbf{Z}_0 = [\mathbf{z}_{\text{cls}};\ \mathbf{z}_1;\ \dots;\ \mathbf{z}_N] + [\mathbf{p}_0;\ \mathbf{p}_1;\ \dots;\ \mathbf{p}_N]

The semicolons mean "stacked as rows", so Z0\mathbf{Z}_0 is a (N+1)×D(N+1) \times D matrix: 197 × 768 for ViT-B/16. After training, position embeddings of neighbouring patches turn out similar, and the model has learned the 2-D layout by itself.

Step 3: the Transformer encoder

Z0\mathbf{Z}_0 passes through LL identical Transformer encoder blocks (12 for ViT-B). Each block applies layer normalisation, multi-head Self-Attention and Multi-Head Attention over all 197 tokens, and a residual connection, then layer normalisation, a two-layer MLP with GELU, and another residual connection. This is the same block BERT uses, unchanged.

Step 4: the head

After the last block, the class token's vector goes through a final layer normalisation and a linear layer to produce class scores. (Some variants instead average all the patch tokens. Both work.)

Sizes

Model Layers Width DD Heads Parameters
ViT-B/16 12 768 12 86 M
ViT-L/16 24 1024 16 307 M
ViT-H/14 32 1280 16 632 M

Worked example of cost. Self-attention compares every token with every other, so its cost grows with the square of the number of tokens. At 224 × 224 with 16-pixel patches there are 196 patch tokens, and about 1962≈38,000196^2 \approx 38{,}000 attention pairs per head per layer. Double the resolution to 448 × 448 and there are 784 tokens and about 615,000615{,}000 pairs, 16 times more. This is why ViTs use large patches, and why higher-resolution variants restrict attention to local windows.

Inductive bias and data hunger

An inductive bias is an assumption built into a model's design. CNNs assume locality (nearby pixels are related) and translation equivariance (a cat is a cat wherever it is). These are good assumptions for images, and they let CNNs learn from modest data. A ViT makes almost no such assumptions. Apart from cutting the image into patches, it must learn that neighbouring patches are related.

The original paper showed the consequence clearly. Trained on ImageNet's 1.3 million images alone, ViTs did worse than ResNets of similar size. Pretrained on the 14-million-image ImageNet-21k they roughly matched them. Pretrained on Google's internal 300-million-image JFT-300M, they beat them: ViT-H/14 reached 88.55% top-1 on ImageNet after fine-tuning. Fewer assumptions mean a slower start, and a higher ceiling once data is plentiful. You can see the same effect in miniature in the code below, where a tiny ViT trained on 1,347 digit images trails a tiny CNN.

Making ViTs practical

  • DeiT (2020) showed that with heavy Data Augmentation (RandAugment, mixup, CutMix, random erasing), strong regularisation and Knowledge Distillation and Small Models from a CNN teacher, a ViT trained on ImageNet alone could reach 81.8% top-1 (DeiT-B) in about three days on one 8-GPU machine.
  • Swin Transformer (2021) restored some CNN structure. It computes attention only inside local windows (cost linear in image size), shifts the windows between layers so information crosses their borders, and merges patches to build a pyramid of resolutions. That made Transformers strong backbones for Object Detection and Image Segmentation.
  • Hybrid and convolution-inspired designs (and in the other direction, ConvNeXt) show the two families have largely converged.

Self-supervised ViTs

ViTs shine when trained without labels (Self-Supervised Learning):

  • DINO (2021) trains a "student" network to match a "teacher" network's output on different augmented crops of the same image, with the teacher a slowly updated average of the student. Strikingly, the class token's attention maps in DINO-trained ViTs outline the main objects, without the model ever seeing a segmentation label.
  • Masked autoencoders (MAE, 2021) hide 75% of the patches and train the ViT to reconstruct the missing pixels, the image equivalent of BERT's masked words. Because the encoder only processes the visible 25%, pretraining is cheap.
  • DINOv2 (2023) scaled self-supervised training to 142 million curated images. Its frozen features are a strong general-purpose choice for classification, retrieval, segmentation and depth estimation.

CLIP takes yet another route, training a ViT to match images with their captions.

In code

A complete miniature ViT in PyTorch, trained on scikit-learn's 8 × 8 digits with 2 × 2 patches (16 patches plus a class token). It takes about half a minute on a CPU.

import torch
import torch.nn as nn
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

class TinyViT(nn.Module):
    def __init__(self, img=8, patch=2, chans=1, dim=64, depth=4, heads=4, classes=10):
        super().__init__()
        n_patches = (img // patch) ** 2                       # 8x8 image, 2x2 patches -> 16
        # Patch embedding: a conv with kernel = stride = patch size is exactly
        # "cut into patches, flatten each, multiply by one shared matrix".
        self.patch_embed = nn.Conv2d(chans, dim, kernel_size=patch, stride=patch)
        self.cls_token = nn.Parameter(torch.zeros(1, 1, dim))
        self.pos_embed = nn.Parameter(torch.randn(1, n_patches + 1, dim) * 0.02)
        layer = nn.TransformerEncoderLayer(dim, heads, dim_feedforward=4 * dim,
                                           activation="gelu", batch_first=True, norm_first=True)
        self.encoder = nn.TransformerEncoder(layer, depth, enable_nested_tensor=False)
        self.norm = nn.LayerNorm(dim)
        self.head = nn.Linear(dim, classes)

    def forward(self, x):                                     # x: (N, C, H, W)
        x = self.patch_embed(x)                               # (N, dim, 4, 4)
        x = x.flatten(2).transpose(1, 2)                      # (N, 16, dim): a sequence of tokens
        cls = self.cls_token.expand(len(x), -1, -1)           # (N, 1, dim)
        x = torch.cat([cls, x], dim=1) + self.pos_embed       # (N, 17, dim)
        x = self.encoder(x)                                   # self-attention over all patches
        return self.head(self.norm(x[:, 0]))                  # classify from the CLS token

torch.manual_seed(0)
d = load_digits()
X = torch.tensor(d.images, dtype=torch.float32).unsqueeze(1) / 16.0
y = torch.tensor(d.target)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)

model = TinyViT()
print(f"{sum(p.numel() for p in model.parameters()):,} parameters")   # 202,186 parameters
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.05)
for epoch in range(30):
    model.train()
    for i in torch.randperm(len(X_tr)).split(64):
        loss = nn.functional.cross_entropy(model(X_tr[i]), y_tr[i])
        opt.zero_grad(); loss.backward(); opt.step()
    if epoch % 10 == 9:
        model.eval()
        with torch.no_grad():
            acc = (model(X_te).argmax(1) == y_te).float().mean()
        print(f"epoch {epoch + 1}  test accuracy {acc:.3f}")

# epoch 10  test accuracy 0.893
# epoch 20  test accuracy 0.933
# epoch 30  test accuracy 0.958

The CNN in Image Classification reached 98.4% on the same split with fewer parameters. That is the data-hunger effect in miniature: on a small dataset, the CNN's built-in assumptions win.

In practice you use a pretrained ViT. A classifier through the Hugging Face pipeline, and frozen DINOv2 features for your own tasks (cat.jpg is any photo; models download on first use):

import torch
from PIL import Image
from transformers import pipeline, AutoImageProcessor, AutoModel

clf = pipeline("image-classification", model="google/vit-base-patch16-224")
print(clf("cat.jpg")[:3])                    # top 3 ImageNet labels with scores

processor = AutoImageProcessor.from_pretrained("facebook/dinov2-small")
dino = AutoModel.from_pretrained("facebook/dinov2-small")
inputs = processor(images=Image.open("cat.jpg").convert("RGB"), return_tensors="pt")
with torch.no_grad():
    features = dino(**inputs).last_hidden_state[:, 0]   # the class token: (1, 384)

Those 384 numbers make a good input for a logistic regression or nearest-neighbour classifier trained on a few hundred of your own labelled images.

Common pitfalls

  • Training a ViT from scratch on a small dataset. With thousands, or even a few hundred thousand, images, a ViT trained from scratch usually loses to a CNN. Fine-tune a pretrained ViT instead, or use a CNN.
  • Changing the resolution without care. Position embeddings are learned for a fixed grid, such as 14 × 14. At a new resolution the grid changes, so the embeddings must be interpolated (libraries do this, sometimes only if you ask). Fine-tune briefly at the new size.
  • Forgetting that cost is quadratic in tokens. Halving the patch size from 16 to 8 quadruples the number of tokens and multiplies attention cost by about 16.
  • Weak training recipes. ViTs are sensitive to optimiser settings and augmentation. Use AdamW with warmup and cosine decay (Learning Rate Schedules) and DeiT-style augmentation, or start from a published recipe.
  • Reading too much into attention maps. Attention visualisations are suggestive, not proof of what the model uses (Interpretability and Explainability). Large ViTs also produce a few high-norm "artifact" tokens in background areas. Adding a few extra learnable "register" tokens (Darcet et al., 2023) cleans them up.

Watch out A pretrained ViT expects exactly its own preprocessing: resolution, resizing method and normalisation constants. CLIP, DINOv2 and ImageNet ViTs all differ. Always use the model's own image processor (AutoImageProcessor in Hugging Face, or timm's data config) rather than a generic pipeline.

Where it leads

A bit of history

Attention entered vision gradually: "non-local" blocks added to CNNs (2018), then networks built on local self-attention (2019). The decisive step was Dosovitskiy and colleagues' ViT paper at Google Brain, released in October 2020 and published at ICLR 2021. It used an almost unmodified Transformer and showed that scale (JFT-300M pretraining) beat the CNN's built-in assumptions. DeiT (December 2020) made ViTs trainable on ImageNet alone. Swin (2021) made them practical backbones, and DINO and MAE (2021) showed how well they learn without labels.

From 2021, CLIP's ViT image encoder became the standard way to connect images to language. SAM (2023), DINOv2 (2023) and the vision encoders of multimodal LLMs followed. In a few years ViTs went from a provocative experiment to the default choice for large-scale vision.

Try it

  1. Work out how many tokens (including [CLS]) a ViT with patch size 14 receives for a 518 × 518 image. How many attention pairs is that per head per layer?
  2. In TinyViT, remove + self.pos_embed and retrain. Accuracy drops but not to chance. Why can the model still do reasonably well without knowing where the patches are?
  3. Harder: replace the class token with mean pooling (x[:, 1:].mean(dim=1)) and compare. Then try patch=4 (4 patches). What happens and why?

Hint for 1: 518/14=37518/14 = 37, so there are 372+1=1,37037^2 + 1 = 1{,}370 tokens and about 1.9 million pairs. This is the setting DINOv2 uses.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A ViT with 16 × 16 patches reads a 224 × 224 RGB image. How many tokens enter the Transformer, counting the class token?

  2. You double the input resolution of a ViT from 224 to 448 pixels but keep 16-pixel patches. Roughly how does the self-attention cost change?

  3. You have 5,000 labelled images. Why is training a ViT from scratch usually a bad idea here?

  4. What happens if you remove the position embeddings from a ViT?

  5. Which method trains a ViT by hiding 75% of the patches and asking it to reconstruct the missing pixels?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Tool

vit-pytorch

Phil Wang (lucidrains) · Intermediate · Free

Compact, readable PyTorch implementations of the vision Transformer and many of its variants. Good for studying how they are built.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/vision/vision-transformer.md