Vision Transformer (ViT)
An Image is Worth 16x16 Words
Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner,
7
Concepts
5
Formulas
7
Demos
Paper Overview
Vision Transformer (ViT) demonstrated that a pure Transformer architecture, applied directly to sequences of image patches, can match or exceed state-of-the-art CNNs on image classification -- without any convolutions. The key insight is that an image can be treated as a sequence of flattened 2D patches, analogous to tokens (words) in NLP.
The architecture is remarkably simple: split a 224×224×3 image into a grid of 16×16 patches, producing N=196 patches. Each patch is flattened to a 768-dimensional vector and linearly projected to the model dimension D. A learnable [CLS] token is prepended (making 197 tokens total), learnable 1D position embeddings are added, and the entire sequence is fed to a standard Transformer encoder with multi-head self-attention and MLP blocks. The [CLS] token's output representation is passed through a classification head.
The critical finding: ViT's performance depends heavily on pre-training data scale. Trained only on ImageNet-1K (1.2M images), ViT-B/16 achieves just 77.9% top-1 -- below ResNet-152's 78.3%. But pre-trained on JFT-300M (300M images), ViT-L/16 reaches 87.8% top-1 on ImageNet, surpassing the best CNNs while using 4x fewer FLOPs to train. ViT-H/14 pre-trained on JFT-300M achieves 88.6% top-1, setting a new state-of-the-art. This revealed a fundamental tradeoff: Transformers lack the inductive biases of CNNs (locality, translation equivariance) but compensate with superior scalability when sufficient data is available.
Chapter Roadmap
Click any topic to jump in
Patch Embeddings
16×16 patches flattened and linearly projected — equivalent to one stride-16 convolution.
Position Embeddings
Learnable per-patch vectors added to embeddings — recover 2D spatial topology from scratch via gradient descent.
[CLS] Token for Classification
A learnable global-reader token aggregates information from all patches — adaptive pooling via attention weights.
Global Attention vs Local Convolutions
Global receptive field from layer 1 — but quadratic cost and no translation bias means more data is needed.
Pre-training at Scale
ViT underperforms CNNs on small datasets but overtakes them beyond ~100M images — lower bias, higher variance.
ViT Variants: DeiT, BEiT, MAE
Distillation (DeiT) and masked reconstruction (BEiT/MAE) make ViT work without massive labeled datasets.
Attention Map Visualization
Attention rollout reveals that ViT discovers object boundaries without segmentation supervision.
Concept by concept
7 sections, in reading order.
Images are split into non-overlapping patches, which are then linearly projected to create token embeddings -- treating each patch as a 'visual word' in a sequence. This is the mechanism that bridges the gap between 2D images and the 1D sequence input that Transformers expect.
The Problem
Transformers were designed for 1D sequences (text), and naively applying self-attention to raw pixels is computationally impossible:
- Self-attention has O(N2) complexity where N is the sequence length.
- A 224×224 image has N=50,176 pixels. Self-attention would require computing and storing a 50,176×50,176 attention matrix -- that is 2.5 billion entries, requiring ~10 GB of memory just for the attention weights of a single layer, single head.
- Even with optimizations, this quadratic scaling makes pixel-level attention infeasible for standard image resolutions.
- Previous works (Image GPT, Stand-Alone Self-Attention) tried to apply attention to pixels but were limited to tiny resolutions (e.g., 64x64) or small local windows, losing the global context that makes Transformers powerful.
- The challenge: reduce the sequence length dramatically while preserving enough spatial information for accurate classification.
The Solution
Patch Embedding converts a 2D image into a manageable 1D sequence by treating non-overlapping image regions as tokens:
Step-by-step for a standard 224×224×3 input with patch size P=16:
-
Split into patches: Divide the image into a grid of 16224×16224=14×14=196 non-overlapping patches. Each patch is 16×16×3 pixels.
-
Flatten each patch: Reshape each 16×16×3 patch into a vector of dimension P2⋅C=162×3=768.
-
Linear projection: Multiply each 768-dim vector by a learnable projection matrix E∈R768×D to get the token embedding. For ViT-Base, D=768, so E is 768×768 (589K parameters). For ViT-Large, D=1024, so E is 768×1024 (786K parameters).
-
Result: A sequence of 196 token embeddings, each of dimension D. The sequence length is now 256x smaller than the pixel count (196 vs 50,176).
Implementation detail: The linear projection is equivalent to a 2D convolution with kernel size = stride = P. In practice, ViT uses nn.Conv2d(3, D, kernel_size=16, stride=16) which produces a 14×14×D feature map, then reshapes to 196×D.
Patch size is the critical tradeoff:
| Patch Size | Tokens | Token Dim | Attention Cost | Detail |
|---|---|---|---|---|
| 32x32 | 49 | 3072 | Low | Coarse |
| 16x16 | 196 | 768 | Medium | Standard |
| 14x14 | 256 | 588 | Higher | Fine |
| 8x8 | 784 | 192 | Very High | Very Fine |
Smaller patches capture finer spatial detail but increase the sequence length quadratically, making attention much more expensive. ViT-B/16 (patch size 16) and ViT-L/16 are the standard configurations. ViT-H/14 uses patch size 14 for slightly finer resolution at higher compute cost.
Key Points
- 1
Patch size P is the most important hyperparameter: it determines both sequence length (N=(H/P)2) and computational cost (O(N2) attention)
- 2
For 224×224 with P=16: each patch is 16×16×3=768 values, projected to model dimension D via a learnable linear layer
- 3
The projection is implemented as Conv2d(3, D, kernel_size=P, stride=P) -- mathematically equivalent to flatten + linear, but more efficient on GPU
- 4
Sequence length reduces from 50,176 (pixels) to 196 (patches) -- a 256x reduction that makes self-attention tractable
- 5
Unlike CNNs, patches have no overlap and no hierarchy -- all spatial information mixing happens through self-attention across the full sequence
- 6
Patch embedding has only P2⋅C⋅D=768×768=590K parameters for ViT-Base -- a tiny fraction of the model's total 86M parameters
Mathematical Formulation
Patch Embedding
z0=[xclass; xp1E; xp2E; ⋯; xpNE]+Epos
x_p^i is the flattened i-th patch (dim P²C), E is the projection matrix (dim P²C × D), x_class is the prepended [CLS] token, and E_pos are the position embeddings. This produces the full input sequence of N+1 tokens, each of dimension D.
Number of Patches
N=P2H×W=(PH)2
For 224x224 with P=16: N = 196. For 224x224 with P=14: N = 256. For 384x384 with P=16: N = 576 (used during fine-tuning at higher resolution).
Mathematical Intuition
A 224×224 image is cut into 16×16 patches, giving N=(224/16)2=196 tokens. Each patch xp∈R16⋅16⋅3 is flattened and linearly projected: zp=Exp with E∈Rd×768. This is mathematically equivalent to a single stride-16 conv with 768 input channels — so ViT's 'first layer' is a CNN layer in disguise, just with no spatial overlap.
Since Transformers have no inherent notion of spatial order (self-attention is permutation-equivariant), position embeddings are added to patch tokens to encode where each patch came from in the original image. Without them, the model cannot distinguish an image from a random shuffle of its patches.
The Problem
Self-attention computes: Attn(Q,K,V)=softmax(QKT/d)V
This operation is permutation-equivariant: if you permute the input tokens, the output tokens are permuted in exactly the same way. Mathematically: Attn(ΠQ,ΠK,ΠV)=Π⋅Attn(Q,K,V)
where Π is any permutation matrix. This means:
- Shuffling all 196 patches randomly would produce the same set of output representations (just reordered) -- the model literally cannot tell which patch was top-left vs bottom-right.
- Spatial relationships (adjacency, relative position, global location) are completely invisible to the Transformer.
- An image of a face with eyes swapped to the chin area would be processed identically to the normal face, unless position information is injected.
- In NLP, this same problem exists and is solved with position embeddings. For vision, the 2D spatial structure makes the problem even more acute since patches have both row and column coordinates.
The Solution
Learned 1D Position Embeddings are added element-wise to patch embeddings before the Transformer encoder:
z0i=xpiE+eposifor i=0,1,…,N
where eposi∈RD is a learnable vector for position i (including position 0 for the [CLS] token).
Key design decisions and findings:
-
1D vs 2D position embeddings: The paper tested both. 1D: a single index i∈{0,1,…,196} with raster-scan order. 2D: separate row and column embeddings (r,c) concatenated. Result: no significant difference (<0.1% accuracy). The model learns the 2D grid structure from 1D positions on its own.
-
Learned vs sinusoidal: Original Transformer (Vaswani et al.) used fixed sinusoidal encodings. ViT uses fully learned embeddings. Result: no significant difference for ViT. Both work equally well, likely because the fixed patch grid is simpler than variable-length text.
-
What the learned embeddings look like: After training, the position embedding similarity matrix reveals clear 2D spatial structure. Position i has high cosine similarity with positions in the same row and column, and similarity falls off with spatial distance. The model recovers the 2D grid purely from data.
-
Parameter count: For ViT-Base with 196 + 1 = 197 positions and D=768: the position embedding table has 197×768=151,296 parameters -- negligible compared to the 86M total.
Resolution transfer and position embedding interpolation:
ViT is pre-trained at 224×224 (196 patches) but often fine-tuned at higher resolution (e.g., 384×384, giving 576 patches). Since the learned position embeddings are for 196 positions, they must be interpolated to 576 positions using 2D bicubic interpolation: the 14×14 position embedding grid is upsampled to 24×24. This works well because the learned embeddings encode smooth spatial functions.
Key Points
- 1
Position embeddings are fully learnable parameters (Epos∈R(N+1)×D), trained end-to-end with the rest of the model
- 2
Added element-wise (not concatenated) to patch embeddings, so they share the same dimension D and do not increase sequence width
- 3
1D sequential indexing (raster scan) performs equally to explicit 2D (row, col) encoding -- the model discovers 2D structure from data alone
- 4
After training, cosine similarity between position embeddings reveals a clear 2D grid pattern: nearby positions are similar, distant positions are dissimilar
- 5
For higher-resolution fine-tuning (e.g., 224 to 384), the 14×14 position grid is bicubically interpolated to 24×24 -- this transfer works because the spatial function is smooth
- 6
Total parameter cost: (N+1)×D=197×768=151K for ViT-Base -- less than 0.2% of total model parameters
Mathematical Formulation
Input Embedding with Positions
z0=[xclass; xp1E; ⋯; xpNE]+Epos
E_pos ∈ R^((N+1) × D) is broadcast-added to the (N+1) × D token matrix. Position 0 is for [CLS], positions 1-N follow raster-scan order across the 14x14 patch grid.
Mathematical Intuition
Self-attention is permutation-invariant: Attn(πZ)=πAttn(Z), so without positional information the model cannot distinguish 'cat on dog' from 'dog on cat'. ViT adds learnable pi∈Rd to each token: zi←zi+pi. Interestingly, after training, cossim(pi,pj) recovers the 2D grid structure — the model rediscovers 'this patch is to the left of that one' from scratch.
A special learnable [CLS] token is prepended to the patch sequence, serving as a global aggregation point. Through self-attention across all Transformer layers, it collects information from every patch and its final representation is used as the image-level feature for classification.
The Problem
After the Transformer encoder processes the sequence, we have N+1 output token representations (one per patch plus [CLS]). We need to reduce these to a single vector for classification. Several approaches exist:
- Global average pooling (GAP) over all N patch tokens: y=N1∑i=1NzLi. Simple but treats all patches equally -- background patches contribute as much as object patches.
- Use a specific patch token: Arbitrary and biased toward that spatial location.
- Learnable aggregation token ([CLS]): A dedicated token that learns to aggregate task-relevant information from all patches through attention.
ViT follows BERT's approach from NLP, where a [CLS] token at position 0 serves as the sequence-level representation. This design choice was made to stay as close to the standard NLP Transformer as possible, validating that the same architecture transfers to vision with minimal modification.
Interestingly, the paper found that GAP works comparably to [CLS] when combined with appropriate learning rate tuning. The choice of [CLS] is primarily about architectural consistency with NLP Transformers rather than a clear accuracy advantage.
The Solution
The [CLS] token mechanism:
-
Initialization: A learnable vector xclass∈RD is initialized randomly (typically from N(0,0.02)). For ViT-Base, this is a single 768-dimensional vector -- just 768 parameters.
-
Prepending: It becomes position 0 in the input sequence: z0=[xclass; xp1E; ⋯; xpNE]+Epos
-
Attention-based aggregation: Over L Transformer layers, [CLS] participates in self-attention with all 196 patch tokens. At each layer, it can attend to any patch and any patch can attend to it. After 12 layers (ViT-Base), [CLS] has been iteratively refined by aggregating information from the entire image.
-
Classification head: The final [CLS] output zL0 is fed through an MLP head:
- During pre-training: MLP(zL0) with one hidden layer and tanh activation
- During fine-tuning: a single linear layer WzL0+b mapping D→K classes
-
Only [CLS] is used: The 196 patch output tokens are discarded for classification (though they are useful for other tasks like detection or segmentation).
How [CLS] learns to aggregate: In early layers, [CLS] attends broadly to many patches, building a coarse global representation. In later layers, attention becomes more focused on discriminative regions (e.g., the subject of the image). This progressive refinement is analogous to how CNN features go from edges to textures to object parts across layers.
Key Points
- 1
[CLS] is a single learnable vector (D=768 for ViT-Base) -- it contains no image information at initialization and must learn everything through attention
- 2
Over L=12 Transformer layers, [CLS] iteratively refines its representation by attending to all 196 patches, building a global image summary
- 3
The paper showed GAP over patch tokens works comparably to [CLS] when learning rates are adjusted, but [CLS] was chosen for consistency with the BERT/NLP Transformer design
- 4
During pre-training, the classification head is an MLP with one hidden layer (dim D) and tanh activation; during fine-tuning, it is replaced by a single linear layer
- 5
For downstream tasks beyond classification (detection, segmentation), the patch token outputs zL1:N are used instead of or alongside [CLS]
- 6
The [CLS] position embedding (position 0) is distinct from patch positions (1-196), allowing the model to treat the aggregation token differently from spatial tokens
Mathematical Intuition
A learnable token zcls∈Rd is prepended to the sequence. Because attention is all-to-all, it can read every patch: zcls(L)=∑iαivi where α is the learned attention distribution. The classifier then acts on zcls(L) only — a learned, content-adaptive global pooling instead of fixed mean pooling.
ViT's self-attention mechanism provides a global receptive field from the very first layer -- every patch can attend to every other patch immediately. This is fundamentally different from CNNs, where receptive fields grow gradually through layer stacking, and has profound implications for what inductive biases the architecture encodes.
The Problem
CNNs encode two strong inductive biases that constrain how they process spatial information:
1. Locality: A 3x3 convolution kernel only sees a 3×3=9 pixel neighborhood. To get a receptive field of r pixels, you need roughly r/2 layers of 3x3 convolutions. For a 224x224 image, global context requires ~112 layers -- far deeper than most practical networks.
2. Translation equivariance: The same filter is applied at every spatial position (weight sharing). A cat detector learned in the top-left works identically in the bottom-right. This is a powerful bias for natural images but also a constraint.
Practical consequences:
- In ResNet-50, the effective receptive field at conv5 is roughly 128x128 pixels -- still not global for 224x224 inputs. Information from opposite corners never directly interacts until the global average pooling at the very end.
- Long-range dependencies (e.g., matching a face to body pose) require the gradient signal to propagate through many layers, making these relationships harder to learn.
- The hierarchical feature pyramid (low-level → high-level) is encoded in the architecture itself: early layers MUST be local because the kernel size constrains them.
The Solution
ViT self-attention is global from layer 1:
At every Transformer layer, the self-attention computation is: Attention(Q,K,V)=softmax(dkQKT)V
where Q,K,V∈R(N+1)×dk are the query, key, and value projections of all N+1 tokens. The attention matrix A=softmax(QKT/dk)∈R(N+1)×(N+1) has entries for every pair of tokens -- patch 1 in the top-left can directly attend to patch 196 in the bottom-right.
What ViT gains from global attention:
- Immediate long-range dependencies: A patch containing an eye can directly reference a patch containing a nose in the first layer, without needing dozens of intermediate layers.
- Flexible receptive field: Each attention head can learn its own pattern -- some heads attend locally (mimicking convolutions), others attend globally, and patterns change across layers.
- No feature hierarchy constraint: All layers operate at the same resolution (N+1 tokens of dimension D), so high-level reasoning can happen at any layer.
What ViT loses (the inductive bias gap):
- No locality bias: ViT must learn from data that nearby patches are more related than distant ones. CNNs get this for free from kernel locality.
- No translation equivariance: A feature learned at one position is not automatically applicable at another. ViT must learn shift invariance from data augmentation and diverse training examples.
- No built-in hierarchy: CNNs progressively reduce resolution and increase channels, creating an automatic multi-scale representation. ViT processes all tokens at the same resolution.
- Quadratic cost: Attention is O(N2D) vs convolution's O(Nk2D). For N=196 and k=3, attention is 196/9≈22× more expensive per layer.
The key tradeoff: CNNs use architectural bias to compensate for limited data. ViT uses massive data to compensate for missing architectural bias. Above ~100M training images, ViT's flexibility becomes an advantage; below that, CNN's inductive biases win.
Key Points
- 1
ViT: O(N2) global attention from the first layer. Every patch attends to every other patch, creating a fully connected graph at every layer
- 2
CNN: O(k2) local connectivity per layer. Effective receptive field of ResNet-50 at conv5 is ~128x128 -- not truly global for 224x224 inputs
- 3
ViT lacks inductive biases (locality, translation equivariance, hierarchy) that CNNs hardcode -- it must learn these properties from data
- 4
With sufficient data (100M+ images), ViT's flexibility outperforms CNN's hardcoded biases. With limited data (<10M), CNN's inductive biases give it the advantage
- 5
Analysis shows early ViT layers learn some heads with local attention (CNN-like) and others with global attention -- the model discovers that locality is useful but does not enforce it
- 6
The quadratic attention cost (O(N2)) is the main computational limitation, driving research into efficient variants (Swin Transformer, PVT, etc.)
Mathematical Intuition
A conv layer has receptive field k×k (local); self-attention has N (global) from layer 1. But this costs O(N2d) memory vs O(k2Nd) for convs. The tradeoff: ViT can model pixel-(0,0) → pixel-(223,223) in one step, but needs ∼100× more data to avoid overfitting because it lacks the translation-equivariance inductive bias of CNNs.
Comparison
Before / Traditional
CNN (e.g., ResNet-50):
- Local 3x3 kernels, receptive field grows gradually
- Full translation equivariance via weight sharing
- Strong inductive bias: locality + hierarchy built into architecture
- Works well with 1M+ images (ImageNet scale)
- Effective receptive field at final conv: ~128x128 pixels
- Hierarchical: 56x56 → 28x28 → 14x14 → 7x7
After / This Paper
ViT (e.g., ViT-B/16):
- Global attention from layer 1: all 196 patches interact
- No translation equivariance (must learn from data)
- Minimal inductive bias: only patch extraction imposes locality
- Needs 100M+ images to match CNNs; exceeds them at 300M+
- Full global receptive field at EVERY layer
- Flat: 196 tokens at every layer (no resolution pyramid)
ViT's performance is strongly correlated with pre-training dataset size in a way that CNNs are not. This section explores why ViT needs large-scale pre-training, the specific data-accuracy relationship, and the computational economics that make ViT attractive despite its data hunger.
The Problem
ViT has almost no built-in inductive biases for vision:
- No locality: Self-attention connects all patches globally. The model must learn that spatially adjacent patches tend to be semantically related -- a fact CNNs encode for free via local kernels.
- No translation equivariance: A filter that detects a horizontal edge at position (3, 5) does not automatically detect it at (10, 15). ViT must see the same pattern at many positions during training to generalize.
- No hierarchical processing: CNNs create multi-scale features (edges → textures → parts → objects) through their progressive downsampling architecture. ViT processes all 196 tokens at the same resolution, requiring it to learn multi-scale representation internally.
The consequence is dramatic on small datasets:
- On ImageNet-1K alone (1.2M images), ViT-B/16 achieves 77.9% top-1 -- significantly below ResNet-152 (78.3%) and BiT-L (ResNet-based, 87.5% with ImageNet-21K pre-training).
- On CIFAR-10/100 trained from scratch, ViT massively overfits and underperforms simple CNNs.
- The model has the capacity to learn but lacks the structural constraints that help small-data learning.
The Solution
Pre-training at scale provides ViT with the diverse examples needed to learn inductive biases from data:
Data scaling results (ViT-B/16 fine-tuned on ImageNet):
| Pre-training Dataset | Images | ViT-B/16 Top-1 | BiT-L (ResNet) Top-1 |
|---|---|---|---|
| ImageNet-1K | 1.2M | 77.9% | 76.8% |
| ImageNet-21K | 14M | 83.6% | 84.7% |
| JFT-300M | 303M | 88.5% | 87.5% |
The crossover point: At ~30M pre-training images, ViT and BiT (ResNet) perform similarly. Below 30M, BiT wins. Above 30M, ViT pulls ahead and the gap widens with more data.
ViT model configurations and their results on ImageNet (pre-trained on JFT-300M):
| Model | Layers | Heads | Hidden D | MLP D | Params | Top-1 |
|---|---|---|---|---|---|---|
| ViT-B/16 | 12 | 12 | 768 | 3072 | 86M | 84.2% |
| ViT-L/16 | 24 | 16 | 1024 | 4096 | 307M | 87.8% |
| ViT-H/14 | 32 | 16 | 1280 | 5120 | 632M | 88.6% |
Why large-scale pre-training works for ViT:
- Spatial relationships learned empirically: With 300M diverse images, the model sees enough examples to learn that adjacent patches are usually related, even without a locality bias.
- Translation invariance from augmentation: Heavy data augmentation (random crops, flips) plus massive data diversity ensures the model sees patterns at all positions.
- Multi-scale features emerge: Analysis of attention patterns shows that lower layers develop local attention (texture-level) while upper layers develop global attention (object-level) -- the hierarchy emerges without being architecturally imposed.
Computational economics (the key practical argument):
- ViT-L/16 pre-trained on JFT-300M requires ~2,500 TPUv3 core-days.
- BiT-L (ResNet-152x4) pre-trained on JFT-300M requires ~9,900 TPUv3 core-days.
- ViT achieves better accuracy with ~4x less compute at the largest scale. The Transformer's efficiency advantage grows with model size.
Transfer learning protocol:
- Pre-train on large dataset (JFT-300M or ImageNet-21K) at 224×224
- Remove pre-training classification head
- Add new linear head for target task
- Fine-tune at higher resolution (384×384 or 512×512) with interpolated position embeddings
- Use lower learning rate for fine-tuning (typically 10−4 to 3×10−5)
Key Points
- 1
Below ~30M pre-training images, CNNs outperform ViT due to their inductive biases filling in for missing data diversity
- 2
At 300M images (JFT-300M), ViT-H/14 achieves 88.6% ImageNet top-1, surpassing the best CNNs while using ~4x fewer TPU core-days to pre-train
- 3
Three ViT scales: ViT-B/16 (86M params, 12 layers), ViT-L/16 (307M params, 24 layers), ViT-H/14 (632M params, 32 layers) -- larger models benefit more from larger datasets
- 4
Pre-training teaches the missing inductive biases: spatial locality, multi-scale features, and approximate translation invariance all emerge from sufficient data
- 5
Fine-tuning protocol: replace classification head, increase resolution (224 to 384), interpolate position embeddings bicubically, use low learning rate
- 6
ViT's compute efficiency improves with scale: at the largest model sizes, Transformers train faster than equivalent-accuracy CNNs because self-attention parallelizes better than convolution stacks
Mathematical Intuition
On ImageNet-1k (1.3M images), ResNets beat ViT. On JFT-300M (300× larger), ViT overtakes. The crossover happens because convs' inductive bias is a regularizer — useful when data is scarce but a ceiling when data is plentiful. Formally, ViT has lower bias (can express any function over patches) but higher variance, and variance only pays off with enough samples.
Comparison
Before / Traditional
CNN Scaling Behavior (BiT-L / ResNet-152x4):
- 87.5% top-1 on ImageNet with JFT-300M pre-training
- Strong performance even with ImageNet-21K (84.7%)
- Diminishing returns from more data beyond ~100M
- 9,900 TPUv3 core-days for JFT pre-training
- Inductive biases provide a "head start" with less data
After / This Paper
ViT Scaling Behavior (ViT-H/14):
- 88.6% top-1 on ImageNet with JFT-300M (+1.1% over BiT)
- Struggles with ImageNet-1K alone (77.9%)
- Performance keeps improving with more data (no plateau seen)
- 2,500 TPUv3 core-days for JFT pre-training (4x cheaper!)
- Flexibility becomes advantage when data compensates for missing biases
Follow-up works addressed ViT's biggest weakness -- its dependence on massive proprietary datasets -- through better training recipes (DeiT), self-supervised masked prediction (BEiT), and masked autoencoders (MAE). These variants made high-performance vision transformers accessible to researchers without access to JFT-300M.
The Problem
Original ViT had a critical practical limitation:
- JFT-300M is proprietary to Google and not publicly available. Without it, ViT-B/16 achieves only 77.9% on ImageNet -- below ResNets.
- Training cost: Even if the data were available, pre-training ViT-H/14 on 300M images requires 2,500 TPUv3 core-days (~$50K+ in cloud compute).
- Research accessibility: Most academic labs have access to ImageNet-1K (1.2M images) and limited compute budgets. ViT's results were impressive but unreproducible for most of the community.
- The fundamental question: Is ViT's advantage inherent to the Transformer architecture, or is it just about having more data than others? Can we make Transformers work with publicly available data?
The Solution
Three landmark follow-up papers solved the data efficiency problem from different angles:
DeiT (Data-efficient Image Transformer, Touvron et al., 2021):
Training ViT effectively on ImageNet-1K alone through better training recipes:
- Knowledge distillation: A pre-trained CNN (RegNetY-16GF) serves as a "teacher." A special distillation token (like [CLS]) is added to the sequence, trained to match the teacher's output via hard-label distillation.
- Heavy augmentation: RandAugment, MixUp (α=0.8), CutMix (α=1.0), random erasing, color jitter.
- Regularization: Stochastic depth (drop path rate 0.1), repeated augmentation, label smoothing (ϵ=0.1).
- Results: DeiT-B achieves 83.1% top-1 on ImageNet-1K with NO external data. DeiT-B distilled reaches 84.2% -- approaching ViT-B/16 pre-trained on ImageNet-21K (83.6%).
BEiT (BERT Pre-training for Image Transformers, Bao et al., 2022):
Self-supervised pre-training via masked image modeling:
- Tokenization: A discrete VAE (dVAE) tokenizes each image into a grid of visual tokens (vocabulary size 8192).
- Masking: Randomly mask 40% of patches in the input.
- Prediction: The Transformer predicts the dVAE token ID for each masked patch (classification over 8192-class vocabulary).
- Key insight: Predicting discrete tokens is more stable than predicting raw pixels because it captures semantic structure rather than low-level statistics.
- Results: BEiT-L achieves 88.6% top-1 after self-supervised pre-training on ImageNet-21K + fine-tuning on ImageNet-1K.
MAE (Masked Autoencoders, He et al., 2022):
Extremely efficient self-supervised pre-training through aggressive masking:
- Masking ratio: 75% of patches are masked -- far more aggressive than BERT's 15% or BEiT's 40%.
- Asymmetric encoder-decoder: The encoder only processes visible patches (25% of 196 = 49 tokens). A lightweight decoder reconstructs all patches including masked ones.
- Reconstruction target: Raw pixel values (MSE loss), not discrete tokens.
- Why 75% works: Images have enormous spatial redundancy. With 75% masking, the remaining patches do not form a trivially interpolatable pattern, forcing the model to learn deep semantic understanding.
- Efficiency: Since the encoder only processes 49 tokens (not 196), pre-training is ~3x faster and uses ~3x less memory than standard ViT training.
- Results: MAE with ViT-H achieves 87.8% top-1 on ImageNet-1K, using only ImageNet-1K for both pre-training and fine-tuning.
Impact on the field: These variants collectively demonstrated that ViT's advantage is architectural, not just data-driven. DeiT showed supervised training can work with the right recipe. BEiT and MAE showed self-supervised pre-training can replace massive labeled datasets entirely.
Key Points
- 1
DeiT: knowledge distillation from a CNN teacher + heavy augmentation achieves 83.1% top-1 on ImageNet-1K with zero external data
- 2
BEiT: masked visual token prediction using a dVAE tokenizer (8192-class vocabulary, 40% mask ratio) -- analogous to BERT for images
- 3
MAE: masks 75% of patches, encoder only processes the visible 25% (49 tokens), reconstructs raw pixels -- 3x faster pre-training than standard ViT
- 4
MAE with ViT-H achieves 87.8% on ImageNet-1K using ONLY ImageNet-1K data -- closing the gap with JFT-300M pre-trained models
- 5
These variants proved ViT's advantage is architectural (scalable self-attention), not just a consequence of data scale
- 6
The masking insight from MAE (images are highly redundant, so aggressive masking forces semantic learning) became foundational for subsequent self-supervised vision research
Mathematical Formulation
MAE Reconstruction Loss
LMAE=∣M∣1∑i∈M∣∣xi−x^i∣∣2
M is the set of masked patch indices (75% of 196 = 147 patches). Only masked patches contribute to the loss -- visible patches are not reconstructed. Each x_i is a P²C = 768-dim patch vector.
DeiT Distillation Loss
LDeiT=(1−λ)⋅LCE(y,ytrue)+λ⋅LCE(ydist,yteacher)
The total loss combines standard cross-entropy on the [CLS] token output with distillation loss on the dedicated distillation token output. The teacher provides hard labels (argmax), not soft probabilities.
Mathematical Intuition
DeiT adds a distillation token so a CNN teacher guides training — cutting data needs from 300M to 1.3M. BEiT and MAE use masked image modeling: mask 75% of patches, predict them. MAE reconstructs pixels with a loss ∥xmask−x^∥22, making ViT self-supervised — no labels needed, yet linear-probe accuracy rivals supervised training.
ViT's attention maps provide a window into what the model has learned, revealing interpretable spatial patterns that evolve across layers and heads. Unlike CNN feature maps which require gradient-based methods (Grad-CAM) for interpretation, ViT's attention weights are directly readable and semantically meaningful.
The Problem
Understanding learned representations is critical for:
- Debugging failures: When ViT misclassifies an image, attention maps can reveal whether it focused on the wrong region (e.g., background instead of object) or the right region with wrong features.
- Trust and deployment: Medical imaging, autonomous driving, and other safety-critical applications require model interpretability. Attention maps provide direct evidence of what the model "looks at."
- Scientific understanding: Do Transformers learn the same features as CNNs (edges, textures, shapes)? Do they develop novel representations?
- Architecture design: Attention patterns reveal redundancy across heads and layers, informing efficient architecture design (pruning, distillation).
The challenge: ViT-B/16 has 12 layers with 12 attention heads each, producing 12×12=144 attention matrices of shape 197×197. How do we extract a meaningful summary from this high-dimensional representation?
The Solution
Attention visualization methods and findings:
1. Raw Attention Maps (per head, per layer): Each attention head produces a 197×197 matrix. To visualize what a specific head attends to, extract the [CLS] token's attention row (shape 197), discard position 0, and reshape the remaining 196 values to 14×14. Bilinearly upsample to the original image resolution.
2. Attention Rollout (Abnar & Zuidema, 2020): To capture cumulative information flow across layers, multiply attention matrices: A~=∏l=1LAl
where Al is the attention matrix at layer l (averaged across heads). Since attention is not a simple linear chain (residual connections add identity), a more accurate version is: A^l=0.5⋅Al+0.5⋅I
This accounts for the skip connection that adds the identity mapping at each layer.
Key findings from attention analysis:
Layer-wise progression:
- Layers 1-3 (early): Attention patterns resemble local filters -- heads attend to nearby patches, capturing texture and edge information. Some heads show stripe patterns (horizontal/vertical edge detectors).
- Layers 4-8 (middle): Attention becomes more semantic. Heads begin attending to object parts: a head might attend to all "face" patches or all "sky" patches, regardless of spatial distance.
- Layers 9-12 (late): [CLS] token attention becomes highly focused on discriminative regions. For a dog image, attention concentrates on the face and body while ignoring background.
Head specialization:
- Some heads in early layers act as "horizontal line detectors" (attending to patches in the same row)
- Others act as "color patch groupers" (attending to patches with similar color)
- Late heads develop "object part" attention (attending to semantically related patches)
Emergent segmentation: The [CLS] attention map from the last layer often closely matches object segmentation masks, even though ViT was trained only for classification -- no segmentation labels were ever provided. This led to methods like DINO (Caron et al., 2021) that extract high-quality segmentation from self-supervised ViT features.
Key Points
- 1
Early layers (1-3): attention patterns resemble local convolutional filters -- nearby patches attend to each other, capturing texture and edge information
- 2
Middle layers (4-8): attention becomes semantic, with heads grouping patches by object parts or material type regardless of spatial distance
- 3
Late layers (9-12): [CLS] attention concentrates on the most discriminative image regions, often aligning closely with object boundaries
- 4
Different heads within the same layer specialize in different patterns -- some detect edges, others group colors, others track objects -- providing a diverse set of features
- 5
Attention Rollout (multiplying attention matrices across layers with residual correction) provides a cumulative view of information flow from input patches to [CLS]
- 6
Self-supervised ViT models (DINO) produce attention maps that closely match semantic segmentation masks, enabling zero-shot segmentation from classification models
Mathematical Intuition
Attention rollout multiplies attention matrices across layers: Aroll=∏l=1L(Al+I)/2, tracing how information mixes from input patches to the [CLS] token. These maps reveal that ViT naturally segments objects without any segmentation supervision — an emergent behavior not seen in CNN feature maps.
Further Reading
Keep reading
Related Papers
Go deeper