An image as a sequence
A transformer takes a sequence of vectors. An image is a grid of pixels, so the only real question is how to turn one into the other.
- : the patch size, usually 16.
- : the resulting sequence length.
A 224 by 224 image cut into 16 by 16 patches gives 196 patches, and each patch is flattened into a vector of numbers.
- : one linear projection, shared by every patch.
- : a learned position embedding, one per position.
That projection is equivalent to a single convolution with kernel size and stride , which is exactly how it is implemented.
After that line, nothing about the model is specific to images. It is the same encoder used for text.
Why the position embedding is not optional
Self-attention is permutation invariant, so without positions the model sees a bag of patches and cannot tell a face from its parts rearranged.
The embedding is learned rather than derived, and interpolating it is what allows a model trained at 224 pixels to be fine-tuned at 384.
The extra token belongs to no patch. It attends to all of them and its final state is the image representation the classifier reads, which avoids having to pool the patches by hand.
The cost, which is the real constraint
Attention is quadratic in the sequence length, and the sequence length is quadratic in the image side.
Halving the patch size quadruples the tokens and multiplies the attention cost by sixteen.
That is why 16 is the usual compromise, and why high resolution vision transformers use windowed attention instead.
One pass, in order
- Cut the image into non-overlapping patches.
- Flatten and project each patch to the model width.
- Prepend the class token and add the position embeddings.
- Run the transformer encoder blocks, each attention followed by an MLP.
- Take the final class token and pass it through one linear layer to the classes.
What it gave up, and what it bought
A convolution assumes neighbouring pixels are related and that a pattern means the same thing anywhere. A vision transformer assumes neither and has to learn both.
That is why it loses to a convolutional network on ImageNet alone and wins decisively once pretrained on a hundred million images.
The gain is reach. A convolutional network builds up its receptive field layer by layer, while every patch here can attend to every other patch in the first block.
Hybrids now dominate in practice: a convolutional stem for the cheap local structure, attention above it for the long-range relationships.