TExcelTAD

Vision Transformers (ViT)

A transformer reads a sequence of vectors. An image is a grid of pixels. The Vision Transformer (ViT, 2020) connects the two in the most direct way possible: cut the image into square patches, flatten each patch into a vector, project it linearly to the model width, and treat the patches as the tokens of a sentence. Add a learnable class token whose final state is used for the prediction, add position embeddings so the model knows where each patch came from, and run a standard transformer encoder. Nothing in it is specific to images except the first reshape.

That simplicity has a price. A CNN is built to assume that nearby pixels belong together and that a pattern means the same thing anywhere in the image. A ViT assumes neither; it has to learn them from data. This lesson builds the patch pipeline in NumPy, shows that the "linear projection of flattened patches" is a convolution in disguise, and trains a tiny ViT and a small CNN side by side on the course's Digits split.

From image to tokens

8 x 8 image p1 p2 p3 p4 4 patches of 4 x 4 flatten:4 x 16 values Linear 16 to E= Conv2d k4 s4 cls p1 p2 p3 p4 + position embeddings 0 to 4 transformer encoder, L blocks cls output LayerNorm, Linear: 10 logits

For an image of H×WH \times W pixels with CC channels and patch size pp, there are n=HW/p2n = HW / p^2 patches, each flattened to a vector of length Cp2Cp^2. The input sequence to the encoder is

z0=[ xcls; x1WE; x2WE; … ; xnWE ]+P,WE∈RCp2×E, P∈R(n+1)×Ez_0 = \left[\, x_{\text{cls}};\ x_1 W_E;\ x_2 W_E;\ \dots;\ x_n W_E \,\right] + P, \qquad W_E \in \mathbb{R}^{C p^2 \times E},\ P \in \mathbb{R}^{(n+1) \times E}

with one projection WEW_E (plus a bias) shared by all patches, a learned class-token vector xclsx_{\text{cls}}, and learned positions PP. After LL blocks, the class token's output zL(0)z_L^{(0)} goes through a final LayerNorm and a linear head. The class token has no pixels of its own: it is a query that, layer by layer, gathers what the classifier needs from the patches. (Averaging all patch outputs instead, "mean pooling", works about as well and is common in later models.)

The patch projection is a convolution. Applying the same linear map to every non-overlapping p×pp \times p patch is exactly what a Conv2d with EE output channels, kernel size pp and stride pp computes: the kernel visits each patch once, and its EE filters are the EE columns of WEW_E. Implementations use the convolution because it is fast and needs no reshape; the output (B, E, H/p, W/p) is flattened to (B, n, E).

Patching in NumPy

Patching is a reshape and a transpose. Splitting (B, 8, 8) into (B, 2, 4, 2, 4) separates "which block of rows, which row inside it" and the same for columns; moving the two inner axes to the end and flattening gives one row per patch. The example patches three digits, embeds them, checks the embedding against an explicit stride-4 convolution, and assembles the encoder's input.

python · try it yourself
import numpy as np
from sklearn.datasets import load_digits

X, y = load_digits(return_X_y=True)
imgs = (X / 16.0).reshape(-1, 8, 8)
img = imgs[:3]                                     # a batch of 3 images, (B, 8, 8)
print("label of image 0:", int(y[0]))
for row in (imgs[0] * 9).round().astype(int):
    print(" ".join(str(v) for v in row))

def patchify(x, p):                                # (B, H, W) -> (B, n, p*p)
    B, H, W = x.shape
    x = x.reshape(B, H // p, p, W // p, p)         # split rows and columns into blocks
    x = x.transpose(0, 1, 3, 2, 4)                 # (B, rows of patches, cols of patches, p, p)
    return x.reshape(B, (H // p) * (W // p), p * p)

P = patchify(img, 4)
print("4x4 patches:", P.shape, " 2x2 patches:", patchify(img, 2).shape)
print("patch 1 (top right) is img[0, :4, 4:]:", np.array_equal(P[0, 1], img[0, :4, 4:].ravel()))

# Linear patch embedding: one weight matrix shared by all patches.
rng = np.random.default_rng(0)
E = 6
W, b = rng.normal(size=(16, E)), rng.normal(size=E)
tokens = P @ W + b                                 # (B, 4, E)

# The same as a convolution with kernel 4 and stride 4: slide the kernel, no overlap.
K = W.T.reshape(E, 4, 4)                           # E kernels of size 4 x 4
conv = np.zeros((3, E, 2, 2))
for i in range(2):
    for j in range(2):
        window = img[:, 4 * i:4 * i + 4, 4 * j:4 * j + 4]           # (B, 4, 4)
        conv[:, :, i, j] = np.einsum("bhw,ehw->be", window, K) + b
print("conv output (B, E, 2, 2) flattened == tokens:",
      np.allclose(conv.reshape(3, E, 4).transpose(0, 2, 1), tokens))

# Prepend a class token and add learned position embeddings.
cls = rng.normal(size=(1, 1, E))
pos = rng.normal(0, 0.02, size=(1, 4 + 1, E))
seq = np.concatenate([np.repeat(cls, 3, axis=0), tokens], axis=1) + pos
print("sequence into the encoder:", seq.shape)
label of image 0: 0
0 0 3 7 5 1 0 0
0 0 7 8 6 8 3 0
0 2 8 1 0 6 4 0
0 2 7 0 0 4 4 0
0 3 4 0 0 5 4 0
0 2 6 0 1 7 4 0
0 1 8 3 6 7 0 0
0 0 3 7 6 0 0 0
4x4 patches: (3, 4, 16)  2x2 patches: (3, 16, 4)
patch 1 (top right) is img[0, :4, 4:]: True
conv output (B, E, 2, 2) flattened == tokens: True
sequence into the encoder: (3, 5, 6)

The printout is the first digit (a 0) scaled to 0 to 9. Patches are numbered row by row, so patch 1 is the top-right quarter, and the check confirms the reshape put the right pixels in it. The convolution loop and the matrix product agree, and with the class token the sequence has 4+1=54 + 1 = 5 tokens of width E=6E = 6.

Patch size: tokens, parameters and cost

The patch size is the ViT's most important design choice. Smaller patches mean more tokens: finer detail, but attention maps that grow with the square of the token count.

python · try it yourself
import numpy as np

def vit_sizes(H, p, C, E):
    n = (H // p) ** 2                    # patches = tokens (plus one class token)
    embed = C * p * p * E + E            # the patch projection (a Conv2d with stride p)
    pos = (n + 1) * E                    # learned position embeddings
    return n, embed, pos, (n + 1) ** 2   # last: entries of one attention map

print("Digits 8x8, 1 channel, E = 64")
for p in (1, 2, 4, 8):
    n, embed, pos, att = vit_sizes(8, p, 1, 64)
    print(f"  patch size {p}: patches {n:2d}, embedding {embed:5d} + positions {pos:5d} = {embed + pos:5d} params, attention map {att:5d}")
n, embed, pos, att = vit_sizes(224, 16, 3, 768)
print(f"ViT-B/16 on 224x224 RGB: {n} patches, patch vector {3 * 16 * 16}, embedding {embed:,} params, attention map {att:,}")
n, _, _, att = vit_sizes(224, 8, 3, 768)
print(f"patch 8 instead: {n} patches, attention map {att:,} ({att / 197 ** 2:.1f}x)")
Digits 8x8, 1 channel, E = 64
  patch size 1: patches 64, embedding   128 + positions  4160 =  4288 params, attention map  4225
  patch size 2: patches 16, embedding   320 + positions  1088 =  1408 params, attention map   289
  patch size 4: patches  4, embedding  1088 + positions   320 =  1408 params, attention map    25
  patch size 8: patches  1, embedding  4160 + positions   128 =  4288 params, attention map     4
ViT-B/16 on 224x224 RGB: 196 patches, patch vector 768, embedding 590,592 params, attention map 38,809
patch 8 instead: 784 patches, attention map 616,225 (15.9x)

On Digits, 2 ×\times 2 patches give 16 tokens and 4 ×\times 4 give 4. Curiously, both need the same 14081408 parameters for embedding plus positions (a larger projection, fewer positions), so the two ViTs trained below have identical sizes. Patch size 1 treats every pixel as a token: 65 tokens with the class token, an attention map of 4225 entries per head per image. The standard ViT-B/16 cuts a 224 ×\times 224 RGB image into 196 patches of 3⋅16⋅16=7683 \cdot 16 \cdot 16 = 768 values; halving the patch size to 8 quadruples the tokens to 784 and multiplies the attention map by 15.9.

A tiny ViT against a small CNN

The recorded example (PyTorch, CPU) uses the course's Digits split: 1077 training, 360 validation and 360 test images, the test set left untouched (it is used once, in the mini-project). It first checks the Conv2d-equals-Linear claim in PyTorch with unfold. Then three models are trained with the same recipe (AdamW, peak learning rate 0.002 with a one-cycle warm-up and decay, weight decay 0.05, batch 64, 30 epochs, no augmentation, the same seed):

  • a CNN with two 3 ×\times 3 conv layers (16 and 32 channels), max pooling and a 2-layer head, 13,706 parameters;
  • a ViT with E=64E = 64, 4 heads, 2 pre-norm blocks with GELU MLPs of width 128, a class token and learned positions, with 2 ×\times 2 patches and with 4 ×\times 4 patches, 69,194 parameters each.

To see how each one copes with less data, each is also trained on only the first 270 training images (60 epochs, so the number of updates is similar). Every number is accuracy on the 360 validation images after the last epoch, with no picking of the best epoch.

python · try it yourself
import torch
from torch import nn
import torch.nn.functional as F
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

torch.manual_seed(0)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
X, y = load_digits(return_X_y=True)
X = X / 16.0                                   # pixels in [0, 1]
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
img = lambda a: torch.tensor(a, dtype=torch.float32).reshape(-1, 1, 8, 8)
Xtr, Xva = img(X_tr), img(X_va)
ytr, yva = torch.tensor(y_tr), torch.tensor(y_va)

# The patch embedding is a convolution with stride = kernel = patch size.
conv = nn.Conv2d(1, 8, kernel_size=4, stride=4)
x = Xtr[:5]
patches = x.unfold(2, 4, 4).unfold(3, 4, 4)                     # (B, C, 2, 2, 4, 4)
patches = patches.permute(0, 2, 3, 1, 4, 5).reshape(5, 4, 16)    # (B, n patches, C*4*4)
linear = patches @ conv.weight.reshape(8, -1).T + conv.bias      # a Linear layer on flat patches
print("Conv2d patch embedding == Linear on patches:",
      torch.allclose(conv(x).flatten(2).transpose(1, 2), linear, atol=1e-6))

class ViT(nn.Module):
    def __init__(self, patch=2, E=64, heads=4, layers=2, classes=10):
        super().__init__()
        n = (8 // patch) ** 2                                         # number of patches
        self.embed = nn.Conv2d(1, E, kernel_size=patch, stride=patch)  # = Linear on flattened patches
        self.cls = nn.Parameter(torch.zeros(1, 1, E))
        self.pos = nn.Parameter(torch.randn(1, n + 1, E) * 0.02)       # learned positions
        layer = nn.TransformerEncoderLayer(E, heads, 2 * E, dropout=0.0, activation="gelu",
                                           batch_first=True, norm_first=True)
        self.encoder = nn.TransformerEncoder(layer, layers, enable_nested_tensor=False)
        self.norm = nn.LayerNorm(E)
        self.head = nn.Linear(E, classes)

    def forward(self, x):                                  # x: (B, 1, 8, 8)
        t = self.embed(x).flatten(2).transpose(1, 2)       # (B, n, E): one token per patch
        t = torch.cat([self.cls.expand(len(x), -1, -1), t], dim=1) + self.pos
        return self.head(self.norm(self.encoder(t)[:, 0]))  # classify from the class token

class CNN(nn.Module):
    def __init__(self):
        super().__init__()
        self.net = nn.Sequential(
            nn.Conv2d(1, 16, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),     # 16 x 4 x 4
            nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),    # 32 x 2 x 2
            nn.Flatten(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 10))

    def forward(self, x):
        return self.net(x)

def train(model, Xtr, ytr, epochs=30, lr=2e-3):
    torch.manual_seed(0)
    opt = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=0.05)
    sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=lr, total_steps=epochs * ((len(Xtr) + 63) // 64), pct_start=0.1)
    for epoch in range(epochs):
        model.train()
        perm = torch.randperm(len(Xtr))
        for i in range(0, len(Xtr), 64):
            idx = perm[i:i + 64]
            loss = F.cross_entropy(model(Xtr[idx].to(device)), ytr[idx].to(device))
            opt.zero_grad(); loss.backward(); opt.step(); sched.step()
        model.eval()
        with torch.no_grad():
            acc = (model(Xva.to(device)).argmax(1).cpu() == yva).float().mean().item()
    return acc

count = lambda m: sum(p.numel() for p in m.parameters())
for name, make in [("CNN", CNN), ("ViT, 2x2 patches", lambda: ViT(patch=2)), ("ViT, 4x4 patches", lambda: ViT(patch=4))]:
    accs = []
    for n in (len(Xtr), 270):                        # all 1077 training images, then a quarter
        torch.manual_seed(0)
        model = make().to(device)
        accs.append(train(model, Xtr[:n], ytr[:n], epochs=30 if n > 300 else 60))
    print(f"{name:17s} {count(model):6d} parameters  validation accuracy: 1077 images {accs[0]:.3f}, 270 images {accs[1]:.3f}")
Conv2d patch embedding == Linear on patches: True
CNN                13706 parameters  validation accuracy: 1077 images 0.978, 270 images 0.939
ViT, 2x2 patches   69194 parameters  validation accuracy: 1077 images 0.964, 270 images 0.867
ViT, 4x4 patches   69194 parameters  validation accuracy: 1077 images 0.969, 270 images 0.933

With all 1077 images the three are close: the CNN reaches 0.978, the ViTs 0.964 and 0.969. On 360 validation images one image is 0.003, so these differ by 3 to 5 images, and a single seed cannot rank them reliably. With 270 images the picture is clearer: the CNN keeps 0.939, the 4 ×\times 4 ViT 0.933, and the 2 ×\times 2 ViT, which must learn relationships between 16 tiny patches from scratch, drops to 0.867. The CNN does this with a fifth of the parameters.

Inductive bias and data hunger

The difference is inductive bias: what the architecture assumes before seeing any data.

CNN ViT
locality built in: a 3 ×\times 3 kernel sees only neighbours none: every patch attends to every patch from layer 1
translation equivariance built in: the same kernel slides everywhere only inside a patch; positions are learned embeddings
receptive field grows layer by layer global from the first layer
what it needs modest data a lot of data, or strong augmentation, or pretraining

Strong assumptions are a gift when they are true and the data is small: the CNN does not have to discover that neighbouring pixels matter. On ImageNet-size data the original ViT was behind comparable ResNets, and it pulled ahead only when pretrained on far larger datasets (tens to hundreds of millions of images), where the flexibility of global attention pays off. Later recipes narrowed the gap on ImageNet alone with heavy augmentation, regularisation and distillation; hybrids put convolutions back in (a conv stem instead of the patch projection, or local windows of attention as in Swin). In practice you rarely train a ViT from scratch: you fine-tune a pretrained one, as in transfer learning. Detection, segmentation and pretrained vision backbones are covered in Computer Vision.

Pitfalls

  • Wrong patch order. x.reshape(B, n, p * p) without the transpose cuts the image into strips of rows, not squares; it runs and silently trains worse. Check one patch against the image slice, as the NumPy example does.
  • Image size not divisible by the patch size. The stride-pp convolution silently drops the leftover border pixels. Resize or pad the images first.
  • Position embeddings at a new resolution. A ViT trained at 224224 with 196 positions cannot take 384-pixel images (576 patches) directly; the usual fix is to interpolate the position grid in 2-D before fine-tuning.
  • Comparing architectures with different recipes. A ViT with augmentation and a long schedule against a CNN trained for 5 epochs proves nothing. Same data, same budget, same evaluation, several seeds.
  • Forgetting the final LayerNorm before the head in a pre-norm encoder, or classifying from a patch token instead of the class token.
  • Reading single-seed differences of a few images as a ranking. On 360 validation images, 1% is 3.6 images.

Practice

  1. A 32 ×\times 32 RGB image (CIFAR size) goes into a ViT with patch size 4 and E=192E = 192. How many tokens enter the encoder, how long is each flattened patch, and how many parameters does the patch embedding have?
Answer

(32/4)2=64(32/4)^2 = 64 patches plus the class token = 65 tokens. Each patch has 3⋅4⋅4=483 \cdot 4 \cdot 4 = 48 values. The embedding has 48⋅192+192=9,40848 \cdot 192 + 192 = 9{,}408 parameters, plus 65⋅192=12,48065 \cdot 192 = 12{,}480 for the positions.

  1. Replace the class token by mean pooling over the patch outputs. Which lines of the ViT class change?
Answer

Drop self.cls and the torch.cat (the positions then have shape (1, n, E)), and classify from self.norm(self.encoder(t).mean(dim=1)) instead of [:, 0].

  1. Why do the 2 ×\times 2 and 4 ×\times 4 ViTs have exactly the same number of parameters, while the 1 ×\times 1 version would have more?
Answer

Everything except the embedding and the positions is independent of the patch size. Embedding plus positions is (p2E+E)+(n+1)E(p^2 E + E) + (n + 1)E with n=64/p2n = 64/p^2: for p=2p = 2 that is 5E+17E=22E5E + 17E = 22E and for p=4p = 4 it is 17E+5E=22E17E + 5E = 22E, both 1408 for E=64E = 64. For p=1p = 1 it is 2E+65E=67E=42882E + 65E = 67E = 4288.

  1. On the 270-image run, name two changes that should help the ViT more than the CNN, and say how you would test them honestly.
Answer

Data augmentation (small shifts and rotations of the digits, which teach the invariances the ViT lacks) and pretraining on more data (for example self-supervised on unlabelled digits) or distillation from the CNN. Test each by training both models with and without it, on the same split, with several seeds, comparing validation accuracy only; the test set stays untouched until the final choice.

Test yourself

A ViT's patch embedding with patch size pp is equivalent to…

  1. a max-pooling layer with stride pp
  2. a Conv2d with kernel size pp and stride pp
  3. a Conv2d with kernel 3 and stride 1
  4. a LayerNorm over each patch

An 8 ×\times 8 image with 2 ×\times 2 patches and a class token gives how many tokens?

  1. 4
  2. 16
  3. 17
  4. 65

What happens to the size of one attention map when the patch size is halved?

  1. It halves
  2. It doubles
  3. It grows about 16 times
  4. It does not change

On the 270-image Digits run, the CNN scored 0.939 and the 2 ×\times 2 ViT 0.867. What is the best explanation?

  1. Transformers cannot classify images
  2. The CNN's built-in locality and translation equivariance substitute for data the ViT does not have
  3. The ViT had fewer parameters
  4. The CNN was evaluated on the training set