Module 22 — Vision Transformer (ViT)
Vision Transformer (ViT) is a Transformer architecture designed for image recognition. Instead of processing pixels directly like Convolutional Neural Networks (CNNs), ViT divides an image into fixed-size patches, converts each patch into an embedding, and processes the sequence of embeddings using Transformer encoder layers.
The Vision Transformer was introduced in the paper "An Image is Worth 16×16 Words" by Google Research.
Topics
- Patch Embedding
- Image Tokens
- CLS Token
- Classification Head
1. Input Image
The input image is represented as
Formula
where
- = Image Height
- = Image Width
- = Number of Channels (RGB = 3)
2. Image Patching
The image is divided into equal-sized patches.
If
- Patch Size =
then the number of patches is
Formula
Each patch has dimensions
3. Patch Flattening
Each image patch is flattened into a vector.
Formula
4. Patch Embedding
Each flattened patch is projected into the Transformer embedding space.
Formula
where
- = Learnable Projection Matrix
- = Bias Vector
or equivalently,
This converts every image patch into an embedding vector.
5. Image Tokens
After projection,
the image becomes a sequence of tokens.
Formula
where
- = Number of Image Patches
6. CLS Token
A learnable classification token is added at the beginning of the sequence.
Formula
where
- = Concatenation
The CLS token learns a global representation of the entire image.
7. Positional Embedding
Position embeddings are added to preserve spatial information.
Formula
where
8. Transformer Encoder
The token sequence is processed through multiple encoder layers.
Formula
or
9. Self-Attention
Each encoder layer computes self-attention.
Formula
10. Multi-Head Attention
Formula
11. Feed Forward Network
Formula
12. CLS Representation
After the encoder stack,
only the CLS token is used for classification.
Formula
where
- = First output token
13. Classification Head
The CLS representation is passed through a linear classifier.
Formula
14. Softmax Prediction
The output probabilities are
Formula
15. Predicted Class
The predicted image class is
Formula
16. Complete Vision Transformer Pipeline
The complete data flow is
17. Matrix Dimensions
Suppose
- Image Size =
- Patch Size =
- Hidden Size = 768
Number of Patches
Patch Embeddings
After CLS Token
Encoder Output
Classification Output
18. Applications
Vision Transformer is widely used in
- Image Classification
- Object Detection
- Image Segmentation
- Medical Imaging
- Remote Sensing
- Face Recognition
- OCR
- Image Retrieval
- Vision-Language Models
- Multimodal AI
Popular ViT-based models include
- ViT
- DeiT
- BEiT
- DINOv2
- MAE
- EVA
- SAM
- CLIP
- SigLIP
Summary
| Concept | Formula |
|---|---|
| Input Image | |
| Number of Patches |