Looking for the lab runner…

Hands-on lab 04 of 10 · Vision Transformer

The Vision Transformer front end and forward pass

Turn an image into a sequence of tokens and classify it with a transformer encoder. You implement patchify twice (pure reshapes, and a strided Conv2d) and show they are the same linear map, then the CLS token, the position embeddings, the forward pass, and a shape tracker. The transformer blocks themselves are torch's (you built one in lab 02).

Time: 45-60 minCheck: python labs/check.py 4

The maths, step by step

B batch, C channels, H x W image, P patch size (argument p in the code), d width, K classes (as in the ViT guide). N counts patches; N+1 tokens with CLS.

  1. 1
    Patchify
    [B, C, H, W] → [B, N, C*P*P],   N = (H/P) * (W/P)

    cut the image into non-overlapping P x P tiles, row by row; flatten each tile in (channel, row, column) order.

  2. 2
    Patch embed
    tokens = patches @ W_e^T + b       W_e: [d, C*P*P]  → [B, N, d]

    Identical to Conv2d(C, d, kernel_size=P, stride=P): the kernel visits each tile once and takes a dot product with it. conv.weight [d, C, P, P] reshaped to [d, C*P*P] is W_e.

  3. 3
    CLS token
    prepend one learned vector:  [B, N, d] → [B, N+1, d]

    It owns no patch; through attention it gathers a summary of the whole image, and the classifier reads only it.

  4. 4
    Positions
    x = x + pos_embed                  pos_embed: [1, N+1, d]

    Attention is permutation-equivariant: without this, shuffling the patches would not change the CLS output.

  5. 5
    Encoder
    L pre-norm blocks, bidirectional (no causal mask)  [B, N+1, d]
  6. 6
    Head
    LayerNorm, take token 0 (CLS), Linear(d, K)        [B, K]
ViT-B/16 at 224 x 224: N = 14 * 14 = 196 patches, 197 tokens, d = 768.

Read alongside

How to work on this page

  1. Write each function in its cell, in order. The hints open one at a time: try Hint 1 first.
  2. ▶ Run (Ctrl/⌘+Enter) defines the cell in this lab's Python process; variables persist between cells, as in a notebook. Try your functions in the scratch cell at the bottom.
  3. ✓ Run checks saves the file and runs python labs/check.py 4: each step turns from TODO to PASS. A FAIL shows what was expected.
  4. Save (Ctrl/⌘+S) writes all cells to labs/lab04_vit.py (the previous version is kept in labs/.backup/), so you can also continue in any editor. After ↺ Reset kernel, press ▶ Run all.

Editor keys: Tab / Shift+Tab indent and dedent by 4 spaces, Enter keeps the indentation, Shift+Enter runs the cell and moves to the next one.

Cells on this page:

0 Imports

Imports

run first

The lab file's imports. Run this cell first (or press Run all).

1 patchify with reshapes (and its inverse)

patchify(images, p)

to write

[B, C, H, W] → [B, N, C*p*p].

Patch n = (row r, column c) of the patch grid, n = r * (W/p) + c. Its vector is images[b, :, r*p:(r+1)*p, c*p:(c+1)*p].reshape(-1), i.e. ordered (channel, row inside the patch, column inside the patch).

Hint 1
split H into (H/p, p) and W into (W/p, p) with one .reshape: [B, C, H/p, p, W/p, p].
Hint 2
move the two grid dims to the front of each sample and the three per-patch dims (C, p, p) to the back: permute(0, 2, 4, 1, 3, 5).
Hint 3
images.reshape(B, C, H // p, p, W // p, p).permute(0, 2, 4, 1, 3, 5) .reshape(B, (H // p) * (W // p), C * p * p)

unpatchify(patches, C, H, W, p)

to write

Inverse of patchify: [B, N, C*p*p] → [B, C, H, W].

(DiT, the diffusion transformer, ends with exactly this step.)

Hint 1
run patchify's steps backwards: reshape, inverse permute, reshape.
Hint 2
[B, gh, gw, C, p, p] -> permute(0, 3, 1, 4, 2, 5) -> [B, C, gh, p, gw, p]

2 patch embedding, two ways

class PatchEmbed(nn.Module)

to write

Write forward_conv(x)

[B, C, H, W] → [B, N, d] using the strided convolution self.proj.

Write forward_linear(x)

[B, C, H, W] → [B, N, d] using patchify() and a matmul with the SAME weights.

Hints for forward_conv
Hint 1
self.proj(x) is [B, d, H/p, W/p]: a d-channel feature map, one pixel per patch.
Hint 2
flatten the two grid dims, then put tokens before channels.
Hint 3
return self.proj(x).flatten(2).transpose(1, 2)
Hints for forward_linear
Hint 1
the conv weight [d, C, p, p] flattened to [d, C*p*p] is a Linear weight whose input order (C, p, p) matches your patchify.
Hint 2
w = self.proj.weight.reshape(self.proj.out_channels, -1)
Hint 3
return patchify(x, self.patch_size) @ w.T + self.proj.bias

3 the ViT forward pass (CLS token, position embeddings, encoder, head)

class ViTConfig

given
Show the given code (it is already written: just run it)

class ViT(nn.Module)

to write

Write forward(images, trace=None)

images [B, C, H, W] → logits [B, n_classes].

If trace is a dict, also record tuple(shape) under these keys:

"input"         the images                       [B, C, H, W]
"patch_tokens"  after patch embedding            [B, N, d]
"tokens"        after CLS + position embeddings  [B, N+1, d]
"encoded"       after the blocks and self.norm   [B, N+1, d]
"cls"           the CLS feature                  [B, d]
"logits"        the output                       [B, n_classes]
Hint 1
order: patch_embed -> prepend CLS -> add pos_embed -> blocks -> norm -> take token 0 -> head. Each block is called as x = block(x).
Hint 2
the CLS parameter is [1, 1, d]; give every sample its copy with self.cls_token.expand(B, -1, -1), then torch.cat([cls, x], dim=1). CLS goes FIRST, at index 0, which is where the head reads it.
Hint 3
to record a shape: if trace is not None: trace["tokens"] = tuple(x.shape)

4 predict the shapes without running anything

vit_shapes(batch, img_size, patch_size, in_chans, dim, n_classes)

to write

Return the shapes forward() records in trace, computed by hand (tuples of ints).

Example: vit_shapes(1, 224, 16, 3, 768, 1000)["tokens"] == (1, 197, 768).

Hint 1
N = (img_size // patch_size) ** 2; the CLS token adds one.
Hint 2
return {"input": (batch, in_chans, img_size, img_size), "patch_tokens": (batch, N, dim), ...} (six keys)

✎ Scratch cell

Experiment here: print shapes, call your functions on small inputs. This cell runs in the same Python process as the cells above, is not part of Run all and is not saved to the lab file (your browser keeps it).