Course map
Stage 1: Foundations
Stage 2: Machine Learning
Stage 3: Deep Learning
Stage 4: LLMs & Generative AI
Stage 5: Production & Specialization

Part 12 / Stage 3

Architectures

Goal: The building blocks of modern models: convolutions, embeddings, attention — assembled into the transformer. Time: ~3 hours · Needs: Parts 10–11

What you will learn

  • Convolutional networks: filters, padding, pooling
  • Sequence models: RNN and LSTM ideas, and their limits
  • Embeddings: learned vectors for tokens
  • Attention: queries, keys, values
  • The transformer
  • Pretraining and fine-tuning

Topics in this part

Practice

Exercise 1: Count parameters

Compute by hand the parameter count of nn.Conv2d(1, 16, kernel_size=3) and of a dense nn.Linear(64, 16). Verify both with sum(p.numel() ...). Which scales with image size?

Show the solution to Exercise 1
# Exercise 1: Count parameters
import torch
from torch import nn

conv = nn.Conv2d(1, 16, kernel_size=3)
dense = nn.Linear(64, 16)

# By hand: conv = 16 filters x (1 channel x 3 x 3) + 16 biases = 144 + 16 = 160
# dense = 64 x 16 + 16 = 1040
print("conv :", sum(p.numel() for p in conv.parameters()))
print("dense:", sum(p.numel() for p in dense.parameters()))
# The conv's count is independent of image size (filters slide); the dense
# layer's first dimension IS the flattened image, so it grows with the image.

Exercise 2: Shift test

Train the lesson's CNN and the Part 10 MLP on digits. Shift every test image one pixel right (torch.roll on the width axis, zeroing the wrapped column). Print each model's accuracy on original vs shifted images. Which degrades less?

Show the solution to Exercise 2
# Exercise 2: Shift test
import torch
from torch import nn
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

torch.manual_seed(0)
X, y = load_digits(return_X_y=True)
X = torch.tensor(X / 16.0, dtype=torch.float32)
y = torch.tensor(y)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)


def train(model, X_in):
    opt = torch.optim.Adam(model.parameters(), lr=1e-3)
    loader = torch.utils.data.DataLoader(
        torch.utils.data.TensorDataset(X_in, y_tr), batch_size=64, shuffle=True)
    for _ in range(10):
        for xb, yb in loader:
            opt.zero_grad()
            nn.functional.cross_entropy(model(xb), yb).backward()
            opt.step()
    return model


def shift_right(flat):
    img = flat.reshape(-1, 8, 8)
    img = torch.roll(img, 1, dims=2)
    img[:, :, 0] = 0.0
    return img.reshape(-1, 64)


mlp = train(nn.Sequential(nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 10)), X_tr)
cnn_body = nn.Sequential(
    nn.Unflatten(1, (1, 8, 8)),
    nn.Conv2d(1, 16, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
    nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(),
    nn.Flatten(), nn.Linear(32 * 4 * 4, 10),
)
cnn = train(cnn_body, X_tr)

for name, model in [("MLP", mlp), ("CNN", cnn)]:
    model.eval()
    with torch.no_grad():
        plain = (model(X_te).argmax(1) == y_te).float().mean().item()
        shifted = (model(shift_right(X_te)).argmax(1) == y_te).float().mean().item()
    print(f"{name}: original {plain:.3f}  shifted {shifted:.3f}  drop {plain - shifted:+.3f}")
# The CNN degrades less: shared filters + pooling buy SOME shift tolerance.
# Both drop a lot on these tiny 8x8 images — one pixel is 12% of the width;
# real augmentation (training on shifted copies) is what closes the rest.

Exercise 3: Attention by hand

With Q = K = V = [[1, 0], [0, 1]] and d = 2, compute the attention weights and output on paper, then verify in code. Why are the diagonal weights larger?

Show the solution to Exercise 3
# Exercise 3: Attention by hand
import math

import torch

Q = K = V = torch.tensor([[1.0, 0.0], [0.0, 1.0]])
d = 2

scores = Q @ K.T / math.sqrt(d)
# scores = [[1/sqrt(2), 0], [0, 1/sqrt(2)]] = [[0.7071, 0], [0, 0.7071]]
weights = torch.softmax(scores, dim=-1)
out = weights @ V

print("scores :", scores.round(decimals=4).tolist())
print("weights:", weights.round(decimals=4).tolist())
print("output :", out.round(decimals=4).tolist())
# Each token's query matches its own key (dot product 1) and is orthogonal to
# the other (0), so the diagonal gets the larger softmax weight: each token
# mostly attends to itself.

Exercise 4: Order blindness

Using random Q, K, V for 4 tokens, show that permuting the token order permutes the attention output rows identically (out[perm] == attention(Q[perm], K[perm], V[perm])). That is why transformers need positional information.


Show the solution to Exercise 4
# Exercise 4: Order blindness
import math

import torch

torch.manual_seed(0)
seq_len, d = 4, 8
Q, K, V = torch.randn(seq_len, d), torch.randn(seq_len, d), torch.randn(seq_len, d)


def attention(Q, K, V):
    weights = torch.softmax(Q @ K.T / math.sqrt(d), dim=-1)
    return weights @ V


out = attention(Q, K, V)
perm = torch.tensor([2, 0, 3, 1])
out_permuted_inputs = attention(Q[perm], K[perm], V[perm])

print("permuting inputs permutes outputs identically:",
      torch.allclose(out[perm], out_permuted_inputs, atol=1e-6))
# Attention treats tokens as a SET: reorder them and the result reorders with
# them, nothing else changes. Positional encodings are what give a transformer
# any notion of order.

Mini-project: Attention from scratch

Implement multi-head self-attention (4 heads, d_model 32) as an nn.Module: per-head Q/K/V projections, scaled dot-product per head, concatenation, output projection. Check your output shape and — using shared weights — compare against nn.MultiheadAttention.

A complete version is in solutions/mini_multihead_attention.py.

Stretch: add a causal mask and positional encodings, and train a tiny model on character sequences.

Common mistakes

Mistake Why it is wrong Fix
Dense layers on images Parameter bloat, no shift-invariance Convolutions
Forgetting positions in a transformer Attention is order-blind; "dog bites man" = "man bites dog" Positional encodings
Unscaled attention scores Softmax saturates as d grows Divide by √d
Comparing embeddings by raw distance Length ≠ meaning Cosine similarity
Fine-tuning assumed better Track C measures it losing to scratch Always baseline

Quick recap

  • A CNN shares its filters across positions — 9,930 parameters hit 0.95 on digits.
  • RNNs carry state sequentially; their two limits motivated attention.
  • An embedding is a trainable table from token id to vector, compared with cosine similarity.
  • Attention is softmax(QKᵀ/√d)V — three lines of code, verified against PyTorch's.
  • A transformer block combines multi-head attention, positional information, a feed-forward network, and residual connections with LayerNorm.
  • Pretrain once, adapt cheaply — that is the economics of modern AI.

Checklist

  • I can explain weight sharing and count a conv layer's parameters.
  • I can name the RNN's two limits.
  • I know what an embedding table's shape means.
  • I wrote attention in three lines and matched PyTorch.
  • I can list the four pieces of a transformer block.
  • I can explain pretrain-then-adapt in one sentence.

Read more: MultiheadAttention

Search the guide