Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.Tokens are the currency of a vision Transformer
A Vision Transformer reads an image as a sentence of square tiles. Smaller tiles or a bigger image mean more words in the sentence: more detail, but more work, and attention work grows with the square of the sentence length. The model also learns a label for where each tile sits. If you later feed it a bigger image, those position labels must be stretched to the new grid, or the model no longer knows where anything is. The demo counts tiles and compute for different image sizes and tile sizes.
A satellite or drone image of 1024 × 1024 pixels gives 4096 tokens at patch 16; whether to tile it, downsample it or pay for long attention is an everyday engineering decision.
- 1. Halving the patch size multiplies the number of tokens by…
- 2. Running a ViT at a higher resolution requires…
- 3. Attention cost grows with the number of tokens…
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.The practical ViT toolbox (2020–2026)
- Tokens: N = (H/P)·(W/P) patch tokens, plus a class token and optional registers. ViT-B/16 at 224 px: 196 + 1 = 197 tokens; patch 14 (CLIP ViT-L/14, DINOv2) gives 256; SigLIP So400m/14 at 384 px gives 729.
- Compute: per layer about 12·N·D² multiply–accumulates (MACs) for the projections and the 4× MLP plus 2·N²·D for attention. ViT-B/16 costs 17.6 GMACs at 224 px and 55.5 at 384 px (papers call these “GFLOPs”). Attention is 4% of a layer at 197 tokens and about half at 4097.
- Training recipes: ViT needs data or regularisation: JFT/ImageNet-21k pre-training in the original paper; AugReg (Steiner et al., 2022) and DeiT III (Touvron et al., 2022) for strong ImageNet-only recipes.
- Resolution changes: FixRes (Touvron et al., 2019) showed that fine-tuning at a higher test resolution helps; ViT fine-tunes at 384 px by interpolating the learned position grid (bicubic in timm), then training briefly.
- FlexiViT (Beyer et al., CVPR 2023): trains with random patch sizes, resizing the patch-embedding weights with PI-resize (a pseudo-inverse) so one model serves many compute budgets.
- NaViT (Dehghani et al., NeurIPS 2023): packs patches of images at their native resolution and aspect ratio into one sequence (Patch n’ Pack), with masks that keep images apart.
- Scaling: Zhai et al. (CVPR 2022) scaled to ViT-G/14 (1.8B parameters, 90.45% ImageNet top-1); ViT-22B (Dehghani et al., ICML 2023) added parallel layers and QK normalisation for stability; SoViT (Alabdulmohsin et al., 2023) tuned width and depth for compute.
- 2024–2026 additions: register tokens remove high-norm artefacts in attention maps (Darcet et al., ICLR 2024); 2-D RoPE (Heo et al., ECCV 2024) extrapolates across resolutions and is used in DINOv3; token merging (ToMe, Bolya et al., ICLR 2023) cuts tokens at inference.
- 1. ViT-B/16 at 384 px has…
- 2. FlexiViT resizes patch-embedding weights with…
- 3. NaViT's main idea is…
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.Choosing patch size and resolution
Exercise 1.
- Token counts with class and register tokens.
- Forward-pass MACs of a ViT.
- Bilinear interpolation of a position-embedding grid.
Practice.
- Pick the backbone by the tokens you can afford: count N for your input size before choosing patch 14 or 16.
- Pre-train or start from a checkpoint at low resolution; fine-tune at the target resolution with interpolated position embeddings (timm:
dynamic_img_size=Trueorresample_abs_pos_embed). - For large inputs (satellite tiles, documents) compare tiling, downsampling and window attention by accuracy per GMAC, not accuracy alone.
- Use registers or a model trained with them (DINOv2-reg, DINOv3) when you need clean attention or patch features.
- Use bf16, FlashAttention (PyTorch SDPA) and token merging or dropping when sequences get long.
import timm, torch
# A ViT-B/16 trained at 224 px, run at 384 px: timm interpolates the 14×14 position grid to 24×24
model = timm.create_model("vit_base_patch16_224.augreg2_in21k_ft_in1k", pretrained=True,
img_size=384, dynamic_img_size=True)
x = torch.randn(1, 3, 384, 384)
tokens = model.forward_features(x) # (1, 577, 768): 24*24 patches + class token
print(tokens.shape)- 1. The quickest way to cut a ViT's cost on large images is…
- 2. timm adapts the position grid to a new size by…
- 3. Patch 14 at 224 px gives…
Level 3: Advanced
★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.Theory
Where the compute goes. One layer costs 12·N·D² MACs for the four D×D projections and the two D×4D MLP matrices, plus 2·N²·D for the scores QKᵀ and the weighted sum AV. The attention share 2N²D / (12ND² + 2N²D) = N / (6D + N) reaches one half at N = 6D: 4608 tokens for ViT-B. Below that, cost is roughly linear in tokens, so going from 224 to 384 px costs about (384/224)² ≈ 2.9× (exactly 55.5 / 17.6 = 3.2× including attention).
Position grids. Learned absolute position embeddings form a g × g grid of vectors. Run at a larger grid g′, each new position must get a vector. Bilinear (or bicubic) interpolation treats the grid as samples of a smooth function of the relative location (u, v) in the image and resamples it, so a token in the top-left of the larger image still carries a “top-left” embedding. Clipping or zero-padding instead assigns most new tokens the wrong location. Relative schemes (RoPE, Swin’s bias tables) depend only on offsets and transfer differently.
PI-resize. Changing the patch size from p to p′ changes the patch-embedding matrix w (p² inputs) to ŵ (p′² inputs). If B is the p′² × p² bilinear upsampling of a patch, FlexiViT asks that ⟨Bx, ŵ⟩ = ⟨x, w⟩ for every patch x; for p′ ≥ p this holds exactly with ŵ = (Bᵀ)⁺w. Naively resizing w like an image changes its inner products (its norm grows with p′²/p²), so token statistics shift.
- 1. Attention takes half of a layer's compute when N equals…
- 2. Interpolation of position embeddings assumes they are…
- 3. PI-resize guarantees that an upsampled patch gives…
Level 4: Expert
★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.What happens when a ViT trained at one resolution is run at another, and which fixes work?
History.
- A. Dosovitskiy et al., “An image is worth 16x16 words” (ICLR 2021): fine-tuned at higher resolution with 2-D interpolated position embeddings.
- H. Touvron et al., “Fixing the train-test resolution discrepancy” (FixRes, NeurIPS 2019).
- L. Beyer et al., “FlexiViT: one model for all patch sizes” (CVPR 2023); M. Dehghani et al., “Patch n’ Pack: NaViT” (NeurIPS 2023).
Exercise 2. A miniature ViT on synthetic scenes.
- Scenes: a bright target and a dimmer distractor (Gaussian blobs) at random places; the label is the target’s quadrant (4 classes). Scenes are rendered at 16, 24 or 32 px; pixel noise grows with resolution (std 0.2 · S/16) so every resolution carries the same information.
- Model: patch 4, tokens = patch embedding + learned position embedding (16 dimensions), ReLU, mean pooling, linear head; Adam, 300 full-batch steps on 400 images at 16 px (a 4 × 4 grid).
- Tests at 24 and 32 px (6 × 6 and 8 × 8 grids): clip the position grid (reuse edge entries), interpolate it bilinearly, interpolate and fine-tune 30 steps on 200 new images, keep a 4 × 4 grid with larger patches (patch-embedding weights resized naively or with PI-resize), or resize the image down to 16 px.
| test | 16 px (native) | 24 px | 32 px |
|---|---|---|---|
| native model | 0.845 | – | – |
| position grid clipped | – | 0.383 | 0.203 |
| position grid interpolated | – | 0.733 | 0.610 |
| interpolated + 30 fine-tuning steps | – | 0.830 | 0.812 |
| larger patches, naive weight resize | – | 0.637 | 0.403 |
| larger patches, PI-resize | – | 0.787 | 0.802 |
| image resized down to 16 px | – | 0.860 | 0.873 |
- Clipping the grid was catastrophic (0.203 at 32 px, below chance 0.25): most tokens claim the wrong location.
- Interpolation kept most of the accuracy but still lost ground as the grid grew; a short fine-tune at the new resolution recovered most of the rest, the FixRes recipe.
- PI-resize beat naive weight resizing on every seed (32 px: 0.802, 0.752, 0.790 against 0.403, 0.310, 0.532).
- Null result for resolution: the extra pixels carried no extra information here, so simply resizing the image down matched the native model (0.873, 0.865, 0.875 against 0.845, 0.855, 0.900). Higher resolution only pays when the task needs finer detail.
- Seeds 1 and 2: same ranking; at 32 px interpolated 0.502 and 0.775, fine-tuned 0.770 and 0.843, clipped 0.268 and 0.395.
ViTs in AI, robotics and aerospace
- Earth observation: foundation models such as Prithvi (NASA–IBM) and SatMAE use ViTs on multispectral tiles; sensor-specific patch embeddings and position grids for varying ground sampling distance are the same resolution problem as here.
- Robotics: vision-language-action models (RT-2, OpenVLA) feed ViT patch tokens (SigLIP, DINOv2) to a policy; token count sets control latency.
- Onboard inference: on space-qualified or embedded hardware, patch size, resolution and token merging are the main levers for meeting a compute budget.
References
- A. Dosovitskiy et al. (2021). “An image is worth 16x16 words: Transformers for image recognition at scale.” ICLR.
- A. Steiner et al. (2022). “How to train your ViT? Data, augmentation, and regularization in vision transformers.” TMLR.
- H. Touvron, M. Cord and H. Jégou (2022). “DeiT III: revenge of the ViT.” ECCV.
- X. Zhai, A. Kolesnikov, N. Houlsby and L. Beyer (2022). “Scaling vision transformers.” CVPR.
- L. Beyer et al. (2023). “FlexiViT: one model for all patch sizes.” CVPR.
- M. Dehghani et al. (2023). “Patch n’ Pack: NaViT, a vision transformer for any aspect ratio and resolution.” NeurIPS.
- M. Dehghani et al. (2023). “Scaling vision transformers to 22 billion parameters.” ICML.
- T. Darcet, M. Oquab, J. Mairal and P. Bojanowski (2024). “Vision transformers need registers.” ICLR.
- B. Heo et al. (2024). “Rotary position embedding for vision transformer.” ECCV.