7 routes42 sections324 units

Unit 5.5 · about 3 h

204 / 324

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.

  • implement

You can now

  • 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 embeddings
  • Positional information for patch encoders

Study, in this order

3 steps

  1. Patch embedding as strided convolution
    D2L - Vision Transformer

    Model plus Patch Embedding sections: \(m = hw/p^2\) patches flattened to \(cp^2\); 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 blocks
    D2L - 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 scale
    Understanding Deep Learning - representation foundations

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

Focus on

  • Patchify is a disjoint row-major grid: \((H/p)\) by \((W/p)\) patches, each flattened to \(Cp^2\) 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.

Reproduce closed-book

From a blank file, patchify a \(2 \times 2\) single-channel image with patch size 1 and show row-major order \(\left[\begin{smallmatrix}0&1&2&3\end{smallmatrix}\right]\). Then derive the (4, 36, 512) output shape from img_size 96 and patch 16.

Traps

  • 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.

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.

Self-test

  1. \(224 \times 224\) image, patch 16: patches and tokens?

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

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

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

Completion criterion

Stop 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.

Mark passed, then open 5.6 Only mark this when you can do it without notes.

Leads to

Comes after

Resources for this unit

  • Understanding Deep Learning - representation foundations
    Simon J. D. Princeprimarytheory
    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 Transformer
    D2L authorsrequiredimplementation
    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

Quick find

Search Michi

Type to search every route, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels