liveBook · Manning

Vision Transformer

As explained in Deep Learning with PyTorch, Second Edition

A transformer-based neural network adapted for computer vision tasks, especially image classification, by processing image patches with attention.

A Vision Transformer (ViT) adapts the Transformer architecture to images. Instead of reading characters or words, it reads an image as a sequence of smaller patches, allowing attention to model relationships across the image. section 9.9

A ViT classification pipeline works as follows:

  • Splits an image into a grid of patches, flattens them, and embeds each patch in a high-dimensional space. section 9.9
  • Prepends a learnable [CLS] token and adds learnable positional embeddings so the model retains patch locations. section 9.9
  • Passes the resulting [B, N+1, D] sequence through Transformer encoder blocks using self-attention and multiheaded attention. section 9.9
  • Uses only the [CLS] output for classification because it aggregates information attended to from the other image patches. section 9.9

Loading a pretrained ViT

Torchvision can instantiate a ViT-B/16 with ImageNet-1K weights: vit = models.vit_b_16(weights=models.ViT_B_16_Weights.IMAGENET1K_V1). The model contains 88.6 million parameters and supports image classification. section 2.1.3

Figure 9.14 Image converted to image patches, which are then flattened and fed into the model
figure

Follow the patch-conversion diagram to see how an image becomes flattened image-token inputs. section 9.9

Figure 9.15 Vision Transformer architecture. The image tokens are passed through a patch embedding layer, and then positional information is added before being fed into the transformer encoder blocks. Only one single output [CLS] token is used in the final output head for classification.
figure

Inspect the architecture diagram showing patch embedding, positional information, encoder blocks, and the final [CLS] classification output. section 9.9

How Deep Learning with PyTorch, Second Edition covers it

How deep it goes
Explains patch tokens, embeddings, positional information, sequence shape, encoder flow, and [CLS] aggregation without implementing ViT internals from scratch.
Examples
Uses Torchvision ImageNet classification, patch diagrams, and SAM's ViT-based image encoder as concrete examples.
What you can do after
Apply it via Torchvision, fine-tune it on a small dataset, and compare patch size or embedding dimension effects.
How it connects
Connects image patches with self-attention, multiheaded attention, positional embeddings, Transformer encoders, and image segmentation.

Also explained in

Compare how 7 books explain Vision Transformer →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Deep Learning with PyTorch, Second Edition. The section links point to the parts of the book it draws on.