Unit 5 of 7 · about 3 hours · implement

Patch embeddings and positional information

Patches turn an image into a token sequence. The grid position that convolution got for free must be added back before attention can use it.

You'll be able to

  • Implement patch extraction as stride-equals-size convolution and verify count, order and flat dimension.
  • Explain where positional information enters a ViT and why attention needs it.
  • Predict token counts and attention-cost scaling when patch size or resolution changes.

Covers

Image layout, patches and patch embeddingsPositional information for patch encoders
1

Read

In this order, only the parts listed

0 of 3 done

  1. Patch embedding as strided convolutionD2L - Vision Transformer

    Model plus Patch Embedding sections: patches flattened to ; single convolution with kernel size and stride set to patch size; worked example img_size 96 with patch 16 gives 36 patches of shape (4, 36, 512)

  2. Class token, positions and pre-norm blocksD2L - Vision Transformer

    Putting It All Together and Vision Transformer Encoder: cls_token plus learnable pos_embedding over num_patches + 1 positions; ViTBlock pre-normalization; head reads X[:, 0]

  3. Vision transformers and scaleUnderstanding Deep Learning - representation foundations

    Sections 12.10.2-12.10.3 (pp. 229-232): patches with learned linear map and learned 1D positional encodings; Figure 12.17; SWin multi-scale windows in Figure 12.18

2

Focus on

  • Patchify is a disjoint row-major grid: by patches, each flattened to values (768 for 3-channel 16px patches).
  • One convolution with kernel equal to stride equal to patch size does extraction plus projection; D2L output keeps one vector per patch.
  • Self-attention is permutation-equivariant, so order must be injected. D2L learns pos_embedding from random init; the UDL ViT learns 1D encodings too.
  • Halving patch size quadruples tokens, multiplies attention-score work by 16, and multiplies per-token projection and MLP work by 4.
Common mistakes · 3
  • Using overlapping patches by default. ViT and D2L use stride equal to patch size, so patches are disjoint.
  • Equating the cls representation with patch averaging. The cls token is learned aggregation; D2L Exercise 2 asks you to implement averaging as an experiment, not an identity.
  • Assuming sinusoidal positions. Both D2L and the UDL ViT learn positional embeddings, so 2D layout must be learned from data.
3

Try it yourself

Closed-book, before checking anything

From a blank file, patchify a single-channel image with patch size 1 and show row-major order . Then derive the (4, 36, 512) output shape from img_size 96 and patch 16.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1. image, patch 16: patches and tokens?Answer

    196 patches, 197 tokens with cls.

  2. 2.Why does a ViT need positional embeddings when a CNN needs none?Answer

    Attention is permutation-equivariant (UDL Problem 12.3), so it cannot see order; convolution bakes locality and translation structure into the operation.

  3. 3.Patch size 16 to 8 at fixed resolution: how does attention work scale?Answer

    Tokens quadruple, so the attention matrix grows 16-fold.

  4. 4.What does LazyConv2d with kernel 16 and stride 16 compute on the worked example?Answer

    Patch extraction plus learned projection to 512-d, giving (4, 36, 512) for batch 4.

5

Practice

  • TensorTonic: Patchify a Batch of Images

    Named problem on the free language-modeling-from-scratch plan: split image batches into a row-major grid of non-overlapping flattened patches.

    Match D2L patch count and ordering before adding any learned projection.

  • D2L Vision Transformer exercises

    Exercises: img_size versus training time, averaged-patch head instead of cls, and hyperparameter tuning for accuracy.

You're done when

Your patchify matches the D2L shape assertions with row-major order, and you predict tokens and attention scaling for a new patch size without notes.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 6 more in the section
  • Understanding Deep Learning - representation foundationsSimon J. D. Prince · primary

    Use 9.3.6-9.3.7 for transfer and self-supervision, 12.9-12.10 for image transformers, and 13.1-13.4 plus 13.10 for GNN vocabulary. Open notebooks 9.4, 12.4 and 13.1 only when a figure or mechanism is unclear.

  • D2L - Vision TransformerD2L authors · required

    Use vision-transformer.md for patch extraction, patch embeddings and a tested small encoder. Add a compact SimCLR-style or paired-data contrastive objective in the explicit training loop from Sections 2 and 3.

Also in this section