Like BERT, ViT uses only the Transformer encoder. The difference is the input: instead of words, it lines up image patches. In the figure at the head of the article, the left shows the overall flow and the right shows the inside of one encoder layer.
An image flows in the following order (for ViT-B/16 with a 224ร224 input).
- Split into patches: cut an image xโRHรWรC with height H, width W, and C channels into N=HW/P2 patches of size PรP, and flatten each patch into a vector of length P2C. Cutting a 224ร224 image into 16ร16 patches gives 14 ร 14 = 196 patches, each with 16 ยท 16 ยท 3 = 768 dimensions.
- Embed: map each patch to a D-dimensional vector (768 for ViT-B) with a learnable matrix E (patch embedding).
- Prepend the [class] token: add one learnable vector xclassโ at the start. It plays the same role as BERT's
[CLS], and the output at this position is used at the end as the representation of the whole image.
- Add position embeddings: add a position embedding Eposโ learned for each position in the patch sequence (numbers 0โ196).
- Pass through the encoder: pass through L Transformer encoder layers.
- Classify: apply layer normalization to the output at the [class] position of the last layer and feed it to the classification head. The head is an MLP with one hidden layer during pre-training and a single linear layer during fine-tuning.
As equations (Eqs. (1)โ(4) of the paper), where zโโ is the output of layer โ, MSA is multi-head self-attention, and LN is layer normalization:
z0โ=[xclassโ;ย xp1โE;ย xp2โE;ย โฏ;ย xpNโE]+Eposโ,EโR(P2C)รD,ย EposโโR(N+1)รD
zโโฒโ=MSA(LN(zโโ1โ))+zโโ1โ,zโโ=MLP(LN(zโโฒโ))+zโโฒโ,โ=1,โฆ,L
y=LN(zL0โ)
Inside an encoder layer
Each layer alternates self-attention by multi-head attention with a position-wise MLP (two layers with GELU activation). Unlike the original Transformer and BERT, layer normalization is placed before each block, and the input is added after the block (Pre-LN). Since self-attention looks at every pair of patches, information from the entire image can be gathered from the very first layer.
Model sizes
Following BERT, the paper used the following three sizes (Table 1 of the paper). The number after the name is the patch size: ViT-L/16 means "Large with 16ร16 patches".
| Model | Layers L | Hidden size D | MLP size | Heads | Parameters |
|---|
| ViT-Base | 12 | 768 | 3072 | 12 | 86M |
| ViT-Large | 24 | 1024 | 4096 | 16 | 307M |
| ViT-Huge | 32 | 1280 | 5120 | 16 | 632M |
Smaller patches make the sequence longer (the length is inversely proportional to the square of the patch size) and increase the computation.
Splitting into patches and applying a linear layer is the same computation as a convolution whose kernel size and stride equal the patch size (16ร16, stride 16). The ViT in PyTorch's torchvision is also implemented with an nn.Conv2d of this form. The paper also tried a "hybrid" that feeds intermediate feature maps of a ResNet instead of patches.