Skip to content
LearnAI

7.1Vision Transformers: images as tokens

How a Transformer built for words learned to see, by cutting an image into a grid of patches and reading them like a sentence.

⏱ 14 minIntermediate

From words to pixels

Everything in the language part of this course rests on one move: turn the input into a sequence of tokensTokenA chunk of text (a word, part of a word, or a character) that a language model reads and writes as a single unit., turn each token into a vector, and let a TransformerTransformerThe neural network architecture behind modern LLMs: stacked blocks of self-attention and feed-forward layers with residual connections. mix information between those vectors with self-attentionSelf-attentionAttention in which the queries, keys and values all come from the same sequence.. Text comes pre-chopped into words and sub-words, so the move is natural there.

An image is different. A 224×224 photo is a grid of 50,176 pixels, each with three color values: about 150,000 numbers in total. There are no obvious “words” in it. You could treat each pixel as a token, but self-attention compares every token with every other token, so 50,176 tokens would mean about 2.5 billion pairwise scores per attention head, per layer. That is far too much.

This lesson is about the trick that made Transformers work for images anyway, the Vision TransformerVision Transformer (ViT)A Transformer that treats an image as a sequence of patch tokens., and why it now sits at the front of almost every model that can “see”, from CLIP to the vision-language chatbots you will meet in the next two lessons.

ANALOGY· A mosaic read tile by tile

Imagine describing a mosaic to a friend over the phone. You don’t read out every grain of colored glass. Instead you go tile by tile, left to right, top to bottom: “tile 1: blue sky; tile 2: blue sky with the edge of the sun; …”, and you say each tile’s number so your friend knows where it goes.

Each tile is a patch. Your short description of it is the patch embedding, and its number is the position embedding. Your friend, who listens to the whole list and works out what the picture shows, is the Transformer. Bigger tiles mean a shorter call but a blurrier picture. Smaller tiles capture detail, but the call takes much longer.

Before Transformers: a quick CNN recap

For about a decade, computer vision meant convolutional neural networks (CNNs). A CNN slides small learned filters, often 3×3 pixels, across the image. Early filters respond to edges and color blobs; deeper layers combine them into textures, parts and eventually whole objects. Pooling layers shrink the grid as you go, so each deep unit “sees” a larger region.

CNNs come with strong built-in assumptions, called an inductive biasInductive biasAssumptions built into a model's architecture, such as a CNN's locality and translation equivariance. Strong biases help with little data; weak ones need more data but can learn more general patterns.:

  • Locality: nearby pixels matter most, so each filter only looks at a small neighborhood.
  • Translation equivariance: a cat in the top-left corner should be detected by the same filter as a cat in the bottom-right, so one filter is reused everywhere.

These assumptions are excellent priors for natural images. They let CNNs learn from relatively little data. They are also a cage: a convolution can only relate two distant parts of an image after many layers have grown its receptive field.

The ViT recipe

In 2020, Dosovitskiy and colleagues at Google published An Image is Worth 16x16 Words. Their recipe is almost shockingly simple, and that simplicity is the point:

  1. Patchify. Cut the image into non-overlapping P×PP \times P patches. A 224×224 image with P=16P = 16 gives a 14×1414 \times 14 grid: 196 patches.
  2. Flatten. Each patch is 16×16×3=76816 \times 16 \times 3 = 768 numbers. Line them up into a vector.
  3. Linear patch embedding. Multiply every flattened patch by the same learned matrix to get a vector of the model’s width DD (768 for ViT-Base). This is the patch embeddingPatch embeddingThe first layer of a Vision Transformer: each P×P image patch is flattened into P·P·3 numbers and mapped by one shared linear layer to a vector of the model's width., the vision equivalent of looking up a word’s embeddingEmbeddingA learned vector representing a token, word, image or document, arranged so that similar meanings get nearby vectors..
  4. Prepend a [CLS] token. Add one extra learned vector at position 0, the [CLS] token[CLS] tokenA learned extra token placed at the start of a sequence. After the Transformer layers, its output vector serves as a summary of the whole input, e.g. for classification.. It is not from the image. It is a blank “summary slot” that, through attention, gathers information from all patches.
  5. Add position embeddings. Attention by itself has no idea of order, so each position (0 for [CLS], then 1 to 196) gets a learned vector added to it, exactly as in the lesson on positional encoding.
  6. Run a standard Transformer encoder. No causal mask: every patch can attend to every other patch.
  7. Classify. Take the output vector at the [CLS] position and feed it to a small classification head.

That’s it. There is no convolution anywhere except, if you like, the patch embedding itself (which is mathematically a convolution with kernel size and stride both equal to PP).

INTERACTIVEImage patchifier
Patch size P
Image224 × 224 × 3Grid14 × 14Patch tokens196+ [CLS] = sequence197Values per patch16·16·3 = 768Patch-embedding weights768×768 ≈ 0.59MAttention pairs per layer38,809
Patch row 3, col 9position index 37flattened length 768[, … ]
The same image as a sequence of 197 tokens (read left to right, top to bottom; position 0 is [CLS])

Hover or tap a patch (or focus the image and use the arrow keys). Each patch becomes one vector of P·P·3 numbers, then a learned linear layer maps it to 768 dimensions and adds a position embedding for its index. Halving P quadruples the token count, and attention cost grows with its square.

Change the patch size and watch the token count change. Hover or tap a patch (or focus the image and use arrow keys) to see its position index and flattened vector length. The strip below is what the Transformer actually receives: one long sequence.

Things to try:

  1. P = 16. The classic ViT-B/16 setting: 196 patch tokens plus [CLS] = 197. Each patch is a 768-long vector, and with D=768D = 768 the patch-embedding matrix has about 0.59 million weights.
  2. P = 8. The token count quadruples to 784, and attention pairs per layer jump from about 39,000 to about 616,000. Notice the flowers in the meadow: at this size they sit in their own patches.
  3. P = 56. Only 16 tokens. Cheap, but the house, tree and lake are mashed into a few big squares. Fine detail is now the patch embedding’s job, and a single linear layer can’t do much with it.
  4. Hover across a row. Position indices run left to right, then wrap to the next row, just like reading. The model is not told this 2D structure directly. With learned 1D position embeddings, it has to discover from data that patch 15 sits right below patch 1.

Why ViTs are data-hungry

Here is the catch the original paper was honest about. Trained on ImageNet alone (about 1.3 million images), ViTs did a little worse than comparably sized ResNets, a strong CNN family. Only when pretrained on much bigger datasets, ImageNet-21k (about 14 million images) or Google’s internal JFT-300M (about 300 million), did they match and then beat the best CNNs.

The reason is the inductive bias from earlier. A ViT doesn’t know that neighboring pixels are related or that a cat is a cat wherever it appears. It has to learn locality from examples. With little data, the CNN’s hard-coded assumptions win. With lots of data, the ViT’s flexibility wins: attention can connect the top-left corner with the bottom-right in the very first layer, and the model can learn patterns a convolution’s assumptions would never allow.

Patch size: the central trade-off

Every image model built on ViTs has to answer one question: how many tokens should an image cost? For an H×WH \times W image and patch size PP,

N=HP⋅WP.N = \frac{H}{P} \cdot \frac{W}{P}.

Halve PP and NN quadruples. Self-attention cost grows with N2N^2, so it rises 16-fold. The common choices are a compromise: 16×16 or 14×14 patches at 224 to 384 pixels, giving roughly 200 to 750 tokens.

Resolution matters for the same reason. Doubling the image side at a fixed patch size also quadruples NN. That is why reading small text in a screenshot is hard for vision models: at 224×224, a whole line of text may fall into a couple of patches.

A practical wrinkle: position embeddings are learned for a fixed grid, say 14×14. To run the model at a higher resolution, you get a bigger grid, and the usual fix is to interpolate the learned position embeddings to the new grid size and fine-tune briefly.

Modern variants

The plain ViT has been refined in many ways. A few that matter for the rest of this part:

  • CLIP and SigLIP encoders. Instead of training on class labels, these ViTs are trained to match images with their captions (next lesson). The resulting encoders, such as CLIP ViT-L/14 or SigLIP So400m/14, are the standard “eyes” bolted onto language models. The suffix gives the patch size: “/14” means 14×14 patches.
  • Dropping [CLS]. Many modern encoders skip the [CLS] token and simply average (pool) all patch outputs, or use an attention-pooling head. When a ViT feeds a language model, all patch outputs are usually kept, not just one summary vector.
  • 2D position encodings. Instead of a learned 1D list, some encoders use 2D rotary embeddings (a 2D version of RoPERotary position embedding (RoPE)Encodes position by rotating query and key vectors by angles proportional to their position, so attention depends on relative distance.), so the model knows each patch’s row and column and can handle grid sizes it never saw in training.
  • Dynamic resolution. Rather than squashing every image to 224×224, models such as Qwen2-VL process images at roughly their native size and aspect ratio, so a wide screenshot simply becomes a wide grid of patches. The Qwen2-VL paper calls this “naive dynamic resolution”, and it relies on 2D rotary position encoding. Its ViT then merges each 2×2 group of neighboring patch outputs into one token, so in that model one LLM token covers about 28×28 pixels. Details vary across versions, so check the specific model’s report.
  • Hierarchical and windowed ViTs. Designs such as Swin Transformer limit attention to local windows and merge patches in stages. That brings back some CNN-like locality and keeps cost manageable at high resolution.
MATH CORNER · optionalThe patch embedding, with numbers

Let the image be x∈RH×W×Cx \in \mathbb{R}^{H \times W \times C}. Reshape it into N=HW/P2N = HW/P^2 flattened patches xp(i)∈RP2Cx_p^{(i)} \in \mathbb{R}^{P^2 C}. The ViT input sequence is

z0=[ xcls;  xp(1)E;  xp(2)E;  … ;  xp(N)E ]+Epos,z_0 = \big[\, x_{\text{cls}};\; x_p^{(1)} E;\; x_p^{(2)} E;\; \dots;\; x_p^{(N)} E \,\big] + E_{\text{pos}},

with patch-embedding matrix E∈R(P2C)×DE \in \mathbb{R}^{(P^2 C) \times D}, a learned [CLS] vector xcls∈RDx_{\text{cls}} \in \mathbb{R}^{D} and position embeddings Epos∈R(N+1)×DE_{\text{pos}} \in \mathbb{R}^{(N+1) \times D}. After LL Transformer layers, the classifier reads zL0z_L^{0}, the output at position 0.

Worked example (tiny). Take a 4×4 grayscale image (C=1C = 1) and P=2P = 2. That makes N=(4/2)2=4N = (4/2)^2 = 4 patches of 2⋅2⋅1=42 \cdot 2 \cdot 1 = 4 numbers each. Say the top-left patch is

[1001]  →  xp(1)=[1,0,0,1].\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix} \;\to\; x_p^{(1)} = [1, 0, 0, 1].

With D=2D = 2 and

E=[10010110],xp(1)E=[1+0+0+1,  0+0+0+0]=[2,0].E = \begin{bmatrix} 1 & 0 \\ 0 & 1 \\ 0 & 1 \\ 1 & 0 \end{bmatrix}, \qquad x_p^{(1)} E = [1{+}0{+}0{+}1,\; 0{+}0{+}0{+}0] = [2, 0].

If the position embedding for position 1 is [0.1,−0.2][0.1, -0.2], the token entering the Transformer is [2.1,−0.2][2.1, -0.2]. Every patch uses the same EE; only the position embedding tells the model where the patch came from.

Counting at real scale:

settingpatches NNsequence N+1N{+}1values per patchattention scores per head per layer
224², P=32P{=}3249503,0722,500
224², P=16P{=}1619619776838,809
224², P=14P{=}1425625758866,049
336², P=14P{=}14576577588332,929

Going from ViT-B/16 at 224 to ViT-L/14 at 336 multiplies the attention-score count by about 8.6.

In code

The whole patchify-and-embed step is one strided convolution. Here is a minimal ViT front end in PyTorch:

import torch, torch.nn as nn

class PatchEmbed(nn.Module):
    def __init__(self, img=224, patch=16, chans=3, dim=768):
        super().__init__()
        self.n = (img // patch) ** 2                       # 196 patches
        # A conv with kernel = stride = patch is exactly "flatten each patch, multiply by E"
        self.proj = nn.Conv2d(chans, dim, kernel_size=patch, stride=patch)
        self.cls = nn.Parameter(torch.zeros(1, 1, dim))     # learned [CLS]
        self.pos = nn.Parameter(torch.zeros(1, self.n + 1, dim))  # learned positions

    def forward(self, x):                      # x: (B, 3, 224, 224)
        x = self.proj(x)                       # (B, 768, 14, 14)
        x = x.flatten(2).transpose(1, 2)       # (B, 196, 768): a sequence!
        cls = self.cls.expand(x.shape[0], -1, -1)
        x = torch.cat([cls, x], dim=1)         # (B, 197, 768)
        return x + self.pos

tokens = PatchEmbed()(torch.randn(2, 3, 224, 224))
print(tokens.shape)  # torch.Size([2, 197, 768]) → feed to a Transformer encoder

From here, the model is the same encoder stack you saw for text, without the causal mask.

COMMON MISCONCEPTIONS
  • “A ViT looks at pixels one at a time.” The smallest unit it sees is a whole patch, often 14×14 or 16×16 pixels. Detail inside a patch reaches the model only through the patch-embedding projection.
  • “Transformers are simply better than CNNs at vision.” It depends on data. With small datasets, CNNs’ built-in locality usually wins. ViTs pull ahead when pretrained on very large datasets, or with strong augmentation and distillation.
  • “The model knows the patches form a 2D grid.” With learned 1D position embeddings, it only gets an index and must learn the grid layout from data. 2D position schemes, such as 2D RoPE, give the structure explicitly.
  • “Smaller patches are always better.” They preserve detail, but token count grows with 1/P21/P^2 and attention cost with 1/P41/P^4. Real systems pick patch size, resolution and token merging together to fit a compute budget.

Check your understanding

0/5 answered
  1. Q1.A 384×384 image is split into 16×16 patches. How many patch tokens does the ViT see (excluding [CLS])?

  2. Q2.What does the patch-embedding layer do?

  3. Q3.Why did the original ViT underperform ResNets when trained only on ImageNet-1k?

  4. Q4.You halve the patch size from 16 to 8 at a fixed resolution. Roughly how does the self-attention score count per layer change?

  5. Q5.What is the [CLS] token in a ViT?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.