The paper that introduced the Vision Transformer (Dosovitskiy and co-authors, Google Research, ICLR 2021) has the title “An Image is Worth 16x16 Words”. The title is the whole idea: cut the picture into squares of pixels, treat each square like a word, and give the sequence of words to a Transformer, the model that reads text. Almost nothing in the model is specific to images.
This lesson uses Transformer parts that Part 7 teaches in full. You need only a short summary of self-attention, in the next section. ConvNeXt, the last network of the CNN tour (P5.9), is the CNN that Transformers are compared with at the end.
Scope: classification, and Swin as the Transformer backbone for dense tasks. Detection and segmentation heads are P5.12 and P5.13, self-supervised training of ViTs is P5.16, and the full Transformer is Part 7.
Self-attention in one page
A Transformer works on a sequence of tokens, each a vector of numbers. In text a token is a word piece. Self-attention lets each token look at all the others. For every token the model makes a query vector, a key vector and a value vector (each is the token times a learned matrix, P7.3). The output for a token is a weighted average of all the values, and the weights come from a softmax over the dot products of that token’s query with every key:
A tiny case with scalar values: one token scores three tokens 2, 1 and 0. The softmax turns the scores into weights 0.665, 0.245 and 0.090, which sum to 1. If the three values are 10, 0 and 4, the output is . A token that matches a key strongly takes most of that token’s value.
Two facts matter for images. First, the scores form a matrix, one score for every pair of tokens, so the cost grows with . Second, nothing in the formula depends on the order of the tokens. Section “Position embeddings” returns to that. Multi-head attention runs several such attentions side by side, each on a slice of the width (12 heads of width 64 in ViT-B). The details are P7.2, P7.3, P7.5 and the whole block is P7.7.
From image to tokens
The steps for a RGB image, with the shapes of PyTorch ( for one image):
- Cut the image into non-overlapping squares of pixels. With that is patches. In general .
- Flatten each patch into a vector of numbers.
- Embed each vector with one learned linear layer to numbers. In ViT-B the width is also 768, which is a coincidence of : for a patch has 3,072 numbers and the layer shrinks it.
- Add a learned class token at the front, which makes tokens.
- Add a learned position embedding to every token.
The result is a matrix, exactly what a text Transformer expects. Everything after that is the standard encoder.
Notice in the widget that the numbers in one patch times the number of patches is always : cutting loses nothing.
The patch embedding is a convolution
Cutting, flattening and multiplying by one matrix is the same computation as a convolution (P5.2, P5.4) with a kernel, stride and output channels. Each output position looks at one patch and nothing else, because the stride equals the kernel size, so patches do not overlap. The kernel of output channel is row of reshaped to .
That is how libraries write it. In torchvision the layer is called conv_proj: Conv2d(3, 768, kernel_size=16, stride=16) with parameters. Its output has shape , which is flattened to tokens. ConvNeXt’s first layer (P5.9) is the same idea with , and Swin’s too. The Code tab checks the equivalence numerically.
The class token and the head
To classify, the model needs one vector for the whole image. ViT borrows the trick of BERT, a Transformer for text: a learned vector, the class token [CLS], is put in front of the patch tokens. It is the same at the start for every image, but attention lets it gather information from all patches in every block. At the end, its output vector goes to a classifier. The paper pre-trains with a small MLP with one hidden layer and fine-tunes with one linear layer; torchvision has the single linear layer, parameters for 1,000 classes.
The class token is a design choice and not a necessity. The paper also tried averaging the patch outputs, as a ResNet averages its last map (P5.9). The two worked similarly well, but needed different learning rates.
Position embeddings
Self-attention treats its input as a set: if you shuffle the tokens, the outputs are the same vectors in the shuffled order, and the average of the outputs does not change. The Python cell below shows this with six tokens. A model that received the patches of a shuffled picture would get the same set of tokens. The class token’s output does not change at all when the patches are shuffled, so the classifier could not tell the two pictures apart. The widget’s Shuffled button shows what that means.
So ViT adds a learned vector to every token: one trainable vector per place in the sequence, a table in ViT-B/16 ( parameters). The table starts without any 2D information. The paper tried 1D (raster order, the default), 2D (separate row and column embeddings) and relative embeddings, and saw no significant gain from the more advanced ones. It also found that the learned embeddings come to encode distance: patches that are close in the image have similar position embeddings, and the row and column structure appears. In an ablation on ViT-B/16 (ImageNet 5-shot linear accuracy), removing position embeddings cost only about 3 points (0.614 against 0.642 with 1D embeddings). A bag of patches, with no order at all, still keeps much of the class information, but the position table clearly helps.
A new image size. The table has one row per place, so a different number of patches does not fit. The usual fix, from the paper, is to keep the patch size and interpolate the table: reshape the 196 patch rows to the grid, resize the grid to the new one ( for a image) and flatten again. The class token’s row is kept as it is.
The encoder and ViT-B/16
The encoder is a stack of identical blocks, each with two sub-layers, and each sub-layer has a residual connection (P4.20) and is preceded by LayerNorm (P4.19):
MSA is multi-head self-attention, and the MLP is two linear layers with a GELU between them, applied to each token separately, with a hidden layer four times as wide as the model. This is the block of P7.7. The paper’s three sizes follow BERT:
- ViT-Base: 12 blocks, width 768, MLP size 3,072, 12 heads, 86 million parameters.
- ViT-Large: 24 blocks, width 1,024, MLP size 4,096, 16 heads, 307 million.
- ViT-Huge: 32 blocks, width 1,280, MLP size 5,120, 16 heads, 632 million.
The name ViT-B/16 is the size and the patch size: Base with patches. Smaller patches make longer sequences, so ViT-B/16 costs more than ViT-B/32 with nearly the same number of parameters (torchvision: 86.6 million for B/16 against 88.2 million for B/32, because B/32 has a larger embedding layer and a smaller position table).
Counting the parameters of torchvision’s vit_b_16 (which has a 1,000-class head and so differs a little from the paper’s 86 million): patch embedding , class token , position embeddings , twelve blocks of each, final LayerNorm and head , in total 86,567,656. In one block, attention has parameters and the MLP . The Code tab prints all of these.
The cost of attention grows with the square of the tokens
Per block, the work is the linear layers and the two products with the score matrix. Counting multiply-adds for one image:
LayerNorm, softmax, GELU, biases and the classifier head are left out of this count; together they are a small fraction of the total. For ViT-B at (), twelve blocks plus the patch embedding give about 17.6 billion multiply-adds, which agrees with the 17.5 to 17.6 billion (the papers call them FLOPs) that the Swin and ConvNeXt papers list for DeiT-B and ViT-B. The term is only about 4% of it. Now give the model a image with the same patch size: tokens.
- Tokens: times as many.
- Score entries per head and layer: against , 8.6 times as many.
- Total multiply-adds: about 55.5 billion, 3.2 times as many. The term has grown to about 11% of the total.
The term would match the linear term at , which is 4,608 tokens for width 768, so at usual image sizes attention is not the largest cost, but it grows fastest. At pixels with patches , and the term is already about 47% of the cost of a block. This is the cost question of P7.12.
What ViT has built in, and what it must learn
A convolution has two assumptions built in (P5.2): each output looks only at a small neighbourhood (locality), and the same weights are used everywhere, so shifting the input shifts the output (translation equivariance). The ViT paper says that in ViT only the MLP layers are local and translation equivariant, the attention is global, and the 2D neighbourhood structure is used only in the patch cutting and when the position embeddings are resized. In this sense ViT has much less image-specific inductive bias, the assumptions a model starts with. It must learn from data what a CNN gets for free.
That has a consequence, and the paper measured it. Evidence from Dosovitskiy et al. (ICLR 2021):
- Trained on ImageNet-1K (1.3 million images) without strong regularization, ViT models gave “modest accuracies of a few percentage points below ResNets of comparable size”. DeiT’s table lists the ViT paper’s ImageNet-1K-only results at : 77.9% for ViT-B/16 and 76.5% for ViT-L/16. With ImageNet-1K pre-training the larger ViT-L did worse than ViT-B.
- On random subsets of the JFT-300M image set (a private Google dataset), ViT-B/32 did much worse than a similar-cost ResNet50 on the 9 million subset and better on 90 million and more. The authors read it as: the convolutional bias helps on small data, and with enough data learning the patterns directly is enough, even beneficial.
- Pre-trained on JFT-300M, ViT-L/16 reached 87.76% top-1 on ImageNet and ViT-H/14 reached 88.55% (both fine-tuned at a higher resolution, about 512 pixels), against 87.54% for the large ResNet BiT-L, pre-trained on the same data. Pre-trained on the public ImageNet-21k (14 million images), ViT-L/16 reached 85.30%.
Note the conditions: the claim is about pre-training on large data and then fine-tuning, with models that were tuned by the authors.
DeiT: the same model, a better recipe
The “needs 300 million images” reading was tested by DeiT (Touvron et al., ICML 2021). Its DeiT-B has the architecture of ViT-B, with no convolution, and is trained on ImageNet-1K only, in under three days on a single machine. What changed is the training: strong data augmentation (RandAugment, Mixup, CutMix, random erasing), repeated augmentation, stochastic depth, label smoothing and AdamW with a smaller weight decay than the ViT paper used. DeiT-B reaches 81.8% top-1 at and 83.1% when fine-tuned at . The paper also trains a student with a distillation token that learns from a CNN teacher (a RegNetY with 84 million parameters), which raises the best ImageNet-1K-only result to 85.2% (1,000 epochs, ). So the data requirement of ViT depends strongly on the recipe.
Swin: windows and stages
Plain ViT has two weaknesses for dense tasks. It produces one feature map at one coarse resolution ( tokens), while detection and segmentation want feature maps at several scales like those of a ResNet (P5.12, P5.13). And global attention gets expensive at the high resolution those tasks need. The Swin Transformer (Liu et al., ICCV 2021) answers both.
- Small patches, many tokens. It starts with patches (48 numbers each) so a image gives tokens.
- Window attention. Attention is computed only inside non-overlapping windows of tokens, with by default. One window has 49 tokens, so each token has 49 scores instead of 3,136. For a map there are windows, and score entries against for global attention, 64 times fewer. If the image side doubles, global attention needs 16 times as many scores and windows only 4 times as many: the cost is linear in the number of tokens for a fixed window.
- Shifted windows. Windows alone never let tokens in different windows exchange information. So every second block moves the window grid by tokens in each direction. A token that was at the edge of a window is now away from the window edge, so across two blocks the information crosses window borders.
- Patch merging. Between stages, each group of neighbouring tokens is concatenated ( numbers) and mapped by a linear layer to . The grid halves in each direction and the width doubles, like the stages of a CNN. Swin-T has four stages with , , , , with blocks, at , , and tokens.
The last stage, , is a single window, so there attention is global. The output is a pyramid of four feature maps, which a detector or a segmentation network can use in place of a ResNet’s (P5.12, P5.13).
What the Swin paper reports (Liu et al., ICCV 2021): on ImageNet-1K at , Swin-T (29 million parameters, 4.5 billion FLOPs) reaches 81.3% against 79.8% for DeiT-S (22 million, 4.6 billion), and Swin-B (88 million, 15.4 billion) reaches 83.5% against 81.8% for DeiT-B (86 million, 17.5 billion). In its ablation on Swin-T, shifting the windows lifted ImageNet accuracy from 80.2% to 81.3% and COCO box AP from 47.7 to 50.5. With Swin-T in place of ResNet-50, four detection frameworks gained between 3.4 and 4.2 box AP at similar model size, FLOPs and latency.
Go deeper Swin details: relative position bias and the cyclic shift
Swin does not add a position embedding at the input. Inside each window’s attention it adds a learned relative position bias to the scores, , which depends only on the offset between two tokens in the window. There are possible offsets, so the table is small, and it can be resized by interpolation for another window size. The paper’s ablation found this better than absolute position embeddings, and that adding absolute ones on top did not help ImageNet and lowered the detection and segmentation scores slightly.
Shifting the window grid creates more windows, some smaller than . The paper avoids padding them by cyclic shifting: roll the feature map so the windows stay the same number and size, then mask the attention between pieces that were not neighbours in the image. Its Table 5 reports this as faster than padding.
Go deeper The distillation token of DeiT
Distillation trains a student network to match the predictions of a teacher. DeiT adds a second learned token, the distillation token, next to the class token. At the output, the class token is trained on the true label and the distillation token on the label that the teacher predicts (a “hard” label). The two tokens meet only through attention. The paper compares this with ordinary distillation, and with a convnet teacher it works better than with a transformer teacher. At inference the two classifiers can be combined. The gain is modest next to the recipe: DeiT-B reaches 81.8% without distillation at and 83.4% with it.
Vision Transformers and ConvNeXt
Did Transformers beat CNNs because of attention, or because of the training recipes and design details around it? P5.9 introduced ConvNeXt (Liu et al., CVPR 2022), a pure CNN built by moving a ResNet step by step toward the Swin design, and the paper compares it with Swin, DeiT and ViT. The numbers below are all from that paper’s tables, and the ConvNeXt authors ran or collected the comparisons, so these are one group’s results. Top-1 accuracy on the ImageNet-1K validation set, input unless stated.
- ImageNet-1K only: ConvNeXt-T 82.1% against Swin-T 81.3%, both 4.5 billion FLOPs. ConvNeXt-B 83.8% against Swin-B 83.5%, both 15.4 billion.
- Pre-trained on ImageNet-22K, then fine-tuned on ImageNet-1K: ConvNeXt-B 85.8% against Swin-B 85.2%; at , 86.8% against 86.4%.
- Plain, non-hierarchical models (an isotropic ConvNeXt with ViT’s constant grid, ImageNet-1K): ConvNeXt-B 82.0% against ViT-B 81.8%, and ConvNeXt-L 82.6% against ViT-L 82.6%, with the ViT numbers from improved training recipes (DeiT’s for B, MAE’s for L).
The authors’ conclusion is that properly designed ConvNets are not inferior to vision Transformers when pre-trained with a large dataset, and that part of the gap between older CNNs and Transformers comes from how they were trained. Read that as what it is: on these tests, at these sizes, with these recipes, the two families are close. It does not show that CNNs are better, and it does not show that Transformers are.
Depth: three ways to see it
Intuition
A ViT reads a picture the way you might read a jigsaw puzzle spread on a table. Each piece is one token. Each piece carries its picture content, plus a label for where it lies in the box (the position embedding, which the model learns). Then, in every round, each piece looks at all the other pieces, decides which ones matter to it, and updates what it believes it is part of. The class token is a piece of paper with no picture on it that listens to everyone and, at the end, announces the answer.
The picture breaks in two places. A puzzle is solved by matching edges, while ViT starts without any such rule and learns what to compare, which is why it needs plenty of examples or a strong training recipe. And a Swin window is a table that is divided into small tables: the rounds are fast because pieces only talk to their own table, and shifting the tables lets news cross the borders.
Math
Tokens and sizes. For an image of pixels and patches of : patches, tokens, per patch, embedding , position table :
Cost per block. Projections for and the output cost , the MLP with hidden width costs , and the scores and the product with cost each, where . The total is .
Window attention (Swin, tokens, channels): global MSA costs and windowed MSA costs for the attention layer alone, which is linear in for fixed .
Permutation. For a permutation matrix , attention on gives , because the softmax acts on each row and the score matrix becomes . Position embeddings break this symmetry.
Code
Torchvision’s ViT-B/16, with random weights so that nothing is downloaded. The parts and their parameters:
import torch
from torchvision import models
def count(m):
return sum(p.numel() for p in m.parameters())
vit = models.vit_b_16(weights=None)
c = vit.conv_proj
print("conv_proj :", c.in_channels, "->", c.out_channels)
print("kernel :", c.kernel_size, "stride", c.stride)
print("class tok :", tuple(vit.class_token.shape))
print("pos embed :", tuple(vit.encoder.pos_embedding.shape))
print("blocks :", len(vit.encoder.layers))
blk = vit.encoder.layers[0]
print("heads :", blk.self_attention.num_heads)
print("MLP in/out:", blk.mlp[0].in_features, blk.mlp[0].out_features)
print("head :", vit.heads.head.out_features, "classes")
parts = {
"patch embed": count(vit.conv_proj),
"[CLS] token": vit.class_token.numel(),
"positions": vit.encoder.pos_embedding.numel(),
"12 blocks": sum(count(b) for b in vit.encoder.layers),
"final norm": count(vit.encoder.ln),
"head": count(vit.heads),
}
for k, v in parts.items():
print(f"{k:12s}{v:>12,}")
print("total ", f"{count(vit):,}", sum(parts.values()) == count(vit))
print("one block ", f"{count(blk):,}")
print(" attention ", f"{count(blk.self_attention):,}")
print(" MLP ", f"{count(blk.mlp):,}")Output from a local run with PyTorch 2.9.1 and torchvision 0.24.1:
conv_proj : 3 -> 768
kernel : (16, 16) stride (16, 16)
class tok : (1, 1, 768)
pos embed : (1, 197, 768)
blocks : 12
heads : 12
MLP in/out: 768 3072
head : 1000 classes
patch embed 590,592
[CLS] token 768
positions 151,296
12 blocks 85,054,464
final norm 1,536
head 769,000
total 86,567,656 True
one block 7,087,872
attention 2,362,368
MLP 4,722,432The patch embedding as a convolution, and as “cut, flatten, multiply”:
torch.manual_seed(0)
x = torch.rand(1, 3, 224, 224) # (N, C, H, W)
# 1. the conv way
y = vit.conv_proj(x) # (1, 768, 14, 14)
tokens = y.flatten(2).transpose(1, 2) # (1, 196, 768)
# 2. the "cut, flatten, multiply" way
P = 16
patches = x[0].unfold(1, P, P).unfold(2, P, P) # (3, 14, 14, 16, 16)
patches = patches.permute(1, 2, 0, 3, 4).reshape(196, 3 * P * P)
W = vit.conv_proj.weight.reshape(768, -1) # (768, 768)
tokens2 = patches @ W.T + vit.conv_proj.bias
print(y.shape, tokens.shape)
print("same tokens:", torch.allclose(tokens[0], tokens2, atol=1e-5))
print(vit(x).shape)torch.Size([1, 768, 14, 14]) torch.Size([1, 196, 768])
same tokens: True
torch.Size([1, 1000])Resizing the position embeddings from the grid to for a image, keeping the class token’s row:
import torch.nn.functional as F
pe = vit.encoder.pos_embedding # (1, 197, 768)
cls_pe, grid = pe[:, :1], pe[:, 1:]
grid = grid.reshape(1, 14, 14, 768).permute(0, 3, 1, 2)
grid = F.interpolate(grid, size=(24, 24), mode="bicubic",
align_corners=False)
grid = grid.permute(0, 2, 3, 1).reshape(1, 576, 768)
new = torch.cat([cls_pe, grid], dim=1)
print(tuple(pe.shape), "->", tuple(new.shape))
vit384 = models.vit_b_16(weights=None, image_size=384)
print(f"{sum(p.numel() for p in vit384.parameters()):,}")(1, 197, 768) -> (1, 577, 768)
86,859,496The 384 model has more parameters than the 224 model, all of them position embeddings. torchvision’s own training scripts do this resizing when loading weights for another size; the code above is the idea in a few lines.
Try it in Python
The first cell cuts a random image into patches with plain NumPy reshapes and embeds them. The second builds a small self-attention and shows that without position vectors shuffling the tokens only shuffles the outputs. Both run in the browser with NumPy.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Running the cell gives 196 patches of 768 numbers, an input of , and 590,592 embedding parameters. In a PyTorch image the channel axis comes first, so the flattening order inside a patch differs from this code, and the embedding matrices differ by a fixed reordering of their rows. Try or and predict the table first. Why does fail?
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Running the cell prints True for the two no-position checks and for the last check. Without positions the shuffled input gives the same outputs in another order. With a fixed vector added per place, the same patches in another order no longer give the same outputs.
Common mistakes
Quiz
Check your understanding
A ViT with patches reads a image. How many attention scores does one head compute in one layer?
The score matrix has one row and one column per token, and the class token is a token like any other: . Leaving out the class token would give 576 tokens and 331,776 scores. Scores for all pairs, not only for the class token, are computed. The pixel count is not involved, because the patches are already the tokens.
You shuffle the 196 patch tokens of an image (the class token stays first) before they enter a Transformer encoder that has no position embeddings. What happens?
Each output is a weighted average of values with weights from query-key scores, and permuting the tokens only permutes the rows of the score matrix, so the outputs are the same set of vectors, reordered, and the encoder cannot tell the two pictures apart. Shuffling does not change the content of any token. Neighbouring patches are not special to the encoder, and it has no grid to check against.
DeiT-B has the same architecture as ViT-B/16 and reaches 81.8% on ImageNet at with ImageNet-1K only. What was the main change?
DeiT keeps the ViT architecture with no convolution, uses ImageNet-1K only, and changes the training: augmentations such as RandAugment, Mixup and CutMix, repeated augmentation, stochastic depth and label smoothing. Convolutions are not added, extra data is not used, and shifted windows belong to Swin.
Why does the cost of Swin grow only linearly with the number of tokens?
A larger image gives more windows of the same size, and the work per window is fixed: 49 tokens with 49 scores each, so the total grows with the number of windows. Patch merging does reduce the tokens between stages, but by a factor of four per stage and not along the depth. Every token still attends inside its window, with no class-token-only scheme, and shifting only moves the window grid.
Exercises
- A RGB image is cut into patches. How many patches, how many tokens with the class token, how many numbers in one flattened patch, and how many attention scores per head and layer?
Show answer
, so patches and 65 tokens. A patch has numbers. The scores number . - How many parameters does the patch embedding of ViT-B/32 have (width 768, patches, RGB, with bias)? Compare it with the 590,592 of ViT-B/16.
Show answer
, four times as many as ViT-B/16, because each patch has four times as many numbers. - ViT-B/16 is fine-tuned at . How many rows does the position table have and how many parameters does it have? How much larger is the model than at ?
Show answer
rows and parameters, against . The model grows by parameters, from 86,567,656 to 86,859,496. - A Swin stage works on tokens with windows. The image side is doubled, so the stage has tokens. How do the score entries for global attention and for window attention change?
Show answer
Global: becomes , 16 times as many. Windows: becomes , 4 times as many.
Next: P5.16 trains vision models without labels. Part 7 teaches the Transformer itself, starting with self-attention in P7.2.