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.

N=HWP2

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.

ek=xkE,E∈ℝ(P2C)×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.

z0=[xclass,e1,…,eN]+Epos

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.

ViT-Base drawn top to bottom. The image is cut into 196 patches of 16 × 16, each patch becomes a 768-dimensional vector, a class token is put in front, position embeddings are added, and the sequence passes through 12 transformer blocks. At the end only the class token's vector is used to pick the class.

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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.

  1. One side. 32 ÷ 8 = 4. 4 patches per side.
  2. Number of patches. N = 4² = 16.
  3. Flatten. One patch is 8 × 8 = 64 pixels with 3 numbers each, so a row of 64 × 3 = 192 numbers.
  4. 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.
  5. Tokens and table. Add the class token for 17 tokens. The attention table has 16² = 256 cells (17² = 289 with 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".

StepMathResult
Patch (brightness)[2 0] / [1 3]2 × 2
Flattenrow by row, from the top leftx = [2, 0, 1, 3]
First column of E [1, 1, 0, 0]2·1 + 0·1 + 1·0 + 3·02
Second column of E [0, 0, 1, 1]2·0 + 0·0 + 1·1 + 3·14
Projectione = 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

PropertyIn plain wordsIn 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² × CBigger patches hold more numbers each, and the table E gets bigger too① 48, 192, 768
No order without positionSelf-attention ignores the order of tokens. The position vector tells it where each patch isSection 2
No "nearby first" ruleIt compares every patch from the first layer. It has to learn from data that neighbors matterThe lines in steps ② and ③

6. How it differs from a convolutional network

7. When to use what

OptionGoodBadUse 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 fineNeeds many stacked layers to connect far-apart placesYou 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 transformersFew built-in rules, so training from scratch needs a lot of data. Cost grows with the square of the patches, so high resolution is expensiveYou 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 sizeMore complex, and tools made for plain transformers do not fit as they areA 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

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 hereTextbook term
A transformer that reads a picture in piecesVision Transformer (ViT)
Piece, square piecePatch
Flatten a patch into a vectorPatch embedding, linear projection
Number of color numbersChannels (3 for RGB color)
Row of tokens, number of patchesSequence, sequence length
Vector added for each placePosition embedding
Token for the classClass token, [CLS]
Final classifying layerClassification head
Table of scores for every pairAttention matrix, self-attention
Rules built into the structureInductive bias
Nearby firstLocality
Same filter finds it wherever it movesTranslation equivariance
Train first on a large datasetPre-training
Take it and adjust it to your dataFine-tuning, transfer learning
A mix of convolution and transformerHybrid, window attention
Fill in values between known onesInterpolation

Sources

← Positional encodingMultimodal learning: how CLIP puts images and text in one space →