Understanding ViT architecture for GPU inference optimization. How transformers see images by treating patches as tokens.
Prerequisites
[B, C, H, W], Linear, Conv2d).What you'll learn
Time
vit.py and the exercises (CPU is fine).In plain words: patches are the "words" of an image. ViT cuts a picture into small square patches, turns each patch into a vector, and reads the row of patches with the same Transformer you met in Module 1.
Until 2020, computer vision meant CNNs: small filters slid across the image, building up from edges to objects layer by layer. ViT asked a blunt question: what if we feed an image to the same Transformer encoder used for text? The recipe: cut a 224×224 image into a 14×14 grid of 16×16-pixel patches, turn each patch into a 768-dim vector with one matrix multiply, prepend one extra learnable [CLS] slot, add a learned position vector to every slot, run 12 standard encoder blocks over the resulting 197 tokens, and read the class out of the [CLS] slot. That's the whole model.
What's new compared with Module 1: only three things. (1) A patch front-end replaces the tokenizer and embedding table. (2) A [CLS] read-out replaces the LM head. (3) Position embeddings index a 2D grid. Everything in between (attention, FFN, LayerNorm, residuals) is the block you already know, minus the causal mask and the KV cache.
Why it matters next: a ViT (or a descendant such as SigLIP or the Qwen-VL vision tower) is the vision encoder in the VLM, VLA and robot-FM modules that follow.
Standard notation used throughout this guide:
| Symbol | Meaning | ViT-B/16 | ViT-L/16 | ViT-H/14 |
|---|---|---|---|---|
| H × W | Image height × width | 224 × 224 | 224 × 224 | 224 × 224 |
| C | Image channels | 3 | 3 | 3 |
| P | Patch size | 16 | 16 | 14 |
| N | Number of patches = (H/P) × (W/P) | 196 | 196 | 256 |
| T | Number of tokens = N + 1 (patches + [CLS]); FLOP formulas use T | 197 | 197 | 257 |
| P²C | Values in one flattened patch (input width of the patch projection) | 768 | 768 | 588 |
| d | Hidden dimension (token width) | 768 | 1024 | 1280 |
| h | Number of attention heads | 12 | 16 | 16 |
| d_k | Head dimension = d / h | 64 | 64 | 80 |
| L | Number of transformer layers | 12 | 24 | 32 |
| d_ff | FFN hidden dimension = 4 × d | 3072 | 4096 | 5120 |
Note on N, T and C. Module 1 calls the token count N. Here N counts patches only and T = N + 1 is the token count (ViT paper notation). The code keeps timm's names B, N, C = x.shape, where N is the token count T and C is the width d, not the image channels.
ViT-B/16 means patch size P=16. With 224×224 images: (224/16)² = 196 patches.
ViT-H/14 means P=14: (224/14)² = 256 patches. Smaller patches = more tokens = more compute but finer detail.
In plain words: a CNN looks at an image through a small window and widens its view layer by layer. A ViT lays all the patches on the table at once and lets any patch look at any other from the very first layer.
What to notice: a CNN must stack many layers before far-apart pixels can interact; a ViT connects any two patches in its first layer.
Why ViT took over vision foundation models:
Inductive bias = assumptions wired into the architecture instead of learned from data. Estimation analogy: a Kalman filter with an accurate process model needs few measurements; one with a generic random-walk model needs far more data to track the same system. A CNN ships with a good "process model" for images. ViT ships with very little.
Locality: a pixel's meaning depends mostly on its neighbours, so a 3×3 conv looks at only 9 pixels. Translation equivariance: shift the input 10 px and the feature map shifts 10 px, because the same filter is reused at every position. Receptive field: the input region that can influence one output value. Stacked 3×3 convs grow it by ~2 px per layer, so a CNN needs depth and downsampling before distant regions can interact.
ViT's bias is weak, not zero. Cutting the image into patches assumes locality, and the FFN applies the same weights to every token. Self-attention, though, is global from layer 1: patch (0,0) can read patch (13,13) directly.
The price, in numbers (ViT paper, §4.3 / Fig. 3): pre-trained on ImageNet-1k (1.3M images), ViT-L does worse than the smaller ViT-B. On ImageNet-21k (14M) they are similar. Only with JFT-300M does the larger model pull ahead. Later recipes (DeiT, Beyer et al. 2022) closed much of the gap with heavy augmentation, but in practice you still start from a pretrained checkpoint.
In plain words: cut, tag, mix, read out. The image is cut into patch tokens, each token is tagged with its position, 12 Transformer blocks mix the tokens, and one summary token gives the answer.
What to notice: the shape changes only at the two ends. All 12 blocks keep [197, 768]: 196 patch tokens plus one [CLS] token, each 768 numbers wide.
In plain words: cut the image into tiles, unroll each tile into one long list of numbers, and run every list through the same learned matrix. Each result is one token.
What to notice: the same matrix W_patch is applied to all 196 patches, so the whole step is one matrix multiply: [196, 768] @ [768, d] = [196, d]. Patch p₀ is highlighted; the others go through the same path. The image holds 3 × 224 × 224 = 150,528 values; patches are numbered row by row, index = 14·row + col (p₀ top-left, p₁₉₅ bottom-right).
A grayscale 4×4 image, patch size P = 2, so (4/2)² = 4 patches of 2·2·1 = 4 values, projected to d = 2:
0 0 | 0 9 0 0 | 0 9 ----+---- 0 0 | 9 9 0 0 | 9 9
Patches in raster (row-major) order: p0 = [0,0,0,0], p1 = [0,9,0,9], p2 = [0,0,0,0], p3 = [9,9,9,9].
E (4×2): column 0 is a "brightness" template [¼,¼,¼,¼]; column 1 is a "left-minus-right edge" template [1,−1,1,−1].
Tokens = patches @ E: p0 → [0, 0], p1 → [4.5, −18] (the edge template fires), p2 → [0, 0], p3 → [9, 0] (bright and flat).
Two things to notice. (1) A Conv2d(1, 2, kernel_size=2, stride=2) whose two kernels are those columns reshaped to 2×2 produces exactly these numbers. (2) p0 and p2 give identical tokens: only the position embedding (§2.3) can tell them apart. In ViT-B/16, E has 768 columns; each column, reshaped to 16×16×3, is a learned template, and the ViT paper (Fig. 7, left) shows their principal components look like smooth colour/frequency basis functions, much like first-layer CNN filters.
proj = nn.Conv2d(3, d, kernel_size=P, stride=P) # cut + flatten + Linear in one kernel x = proj(img) # [B, d, 14, 14] x = x.flatten(2).transpose(1, 2) # [B, 196, d], row-major patch order
| Model | P²·C (patch vector) | d (token width) | W_patch shape |
|---|---|---|---|
| ViT-B/16 | 768 | 768 | 768 × 768: square only by coincidence |
| ViT-L/16 | 768 | 1024 | 768 → 1024 |
| ViT-H/14 | 588 | 1280 | 588 → 1280 |
| ViT-B/32 | 3072 | 768 | 3072 → 768 |
In plain words: attention is like a meeting where nobody has a seat number. It hears what every patch says but not where the patch sits. A position embedding stamps each patch with its seat number.
What to notice: without positions, attention treats the patches as an unordered set: shuffle them and the patch outputs shuffle the same way, while the [CLS] output does not change at all. Adding a learned vector Ei (purple outline) to slot i makes the same patch content at a different place a different input.
cls_token = nn.Parameter(torch.zeros(1, 1, 768)) pos_embed = nn.Parameter(torch.zeros(1, 197, 768)) x = torch.cat([cls_token.expand(B, -1, -1), patches], dim=1) + pos_embed # [B, 197, 768]
In plain words: attention lets the patches talk to each other; the FFN lets each patch think on its own. A residual "highway" carries the input past both, so each block only adds a correction.
What to notice: the orange step mixes information across patches; the green step transforms each patch on its own. Each result is added back onto the blue residual stream, so the shape stays [197, 768] through all 12 blocks.
You arrive here from Module 1, a decoder-only LLM that is already pre-norm with a GELU FFN. The differences that matter for inference are elsewhere:
| Module 1: decoder-only LLM | ViT | |
|---|---|---|
| Input → tokens | tokenizer + nn.Embedding lookup of integer IDs | Conv2d(k = s = P) on pixels: a linear projection of real-valued patches |
| Sequence length | variable, grows during generation | fixed T = (H/P)² + 1 for a given resolution → static shapes, easy TensorRT engines |
| Positions | sinusoidal / learned / RoPE | learned absolute table [1, T, d], added once at the input |
| Mask | causal (token t sees 0..t) | none: bidirectional encoder |
| Block internals | pre-norm, MHA, FFN, residuals | identical (pre-norm, MHA, GELU 4× FFN) |
| Output | LM head at every position | final LN → token 0 ([CLS]) → one linear head |
| Inference phases | prefill + many decode steps with a KV cache | one forward pass, no KV cache |
| Usual bottleneck | decode: memory-bound weight/KV reads | GEMMs; FFN ≈ 64% of the FLOPs at 224 px |
Attention mechanics (Q·Kᵀ shapes, the head reshape, a worked numeric example) are covered in Module 1 and not repeated here.
In plain words: most of the work is the FFN's two big matrix multiplies, not attention. Attention's token-pair part only takes over once the image, and so the token count, gets large.
What to notice: at 224 px the FFN does about two thirds of the work and the T² part of attention only 4%. At 1024 px (T = 4097, the resolution of SAM's ViT-H encoder) the T² part becomes the largest share (47%) and the total grows 37.6× (17.56 → 659.8 GMACs).
ViT-B/16 per image: 17.56 GMACs = 35.1 GFLOPs (paper tables print the GMAC number as "GFLOPs"): patch embed 0.12 GMACs (0.7%), attention over 12 layers 6.29 GMACs (35.8%, of which only 0.72 GMACs is the T² part), FFN 11.16 GMACs (63.5%). Parameters, which match count_parameters() in vit.py:
| Part | Parameters | Share of 86.57M |
|---|---|---|
| Patch embed (Conv2d 16×16, 3 → 768) | 590.6K | 0.68% |
| [CLS] + position table | 152.1K | 0.18% |
| 12 blocks, 7.09M each = QKV 1.77M + out-proj 0.59M + FFN 4.72M + 2 LayerNorms 3K (all 12 heads share one fused QKV and one out-proj matrix) | 85.05M | 98.25% |
| Final LayerNorm + head | 770.5K | 0.89% |
from torch.utils.flop_counter import FlopCounterMode
with FlopCounterMode(display=False) as fc:
model(torch.randn(1, 3, 224, 224))
print(fc.get_total_flops() / 2e9, "GMACs") # ≈ 17.56 for ViT-B/16
One multiply-accumulate (MAC) = 2 FLOPs. Model tables (ViT/DeiT papers, timm, fvcore) count MACs but label them "FLOPs". So "ViT-B/16 = 17.6 GFLOPs" means 17.6 GMACs = 35.1 real GFLOPs. The calculator below and vit.py report both; use FLOPs (2×MAC) when you divide by a GPU's peak TFLOPS.
Per-layer derivation for ViT-B/16 (T = 197 tokens, d = 768, d_ff = 3072), in MACs:
| Op | Shapes | Formula | MACs | Share |
|---|---|---|---|---|
| QKV projection | [197,768] @ [768,2304] | 3·T·d² | 348.6 M | 24.0% |
| Q·Kᵀ (12 heads) | 12 × [197,64] @ [64,197] | T²·d | 29.8 M | 2.0% |
| softmax | 12 × 197 × 197 | a few ops per element, not MACs | ~0 | ~0 |
| A·V | 12 × [197,197] @ [197,64] | T²·d | 29.8 M | 2.0% |
| Output projection | [197,768] @ [768,768] | T·d² | 116.2 M | 8.0% |
| FFN fc1 | [197,768] @ [768,3072] | 4·T·d² | 464.8 M | 32.0% |
| FFN fc2 | [197,3072] @ [3072,768] | 4·T·d² | 464.8 M | 32.0% |
| Layer total | 12·T·d² + 2·T²·d | 1,454 M | 100% |
×12 layers = 17.45 G, + patch embed 196·768·768 = 0.116 G, + head 768·1000 = 0.8 M → 17.56 GMACs ≈ 17.6 ✔ (= 35.1 GFLOPs). The T²-dependent part over the linear part is 2·T²·d / 12·T·d² = T/(6d) = 197/4608 ≈ 0.04.
Click a header to expand. The code is a lightly simplified version of vit.py (dropout and type hints removed).
In plain words: tokens grow with the square of the image side. Double the side and the linear layers do about 4× the work, while attention's T² part does about 16×. Drag the image size and watch the orange share grow.
Parameter counts match count_parameters() in vit.py exactly, and FLOPs match compute_flops() (and PyTorch's FlopCounterMode).
1 MAC = 2 FLOPs; totals include the patch embedding and the head. The score matrix is B·h·T²·2 bytes; fused attention kernels never store it. Parameters equal count_parameters() in vit.py.
| Aspect | CNN (ResNet, EfficientNet) | ViT |
|---|---|---|
| Inductive Bias | Strong: locality, translation equivariance (weight sharing) | Weak: only patching + a shared per-token MLP; the 2D layout is learned from data |
| Data Efficiency | Trains well from scratch on small datasets | Original 2020 recipe needed ImageNet-21k (14M) or JFT-300M pre-training; DeiT-style augmentation + distillation trains well on ImageNet-1k (1.3M) alone. In practice: start from a pretrained checkpoint |
| Scaling | Also scales when trained comparably (NFNets match ViTs at JFT-4B scale, Smith et al. 2023) | Scales well; dominant at foundation-model scale, helped by shared tooling with LLMs and easy multimodal fusion |
| Global Context | Requires deep networks (large receptive field) | From layer 1 (self-attention) |
| Inference kernels | Mature, highly tuned conv kernels (cuDNN, TensorRT) | Mostly large GEMMs (Tensor-Core friendly) plus fused attention; cost grows as T² at high resolution |
| Transfer Learning | Good | Excellent (especially with large pretraining) |
Use CNN when: training from scratch on very little data, or targeting tiny MCU/NPU accelerators without good transformer support.
Use ViT when: a pretrained checkpoint exists, you need multimodal features (VLM/VLA), or you want the best accuracy at scale. On Jetson Orin-class GPUs with TensorRT, efficient ViTs run in real time (EfficientViT reports TensorRT FP16 latencies on Jetson AGX Orin), and ViT backbones such as DINOv2 and SigLIP are common in robotics stacks.
Hybrid approaches: ConvNeXt (CNN with transformer tricks), early-conv stems + ViT, EfficientViT (conv + linear attention).
In plain words: a ViT forward pass is one big "prefill". Every weight is reused by all ~200 tokens, so the GPU's arithmetic, not its memory bus, sets the speed. Fewer tokens and lower-precision Tensor Cores help most.
The general techniques used below (quantization, kernel fusion, FlashAttention, the roofline model) are explained step by step in the Memory & inference efficiency cookbook.
| Technique | Benefit | Implementation |
|---|---|---|
| Fused attention (FlashAttention-style) | Never writes the T×T score matrix to DRAM: O(T) memory instead of O(T²). Small win at 224 px, large at high resolution | F.scaled_dot_product_attention; TensorRT fused MHA |
| Patch embedding as one GEMM | Conv2d(k = s = P) is one GEMM-shaped kernel, no separate reshape/copy | TensorRT, cuDNN |
| INT8 quantization | Up to 2× Tensor-Core throughput and ½ the weight bytes vs FP16 (Orin's Ampere GPU has no FP8 Tensor Cores) | TensorRT INT8 PTQ or explicit Q/DQ (NVIDIA ModelOpt); torchao on GPU. Not torch.ao.quantization eager mode: CPU-only and slated for removal |
| FP16/BF16 | ½ the weight/activation memory of FP32, Tensor-Core matmuls | torch.autocast("cuda", dtype=torch.float16), model.half(); TensorRT --fp16 |
| Operator fusion | Fewer DRAM round-trips for memory-bound element-wise ops | QKV as one GEMM; bias + GELU in the fc1 epilogue; residual-add + LayerNorm; fused MHA (TensorRT does these automatically; dropout is a no-op at inference) |
| Dynamic resolution | Run at a new input size without retraining from scratch | Bicubic-interpolate pos_embed (paper §3.2), then rebuild the static TensorRT engine for the new shape |
Rule of thumb: a Linear layer applied to T tokens does 2·T FLOPs per weight, and an FP16 weight is 2 bytes, so its arithmetic intensity is ≈ T FLOP/byte (ignoring activations). ViT-B handles T = 197 tokens per image → ≈ 197 FLOP/byte (whole model: 35.1 GFLOP ÷ 173 MB of weights ≈ 203).
The device's ridge point: NVIDIA lists the Orin Nano Super at 17 FP16 TFLOPS (half its 33 dense INT8 TOPS) and 102 GB/s of LPDDR5 → ridge ≈ 17 000 / 102 ≈ 167 FLOP/byte. Above the ridge you are compute-bound; below it, bandwidth-bound.
Two lower bounds: compute 35.1 GFLOP ÷ 17 TFLOPS ≈ 2.1 ms; weight streaming 86.6 M × 2 B = 173 MB ÷ 102 GB/s ≈ 1.7 ms. So ViT-B is already (slightly) compute-bound at batch 1, and more so at larger batches (batch 4: 8.3 ms of compute vs the same 1.7 ms of weights). Lower-precision Tensor Cores (INT8) buy speed here; memory tricks don't. Real TensorRT latencies are higher than these bounds (kernel efficiency, LayerNorm/softmax/GELU traffic, clocks).
Contrast with Module 1: an LLM in decode processes T = 1 token per step, so intensity ≈ 1 FLOP/byte, about 167× below the ridge (≈ 167 FLOP/byte). That's why KV caches and weight quantization dominate LLM inference, while ViT has no decode phase: the whole image is one "prefill".
• Attention scores, per layer: 197 × 197 × 12 heads × 4 B = 1.9 MB per image (FP32).
• FFN hidden activation, per layer: 197 × 3072 × 4 B = 2.4 MB per image — about the same size.
• At inference, activations are freed layer by layer, so the per-layer peak (a few MB per image) is what matters.
• At 1024 px (T = 4097, the resolution of SAM's ViT-H image encoder), the per-layer scores grow to ≈ 806 MB per image in FP32 (403 MB in FP16). That is why fused attention and windowed attention matter at high resolution. For comparison, an LLM prefill of 4096 tokens with 32 heads would need 4096² × 32 × 4 B ≈ 2.1 GB per layer if the scores were materialized.
Conv2d(k = s = P) is the same math in one kernel. For ViT-B/16, P²C = d = 768 only by coincidence.1. How many tokens does ViT-L/14 see at 336×336?
2. What is the shape of ViT-L/16's patch projection? And ViT-H/14's?
3. Remove pos_embed and shuffle the patches. What happens to the patch outputs, and to [CLS]?
vit.py's demo_permutation() measures a relative error of ~2e-7 without pos_embed vs ~5e-2 with it.4. Your checkpoint was trained at 224 px but you deploy at 448 px. What breaks, how do you fix it, and what does it cost?
pos_embed has 197 rows. Keep row 0 (CLS), reshape the other 196 rows to a 14×14×d grid, bicubic-interpolate to 28×28, flatten and re-attach CLS (the paper's §3.2 recipe), then rebuild the static TensorRT engine. Cost: 78.5 vs 17.6 GMACs ≈ 4.5×, more than the 4× pixel increase because of the T² term.5. Why does ViT have no KV cache?
6. For ViT-B/16 at 224 px, how big is the T² part relative to the linear layers, and at what T would they be equal?
7. A paper table says ViT-B/16 = 17.6 GFLOPs, but vit.py prints 35.1 GFLOPs. Who is wrong?
8. Batch 1, FP16, Orin Nano Super (17 TFLOPS, 102 GB/s): is ViT-B/16 compute- or bandwidth-bound?
9. Derive the per-block parameter count of ViT-B (d = 768, d_ff = 4d) from the layer shapes.
print_model_summary() prints.10. What does the VLM module remove from this ViT, and why?
vit.py)🔧 Build it yourself
labs/lab04.html is a guided lab: build a small ViT from scratch, one piece at a time, and run it. Setup is in labs/index.html. The exercises below then probe vit.py.
E1 (easy) — count by hand. Using only the shapes, write params(d, L, P, n_cls, img=224) for a ViT and compare it with count_parameters() for Ti/S/B/L/H.
Self-verify: assert params(768, 12, 16, 1000) == count_parameters(vit_base_patch16()) == 86_567_656 (hint: per block 12d² + 13d; build the big ones under with torch.device("meta"):).
E2 (easy) — patchify + Linear. Write PatchEmbedLinear that reshapes [B, C, H, W] → [B, N, P·P·C] (paper order: pixel-major, channel last) and applies nn.Linear(P*P*C, d). Copy weights from the conv with lin.weight = conv.weight.permute(0, 2, 3, 1).reshape(d, -1).
Self-verify: torch.allclose(PatchEmbedLinear(x), PatchEmbed(x), atol=1e-5) for 224/P16 and 32/P8. Bonus: show that F.unfold gives the (C, P, P) order and needs no permute.
E3 (medium) — see the attention maps. Add a return_attn option to Attention that computes softmax(q @ k.T * self.scale) @ v explicitly and returns the [B, h, T, T] matrix.
Self-verify: the output equals the SDPA path to 1e-6; every row of attn sums to 1; changing the last token changes token 0's output (no causal mask). Then reshape attn[:, :, 0, 1:] to 14×14 and plot a CLS-attention map.
E4 (medium) — why position embeddings are needed. Extend demo_permutation() to also compare the [CLS] output and the logits. Note the trap: at random init attention is nearly uniform, so [CLS] barely moves under a shuffle even with pos_embed (relative change ~1e-3); patch outputs are the more sensitive probe, and a trained/pretrained model gives a clearer [CLS] signal.
Self-verify: with model.pos_embed.zero_(), [CLS] and logits agree to ~1e-6 under any permutation (relative error ~8e-7 for vit_tiny_patch16, seed 0); with pos_embed, patch outputs differ by ~5e-2.
E5 (hard) — run at 384 px. Implement resize_pos_embed(pos, new_grid): keep pos[:, :1], reshape pos[:, 1:] to [1, d, 14, 14], F.interpolate(..., size=(24, 24), mode="bicubic", align_corners=False), flatten and concatenate. Load it into ViT(img_size=384).
Self-verify: resizing to the same 14×14 grid returns the input (to ~1e-6); the output shape is [B, 1000]; compute_flops(model)["total_gmacs"] = 55.48 and equals FlopCounterMode total / 2.
E6 (hard) — is it the real thing? Build torchvision.models.vit_b_16(weights=None) and map its state dict onto vit_base_patch16(): conv_proj→patch_embed.proj, class_token→cls_token, encoder.pos_embedding→pos_embed, layers.i.ln_1/ln_2→blocks.i.norm1/norm2, self_attention.in_proj_*→attn.qkv.*, out_proj→attn.proj, mlp.0/mlp.3→mlp.fc1/fc2, encoder.ln→norm, heads.head→head.
Self-verify: load_state_dict(..., strict=True) succeeds and logits match to ~1e-4. torchvision zero-initializes the head, so randomize it first or the comparison is trivially 0. Try it with LayerNorm eps = 1e-5 to see why vit.py uses 1e-6.
An inference-only excerpt of vit.py: no dropout, simplified signatures, no analysis helpers. It is state-dict compatible with vit.py (same parameter names and shapes).
"""
Vision Transformer (ViT) Reference Implementation (condensed, inference-only)
Full version with dropout, FLOP counting and demos: vit.py
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
class PatchEmbed(nn.Module):
"""Convert image to patch embeddings using Conv2d."""
def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):
super().__init__()
self.img_size = img_size
self.patch_size = patch_size
self.num_patches = (img_size // patch_size) ** 2
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
def forward(self, x: torch.Tensor) -> torch.Tensor:
# x: [B, 3, H, W] -> [B, num_patches, embed_dim]
x = self.proj(x) # [B, embed_dim, H/P, W/P]
x = x.flatten(2).transpose(1, 2) # [B, num_patches, embed_dim]
return x
class Attention(nn.Module):
"""Multi-head self-attention (no causal mask)."""
def __init__(self, dim=768, num_heads=12, qkv_bias=True):
super().__init__()
assert dim % num_heads == 0
self.num_heads = num_heads
self.head_dim = dim // num_heads
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.proj = nn.Linear(dim, dim)
def forward(self, x: torch.Tensor) -> torch.Tensor:
B, N, C = x.shape # [B, T, d]: batch, tokens T, width d (timm names them N, C)
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)
q, k, v = qkv.unbind(0)
# softmax(q @ k^T / sqrt(d_k)) @ v in one fused kernel (PyTorch 2.0+)
x = F.scaled_dot_product_attention(q, k, v) # [B, h, T, d_k]
x = x.transpose(1, 2).reshape(B, N, C)
return self.proj(x)
class MLP(nn.Module):
"""Feed-forward network with GELU activation."""
def __init__(self, dim=768, mlp_ratio=4.0):
super().__init__()
hidden = int(dim * mlp_ratio)
self.fc1 = nn.Linear(dim, hidden)
self.fc2 = nn.Linear(hidden, dim)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.fc2(F.gelu(self.fc1(x)))
class Block(nn.Module):
"""Transformer encoder block with pre-norm."""
def __init__(self, dim=768, num_heads=12, mlp_ratio=4.0):
super().__init__()
self.norm1 = nn.LayerNorm(dim, eps=1e-6)
self.attn = Attention(dim, num_heads)
self.norm2 = nn.LayerNorm(dim, eps=1e-6)
self.mlp = MLP(dim, mlp_ratio)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = x + self.attn(self.norm1(x)) # Pre-norm + residual
x = x + self.mlp(self.norm2(x))
return x
class ViT(nn.Module):
"""Vision Transformer for image classification."""
def __init__(
self,
img_size=224,
patch_size=16,
in_chans=3,
num_classes=1000,
embed_dim=768,
depth=12,
num_heads=12,
mlp_ratio=4.0,
):
super().__init__()
self.patch_embed = PatchEmbed(img_size, patch_size, in_chans, embed_dim)
num_patches = self.patch_embed.num_patches
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))
self.blocks = nn.ModuleList([
Block(embed_dim, num_heads, mlp_ratio) for _ in range(depth)
])
self.norm = nn.LayerNorm(embed_dim, eps=1e-6)
self.head = nn.Linear(embed_dim, num_classes)
# Only matters when training from scratch (vit.py also inits the Linears)
nn.init.trunc_normal_(self.pos_embed, std=0.02)
nn.init.trunc_normal_(self.cls_token, std=0.02)
def forward(self, x: torch.Tensor) -> torch.Tensor:
B = x.shape[0]
x = self.patch_embed(x) # [B, 196, 768]
cls_tokens = self.cls_token.expand(B, -1, -1)
x = torch.cat([cls_tokens, x], dim=1) # [B, 197, 768]
x = x + self.pos_embed
for block in self.blocks:
x = block(x)
x = self.norm(x)
return self.head(x[:, 0]) # [B, num_classes]
# Model configurations
def vit_base_patch16():
return ViT(patch_size=16, embed_dim=768, depth=12, num_heads=12)
def vit_large_patch16():
return ViT(patch_size=16, embed_dim=1024, depth=24, num_heads=16)
def vit_huge_patch14():
return ViT(patch_size=14, embed_dim=1280, depth=32, num_heads=16)
if __name__ == "__main__":
model = vit_base_patch16().eval()
print(f"ViT-B/16 Parameters: {sum(p.numel() for p in model.parameters()):,}") # 86,567,656
x = torch.randn(1, 3, 224, 224)
with torch.no_grad():
out = model(x)
print(f"Input: {x.shape} -> Output: {out.shape}")
Setup and run the full reference implementation:
# Setup (one time)
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
# Run demo (CPU is fine, ~1 GB RAM)
python vit.py
Outputs: a per-module parameter breakdown, compute in GMACs and GFLOPs, a shape-annotated forward pass checked against model(x), a Conv2d ≡ patchify + Linear check, a patch-shuffle test showing why position embeddings are needed, and a Ti/S/B/L/H comparison table.
Videos and visual walkthroughs are collected in 🎬 Learn it visually at the top of this page.