Explain Vision Transformers (ViT) and its variants

Transformers for Image Recognition at Scale which proposed Vision Transformer model
Title: This figure is taken from “An Image is Worth 16×16 Words: Transformers for Image Recognition at Scale” which proposed Vision Transformer model
Source: “An Image is Worth 16×16 Words: Transformers for Image Recognition at Scale” Paper by Dosovitskiy et al., 2020

Introduction

For nearly a decade, convolutional neural networks (CNNs) dominated computer vision. Architectures like AlexNet, VGGNet, and ResNet achieved remarkable success by exploiting the spatial structure of images through local receptive fields and translation equivariance. Then, in October 2020, researchers at Google Brain asked a simple question: what if we applied the transformer architecture, which had revolutionized natural language processing, directly to images?

The result was the Vision Transformer (ViT), introduced in the paper “An Image is Worth 16×16 Words: Transformers for Image Recognition at Scale” [1]. The key insight was elegantly simple: treat an image as a sequence of patches, just as NLP models treat text as a sequence of tokens. This approach achieved state-of-the-art results on image classification benchmarks while using substantially fewer computational resources than CNNs when pre-trained on large datasets.

ViT’s success sparked a paradigm shift in computer vision. For the first time, a single architecture could dominate both vision and language tasks, opening the door to unified multimodal models. Today, transformer-based architectures have largely replaced CNNs as the backbone of choice for most vision applications.

How Vision Transformers Work

The ViT architecture processes images through several key stages: patch embedding, positional encoding, transformer encoding, and classification.

Patch Embedding

Unlike CNNs that process images through hierarchical convolutions, ViT divides an input image into fixed-size patches. For a 224×224 image with 16×16 patches, this creates a sequence of 196 patches. Each patch is flattened into a vector and linearly projected into an embedding space. This transforms spatial image data into a sequence that the transformer can process.

A special classification token, borrowed from BERT, is prepended to the sequence. This [CLS] token aggregates information from all patches through attention and serves as the image representation for classification.

Positional Encoding

Transformers are permutation-invariant, meaning they have no inherent notion of order. To preserve spatial information about where each patch originated in the image, ViT adds learnable positional embeddings to the patch embeddings. Unlike the fixed sinusoidal encodings in the original transformer, ViT learns these positions during training, allowing the model to discover optimal spatial representations.

The Transformer Encoder

The embedded patches flow through a standard transformer encoder consisting of alternating multi-head self-attention and feed-forward layers, with layer normalization and residual connections. The self-attention mechanism allows each patch to attend to every other patch, enabling the model to capture global relationships from the very first layer. This contrasts sharply with CNNs, where global context only emerges in deeper layers after multiple pooling operations.

The following code illustrates the core components of patch embedding and self-attention:

Python
import torch
import torch.nn as nn

class PatchEmbedding(nn.Module):
    def __init__(self, img_size=224, patch_size=16, in_channels=3, embed_dim=768):
        super().__init__()
        self.num_patches = (img_size // patch_size) ** 2
        # Linear projection of flattened patches
        self.proj = nn.Conv2d(in_channels, embed_dim,
                              kernel_size=patch_size, stride=patch_size)
        self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
        self.pos_embed = nn.Parameter(torch.zeros(1, self.num_patches + 1, embed_dim))

    def forward(self, x):
        B = x.shape[0]
        # Project patches: (B, C, H, W) -> (B, embed_dim, H/P, W/P) -> (B, num_patches, embed_dim)
        x = self.proj(x).flatten(2).transpose(1, 2)
        # Prepend [CLS] token and add positional embeddings
        cls_tokens = self.cls_token.expand(B, -1, -1)
        x = torch.cat([cls_tokens, x], dim=1)
        x = x + self.pos_embed
        return x

The patch embedding uses a convolution with kernel size and stride equal to the patch size. This is mathematically equivalent to flattening each patch and applying a linear projection, but more computationally efficient. The [CLS] token and positional embeddings are learnable parameters that the model optimizes during training.

Inductive Biases: ViT vs CNNs

A crucial difference between ViT and CNNs lies in their inductive biases. CNNs encode strong assumptions about images: locality (nearby pixels are related), translation equivariance (the same pattern is recognized anywhere in the image), and hierarchical structure (simple features combine into complex ones). These biases make CNNs highly sample-efficient but potentially limit their flexibility.

ViT has minimal image-specific biases. Only the patch extraction step imposes local structure; the transformer layers treat patches as an unordered set (modulo positional embeddings). This flexibility comes at a cost: ViT requires substantially more training data to learn patterns that CNNs encode by design. The original paper showed that ViT underperforms ResNets when trained on ImageNet alone (1.3M images) but surpasses them when pre-trained on larger datasets like JFT-300M (300M images).

Major ViT Variants

The success of ViT inspired numerous variants addressing its limitations.

DeiT (Data-efficient Image Transformers)

Diagram from the DeiT paper showing the proposal of including a new distillation token
Title: Diagram from the DeiT paper showing the proposal of including a new distillation token
Source: “Training data-efficient image transformers
& distillation through attention” Paper by Touvron et. al.

Facebook AI’s DeiT [2] tackled ViT’s data hunger. Through extensive training recipe optimization, including strong data augmentation, regularization, and a novel distillation approach, DeiT achieved competitive results training only on ImageNet. The key innovation was the distillation token: a second special token that learns from a CNN teacher model. This combined the strengths of both architectures. DeiT-Base achieves 83.1% top-1 accuracy on ImageNet without external data.

Swin Transformer

Diagram from the Swin Transformer paper showing the architecture
Title: Diagram from the Swin Transformer paper showing the architecture
Source: “Swin Transformer: Hierarchical Vision Transformer using Shifted Windows” Paper by Liu et. al.

Microsoft’s Swin Transformer [3] introduced a hierarchical design that produces multi-scale feature maps, making it suitable for dense prediction tasks like object detection and segmentation. Instead of global self-attention (which scales quadratically with image size), Swin computes attention within local windows. Shifted windows in alternating layers allow cross-window connections while maintaining linear complexity. Swin won the ICCV 2021 Best Paper award and achieves 87.3% top-1 accuracy on ImageNet.

BEiT (BERT Pre-training of Image Transformers)


Title: Diagram from the BEIT paper showing the overview of BEIT pre-training
Source: Bao et. al.
Title: Diagram from the BEIT paper showing the overview of BEIT pre-training
Source: “BEIT: BERT Pre-Training of Image Transformers” Paper by Bao et. al. 

Microsoft’s BEiT [4] brought BERT-style masked pre-training to vision. During pre-training, random patches are masked, and the model learns to predict their discrete visual tokens (obtained from a trained tokenizer). This self-supervised approach allows BEiT to leverage unlabeled images effectively. BEiT-Large achieves 86.3% accuracy using only ImageNet for pre-training, outperforming supervised ViT-Large trained on the much larger ImageNet-22K.

Comparison of ViT Variants

ModelKey InnovationImageNet AccParametersAttention Type
ViT-BaseOriginal patch-based transformer77.9% (IN-1K only)86MGlobal
ViT-LargeScaled ViT with JFT pre-training87.8% (JFT-300M)307MGlobal
DeiT-BaseDistillation token, training recipes83.10%86MGlobal
Swin-BaseShifted windows, hierarchical83.50%88MLocal (shifted)
Swin-LargeScaled Swin87.30%197MLocal (shifted)
BEiT-LargeMasked image modeling86.30%304MGlobal
Title: Comparing the key innovations of the proposed Vision Transformer model variants
Source: AIML.com Research

Summary

Vision Transformers represent a fundamental shift in computer vision, demonstrating that the transformer architecture can match or exceed CNN performance on visual tasks. By treating images as sequences of patches, ViT enables unified architectures for vision and language while achieving excellent results when sufficient training data is available.

The key concepts to understand are: patch embedding transforms images into sequences, positional embeddings preserve spatial information, and global self-attention captures long-range dependencies from the first layer. However, this flexibility comes at the cost of requiring more data than CNNs, which encode useful visual priors by design.

Subsequent variants like DeiT, Swin, and BEiT addressed ViT’s limitations through improved training strategies, efficient attention mechanisms, and self-supervised pre-training, making vision transformers practical across a wide range of applications and data regimes.

Video Explanations

  • This video, “Vision Transformers (ViT) Explained + Fine-Tuning in Python” by James Briggs provides a comprehensive walkthrough of the ViT architecture and demonstrates fine-tuning using Hugging Face. (Runtime: 30 minutes)
YouTube video
“Vision Transformers (ViT) Explained + Fine-Tuning in Python” by James Briggs
  • This video, “An Image is Worth 16×16 Words: Transformers for Image Recognition at Scale” by Yannic Kilcher offers an in-depth paper review explaining the key insights and experimental results from the original ViT paper. (Runtime: 30 minutes)
YouTube video
“An Image is Worth 16×16 Words: Transformers for Image Recognition at Scale” by Yannic Kilcher

References

  • [1] Dosovitskiy, A., Beyer, L., Kolesnikov, A., et al. (2021). An Image is Worth 16×16 Words: Transformers for Image Recognition at Scale. ICLR 2021. arXiv:2010.11929
  • [2] Touvron, H., Cord, M., Douze, M., et al. (2021). Training data-efficient image transformers & distillation through attention. ICML 2021. arXiv:2012.12877
  • [3] Liu, Z., Lin, Y., Cao, Y., et al. (2021). Swin Transformer: Hierarchical Vision Transformer using Shifted Windows. ICCV 2021 (Best Paper). arXiv:2103.14030
  • [4] Bao, H., Dong, L., & Wei, F. (2022). BEiT: BERT Pre-Training of Image Transformers. ICLR 2022. arXiv:2106.08254

Author

Help us improve this post by suggesting in comments below:

– modifications to the text, and infographics
– video resources that offer clear explanations for this question
– code snippets and case studies relevant to this concept
– online blogs, and research publications that are a “must read” on this topic

Leave the first comment

Partner Ad
Find out all the ways that you can
Contribute