Skip to content
HasanAI
Log in Sign up

πŸ–ΌοΈ ViT: An Image is Worth 16x16 Words

Cut the image into patches and hand them to a plain Transformer
Ten Landmark Papers Intermediate
Contents

    ViT: An Image is Worth 16Γ—16 Words (Dosovitskiy et al., 2020)

    For a decade, vision meant convolutions. A CNN builds in two assumptions about images: locality (nearby pixels matter together) and translation equivariance (a cat is a cat wherever it appears). Those assumptions are why CNNs learn well from limited data.

    The Vision Transformer asks what happens if you drop both. Cut the image into 16Γ—16 patches, flatten each into a vector, treat the sequence of patches like the words of a sentence, and hand it to an unmodified Transformer encoder. The answer the paper gives has two halves:

    • Trained on ImageNet alone (1.3M images), ViT loses to comparable ResNets.
    • Pre-trained on 14M (ImageNet-21k) or 300M (JFT-300M) images, it wins, and at lower pre-training cost. ViT-H/14 reached 88.55% top-1 on ImageNet.

    Large-scale training trumps inductive bias. This page builds the patch pipeline, counts the paper's model sizes, and reproduces the data-hunger result at small scale.

    helpers ready

    1. From image to token sequence

    For an image of size $H \times W \times C$ and patch size $P$:

    $$N = \frac{HW}{P^2} \text{ patches}, \qquad \text{each flattened to } P^2 C \text{ numbers}$$

    A 224Γ—224 RGB image with $P = 16$ gives $14 \times 14 = 196$ patches of $16 \cdot 16 \cdot 3 = 768$ numbers each. A learned linear map, the patch embedding, projects each to the model width $D$. A learnable [class] token is prepended, as in BERT, giving 197 tokens, and a learned position embedding is added to each.

    The patch split is just a reshape. The cell checks that it matches cutting the patches out by hand.

    ==============================================================================
      PATCHIFY A 224 x 224 x 3 IMAGE
    ==============================================================================
      image (224, 224, 3)  ->  sequence (196, 768)  (patches x numbers per patch)
      [PASS] reshape-based patchify == slicing patches out one by one, row-major
      plus [class] token: 197 tokens per image
      patch 16 -> 196 tokens;  patch 14 -> 256;  patch 32 -> 49
      Halving the patch size quadruples the sequence length, and attention cost grows with its square.

    2. The paper's models, counted

    Model Layers Width $D$ MLP Heads Paper
    ViT-Base 12 768 3072 12 86M
    ViT-Large 24 1024 4096 16 307M
    ViT-Huge 32 1280 5120 16 632M

    "ViT-L/16" means the Large model with 16Γ—16 patches. Counting the patch embedding, [class] token, position table, encoder layers and final layer norm, and leaving out the task-specific classification head:

    ==============================================================================
      COUNTING ViT PARAMETERS (224 x 224 input, no classification head)
    ==============================================================================
      ViT-B/16     85,798,656  =   85.8M   (paper: 86M, -0.2%)
      ViT-L/16    303,301,632  =  303.3M   (paper: 307M, -1.2%)
      ViT-H/14    630,764,800  =  630.8M   (paper: 632M, -0.2%)
    
      Nearly all of it is the encoder: the patch embedding of ViT-B/16 is only 0.7% of the total.

    3. Data hunger, reproduced in miniature

    The paper's central finding is a crossover. With little data the CNN's built-in assumptions help, and ViT, which must learn that neighbouring pixels are related, falls behind. With enough data that handicap disappears.

    The miniature version: 8Γ—8 digits, a small ViT (2Γ—2 patches, so 16 tokens, plus [class]; 4 layers, $D = 64$) against a small CNN with a comparable parameter count. Both are trained on 100, 300 and 1,000 images and tested on the same 597 held-out images, averaged over 3 seeds.

    ViT parameters: 136,138   CNN parameters: 124,778
    ==============================================================================
      ViT vs CNN AS THE TRAINING SET GROWS
    ==============================================================================
        100 training images:  CNN 0.915 Β± 0.011   ViT 0.592 Β± 0.025   CNN lead +32.2 points
        300 training images:  CNN 0.969 Β± 0.002   ViT 0.838 Β± 0.020   CNN lead +13.2 points
       1000 training images:  CNN 0.987 Β± 0.005   ViT 0.924 Β± 0.015   CNN lead +6.3 points
      [PASS] with 100 images the CNN leads
      [PASS] the CNN's lead shrinks as data grows (100 -> 1,000 images)

    4. What the position embeddings learned

    ViT's position embeddings are plain learned vectors, one per patch slot, with no built-in notion of 2-D layout. The paper's Figure 7 shows that after training on large data they rediscover the grid: each position's embedding is most similar to those in the same row and column.

    The cell measures the same thing on the model trained with 1,000 images. It takes the cosine similarity between every pair of position embeddings and correlates it with how close the two patches are on the 4Γ—4 grid.

    ==============================================================================
      DO THE LEARNED POSITIONS KNOW THE 2-D LAYOUT?
    ==============================================================================
      correlation between embedding similarity and grid closeness: r = 0.342
      patches 1 step  apart: mean cosine similarity +0.340
      patches 2 steps apart: mean cosine similarity -0.090
      patches 3 steps apart: mean cosine similarity -0.207
      patches 4 steps apart: mean cosine similarity -0.125
      [PASS] neighbouring patches have more similar embeddings than distant ones (r > 0)

    5. Where the [class] token looks

    In the last layer, the [class] token's attention weights over the 16 patches show which parts of the image the classification draws on. The animation steps through test digits, showing the trained model's real attention (averaged over heads) as a heat overlay.

    Summary

    • ViT turns an image into a sequence: $HW/P^2$ flattened patches, linearly embedded, plus a [class] token and learned positions. The rest is a standard Transformer encoder. The reshape-based patchify was checked against cutting patches out by hand.
    • Counted from their configurations, ViT-B/16, L/16 and H/14 come to 85.8M, 303M and 631M parameters, matching the paper's 86M, 307M and 632M to within about 1%.
    • Without convolutions' locality and translation equivariance, ViT needs more data. In miniature, a CNN of similar size led at 100 training images and its lead shrank as data grew, the same direction as the paper's crossover at ImageNet-21k / JFT scale.
    • The learned position embeddings partly recovered the 2-D layout on their own, even at this size: neighbouring patches average +0.34 cosine similarity and patches three steps apart -0.21 (correlation with grid closeness r = 0.34).
    • Descendants: DeiT (data-efficient training with distillation), Swin (local windows, which reintroduce some locality), MAE (BERT-style masked pre-training for images), and the vision encoders of today's multimodal models.

    References

    1. An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale β€” Dosovitskiy et al., 2020 (ICLR 2021)