Chapter 29 of 42 · ~18 min read & lab+75 XP
Chapter 29 · Deep Learning

Vision Transformers (ViT): Patch Embeddings, CLS Tokens, Inductive Bias & ViT vs. CNNs

How 'An Image Is Worth 16×16 Words' unified vision and NLP: slicing images into patch tokens via Conv2d(stride=P), [CLS] + Positional Embeddings, quadratic patch compute, and CNN vs. ViT inductive bias!

Why ML Engineers & Data Scientists Actually Need This

Vision Transformers (ViT) unified computer vision with language modeling — powering CLIP, DINOv2, SAM, and every modern Multimodal VLM (GPT-4o, Gemini, Claude)!

ML / AI Engineer

Understanding patch size PP vs. O(N2)O(N^2) token scaling is critical for tuning VLM vision encoders and high-resolution OCR!

Data Scientist

Knowing why vanilla ViT overfits on small datasets without pre-training (less inductive bias than CNNs!) guides when to use ConvNeXt vs. pretrained ViT/DeiT.

Interview & Debug Edge

Frequent Vision/Multimodal interview question: 'How does ViT convert a 224×224 RGB image into tokens, and what happens to attention FLOPs if you halve the patch size from 16 to 8?'

Step 0 · Test Your Gut Before Any Math!

Halving ViT's patch size from P = 16 to P = 8 increases the number of patch tokens by 4× (196 → 784). By what factor does O(N2)O(N^2) self-attention compute grow?

What You Will Master in This Chapter
  • Compute exact ViT token counts N=(H/P)(W/P)+1N = (H/P)(W/P) + 1 and explain why smaller patches (P=8P=8 vs. P=16P=16) blow up O(N2)O(N^2) attention cost by 16×
  • Implement ViT Patch Embedding cleanly in 1 line of PyTorch: nn.Conv2d(3, D, kernel_size=P, stride=P)
  • Explain the role of the learnable [CLS] token (vs. Global Average Pooling) and Positional Embeddings
  • Contrast CNN Inductive Bias (locality, shift equivariance) against ViT Global Self-Attention at small vs. massive dataset scale
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 1
N=H⋅WP2,z0=[xcls;  xp1E;… ;xpNE]+EposN = \frac{H \cdot W}{P^2}, \quad z_0 = [x_{\text{cls}}; \; x_p^1 E; \dots; x_p^N E] + E_{\text{pos}}Say aloud:“N patches equals H times W over P squared; initial tokens concatenate CLS and projected patches plus positional embeddings”
Plain-English Meaning
ViT's exact input tokenization formula: flatten each P×P×3P \times P \times 3 patch, project to dimension DD, prepend [CLS], and add positional embeddings!
Everyday Example
For 224×224, P=16, D=768: N = 196, sequence shape = (B, 197, 768).
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Instead of sliding a tiny 3×3 magnifying glass pixel-by-pixel like a CNN, ViT cuts the photo into a 14×14 grid of jigsaw tiles, turns each tile into a 'visual word', and lets every tile talk directly to every other tile in Layer 1!

1. Patch Embeddings: Turning Pixels Into Visual Tokens

Vision Transformer (ViT): Image → 16×16 Patch Embeddings → Transformer224×224 RGBInput image196 Patches(16×16×3 = 768)+ [CLS] & Pos197 × D tokensViT EncoderGlobal Attn ✓
Vision Transformer (ViT) chops a 224×224 image into 16×16 patches (196 tokens), projects each patch linearly into D-dim embeddings, and runs standard Transformer Self-Attention!

Splitting a (B, 3, 224, 224) image into 16×16 non-overlapping patches and multiplying each by a linear projection matrix E is mathematically identical to a single strided convolution: nn.Conv2d(3, D, kernel_size=16, stride=16) followed by .flatten(2).transpose(1, 2)!

Animated Mini-Lab • Vision Transformer

ViT Patch Size vs. Quadratic Attention Cost (224×224)

Grid: 14×14 → Tokens (+CLS): 197 → Attention Matrix N²: 38,809 pairs

2. `[CLS]` Token & Positional Embeddings

Inside ViT Token Sequence: [CLS] Token + Patch Projections + Positional Embeddings[CLS]P₁ + E₁P₂ + E₂P₃ + E₃...P₁₉₆ + E₁₉₆Patch embedding is literally a single `nn.Conv2d(3, D, kernel_size=16, stride=16)`!
ViT prepends a learnable [CLS] token and adds 1D/2D positional embeddings so global self-attention knows where each patch lives in the image!

Because Self-Attention treats tokens as an unordered set, ViT adds learnable Positional Embeddings EposE_{\text{pos}} so the model knows which patch is top-left vs. bottom-right, and prepends a learnable [CLS] token whose final output vector summarizes the whole image for classification (or uses Global Average Pooling across all patch tokens).

3. Inductive Bias: ViT vs. CNNs

Inductive Bias Trade-Off: CNNs (Local) vs. Vision Transformers (Global)CNNs (ResNet / ConvNeXt)• Strong locality & shift equivariance built-in• Data-efficient on small-to-medium datasetsReceptive field grows gradually with depthVision Transformers (ViT / DINOv2)• Global receptive field right from Layer 1!• Scales smoothly to 1B+ images & Multimodal VLMsNeeds pre-training or strong augmentation (DeiT)
CNNs bake in strong locality & translation-equivariance bias (shine on small data); ViTs have minimal inductive bias and global receptive fields from Layer 1 (dominate at scale)!

CNNs bake in locality and translation equivariance — helping them learn fast on small datasets. ViTs drop those assumptions in favor of Layer-1 global attention, which initially needs more data (or DeiT distillation / SSL pre-training) but scales far better to massive datasets and Multimodal LLMs!

Pause & Check · Quick Intuition Pulse

What PyTorch layer implements ViT's non-overlapping 16×16 patch extraction + linear projection in ONE fast GPU kernel?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Simply 2D-interpolate (bicubic resize) the learned Positional Embeddings from 14×14 to 28×28 — ViT's Transformer blocks handle any sequence length seamlessly!

Interactive Visual Lab
Lab Challenge: Watch the 60 FPS ViT Patch-to-CLS pipeline convert a 224×224 image into 197 Transformer tokens.
Interactive Animation • ViT Deep Lab

Vision Transformer (ViT): Image Patches to Global Self-Attention

See how ViT treats an image as a sequence of 196 visual 'words' with global attention from Layer 1.

Step 1 / 4
1. Slice 224×224 RGB image into 196 non-overlapping 16×16 patches
2. Linearly project each patch → 768-dim token via Conv2d(stride=16)
3. Prepend [CLS] token + add Positional Embeddings (197 × 768)
4. Run 12 Transformer Encoder blocks → Classify from [CLS] output ✓
0%
ViT Step 1
Intuition Takeaway: Vision Transformers (ViT) slice images into P×PP \times P patch tokens (Conv2d(3, D, P, P)), add positional embeddings + [CLS], and trade CNN locality bias for Layer-1 global self-attention that scales seamlessly to multimodal foundation models.
Where This Powers Real ML, Deep Learning & Generative AI

Multimodal VLM Vision Encoders (SigLIP, CLIP, DINOv2)

ViT patch tokens feed directly alongside text tokens inside every modern Vision-Language Model.

Production NumPy & PyTorch Code Patterns
import torch
import torch.nn as nn

# Vision Transformer (ViT) Patch Embedding + [CLS] Token + Positional Embeddings
class ViTPatchEmbed(nn.Module):
    def __init__(self, img_size: int = 224, patch_size: int = 16, in_ch: int = 3, dim: int = 768):
        super().__init__()
        num_patches = (img_size // patch_size) ** 2
        # Stride=patch_size Conv2d projects every P×P patch in one fused kernel
        self.proj = nn.Conv2d(in_ch, dim, kernel_size=patch_size, stride=patch_size)
        self.cls_token = nn.Parameter(torch.zeros(1, 1, dim))
        self.pos_embed = nn.Parameter(torch.randn(1, num_patches + 1, dim) * 0.02)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        # [B, 3, 224, 224] -> [B, 768, 14, 14] -> [B, 196, 768]
        patches = self.proj(x).flatten(2).transpose(1, 2)
        cls = self.cls_token.expand(x.size(0), -1, -1)
        return torch.cat([cls, patches], dim=1) + self.pos_embed

vit_embed = ViTPatchEmbed(img_size=224, patch_size=16, dim=768)
tokens = vit_embed(torch.randn(2, 3, 224, 224))
print("ViT sequence shape [B, 1+N_patches, D]:", tuple(tokens.shape))
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Saying ViTs have 'no convolutions at all' without knowing the patch-stem trick.
Best Practice: Mention that standard ViT patchification is implemented as a single strided Conv2d(3, D, P, P) — and hybrid Conv-stems often improve ViT training stability!
Chapter Mastery Check (+75 XP)
Score: 0 / 1
1How many total tokens (including [CLS]) does a ViT-B/16 produce for a 224×224 image?

Apply What You Learned — Solve Matching Coding Problems