Vision Transformer › Worked Example: Tracing a Patch Through ViT
Language AI HandbookAll chapters Vision Transformer › Worked Example: Tracing a Patch Through ViTOne section · Sections in this chapter9 / 14 ↓
Reading tools Definitions & inline links
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
To solidify the mechanics, let's trace a single patch from raw pixels all the way to the transformer encoder output, working through the dimensions explicitly.
Consider an RGB image of size and a model configuration of patch size , embedding dimension , 12 transformer layers, and 12 attention heads. We focus on the patch at grid position , the second patch in the first row.
Step 1: Extract the patch. The patch at corresponds to pixels in the image tensor. Slicing this region gives a sub-tensor of shape .
Step 2: Flatten. We flatten this sub-tensor into a 1D vector: . In Python: patch_vec = patch.reshape(-1) yields a vector . (We index from 1, so is patch 2 in the sequence.)
Step 3: Linear projection. The patch embedding matrix transforms the raw patch vector to an embedding: .
Step 4: Add position embedding. The sequence index of this patch is in 0-indexed patch coordinates, which becomes position 2 in the full sequence (after the CLS token at position 0). We add the position embedding: .
Step 5: Transformer processing. The full sequence (196 patches plus 1 CLS token) passes through 12 transformer layers. In each layer, self-attention is computed across all 197 tokens. Our patch at position 2 can receive information from the CLS token (position 0) and all other 195 patches. After 12 layers, the representation reflects a complex mixture of information from all spatial locations, weighted by learned attention patterns.
Step 6: Classification. The final representation of the CLS token, , is passed to the linear classification head. Our individual patch representation is not directly used for classification but contributed to the CLS token's representation through attention in all 12 layers.
This trace shows that the path from raw pixels to a classification decision passes through a sequence of linear transformations and attention-based mixing operations, all operating in the same -dimensional space. No special-purpose vision operations are required after the initial patching step.