Skip to content

23. Vision Transformers and CNN-ViT Hybrids

Understand how Vision Transformers (ViTs) apply Transformer architectures to Computer Vision, how images are converted into patch tokens, how self-attention captures global relationships, and how CNN and Transformer architectures can be combined to build efficient and powerful vision systems.


๐ŸŽฏ Learning Objectives

After completing this chapter, you will be able to:

  • Explain why Vision Transformers were introduced
  • Understand the limitations of traditional CNNs for global context modeling
  • Explain the core architecture of Vision Transformers
  • Understand image patching
  • Convert image patches into token embeddings
  • Understand positional embeddings
  • Explain self-attention in Vision Transformers
  • Understand Multi-Head Self-Attention (MHSA)
  • Understand the Transformer Encoder used by ViT
  • Explain the role of the [CLS] token
  • Understand the ViT classification pipeline
  • Compare CNNs and Vision Transformers
  • Understand the computational characteristics of self-attention
  • Understand why ViTs require substantial training data
  • Understand pretrained Vision Transformers
  • Use Vision Transformer models with PyTorch and TorchVision
  • Understand CNN-ViT hybrid architectures
  • Explain how CNNs can provide local feature extraction before Transformer processing
  • Understand hierarchical vision architectures
  • Compare CNN, ViT, and hybrid approaches
  • Understand Transfer Learning with ViTs
  • Identify practical ViT deployment considerations
  • Understand how Vision Transformers connect Computer Vision with modern Foundation Models

๐Ÿ“– Overview

Convolutional Neural Networks revolutionized Computer Vision by learning spatial patterns through convolutional filters.

CNNs are particularly strong at learning:

Edges
 โ†“
Textures
 โ†“
Shapes
 โ†“
Objects

However, traditional convolution operates over local receptive fields.

To understand relationships between distant regions, CNNs typically need:

More Layers
+
Larger Receptive Fields
+
Downsampling

Transformers introduced another approach.

Instead of processing visual information primarily through local convolution operations, a Vision Transformer converts an image into a sequence of tokens and applies:

Self-Attention

to model relationships between different image regions.

The fundamental transition is:

CNN

Image
 โ†“
Convolution
 โ†“
Feature Maps
 โ†“
Classification

to:

Vision Transformer

Image
 โ†“
Image Patches
 โ†“
Patch Tokens
 โ†“
Self-Attention
 โ†“
Transformer Encoder
 โ†“
Classification

๐Ÿง  Why Vision Transformers?

CNNs naturally encode local spatial structure.

For example:

Pixel
 โ†“
Local Neighborhood
 โ†“
Edges
 โ†“
Textures
 โ†“
Shapes
 โ†“
Objects

Self-attention provides a mechanism for directly relating different regions of an image.

For example:

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Image โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                                  โ”‚
โ”‚  Head                      Tail  โ”‚
โ”‚    โ—                         โ—    โ”‚
โ”‚                                  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

A Transformer can directly model:

Head โ†” Tail

even when those regions are far apart.


๐Ÿง  CNN Locality vs Transformer Global Context

flowchart LR

    IMAGE["Image"]

    CNN["CNN"]
    LOCAL["Local Receptive Fields"]
    HIER["Hierarchical Features"]
    OUTPUT1["Visual Representation"]

    PATCH["Image Patches"]
    TOKEN["Patch Tokens"]
    ATTENTION["Self-Attention"]
    GLOBAL["Global Relationships"]
    OUTPUT2["Visual Representation"]

    IMAGE --> CNN
    CNN --> LOCAL
    LOCAL --> HIER
    HIER --> OUTPUT1

    IMAGE --> PATCH
    PATCH --> TOKEN
    TOKEN --> ATTENTION
    ATTENTION --> GLOBAL
    GLOBAL --> OUTPUT2

Both approaches can learn powerful visual representations, but they encode spatial relationships differently.


๐Ÿง  From CNN to Vision Transformer

The evolution can be viewed as:

Traditional CNN
      โ†“
Deep CNN
      โ†“
Residual CNN
      โ†“
Efficient CNN
      โ†“
Vision Transformer
      โ†“
Hybrid CNN + Transformer
      โ†“
Modern Vision Foundation Models

๐Ÿง  Vision Transformer Architecture

The original Vision Transformer architecture can be simplified as:

Input Image
    โ†“
Split into Patches
    โ†“
Flatten Patches
    โ†“
Linear Projection
    โ†“
Patch Embeddings
    โ†“
Add Positional Embeddings
    โ†“
Transformer Encoder
    โ†“
Classification Head

๐Ÿง  Vision Transformer Architecture

flowchart TD

    IMAGE["Input Image"]

    PATCH["Split Image into Patches"]

    FLATTEN["Flatten Patches"]

    PROJECTION["Linear Projection"]

    POSITION["Add Positional Embeddings"]

    ENCODER["Transformer Encoder"]

    CLS["CLS Representation"]

    HEAD["Classification Head"]

    OUTPUT["Prediction"]

    IMAGE --> PATCH
    PATCH --> FLATTEN
    FLATTEN --> PROJECTION
    PROJECTION --> POSITION
    POSITION --> ENCODER
    ENCODER --> CLS
    CLS --> HEAD
    HEAD --> OUTPUT

๐Ÿงฉ Image Patching

A Vision Transformer does not normally process every individual pixel as an independent token.

Instead, the image is divided into fixed-size patches.

Suppose:

Image Size = 224 ร— 224
Patch Size = 16 ร— 16

Then the number of patches per dimension is:

[ \frac{224}{16}=14 ]

Total patches:

[ 14\times14=196 ]

Therefore:

224 ร— 224 Image
        โ†“
196 Patches

๐Ÿง  General Number of Patches

For an image of size:

H ร— W

with patch size:

P ร— P

the number of patches is:

[ N=\frac{H}{P}\times\frac{W}{P} ]

where:

H = Image Height
W = Image Width
P = Patch Size
N = Number of Patches

๐Ÿง  Patch Visualization

Original Image

โ”Œโ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”
โ”‚ P1 โ”‚ P2 โ”‚ P3 โ”‚ P4 โ”‚
โ”œโ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”ค
โ”‚ P5 โ”‚ P6 โ”‚ P7 โ”‚ P8 โ”‚
โ”œโ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”ค
โ”‚ P9 โ”‚P10 โ”‚P11 โ”‚P12 โ”‚
โ”œโ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”ค
โ”‚P13 โ”‚P14 โ”‚P15 โ”‚P16 โ”‚
โ””โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”˜

Each patch becomes a token.

Patch 1 โ†’ Token 1
Patch 2 โ†’ Token 2
Patch 3 โ†’ Token 3
...
Patch N โ†’ Token N

๐Ÿง  Patch Size Trade-Off

Patch size affects:

Number of Tokens
+
Computational Cost
+
Spatial Detail

Smaller patches:

More Tokens
+
More Spatial Detail
+
Higher Attention Cost

Larger patches:

Fewer Tokens
+
Lower Computational Cost
+
Less Fine-Grained Detail

๐Ÿ“Š Patch Size Trade-Off

Patch Size
    โ”‚
    โ”‚  8ร—8
    โ”‚   โ—
    โ”‚
    โ”‚       16ร—16
    โ”‚          โ—
    โ”‚
    โ”‚              32ร—32
    โ”‚                  โ—
    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ†’
       Token Count / Computation

Smaller Patch
      โ†“
More Tokens
      โ†“
Higher Attention Cost

๐Ÿง  Flattening Image Patches

Suppose an RGB patch is:

16 ร— 16 ร— 3

The flattened patch contains:

[ 16\times16\times3=768 ]

values.

The patch can therefore be represented as:

16 ร— 16 ร— 3
       โ†“
Flatten
       โ†“
768-dimensional vector

๐Ÿง  Patch Embedding

The flattened patch is projected into a model embedding dimension.

For example:

Patch
768 values
   โ†“
Linear Projection
   โ†“
768-dimensional Embedding

The projection can be represented as:

[ z=Wx+b ]

where:

x = Flattened Patch
W = Learnable Projection Matrix
b = Bias
z = Patch Embedding

๐Ÿง  Patch Embedding Pipeline

flowchart LR

    PATCH["16 ร— 16 ร— 3 Patch"]

    FLAT["Flatten"]

    VECTOR["768 Values"]

    LINEAR["Linear Projection"]

    TOKEN["Patch Embedding"]

    PATCH --> FLAT
    FLAT --> VECTOR
    VECTOR --> LINEAR
    LINEAR --> TOKEN

๐Ÿง  Why Do We Need Positional Embeddings?

Transformers process sequences.

However, self-attention itself does not inherently encode the spatial position of a token.

Consider:

Patch A
Patch B
Patch C

and:

Patch C
Patch A
Patch B

Without positional information, the model needs another mechanism to understand that the order or spatial location changed.

Therefore:

Patch Embedding
+
Positional Embedding

are combined.


๐Ÿง  Positional Embedding

The input to the Transformer can be represented as:

[ Z_0=E+E_{pos} ]

where:

E     = Patch Embeddings
Epos  = Positional Embeddings
Z0    = Transformer Input

๐Ÿง  CLS Token

Many ViT architectures prepend a learnable classification token:

[CLS]
Patch 1
Patch 2
Patch 3
...
Patch N

Therefore the sequence length becomes:

[ N+1 ]

The Transformer processes the entire sequence.

The final representation of:

[CLS]

can be used by the classification head.


๐Ÿง  Token Sequence

[CLS]
  +
Patch 1
  +
Patch 2
  +
Patch 3
  +
...
  +
Patch N

Conceptually:

Image
 โ†“
Patches
 โ†“
Embeddings
 โ†“
[CLS] + Patch Tokens
 โ†“
Positional Information
 โ†“
Transformer

๐Ÿง  ViT Input Representation

flowchart TD

    IMAGE["Image"]

    PATCHES["Image Patches"]

    EMBED["Patch Embeddings"]

    CLS["CLS Token"]

    POSITION["Positional Embeddings"]

    SEQUENCE["Token Sequence"]

    IMAGE --> PATCHES
    PATCHES --> EMBED
    EMBED --> SEQUENCE
    CLS --> SEQUENCE
    POSITION --> SEQUENCE

๐Ÿง  Self-Attention

Self-attention allows each token to interact with other tokens.

For an image:

Patch 1
Patch 2
Patch 3
...
Patch N

each patch can attend to:

Patch 1
Patch 2
Patch 3
...
Patch N

This enables global relationships.


๐Ÿง  Query, Key and Value

Self-attention transforms the input into:

Query
Key
Value

The attention operation is:

[ Attention(Q,K,V)=softmax\left(\frac{QK^T}{\sqrt{d_k}}\right)V ]

where:

Q  = Queries
K  = Keys
V  = Values
dk = Key Dimension

๐Ÿง  Self-Attention Intuition

Suppose:

Patch A = Dog's Head
Patch B = Dog's Body
Patch C = Background

Self-attention can learn:

Head โ†” Body

more strongly than:

Head โ†” Background

The model learns these relationships from data.


๐Ÿง  Attention Matrix

If there are:

N Tokens

the attention scores form approximately:

N ร— N

relationships.

For example:

       P1   P2   P3   P4

P1     โ—    โ—    โ—    โ—
P2     โ—    โ—    โ—    โ—
P3     โ—    โ—    โ—    โ—
P4     โ—    โ—    โ—    โ—

Each row represents how strongly one token attends to other tokens.


๐Ÿง  Multi-Head Self-Attention

Instead of using a single attention mechanism, Transformers use multiple attention heads.

Input
  โ†“
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ Head 1  โ”‚ Head 2  โ”‚ Head 3  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
       โ†“
   Concatenate
       โ†“
   Projection
       โ†“
     Output

Different heads can learn different relationships.


๐Ÿง  Multi-Head Attention

flowchart TD

    INPUT["Token Embeddings"]

    HEAD1["Attention Head 1"]

    HEAD2["Attention Head 2"]

    HEAD3["Attention Head 3"]

    HEADN["Attention Head N"]

    CONCAT["Concatenate"]

    PROJ["Linear Projection"]

    OUTPUT["Attention Output"]

    INPUT --> HEAD1
    INPUT --> HEAD2
    INPUT --> HEAD3
    INPUT --> HEADN

    HEAD1 --> CONCAT
    HEAD2 --> CONCAT
    HEAD3 --> CONCAT
    HEADN --> CONCAT

    CONCAT --> PROJ
    PROJ --> OUTPUT

๐Ÿง  Transformer Encoder

A Vision Transformer uses Transformer Encoder blocks.

A simplified encoder contains:

Input
 โ†“
Layer Normalization
 โ†“
Multi-Head Self-Attention
 โ†“
Residual Connection
 โ†“
Layer Normalization
 โ†“
MLP / Feed-Forward Network
 โ†“
Residual Connection
 โ†“
Output

๐Ÿง  Transformer Encoder Block

flowchart TD

    INPUT["Input Tokens"]

    LN1["LayerNorm"]

    MHA["Multi-Head Self-Attention"]

    ADD1["Residual Add"]

    LN2["LayerNorm"]

    MLP["Feed-Forward MLP"]

    ADD2["Residual Add"]

    OUTPUT["Output Tokens"]

    INPUT --> LN1
    LN1 --> MHA
    MHA --> ADD1
    INPUT --> ADD1

    ADD1 --> LN2
    LN2 --> MLP
    MLP --> ADD2
    ADD1 --> ADD2

    ADD2 --> OUTPUT

๐Ÿง  Transformer MLP

The feed-forward component usually contains:

Linear
 โ†“
Activation
 โ†“
Linear

For example:

nn.Sequential(
    nn.Linear(
        embedding_dim,
        hidden_dim
    ),
    nn.GELU(),
    nn.Linear(
        hidden_dim,
        embedding_dim
    )
)

The MLP operates independently on each token after the attention operation.


๐Ÿง  Layer Normalization

Transformer architectures commonly use Layer Normalization.

Conceptually:

Token Representation
        โ†“
LayerNorm
        โ†“
Attention / MLP

Layer Normalization helps stabilize training.


๐Ÿง  ViT Encoder Stack

A complete ViT contains multiple encoder blocks.

Patch Tokens
     โ†“
Encoder Block 1
     โ†“
Encoder Block 2
     โ†“
Encoder Block 3
     โ†“
...
     โ†“
Encoder Block L
     โ†“
Classification

๐Ÿง  Vision Transformer Complete Architecture

flowchart TD

    IMAGE["Input Image"]

    PATCH["Patch Extraction"]

    EMBED["Patch Embedding"]

    CLS["CLS Token"]

    POS["Positional Embedding"]

    E1["Transformer Encoder 1"]

    E2["Transformer Encoder 2"]

    EN["Transformer Encoder N"]

    HEAD["Classification Head"]

    OUTPUT["Prediction"]

    IMAGE --> PATCH
    PATCH --> EMBED
    EMBED --> POS
    CLS --> POS
    POS --> E1
    E1 --> E2
    E2 --> EN
    EN --> HEAD
    HEAD --> OUTPUT

๐Ÿง  ViT Classification Pipeline

Image
 โ†“
Patches
 โ†“
Patch Embeddings
 โ†“
CLS + Patch Tokens
 โ†“
Position Information
 โ†“
Transformer Encoder
 โ†“
CLS Representation
 โ†“
MLP Head
 โ†“
Class Prediction

๐Ÿง  CNN vs Vision Transformer

CNN Vision Transformer
Convolution-based Attention-based
Strong locality bias Global token interactions
Translation-aware inductive bias More flexible learned relationships
Naturally hierarchical Original ViT is less explicitly hierarchical
Usually works well with moderate data Often benefits strongly from large-scale pretraining
Local receptive fields Global attention
Efficient spatial processing Attention cost grows with token count
Mature edge/mobile ecosystem Strong scaling behavior

Neither architecture is universally superior.

The correct architecture depends on:

Dataset
Task
Compute
Latency
Model Scale
Pretraining
Deployment Environment

๐Ÿง  CNN Inductive Bias

CNNs encode useful assumptions directly into the architecture:

Locality
+
Translation Equivariance
+
Weight Sharing

This can make CNNs highly data-efficient for many vision tasks.


๐Ÿง  Vision Transformer Inductive Bias

ViTs have weaker built-in spatial inductive biases than CNNs.

They learn relationships from data through attention.

This provides flexibility but can increase reliance on:

Large Datasets
+
Strong Pretraining

๐Ÿง  Why ViTs Often Benefit From Large Datasets

CNNs already contain strong assumptions about images.

ViTs rely more heavily on learned representations.

Therefore:

Small Dataset
+
Weak Pretraining

can make a ViT harder to train effectively.

But:

Large-Scale Pretraining
+
Transfer Learning

can make ViTs extremely powerful.


๐Ÿง  Attention Complexity

If there are:

N Tokens

self-attention typically has quadratic complexity with respect to sequence length:

[ O(N^2) ]

For images:

[ N=\frac{H}{P}\times\frac{W}{P} ]

Therefore reducing patch size increases:

N
 โ†“
Attention Computation
 โ†“
Memory Requirement

๐Ÿง  Patch Size and Attention Cost

Suppose:

Image = 224 ร— 224

Patch = 16

14 ร— 14 = 196 tokens

Attention matrix:

196 ร— 196

Patch = 8

28 ร— 28 = 784 tokens

Attention matrix:

784 ร— 784

The increase in token count causes a much larger increase in attention computation.


๐Ÿ“Š Token Count Growth

Patch Size
    โ”‚
16  โ”‚       โ—
    โ”‚
12  โ”‚          โ—
    โ”‚
 8  โ”‚                    โ—
    โ”‚
    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ†’
          Token Count

The smaller the patch size, the greater the number of tokens.


๐Ÿง  Why Hierarchical Vision Transformers?

The original ViT uses a relatively flat token sequence.

Modern vision architectures often introduce hierarchy:

High Resolution
      โ†“
Local Features
      โ†“
Downsampling
      โ†“
Lower Resolution
      โ†“
Higher Semantic Representation

This resembles the hierarchical structure of CNNs.


๐Ÿง  Hierarchical Vision Architecture

flowchart LR

    IMAGE["High Resolution Image"]

    S1["Stage 1<br>Fine Features"]

    S2["Stage 2<br>Intermediate Features"]

    S3["Stage 3<br>Semantic Features"]

    S4["Stage 4<br>High-Level Features"]

    IMAGE --> S1
    S1 --> S2
    S2 --> S3
    S3 --> S4

This pattern is common in modern vision architectures.


๐Ÿง  CNN + Transformer Hybrid

A hybrid architecture combines:

CNN
+
Transformer

The CNN can extract local features efficiently.

The Transformer can model broader relationships.


๐Ÿง  Hybrid Architecture

Image
 โ†“
CNN Feature Extractor
 โ†“
Feature Map
 โ†“
Tokenization
 โ†“
Transformer Encoder
 โ†“
Classification Head

๐Ÿง  CNN-ViT Hybrid

flowchart TD

    IMAGE["Input Image"]

    CNN["CNN Feature Extractor"]

    FEATURE["Feature Maps"]

    TOKEN["Tokenization"]

    TRANSFORMER["Transformer Encoder"]

    HEAD["Task Head"]

    OUTPUT["Prediction"]

    IMAGE --> CNN
    CNN --> FEATURE
    FEATURE --> TOKEN
    TOKEN --> TRANSFORMER
    TRANSFORMER --> HEAD
    HEAD --> OUTPUT

๐Ÿง  Why Combine CNN and Transformer?

CNNs provide:

Locality
Efficient Spatial Processing
Translation-Aware Features

Transformers provide:

Global Context
Long-Range Relationships
Flexible Attention

Therefore:

CNN
+
Transformer

can combine complementary strengths.


๐Ÿง  Hybrid Model Design

A hybrid model may look like:

Input Image
     โ†“
Convolution
     โ†“
Feature Extraction
     โ†“
Patch / Token Projection
     โ†“
Self-Attention
     โ†“
Global Representation
     โ†“
Task Head

๐Ÿง  CNN vs ViT vs Hybrid

Architecture Local Features Global Context Data Efficiency Compute Characteristics
CNN Strong Indirect Strong Usually efficient
ViT Learned Strong Often lower without pretraining Attention can be expensive
Hybrid Strong Strong Often balanced Depends on architecture

๐Ÿง  Vision Transformer Transfer Learning

As with CNNs, pretrained ViTs can be reused.

Pretrained ViT
      โ†“
Remove Original Head
      โ†“
Add Target Head
      โ†“
Freeze Backbone
      โ†“
Train Head
      โ†“
Fine-Tune Selected Layers

๐Ÿง  ViT Transfer Learning

flowchart TD

    PRETRAINED["Pretrained ViT"]

    BACKBONE["Transformer Backbone"]

    HEAD["New Classification Head"]

    FREEZE["Freeze Backbone"]

    TRAIN["Train Head"]

    UNFREEZE["Unfreeze Selected Layers"]

    FINETUNE["Fine-Tune"]

    EVAL["Evaluate"]

    PRETRAINED --> BACKBONE
    BACKBONE --> HEAD
    BACKBONE --> FREEZE
    FREEZE --> TRAIN
    TRAIN --> UNFREEZE
    UNFREEZE --> FINETUNE
    FINETUNE --> EVAL

๐Ÿ Part I โ€” Vision Transformer with PyTorch

PyTorch provides Transformer building blocks, while TorchVision provides pretrained vision architectures.

A modern workflow commonly uses a pretrained vision model and replaces its classification head.


๐Ÿงช Load a Pretrained Vision Transformer

import torch
import torch.nn as nn

from torchvision import models


weights = (
    models.ViT_B_16_Weights.DEFAULT
)


model = models.vit_b_16(
    weights=weights
)

๐Ÿง  Inspect the Model

print(model)

A Vision Transformer contains components conceptually similar to:

conv_proj
+
encoder
+
heads

The patch projection converts image regions into embeddings.

The encoder contains the Transformer blocks.

The head produces task-specific predictions.


๐Ÿง  Replace the Classification Head

Suppose the target dataset contains:

5 Classes

The classifier can be replaced:

num_features = (
    model.heads.head.in_features
)


model.heads.head = nn.Linear(
    num_features,
    5
)

๐Ÿง  Freeze the Transformer Backbone

for param in model.parameters():

    param.requires_grad = False

Then:

for param in model.heads.parameters():

    param.requires_grad = True

Now:

ViT Backbone
     โ†“
Frozen

Classification Head
     โ†“
Trainable

๐Ÿงช ViT Optimizer

optimizer = torch.optim.AdamW(

    model.heads.parameters(),

    lr=1e-3,

    weight_decay=1e-4
)

๐Ÿง  Fine-Tuning a ViT

After training the classification head, selected Transformer blocks can be unfrozen.

For example:

for param in (
    model.encoder.layers[-2:].parameters()
):

    param.requires_grad = True

Then use a smaller learning rate:

optimizer = torch.optim.AdamW(

    filter(
        lambda p: p.requires_grad,
        model.parameters()
    ),

    lr=1e-5,

    weight_decay=1e-4
)

๐Ÿง  ViT Fine-Tuning Strategy

Stage 1
โ”€โ”€โ”€โ”€โ”€โ”€โ”€

ViT Backbone
   โ†“
Frozen

Head
   โ†“
Trainable


Stage 2
โ”€โ”€โ”€โ”€โ”€โ”€โ”€

Last Transformer Blocks
   โ†“
Trainable

Head
   โ†“
Trainable


Stage 3
โ”€โ”€โ”€โ”€โ”€โ”€โ”€

Additional Transformer Blocks
   โ†“
Optional Fine-Tuning

๐Ÿง  ViT Preprocessing

Use the preprocessing associated with the pretrained weights where possible.

weights = (
    models.ViT_B_16_Weights.DEFAULT
)

preprocess = (
    weights.transforms()
)

This ensures that the input preprocessing aligns with the pretrained checkpoint.


๐Ÿง  Why Preprocessing Is Critical for ViT

A pretrained model expects a particular:

Image Size
Normalization
Tensor Format
Value Range

Mismatch can reduce transfer-learning performance.

Therefore:

Preprocessing should be versioned alongside the model.


๐Ÿง  ViT Training Pipeline

flowchart LR

    IMAGE["Raw Image"]

    TRANSFORM["Pretrained Weight Transform"]

    PATCH["Patch Projection"]

    TOKEN["Token Sequence"]

    ENCODER["Transformer Encoder"]

    HEAD["Classification Head"]

    OUTPUT["Prediction"]

    IMAGE --> TRANSFORM
    TRANSFORM --> PATCH
    PATCH --> TOKEN
    TOKEN --> ENCODER
    ENCODER --> HEAD
    HEAD --> OUTPUT

๐Ÿงช Simple ViT Training Loop

for epoch in range(
    epochs
):

    model.train()

    for images, labels in train_loader:

        images = images.to(
            device
        )

        labels = labels.to(
            device
        )

        optimizer.zero_grad()

        logits = model(
            images
        )

        loss = criterion(
            logits,
            labels
        )

        loss.backward()

        optimizer.step()

๐Ÿง  ViT Classification Loss

For multi-class classification:

criterion = nn.CrossEntropyLoss()

The model should output:

Raw Logits

rather than applying softmax before the loss.


๐Ÿง  ViT Feature Representation

The Transformer produces contextualized token representations.

Conceptually:

Patch Tokens
     โ†“
Self-Attention
     โ†“
Context-Aware Tokens
     โ†“
CLS Representation
     โ†“
Classification

Each token can incorporate information from other image regions.


๐Ÿง  Contextualization

Before attention:

Patch 1
Patch 2
Patch 3

After attention:

Patch 1 + Context
Patch 2 + Context
Patch 3 + Context

The representation of each patch becomes contextual.


๐Ÿง  CNN Feature Maps vs Transformer Tokens

CNN:

H ร— W ร— C

Transformer:

N ร— D

where:

N = Number of Tokens
D = Embedding Dimension

Both are representations of visual information, but their structures differ.


๐Ÿง  Feature Representation Comparison

flowchart LR

    IMAGE["Image"]

    CNN["CNN"]

    MAP["Feature Map<br>H ร— W ร— C"]

    VIT["ViT"]

    TOKENS["Tokens<br>N ร— D"]

    IMAGE --> CNN
    CNN --> MAP

    IMAGE --> VIT
    VIT --> TOKENS

๐Ÿง  Vision Transformer Attention Visualization

Attention maps can provide insight into which image regions interact.

Conceptually:

Input Image
     โ†“
Attention Weights
     โ†“
Attention Map
     โ†“
Important Regions

This can be useful for analysis, but attention maps should not automatically be interpreted as definitive explanations of model decisions.


๐Ÿง  Attention Map Concept

Image

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚     โ–‘โ–‘โ–‘โ–‘            โ”‚
โ”‚   โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ           โ”‚
โ”‚   โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ    โ–‘โ–‘     โ”‚
โ”‚      โ–‘โ–‘             โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Darker Region
     โ†“
Higher Attention Weight

The actual interpretation depends on the model, head, layer, and visualization method.


๐Ÿง  Vision Transformer Advantages

ViTs provide:

  • Global self-attention
  • Strong scaling with large-scale pretraining
  • Flexible representation learning
  • Powerful long-range relationship modeling
  • A unified Transformer architecture
  • Strong compatibility with modern Foundation Model research
  • Effective Transfer Learning when suitable pretrained checkpoints are available

โš  Vision Transformer Limitations

Potential limitations include:

  • High attention cost for long token sequences
  • Large memory requirements
  • Greater dependence on pretraining for many tasks
  • More sensitivity to patch size
  • More expensive inference for high-resolution images
  • Less built-in locality than CNNs
  • More complex deployment for large models

๐Ÿง  When Should You Use a CNN?

CNNs may be preferable when:

Dataset is Limited
+
Latency is Important
+
Edge Deployment
+
Strong Local Patterns
+
Compute is Constrained

Examples:

Mobile Vision
Industrial Edge Devices
Real-Time Camera Systems

๐Ÿง  When Should You Use a ViT?

ViTs can be attractive when:

Large-Scale Pretraining
+
Large Dataset
+
Global Context
+
Strong Compute Infrastructure

Examples:

Large-Scale Image Classification
Image Retrieval
Multimodal Systems
Vision Foundation Models

๐Ÿง  When Should You Use a Hybrid?

Hybrid architectures are useful when:

Local Feature Extraction
+
Global Context

are both important.

For example:

Industrial Inspection
Medical Imaging
High-Resolution Vision
Complex Object Recognition

๐Ÿง  Architecture Selection

flowchart TD

    START["Vision Task"]

    DATA["Dataset Size"]

    LATENCY["Latency / Compute Constraints"]

    GLOBAL["Need Strong Global Context"]

    CNN["CNN"]

    VIT["Vision Transformer"]

    HYBRID["CNN + Transformer"]

    START --> DATA

    DATA -->|Small / Medium| LATENCY
    DATA -->|Large / Strong Pretraining| GLOBAL

    LATENCY -->|Strict| CNN
    LATENCY -->|Flexible| GLOBAL

    GLOBAL -->|Strong Global Context| VIT
    GLOBAL -->|Local + Global Required| HYBRID

๐Ÿง  Model Selection Matrix

Requirement CNN ViT Hybrid
Local feature extraction Excellent Good Excellent
Global context Good Excellent Excellent
Small dataset Often strong Often challenging without pretraining Strong
Large-scale pretraining Strong Excellent Excellent
Edge inference Strong Variable Variable
Long-range relationships Moderate Excellent Excellent
High-resolution workloads Efficient variants available Can be expensive Depends on design

๐Ÿง  Modern Vision Architecture Landscape

CNN
 โ”‚
 โ”œโ”€โ”€ ResNet
 โ”‚
 โ”œโ”€โ”€ EfficientNet
 โ”‚
 โ””โ”€โ”€ MobileNet
 โ”‚
 โ–ผ
Vision Transformers
 โ”‚
 โ”œโ”€โ”€ ViT
 โ”‚
 โ”œโ”€โ”€ Hierarchical Transformers
 โ”‚
 โ””โ”€โ”€ Swin-style architectures
 โ”‚
 โ–ผ
Hybrid Architectures
 โ”‚
 โ”œโ”€โ”€ CNN + Transformer
 โ”‚
 โ””โ”€โ”€ Multi-scale Vision Models
 โ”‚
 โ–ผ
Vision Foundation Models

๐Ÿง  Vision Transformers and Foundation Models

The Transformer architecture is no longer limited to language.

The same core concepts have expanded into:

Text
+
Images
+
Audio
+
Video
+
Multimodal Data

This creates a broader architecture:

Input Modality
      โ†“
Tokenization / Representation
      โ†“
Transformer
      โ†“
Contextual Representation
      โ†“
Task / Generation

๐Ÿง  Multimodal Vision Architecture

Modern multimodal systems may combine:

Image Encoder
      +
Text Encoder / LLM
      โ†“
Shared Representation
      โ†“
Multimodal Reasoning

Conceptually:

flowchart TD

    IMAGE["Image"]

    VISION["Vision Encoder"]

    TEXT["Text"]

    LANGUAGE["Language Model"]

    REPRESENTATION["Shared / Aligned Representation"]

    OUTPUT["Multimodal Output"]

    IMAGE --> VISION
    VISION --> REPRESENTATION

    TEXT --> LANGUAGE
    LANGUAGE --> REPRESENTATION

    REPRESENTATION --> OUTPUT

This forms an important bridge from Deep Learning to modern Generative AI.


๐Ÿข Enterprise Perspective

Vision Transformers and hybrid architectures are increasingly relevant to enterprise Computer Vision systems.

Potential applications include:

Document Understanding
Medical Imaging
Industrial Inspection
Retail Vision
Satellite Image Analysis
Visual Search
Product Classification
Image Retrieval
Multimodal AI

๐Ÿข Enterprise Vision Architecture

A production vision platform may support multiple model families:

VisionProvider
      โ”‚
      โ”œโ”€โ”€ CNN Adapter
      โ”‚      โ””โ”€โ”€ ResNet
      โ”‚
      โ”œโ”€โ”€ ViT Adapter
      โ”‚      โ””โ”€โ”€ Vision Transformer
      โ”‚
      โ””โ”€โ”€ Hybrid Adapter
             โ””โ”€โ”€ CNN + Transformer

The application should depend on the capability rather than a specific model.


๐Ÿข Model Abstraction

flowchart LR

    APP["Enterprise Application"]

    API["VisionProvider"]

    CNN["CNN Adapter"]

    VIT["ViT Adapter"]

    HYBRID["Hybrid Adapter"]

    APP --> API

    API --> CNN
    API --> VIT
    API --> HYBRID

This allows an organization to change:

ResNet

to:

ViT

without necessarily changing the business-facing API.


๐Ÿข Production Vision Model Pipeline

Data Collection
      โ†“
Data Validation
      โ†“
Preprocessing
      โ†“
Model Training
      โ†“
Evaluation
      โ†“
Model Registry
      โ†“
Deployment
      โ†“
Inference
      โ†“
Monitoring
      โ†“
Drift Detection
      โ†“
Retraining

๐Ÿข ViT Production Considerations

Important production concerns include:

Model

Architecture
Parameter Count
Embedding Dimension
Number of Layers
Number of Heads
Patch Size

Performance

Accuracy
Precision
Recall
F1
Latency
Throughput

Infrastructure

GPU Memory
CPU
GPU
Batch Size
Autoscaling

Operations

Model Version
Checkpoint Version
Preprocessing Version
Monitoring
Rollback

๐Ÿง  High-Resolution Vision Challenge

Suppose:

Image = 1024 ร— 1024
Patch = 16 ร— 16

Number of patches:

[ \frac{1024}{16}\times\frac{1024}{16} = 64\times64 = 4096 ]

Then full self-attention has a token-pair matrix of approximately:

4096 ร— 4096

This illustrates why high-resolution vision can make global attention expensive.


๐Ÿง  Why Efficient Attention Matters

As resolution increases:

Image Resolution
      โ†“
Patch Count
      โ†“
Token Count
      โ†“
Attention Cost
      โ†“
Memory Requirement

This motivates architectures that use:

Local Attention
+
Hierarchical Processing
+
Windowed Attention
+
Sparse Attention
+
Efficient Tokenization

๐Ÿง  Hierarchical and Local Attention

Instead of every token attending to every other token:

Global Attention

P1 โ†” P2 โ†” P3 โ†” ... โ†” PN

a model may restrict attention:

Local / Window Attention

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ P1 P2 โ”‚
โ”‚ P3 P4 โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ P5 P6 โ”‚
โ”‚ P7 P8 โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

This can reduce computational requirements.


๐Ÿง  CNN + ViT Hybrid Strategy

A practical hybrid can use:

CNN
 โ†“
Local Feature Extraction
 โ†“
Downsample
 โ†“
Tokenization
 โ†“
Transformer
 โ†“
Global Context
 โ†“
Prediction

This provides a useful architectural compromise.


๐Ÿงช Practical Exercise 1 โ€” Patch Extraction

Given:

Image = 224 ร— 224
Patch = 16 ร— 16

calculate:

Number of Patches

Then implement patch extraction using PyTorch.


๐Ÿงช Practical Exercise 2 โ€” Patch Embeddings

Implement:

Image
 โ†“
Unfold / Patchify
 โ†“
Flatten
 โ†“
Linear Projection

Verify:

Input Shape
Output Token Shape

๐Ÿงช Practical Exercise 3 โ€” Positional Embeddings

Create a toy sequence:

16 Tokens

Add:

Learnable Positional Embeddings

and inspect the resulting tensor shape.


๐Ÿงช Practical Exercise 4 โ€” Self-Attention

Implement a simplified self-attention mechanism:

attention = torch.softmax(
    q @ k.transpose(-2, -1),
    dim=-1
)

output = attention @ v

Then experiment with different token counts.


๐Ÿงช Practical Exercise 5 โ€” Load Pretrained ViT

Load:

models.vit_b_16(
    weights=(
        models.ViT_B_16_Weights.DEFAULT
    )
)

Inspect:

Model Structure
Parameter Count
Input Size
Classifier

๐Ÿงช Practical Exercise 6 โ€” Transfer Learning with ViT

Replace the classification head.

Train:

Head Only

Then:

Head + Last Transformer Blocks

Compare:

Accuracy
Training Time
Validation Loss

๐Ÿงช Practical Exercise 7 โ€” CNN vs ViT

Train:

ResNet-18

and:

ViT

on the same dataset.

Compare:

Accuracy
Training Time
Inference Latency
Memory

๐Ÿงช Practical Exercise 8 โ€” CNN-ViT Hybrid

Design:

CNN
 โ†“
Feature Map
 โ†“
Tokenization
 โ†“
Transformer Encoder
 โ†“
Classifier

Implement a simplified prototype.


๐Ÿงช Practical Exercise 9 โ€” Patch Size Experiment

Compare:

Patch = 8
Patch = 16
Patch = 32

Measure:

Token Count
Training Time
Memory
Accuracy
Inference Latency

๐Ÿงช Practical Exercise 10 โ€” High Resolution

Experiment with:

224 ร— 224
384 ร— 384
512 ร— 512

Compare:

Token Count
Attention Cost
GPU Memory
Inference Latency

๐Ÿงช Practical Exercise 11 โ€” Attention Visualization

Extract attention information from a Vision Transformer and visualize how attention patterns differ across:

Layers
Heads
Images

Treat attention visualization as an analytical tool rather than a guaranteed explanation of model reasoning.


๐Ÿงช Practical Exercise 12 โ€” Production Benchmark

Compare:

ResNet-50
ViT
CNN-ViT Hybrid

under the same production constraints.

Measure:

Accuracy
P95 Latency
Throughput
GPU Memory
Model Size
Cost per Inference

Select the architecture based on the complete production trade-off.


๐Ÿง  Interview Questions

Beginner

1. What is a Vision Transformer?

A Vision Transformer is a Computer Vision architecture that represents an image as a sequence of patch tokens and processes those tokens using Transformer encoder blocks.

2. Why do ViTs divide images into patches?

Patches provide a manageable token representation of the image while preserving spatial information through positional embeddings.

3. What is a patch embedding?

A numerical representation produced by projecting a flattened image patch into the model's embedding space.

4. Why are positional embeddings needed?

They provide information about where tokens originated in the image.

5. What is a CLS token?

A learnable token commonly prepended to the patch sequence whose final representation can be used for classification.


Intermediate

6. How does self-attention work in ViT?

It computes relationships between token representations using Query, Key, and Value projections.

7. What is Multi-Head Self-Attention?

It performs attention through multiple learned attention heads, allowing different representation subspaces and relationships to be modeled in parallel.

8. Why can ViTs model global relationships effectively?

Self-attention allows tokens to directly interact with other tokens across the image.

9. What is the major computational challenge of standard self-attention?

Its attention computation generally grows quadratically with the number of tokens.

10. How does patch size affect ViT performance?

Smaller patches provide more spatial detail but increase token count and attention computation.

11. Why do ViTs often benefit from large-scale pretraining?

They have weaker built-in image-specific inductive biases than CNNs and can therefore benefit substantially from learning visual representations from large datasets.

12. What is a CNN-ViT hybrid?

An architecture that combines CNN-based local feature extraction with Transformer-based global contextual modeling.


Advanced

13. Why are CNNs often more data-efficient than ViTs?

CNNs encode strong image-specific inductive biases such as locality, weight sharing, and translation-related structure.

14. Why can ViTs outperform CNNs at scale?

With sufficient data and compute, attention-based architectures can learn highly flexible global representations and scale effectively with model and dataset size.

15. Why is high-resolution ViT inference expensive?

Higher image resolution creates more patches, which increases token count and therefore the cost of global self-attention.

16. How can the cost of Vision Transformers be reduced?

Possible approaches include:

Larger Patches
Local Attention
Windowed Attention
Hierarchical Architecture
Token Reduction
Efficient Attention
Downsampling

17. What is the difference between CNN feature maps and ViT tokens?

CNNs represent visual information primarily as spatial feature maps, while ViTs represent the image as a sequence of contextualized token embeddings.

18. Why might a hybrid model outperform either a pure CNN or pure ViT?

A hybrid can combine CNN locality and efficient spatial processing with Transformer global context.

19. How would you fine-tune a pretrained ViT?

Start with the classification head, freeze most of the Transformer backbone, then progressively unfreeze selected Transformer blocks using a smaller learning rate.

20. How would you select between ResNet and ViT for production?

Evaluate:

Accuracy
Latency
Throughput
Memory
Training Data
Pretraining Availability
Inference Cost
Hardware

rather than selecting solely on benchmark accuracy.

21. Why does patch size influence computational cost so strongly?

Because token count grows inversely with the square of patch size for a fixed image resolution, while global attention scales approximately quadratically with token count.

22. What happens when image resolution doubles?

If patch size remains constant, the number of patches increases by approximately four times in two dimensions, while a full attention matrix can increase by approximately sixteen times.


๐Ÿข Enterprise Perspective

Vision Transformers represent an important architectural transition:

Hand-Designed Local Structure
          โ†“
CNN Feature Learning
          โ†“
Residual CNNs
          โ†“
Attention-Based Vision
          โ†“
Multimodal Foundation Models

For enterprise AI engineers, the important lesson is not simply:

"ViT is better than CNN."

Instead:

Architecture selection should be driven by workload requirements, available data, pretraining, infrastructure, and production constraints.


๐Ÿข Enterprise Model Selection

A production architecture decision should consider:

Business Requirements
        โ†“
Dataset Characteristics
        โ†“
Model Candidates
        โ†“
Accuracy Benchmark
        โ†“
Latency Benchmark
        โ†“
Cost Benchmark
        โ†“
Operational Complexity
        โ†“
Production Decision

๐Ÿข Enterprise Vision Platform

A scalable platform may expose:

VisionProvider
      โ”‚
      โ”œโ”€โ”€ CNN
      โ”‚
      โ”œโ”€โ”€ ViT
      โ”‚
      โ”œโ”€โ”€ Hybrid
      โ”‚
      โ””โ”€โ”€ Vision Foundation Model

Applications consume capabilities:

classify()
embed()
detect()
segment()

rather than depending directly on a particular model architecture.


๐Ÿข Production Vision Architecture

flowchart TD

    CLIENT["Enterprise Application"]

    GATEWAY["API Gateway"]

    VISION["Vision Service"]

    PREPROCESS["Preprocessing"]

    ROUTER["Model Router"]

    CNN["CNN Model"]

    VIT["Vision Transformer"]

    HYBRID["CNN-ViT Hybrid"]

    OUTPUT["Prediction / Embedding"]

    MONITOR["Monitoring"]

    CLIENT --> GATEWAY
    GATEWAY --> VISION
    VISION --> PREPROCESS
    PREPROCESS --> ROUTER

    ROUTER --> CNN
    ROUTER --> VIT
    ROUTER --> HYBRID

    CNN --> OUTPUT
    VIT --> OUTPUT
    HYBRID --> OUTPUT

    VISION --> MONITOR
    OUTPUT --> MONITOR

A model router can select different models based on:

Task
Latency Requirement
Input Resolution
Model Availability
Cost

๐Ÿข Model Governance

For production Vision Transformer systems, track:

Model Architecture
Checkpoint
Pretraining Dataset
Model License
Patch Size
Input Resolution
Embedding Dimension
Number of Layers
Number of Heads
Target Dataset
Training Configuration
Model Version
Evaluation Results
Deployment Version

๐Ÿข Production Monitoring

Monitor:

P50 Latency
P95 Latency
P99 Latency
Throughput
GPU Utilization
GPU Memory
Prediction Distribution
Input Distribution
Data Drift
Error Rate
Business Metrics

๐Ÿข Cost Considerations

A larger Transformer may provide higher accuracy but also:

Higher GPU Cost
+
Higher Memory
+
Higher Latency
+
Lower Throughput

Therefore:

Model Accuracy
      โ‰ 
Production Value

Production value depends on the complete system.


๐Ÿง  Architecture Decision Example

Suppose an enterprise needs:

Real-Time Camera Classification

with:

Latency < 50 ms
Limited GPU
Moderate Dataset

A lightweight CNN may be a better initial choice.


Suppose the requirement is:

Large-Scale Image Retrieval
+
Large Pretrained Dataset
+
GPU Infrastructure

A Vision Transformer may be attractive.


Suppose the requirement is:

High-Resolution Industrial Inspection
+
Local Defect Detection
+
Global Context

A CNN-Transformer hybrid may be worth evaluating.


๐Ÿง  Architecture Decision Matrix

                   Locality      Global Context

CNN                    โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ        โ–ˆโ–ˆโ–ˆโ–ˆ
ViT                    โ–ˆโ–ˆโ–ˆโ–ˆ            โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ
Hybrid                 โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ         โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ

This is a conceptual comparison, not a benchmark.


Production Insight

Vision Transformers should not be adopted simply because Transformers are dominant in modern AI.

For a production Computer Vision system, evaluate:

Dataset Size
+
Pretraining
+
Accuracy
+
Latency
+
Throughput
+
GPU Memory
+
Cost
+
Deployment Environment

CNNs remain extremely valuable, especially for efficient vision workloads.

The most practical architecture may also be a hybrid:

CNN
  โ†“
Local Feature Extraction
  โ†“
Transformer
  โ†“
Global Context
  โ†“
Prediction

The goal of architecture selection is not to choose the newest model. It is to choose the model that satisfies the complete production workload.


๐Ÿ“Œ Key Takeaways

  • Vision Transformers apply Transformer architectures to Computer Vision.
  • Images are divided into fixed-size patches.
  • Each patch becomes a token representation.
  • Patch embeddings convert image patches into model embeddings.
  • Positional embeddings provide spatial information.
  • A CLS token is commonly used for classification.
  • Self-attention allows image regions to model relationships with other regions.
  • Multi-Head Self-Attention allows multiple attention patterns to be learned.
  • Transformer Encoder blocks contain attention, MLP, normalization, and residual connections.
  • Standard self-attention has approximately quadratic complexity with respect to token count.
  • Smaller patches increase token count and computational cost.
  • ViTs often benefit strongly from large-scale pretraining.
  • CNNs provide strong locality and image-specific inductive biases.
  • ViTs provide flexible global relationship modeling.
  • Neither CNNs nor ViTs are universally superior.
  • CNN-ViT hybrids combine local convolutional features with global attention.
  • Hierarchical vision architectures help manage computational complexity.
  • Pretrained ViTs can be adapted using Transfer Learning and fine-tuning.
  • Correct preprocessing is part of the pretrained model contract.
  • High-resolution vision creates significant attention and memory challenges.
  • Production model selection must consider accuracy, latency, throughput, memory, and cost.
  • Vision Transformers form an important bridge from traditional Deep Learning toward modern multimodal and Vision Foundation Models.

๐Ÿ“š Further Reading

Continue with:

The next phase moves from Computer Vision into Sequential Learning and Transformers, beginning with Recurrent Neural Networks and their role in modeling sequential data.


โžก๏ธ Next Chapter

24. Recurrent Neural Networks


Enterprise AI Engineering Handbook
Building Production-Grade Enterprise AI Systems โ€” One Chapter at a Time.