Imports
run firstThe lab file's imports. Run this cell first (or press Run all).
Hands-on lab 04 of 10 · Vision Transformer
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).
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.
[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.
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.
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.
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.
L pre-norm blocks, bidirectional (no causal mask) [B, N+1, d]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.
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:
The lab file's imports. Run this cell first (or press Run all).
patchify(images, p)[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).
unpatchify(patches, C, H, W, p)Inverse of patchify: [B, N, C*p*p] → [B, C, H, W].
(DiT, the diffusion transformer, ends with exactly this step.)
class PatchEmbed(nn.Module)forward_conv(x)[B, C, H, W] → [B, N, d] using the strided convolution self.proj.
forward_linear(x)[B, C, H, W] → [B, N, d] using patchify() and a matmul with the SAME weights.
forward_convforward_linearclass ViTConfigclass ViT(nn.Module)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]
vit_shapes(batch, img_size, patch_size, in_chans, dim, n_classes)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).
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).