patch-embedding -- ViT: image → patches → tokens

The kind of model behind a chatbot reads a list of items, so an image has to become a list before one can look at it. It is cut into a grid of small squares — sixteen pixels on a side is common — and each square's raw pixel values are flattened into one long row and multiplied by a shared table that turns them into a row of numbers of a fixed length, exactly the kind of row a word becomes. From then on the model has no idea it is looking at a picture; it is doing what it does to a sentence. Smaller squares mean finer detail and a longer list. Halving the square size makes four times as many patches, and attention over those patches costs sixteen times as much. Once the class token is on the list, the same cut costs less than sixteen times.

Interactive page: the Vision Transformer (ViT) patch embedding -- how an image becomes a sequence of tokens a transformer can consume. Anchor: F (CNN / vision), the CNN→transformer bridge; Family F, builds on convolution.

What it shows

A ViT has no convolutions in its trunk, so the image must be turned into tokens:

  1. Patchify -- cut the S×S×3 image into a grid of non-overlapping P×P patches (N = (S/P)² of them).
  2. Flatten + project -- each patch is P·P·3 raw numbers; a shared linear matrix W (D × P²·3) maps it to a D-dim token: token = W·flatten. This is mathematically identical to a single Conv2d with kernel = stride = P -- the CNN→transformer bridge.
  3. CLS + position -- a learnable [CLS] token is prepended and a positional embedding pos[i] is added to each token (a transformer is otherwise order-blind), giving a length-N+1 sequence of D-dim tokens.

The page shows the gridded image, the selected patch flattening → projecting → landing as one column in the token-sequence heatmap ([CLS] + N patch tokens, D rows). Smaller P → more, smaller patches → a longer sequence. The patch count grows as 1/P², so attention over the patches grows as 1/P⁴: halving P costs sixteen times as much on the patches, and less than that once the class token is counted.

Drag on the image (or the slider) to pick a patch and watch its token light up in the sequence; tune the patch size P, embed dim D, image preset, seed; the rasterize-to-tokens sweep animates; hover a patch or a sequence column to inspect.

Render tier

T2 (Canvas2D: the procedurally-rendered image via an offscreen canvas + the patch/projection/token panels + the token-sequence heatmap).

Wiring

layout.mount + controls (preset, P, D, patch, seed) + animate (the rasterize sweep) + onPointer drag-to-pick-patch + hover. ?preset / ?P / ?D / ?patch / ?seed / ?hover hooks. Source: page.js.