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.
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.
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:
- Patchify. Cut the image into non-overlapping patches. A 224×224 image with gives a grid: 196 patches.
- Flatten. Each patch is numbers. Line them up into a vector.
- Linear patch embedding. Multiply every flattened patch by the same learned matrix to get a vector of the model’s width (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..
- 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.
- 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.
- Run a standard Transformer encoder. No causal mask: every patch can attend to every other patch.
- 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 ).
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.
Things to try:
- P = 16. The classic ViT-B/16 setting: 196 patch tokens plus [CLS] = 197. Each patch is a 768-long vector, and with the patch-embedding matrix has about 0.59 million weights.
- 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.
- 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.
- 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 image and patch size ,
Halve and quadruples. Self-attention cost grows with , 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 . 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 . Reshape it into flattened patches . The ViT input sequence is
with patch-embedding matrix , a learned [CLS] vector and position embeddings . After Transformer layers, the classifier reads , the output at position 0.
Worked example (tiny). Take a 4×4 grayscale image () and . That makes patches of numbers each. Say the top-left patch is
With and
If the position embedding for position 1 is , the token entering the Transformer is . Every patch uses the same ; only the position embedding tells the model where the patch came from.
Counting at real scale:
| setting | patches | sequence | values per patch | attention scores per head per layer |
|---|---|---|---|---|
| 224², | 49 | 50 | 3,072 | 2,500 |
| 224², | 196 | 197 | 768 | 38,809 |
| 224², | 256 | 257 | 588 | 66,049 |
| 336², | 576 | 577 | 588 | 332,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.
- “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 and attention cost with . Real systems pick patch size, resolution and token merging together to fit a compute budget.
Check your understanding
Q1.A 384×384 image is split into 16×16 patches. How many patch tokens does the ViT see (excluding [CLS])?
Q2.What does the patch-embedding layer do?
Q3.Why did the original ViT underperform ResNets when trained only on ImageNet-1k?
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?
Q5.What is the [CLS] token in a ViT?
Further reading
- paperAn Image is Worth 16x16 Words: Transformers for Image Recognition at Scale — Dosovitskiy et al. (2020), the original ViT paper. Section 3 is the recipe; Section 4 the data-scale story.
- paperTraining data-efficient image transformers & distillation through attention (DeiT) — How to train ViTs on ImageNet alone, without a giant private dataset.
- paperMasked Autoencoders Are Scalable Vision Learners (MAE) — Self-supervised ViT pretraining by hiding 75% of patches.
- paperSwin Transformer: Hierarchical Vision Transformer using Shifted Windows — Local windows and patch merging for efficient high-resolution vision.
- paperQwen2-VL: Enhancing Vision-Language Model's Perception of the World at Any Resolution — Naive dynamic resolution and 2D/multimodal rotary position embeddings.