The Wayback Machine - https://web.archive.org/web/20250118003207/https://www.geeksforgeeks.org/vision-transformer-vit-architecture/
Open In App

Vision Transformer (ViT) Architecture

Last Updated : 08 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

  1. Image Patching and Embedding
  2. Positional Encoding
  3. Transformer Encoder
  4. Classification Head (MLP Head)

Let's break down each of these components.

Vision-Transformer-Architecture_
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:

  1. Input Image Processing: The input image is divided into patches, which are flattened and embedded using a linear projection.
  2. Positional Encoding: Positional encodings are added to the patch embeddings to retain spatial information.
  3. 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.
  4. 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.


Next Article
Article Tags :

Similar Reads

three90RightbarBannerImg