Welcome everyone. Today we begin with an overview of Vision Transformers, or ViTs, which adapt the Transformer architecture from natural language processing directly to computer vision, challenging the decades-long dominance of convolutional networks.
At its core, a Vision Transformer discards convolutions entirely. The image is split into fixed-size patches, typically sixteen by sixteen pixels, each flattened and linearly projected into an embedding. These patch embeddings form a token sequence, processed by the same self-attention machinery used for words in text.
Because self-attention is permutation-invariant, the model has no built-in notion of spatial order. Learnable positional embeddings are added to each patch token to encode its location in the two-dimensional grid, restoring the spatial structure the architecture itself lacks.
The key insight is inductive bias. Convolutions hardwire locality and translation equivariance; ViTs do not. Dosovitskiy and colleagues showed in 2020 that with sufficient pretraining data, such as JFT-300M, ViTs outperform CNNs on benchmarks like ImageNet, but they underperform when data is scarce.
To summarize, ViTs leverage multi-head self-attention to model global interactions across the entire image from the first layer, trading built-in spatial priors for scalability and a uniform architecture across modalities.
Next, we examine the core architecture and motivation in detail, including the classification token, the encoder stack, and hands-on PyTorch implementations to solidify these concepts.
Equations, code and original cards
Overview of Vision Transformers
• Transformer architecture adapted from NLP to vision
• Images as token sequences: 16×16 patches, linearly projected
• Learnable positional embeddings restore spatial order
• Historical context: Dosovitskiy et al. 2020, ViT breakthrough
• Core architecture and motivation
Conceptual Foundation
• ViT treats image patches as tokens, analogous to words in NLP
• Transformer encoder: multi-head self-attention over patch tokens
• Positional embeddings compensate for permutation invariance
Moment 02 / 10
Mathematical Foundations of Vision Transformers
Today we examine the mathematical foundations of Vision Transformers, the ViT architecture introduced by Dosovitskiy and colleagues in 2021. The core idea is to tokenize an image and then process it with the same machinery that dominates sequence modeling.
First, we partition the image into non-overlapping 16 by 16 patches. Each patch is flattened into a 768-dimensional vector, since 16 times 16 times 3 color channels equals 768. These tiles play the role that tokens play in language modeling.
Mathematically, each flattened patch is projected through a learnable linear embedding into the model's hidden dimension. This reshaping converts two-dimensional spatial structure into a one-dimensional sequence, which is precisely the inductive bias ViT gives up relative to convolutions.
Next, the transformer attention mechanism: queries, keys, and values are linear projections of the embedded sequence, and attention weights come from the softmax of Q K transpose scaled by one over the square root of d-k. This lets every patch attend to every other patch.
To ground this in practice, here is a PyTorch snippet implementing patch embedding and scaled dot-product attention. Note that positional information must be injected explicitly, because attention itself is permutation-invariant and has no notion of spatial layout.
The unfold operations extract the patch grid directly from the image tensor, and the linear layer maps each 768-dimensional patch into the embedding space. This is exactly the tokenization pipeline the attention layers consume downstream.
To summarize: images are tokenized into flattened patches, linearly embedded, augmented with positional encodings, and processed by multi-head self-attention. Next we will trace gradient backpropagation through this stack and examine the training objective.
Start with the patchify operator: a 224 by 224 RGB image becomes 196 non-overlapping 16 by 16 patches, the token grid used by Dosovitskiy and colleagues in Vision Transformer.
Each patch is flattened and passed through one linear projection, equivalently a stride 16 convolution, producing token embeddings that enter the residual stream rather than handcrafted features.
Because self attention is permutation equivariant, we inject learned two dimensional positional embeddings, adding spatial coordinates to the residual stream so attention logits can depend on where tokens sit.
Now perturb that table: shuffle positions, zero them, or interpolate a coarser grid, and watch token similarity, attention maps, and effective receptive field degrade as geometry is removed.
In PyTorch, use a convolution with kernel and stride equal to patch size, then add learned positions and a class token before layer normalization and the encoder.
The trade-off is sequence length against detail: sixteen gives 196 tokens, thirty-two gives 49, cutting quadratic attention cost but weakening spatial inductive bias, sample efficiency, and fine-grained localization.
Equations, code and original cards
Moment 04 / 10
Comparing ViT and CNN Architectures
Let's compare Vision Transformers and Convolutional Neural Networks at the architectural level. The contrast between their inductive biases explains nearly every difference in how they perform on visual recognition tasks.
CNNs build features from local receptive fields: each convolutional output aggregates only a small spatial neighborhood. ViTs instead apply global self-attention, so every patch token interacts with every other token from the first layer onward. This single distinction drives most of the architectural divergence.
Here is the self-attention operation: softmax of Q K transpose over the square root of d-k, times V. Each patch token computes attention weights against all others, so the model explicitly scores the relevance of every image region to every other region.
Because attention is global, a ViT's effective receptive field spans the full image immediately. A CNN achieves comparable context only by stacking many layers, since each convolution expands the receptive field by roughly the kernel size.
In contrast, the convolution here combines inputs within a fixed kernel window using shared weights. That weight sharing plus spatial locality is a strong inductive bias: translation equivariance is built in rather than learned from data.
Locality makes CNNs parameter-efficient and data-efficient for texture and edge detection, but long-range dependencies require deep stacks. ViTs capture those dependencies in one attention layer, at the cost of weaker spatial priors and higher sample complexity.
These PyTorch snippets make the structural difference concrete. Reading the forward passes side by side grounds the theory in actual computation graphs.
The ViT forward pass flattens the image into patch embeddings, runs them through transformer encoder blocks, and classifies from the class token at position zero. There is no spatial hierarchy beyond the initial patching.
The CNN forward pass applies stacked convolutions, flattens the final feature map, and feeds it to a fully connected head. Note the locality is hard-coded into the convolution, while the ViT must learn spatial structure from positional encodings.
To summarize: local versus global processing, hard-coded versus learned inductive biases, and the resulting trade-offs in sample complexity and compute. These differences explain why ViTs dominate at scale while CNNs remain competitive in data-limited regimes.
Equations, code and original cards
Comparing ViT and CNN Architectures
Architectural Differences and Key Concepts
• Local receptive fields (CNN) vs. global self-attention (ViT)
• Effective receptive field: depth-limited vs. immediate
• Inductive bias: translation equivariance vs. learned spatial structure
class ViT(nn.Module): def forward(self, x): x = self.patch_embedding(x) x = self.transformer(x) return self.mlp_head(x[:, 0])
class CNN(nn.Module): def forward(self, x): x = self.conv_layers(x) x = torch.flatten(x, 1) return self.fc(x)
Moment 05 / 10
Advanced Techniques & Optimizations (2024-2026)
Here we survey the frontier of Vision Transformer optimization for 2024 through 2026. The slide collects the scaling laws, efficient attention, and robustness methods that currently define state-of-the-art practice and compute allocation.
Scaling laws, following Kaplan and the Chinchilla analysis of Hoffmann, let us predict loss as a power law in parameters, data, and compute, so we allocate flops before training rather than after.
The fitted form is C of n equals alpha times n to the power a plus beta, with a positive exponent when C denotes required compute. It converts parameter count into an expected training flop budget before any run.
The PyTorch snippet uses a Linformer-style low-rank projection of keys and values, cutting attention from order n squared in sequence length toward linear while preserving accuracy.
Augmentation, stochastic depth, and label smoothing regularize; hybrid convolution transformer stems restore locality bias; alignment losses improve robustness under distribution shift and adversarial perturbation.
Together these methods trade off scale, efficiency, and resilience rather than maximizing any one. Keep them in mind as the reference toolkit for modern Vision Transformer design.
Equations, code and original cards
Advanced Techniques & Optimizations (2024-2026)
• ViT scaling laws: Kaplan 2020, Chinchilla, Zhai 2022
Mathematical Derivations and Whiteboard Walkthrough
We will derive the mechanics rather than admire them: attention logits, softmax normalization, reverse-mode gradients, cross-entropy, and the stability tricks that make deep training converge.
Start with scaled dot-product attention, from Vaswani and colleagues in 2017: form logits by matching each query against all keys, then divide by the square root of the key dimension so the softmax input keeps unit scale.
The query and key matrices live in the same head dimension; their inner products grow with that dimension, so the scaling keeps logit variance roughly constant and prevents softmax saturation.
Softmax then exponentiates and normalizes those logits into a distribution over positions; because the weights sum to one, the output is a convex combination of value vectors rather than an unbounded mixture.
That convex combination routes information across the sequence: high-probability positions dominate the residual stream, while low-probability positions contribute almost nothing to the next representation.
For optimization, reverse-mode automatic differentiation applies the chain rule from the loss back to every parameter through the composed layers; for each preactivation, we ask how a small parameter perturbation changes the final objective.
Those partial derivatives are Jacobian-vector products: exact, local sensitivities that accumulate layer by layer into the gradient used for each weight update.
Backpropagation is therefore not a separate learning rule; it is the efficient bookkeeping that lets gradient descent see every operation contribution to error.
For image classification, cross-entropy compares the predicted softmax distribution with the target distribution; with one-hot labels it reduces to the negative log likelihood assigned to the correct class.
Minimizing that objective increases the probability mass on the true label and, through the softmax coupling, suppresses competing logits.
The main pathologies are vanishing and exploding gradients: products of many Jacobians can shrink toward zero or blow up, so updates either stall or become unstable.
Saddles and plateaus are more common than bad local minima in high dimensions; gradient clipping, layer normalization, residual connections, and adaptive optimizers keep the gradient norm usable.
These pieces, scaled attention, reverse-mode differentiation, cross-entropy, and norm-aware optimization, are the working mathematics behind Vision Transformers, from patch embeddings to classification logits.
Equations, code and original cards
Self-Attention, Backpropagation, and Loss Geometry
Let's examine the PyTorch implementation of a Vision Transformer, walking through each component — patch embedding, positional encoding, multi-head self-attention — and the training loop that integrates them.
Patch extraction uses nn.Unfold with kernel and stride equal to the patch size, producing non-overlapping patches that are flattened into tokens. This converts the two-dimensional spatial grid into a sequence the transformer consumes.
Positional embeddings restore the spatial information discarded by flattening. ViT uses a learned parameter of shape one by num patches plus one by embedding dimension, broadcast-added to every token embedding.
The self-attention module projects tokens to queries, keys, and values, computes scaled dot-product attention — Q K transpose over the square root of the head dimension — then softmax-normalizes and aggregates values across all patches.
For training, cross-entropy loss over the class logits pairs with AdamW — Adam with decoupled weight decay — at a learning rate around three e minus four, the standard recipe for ViT optimization.
These components assemble into a standard training loop: forward pass, loss computation, backpropagation through the residual stream, and an optimizer step, repeated over epochs until convergence.
In summary, these snippets show how patch embedding, positional encoding, multi-head attention, and optimization compose into a working Vision Transformer — the full architecture in roughly fifty lines of PyTorch.
Equations, code and original cards
Implementation Details: PyTorch Code Examples
Key Components of Vision Transformer Implementation
Let's trace a complete forward pass through a Vision Transformer, from linear patch embedding all the way to the classification logits.
Now vary the patch size and the embedding dimension, then rerun. Watch how the token count, and with it the quadratic self-attention cost, reshapes the attention maps.
The output panel visualizes the class token's logit vector alongside per-head attention maps from every transformer block.
Sweep these configurations yourself. Notice that halving the patch size quadruples the sequence length, refining spatial resolution at real computational expense.
Equations, code and original cards
Moment 09 / 10
Cutting-Edge Variations and Open Research Questions
The frontier is no longer the vanilla vision transformer; it is multimodal alignment, subquadratic attention, robust deployment, and scaling behavior. Treat these as coupled systems questions, not isolated tricks.
CLIP aligns image and text encoders with a temperature-scaled contrastive loss, yielding zero-shot classification. Whisper is different: an audio encoder-decoder, useful because sequence modeling transfers across modalities.
Adaptive tokenization prunes or merges redundant patches, while sparse attention restricts affinities to local bands, landmarks, or routing clusters, cutting quadratic cost toward near-linear without losing global context.
In PyTorch, a boolean mask is added to attention logits before softmax; masked positions receive negative infinity, so probability mass flows only through allowed edges such as bands and global tokens.
Formally, dense attention forms softmax of queries times keys transposed, scaled by the square root of head dimension, then values; cost grows as sequence length squared times width, while sparsity keeps chosen pairs.
Robustness is not cosmetic: small norm-bounded perturbations can flip predictions, and learned embeddings can encode demographic skew, so evaluation must include adversarial stress tests, subgroup calibration, and mitigation audits.
For edge deployment, prefer depthwise convolutions, low-rank projections, quantization-aware training, and operator fusion; measure latency, memory traffic, and energy, not accuracy alone.
Open questions include whether vision scaling laws mirror Kaplan and Chinchilla, how tokenization changes sample complexity, and whether objectives beyond classification align features with human perceptual and causal structure.
The agenda is therefore joint: better inductive bias, cheaper attention, verified robustness, and hardware-aware training, evaluated by scaling curves and failure modes rather than leaderboard deltas alone.
Equations, code and original cards
Frontier Directions in Vision Transformers
1. Multimodal Alignment
• CLIP: contrastive image-text embedding, zero-shot transfer
• Optimize latency, memory traffic, energy on target silicon
5. Open Research Questions
• Vision scaling laws, tokenization and sample complexity
• Objectives aligned with perception, causality, and control
# boolean mask: local bands plus global tokenslogits = q @ k.transpose(-2, -1) / math.sqrt(d)logits = logits.masked_fill(~mask, float('-inf'))
\text{Efficient Attention: }\quad \text{Attention}(Q,K,V) = \text{softmax} \left( \frac{QK^T}{\sqrt{d}} \odot M \right) V
Moment 10 / 10
Challenging Vision Transformer Quiz
Time to stress-test your understanding of Vision Transformers. Work through each question independently—think carefully about patch embeddings, positional encodings, and the quadratic cost of global self-attention. I'll review the reasoning with you after you submit.
Equations, code and original cards
MAKE IT YOURS
Explain the change.
References, scope & corrections
Research snapshots in the source material are not a claim of current state of the art. The reference review corrects identified errors; it is not exhaustive certification of every historical statement. Source code snippets are examples, not a tested production training system.