Vision Transformer (ViT) Architecture
Last Updated :
08 Jan, 2025
Vision Transformer (ViT) is an innovative deep learning architecture designed to process visual data using the same transformer architecture that revolutionized natural language processing (NLP). Unlike convolutional neural networks (CNNs), which rely on convolutions to capture local spatial features, Vision Transformers adopt the self-attention mechanism to model global relationships across image patches. This architecture has demonstrated state-of-the-art performance in many computer vision tasks such as image classification, object detection, and segmentation.
In this article, we will explore the structure and components of Vision Transformer architecture in detail.
Prerequisites: Convolutional Neural Networks (CNNs), Transformers, Self-Attention Mechanism
Vision Transformer (ViT) Architecture Overview
The Vision Transformer builds upon the transformer architecture initially introduced by Vaswani et al. in 2017 for NLP tasks. Transformers are highly effective at processing sequential data, utilizing self-attention to model dependencies between different parts of the input. Vision Transformers apply this architecture to image data, treating the image as a sequence of patches instead of a grid of pixels.
Vision Transformer architecture comprises several key stages:
- Image Patching and Embedding
- Positional Encoding
- Transformer Encoder
- Classification Head (MLP Head)
Let's break down each of these components.
Architecture and Working of Vision Transformer (ViT) 1. Image Patching and Embedding
The first and most critical step in the ViT pipeline is to convert the image into a sequence of patches, similar to the tokens in an NLP model.
- Patch Splitting: The input image, usually of size H \times W \times C (height, width, and channels), is divided into fixed-size patches. For example, an image of size 224x224 can be split into non-overlapping 16x16 patches, resulting in \frac{224}{16} \times \frac{224}{16} = 14 \times 14 = 196 patches.
- Patch Flattening: Each patch is then flattened into a 1D vector. A patch of size P \times P \times C (e.g., 16x16x3) is reshaped into a vector of size P^2 \times C, creating 196 patch vectors for an image.
- Patch Embedding: Each flattened patch is projected into a higher-dimensional space (embedding dimension D) through a learnable linear projection. This linear transformation enables the model to learn richer feature representations for each patch. The result is a sequence of patch embeddings, each representing a part of the image. The total number of patches in the sequence is N = \frac{H}{P} \times \frac{W}{P}, where N is the number of patches. For instance, with a 224x224 image and 16x16 patches, we have 196 patches.
2. Positional Encoding
Transformers do not inherently capture the spatial order of input sequences. Since the patches are processed as independent tokens, it's essential to introduce positional encodings to retain the spatial structure of the original image.
- Positional Embedding: Positional encodings are added to each patch embedding to encode information about the location of patches within the image. These embeddings help the model understand the spatial relationships between patches, similar to how transformers in NLP encode the positions of words in a sentence.
- Learned vs. Fixed Positional Encoding: In ViTs, positional encodings can either be learned during training or predefined (fixed). Most implementations of Vision Transformers use learnable positional encodings.
3. Transformer Encoder Layers
Once the patches are embedded and augmented with positional information, they are passed through a stack of transformer encoder layers. These layers consist of two primary components: Multi-Head Self-Attention (MSA) and a Feed-Forward Neural Network (FFN).
1. Multi-Head Self-Attention (MSA)
- Self-Attention: The self-attention mechanism allows each patch to attend to every other patch in the sequence. This means that the transformer can model long-range dependencies and relationships between different parts of the image. Each patch computes a weighted sum of the values of all other patches based on its similarity to them, known as the attention score.
\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right) V
Where Q (query), K (key), andV (value) are learned linear projections of the input patch embeddings.
The dot product between queries and keys determines the attention score, and softmax normalizes it.
The weighted sum of values determines the output.
- Multi-Head Attention: The attention mechanism is computed in parallel across multiple attention heads, allowing the model to focus on different parts of the image simultaneously.
2. Feed-Forward Network (FFN)
After self-attention, the patches are passed through a feed-forward network (FFN). The FFN consists of two fully connected layers with a non-linear activation function (typically GELU) in between.
Each transformer encoder layer includes residual (skip) connections and layer normalization to stabilize training and improve convergence. These techniques ensure that the deeper layers do not lose important information from the earlier layers.
Stacking Encoder Layers
Multiple transformer encoder layers (e.g., 12, 24 layers) are stacked on top of each other. Each layer refines the patch embeddings, allowing the model to build more complex and abstract representations of the image.
4. Classification Token (CLS Token)
In Vision Transformers, a special classification token (CLS token) is introduced at the beginning of the input sequence. This token serves a critical role: it gathers information from all the patches throughout the transformer layers.
The CLS token learns to represent the entire image by attending to the different patches through the self-attention mechanism. At the output of the transformer layers, the CLS token is extracted and passed to a classifier for the final prediction.
5. MLP Head (Classification Head)
After the transformer encoders process the sequence of patches and the CLS token, the output corresponding to the CLS token is used for classification.
The output of the CLS token is fed into an MLP, typically consisting of one or two fully connected layers. A softmax layer is applied at the end of the MLP for classification tasks, predicting the image’s label.
Vision Transformer Architecture Summary
To summarize, the Vision Transformer architecture involves the following key steps:
- Input Image Processing: The input image is divided into patches, which are flattened and embedded using a linear projection.
- Positional Encoding: Positional encodings are added to the patch embeddings to retain spatial information.
- Transformer Encoder: The patch embeddings (along with the CLS token) are passed through multiple transformer encoder layers, which include multi-head self-attention and feed-forward networks.
- Classification Head: The CLS token's output is extracted and fed into an MLP for final classification.
Vision Transformer (ViT) vs. Convolutional Neural Networks (CNNs)
- Local vs. Global Attention: CNNs capture local spatial features through convolutions, whereas ViTs capture global relationships using self-attention.
- Inductive Biases: CNNs have built-in inductive biases, such as locality and translation invariance, which make them effective at image tasks with smaller datasets. Vision Transformers, on the other hand, rely on data to learn these patterns, making them more flexible but data-hungry.
- Training Data Requirements: Vision Transformers typically require large amounts of training data to achieve their best performance, while CNNs can perform well even with smaller datasets.
Strengths of Vision Transformer Architecture
- Global Context: ViTs are excellent at capturing long-range dependencies between image patches, giving them a better understanding of the global context of images.
- Scalability: ViTs scale well with larger datasets and deeper architectures, making them highly effective for large-scale vision tasks.
- Flexibility: Since ViTs don't rely on convolutions, they can be easily adapted to different tasks and domains beyond image classification, such as video analysis and object detection.
Challenges and Limitations
- Data Requirements: ViTs are data-hungry and typically require large-scale datasets for effective training. Fine-tuning ViTs pre-trained on large datasets (like ImageNet) is a common practice when data is limited.
- Computational Resources: Vision Transformers demand significant computational power, especially during training, due to the quadratic complexity of the self-attention mechanism.
Vision Transformer architecture marks a significant shift in how visual data is processed by leveraging the self-attention mechanism of transformers. It excels in capturing global relationships between image patches, providing a powerful alternative to traditional convolutional neural networks. While ViTs are highly flexible and scalable, they require large datasets and computational resources to realize their full potential. As research and development in this field continue, ViTs are expected to play an increasingly important role in the future of computer vision tasks.
Similar Reads
Vision Transformer (ViT) Architecture
Vision Transformer (ViT) is an innovative deep learning architecture designed to process visual data using the same transformer architecture that revolutionized natural language processing (NLP). Unlike convolutional neural networks (CNNs), which rely on convolutions to capture local spatial feature
7 min read
Vision Transformer (ViT) Architecture
Vision Transformer (ViT) is an innovative deep learning architecture designed to process visual data using the same transformer architecture that revolutionized natural language processing (NLP). Unlike convolutional neural networks (CNNs), which rely on convolutions to capture local spatial feature
7 min read
Vision Transformer in Computer Vision
Vision Transformers (ViTs) are inspired by the success of transformers in NLP and apply self-attention mechanisms to interpret images by treating them as sequences of words. ViTs have found applications in various fields such as image classification, object detection, and segmentation. In this artic
9 min read
Vision Transformer in Computer Vision
Vision Transformers (ViTs) are inspired by the success of transformers in NLP and apply self-attention mechanisms to interpret images by treating them as sequences of words. ViTs have found applications in various fields such as image classification, object detection, and segmentation. In this artic
9 min read
Vision Transformers (ViT) in Image Recognition
Convolutional neural networks (CNNs) have been at the forefront of the revolutionary progress in image recognition in the last ten years. Nonetheless, the field has been transformed by the introduction of Vision Transformers (ViT) which have implemented transformer architecture principles with image
9 min read
ResNeXt Architecture in Computer Vision
The ResNext model represents a significant evolution in convolutional neural network (CNN) architectures. Developed with the idea of increasing the accuracy of models without substantially increasing computational complexity, ResNext is a powerful tool in the field of deep learning, especially in ta
8 min read
Machine Translation with Transformer in Python
Machine translation converts a sequence of text from one language to another. Popular online translation services like Google Translate, Microsoft Translator, and others use machine translation techniques to provide users with quick and accessible translations between a wide range of languages. Tran
11 min read
Mobilenet V2 Architecture in Computer Vision
MobileNet V2 is a highly efficient convolutional neural network architecture designed for mobile and embedded vision applications. Developed by researchers at Google, MobileNet V2 improves upon its predecessor, MobileNet V1, by providing better accuracy and reduced computational complexity. This art
5 min read
VGG-Net Architecture Explained
The Visual Geometry Group (VGG) models, particularly VGG-16 and VGG-19, have significantly influenced the field of computer vision since their inception. These models, introduced by the Visual Geometry Group from the University of Oxford, stood out in the 2014 ImageNet Large Scale Visual Recognition
6 min read
MVC Architecture - System Design
MVC(Model-View-Controller) Architecture is a fundamental design pattern in software development, separating an application into Model, View, and Controller components. This article explores its role in building robust, maintainable systems, emphasizing its benefits and implementation strategies. Imp
11 min read
Architecture of TensorFlow
Prerequisite: Introduction to TensorFlow TensorFlow is an end-to-end open-source platform for machine learning developed by Google with many enthusiastic open-source contributors. TensorFlow is scalable and flexible to run on data centers as well as mobile phones. It can run on single-machine as wel
6 min read
Unet++ Architecture Explained
U-Net++ or Nested U-Net is a deep learning architecture that was introduced in 2019 in the "UNet++. In UNet, the encoder part captures high-level features from the input image through a series of convolutional and pooling layers, while the decoder part upsamples these features to generate a dense se
11 min read
Xilinx FPGA Architecture
FPGA, which stands for field-programmable gate array, can be used to solve any computable issue. It is an integrated circuit that may be customized after manufacturing by a client or a designer. To be more specific, FPGAs (Field Programmable Gate Arrays) are semiconductor devices that consist of a m
5 min read
U-Net Architecture Explained
U-Net is a widely used deep learning architecture that was first introduced in the "U-Net: Convolutional Networks for Biomedical Image Segmentation" paper. The primary purpose of this architecture was to address the challenge of limited annotated data in the medical field. This network was designed
8 min read
Vision Transformers vs. Convolutional Neural Networks (CNNs)
In recent years, the landscape of computer vision has evolved significantly with the introduction of Vision Transformers (ViTs), which challenge the dominance of traditional Convolutional Neural Networks (CNNs). While CNNs have been the backbone of many state-of-the-art image classification models,
5 min read
Architecture and Working of Transformers in Deep Learning
Transformers are a type of deep learning model that utilizes self-attention mechanisms to process and generate sequences of data efficiently, capturing long-range dependencies and contextual relationships. The article aims to discuss the architecture and working of the transformers model in deep lea
9 min read
LeNet-5 Architecture
In the late 1990s, Yann LeCun, Léon Bottou, Yoshua Bengio, and Patrick Haffner created a convolutional neural network (CNN) based architecture called LeNet. The LeNet-5 architecture was developed to recognize handwritten and machine-printed characters, a function that showcased the potential of deep
5 min read
Layered Architecture in Computer Networks
Layered architecture in computer networks refers to dividing a network's functioning into different layers, each responsible for a certain communication component. The major goal of this layered architecture is to separate the complex network communication process into manageable, smaller activities
10 min read
Building a Vision Transformer from Scratch in PyTorch
Vision Transformers (ViTs) have revolutionized the field of computer vision by leveraging transformer architecture, which was originally designed for natural language processing. Unlike traditional CNNs, ViTs divide an image into patches and treat them as tokens, allowing the model to learn spatial
5 min read
Computer Vision with PyTorch
PyTorch is a powerful framework applicable to various computer vision tasks. The article aims to enumerate the features and functionalities within the context of computer vision that empower developers to build neural networks and train models. It also demonstrates how PyTorch framework can be utili
6 min read