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
- Builds on
- 32 concepts →
- Quiz
- 5 questions ↓
The full path from zero — 32 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Tensors and Shapes
- Supervised Learning
- Images as Data
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Convolutional Neural Networks
- Vanishing and Exploding Gradients
- Normalization Layers: BatchNorm and LayerNorm
- Image Classification
- LSTMs and GRUs
- Residual Connections
- Sequence-to-Sequence Models
- Attention
- Self-Attention and Multi-Head Attention
- Positional Encodings
- The Transformer
- 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.
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.
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 , width and channels, and a patch size . There are patches. For ViT-B/16 ("Base", patch size 16) on a 224 × 224 RGB image, . Each patch is flattened to a vector of length .
The patch embedding multiplies every flattened patch by the same learned matrix (and adds a bias) to get a -dimensional token:
For ViT-B, , so is . 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 , one vector per slot, to each token (Positional Encodings covers the options). It also puts the learned class token in front:
The semicolons mean "stacked as rows", so is a 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
passes through 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 | 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 attention pairs per head per layer. Double the resolution to 448 × 448 and there are 784 tokens and about 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 (
AutoImageProcessorin Hugging Face, ortimm's data config) rather than a generic pipeline.
Where it leads
- CLIP and Contrastive Learning trains a ViT and a text Transformer together so that images and captions share one embedding space.
- Multimodal LLMs feed ViT patch tokens, through a small projector, into a language model.
- Segment Anything and DETR-style detectors use ViT encoders.
- Video Transformers extend patches to "tubelets" across time.
- Diffusion Transformers use the same patch tokens to generate images.
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
- 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?
- In
TinyViT, remove+ self.pos_embedand retrain. Accuracy drops but not to chance. Why can the model still do reasonably well without knowing where the patches are?- Harder: replace the class token with mean pooling (
x[:, 1:].mean(dim=1)) and compare. Then trypatch=4(4 patches). What happens and why?Hint for 1: , so there are tokens and about 1.9 million pairs. This is the setting DINOv2 uses.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
An Image is Worth 16x16 Words
The Vision Transformer: images as sequences of patches.
Training data-efficient image transformers & distillation through attention
DeiT showed that with strong augmentation, regularisation and distillation a vision Transformer can be trained well on ImageNet alone.
Emerging Properties in Self-Supervised Vision Transformers
DINO: self-distillation without labels or negatives; its attention maps segment objects on their own.
DINOv2: Learning Robust Visual Features without Supervision
Self-supervised ViTs trained on a large curated image collection, whose frozen features work well for classification, segmentation and depth without fine-tuning.
Swin Transformer: Hierarchical Vision Transformer using Shifted Windows
A vision Transformer with local attention windows and a CNN-like pyramid of resolutions, which made Transformers practical backbones for detection and segmentation.
Masked Autoencoders Are Scalable Vision Learners
Hide 75% of an image's patches and reconstruct them with a Vision Transformer: BERT-style pretraining for images.
vit-pytorch
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