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!
Vision Transformers (ViT) unified computer vision with language modeling — powering CLIP, DINOv2, SAM, and every modern Multimodal VLM (GPT-4o, Gemini, Claude)!
Understanding patch size vs. token scaling is critical for tuning VLM vision encoders and high-resolution OCR!
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.
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?'
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 self-attention compute grow?
- Compute exact ViT token counts and explain why smaller patches ( vs. ) blow up 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
[CLS], and add positional embeddings!224×224, P=16, D=768: N = 196, sequence shape = (B, 197, 768).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
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)!
ViT Patch Size vs. Quadratic Attention Cost (224×224)
2. `[CLS]` Token & Positional Embeddings
[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 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
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!
What PyTorch layer implements ViT's non-overlapping 16×16 patch extraction + linear projection in ONE fast GPU kernel?
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!
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.
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.Multimodal VLM Vision Encoders (SigLIP, CLIP, DINOv2)
ViT patch tokens feed directly alongside text tokens inside every modern Vision-Language Model.
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))
Conv2d(3, D, P, P) — and hybrid Conv-stems often improve ViT training stability![CLS]) does a ViT-B/16 produce for a 224×224 image?