Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 5: Computer Vision and CNNs

Vision Transformers

P5.1540 min●●● AdvancedReviewed Dec 3, 2026

Why this matters for machine learning

Many current image models are Transformers that read a picture as a sequence of patches. Knowing how the patches become tokens, and what the attention costs, lets you read a model card such as ViT-B/16 and see why high-resolution images are expensive.

  • Detection and segmentation models use Transformer backbones such as Swin, which keeps the cost linear in the number of pixels (tokens) so that large images stay affordable. (P5.12: Detection architectures)
  • Self-supervised image models such as DINO and MAE are trained on ViT backbones. (P5.16: Self-supervised vision)
  • The same idea of turning a signal into a sequence of tokens carries over to audio, video and time series. (P7.15: Transformers beyond text, coming soon)
  • The cost of attention in the number of tokens is the central cost question for long inputs, and an image at high resolution is a long input. (P7.12: The cost of attention, coming soon)

Before this: Padding, stride and dilation, The CNN architecture tour, Residual connections

After this lesson you can

  • Turn an image into the token sequence of a Vision Transformer and give the shape at each step, including the class token and the position embeddings
  • Show that the patch embedding is a convolution with kernel size and stride equal to the patch size
  • Count the parameters of ViT-B/16 by part, and compute how the attention cost grows with image size
  • State what the ViT and DeiT papers found about data, and how Swin's windows and stages change the cost
  • Compare Vision Transformers with ConvNeXt using only the numbers and conditions the papers report

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 16×1616\times16 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 TT tokens, each a vector of dmodeld_{\text{model}} 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:

output=softmax ⁣(QK⊤dk)V.\text{output}=\mathrm{softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}}\right)\mathbf{V}.

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 0.665⋅10+0.245⋅0+0.090⋅4=7.010.665\cdot10+0.245\cdot0+0.090\cdot4=7.01. A token that matches a key strongly takes most of that token’s value.

Two facts matter for images. First, the scores form a T×TT\times T matrix, one score for every pair of tokens, so the cost grows with T2T^2. 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 224×224224\times224 RGB image, with the shapes of PyTorch ((C,H,W)(C,H,W) for one image):

  1. Cut the image into non-overlapping squares of P×PP\times P pixels. With P=16P=16 that is 14×14=19614\times14=196 patches. In general N=HW/P2N=HW/P^2.
  2. Flatten each patch into a vector of P⋅P⋅3=768P\cdot P\cdot3=768 numbers.
  3. Embed each vector with one learned linear layer to dmodeld_{\text{model}} numbers. In ViT-B the width is also 768, which is a coincidence of 16⋅16⋅316\cdot16\cdot3: for P=32P=32 a patch has 3,072 numbers and the layer shrinks it.
  4. Add a learned class token at the front, which makes T=N+1=197T=N+1=197 tokens.
  5. Add a learned position embedding to every token.

The result is a 197×768197\times768 matrix, exactly what a text Transformer expects. Everything after that is the standard encoder.

Cut a picture into patches

Patch size
Order

The sequence the Transformer receives, first tokens only. Each patch becomes one token; the first token, [CLS], is added.

Number under a tile = which patch it is in the original picture. The sequence position is its place in this row.

  • Patches: 14 × 14 = 196. With [CLS]: 197 tokens.
  • Numbers in one flattened patch: 16 · 16 · 3 = 768.
  • Attention scores per head and layer: 197² = 38,809, which is the same as for 16×16 patches.
  • Patches in their original order.

The picture is drawn by code (no photo). Numbers on the grid show the original patch index and appear when the patches are at least 32×32.

Cut a 224 by 224 picture (drawn by code) into patches. Choose the patch size to see the number of patches, the tokens, the numbers in one flattened patch and the attention scores. The strip shows the first tokens: [CLS] and the first patches. Shuffled puts the same patches in a different order: the set of tokens does not change, only their positions.

Notice in the widget that the numbers in one patch times the number of patches is always 224⋅224⋅3=150,528224\cdot224\cdot3=150{,}528: cutting loses nothing.

The patch embedding is a convolution

Cutting, flattening and multiplying by one matrix E\mathbf{E} is the same computation as a convolution (P5.2, P5.4) with a P×PP\times P kernel, stride PP and dmodeld_{\text{model}} 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 oo is row oo of E⊤\mathbf{E}^\top reshaped to (3,P,P)(3,P,P).

That is how libraries write it. In torchvision the layer is called conv_proj: Conv2d(3, 768, kernel_size=16, stride=16) with 768⋅16⋅16⋅3+768=590,592768\cdot16\cdot16\cdot3+768=590{,}592 parameters. Its output has shape (768,14,14)(768,14,14), which is flattened to 196196 tokens. ConvNeXt’s first layer (P5.9) is the same idea with P=4P=4, 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, 768⋅1000+1000=769,000768\cdot1000+1000=769{,}000 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 197×768197\times768 table in ViT-B/16 (151,296151{,}296 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 14×1414\times14 grid, resize the grid to the new one (24×2424\times24 for a 384×384384\times384 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):

zℓ′=MSA(LN(zℓ−1))+zℓ−1,zℓ=MLP(LN(zℓ′))+zℓ′.\begin{aligned} \mathbf{z}'_\ell&=\mathrm{MSA}\big(\mathrm{LN}(\mathbf{z}_{\ell-1})\big)+\mathbf{z}_{\ell-1},\\ \mathbf{z}_\ell&=\mathrm{MLP}\big(\mathrm{LN}(\mathbf{z}'_\ell)\big)+\mathbf{z}'_\ell . \end{aligned}

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 16×1616\times16 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 590,592590{,}592, class token 768768, position embeddings 151,296151{,}296, twelve blocks of 7,087,8727{,}087{,}872 each, final LayerNorm 1,5361{,}536 and head 769,000769{,}000, in total 86,567,656. In one block, attention has 2,362,3682{,}362{,}368 parameters and the MLP 4,722,4324{,}722{,}432. 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 T×TT\times T score matrix. Counting multiply-adds for one image:

12 T dmodel2⏟projections and MLP+2 T2 dmodel⏟scores and weighted sum.\underbrace{12\,T\,d_{\text{model}}^{2}}_{\text{projections and MLP}}+\underbrace{2\,T^{2}\,d_{\text{model}}}_{\text{scores and weighted sum}} .

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 224×224224\times224 (T=197T=197), 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 T2T^2 term is only about 4% of it. Now give the model a 384×384384\times384 image with the same patch size: 24⋅24+1=57724\cdot24+1=577 tokens.

  • Tokens: 577/197=2.93577/197=2.93 times as many.
  • Score entries per head and layer: 5772=332,929577^2=332{,}929 against 1972=38,809197^2=38{,}809, 8.6 times as many.
  • Total multiply-adds: about 55.5 billion, 3.2 times as many. The T2T^2 term has grown to about 11% of the total.

The T2T^2 term would match the linear term at T=6 dmodelT=6\,d_{\text{model}}, which is 4,608 tokens for width 768, so at usual image sizes attention is not the largest cost, but it grows fastest. At 1024×10241024\times1024 pixels with 16×1616\times16 patches T=4097T=4097, and the T2T^2 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 384×384384\times384: 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 224×224224\times224 and 83.1% when fine-tuned at 384×384384\times384. 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, 384×384384\times384). 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 (14×1414\times14 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.

  1. Small patches, many tokens. It starts with 4×44\times4 patches (48 numbers each) so a 224×224224\times224 image gives 56×56=3,13656\times56=3{,}136 tokens.
  2. Window attention. Attention is computed only inside non-overlapping windows of M×MM\times M tokens, with M=7M=7 by default. One window has 49 tokens, so each token has 49 scores instead of 3,136. For a 56×5656\times56 map there are 8⋅8=648\cdot8=64 windows, and 64⋅492=153,66464\cdot49^2=153{,}664 score entries against 31362=9,834,4963136^2=9{,}834{,}496 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.
  3. Shifted windows. Windows alone never let tokens in different windows exchange information. So every second block moves the window grid by ⌊M/2⌋=3\lfloor M/2\rfloor=3 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.
  4. Patch merging. Between stages, each group of 2×22\times2 neighbouring tokens is concatenated (4C4C numbers) and mapped by a linear layer to 2C2C. The grid halves in each direction and the width doubles, like the stages of a CNN. Swin-T has four stages with C=96C=96, 192192, 384384, 768768, with 2,2,6,22,2,6,2 blocks, at 56256^2, 28228^2, 14214^2 and 727^2 tokens.

The last stage, 7×77\times7, 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 224×224224\times224, 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 B\mathbf{B} to the scores, softmax(QK⊤/d+B)V\mathrm{softmax}(\mathbf{Q}\mathbf{K}^\top/\sqrt{d}+\mathbf{B})\mathbf{V}, which depends only on the offset between two tokens in the window. There are (2M−1)2(2M-1)^2 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 M×MM\times M. 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 224×224224\times224 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, 224×224224\times224 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 384×384384\times384, 86.8% against 86.4%.
  • Plain, non-hierarchical models (an isotropic ConvNeXt with ViT’s constant 14×1414\times14 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 H×WH\times W pixels and patches of P×PP\times P: N=HW/P2N=HW/P^2 patches, T=N+1T=N+1 tokens, xp∈RP2C\mathbf{x}_p\in\mathbb{R}^{P^2C} per patch, embedding E∈RP2C×dmodel\mathbf{E}\in\mathbb{R}^{P^2C\times d_{\text{model}}}, position table Epos∈RT×dmodel\mathbf{E}_{\text{pos}}\in\mathbb{R}^{T\times d_{\text{model}}}:

z0=[xclass; xp1E;… ;xpNE]+Epos.\begin{aligned} \mathbf{z}_0&=[\mathbf{x}_{\text{class}};\,\mathbf{x}_p^{1}\mathbf{E};\dots;\mathbf{x}_p^{N}\mathbf{E}]\\ &\quad+\mathbf{E}_{\text{pos}} . \end{aligned}

Cost per block. Projections for Q,K,V\mathbf{Q},\mathbf{K},\mathbf{V} and the output cost 4Td24Td^2, the MLP with hidden width 4d4d costs 2⋅T⋅d⋅4d=8Td22\cdot T\cdot d\cdot4d=8Td^2, and the scores QK⊤\mathbf{Q}\mathbf{K}^\top and the product with V\mathbf{V} cost T2dT^2d each, where d=dmodeld=d_{\text{model}}. The total is 12Td2+2T2d12Td^2+2T^2d.

Window attention (Swin, h×wh\times w tokens, CC channels): global MSA costs 4hwC2+2(hw)2C4hwC^2+2(hw)^2C and windowed MSA costs 4hwC2+2M2hwC4hwC^2+2M^2hwC for the attention layer alone, which is linear in hwhw for fixed MM.

Permutation. For a permutation matrix Π\mathbf{\Pi}, attention on ΠX\mathbf{\Pi}\mathbf{X} gives Π⋅attention(X)\mathbf{\Pi}\cdot\text{attention}(\mathbf{X}), because the softmax acts on each row and the score matrix becomes ΠSΠ⊤\mathbf{\Pi}\mathbf{S}\mathbf{\Pi}^\top. 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,432

The 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 14×1414\times14 grid to 24×2424\times24 for a 384×384384\times384 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,496

The 384 model has (577−197)⋅768=291,840(577-197)\cdot768=291{,}840 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.

Patchify and embed

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 197×768197\times768, and 590,592 embedding parameters. In a PyTorch image the channel axis comes first, so the flattening order inside a patch differs from this (H,W,C)(H,W,C) code, and the embedding matrices differ by a fixed reordering of their rows. Try P=14P=14 or P=40P=40 and predict the table first. Why does P=40P=40 fail?

Attention does not know the order

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

  1. A ViT with 16×1616\times16 patches reads a 384×384384\times384 image. How many attention scores does one head compute in one layer?

  2. 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?

  3. DeiT-B has the same architecture as ViT-B/16 and reaches 81.8% on ImageNet at 224×224224\times224 with ImageNet-1K only. What was the main change?

  4. Why does the cost of Swin grow only linearly with the number of tokens?

Exercises

  1. A 256×256256\times256 RGB image is cut into 32×3232\times32 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 answer256/32=8256/32=8, so 8⋅8=648\cdot8=64 patches and 65 tokens. A patch has 32⋅32⋅3=3,07232\cdot32\cdot3=3{,}072 numbers. The scores number 652=4,22565^2=4{,}225.
  2. How many parameters does the patch embedding of ViT-B/32 have (width 768, 32×3232\times32 patches, RGB, with bias)? Compare it with the 590,592 of ViT-B/16.
    Show answer32⋅32⋅3⋅768+768=2,359,296+768=2,360,06432\cdot32\cdot3\cdot768+768=2{,}359{,}296+768=2{,}360{,}064, four times as many as ViT-B/16, because each patch has four times as many numbers.
  3. ViT-B/16 is fine-tuned at 384×384384\times384. How many rows does the position table have and how many parameters does it have? How much larger is the model than at 224×224224\times224?
    Show answer24⋅24+1=57724\cdot24+1=577 rows and 577⋅768=443,136577\cdot768=443{,}136 parameters, against 151,296151{,}296. The model grows by 291,840291{,}840 parameters, from 86,567,656 to 86,859,496.
  4. A Swin stage works on 56×5656\times56 tokens with 7×77\times7 windows. The image side is doubled, so the stage has 112×112112\times112 tokens. How do the score entries for global attention and for window attention change?
    Show answerGlobal: 31362=9,834,4963136^2=9{,}834{,}496 becomes 125442=157,351,93612544^2=157{,}351{,}936, 16 times as many. Windows: 64⋅492=153,66464\cdot49^2=153{,}664 becomes 256⋅492=614,656256\cdot49^2=614{,}656, 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.

Key takeaways

  • A ViT cuts an image into P×PP\times P patches, flattens each one and maps it with one linear layer to a token of width dmodeld_{\text{model}}. A 224×224224\times224 image with 16×1616\times16 patches gives 196 tokens of 768 numbers.
  • That linear layer is a convolution with kernel size and stride PP. A learned class token is added at the front, learned position embeddings are added to every token, and a standard Transformer encoder follows. The class token's output goes to a linear classifier.
  • ViT-B/16 has 12 blocks, width 768, 12 heads, MLP size 3,072 and 86,567,656 parameters in torchvision. Attention scores grow with the square of the number of tokens: 1972197^2 at 224×224224\times224 and 5772577^2 at 384×384384\times384.
  • ViT has little built-in image structure. The ViT paper found that it needs large pre-training data to beat CNNs, and DeiT-B reached 81.8% at 224×224224\times224, and 83.1% when fine-tuned at 384×384384\times384, on ImageNet-1K alone with a strong training recipe.
  • Swin computes attention inside 7×77\times7 windows, shifts the windows in every second block and merges patches between stages, so the cost is linear in the number of pixels (tokens) and the stages give feature maps like a CNN's. ConvNeXt, a pure CNN, matches or beats Swin in the ConvNeXt paper's tests, so the evidence does not say that attention alone is better.
Found a mistake? Tell us