AI
Vision Transformer (ViT): How It Sees Images
Vision transformer explained: how ViT turns an image into patches and reads them like words, how it compares with CNNs, key variants and how to use one.
A vision transformer (ViT) is a neural network that understands images by cutting them into small square patches and processing those patches like words in a sentence, using the same transformer architecture that powers language models. A 224 × 224 pixel image becomes a sequence of 196 patches of 16 × 16 pixels. Each patch is turned into a vector, and self-attention lets every patch look at every other patch to work out what the image shows.
Introduced by Google researchers in the 2020 paper "An Image is Worth 16x16 Words", the vision transformer matched or beat the best convolutional networks (CNNs) on image classification when trained on enough data. Today ViTs are the image encoders inside many vision-language models, image search systems and segmentation models. This guide covers how a ViT works step by step with real numbers, the vision transformer architecture and model sizes, the original results, vision transformer vs CNN, the key variants, a short code example and how to choose one.
What Is a Vision Transformer (ViT)?
A vision transformer is an image model built from a standard transformer encoder, the same kind of block used in BERT. It has very few changes made for images. The authors' goal was to see how far a plain transformer could go on vision with as little image-specific design as possible.
What is ViT model in one sentence? It treats an image as a sequence of patch "tokens", adds information about where each patch came from, runs the sequence through layers of self-attention, and reads the answer from a special classification token.
The key difference from earlier vision models is what the model assumes. A CNN is built around the idea that nearby pixels matter most and that a pattern means the same thing anywhere in the image. A ViT has almost none of these built-in assumptions, which the paper calls inductive biases. Apart from cutting the image into patches, it has to learn spatial relationships from data. That makes it more flexible, and much more hungry for training data.
If you're new to transformers, our explainer on the transformer model covers self-attention from the ground up.
Vision Transformer Explained, Step by Step
Here is the vision transformer explained in six steps, using the base model (ViT-B/16) and a 224 × 224 colour image.
1. Split the image into patches. With 16 × 16 pixel patches, a 224 × 224 image becomes a 14 × 14 grid: 196 patches. Each patch holds 16 × 16 × 3 = 768 numbers (pixels times colour channels).
2. Flatten and project each patch. Each patch's 768 values are multiplied by a learned matrix to produce a vector of the model's width, which is also 768 for ViT-Base. This is the patch embedding, the image equivalent of a word embedding. The result is a sequence of 196 vectors.
3. Add a class token. A learned vector called the [CLS] token is put at the front of the sequence, making 197 tokens. It doesn't come from any patch. Its job is to collect information from all patches as it passes through the layers, and its final value represents the whole image.
4. Add position embeddings. Self-attention by itself has no sense of order. Shuffle the patches and the output would be the same. So a learned position embedding is added to each token, telling the model which part of the grid each patch came from. The paper found that simple 1D learned position embeddings worked about as well as more complex 2D versions, because the model learns the grid structure on its own.
5. Run the transformer encoder. The 197 tokens go through 12 identical layers. Each layer has:
- Layer normalisation.
- Multi-head self-attention (12 heads in ViT-Base). Every token computes how relevant every other token is to it, so a patch showing an ear can pick up information from a patch showing an eye on the other side of the image. In each head that is a 197 × 197 attention matrix.
- A residual connection, then layer normalisation again.
- An MLP (two fully connected layers, 768 → 3,072 → 768) with a GELU activation, and another residual connection.
6. Classify. The final vector for the [CLS] token goes through a small classification head that outputs a score for each class, such as the 1,000 ImageNet categories.
Because attention connects every patch to every other patch from the first layer, a ViT can relate distant parts of an image straight away. A CNN builds up that global view gradually through many layers.
Vision Transformer Architecture and Model Sizes
The vision transformer architecture comes in standard sizes, named by model size and patch size. ViT-L/16 means the Large model with 16 × 16 patches. The original paper defined three:
| Model | Layers | Hidden size | MLP size | Attention heads | Parameters |
|---|---|---|---|---|---|
| ViT-Base | 12 | 768 | 3,072 | 12 | 86 million |
| ViT-Large | 24 | 1,024 | 4,096 | 16 | 307 million |
| ViT-Huge | 32 | 1,280 | 5,120 | 16 | 632 million |
Source: Dosovitskiy et al., "An Image is Worth 16x16 Words", Table 1.
Patch size matters as much as model size. Smaller patches mean more tokens, more detail and more compute:
| Patch size | Tokens for a 224 × 224 image | Tokens for a 448 × 448 image |
|---|---|---|
| 32 × 32 | 49 | 196 |
| 16 × 16 | 196 | 784 |
| 14 × 14 | 256 | 1,024 |
| 8 × 8 | 784 | 3,136 |
Self-attention cost grows with the square of the number of tokens. Going from 16 × 16 to 8 × 8 patches multiplies the token count by four and the attention cost by about sixteen. That is the main reason ViTs get expensive at high resolutions, and why many later designs restrict attention to local windows.
How Well Did ViT Work? The Original Results
ViTs were first pre-trained on large labelled datasets and then fine-tuned on smaller ones. The paper used ImageNet (1.3 million images), ImageNet-21k (14 million) and Google's internal JFT-300M (303 million). Here's how the best models compared with the strongest CNNs of the time:
| Model | Pre-training data | ImageNet top-1 | CIFAR-100 | VTAB (19 tasks) | Pre-training compute (TPUv3-core-days) |
|---|---|---|---|---|---|
| ViT-H/14 | JFT-300M | 88.55% | 94.55% | 77.63% | 2,500 |
| ViT-L/16 | JFT-300M | 87.76% | 93.90% | 76.28% | 680 |
| ViT-L/16 | ImageNet-21k | 85.30% | 93.25% | 72.72% | 230 |
| BiT-L (ResNet152x4, a CNN) | JFT-300M | 87.54% | 93.51% | 76.29% | 9,900 |
| Noisy Student (EfficientNet-L2, a CNN) | JFT-300M | 88.4% | n/a | n/a | 12,300 |
Source: Dosovitskiy et al., Table 2.
Two findings stood out. First, the ViTs matched or beat the best CNNs with much less pre-training compute: ViT-L/16 beat BiT-L on every task using about one fourteenth of the TPU time. Second, data size decided everything. When pre-trained only on ImageNet, the large ViTs did worse than the base model and worse than comparable ResNets. Only with JFT-300M did the bigger models pull ahead. The paper's own summary: large-scale training trumps inductive bias.
Vision Transformer vs CNN
How does a vision transformer vs CNN compare in practice? They are now close in accuracy. The differences are in how they learn and what they cost.
| CNN | Vision transformer | |
|---|---|---|
| Basic operation | Convolution: small filters slide over the image | Self-attention between image patches |
| Built-in assumptions | Strong: locality, translation equivariance | Weak: learns spatial structure from data |
| Receptive field | Local at first, grows with depth | Global from the first layer |
| Data needs | Learns well from smaller datasets | Needs large pre-training data or heavy augmentation |
| Scaling with data and model size | Good | Very good; gains continue at large scale |
| Cost vs resolution | Grows roughly linearly with pixels | Global attention grows with the square of the token count |
| Dense tasks (detection, segmentation) | Natural multi-scale feature maps | Plain ViT is single-scale; hierarchical variants fix this |
| Fit with language models | Needs adapters | Same token format as text, easy to combine |
| Typical use today | Edge devices, real-time detection, small datasets | Foundation models, vision-language models, large-scale tasks |
CNNs didn't stand still. The 2022 paper "A ConvNet for the 2020s" updated a ResNet step by step with design ideas borrowed from transformers. The resulting ConvNeXt reached 87.8% ImageNet top-1 and outperformed Swin Transformers on COCO detection and ADE20K segmentation. The fair conclusion is that architecture matters less than data, training recipe and scale. ViTs became the default for large foundation models mainly because they scale well and share a format with language models.
For a broader view of the field, see our guide to computer vision.
Key Variants: How ViTs Evolved
The original ViT had two big drawbacks: it needed huge datasets and it worked at a single scale. Most of the variants since then fix one or both.
| Variant | Year | What it changed | Notable result |
|---|---|---|---|
| DeiT | 2020 | Training recipe and a distillation token, learning from a teacher model | 86M-parameter ViT reached 83.1% on ImageNet with no external data, trained on one machine in under three days |
| How to train your ViT (AugReg) | 2021 | Systematic data augmentation and regularisation | ViTs trained on public ImageNet-21k matched or beat versions trained on JFT-300M |
| Swin Transformer | 2021 | Hierarchical feature maps and attention in shifted local windows | Linear cost with image size; 87.3% ImageNet-1K, 58.7 box AP on COCO, 53.5 mIoU on ADE20K |
| MAE (masked autoencoders) | 2021 | Self-supervised pre-training: hide 75% of patches and reconstruct them | Training 3x or more faster; ViT-Huge reached 87.8% using only ImageNet-1K data |
| CLIP and SigLIP | 2021 onward | ViT image encoder trained to match images with captions | Zero-shot classification and image-text search |
| DINOv2 | 2023 | Self-supervised training on curated data; a 1B-parameter ViT distilled into smaller models | General-purpose features that beat OpenCLIP on most benchmarks without fine-tuning |
| Registers | 2023 | Extra "register" tokens in the input | Removes high-norm artifact tokens in feature maps; smoother attention maps |
| DINOv3 | 2025 | Larger self-supervised training plus "Gram anchoring" for dense features | Strong dense features across tasks without fine-tuning |
Two of these deserve a closer look. Self-supervised pre-training (MAE, DINOv2, DINOv3) removed the dependence on huge labelled datasets: the model learns from unlabelled images. CLIP-style training linked ViTs to language, which is how most vision-language models see. Our guide to the CLIP model explains that training method.
What Vision Transformers Are Used For
- Image classification: the original task, from product categories to medical image triage.
- Image encoders for vision-language models: most multimodal assistants pass images through a ViT-style encoder and feed the patch tokens to a language model.
- Segmentation: Meta's Segment Anything Model uses a ViT image encoder, trained on over 1 billion masks across 11 million images.
- Object detection: detection models built on ViT or Swin backbones.
- Image search and embeddings: ViT features power "find similar images" and text-to-image search.
- Video: video transformers split clips into patches across space and time.
- Science and industry: satellite imagery, pathology slides, manufacturing inspection, often starting from a self-supervised ViT backbone.
How Vision Transformers Are Trained and Fine-Tuned
Almost every ViT you use goes through two stages.
Pre-training teaches general visual features on a large dataset. The original ViTs used supervised pre-training: predict the label of each image in ImageNet-21k or JFT-300M. The Hugging Face model card for the base model lists the recipe: TPUv3 hardware, a batch size of 4,096, a learning-rate warm-up of 10,000 steps and gradient clipping at a global norm of 1 for ImageNet. Since then, self-supervised pre-training has become common, because it doesn't need labels. MAE learns by filling in hidden patches. DINOv2 and DINOv3 learn by making different views of the same image produce consistent features.
Fine-tuning adapts the model to your task. The classification head is replaced with a new one sized for your classes, and the model is trained further on your labelled images, usually with a much smaller learning rate. The original paper found that fine-tuning at a higher resolution than pre-training improves accuracy. For example, the model pre-trained at 224 × 224 is fine-tuned at 384 × 384, keeping the patch size, so the sequence gets longer. The pre-trained position embeddings are then interpolated in 2D to fit the bigger grid.
There are three common ways to adapt a ViT to your own images, from cheapest to most thorough:
- Linear probe. Freeze the whole ViT, extract the [CLS] or average token for each image and train a simple classifier on top. It's fast and works well with self-supervised backbones and small datasets.
- Partial fine-tuning. Unfreeze only the last few blocks plus the head. It costs less than full fine-tuning and is less prone to overfitting.
- Full fine-tuning. Train all weights. It gives the best accuracy when you have thousands of labelled images per class and the compute for it.
Parameter-efficient methods such as LoRA, borrowed from language models, also work on ViTs and keep the number of trained weights small.
For a small project, a good default is to start with a linear probe on a strong pre-trained backbone. Move to fine-tuning only if accuracy falls short. Hold out a validation set from the start, and keep the same preprocessing at training and inference time.
Using a Vision Transformer in Python
The quickest way to try a ViT is a pre-trained model from Hugging Face. The google/vit-base-patch16-224 model was pre-trained on ImageNet-21k and fine-tuned on ImageNet at 224 × 224 resolution:
from transformers import pipeline
classifier = pipeline("image-classification", model="google/vit-base-patch16-224")
results = classifier("http://images.cocodataset.org/val2017/000000039769.jpg")
for r in results:
print(r["label"], round(r["score"], 3))The pipeline handles resizing and normalisation. If you build the steps yourself, match the model's preprocessing exactly. This model expects 224 × 224 inputs normalised with a mean and standard deviation of 0.5 per channel.
In PyTorch, torchvision also ships ViTs, such as vit_b_16(weights=ViT_B_16_Weights.DEFAULT). To see how the patch embedding works, note that it is usually written as a convolution whose kernel size and stride both equal the patch size:
import torch
import torch.nn as nn
patch_embed = nn.Conv2d(3, 768, kernel_size=16, stride=16)
x = torch.randn(1, 3, 224, 224) # one RGB image
tokens = patch_embed(x) # shape (1, 768, 14, 14)
tokens = tokens.flatten(2).transpose(1, 2) # shape (1, 196, 768)That convolution is exactly "cut into 16 × 16 patches and apply one linear projection to each". It isn't a sliding filter in the usual CNN sense, because the patches don't overlap.
How to Choose a Vision Transformer
- Don't train from scratch on a small dataset. Start from a pre-trained checkpoint and fine-tune, or train a linear classifier on frozen features.
- For general-purpose features, self-supervised backbones such as DINOv2 or DINOv3 are strong starting points.
- For matching images with text, use a CLIP or SigLIP image encoder.
- For detection and segmentation, prefer a hierarchical backbone (Swin and its successors) or a ViT with a detection or segmentation head built for it.
- For phones and edge devices, consider efficient hybrids or a modern CNN. Plain ViTs at high resolution can be too slow.
- Match patch size to the detail you need. Smaller patches catch fine detail but cost far more compute.
Limitations and Common Mistakes
- Data hunger. Trained from scratch on a few thousand images, a ViT usually loses to a CNN. Use pre-training.
- Resolution changes. Position embeddings are learned for one grid size. Fine-tuning at a higher resolution needs them interpolated to the new grid, which is what the original paper did. Most libraries handle this, but custom code often forgets it.
- Preprocessing mismatch. Using ImageNet's usual normalisation on a model trained with 0.5 mean and standard deviation, or the wrong input size, quietly hurts accuracy.
- Quadratic cost. Large images with small patches can run out of memory. Use windowed attention, larger patches or a hierarchical model.
- Reading too much into attention maps. Attention maps are a rough guide to what the model looks at, not a reliable explanation. The registers paper showed some high-attention tokens are artifacts in background areas.
FAQ
Is a vision transformer a CNN?
No. A vision transformer uses self-attention between image patches instead of convolution layers. The patch embedding is often implemented as a convolution with non-overlapping patches, but the rest of the network is a standard transformer encoder.
Is a vision transformer better than a CNN?
Not automatically. With large pre-training data or self-supervised training, ViTs match or beat CNNs and scale better. On small datasets, on edge devices or for real-time detection, modern CNNs are often as good or better and cheaper.
Is a vision transformer an LLM?
No. A vision transformer processes images and outputs image features or labels. It shares the transformer architecture with large language models, and in vision-language models a ViT often acts as the "eyes" that feed image tokens into an LLM.
What is the CLS token in a vision transformer?
It is a learned extra token placed at the start of the patch sequence. Through self-attention it gathers information from all patches, and its final value is used to classify the whole image. Some newer models average all patch tokens instead.
How much data does a vision transformer need?
Trained from scratch, the original ViTs needed tens to hundreds of millions of images to beat CNNs. With stronger training recipes, such as DeiT on ImageNet's 1.3 million images, or by fine-tuning a pre-trained model, far less data works.