Deep Learning · Computer Vision
Vision Transformers: Reading an Image as a Sequence of Patches
A Vision Transformer (ViT) replaces the CNN's sliding local filters with a Transformer encoder that relates image patches to one another. We will turn a picture into tokens, calculate the token count, explain class and position embeddings, perform one attention calculation, trace an encoder block, compare patch sizes, and use a pretrained ViT without claiming it always beats a CNN.
Why Convert an Image Into Tokens?
Imagine a satellite image containing a river, fields and a smoke plume. A CNN begins by applying small local filters; distant regions interact only after information crosses several layers. A Transformer offers another route: represent image regions as a sequence and let each region directly weigh information from every other region through self-attention.
A Transformer was originally designed for sequences, not a height-by-width pixel grid. Passing one token per pixel would make the sequence enormous. ViT therefore groups nearby pixels into fixed, non-overlapping patches. Each patch is flattened and mapped to a fixed-length embedding vector. The result looks like a sequence of visual tokens.
ViT turns a two-dimensional image into a sequence of patch tokens
This 3 × 3 teaching image becomes nine patch tokens. Real models commonly use many more.
Patch Size Controls the Sequence Length
For an H × W image and square P × P patches, the number of patch tokens is (H/P) × (W/P), assuming the dimensions divide evenly. The original ViT naming convention uses labels such as ViT-B/16: a Base-sized Transformer with 16 × 16 patches.
Number of patch tokens
N = (H × W) / P²
H and W are image height and width, P is patch side length, and N excludes any special class token.
A 224 × 224 RGB image with 16 × 16 patches
1. Patches per side
224 / 16 = 14
2. Patch tokens
14 × 14 = 196
3. Sequence length
196 + 1 [CLS]
= 197 tokens
values in one RGB patch = 16 × 16 × 3 = 768
A learned linear projection converts those 768 raw values into the model's embedding dimension D. D also happens to be 768 in ViT-Base, but that equality is a model choice, not a general rule.
The Class Token Collects Evidence for Classification
ViT prepends one learned vector called [CLS] to the patch sequence. It contains no pixels. Across encoder layers, self-attention lets this token collect information from the patches. The final [CLS] representation is passed to a classifier that outputs image-level logits. Other architectures may pool patch tokens instead, so [CLS] is a design choice rather than a universal Transformer requirement.
Patch content alone does not say where it came from
Without position information, these two sequences contain the same token contents even though their layouts differ.
Ordered layout
Same content, shuffled
Self-Attention Lets One Patch Request Context From Others
Each token is projected into three vectors. A query Q describes what this token is looking for. A key K describes what another token offers. Their dot product gives a compatibility score. A value V carries the information that will be mixed.
Where Q, K and V actually come from
Every patch first has a token vector X. The model owns three learned weight matrices. Multiplying X by each matrix creates three different views of the same token.
Token X
calculated from patch values, patch-projection weights and position
Query Q
X × W_Q
what this token is looking for
Key K
X × W_K
what each token can be matched on
Value V
X × W_V
the information each token can send
Scaled dot-product attention
Attention(Q,K,V) = softmax(QKᵀ / √dk)V
QKᵀ: multiply each query by every key and add matching vector components to measure compatibility.
÷ √dk: scale scores before softmax so wider vectors do not create unnecessarily extreme dot products.
softmax: exponentiate and divide by the row total to create positive weights that sum to 1.
× V: multiply each value vector by its weight and add them to create the requested context.
One query attends to three patches
We manually choose two-number q, k and v vectors so the arithmetic remains visible. In a real forward pass, the learned projection matrices shown above calculate them. Here dk=2 because every query and key contains two numbers, so the scale is √2.
Inputs
q=[1,0]
k₁=[1,0], k₂=[0,1], k₃=[1,1]
v₁=[2,0], v₂=[0,2], v₃=[1,1]
1. Dot products
q·k₁=(1×1)+(0×0)=1
q·k₂=(1×0)+(0×1)=0
q·k₃=(1×1)+(0×1)=1
2. Scale the scores
[1,0,1] / √2
≈ [0.707, 0, 0.707]
3. Softmax
exp scores ≈ [2.028,1,2.028]
divide each by 5.056
≈ [0.401,0.198,0.401]
4. Weight and add the values
0.401[2,0] + 0.198[0,2] + 0.401[1,1]
= [0.802,0] + [0,0.396] + [0.401,0.401]
= [1.203, 0.797]
Interpretation: this query receives equal strong weight from patches 1 and 3, less from patch 2, then blends their value information. The two output numbers are the new context for this query in our tiny head.
An attention head creates a token-to-token weight table
Each row sums to 1. Darker cells receive more value information for that query token in this illustrative head.
Multiple Heads and Encoder Blocks Build Richer Relationships
Multi-head attention runs several learned query/key/value projections in parallel. One head might become sensitive to colour continuity while another relates distant object parts; these interpretations are not guaranteed labels. Head outputs are concatenated and projected. A token-wise MLP then transforms each representation, while LayerNorm and residual shortcuts stabilize deep stacks.
Embedding width D = 768
chosen by the ViT-Base design
Heads h = 12
also an architecture choice
dk = D/h = 64
calculated width per head
12 × 64 = 768
concatenation restores D
One Transformer encoder block updates every token
token sequence
patch + position
LayerNorm
stabilize values
Multi-head attention
tokens exchange context
Add shortcut
preserve input
LayerNorm + MLP
transform each token
Add shortcut
block output
LayerNorm changes the distribution of values but keeps the token shape. Attention and the MLP also return width D so their outputs can be added to the residual path position by position. In ViT-Base, the MLP's hidden width 3,072 is a designer-selected expansion—four times 768—before a second learned layer returns it to 768.
After one block, every patch token contains its original visual information plus context gathered from other tokens. Repeating blocks refines those representations. For classification, the final normalized [CLS] token is sent through a linear head to produce class logits.
Smaller Patches Preserve Detail but Make Attention Expensive
Standard global self-attention compares every token with every token, creating an N × N score matrix per head. Halving patch width gives four times as many 2D patches and roughly sixteen times as many token-pair scores.
| Patch size on 224×224 | Patch tokens N | Attention score pairs N² | Trade-off |
|---|---|---|---|
| 32×32 | 49 | 2,401 | Cheaper, but coarse patches can hide small details |
| 16×16 | 196 | 38,416 | Common balance for standard ViT |
| 8×8 | 784 | 614,656 | More local detail, much larger global-attention matrix |
The table omits [CLS], batch, head and embedding dimensions, but accurately shows the quadratic token relationship. Hierarchical/windowed designs such as Swin restrict attention regions to reduce cost for high-resolution vision.
CNN and ViT Encode Different Starting Assumptions
| Question | Typical CNN | Plain ViT |
|---|---|---|
| Built-in assumption | Local filters and shared weights | Patch tokens and learned global attention |
| Early information mixing | Mostly local; receptive field grows with depth | Any token can attend to any token in a standard ViT block |
| Position | Encoded naturally by the 2D convolution grid | Added explicitly with position embeddings |
| Data behaviour | Strong local inductive bias can help with less data | Plain ViT historically benefits strongly from large-scale pretraining |
| Attention cost | Convolution cost depends on kernel and feature-map sizes | Global attention grows roughly with the square of token count |
| Best practical choice | Depends on model family, pretraining, task and hardware | Depends on model family, pretraining, task and hardware |
“ViT sees globally” does not mean it automatically understands every long-range relationship, and “CNN is local” does not mean later CNN layers cannot represent global context. Architecture, scale, pretraining, augmentation and optimization all matter. For a modest dataset, comparing pretrained models is more useful than repeating universal claims.
Use the Preprocessing Bundled With Pretrained Weights
A pretrained ViT expects the resolution, scaling and normalization used during its training. Torchvision weight objects provide matching transforms and class metadata, reducing silent preprocessing mismatch.
import torch
from torch import nn
from torchvision.io import decode_image
from torchvision.models import vit_b_16, ViT_B_16_Weights
weights = ViT_B_16_Weights.DEFAULT
model = vit_b_16(weights=weights)
preprocess = weights.transforms()
# Pretrained inference on one image
image = decode_image("satellite_tile.jpg")
batch = preprocess(image).unsqueeze(0)
model.eval()
with torch.no_grad():
logits = model(batch)
class_id = int(logits.argmax(dim=1))
print(weights.meta["categories"][class_id])
# Adapt the classifier for four project classes.
input_features = model.heads.head.in_features
model.heads.head = nn.Linear(input_features, 4)
# A conservative start: train only the new head.
for parameter in model.parameters():
parameter.requires_grad = False
for parameter in model.heads.parameters():
parameter.requires_grad = TrueViT_B_16_Weights.DEFAULT selects an official pretrained weight recipe. weights.transforms() supplies the resize, crop, value scaling and normalization expected by those exact weights.unsqueeze(0) adds the batch dimension: one C × H × W image becomes 1 × C × H × W. The leading 1 is calculated from the one image being sent.model.eval() and torch.no_grad() switch inference-sensitive layers to evaluation behaviour and stop gradient recording. They do not alter the learned weights.nn.Linear(input_features, 4) replaces the original classifier. input_features is read from the model; 4 is chosen because this project has four labels. Its weights begin initialized and are learned during fine-tuning.After the new head learns, optionally unfreeze later encoder blocks and fine-tune with a smaller learning rate. Freezing is not permanent: it is a staged starting strategy that should be validated.
Common Vision Transformer Problems
| Symptom | Likely cause | What to do |
|---|---|---|
| Shape error at patch embedding | Image dimensions or channels do not match the model | Use the weight-specific transform; inspect [N,C,H,W] before the forward pass |
| Position-embedding size mismatch | Fine-tuning at a different resolution changes token count | Use a supported interpolation path or the expected resolution; do not discard learned positions blindly |
| Training from scratch performs poorly | Dataset too small or recipe too weak for a plain ViT | Begin from pretrained weights or compare a CNN with stronger local bias |
| Out of memory after smaller patches | N² attention matrix grew rapidly | Use larger patches, lower resolution/batch, checkpointing, or a windowed/hierarchical model |
| Attention map looks convincing but prediction is wrong | Attention weight is not a complete explanation | Use counterfactual/occlusion tests and quantitative evaluation alongside visualization |
| Fine-tuning destroys pretrained accuracy | Learning rate too large or all layers changed immediately | Train the head first, unfreeze gradually, and use discriminative/smaller rates |
When a ViT Is a Reasonable Starting Point
Strong pretrained checkpoint exists
A ViT can transfer rich patch relationships even when your labelled dataset is modest.
Long-range image context matters
Global attention can connect separated regions directly, though task evidence must confirm the benefit.
High-resolution dense prediction
Prefer a hierarchical/windowed vision Transformer or hybrid; plain global attention may be too expensive.
Tiny edge deployment
Benchmark lightweight CNNs and compact/hybrid Transformers. Parameter count alone does not determine latency.
Learning the basics
Implement a tiny patch embed and attention block, but do not expect from-scratch toy training to match a pretrained system.
Need reliable explanation
Attention is not sufficient. Pair model choice with task-specific interpretability and validation methods.
The ViT in One Connected Explanation
- Split the image into patches and linearly project each flattened patch into an embedding.
- Add position embeddings because attention alone does not know the 2D order.
- Prepend [CLS] when using the classic ViT classification design.
- Use multi-head self-attention so tokens exchange weighted value information.
- Use MLPs, normalization and residual shortcuts inside repeated encoder blocks.
- Smaller patches preserve detail but increase token count and quadratic global-attention cost.
- Choose between CNNs, ViTs and hybrids through pretrained evidence on your own data and hardware.