Vision Transformers & Vision–Language Models
Images as sequences of patches, and models that connect them to language.
Cut a photo into 196 squares, flatten each square into a vector, and hand the sequence to the same kind of transformer that reads sentences. That is a Vision Transformer, and from its very first layer every patch can draw on every other. Train one beside a text transformer so that pictures land next to their captions, and you get a model that sorts images into categories it was never trained on, and the visual front end of chatbots that answer questions about pictures.
What you’ll learn
- Build a Vision Transformer from patch embedding, class token, position embeddings and pre-norm encoder blocks, and count its tokens and parameters.
- Derive the cost of one ViT block, multiply–adds, and find the resolution at which attention's quadratic term takes over.
- Contrast what one ViT layer can mix with what a convolution can, and explain why ViTs lean on large datasets, strong regularization or self-supervised pretraining.
- Explain contrastive image–text pretraining (CLIP), and derive zero-shot classification as logistic regression whose weights the text encoder computes from class names.
- Describe how generative vision–language models feed images to a language model, through a projector (LLaVA) or gated cross-attention (Flamingo), and how they are trained.
From pixels to tokens
A transformer reads a sequence of vectors, so an image must first become one. The Vision Transformer (ViT; Dosovitskiy et al., 2021) cuts an image into a grid of non-overlapping patches, of them, flattens each patch into a vector of numbers, and maps every patch with the same matrix to a token of width . This is the patch embedding. Because the same map acts on every non-overlapping window, it is exactly a convolution whose kernel size and stride both equal , with output channels, and libraries implement it that way.
Two learned extras complete the input. A class token , borrowed from BERT's [CLS] token, goes in front; its state after the last layer will summarize the image. And because attention treats its inputs as an unordered set, every token gets a learned position embedding added, one vector per slot of the sequence (positional encoding).
From here on the model is an ordinary transformer encoder: identical pre-norm blocks, each a multi-head self-attention layer followed by a two-layer MLP with a GELU in between, both inside residual connections with layer normalization at the start of each branch (The Transformer Block takes the block apart). Every block keeps the shape . After the last block, the class token's state is normalized once more and sent to a classification head: an MLP with one hidden layer during pretraining, replaced by a single zero-initialized linear layer when the model is fine-tuned on a new task.
import torch
import torch.nn as nn
class ViT(nn.Module):
def __init__(self, img=224, P=16, C=3, D=768, depth=12, heads=12, classes=1000):
super().__init__()
N = (img // P) ** 2 # 196 patches
self.patchify = nn.Conv2d(C, D, kernel_size=P, stride=P) # one linear map per patch
self.cls = nn.Parameter(torch.zeros(1, 1, D)) # learnable class token
self.pos = nn.Parameter(0.02 * torch.randn(1, N + 1, D)) # learned position embeddings
block = nn.TransformerEncoderLayer(D, heads, dim_feedforward=4 * D, activation='gelu',
batch_first=True, norm_first=True)
self.encoder = nn.TransformerEncoder(block, depth, enable_nested_tensor=False)
self.norm, self.head = nn.LayerNorm(D), nn.Linear(D, classes)
def forward(self, x): # x: (B, 3, 224, 224)
z = self.patchify(x).flatten(2).transpose(1, 2) # (B, 196, D)
z = torch.cat([self.cls.expand(len(z), -1, -1), z], dim=1) # (B, 197, D)
z = self.encoder(z + self.pos)
return self.head(self.norm(z[:, 0])) # read out the class token
model = ViT()
print(sum(p.numel() for p in model.parameters())) # 86567656A ViT-B/16 assembled from PyTorch's built-in blocks, with a 1,000-class linear head: 86,567,656 parameters. norm_first=True selects the pre-norm block. Dosovitskiy et al. also tried classifying from the average of the patch tokens instead of a class token; it worked as well, once its learning rate was tuned separately.
ViT-H/14 cuts a image into -pixel patches. How many tokens does its encoder process, class token included?
- 197
- 256
- 3,137
- 257
Show the answer
D. 257
patches per side, so patch tokens, plus the class token: 257. Smaller patches mean more tokens for the same image, and every block's cost grows with them.
What a block costs
Where do 86 million parameters and the compute of a forward pass go? Count one block, with tokens (class token included) of width , writing MACs for multiply–adds.
Attention projects every token to a query, a key and a value, and projects the concatenated head outputs back to width : four matrices with biases, applied to every token.
The MLP widens each token to and back, and the two layer norms each hold a gain and a bias vector:
Attention itself has no parameters, but it compares every pair of tokens. With heads of size , the scores cost per head, in all, and the weighted sum of values the same again. Adding everything up:
The share of the quadratic term depends only on the ratio of tokens to width. For ViT-B/16 at 224 pixels (, ) it is about 4%. Twelve blocks of parameters make 85.1 million; the patch embedding, class token, position embeddings and head bring the total to 86.6 million, and a forward pass to about 17.6 billion MACs.
| Model | Blocks | Width | MLP width | Heads | Parameters |
|---|---|---|---|---|---|
| ViT-Base | 12 | 768 | 3,072 | 12 | 86 M |
| ViT-Large | 24 | 1,024 | 4,096 | 16 | 307 M |
| ViT-Huge | 32 | 1,280 | 5,120 | 16 | 632 M |
Keep ViT-B () and 16-pixel patches, but feed it ever larger square images. At what image side, in pixels, does the attention term equal everything else in a block? Ignore the class token.
Show the answer
1086 px
The share is one half when tokens, a grid of patches per side, so an image about pixels wide. At 384 pixels (577 tokens) attention is 11% of the work; at 2,048 pixels it is 78%. Resolution, not depth, is what makes attention expensive.
As in a CNN, no parameter depends on the image size. Unlike a CNN, compute grows faster than the number of pixels: linearly in through the projections and MLPs, quadratically through attention, and halving the patch size quadruples . Detection and segmentation want both high resolution and small patches, which is exactly where plain ViTs become expensive.
A global view from the first layer
A convolutional unit sees only its receptive field, which grows by a few pixels per layer. Before looking at what attention does differently, see how slowly that happens.
In a ViT any token may attend to any other, so a patch in the top-left corner can draw on one in the bottom-right in the first block. Do trained models use this? Dosovitskiy et al. measured each head's attention distance: the image distance between a query patch and the patches it attends to, averaged with the attention weights, the analogue of a receptive field's size. In the lowest blocks some heads already attend across most of the image while others stay close to the query patch, much like early convolutions; the local heads were less pronounced when a ResNet fed the transformer its features. With depth, the distance grows for every head.
The weights themselves differ in kind. A convolution applies the same kernel to the same relative positions in every image. An attention head computes its weights from the tokens, so one head can link the two ears of a cat in one image and the two wheels of a bicycle in the next. The widget below uses words instead of patches; in a ViT each word would be a patch.
Order enters only through the position embeddings. Self-attention, MLPs and layer norms treat the tokens as a set, so without them a ViT sees a bag of patches. In the authors' ablation, removing them lowered ViT-B/16's ImageNet 5-shot linear-probe accuracy from 64.2% to 61.4%, a clear gap, yet position embeddings built for 2-D grids, or relative ones, did no better than plain learned 1-D embeddings. The learned embeddings had come to encode the grid by themselves: neighboring patches ended up with similar embeddings, and so did patches in the same row or column.
Data, recipes and pretraining
That missing inductive bias has a price in data. Trained on ImageNet-1k's 1.3 million images without strong regularization, the original ViTs fell a few points short of ResNets of similar size; pretrained on ImageNet-21k (14 million images) or on the 300-million-image JFT-300M, they caught up and then pulled ahead (ConvNets vs Vision Transformers examines that experiment and what later work made of it). Three remedies made ViTs practical without JFT-scale labeled data:
- Augmentation, regularization and distillation. Steiner et al. (2022) found that strong augmentation and regularization, given enough compute, can stand in for an order of magnitude more data: ViTs trained on the public ImageNet-21k matched or beat counterparts trained on JFT-300M. DeiT (Touvron et al., 2021) trained a ViT-B-sized model to 81.8% top-1 on ImageNet-1k alone with a strong recipe, and to 83.4% with distillation from a CNN teacher through a second, distillation token.
- Self-supervised pretraining. Patches are already tokens, so hiding some of them is natural: a masked autoencoder masks 75% of the patches and reconstructs their pixels (Masked Modeling Across Modalities), and DINO trains a student ViT to match a moving-average teacher across crops of an image (Non-Contrastive & Self-Distillation Methods).
- Language supervision. The captions people write for their photos are free labels at web scale. The next step builds on them.
Think first A ViT-B/16 pretrained at is fine-tuned at . What has to change in the model, and what can stay as it is?
Every weight can stay: the patch embedding still sees patches, and the blocks accept any number of tokens. Only the position embeddings no longer fit, because the grid grows from to patches, 577 tokens instead of 197. Dosovitskiy et al. interpolated the learned embeddings in 2-D, according to their location in the image, and then fine-tuned. With about three times as many tokens, each image also costs about three times as much. Patches, Resolution & Token Efficiency follows this thread.
Images meet text: CLIP
A label set such as ImageNet's fixes 1,000 classes in advance. Captions on the web describe whatever people photograph. CLIP (Radford et al., 2021) learns from 400 million (image, text) pairs collected from the internet with two encoders, one for images (a ResNet or a ViT) and one for text (a transformer), each followed by a linear projection into a shared embedding space and normalized to unit length. For a batch of pairs it computes all cosine similarities between image and text , and trains both encoders so that every image picks out its own caption among the , and every caption its own image:
To sort images into classes the model was never trained on, write one caption per class, such as "a photo of a {label}.", embed it with the text encoder and normalize: . Score each class by its similarity to the image embedding and apply a softmax:
Written out, it is multinomial logistic regression: unit-norm image features as inputs, unit-norm weights, no bias, and logits scaled by a fixed temperature. The weight matrix is not fitted to labeled images: the text encoder generates it from the class names, which is why Radford et al. call it a hypernetwork.
Seen this way, every training batch was a small classification problem with one example per class and 32,768 classes described in language. Changing the classes at test time means writing new prompts, not retraining: that is zero-shot classification.
import torch
import torch.nn.functional as F
@torch.no_grad()
def zero_shot(image_encoder, text_encoder, tokenize, images, class_names, scale=100.0):
prompts = [f"a photo of a {c}." for c in class_names] # one caption per class
w = F.normalize(text_encoder(tokenize(prompts)), dim=-1) # (K, d): the classifier's weights
u = F.normalize(image_encoder(images), dim=-1) # (B, d)
return (scale * u @ w.T).softmax(dim=-1) # (B, K) class probabilities
def clip_loss(u, v, scale):
"""u, v: (N, d) unit image and text embeddings of N matching pairs."""
logits = scale * u @ v.T # (N, N); pair i on the diagonal
target = torch.arange(len(u))
return (F.cross_entropy(logits, target) + F.cross_entropy(logits.T, target)) / 2scale is . The class weights depend only on the class names, so they are computed once and reused for every image. Averaging the embeddings of many prompts per class ("a photo of a big {label}.", "a photo of a small {label}.", …) builds an ensemble that costs nothing extra per image.
Prompts matter. The template "A photo of a {label}." raised ImageNet zero-shot accuracy by 1.3 points over the bare class names, and averaging the embeddings of 80 prompts added another 3.5. The best CLIP model, a ViT-L/14 given one extra epoch of training at 336 pixels, reached 76.2% top-1 zero-shot on ImageNet, matching the original ResNet-50 without using any of its 1.28 million labeled training images; on natural distribution shifts its accuracy fell far less than that of ImageNet-trained models equally accurate on ImageNet. It was weak on specialized, complex or abstract tasks: counting objects in synthetic scenes, satellite images, tumor detection in lymph-node slides, traffic signs.
A CLIP model must sort photos into "otter", "beaver" and "muskrat", classes for which it has never seen a labeled example. How does it decide?
- It fine-tunes its image encoder on a few photos of each class first
- It generates a caption for the photo and searches it for one of the three names
- It compares the photo's embedding with the embeddings of a caption for each class and picks the most similar
- It uses the weights of an ImageNet classifier for those three classes
Show the answer
C. It compares the photo's embedding with the embeddings of a caption for each class and picks the most similar
The three captions, such as "a photo of a beaver.", become the rows of a linear classifier through the text encoder; the image embedding is scored against each and a softmax turns the scores into probabilities. No labeled photo and no gradient step is involved.
Vision–language models that write
CLIP can score how well a caption fits an image, but it cannot write one. Generative vision–language models, a family of multimodal models, put a pretrained vision encoder in front of a pretrained language model and train the connection, so that the language model generates text conditioned on the image. Two designs illustrate the main choice, where the image enters the language model.
Visual tokens in the input (LLaVA). Liu, Li, Wu & Lee (2023) take the grid of patch features from a CLIP ViT-L/14 and map each through a trainable matrix into the language model's word-embedding space, . These visual tokens sit in the input sequence beside the text, and the language model is trained by next-token prediction on the answers. Training has two stages. First only is trained, on 595,000 captioned images, with the vision encoder and the language model frozen: in the authors' words, a compatible visual tokenizer for the frozen language model. Then and the language model are fine-tuned together, the vision encoder still frozen, on 158,000 instruction-following examples (conversations, detailed descriptions and reasoning questions) that a text-only GPT-4 wrote from the captions and object boxes of images it never saw. The follow-up LLaVA-1.5 replaced by a two-layer MLP, used 336-pixel images ( visual tokens) and trained in about a day on one node of eight A100 GPUs.
Cross-attention into a frozen language model (Flamingo). Alayrac et al. (2022) froze both pretrained networks. A Perceiver Resampler, a small transformer whose learned latent queries cross-attend to the image features, turns any number of features into 64 visual tokens. Between the frozen language-model blocks, Flamingo adds new gated cross-attention layers through which the text tokens read those visual tokens. Each new layer's output is multiplied by with a learned scalar initialized to , so at the start the model computes exactly what the language model alone computed. Trained on 43 million web pages with interleaved images and text, plus image–text and video–text pairs, Flamingo learned new tasks from a few examples in its prompt, as language models do.
| Choice | LLaVA (2023) | Flamingo (2022) |
|---|---|---|
| Where the image enters | as tokens in the language model's input | through new cross-attention layers between its blocks |
| Visual tokens per image | one per patch: 256 at 224 pixels, 576 in LLaVA-1.5 | 64, from the Perceiver Resampler |
| Trained | the projection, then projection and language model | resampler and cross-attention layers; both pretrained networks frozen |
| Data | captioned images, then GPT-4-written instructions | interleaved web pages, image–text and video–text pairs |
Such a model can be asked anything that can be phrased in text about an image: describe it, answer a question about it, read the text in it, compare two images, follow an instruction that refers to its content. The language model's habits can also override the pixels. Li, Du, Zhou et al. (2023) found that large vision–language models frequently mention objects that are not in the image, and that the objects most prone to this object hallucination are those that often co-occur with what is there, or appear often in the instruction data.
Key takeaways
- A ViT turns an image into patch tokens with one shared linear map (a stride- convolution), prepends a class token, adds learned position embeddings and runs a standard pre-norm transformer encoder; ViT-B/16 at 224 pixels processes 197 tokens of width 768 with 86 million parameters.
- A block has parameters and costs multiply–adds; attention's share is about 4% for ViT-B/16 at 224 pixels and reaches one half near 1,086 pixels.
- Every token can attend to every other from the first layer, with weights computed from content; locality, translation equivariance and the 2-D layout must be learned, so ViTs lean on large datasets, strong augmentation and distillation, or self-supervised pretraining.
- CLIP trains an image and a text encoder with a symmetric contrastive loss on 400 million pairs; zero-shot classification is a linear classifier whose unit-norm weights are text embeddings of prompts, and it reached 76.2% on ImageNet without its labels.
- Generative vision–language models feed visual tokens to a language model, either in its input through a projection (LLaVA) or through gated cross-attention layers in a frozen model (Flamingo); they first align, then learn from instruction or interleaved data, and can describe objects that are not there.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Which PyTorch layer computes the patch embedding of ViT-B/16 exactly?
nn.Conv2d(3, 768, kernel_size=3, stride=1, padding=1)nn.MaxPool2d(16)followed bynn.Linear(3, 768)nn.Conv2d(3, 768, kernel_size=16, stride=16)nn.Linear(224 * 224 * 3, 768)applied to the whole flattened image
Show the answer
C. nn.Conv2d(3, 768, kernel_size=16, stride=16)
The same linear map is applied to every non-overlapping patch, which is a convolution whose kernel size equals its stride. It produces a grid of 768-dimensional tokens.
You double the side of the input image (224 → 448 pixels) of a ViT with fixed 16-pixel patches. By what factors do the projection-and-MLP cost and the attention cost of a block grow?
- By 4 and by 16
- By 2 and by 4
- Both by 4
- Both by 16
Show the answer
A. By 4 and by 16
Doubling the side quadruples the number of patches . The projections and MLP cost , linear in ; the attention scores and weighted sums cost , quadratic in .
In CLIP's zero-shot classification of an image into classes, what plays the role of the classifier's weight vectors?
- The average image embedding of a few labeled photos per class
- The weights of a linear layer trained on ImageNet
- The rows of the patch-embedding matrix
- The normalized text embeddings of one prompt per class, such as "a photo of a {label}."
Show the answer
D. The normalized text embeddings of one prompt per class, such as "a photo of a {label}."
The logits are with the unit text embedding of class 's prompt: logistic regression whose weights the text encoder generates from class names, with no labeled images.
In LLaVA's first training stage, on captioned images, which parameters are updated?
- All of them: vision encoder, projection and language model
- Only the projection that maps image features to word embeddings
- Only the vision encoder
- Only the language model
Show the answer
B. Only the projection that maps image features to word embeddings
With both pretrained networks frozen, the first stage only aligns the image features with the language model's embedding space, training a visual tokenizer for it. The second stage fine-tunes the projection and the language model on instruction data; the vision encoder stays frozen throughout.
Flamingo multiplies the output of every new cross-attention layer by , with learned and initialized to . Why?
- To keep the attention weights sparse
- To normalize the scale of the image features
- So that at initialization the model computes exactly what the frozen language model did, which keeps training stable
- To stop text tokens from seeing images that come later in the sequence
Show the answer
C. So that at initialization the model computes exactly what the frozen language model did, which keeps training stable
With the new layers add nothing at first, so the pretrained language model starts intact; the gates open gradually as is learned. Alayrac et al. report better stability and final performance this way.
Go deeper
- Hierarchical Vision Transformers · Shifted windows, multiscale features and dense prediction with transformers.
- What Vision Transformers Attend To · Attention maps, high-norm artifact tokens and registers.
- Patches, Resolution & Token Efficiency · Flexible patch sizes, native-resolution packing and merging tokens.
Further reading
- A. Dosovitskiy et al., "An image is worth 16x16 words: Transformers for image recognition at scale," ICLR (2021).
- A. Radford et al., "Learning transferable visual models from natural language supervision," ICML (2021).
- H. Liu, C. Li, Q. Wu & Y. J. Lee, "Visual instruction tuning," NeurIPS (2023).
- J.-B. Alayrac et al., "Flamingo: a visual language model for few-shot learning," NeurIPS (2022).