Thursday, November 12, 2026

Understanding the Vision Transformer (ViT): A Paper Walkthrough With Code

TL;DR

An image is worth 16x16 words, at least according to the Vision Transformer paper. This walkthrough shows how ViT cuts a picture into patches, feeds them to a plain Transformer, and matches or beats strong CNNs once it has seen enough images. It covers the architecture step by step with runnable NumPy code, then the results and limits. Turns out the patch embedding is a convolution wearing a disguise.

Three patches worth zooming in on:

Say you have trained convolutional networks for years, and a colleague claims you can classify images with the same Transformer that powers language models, with no convolutions at all. You would want to know how an image becomes a sequence of words, what the model gives up, and when the claim actually holds.

The Vision Transformer (ViT) is the model that answered that question. Introduced by Alexey Dosovitskiy and colleagues at Google in 2020, ViT splits an image into fixed-size patches, turns each patch into a vector, and feeds the sequence to a standard Transformer encoder. Its main finding is that this works as well as or better than leading CNNs, but only when the model is pre-trained on a very large dataset. This walkthrough covers the architecture step by step, with a runnable NumPy example of the patch embedding, then the paper’s results and limits.

Key Takeaways

  • ViT treats an image as a sequence: a 224 by 224 image cut into 16 by 16 patches becomes 196 tokens, plus one class token.
  • Each patch is flattened and projected to the model width by one shared linear layer, which is the same as a convolution with a 16 by 16 kernel and stride 16.
  • After the patch embedding, ViT is an almost unchanged Transformer encoder, the same design used for text.
  • ViT has fewer built-in assumptions about images than a CNN. Trained only on ImageNet it falls a few points behind comparable ResNets; pre-trained on 14M to 300M images it matches or beats them.
  • The largest model, ViT-H/14 pre-trained on JFT-300M, reached 88.55% top-1 accuracy on ImageNet.

What Is the Vision Transformer?

The Vision Transformer is an image classification model that applies a standard Transformer encoder directly to sequences of image patches. The paper, “An Image is Worth 16×16 Words: Transformers for Image Recognition at Scale”, was posted to arXiv in October 2020 and published at ICLR 2021. Its title is the core idea: each 16 by 16 patch plays the role of a word.

Before ViT, most attempts to use attention in vision kept convolutions around or used special attention patterns to handle the cost of attending over every pixel. ViT avoids that cost by attending over patches instead of pixels, which cuts the sequence from 50,176 pixels to 196 patches for a 224 by 224 image. The authors deliberately changed as little as possible in the Transformer itself, so they could reuse designs and implementations built for language.

How Does ViT Work, Step by Step?

Step 1: Split the Image Into Patches

The image is cut into a grid of non-overlapping square patches. With a 224 by 224 RGB image and 16 by 16 patches, the grid is 14 by 14, so there are 196 patches. Each patch holds 16 × 16 × 3 = 768 numbers, which are flattened into one vector.

The patch size is part of each model’s name: ViT-B/16 is the Base model with 16 by 16 patches, and ViT-H/14 is the Huge model with 14 by 14 patches. Smaller patches mean more tokens, which means more computation and usually better accuracy.

Step 2: Project Each Patch to an Embedding

A single learned linear layer maps every flattened patch to a vector of the model’s width, 768 for ViT-Base. The same weights are used for every patch, just as a language model uses the same embedding table for every word.

Step 3: Add a Class Token and Position Embeddings

ViT prepends a learnable class token to the sequence, borrowed from BERT’s [CLS] token. After the encoder, the output at this position represents the whole image and goes to the classification head.

Attention does not know the order of its inputs, so ViT adds a learnable position embedding to every token. The paper tried 2D-aware position embeddings too and found no significant gain over simple 1D ones; the model learns the grid layout on its own.

The Patch Embedding in NumPy

This code runs steps 1 to 3 for a random 224 by 224 image with ViT-Base/16 settings. The weights are random, since the point is the shapes and the operations, not a trained model:

import numpy as np

rng = np.random.default_rng(0)

# ViT-Base/16 settings from the paper: 224x224 RGB input, 16x16 patches, width 768.
image_size, patch_size, channels, dim = 224, 16, 3, 768
image = rng.random((image_size, image_size, channels), dtype=np.float32)

# 1. Cut the image into non-overlapping 16x16 patches and flatten each one.
n_side = image_size // patch_size                      # 14 patches per side
patches = image.reshape(n_side, patch_size, n_side, patch_size, channels)
patches = patches.transpose(0, 2, 1, 3, 4)            # (14, 14, 16, 16, 3)
patches = patches.reshape(n_side * n_side, -1)        # (196, 768)

# 2. Project each flattened patch to the model width with one shared linear layer.
W = rng.normal(0, 0.02, (patches.shape[1], dim)).astype(np.float32)
b = np.zeros(dim, dtype=np.float32)
tokens = patches @ W + b                               # (196, 768)

# 3. Prepend a learnable [class] token and add learnable position embeddings.
cls_token = np.zeros((1, dim), dtype=np.float32)
pos_embed = rng.normal(0, 0.02, (n_side * n_side + 1, dim)).astype(np.float32)
sequence = np.concatenate([cls_token, tokens]) + pos_embed

print("patches:        ", patches.shape)
print("patch tokens:   ", tokens.shape)
print("encoder input:  ", sequence.shape)
print("projection params:", W.size + b.size)

# The same projection written as a 16x16 convolution with stride 16 gives the same result.
kernel = W.reshape(patch_size, patch_size, channels, dim)
conv_out = np.einsum("ipjqc,pqcd->ijd",
                     image.reshape(n_side, patch_size, n_side, patch_size, channels),
                     kernel).reshape(-1, dim) + b
print("conv matches linear:", np.allclose(conv_out, tokens, atol=1e-4))

Output:

patches:         (196, 768)
patch tokens:    (196, 768)
encoder input:   (197, 768)
projection params: 590592
conv matches linear: True

Two details are worth noticing. For ViT-B/16, a flattened patch happens to have 768 values, the same as the model width, but that is a coincidence; ViT-L/16 projects the same 768 values to 1,024. And the last line confirms what many implementations exploit: the patch projection is mathematically a convolution with a 16 by 16 kernel and a stride of 16. That is why PyTorch and JAX implementations usually write it as one Conv2d layer.

Step 4: Run the Transformer Encoder

The 197 tokens pass through a stack of standard Transformer encoder layers. Each layer applies layer normalization, multi-head self-attention, a residual connection, then layer normalization, a two-layer MLP with a GELU activation and another residual connection. Every token can attend to every other token in every layer, so information can move across the whole image from the first layer on.

The paper defines three sizes, reused by many later models:

Model Layers Width MLP size Heads Parameters
ViT-Base 12 768 3,072 12 86M
ViT-Large 24 1,024 4,096 16 307M
ViT-Huge 32 1,280 5,120 16 632M

Step 5: Classify From the Class Token

The final output of the class token goes to a classification head: an MLP with one hidden layer during pre-training and a single linear layer during fine-tuning. For fine-tuning at a higher resolution, the paper keeps the patch size, which makes the sequence longer, and interpolates the learned position embeddings in 2D to fit the larger grid.

Why Does ViT Need So Much Data?

This is the paper’s most important finding. CNNs have useful assumptions built in, called inductive biases: they look at local neighborhoods, and a pattern is recognized the same way wherever it appears. ViT has much less of this. Apart from cutting the image into patches, it has to learn from data that nearby pixels are related.

The experiments show the cost and the payoff:

  • Trained on ImageNet alone (1.3M images), ViT reached accuracies a few percentage points below ResNets of comparable size.
  • Pre-trained on ImageNet-21k (14M images), the gap closed, and the larger ViT models performed about as well as ResNets pre-trained on the same data.
  • Pre-trained on Google’s internal JFT-300M dataset (303M images), ViT beat them. ViT-H/14 reached 88.55% top-1 accuracy on ImageNet, and the paper reports it took 2.5 thousand TPUv3-core-days to pre-train, against 9.9 thousand for the BiT-L ResNet it outperformed.

In short, with enough data, learning the structure beats assuming it. With too little data, the assumptions in a CNN win.

What Does ViT Learn?

The paper includes a few analyses of the trained models. The learned position embeddings end up encoding the 2D grid: patches in the same row or column get similar embeddings. Some attention heads attend across most of the image even in the lowest layers, which a CNN cannot do that early, while other heads stay local, much like early convolution layers.

Limits and What Came Next

The original paper studies image classification and transfer to other classification benchmarks. It does not report object detection or segmentation results; those came from later work. Its main practical limits are the need for large pre-training datasets and the cost of attention, which grows with the square of the number of patches, so doubling the image side length means four times as many tokens and roughly sixteen times the attention cost.

Follow-up research addressed both. DeiT (Touvron et al., 2020) trained ViT-style models competitively on ImageNet alone, using strong data augmentation and distillation from a CNN teacher. Swin Transformer (Liu et al., 2021) restricted attention to local windows in a hierarchical design, which made it practical for detection and segmentation. More recently, state space models have been tried as an alternative to attention over patches, which we cover in our article on Mamba state space models.

Google released the original code and pre-trained weights in the google-research/vision_transformer repository, written in JAX and Flax. If you have not used JAX before, our walkthrough of reproducing NanoGPT in JAX covers the basics with a language model.

Back to the CNN Engineer

The colleague’s claim turns out to be true, with one condition. An image does become a sequence of words: 196 patch tokens and a class token, produced by what is really a strided convolution. The plain Transformer then matches or beats strong CNNs, but only after pre-training on tens of millions of images or more. For most teams today, that means starting from a pre-trained ViT checkpoint and fine-tuning it, rather than training one from scratch.

Frequently Asked Questions

What Does “16×16” Mean in the ViT Paper Title?

It refers to the patch size. ViT cuts images into 16 by 16 pixel patches, and each patch is treated like one word in a sentence. Model names such as ViT-B/16 or ViT-H/14 state the patch size after the slash.

Is ViT Better Than a CNN?

It depends on the data. With large-scale pre-training, ViT matched or beat leading CNNs in the paper while using less pre-training compute. Trained only on a dataset the size of ImageNet, the original ViT did worse than comparable ResNets, although later training methods such as DeiT closed much of that gap.

Why Does ViT Use a Class Token?

The class token is a learnable vector added at the start of the sequence. Through attention it gathers information from all patches, and its final output is used for classification. The idea comes from BERT, and the paper notes that averaging all patch outputs can work just as well with suitable tuning.

Can I Train a ViT From Scratch?

You can, but on a dataset of a few thousand or even a million images, a plain ViT usually underperforms a CNN unless you use heavy augmentation and regularization. Fine-tuning a pre-trained checkpoint is the common choice.

Disclaimer: The content on this website reflects the views of contributing authors and not necessarily those of Generative AI Lab. This site may contain sponsored content, affiliate links, and material created with generative AI. Thank you for your support.

Generative AI Lab mascot
Generative AI Lab Editorial Team
Articles researched, written and edited by the Generative AI Lab team. About Generative AI Lab

Must read

- Advertisement -spot_img

More articles

- Advertisement -spot_img

Latest articles