Vision Transformer (ViT)

Dive into Deep Learning · §11.5

Transformers for Vision (ViT)
patches as tokens · strided conv stem · <cls> & position embeddings · 2D grid probing · matched CNN comparison

Why Pixel-Level Self-Attention Explodes Quadratically

Motivation

  • Pixel tokens (96 \times 96): m = 9{,}216 tokens \to m^2 = 84.9\text{M} attention pairs per head and layer (2.52\text{B} pairs on 224 \times 224 ImageNet).
  • 16 \times 16 Patch tokens (ViT): Partitioning an image into non-overlapping p \times p patches reduces sequence length by p^2 (256\times) and attention scores by p^4 (65{,}536\times fewer pairs).

Inductive Bias: CNN Locality vs. Global Patch Mixing

Architectural Trade-Off

  • Convolutional networks (CNNs): Bake in 2D spatial locality (k \times k sliding filters) and translation equivariance; receptive field grows gradually across depth.
  • Vision Transformers (ViTs): Global all-pairs receptive field from layer 1 (m \times m attention), but zero built-in 2D grid prior without positional embeddings.

Anatomy of the Vision Transformer (ViT)

Architecture Overview

  • 1. Patchification stem (PatchEmbedding): Maps a 96 \times 96 image with patch size p = 16 into a 6 \times 6 grid of m = 36 patch vectors in \mathbb{R}^d.
  • 2. <cls> token & position table: Prepends 1 learnable <cls> vector and adds learned 1D positional embeddings across all m + 1 = 37 slots.
  • 3. Bidirectional encoder + head: Passes the 37 tokens through L unmasked pre-norm ViTBlock layers and classifies the final <cls> vector X[:, 0].
The vision transformer from bottom to top: a 96 by 96 image cut into a 6 by 6 grid of 16 by 16 patches; a strided convolution that embeds each patch as a token; a learned cls token prepended to the 36 patch tokens and learned position embeddings added; L pre-norm encoder blocks with multi-head attention and a GELU MLP on the residual stream; and a final norm and linear head that read the cls output only.

Patchifying and Projecting in One Strided Convolution

The Patch Embedding Stem

  • Cutting an (H, W, C) image into m = (H/p)(W/p) non-overlapping p \times p patches and multiplying each by \mathbf{W}_E \in \mathbb{R}^{C p^2 \times d} is identical to a 2D convolution with kernel_size=p, stride=p.
  • Reshaping the (B, d, H/p, W/p) conv output to (B, m, d) produces the token sequence in one fused GPU kernel.

Implementing and Verifying PatchEmbedding

Stem Implementation

PatchEmbedding checks 96 % 16 == 0 and maps four 96 \times 96 images to (4, 36, 512):

class PatchEmbedding(nn.Module):
    """Image-to-sequence stem of the vision transformer."""
    def __init__(self, img_size=96, patch_size=16, num_hiddens=512,
                 num_channels=3):
        super().__init__()
        # A partial trailing patch would silently shrink the token grid
        assert img_size % patch_size == 0, 'patches must tile the image'
        self.num_patches = (img_size // patch_size) ** 2
        self.conv = nn.Conv2d(num_channels, num_hiddens,
                              kernel_size=patch_size, stride=patch_size)

    def forward(self, X):  # (batch, c, h, w) -> (batch, patches, d)
        return self.conv(X).flatten(2).transpose(1, 2)

Verifying PatchEmbedding on Four Images

Stem Implementation

img_size, patch_size, num_hiddens, batch_size = 96, 16, 512, 4
patch_emb = PatchEmbedding(img_size, patch_size, num_hiddens, num_channels=1)
X = torch.zeros(batch_size, 1, img_size, img_size)
d2l.check_shape(patch_emb(X),
                (batch_size, (img_size//patch_size)**2, num_hiddens))

The ViT Encoder Block (ViTBlock)

Encoder Block

Following Dosovitskiy et al. (2021), ViTBlock configures our d2l.TransformerBlock (§11.1) with pre-norm LayerNorm, unmasked multi-head self-attention, and a two-layer exact-GELU MLP:

\mathbf{H} = \mathbf{X} + \mathrm{MHA}\bigl(\mathrm{LN}_1(\mathbf{X})\bigr), \qquad \mathbf{Y} = \mathbf{H} + \mathrm{MLP}\bigl(\mathrm{LN}_2(\mathbf{H})\bigr)

class ViTBlock(d2l.TransformerBlock):
    """Pre-norm block with LayerNorm and an exact-GELU MLP."""
    def __init__(self, num_hiddens, mlp_num_hiddens, num_heads, dropout,
                 use_bias=False):
        super().__init__(
            num_hiddens, num_heads, dropout=dropout, norm='layer',
            bias=use_bias, ffn_factory=lambda: nn.Sequential(
                nn.Linear(num_hiddens, mlp_num_hiddens),
                nn.GELU(),  # Exact GELU
                nn.Dropout(dropout),
                nn.Linear(mlp_num_hiddens, num_hiddens)))

Why does ViT use LayerNorm and GELU rather than RMSNorm and SwiGLU? Only for historical fidelity to the 2020 ViT paper—modern vision backbones (such as SigLIP 2, DINOv2, and AIMv2) adopt RMSNorm, SwiGLU, and 2D RoPE just like LLMs.

The <cls> Readout Token and ViT Forward Pass

Readout & Forward Pass

To pool m = 36 patch tokens into a single image representation without favoring any specific patch location, ViT prepends self.cls_token at index 0 and reads X[:, 0] after L blocks:

def forward(self, X):                  # X: (batch, 1, 96, 96) images
    X = self.patch_embedding(X)        # (batch, 36, 512) patch tokens
    cls = self.cls_token.expand(X.shape[0], -1, -1)
    X = self.dropout(torch.cat((cls, X), 1) + self.pos_embedding)
    for blk in self.blks:              # L blocks over (batch, 37, 512)
        X = blk(X)
    return self.head(X[:, 0])          # LayerNorm + Linear on <cls> slot 0

Global average pooling across the m patch outputs (X[:, 1:].mean(dim=1)) works comparably well in practice; <cls> is a clean convention inherited from BERT.

Encoding 2D Spatial Position in a 1D Sequence

Positional Encodings for Grids

  • Learned 1D Table (Original ViT): Free vector \mathbf{p}_k \in \mathbb{R}^d for each raster index k \in \{0, \dots, m\}; must discover 2D grid topology from data.
  • 2D Sinusoidal Code: Concatenates d/2-dim row code \mathbf{s}_r and d/2-dim column code \mathbf{s}_c.
  • 2D Axial RoPE: Rotates half of query/key channels by row r and half by column c (used in DINOv2 / SigLIP 2).

Optimizer Sensitivity: Why ViTs Demand AdamW

Optimization Recipe

  • Unlike ResNets (which train reliably under SGD + momentum), ViTs train markedly worse under SGD because attention projections (\mathbf{W}_q, \mathbf{W}_k) and MLPs have vastly different gradient scales.
  • The ViT recipe: AdamW (\eta_{\max} = 3 \times 10^{-4}), selective weight decay (\lambda = 0.05 on 2D/4D weights only), and 1-epoch linear warmup + cosine decay.

Training Our 6.5M-Parameter ViT on Fashion-MNIST

First Training Run

  • Model configuration: 96 \times 96 images, patch size p = 16 (m = 36 patches), width d = 512, MLP width d_{\text{mlp}} = 2{,}048, H = 8 heads, L = 2 blocks (\mathbf{6.46\text{M}} parameters).
  • 10-epoch trajectory: Validation accuracy climbs smoothly to \approx 89\% (0.888\text{--}0.892 across seeds) in 10 epochs of 128-image minibatches.

ViT: 6.5M parameters, validation accuracy 0.89

Does the Trained ViT Rely on Patch Layout?

Spatial Permutation Probe

We test how strongly the trained ViT depends on 2D spatial layout by permuting the 36 patches of every validation image across five random permutations (shuffle_patches) at test time:

trained ViT: 0.888 as is, 0.25 to 0.40 with its patches shuffled
  • Strong spatial reliance (89\% \to 25\%\text{--}45\%): Scrambling where patches land cuts accuracy by roughly 45–65 percentage points, proving the classifier relies heavily on patch positions.
  • Bag-of-patches floor (\gg 10\% random guessing): Even scrambled images remain 2.5\text{--}4.5\times above the 10\% chance floor because local 16 \times 16 textures (boot soles, collar cutouts) identify several garment classes without global geometry.

Do Learned Position Embeddings Discover the 2D Grid?

Probing Position Geometry

  • Cosine similarity by Chebyshev grid distance k = \max(|r - r'|, |c - c'|): We compare the trained 36 \times 512 position table against a hard-coded 2D sinusoidal grid and random vectors.
  • Faint local structure after 10 epochs: Only adjacent patches (k = 1) show positive excess similarity (+0.05 vs. -0.03 for random noise), whereas the 2D sinusoidal code drops sharply from +0.76 to -0.46.
  • Why? Discovering full 2D grid topology from 1D raster IDs requires large datasets and hundreds of epochs (Dosovitskiy et al., 2021).

Position Similarity by Grid Distance

Probing Position Geometry

          learned: +0.04  -0.07  -0.05  -0.05  +0.05
learned - initial: +0.08  -0.10  -0.06  -0.05  +0.15
   2-D sinusoidal: +0.76  +0.21  -0.30  -0.46  -0.36
           random: -0.03  -0.03  -0.03  -0.02  -0.03

A Controlled Comparison: ViT vs. Matched ResNet

Experimental Design

  • To isolate convolutional inductive bias fairly, CompactResNet (7 residual blocks) matches ViT (L = 2, d = 512, p = 16) across all four experimental axes:
  • Identical budget: 6.46\text{M} vs. 6.45\text{M} parameters, 0.48 vs. 0.55\text{ GFLOPs/image}, 10 epochs on 96 \times 96 Fashion-MNIST, and AdamW (\lambda = 0.05) with warmup + cosine decay.

In the Small-Data Regime, the CNN Leads by 5 Points

ViT vs. CNN Results

  • Consistent 5-point CNN advantage: Across independent runs (seed spread \le 0.1\%), CompactResNet reaches \approx 94\% validation accuracy versus \approx 89\% for ViT.
  • Faster early convergence: Built-in 2D locality and translation equivariance give the CNN a lead of several points at epoch 1 that persists through epoch 10.

When Does ViT Overtake CNNs? Scale and Pretraining

Scaling Laws for Vision

  • Dataset scale crossover (Dosovitskiy et al. 2021): ResNets lead below 10\text{M} images, but ViTs overtake ResNets at 30\text{M}\text{--}300\text{M} images where global attention outgrows fixed local filters.
  • Unified multimodal interface: Because ViT turns images into standard token vectors, feeding visual patches into an LLM or Perceiver resampler requires zero architectural change.

Concept Check: Patch Sizing, FLOPs, and Invariance

Check Your Understanding

Work through these three quantitative questions:

  1. Halving the patch size: In our 96 \times 96 ViT (d = 512, L = 2), suppose we halve the patch size from p = 16 to p = 8. What happens to (a) the number of patch tokens m, (b) the parameter count of the L ViTBlock layers, and (c) the forward FLOPs per image?
  2. ImageNet token count: How many patch tokens m and per-head attention scores m^2 does a 224 \times 224 ImageNet image produce at p = 16 versus p = 8?
  3. Zeroed positional embeddings: If you set model.pos_embedding.zero_() at test time and evaluate shuffled_accuracy(model, data, perm) across 5 different random permutations perm, how much will the 5 accuracies differ from each other?

Concept Check: Patch Sizing, FLOPs, and Invariance (answers)

Check Your Understanding

Answers:

    1. Patch tokens quadruple: m = 36 \to 144 (12 \times 12 grid). (b) ViTBlock parameter count (12 L d^2) is completely unchanged (and total parameters drop by <1\% as the 16 \times 16 conv stem shrinks to 8 \times 8). (c) Forward FLOPs quadruple (0.48 \to 1.92\text{ GFLOPs}).
  1. At p = 16: m = 14^2 = 196 tokens (38{,}416 scores/head). At p = 8: m = 28^2 = 784 tokens (614{,}656 scores/head, 16\times more attention scores).
  2. Zero difference (identical to within floating-point rounding): without positional embeddings, self-attention is strictly permutation-equivariant and <cls> readout is strictly permutation-invariant.

Summary: Vision Transformers vs. Convolutional Networks

Key Takeaways

  • Stride-p Patch Stem: Maps (C, H, W) \to m = HW / p^2 tokens in one conv layer while keeping block parameters (12 L d^2) independent of m.
  • Spatial Inductive Bias: Without positional embeddings, ViT is permutation-invariant over patches; shuffling patches at test time drops accuracy from 89\% to 25\%\text{--}45\%.
  • Small Data vs. Scale: Matched ResNet leads by 5\% from scratch on small data, whereas pretrained ViTs dominate at foundation scale.