🖼️ Vision Transformer (ViT)

Understanding ViT architecture for GPU inference optimization. How transformers see images by treating patches as tokens.

Before you start

Prerequisites

  • Module 1: Transformer: multi-head attention, FFN, pre-norm residual blocks, FLOP counting.
  • Basic PyTorch shapes ([B, C, H, W], Linear, Conv2d).

What you'll learn

  • How an image becomes 197 tokens: patches, one GEMM, [CLS], position embeddings.
  • What ViT keeps from the LLM block and what it drops (causal mask, KV cache).
  • Where the compute goes (FFN ≈ 64%) and why "17.6 GFLOPs" is really 17.6 GMACs.
  • When attention starts to matter (high resolution) and how ViT sits on the Orin roofline.

Time

  • ~60 min reading + widgets.
  • ~20 min running vit.py and the exercises (CPU is fine).
🎬 Learn it visually
  1. An image is worth 16x16 words: ViT | Vision Transformer explained, AI Coffee Break with Letitia (video, 5 min). Watch this first: a short visual summary of the paper's one idea, image patches as tokens.
  2. Transformers for Vision, Dive into Deep Learning §11.8 (Zhang, Lipton, Li, Smola). A textbook chapter that draws the patch-embedding pipeline and builds each piece in a few lines of code.
  3. Vision Transformer Quick Guide: Theory and Code in (almost) 15 min, DeepFindr (video, 17 min). Code-along: a compact PyTorch ViT after a short theory recap.
  4. An Image is Worth 16x16 Words (Paper Explained), Yannic Kilcher (video, 30 min). A slower walk through the original paper, its experiments and design choices.

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.

⏱️ ViT in one minute

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.

1. Notation & Dimensions

Standard notation used throughout this guide:

Symbol Meaning ViT-B/16 ViT-L/16 ViT-H/14
H × WImage height × width224 × 224224 × 224224 × 224
CImage channels333
PPatch size161614
NNumber of patches = (H/P) × (W/P)196196256
TNumber of tokens = N + 1 (patches + [CLS]); FLOP formulas use T197197257
P²CValues in one flattened patch (input width of the patch projection)768768588
dHidden dimension (token width)76810241280
hNumber of attention heads121616
d_kHead dimension = d / h646480
LNumber of transformer layers122432
d_ffFFN hidden dimension = 4 × d307240965120

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.

💡 The /16 or /14 in ViT Names

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.

2. Inference Data Flow

2.0 Why Vision Transformer? (Replacing CNNs)

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.

CNN vs ViT: how far one layer can see ① CNN: local → global 224² 7² resolution ↓ · channels ↑ ② ViT: global from layer 1 14×14 patches p₀ p₁₉₅ ③ all-to-all attention

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:

🧩 Decoding the jargon

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.

2.1 High-Level Inference Pipeline

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.

ViT pipeline (one image) Image [3, 224, 224] Patch embed [196, 768] + [CLS] + pos [197, 768] Encoder × 12 [197, 768] Final LN → [CLS] [768] Linear head [1000]
data learned weights mixing across tokens output bookkeeping

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.

2.2 Patch Embedding: Image → Tokens

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.

Patchify: each 16×16 patch becomes one token Image [3, 224, 224] p₀ p₁₉₅ 14×14 patches p₀ flattened: 768 numbers 16 · 16 · 3 = 768 × W_patch [768, d] one token, width d d = 768 for ViT-B

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).

Patchify shapes, step by step
Intuition
Tiles in, tokens out: every P×P tile becomes one row of numbers, and one shared matrix turns each row into a d-wide token.
N = (H / P) · (W / P)
Xp : [N, P²·C]
Z = Xp · E + b   : [N, d]
Read it aloud
An H×W image with C colour channels, cut into P×P tiles, gives N tiles. Each tile becomes one row of P²·C numbers in Xp. The matrix E has P²·C rows and d columns, so Xp·E gives N tokens, each d numbers wide. For ViT-B/16: N = (224/16)² = 196, P²·C = 16·16·3 = 768, and E is [768, 768], square only by coincidence (ViT-L/16 maps the same 768 numbers to d = 1024).
Why it exists
A Transformer needs a sequence of vectors. Using every pixel as a token would give 224·224 = 50,176 tokens and about 2.5 billion attention pairs per head; 16×16 patches give 196 tokens and 38,416 pairs (65,536× fewer). The matrix E also lets the token width d be chosen independently of the patch size.
Tiny example

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.

Code
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
Size
Projection: 3·16·16·768 + 768 bias = 590,592 parameters. With [CLS] (768) and the position table (197·768 = 151,296), the whole embedding layer is 742,656 parameters, 0.86% of ViT-B's 86.57M. The Conv2d weight [768, 3, 16, 16], reshaped, is exactly a Linear weight [768 out, 768 in]. The paper writes the matrix as E; the official JAX code, timm and this repo implement all three steps as one Conv2d.
ModelP²·C (patch vector)d (token width)W_patch shape
ViT-B/16768768768 × 768: square only by coincidence
ViT-L/167681024768 → 1024
ViT-H/145881280588 → 1280
ViT-B/3230727683072 → 768

2.3 Position Embeddings: Where is Each Patch?

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.

Position embeddings: give every patch an address Without positions P₀ P₁ P₂ P₁₉₅ order is invisible With positions CLS+E₀ P₀+E₁ P₁+E₂ P₁₉₅+E₁₉₆ each slot has an address

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.

The input sequence: [CLS] + patches + positions
Intuition
Put one empty "summary" slot in front of the patches, then add a learned address vector to every slot.
z0 = [ xcls ; Xp·E ] + Epos
[1, d] stacked on [196, d] → [197, d],  Epos : [197, d]
Read it aloud
The starting sequence z-zero is the class token stacked on top of the 196 patch tokens, plus one learned position vector per row. Row 0 belongs to [CLS]; row 1 is the top-left patch (0, 0) and row 196 the bottom-right patch (13, 13).
Why it exists
Attention and the FFN are permutation-equivariant, so Epos is the model's only source of "where". [CLS] gives the classifier one vector that must collect its content from the patches through attention (the alternative, averaging the patch outputs, is discussed in §3).
Tiny example
In the 4×4 example above, p0 and p2 both became [0, 0]. They sit in rows 1 and 3. With position vectors E1 = [0.5, 0] and E3 = [0.5, 0.5]: p0 → [0.5, 0] and p2 → [0.5, 0.5]. Same content, different inputs.
Code
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]
Key fact
The table is one-dimensional (rows 0–196), yet after training nearby patches get similar vectors: the 2D grid is learned. Try the widget below.
🧭 Try it: position similarity → a position-only attention head

Click any patch. Left: how similar its position vector is to every other patch's (cosine). Right: where a head that looks only at position would attend, with score β·cos(Eq, Ej). The vectors are fixed 2D sin-cos embeddings (d = 768, as used by MAE and many later ViTs), computed in your browser.

cos(Eq, Ej): colour stretched from min to 1.00
softmaxj(β · cos) over the 196 patches
20

What to notice: similarity is highest along the query's own row and column and fades with distance, although nothing in attention knows about rows. The learned table of the original ViT ends up with the same pattern (ViT paper, Fig. 7 centre: "closer patches tend to have more similar position embeddings"). Raise β and the head becomes a local, 3×3-conv-like filter (β = 60: ~88% of the weight in the 3×3 neighbourhood); at β = 0 it averages the whole image. ViT does not get locality for free, but each head can learn it. In β·cos, β plays the role of ‖q‖·‖k‖/√dk.

2.4 Complete ViT Block: Multi-Head Attention + FFN

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.

ViT encoder block (repeated 12×) residual residual Input x [197, 768] LayerNorm Self-attention 12 heads · no mask LayerNorm FFN (MLP) 768 → 3072 → 768 Output [197, 768]

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 LLMViT
Input → tokenstokenizer + nn.Embedding lookup of integer IDsConv2d(k = s = P) on pixels: a linear projection of real-valued patches
Sequence lengthvariable, grows during generationfixed T = (H/P)² + 1 for a given resolution → static shapes, easy TensorRT engines
Positionssinusoidal / learned / RoPElearned absolute table [1, T, d], added once at the input
Maskcausal (token t sees 0..t)none: bidirectional encoder
Block internalspre-norm, MHA, FFN, residualsidentical (pre-norm, MHA, GELU 4× FFN)
OutputLM head at every positionfinal LN → token 0 ([CLS]) → one linear head
Inference phasesprefill + many decode steps with a KV cacheone forward pass, no KV cache
Usual bottleneckdecode: memory-bound weight/KV readsGEMMs; 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.

2.5 Full Model: Where the Parameters and Compute Go

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.

Share of ViT-B/16 compute (MACs) 224 px · T = 197 QKV + out 31.8% T² 4.1% FFN 63.5% 17.6 GMACs 1024 px · T = 4097 QKV + out 17.6% T² 46.9% FFN 35.2% 660 GMACs
patch embed + head QKV + output projection (weight matrices) QKᵀ and A·V (mixing across tokens) FFN (per-token compute)

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:

PartParametersShare of 86.57M
Patch embed (Conv2d 16×16, 3 → 768)590.6K0.68%
[CLS] + position table152.1K0.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.05M98.25%
Final LayerNorm + head770.5K0.89%
The cost of one block, in multiply-adds
Intuition
A Linear layer costs tokens × inputs × outputs multiply-adds; attention's score step costs tokens × tokens × width.
MACs per block = 12·T·d² + 2·T²·d
FLOPs = 2 × MACs
Read it aloud
Twelve times tokens times width squared, from the weight matrices (QKV 3, output projection 1, FFN 8), plus two times tokens squared times width, from QKᵀ and A·V. T is the token count (197), d the width (768).
Why it exists
It tells you what to optimize. The first term grows linearly with tokens, the second with their square. Their ratio is T/(6d), so for ViT-B the T² part only catches up with the rest at T = 6d = 4608 tokens.
Tiny example
T = 4 tokens, d = 2: 12·4·2² = 192 plus 2·4²·2 = 64, so 256 MACs = 512 FLOPs. For ViT-B: 1,394 M + 60 M = 1,454 M MACs per block (full table below).
Code
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
🧮 FLOPs vs MACs: read this before any number on this page

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:

OpShapesFormulaMACsShare
QKV projection[197,768] @ [768,2304]3·T·d²348.6 M24.0%
Q·Kᵀ (12 heads)12 × [197,64] @ [64,197]T²·d29.8 M2.0%
softmax12 × 197 × 197a few ops per element, not MACs~0~0
A·V12 × [197,197] @ [197,64]T²·d29.8 M2.0%
Output projection[197,768] @ [768,768]T·d²116.2 M8.0%
FFN fc1[197,768] @ [768,3072]4·T·d²464.8 M32.0%
FFN fc2[197,3072] @ [3072,768]4·T·d²464.8 M32.0%
Layer total12·T·d² + 2·T²·d1,454 M100%

×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.

3. Architecture Blocks (Expandable)

Click a header to expand. The code is a lightly simplified version of vit.py (dropout and type hints removed).

4. Complexity Calculator

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).

Interactive ViT FLOPs & Memory Calculator

Presets:
224 px
Tokens (patches + [CLS]) 196 patches · 197 tokens
Attention FLOPs / layer (T² part) -
FFN FLOPs / layer -
Total FLOPs -
Total MACs (papers' "GFLOPs") -
Score matrix, one layer, FP16 -
Parameters -

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.

5. ViT vs CNN: When to Use What

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)
💡 Practical Guidance

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).

6. GPU Optimization Techniques

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.

ViT-Specific Optimizations

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
📐 Back-of-envelope: ViT-B/16 on Jetson Orin Nano Super, batch 1, FP16

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".

⚠️ ViT activation memory is small at 224 px

• 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.

7. Recap, Self-Check and Exercises

Key takeaways

Self-check

1. How many tokens does ViT-L/14 see at 336×336?

Answer
(336/14)² = 24² = 576 patches, + 1 [CLS] = 577 tokens. This is the CLIP ViT-L/14-336 tower that LLaVA-1.5 uses in the VLM module (where [CLS] is dropped, leaving 576 image tokens).

2. What is the shape of ViT-L/16's patch projection? And ViT-H/14's?

Answer
ViT-L/16: 16·16·3 = 768 inputs → d = 1024 outputs. ViT-H/14: 14·14·3 = 588 → 1280. ViT-B/16's square 768 × 768 is a coincidence.

3. Remove pos_embed and shuffle the patches. What happens to the patch outputs, and to [CLS]?

Answer
The patch outputs come out shuffled the same way (attention and the FFN are permutation-equivariant) and the [CLS] output is unchanged. 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?

Answer
T goes from 197 to 785, but 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?

Answer
There is no autoregressive loop: all tokens are known up front and processed in one bidirectional pass, so nothing computed for one step is reused by a later step.

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?

Answer
Ratio = 2T²d / 12Td² = T/(6d) = 197/4608 ≈ 0.043. Equal at T = 6d = 4608 tokens, i.e. a 68×68 grid ≈ 1088 px at P = 16.

7. A paper table says ViT-B/16 = 17.6 GFLOPs, but vit.py prints 35.1 GFLOPs. Who is wrong?

Answer
Neither. The paper's number is 17.6 G multiply-accumulates; each MAC is 2 FLOPs, so 35.1 GFLOPs. Use the 35.1 figure when dividing by a GPU's peak TFLOPS.

8. Batch 1, FP16, Orin Nano Super (17 TFLOPS, 102 GB/s): is ViT-B/16 compute- or bandwidth-bound?

Answer
Compute bound ≈ 35.1 GFLOP / 17 TFLOPS ≈ 2.1 ms; weight streaming ≈ 173 MB / 102 GB/s ≈ 1.7 ms. Intensity ≈ 203 FLOP/byte vs a ridge of ≈ 167, so it is (slightly) compute-bound, and more so at larger batch. LLM decode (T = 1) is about 167× below the ridge.

9. Derive the per-block parameter count of ViT-B (d = 768, d_ff = 4d) from the layer shapes.

Answer
QKV (3d² + 3d) + out-proj (d² + d) + fc1 (4d² + 4d) + fc2 (4d² + d) + 2 LayerNorms (4d) = 12d² + 13d = 7,077,888 + 9,984 = 7,087,872, exactly what print_model_summary() prints.

10. What does the VLM module remove from this ViT, and why?

Answer
The [CLS] token and the classification head. The LLM wants every patch token (spatial detail), not one pooled vector, and it is not predicting ImageNet classes.

Hands-on exercises (with 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.

8. Condensed Reference Implementation

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}")
▶ Run the code

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.

9. References

Videos and visual walkthroughs are collected in 🎬 Learn it visually at the top of this page.

Papers

Implementation Resources