Lesson 4.5 — Vision Transformer
Previous lesson · 4.4 Autoregressive Language Modeling · Course overview · Next lesson · 4.6 Graph Neural Networks
From Spatial Grids to Image Sequences
Lesson 3.2 uses a CNN with local connections and shared kernels. Lesson 4.3 uses a Transformer with input-dependent weighted aggregation. A Vision Transformer (ViT) divides an image into patches, projects each patch into a continuous vector, and lets the vectors exchange information in an encoder. Each patch starts as a vector of pixels rather than a vocabulary ID.
CNN
Local kernels build up receptive fields across layers, then global pooling combines spatial features. The convolutional structure favors local patterns and weight sharing across locations.
ViT
Patch projections and position encodings form the input sequence. Global self-attention mixes information across the sequence, and CLS or pooling provides an image-level representation.
The original ViT uses learned absolute position embeddings and a stack of encoder blocks. This miniature model uses fixed sinusoidal positions, a single pre-norm encoder block, a GELU feed-forward network, and a learned CLS vector so the computation is easy to inspect.
Image Patchification · From Pixels to Tokens
Use batch-first NCHW layout and square, nonoverlapping patches of side length P. Assume both image dimensions are divisible by P. Traverse patch positions from left to right and top to bottom. Within each patch, flatten in channel, row, column order. The batch axis is preserved.
For a 224 × 224 RGB image with P = 16, there are 196 patches, each with 768 values. Adding CLS gives 197 tokens. With P = 8, there are 784 patches and 785 tokens. If the image dimensions are incompatible with the patch size, choose a cropping, padding, or resizing rule first.
Image Patchification Player
The grayscale example has one channel. RGB uses the same row-major pixel order within each channel, then concatenates the channels.
Patch Embedding · Linear Projection
Every patch uses the same matrix and bias. The raw patch width CP² can differ from the model width D. The projection acts directly on the pixel values, then adds the same bias to each projected patch.
A convolution with kernel size and stride P and zero padding width gives the same computation. Reshape the transpose of W_E to (D, C, P, P), then flatten the output spatial axes and transpose to (B, N, D). The two outputs agree when pixel ordering and biases match. PyTorch nn.Linear stores weights in (out, in) order. This lesson writes row vectors multiplying weights on the right.
Patch Embedding Inspector
Every patch is multiplied by the same matrix. This projection acts on pixel values, so changing the pixels can change the embedding without moving the patch.
Position and the CLS Token
CLS is a learned classification vector shared across images. Prepend it to the patch sequence so attention can mix patch information into that row. At the end of the encoder, the classifier reads the CLS row. Mean pooling over patch rows is another possible readout.

The letters identify pieces of the illustration and are excluded from the pixel data. Both images contain exactly the same four patches. Only B and D have traded places. On the left, two short strokes meet at a boundary. On the right they lie in different rows. A classifier asked to detect one continuous stroke must distinguish these arrangements.
Let be the projected patches. A shared projection produces the same wherever B lands. With position embeddings attached to grid slots, B enters the encoder as on the left and on the right. The encoder now has the information needed to learn adjacency. Whether it uses it depends on training.
Without position encodings or a mask, the encoder is permutation equivariant over token rows. Permuting the patches while keeping CLS in place leaves the CLS output invariant. Patch flattening and projection still retain the order of pixels within each patch. Here the one-dimensional sinusoidal positions follow row-major patch order. Two-dimensional or relative position methods can express spatial relationships more directly. A model with learned absolute spatial embeddings may need to interpolate them when image resolution changes.
Compare patch embeddings with and without the position signal
CLS Token & Positional Embedding
CLS is a learned vector shared across images. The position code adds a fixed vector to each sequence row, including CLS at row zero.
Visual Self-attention · Patch-to-Patch Relationships
The image classifier uses bidirectional self-attention. Every token, including CLS, can read every token. Compare this with the causal decoder from Lesson 4.4, where each token can read only its prefix. The learned heads can assign different weights to patches.
Visual Self-attention Map
Read along one query row. Map opacity is rescaled within that row for visibility, while percentages display the actual weights. CLS has no image region and its self-weight is reported separately.
ViT Encoder Block · Full Tensor Dataflow
Apply the pre-norm Transformer block from Lesson 4.3 to visual tokens with bidirectional attention. The classifier reads the final CLS representation. Patch rows can influence that representation through self-attention.
ViT Block Dataflow
| Stage | Default shape | Parameters |
|---|---|---|
| Patchify | (B,4,16) | 0 |
| Patch Linear + bias | (B,4,8) | 136 |
| CLS + fixed position | (B,5,8) | 8 |
| Q/K/V/O | (B,2,5,4) per Q/K/V | 256 |
| FFN (no bias) | (B,5,16) hidden | 256 |
| Two LayerNorms | (B,5,8) | 32 |
| CLS head + bias | (B,3) | 27 |
| Total | 1 block | 715 |
For dense visual prediction, retain the patch rows and reshape them into the original spatial grid. The original ViT applies a final LayerNorm. This teaching model leaves that operation out of the encoder trace.
Resolution & Computational Complexity
At fixed image resolution, smaller patches give finer spatial granularity and a longer token sequence. Let T = N + 1 include CLS, D be the model width, H_a the number of heads, and F the FFN hidden width. The estimates below count dense matrix products in one encoder block and the bytes needed for one materialized attention score tensor.
Halving the patch side length quadruples the patch count when both sizes divide the image dimensions. The quadratic attention term grows by approximately 16× when the CLS contribution is small. The patch projection takes roughly HWCD multiply–accumulates, independent of patch size, while its weight count grows with P². Actual memory use and latency also depend on data type, hardware, and whether the attention kernel materializes its scores.
Resolution & Computational Complexity
Counts describe one square RGB image and one encoder block with FFN width 4D. Block parameter counts include two LayerNorms and assume bias-free linear layers. MAC counts exclude the patch projection, classification head, and elementwise operations.
Visual Tokens for Multimodal Models · Cross-attention
Patch representations can become visual tokens for another module. In cross-attention, the query comes from a separate sequence, such as text or actions. Keys and values come from the visual representations. The output has one row per query, regardless of the number of patches.
Another design projects the visual features to the language model width, concatenates them with text tokens, and uses joint self-attention. This lab isolates cross-attention and tensor shapes. Chapter 6 covers broader vision–language training and visual feature projectors.
Visual Cross-attention Explorer
The external query has one row. Four patch tokens provide keys and values, so the output is one context vector. CLS is excluded from this patch retrieval example.
Engineering Experiment · Robot Vision Transformer
The synthetic defect task from Lesson 3.2 uses 8 × 8 grayscale images with a random-position vertical or horizontal line, or no defect. The generator adds uniform pixel noise. Draw 48 training images with the training seed and 24 validation images with seed plus 1000. The default mini ViT uses patches of size 4, width 8, two attention heads, and an FFN of width 16. The 55-parameter CNN uses one convolution, ReLU, global average pooling, and a linear classifier. Both models use the same data and full-batch Adam budget of 100 updates at learning rate 0.03. Their parameter counts and initializations differ.
| Training images | Validation images | ViT parameters (P=4) |
|---|---|---|
| 48 | 24 | 715 |
Live Mini ViT vs. CNN Training
Actual default benchmark (PyTorch)
| Model | Parameters | Train CE | Val CE | Val accuracy |
|---|---|---|---|---|
| ViT + PE | 715 | 0.00000215 | 0.207478 | 23/24 = 95.83% |
| ViT − PE | 715 | 0.255373 | 0.232838 | 22/24 = 91.67% |
| CNN | 55 | 0.017261 | 0.026326 | 24/24 = 100% |
With position encoding, the ViT nearly minimizes the training cross-entropy at the reported checkpoint. The CNN achieves lower validation cross-entropy on this small split. Local structure, parameter count, initialization, and optimization may affect the comparison. The ViT without positions can still distinguish patterns within each patch. Evaluating data efficiency or relative architecture performance would require several training set sizes, multiple seeds, an independent test set, and matched budgets.
Reproducible PyTorch implementation
Save the script as vit0405.py and run it with PyTorch installed. It uses unfold and scaled dot-product attention. The script checks the equivalence of patch projection and a convolution with kernel size and stride equal to the patch size.
import math
import torch
from torch import nn
from torch.nn import functional as F
torch.set_default_dtype(torch.float64)
torch.set_num_threads(1)
# Same data generator and CNN as 0302.
class RNG:
def __init__(self, seed): self.s=seed & 0xffffffff
def __call__(self):
self.s=(1664525*self.s+1013904223)&0xffffffff
return self.s/4294967296
def dataset(n,seed,noise=.12):
r=RNG(seed); X=[]; Y=[]
for i in range(n):
c=i%3; p=1+int(6*r()); Y.append(c)
X.append([.2+.7*int((c==1 and j%8==p) or (c==2 and j//8==p))+noise*(2*r()-1) for j in range(64)])
return torch.tensor(X).reshape(n,1,8,8),torch.tensor(Y,dtype=torch.long)
def patchify(x,P):
return F.unfold(x,kernel_size=P,stride=P).transpose(1,2)
def positions(T,D):
return torch.tensor([[math.sin(t/10000**(2*(j//2)/D)) if j%2==0 else math.cos(t/10000**(2*(j//2)/D)) for j in range(D)] for t in range(T)])
class MiniViT(nn.Module):
def __init__(self,P=4,D=8,H=2,seed=3):
super().__init__(); assert 8%P==0 and D%H==0
self.P,self.D,self.H=P,D,H
r=RNG(seed+2000)
shapes=[('E',P*P,D),('eb',1,D),('cls',1,D),('Q',D,D),('K',D,D),('V',D,D),('O',D,D),('U',D,2*D),('W',2*D,D),('g1',1,D),('b1',1,D),('g2',1,D),('b2',1,D),('R',D,3),('rb',1,3)]
self.p=nn.ParameterDict()
for name,a,b in shapes:
vals=[1. if name.startswith('g') else 0. if name in ('eb','b1','b2','rb') else .8*(r()-.5) for _ in range(a*b)]
self.p[name]=nn.Parameter(torch.tensor(vals).reshape(a,b))
def forward(self,x,position=True):
p=self.p; B=x.shape[0]; D,H=self.D,self.H; d=D//H
E=patchify(x,self.P)@p['E']+p['eb']; X=torch.cat([p['cls'].expand(B,-1,-1),E],1)
T=X.shape[1]
if position: X=X+positions(T,D).to(x)
N=F.layer_norm(X,(D,),p['g1'].flatten(),p['b1'].flatten(),1e-5)
split=lambda a:a.reshape(B,T,H,d).transpose(1,2)
q,k,v=[split(N@p[n]) for n in ('Q','K','V')]
A=F.scaled_dot_product_attention(q,k,v,dropout_p=0,is_causal=False).transpose(1,2).reshape(B,T,D)@p['O']
Y=X+A; M=F.layer_norm(Y,(D,),p['g2'].flatten(),p['b2'].flatten(),1e-5)
Z=Y+F.gelu(M@p['U'],approximate='tanh')@p['W']
return Z[:,0]@p['R']+p['rb']
class TinyCNN(nn.Module):
def __init__(self,filters=4,seed=3):
super().__init__(); self.conv=nn.Conv2d(1,filters,3); self.head=nn.Linear(filters,3); r=RNG(seed+2000)
with torch.no_grad():
for p in (self.conv.weight,self.head.weight): p.copy_(torch.tensor([.8*(r()-.5) for _ in range(p.numel())]).reshape(p.shape))
self.conv.bias.zero_(); self.head.bias.zero_()
def forward(self,x): return self.head(F.relu(self.conv(x)).mean((2,3)))
def run(seed=3,P=4,noise=.12,lr=.03,updates=100,position=True,kind='vit'):
X,Y=dataset(48,seed,noise); V,T=dataset(24,seed+1000,noise)
m=MiniViT(P,8,2,seed) if kind=='vit' else TinyCNN(4,seed)
pred=lambda x:m(x,position) if kind=='vit' else m(x)
opt=torch.optim.Adam(m.parameters(),lr=lr); hist=[]
for t in range(updates+1):
loss=F.cross_entropy(pred(X),Y)
if t%10==0 or t==updates:
with torch.no_grad():
z=pred(V); y=z.argmax(1); cm=torch.bincount(3*T+y,minlength=9).reshape(3,3)
p={k:v.detach().tolist() for k,v in m.p.items()} if kind=='vit' else [p.detach().flatten().tolist() for p in m.parameters()]
hist.append(dict(t=t,tr=loss.item(),va=F.cross_entropy(z,T).item(),acc=(y==T).double().mean().item(),cm=cm.tolist(),p=p))
if t<updates: opt.zero_grad(); loss.backward(); opt.step()
return m,hist
if __name__=='__main__':
for kind,pos in [('vit',True),('vit',False),('cnn',True)]:
m,h=run(position=pos,kind=kind)
print(kind,pos,sum(p.numel() for p in m.parameters()),{k:v for k,v in h[0].items() if k!='p'},{k:v for k,v in h[-1].items() if k!='p'})
# Conv2d with kernel = stride = P equals patch projection (CHW order).
X,_=dataset(3,3); m=MiniViT(); p=m.p
direct=patchify(X,4)@p['E']+p['eb']
conv=F.conv2d(X,p['E'].T.reshape(8,1,4,4),p['eb'].flatten(),stride=4).flatten(2).transpose(1,2)
torch.testing.assert_close(direct,conv)
AI-native verification workflow
Trace the patch count, Q/K/V shapes, and CLS row through the block. Check attention row sums and compare the patch outputs from unfold and Conv2d. With positions disabled, reorder patch rows and compare CLS outputs. In the training comparison, vary one setting at a time and record the parameter count, cross-entropy, and accuracy. Follow the same path in an implementation from patch embedding through encoder blocks to normalization and readout.
Authoritative References
Lesson 4.6 replaces the regular image grid with an explicit graph. It follows messages along edges and shows how to normalize and aggregate them.
Previous lesson · 4.4 Autoregressive Language Modeling · Course overview · Next lesson · 4.6 Graph Neural Networks