Skip to main content
LearnMLAcademy
Advanced10 min read

Vision Transformers

Process image patches with Transformer self-attention using Vision Transformers, with feature-map visuals, architecture comparisons, and image exercises.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

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.

Image divided into patches and converted into a token sequenceA three by three image grid is flattened into nine patch cards, each projected into an embedding, with a class token and position embeddings added.P1P2P3P4P5P6P7P8P9divide image into fixed patchesP1P2P3P4P5P6P7P8P9flatten each patch and project to D numbers[CLS]P1 … P9+ positionembedding
A patch token is not a label such as “wheel.” It is a learned vector representation of raw patch values. The Transformer updates each vector by exchanging information with the other tokens.

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

skypos 1
skypos 2
treepos 3
roadpos 4
carpos 5
roadpos 6

Same content, shuffled

roadpos 1
treepos 2
skypos 3
roadpos 4
skypos 5
carpos 6
ViT adds a learned position vector to every patch embedding. It can therefore distinguish “sky at the top” from the same sky-coloured patch placed near the road.

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

What is learned? W_Q, W_K and W_V begin with initialized values and training updates them. Q, K and V are not permanent parameters and are not entered by a developer; the model calculates new ones from the current tokens during every forward pass.

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.

key CLS
key P1
key P2
key P3
query CLS
0.28
0.18
0.34
0.20
query P1
0.12
0.56
0.20
0.12
query P2
0.31
0.13
0.37
0.19
query P3
0.18
0.22
0.19
0.41
Different heads use different learned query, key and value projections, so they can model different relationships. Individual attention weights should not automatically be interpreted as faithful explanations of a model decision.

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

Attention mixes information across tokens. The MLP—two dense layers with a nonlinearity—processes each token position independently. Residual shortcuts make both sublayers learn changes to their inputs.

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×224Patch tokens NAttention score pairs N²Trade-off
32×32492,401Cheaper, but coarse patches can hide small details
16×1619638,416Common balance for standard ViT
8×8784614,656More 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

QuestionTypical CNNPlain ViT
Built-in assumptionLocal filters and shared weightsPatch tokens and learned global attention
Early information mixingMostly local; receptive field grows with depthAny token can attend to any token in a standard ViT block
PositionEncoded naturally by the 2D convolution gridAdded explicitly with position embeddings
Data behaviourStrong local inductive bias can help with less dataPlain ViT historically benefits strongly from large-scale pretraining
Attention costConvolution cost depends on kernel and feature-map sizesGlobal attention grows roughly with the square of token count
Best practical choiceDepends on model family, pretraining, task and hardwareDepends 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.

vit_inference_and_finetuning.py
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 = True
ViT_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

SymptomLikely causeWhat to do
Shape error at patch embeddingImage dimensions or channels do not match the modelUse the weight-specific transform; inspect [N,C,H,W] before the forward pass
Position-embedding size mismatchFine-tuning at a different resolution changes token countUse a supported interpolation path or the expected resolution; do not discard learned positions blindly
Training from scratch performs poorlyDataset too small or recipe too weak for a plain ViTBegin from pretrained weights or compare a CNN with stronger local bias
Out of memory after smaller patchesN² attention matrix grew rapidlyUse larger patches, lower resolution/batch, checkpointing, or a windowed/hierarchical model
Attention map looks convincing but prediction is wrongAttention weight is not a complete explanationUse counterfactual/occlusion tests and quantitative evaluation alongside visualization
Fine-tuning destroys pretrained accuracyLearning rate too large or all layers changed immediatelyTrain 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.

Continue Learning

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Vision Transformers"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Summary / Key Takeaways

  • A ViT turns image patches into token embeddings.
  • Position information tells the model where patches occurred.
  • Self-attention exchanges information between patches.
  • Stacked Transformer blocks build contextual image features.
  • Patch size trades spatial detail against attention cost.
  • Large-scale pretraining helps, but CNN baselines may be better under smaller budgets.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
What becomes one input token in a basic Vision Transformer?
Question 2 of 5numerical/formula
A 32×32 image uses 8×8 non-overlapping patches. How many patch tokens are created before any class token?
Question 3 of 5conceptual
Why add position information to patch embeddings?
Question 4 of 5interpretation
What happens to attention cost when patch size is made much smaller?
Question 5 of 5practical selection
When is a CNN baseline especially important?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What becomes one input token in a basic Vision Transformer?▼

Correct Answer: An embedded image patch

The image is divided into patches, flattened or projected, and represented as a token sequence.

2A 32×32 image uses 8×8 non-overlapping patches. How many patch tokens are created before any class token?▼

Correct Answer: 16

There are 32/8=4 patches along each axis, giving 4×4=16 tokens.

3Why add position information to patch embeddings?▼

Correct Answer: Attention alone does not encode where a patch occurred

Self-attention processes a set of representations, so positions must be supplied explicitly.

4What happens to attention cost when patch size is made much smaller?▼

Correct Answer: Token count grows and quadratic attention cost can rise sharply

Smaller patches create more tokens, and full self-attention compares every token pair.

5When is a CNN baseline especially important?▼

Correct Answer: With limited data or tight compute budgets

ViTs often benefit from scale and pretraining; CNN inductive bias can be competitive under smaller budgets.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next