Vision Transformer (ViT): reading a picture as patches, like words
The transformer was built to read sentences. Cut a picture into small square pieces and feed each piece in as if it were a word, and it can read pictures too. Change the patch size and watch how the number of pieces and the cost change.
Short answer. A Vision Transformer (ViT) cuts a picture into patches (small square pieces), flattens the pixels of each patch into one row, turns that row into a vector with a linear projection, adds position information and a class token, and feeds the result to a plain transformer. The number of patches is N = (picture side ÷ patch side)² and the self-attention table has N² cells. A 224 × 224 picture cut with patch 16 gives 196 patches and 38,416 cells. Unlike a convolutional network, it has no built-in rule that "nearby pixels come first", so it works best when you have a lot of data or a model already trained on a large dataset.
Use the patch buttons to move the cut lines. Click a patch in the picture, or type its number in the box, to choose it. The picture is a made-up 32 × 32 pixels, and each pixel has 3 color numbers (red, green, blue). A real ViT usually takes bigger pictures, but it cuts and flattens them the same way. This lab only counts; it does not train anything.
Try this. ① At the start (patch 8) there are 4 patches per side, 16 patches, 192 numbers per patch (8 × 8 × 3), and 256 attention cells (289 with the class token). The sun sits entirely inside patch 4. ② Press "Patch 4": 8 per side, 64 patches, 48 numbers, 4,096 cells. Halving the patch gave 4 times the patches and 16 times the cells. The sun is now split over four patches (7, 8, 15 and 16), and the chosen patch becomes patch 16 at the same place. ③ "Patch 16" gives 2 per side, 4 patches, 768 numbers and 16 cells. Few patches and little work, but each patch holds a whole quarter of the picture.
Definitions
The text below explains with the small picture in the lab and a 224 × 224 picture. Here are the definitions of the ideas this page uses. Let H, W, C be the picture's height, width and number of channels, P the side of a patch, and D the length of a token vector.
- patch
- A square piece of size P × P × C cut from an H × W × C picture, with no overlap. When H and W are multiples of P, the number of patches N is below.
- patch embedding, linear projection
- A linear projection that takes the row xk of length P²C made by flattening patch k and multiplies it by a learned matrix E, shared by all patches, to get a vector of length D.
- class token, [CLS]
- A learned vector xclass put at the front of the sequence of patch embeddings. At the last layer, only the output vector at this place goes into the classification head to choose the class of the whole picture.
- position embedding
- A learned vector, one per token place, added to the token at that place. With the class token there are N + 1 places, so Epos is (N + 1) × D, and the sequence z₀ that enters the encoder is below.
- Vision Transformer (ViT)
- A model that cuts a picture into patches, builds the sequence z₀ from patch embeddings, a class token and position embeddings, passes it through Transformer encoder layers in turn, and classifies from the output at the class token's place.
- inductive bias
- An assumption built into a model's structure in advance. The locality (look at near things first) and translation equivariance (the same filter finds a thing wherever it moves) of a convolutional neural network are examples. A Vision Transformer compares all patches from the first layer, so it has to learn such assumptions from data.
1. What a Vision Transformer is: a picture read like words
A transformer takes a row of words (tokens) and mixes their meaning with self-attention, where every word is compared with every other word. A picture has no words. If every pixel were a word, one 224 × 224 picture would be 50,176 words, and the attention table that compares every pair would be far too big.
So a Vision Transformer groups pixels into words. It cuts the picture like a checkerboard into squares of P × P pixels (patches) and uses each patch as one word. After that it is the same encoder a transformer uses to read text. The title of the original paper, "An Image is Worth 16x16 Words", is exactly this idea.
2. The steps: from cutting to a class
1. Cut picture H × W × C → N patches (each P × P × C) N = (H × W) ÷ P²
2. Flatten patch k → a row x_k of P²·C numbers
3. Project e_k = x_k · E E is a (P²·C) × D table, learned
4. Class token put one vector x_class in front learned
5. Position z₀ = [x_class, e_1, …, e_N] + E_pos E_pos is (N + 1) × D, learned
6. Encoder pass z₀ through the transformer encoder layers
7. Classify the vector at the class token place in the last layer → classification head → class scores
C is the number of channels (3 for color), and D is the length of a token vector, chosen by the model. Line 5 is equation (1) of the original paper.
Patch to vector: the linear projection
A flattened patch is a row of P²·C numbers. Multiply it by a table E and you get a vector of length D. Every patch uses the same E. In text, a word is looked up in an embedding table to get its vector; in a picture, this multiplication does that job.
Adding position information
Self-attention does not look at the order of tokens. Without position information you could shuffle the patches and the result at the class token would not change. The model could not tell whether the sun is at the top left or the bottom right. So each place gets its own position vector, added to the token (positional encoding). The original ViT used a learned 1D position vector for each patch number, and reported that versions aware of 2D places did not do much better.
The class token
To give one answer for the whole picture (say, "cat"), you need one vector. Put one learned vector (the class token) at the front, and as it passes through the layers it gathers information from every patch through attention. In the last layer, only the vector at this place goes to the classification head. It is the same trick as the [CLS] token of the text model BERT. Averaging all the patch vectors is another option.
3. How the formula is built
Take a 224 × 224 picture and patch 16, and build up the number of patches and the size of the attention table. The picture is the 32 × 32 picture from the lab above, made 7 times bigger (32 × 7 = 224). H is the picture side, P is the patch side, N is the number of patches.
- Cut one side:
H ÷ P. 224 ÷ 16 = 14. One side is 14 patches. It must divide evenly, so the picture is resized to a multiple of the patch size first. - Square it:
N = (H ÷ P)². The other side is also 14, so 14 × 14 = 196 patches. That is the same as the picture's area (H²) divided by one patch's area (P²). Why: patches line up in two directions, across and down, so you multiply the per-side count twice. - Every pair:
cells = N × N. Self-attention gives each patch one score against every patch, itself included. One patch is compared with 196, and all 196 do the same. Why: to link the far ends of the picture from the very first layer, it compares with everything instead of picking only neighbors. - Done:
cells = N² = (H ÷ P)⁴. 196² = 38,416 cells (197² = 38,809 with the class token). It is the fourth power of the patches per side, so halving the patch to 8 gives 784 patches and 614,656 cells, 16 times more. Doubling the picture side to 448 gives the same 16 times.
There is one such table per layer and per attention head. The work and memory for the attention table grow with N², while the work done on each token by itself (the projection, the small network inside each layer) grows with N. So with few patches the second part is bigger, and as the patches grow in number, the N² part overtakes it.
Try this. Press "Next" three times and watch the piece added to the formula (orange background). ① 13 vertical lines cut one side into 14. ② The grid becomes 196 squares. ③ Lines go from the orange patch at the center of the sun (patch 27) to the centers of all 196 patches. ④ The purple table on the right has 196 × 196 = 38,416 cells, and the one orange band (196 cells) is the lines from step ③.
4. Work it out by hand
Use the lab's starting values: a 32 × 32 color picture and patch 8.
- One side.
32 ÷ 8 = 4. 4 patches per side. - Number of patches.
N = 4² = 16. - Flatten. One patch is
8 × 8 = 64pixels with 3 numbers each, so a row of64 × 3 = 192numbers. - Project. Multiply the row of 192 by a 192 × D table E to get one vector of D numbers. All 16 patches use the same E.
- Tokens and table. Add the class token for 17 tokens. The attention table has
16² = 256cells (17² = 289with the class token).
Now one projection with real numbers. Keep it tiny: one 2 × 2 patch of a gray picture (1 number per pixel), turned into D = 2. E is normally learned; here it is picked by hand to give "sum of the top row" and "sum of the bottom row".
| Step | Math | Result |
|---|---|---|
| Patch (brightness) | [2 0] / [1 3] | 2 × 2 |
| Flatten | row by row, from the top left | x = [2, 0, 1, 3] |
| First column of E [1, 1, 0, 0] | 2·1 + 0·1 + 1·0 + 3·0 | 2 |
| Second column of E [0, 0, 1, 1] | 2·0 + 0·0 + 1·1 + 3·1 | 4 |
| Projection | e = x · E | [2, 4] |
| Add position (this place's position vector [0.5, 0]) | [2 + 0.5, 4 + 0] | [2.5, 4] |
5. Properties to know
| Property | In plain words | In the lab |
|---|---|---|
Patches N = (H ÷ P)² | Halve the patch side and you get 4 times the patches | ① patch 8 → 4: 16 → 64 |
Attention cells N² = (H ÷ P)⁴ | Halve the patch, or double the picture side, and you get 16 times the cells | ① 256 → 4,096, ② 38,416 → 614,656 |
Length of one patch P² × C | Bigger patches hold more numbers each, and the table E gets bigger too | ① 48, 192, 768 |
| No order without position | Self-attention ignores the order of tokens. The position vector tells it where each patch is | Section 2 |
| No "nearby first" rule | It compares every patch from the first layer. It has to learn from data that neighbors matter | The lines in steps ② and ③ |
6. How it differs from a convolutional network
- How far it looks. A convolution filter sees only nearby pixels, like a 3 × 3 square. You stack layers to see wider. ViT self-attention sees every patch from the first layer.
- Rules built in. A convolutional network has two rules built into its structure: "nearby pixels are closely related" and "the same pattern is found by the same filter wherever it is". Built-in rules like these are called inductive bias. A ViT has almost none. In the words of the original paper, it barely uses the 2D neighbor structure, except when cutting the patches and when adjusting the position vectors. So it must learn those relations from data, and it needs a lot of data. The original paper reported that trained only on a mid-sized dataset such as ImageNet, it does a little worse than a ResNet (a convolutional network) of similar size, and that trained first on much more data and then transferred, it does better.
- How the cost grows. A convolution layer costs in proportion to the number of pixels. The ViT attention table grows with the square of the patches, which is the fourth power of the picture side (section 3). High resolution is expensive.
7. When to use what
| Option | Good | Bad | Use it when |
|---|---|---|---|
| Convolutional network (CNN) | The "nearby first" rule is built in, so it learns well even from little data. Cost is proportional to pixels, so big pictures are fine | Needs many stacked layers to connect far-apart places | You have little data and no useful pretrained model. High resolution. Small devices |
| Vision Transformer (ViT) | Sees the whole picture from the first layer. Simple structure that scales well with more data and bigger models, and it shares parts with text transformers | Few built-in rules, so training from scratch needs a lot of data. Cost grows with the square of the patches, so high resolution is expensive | You fine-tune a model pretrained on a large dataset (transfer learning). Resolutions like 224 × 224 that give a few hundred patches |
| A mix of both (convolution stem + transformer, or attention only inside small windows) | Looks at nearby things first with convolution or small windows. Window attention costs in proportion to picture size | More complex, and tools made for plain transformers do not fit as they are | A medium amount of data. Detection and segmentation that need high resolution |
The original paper has a mix too (hybrid): instead of the picture, it cuts the feature map from a convolutional network into patches. The Swin Transformer splits the picture into small windows, runs attention only inside each window, and shifts the windows from layer to layer to link neighboring windows. That is why its cost grows in proportion to picture size.
Where it is used
- Image classification. The last vector of the class token goes to the classification head to pick a class.
- Reusing a pretrained model. Take a ViT trained on a large dataset and fine-tune it on your own data. The original paper evaluated it this way too (transfer learning).
- A base for detection and segmentation. Mixed designs with window attention are used as the base model for object detection and segmentation (Swin paper).
Frequently asked
Are smaller patches always better?
Smaller patches see the picture in finer detail, but the cost grows fast. Halve the patch side and you get 4 times as many patches and 16 times as many attention cells. For a 224 × 224 picture, patch 16 gives 196 patches and 38,416 cells, and patch 8 gives 784 patches and 614,656 cells.
Can I feed a bigger picture than the one used in training?
If you keep the patch size, you get more patches, and there is no position vector for the new places. When the original paper fine-tuned on bigger pictures, it interpolated the learned position vectors in 2D, following where each patch sits in the picture. More patches also means the attention table grows with the square.
Does a ViT have no convolution at all?
The linear projection that turns a patch into a vector is the same math as one convolution whose kernel size and stride equal the patch size, so code often writes it as one convolution layer. The transformer layers after it have no convolution.
Words
| Words used here | Textbook term |
|---|---|
| A transformer that reads a picture in pieces | Vision Transformer (ViT) |
| Piece, square piece | Patch |
| Flatten a patch into a vector | Patch embedding, linear projection |
| Number of color numbers | Channels (3 for RGB color) |
| Row of tokens, number of patches | Sequence, sequence length |
| Vector added for each place | Position embedding |
| Token for the class | Class token, [CLS] |
| Final classifying layer | Classification head |
| Table of scores for every pair | Attention matrix, self-attention |
| Rules built into the structure | Inductive bias |
| Nearby first | Locality |
| Same filter finds it wherever it moves | Translation equivariance |
| Train first on a large dataset | Pre-training |
| Take it and adjust it to your data | Fine-tuning, transfer learning |
| A mix of convolution and transformer | Hybrid, window attention |
| Fill in values between known ones | Interpolation |
Sources
- Alexey Dosovitskiy et al., An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale, arXiv:2010.11929. Cutting patches and equation (1), learned position vectors and the class token, inductive bias and the amount of data, the hybrid, interpolating position vectors when fine-tuning on bigger pictures.
- Ashish Vaswani et al., Attention Is All You Need, arXiv:1706.03762. The transformer encoder, and self-attention cost growing with the square of the sequence length.
- Ze Liu et al., Swin Transformer: Hierarchical Vision Transformer using Shifted Windows, arXiv:2103.14030. Attention only inside windows, cost proportional to picture size, detection and segmentation.
- torchvision source, vision_transformer.py. An implementation that writes the patch projection as one convolution layer with kernel and stride equal to the patch size.
← Positional encodingMultimodal learning: how CLIP puts images and text in one space →