TExcelTAD

Exercises

Twenty-six exercises across the whole course, most of them small enough to do on paper: shapes, parameter counts, gradients and the bugs that hide in real training code. Try each one before opening the answer. Five answers include a short NumPy program that checks the hand computation; you can edit and run it.

# Exercise Practises
1 Counting the parameters of an MLP Neurons and Layers
2 Derivatives of activations Activation Functions
3 Pick the head and the loss Output Layers and Their Losses
4 Backward through a linear layer Backpropagation, Layer by Layer
5 Gradients that add up A Small Autograd Engine, Training an MLP with Your Autograd
6 Accumulated gradients in PyTorch Autograd in PyTorch
7 A view that fails Tensors
8 Same device, or not Devices
9 Missing parameters nn.Module, Custom Layers and Hooks
10 Batches per epoch Dataset and DataLoader
11 A checkpoint that resumes exactly Checkpoints, Seeds and Reproducibility, A Reusable Training Loop
12 Training memory Memory, Mixed Precision and Multiple Devices
13 A suspicious first loss Debugging a Network
14 Initialisation scales Weight Initialisation
15 Twenty sigmoid layers Vanishing and Exploding Gradients
16 Running statistics Batch Normalisation
17 Which axis to normalise Layer Normalisation and RMSNorm
18 Dropout at training and at inference Dropout and Other Regularisers
19 The identity path Residual Connections
20 Tables and categories MLPs on Tabular Data, Embedding Layers
21 Shapes, parameters and receptive field of a CNN Convolution Layers, Pooling, Stride and Receptive Fields, A CNN in NumPy, CNN Architectures
22 Recurrent parameter counts and padding RNNs, LSTM and GRU, Training Sequence Models
23 Attention by hand Attention from Scratch
24 Transformer sizes and perplexity The Transformer Block, A Tiny Character Transformer, Vision Transformers
25 KL, the optimal discriminator and the noise level Autoencoders, VAEs, GANs, Diffusion: Noising, Diffusion: Training and Sampling
26 One GCN propagation, and choosing an architecture Message Passing, GCN in PyTorch, Choosing an Architecture

Exercise 1: Counting the parameters of an MLP

An MLP for 28 ×\times 28 images maps 784 inputs to 256 hidden units, then to 128, then to 10 outputs, with a bias on every unit. How many parameters does it have? Which layer holds most of them?

Answer

A linear layer from ninn_{in} to noutn_{out} units has ninnoutn_{in} n_{out} weights and noutn_{out} biases:

  • 784⋅256+256=200,960784 \cdot 256 + 256 = 200{,}960
  • 256⋅128+128=32,896256 \cdot 128 + 128 = 32{,}896
  • 128⋅10+10=1,290128 \cdot 10 + 10 = 1{,}290

In total 235,146235{,}146 parameters, 85 % of them in the first layer, which connects every pixel to every hidden unit. That is the cost a convolution avoids by sharing a small kernel across positions (exercise 21).

Exercise 2: Derivatives of activations

Give the derivative at z=0z = 0 and the largest possible derivative of the sigmoid, tanh and ReLU (take ReLU's derivative at 0 to be 0, as PyTorch does). Which of them can make a unit stop learning for good, and how?

Answer
  • Sigmoid: σ′(z)=σ(z)(1−σ(z))\sigma'(z) = \sigma(z)(1 - \sigma(z)), which is 0.250.25 at z=0z = 0 and never larger.
  • Tanh: 1−tanh⁡2(z)1 - \tanh^2(z), which is 11 at z=0z = 0 and never larger.
  • ReLU: 11 for z>0z > 0, 00 for z≤0z \le 0, so 00 at z=0z = 0 and at most 11.

Sigmoid and tanh saturate: for large ∣z∣\lvert z \rvert the derivative is close to 0 and learning slows, but it never reaches exactly 0. A ReLU unit whose pre-activation is negative for every training input has gradient exactly 0 for all its incoming weights: a dead ReLU that never recovers. Leaky ReLU, GELU and SiLU keep a small gradient for negative inputs.

Exercise 3: Pick the head and the loss

For each task, give the last layer's size and activation and the PyTorch loss, and say what shape and dtype the targets have:

  1. predicting a house price;
  2. spam or not spam;
  3. one of 5 product categories;
  4. any subset of 20 tags for a photo.
Answer
  1. 1 linear output, no activation; nn.MSELoss (or nn.HuberLoss); float targets of shape (N, 1) or (N,) matching the output.
  2. 1 output, a logit; nn.BCEWithLogitsLoss (the sigmoid is inside the loss); float targets 0.0 or 1.0, shape (N,) after squeeze(1).
  3. 5 outputs, logits; nn.CrossEntropyLoss (log-softmax inside); targets are class indices, torch.long, shape (N,), not one-hot.
  4. 20 outputs, 20 independent logits; nn.BCEWithLogitsLoss; float targets of shape (N, 20) with a 1 for every tag present.

The common bug is a softmax or sigmoid in the model and in the loss: the loss then squashes probabilities a second time, trains badly and raises no error.

Exercise 4: Backward through a linear layer

A linear layer computes Y=XW+bY = XW + b for a batch XX of 2 examples with 3 features and WW of shape 3×23 \times 2:

X=(12001−1),W=(100111),∂L∂Y=(1002)X = \begin{pmatrix} 1 & 2 & 0 \\ 0 & 1 & -1 \end{pmatrix}, \quad W = \begin{pmatrix} 1 & 0 \\ 0 & 1 \\ 1 & 1 \end{pmatrix}, \quad \frac{\partial L}{\partial Y} = \begin{pmatrix} 1 & 0 \\ 0 & 2 \end{pmatrix}

Compute ∂L/∂W\partial L / \partial W, ∂L/∂b\partial L / \partial b and ∂L/∂X\partial L / \partial X, and check their shapes.

Answer

The rules: ∂L/∂W=X⊤ ∂L/∂Y\partial L / \partial W = X^\top \, \partial L / \partial Y (shape 3×23 \times 2, like WW), ∂L/∂b\partial L / \partial b is the column sum of ∂L/∂Y\partial L / \partial Y (shape 2, the bias was broadcast over the batch), and ∂L/∂X=∂L/∂Y W⊤\partial L / \partial X = \partial L / \partial Y \, W^\top (shape 2×32 \times 3, like XX).

python · try it yourself
import numpy as np

X = np.array([[1., 2., 0.], [0., 1., -1.]])     # 2 examples, 3 features
W = np.array([[1., 0.], [0., 1.], [1., 1.]])    # 3 inputs, 2 outputs
dY = np.array([[1., 0.], [0., 2.]])             # gradient arriving from the layer above
print("dW =", (X.T @ dY).tolist())
print("db =", dY.sum(axis=0).tolist())
print("dX =", (dY @ W.T).tolist())

# numerical check of one entry: L = sum(dY * (X @ W + b)) has exactly this gradient
L = lambda W: np.sum(dY * (X @ W))
E = np.zeros_like(W); E[1, 0] = 1e-6
print("numerical dL/dW[1, 0] =", round((L(W + E) - L(W - E)) / 2e-6, 6))
dW = [[1.0, 0.0], [2.0, 2.0], [0.0, -2.0]]
db = [1.0, 2.0]
dX = [[1.0, 0.0, 1.0], [0.0, 2.0, 2.0]]
numerical dL/dW[1, 0] = 2.0

Every gradient has the shape of the thing it is the gradient of; checking that catches most transposition bugs.

Exercise 5: Gradients that add up

In an autograd engine, f(x)=x⋅x+3xf(x) = x \cdot x + 3x is built from three nodes, and xx is used three times. At x=2x = 2, what does each use contribute to ∂f/∂x\partial f / \partial x, and what must the engine do with the contributions? What goes wrong if _backward writes self.grad = … instead of self.grad += …? And if a bias of shape (3,) is added to a batch of shape (4, 3), what is the shape of its gradient and how is it computed?

Answer

The product x⋅xx \cdot x sends x=2x = 2 back to each of its two inputs, and 3x3x sends 33: the contributions 2+2+3=72 + 2 + 3 = 7 must be summed, which equals f′(2)=2⋅2+3f'(2) = 2 \cdot 2 + 3. With = instead of +=, the last contribution overwrites the others and the engine returns 2 or 3. The bias gradient has the bias's shape (3,): the incoming (4, 3) gradient is summed over the broadcast axis 0, the "un-broadcast" step of the engine.

Exercise 6: Accumulated gradients in PyTorch

python
x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
y = (x ** 2).sum()
y.backward(retain_graph=True)
y.backward()
print(x.grad)

What is printed? Is y a leaf tensor? What would y.grad be?

Answer

tensor([ 4., 8., 12.]): each call adds ∂y/∂x=2x=(2,4,6)\partial y / \partial x = 2x = (2, 4, 6) to x.grad, and nothing clears it in between. That is why a training loop calls optimizer.zero_grad() every step. y is not a leaf (it was computed from a tensor that requires grad, so it has a grad_fn), and PyTorch keeps .grad only for leaves: y.grad is None (with a warning) unless y.retain_grad() was called before backward.

Exercise 7: A view that fails

x has shape (2, 3, 4). Why does x.permute(0, 2, 1).view(-1) raise an error while x.view(-1) works? Give two fixes.

Answer

view only reinterprets the existing memory, so the elements must already lie in the order the new shape needs. permute returns a tensor with swapped strides and the same memory: it is not contiguous, and no single stride can walk it in the permuted order, so view raises "view size is not compatible with input tensor's size and stride". Fixes: x.permute(0, 2, 1).reshape(-1) (copies when it has to) or x.permute(0, 2, 1).contiguous().view(-1) (copies explicitly).

Exercise 8: Same device, or not

A training script runs on a machine with a GPU and stops with "Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu". The model was moved with model.to(device), and the loop does logits = model(xb.to(device)) and loss = loss_fn(logits, yb). Find the bug. Why did the same script run fine on a laptop without a GPU?

Answer

The labels yb stay on the CPU while logits are on the GPU; write yb = yb.to(device) (move each batch's inputs and targets together). On the laptop device was cpu, so everything was on one device and the bug was invisible: test device-agnostic code with the device it will really run on, or at least read every tensor that enters the loss.

Exercise 9: Missing parameters

python
class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.layers = [nn.Linear(64, 64) for _ in range(4)]
        self.head = nn.Linear(64, 10)
    def forward(self, x):
        for layer in self.layers:
            x = torch.relu(layer(x))
        return self.head(x)

sum(p.numel() for p in Net().parameters()) prints 650. Why not 17,290, and what does it mean for training?

Answer

A plain Python list is invisible to nn.Module: only attributes that are modules, nn.Parameters, or containers such as nn.ModuleList are registered. The four hidden layers (4⋅(64⋅64+64)=16,6404 \cdot (64 \cdot 64 + 64) = 16{,}640 parameters) are missing from parameters(), so the optimizer never updates them, state_dict() does not save them and model.to(device) does not move them. Only the head's 650650 parameters are counted. Fix: self.layers = nn.ModuleList([...]), then 16,640+650=17,29016{,}640 + 650 = 17{,}290.

Exercise 10: Batches per epoch

The Digits training split has 1077 images. How many batches does a DataLoader with batch_size=64 give per epoch, and how large is the last one? And with drop_last=True?

Answer

1077=16⋅64+531077 = 16 \cdot 64 + 53, so 17 batches, the last with 53 images. With drop_last=True, 16 batches, and a different set of 53 images is left out in every epoch (the order is reshuffled). Dropping the short batch matters when a layer behaves badly on small batches (batch normalisation) or when the code assumes a fixed batch size.

Exercise 11: A checkpoint that resumes exactly

A training job with AdamW, a cosine schedule and a shuffling DataLoader is stopped after epoch 12 and restarted from a checkpoint. List what the checkpoint must contain for epochs 13 to 40 to be identical to an uninterrupted run, and say which item is most often forgotten.

Answer

The model's state_dict; the optimizer's state_dict (AdamW's two moment estimates per parameter and its step count); the scheduler's state_dict; the epoch (and the best validation score so far, for early stopping and best-model saving); and the random states that decide what happens next: Python's random, NumPy's and PyTorch's generators and the DataLoader's shuffling generator. The optimizer state and the random states are the usual omissions: without the first, Adam restarts with zero moments and takes a few oversized steps; without the second, the run continues correctly but differently. Load with torch.load(..., weights_only=True) where possible, because a pickled checkpoint from an unknown source can run code.

Exercise 12: Training memory

A model has 100 million parameters, trained in float32 with Adam. How much memory do the parameters, the gradients and the optimizer state take, before any activation? Which part grows with the batch size?

Answer

Each float32 is 4 bytes: parameters 400400 MB, gradients 400400 MB, Adam's first and second moments 2⋅400=8002 \cdot 400 = 800 MB, in total 1.61.6 GB (16 bytes per parameter). The activations saved for the backward pass grow linearly with the batch size (and with depth and sequence length); they are what gradient accumulation and activation checkpointing reduce, while sharding (ZeRO/FSDP) spreads the 16 bytes per parameter over several devices.

Exercise 13: A suspicious first loss

A 10-class classifier prints a cross-entropy of 8.5 on its very first batch, before any update. What should it be, and what does 8.5 suggest? What is the next check?

Answer

With small random weights the logits are close to each other, the softmax is close to uniform and the loss is about ln⁡10≈2.303\ln 10 \approx 2.303. A loss of 8.5 means the network is confidently wrong from the start: logits with a large spread, usually from an initialisation that is too large, unscaled inputs (pixels 0 to 255 instead of 0 to 1) or a wrong last layer. Next, overfit one small batch: a correct model and loop drive the loss on 32 fixed examples close to 0 within a few hundred steps; if it cannot, the bug is in the model, the loss or the update, not in the data size.

Exercise 14: Initialisation scales

A ReLU layer has 512 inputs. What standard deviation does He initialisation give? PyTorch's default for nn.Linear draws weights uniformly from [−1/nin,1/nin][-1/\sqrt{n_{in}}, 1/\sqrt{n_{in}}]: what is its standard deviation, and what happens to activations in a deep ReLU stack with it?

Answer

He: 2/512=0.0625\sqrt{2/512} = 0.0625. PyTorch's default: the bound is 1/512≈0.04421/\sqrt{512} \approx 0.0442 and a uniform distribution on [−a,a][-a, a] has standard deviation a/3≈0.0255a/\sqrt{3} \approx 0.0255, so the weight variance is 1/(3nin)1/(3 n_{in}), six times smaller than He's 2/nin2/n_{in}. In a deep plain ReLU stack, each layer then multiplies the activations' second moment by about 1/61/6 and the signal shrinks layer after layer; normalisation layers and residual connections are what make the default work in practice, and nn.init.kaiming_normal_ restores the He scale.

Exercise 15: Twenty sigmoid layers

Ignoring the weights, the backward pass through a sigmoid multiplies the gradient by σ′(z)≤0.25\sigma'(z) \le 0.25. Give an upper bound for the factor after 20 sigmoid layers. Name three remedies.

Answer

0.2520≈9.1⋅10−130.25^{20} \approx 9.1 \cdot 10^{-13}: the first layers receive essentially no gradient (vanishing gradients). Remedies: activations whose derivative is 1 over a large range (ReLU, GELU), an initialisation that keeps the variance constant (Xavier, He), normalisation layers, residual connections that give the gradient an identity path, and for exploding gradients, gradient clipping.

Exercise 16: Running statistics

A BatchNorm1d feature starts with running mean 0 and PyTorch's momentum 0.1. Two training batches have mean 2. What is the running mean after each? Which value does the layer use in model.eval(), and why does a batch of one example cause trouble in training mode?

Answer

PyTorch updates running←(1−0.1)⋅running+0.1⋅batch mean\text{running} \leftarrow (1 - 0.1) \cdot \text{running} + 0.1 \cdot \text{batch mean}: 0.9⋅0+0.2=0.20.9 \cdot 0 + 0.2 = 0.2, then 0.9⋅0.2+0.2=0.380.9 \cdot 0.2 + 0.2 = 0.38. In eval mode the layer normalises with the running mean and variance, not with the batch's, so a prediction does not depend on the other examples in the batch. In training mode a batch of one has variance 0 per feature: every normalised value becomes 0, the feature carries no information, and PyTorch raises an error for it.

Exercise 17: Which axis to normalise

A transformer's activations have shape (N, T, d) = (batch, tokens, features). Over which axes do batch normalisation and layer normalisation compute their mean and variance? Why do transformers use layer norm (or RMSNorm)?

Answer

Batch norm averages each feature over the batch (and the tokens): axes NN and TT, one statistic per feature. Layer norm averages over the features of one token: axis dd, one statistic per token, independent of the other examples and of padding. It works the same in training and inference, with any batch size (including 1 at generation time) and any sequence length; RMSNorm drops the mean subtraction and the bias and only divides by the root mean square.

Exercise 18: Dropout at training and at inference

With inverted dropout and p=0.2p = 0.2, a unit's activation 3.0 becomes what during training (two cases), and what at inference? Why is the expected value unchanged?

Answer

During training it is dropped with probability 0.2 (output 0) or kept and scaled by 1/(1−0.2)=1.251/(1 - 0.2) = 1.25 (output 3.753.75). The expected value is 0.8⋅3.75=3.00.8 \cdot 3.75 = 3.0, the original value. At inference (model.eval()) dropout is the identity: the output is 3.03.0, no scaling, which is why the scaling is done during training ("inverted").

Exercise 19: The identity path

A residual block computes y=x+F(x)y = x + F(x). What is ∂y/∂x\partial y / \partial x? Ten blocks are stacked, and in each, ∂F/∂x\partial F / \partial x is about 0.10.1 (in one dimension, as early in training when the branches are small). Compare the gradient factor through the stack with that of ten plain layers y=F(x)y = F(x) with the same FF.

Answer

∂y/∂x=1+∂F/∂x\partial y / \partial x = 1 + \partial F / \partial x. Plain layers multiply ten factors of 0.10.1: 0.110=10−100.1^{10} = 10^{-10}, the gradient vanishes. Residual blocks multiply ten factors of 1.11.1: 1.110≈2.591.1^{10} \approx 2.59, the gradient reaches the first block at a usable size. The identity path keeps every factor near 1 whenever the branch is small, which is why residual branches are often initialised so that F≈0F \approx 0 (for example a zero-initialised last layer). It is not a guarantee: branches whose derivatives are large can still make the product explode, which normalisation inside the branch keeps in check.

Exercise 20: Tables and categories

You must predict loan default from 40 numeric columns and a city column with 3,000 distinct values, on 50,000 rows. What should the first model be? If you also train an MLP, how should city enter it, and how many parameters does an embedding of size 16 add compared with a one-hot linear layer into 64 units?

Answer

A gradient-boosted tree model first: on tables of this size it is usually as good as or better than an MLP and needs less tuning. For the MLP, standardise the numeric columns on the training data only and feed city through an nn.Embedding(3000, 16), concatenated with the numbers: 48,00048{,}000 parameters. A one-hot input into a 64-unit linear layer needs 3000⋅64=192,0003000 \cdot 64 = 192{,}000 weights for the same column; an embedding is exactly that one-hot product with a smaller matrix, and rare cities share what the network learns through their neighbours in the embedding space (give unseen or very rare cities a shared "other" index).

Exercise 21: Shapes, parameters and receptive field of a CNN

An input of shape 3×32×323 \times 32 \times 32 goes through Conv2d(3, 16, 5, padding=2), MaxPool2d(2) and Conv2d(16, 32, 3, stride=2, padding=1). Give the output shape and the parameter count of each layer. Separately, what is the receptive field of one output of the stack conv 3 ×\times 3, conv 3 ×\times 3, pool 2 ×\times 2 (stride 2), conv 3 ×\times 3, all convolutions with stride 1?

Answer

Output size ⌊(n+2p−k)/s⌋+1\lfloor (n + 2p - k)/s \rfloor + 1 (dilation 1); parameters CoutCink2+CoutC_{out} C_{in} k^2 + C_{out}. The receptive field grows by (k−1)(k - 1) times the current jump, the input distance between neighbouring positions, and a stride multiplies the jump.

python · try it yourself
def out_size(n, k, s=1, p=0, d=1):
    return (n + 2 * p - d * (k - 1) - 1) // s + 1

def conv_params(c_in, c_out, k):
    return c_out * c_in * k * k + c_out

n = out_size(32, 5, p=2)
print("conv 5x5, pad 2:", (16, n, n), "params", conv_params(3, 16, 5))
n = out_size(n, 2, s=2)
print("max pool 2x2:   ", (16, n, n), "params 0")
n = out_size(n, 3, s=2, p=1)
print("conv 3x3, s 2:  ", (32, n, n), "params", conv_params(16, 32, 3))

r, j = 1, 1                                     # receptive field and jump (input pixels per step)
for name, k, s in [("conv 3x3", 3, 1), ("conv 3x3", 3, 1), ("pool 2x2", 2, 2), ("conv 3x3", 3, 1)]:
    r, j = r + (k - 1) * j, j * s
    print(f"after {name}: receptive field {r}, jump {j}")
conv 5x5, pad 2: (16, 32, 32) params 1216
max pool 2x2:    (16, 16, 16) params 0
conv 3x3, s 2:   (32, 8, 8) params 4640
after conv 3x3: receptive field 3, jump 1
after conv 3x3: receptive field 5, jump 1
after pool 2x2: receptive field 6, jump 2
after conv 3x3: receptive field 10, jump 2

The first convolution keeps 32×3232 \times 32 ("same" padding) with 1216 parameters, pooling halves it to 16×1616 \times 16, and the strided convolution gives 32×8×832 \times 8 \times 8 with 4640 parameters. The receptive field is 10 pixels: the last convolution sees 3 positions that are 2 input pixels apart. Compare 1216 parameters with a dense layer from 3072 inputs to 16⋅32⋅3216 \cdot 32 \cdot 32 outputs: weight sharing is the whole saving.

Exercise 22: Recurrent parameter counts and padding

How many parameters do nn.RNN(10, 20), nn.GRU(10, 20) and nn.LSTM(10, 20) have (input size 10, hidden size 20, one layer, PyTorch's two bias vectors)? A batch holds sequences of lengths 5, 3 and 2, padded to 5: what fraction of the positions is padding, and what must the loss do about it?

Answer

Each gate block has an input matrix h×dh \times d, a recurrent matrix h×hh \times h and two biases of size hh: h(d+h+2)=20⋅32=640h(d + h + 2) = 20 \cdot 32 = 640. The RNN has one block (640), the GRU three (1920), the LSTM four (2560). Of the 3⋅5=153 \cdot 5 = 15 positions, 0+2+3=50 + 2 + 3 = 5 are padding, one third. The loss must ignore them (a mask, or ignore_index in CrossEntropyLoss), and many-to-one models must read the state at each sequence's real last step, not at position 5; pack_padded_sequence does both for PyTorch's recurrent layers.

Exercise 23: Attention by hand

One query q=(1,0)q = (1, 0) attends over three keys k1=(1,0)k_1 = (1, 0), k2=(0,1)k_2 = (0, 1), k3=(1,1)k_3 = (1, 1) with values v1=(1,0)v_1 = (1, 0), v2=(0,1)v_2 = (0, 1), v3=(2,2)v_3 = (2, 2). Compute the scaled scores, the attention weights and the output.

Answer

Scores q⋅ki/2q \cdot k_i / \sqrt{2}: 0.70710.7071, 00, 0.70710.7071. Softmax: e0.7071≈2.028e^{0.7071} \approx 2.028, so the weights are 2.028/5.056≈0.40112.028 / 5.056 \approx 0.4011 for keys 1 and 3 and 1/5.056≈0.19781 / 5.056 \approx 0.1978 for key 2. Output: 0.4011⋅(1,0)+0.1978⋅(0,1)+0.4011⋅(2,2)=(1.2033,1.0)0.4011 \cdot (1, 0) + 0.1978 \cdot (0, 1) + 0.4011 \cdot (2, 2) = (1.2033, 1.0).

python · try it yourself
import numpy as np

q = np.array([1.0, 0.0])
K = np.array([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]])
V = np.array([[1.0, 0.0], [0.0, 1.0], [2.0, 2.0]])
scores = K @ q / np.sqrt(len(q))
w = np.exp(scores - scores.max()); w /= w.sum()
print("scores :", np.round(scores, 4).tolist())
print("weights:", np.round(w, 4).tolist())
print("output :", np.round(w @ V, 4).tolist())
scores : [0.7071, 0.0, 0.7071]
weights: [0.4011, 0.1978, 0.4011]
output : [1.2033, 1.0]

Exercise 24: Transformer sizes and perplexity

  1. How many parameters does one transformer block with d=512d = 512 have: four d×dd \times d attention projections with biases, an MLP d→4d→dd \to 4d \to d with biases, and two layer norms? Compare with 12d212 d^2.
  2. A character model over 40 characters reaches a validation loss of 1.5 nats per character. What is its perplexity, and what is the loss and perplexity of a model that guesses uniformly?
  3. How many tokens does a ViT make from a 224×224224 \times 224 image with 16×1616 \times 16 patches, including the class token?
Answer
  1. Attention 4d2+4d=1,050,6244d^2 + 4d = 1{,}050{,}624; MLP d⋅4d+4d+4d⋅d+d=8d2+5d=2,099,712d \cdot 4d + 4d + 4d \cdot d + d = 8d^2 + 5d = 2{,}099{,}712; layer norms 2⋅2d=20482 \cdot 2d = 2048. Total 3,152,3843{,}152{,}384, only 0.2 % more than 12d2=3,145,72812 d^2 = 3{,}145{,}728: the biases and norms are negligible.
  2. Perplexity e1.5≈4.48e^{1.5} \approx 4.48: the model is as uncertain as a uniform choice among about 4.5 characters. Uniform guessing gives loss ln⁡40≈3.689\ln 40 \approx 3.689 and perplexity 40.
  3. (224/16)2=196(224/16)^2 = 196 patch tokens plus the class token, 197.

Exercise 25: KL, the optimal discriminator and the noise level

  1. A VAE encoder outputs μ=1\mu = 1 and log⁡σ2=0\log \sigma^2 = 0 for one latent dimension. What is its KL term to the prior N(0,1)\mathcal{N}(0, 1)? Why is the sample written as z=μ+σϵz = \mu + \sigma \epsilon?
  2. At a point xx, pdata(x)=0.3p_{data}(x) = 0.3 and the generator's density is pg(x)=0.1p_g(x) = 0.1. What does the optimal GAN discriminator output there?
  3. In DDPM with the linear schedule (β\beta from 10−410^{-4} to 0.020.02, T=1000T = 1000), how much of x0x_0 and of the noise is left in xtx_t at t=250t = 250, 500500 and 10001000?
Answer
  1. KL=12(μ2+σ2−1−log⁡σ2)=12(1+1−1−0)=0.5\text{KL} = \frac{1}{2}(\mu^2 + \sigma^2 - 1 - \log \sigma^2) = \frac{1}{2}(1 + 1 - 1 - 0) = 0.5 nats. Writing the sample as μ+σϵ\mu + \sigma \epsilon with ϵ∼N(0,1)\epsilon \sim \mathcal{N}(0, 1) drawn outside the network (the reparameterisation trick) makes zz a differentiable function of μ\mu and σ\sigma, so the reconstruction loss can send gradients into the encoder.
  2. D∗(x)=pdata/(pdata+pg)=0.3/0.4=0.75D^*(x) = p_{data} / (p_{data} + p_g) = 0.3 / 0.4 = 0.75.
  3. xt=αˉt x0+1−αˉt ϵx_t = \sqrt{\bar\alpha_t}\, x_0 + \sqrt{1 - \bar\alpha_t}\, \epsilon with αˉt=∏s≤t(1−βs)\bar\alpha_t = \prod_{s \le t} (1 - \beta_s):
python · try it yourself
import numpy as np

betas = np.linspace(1e-4, 0.02, 1000)            # the linear DDPM schedule, T = 1000
alpha_bar = np.cumprod(1 - betas)
for t in (1, 250, 500, 1000):
    ab = alpha_bar[t - 1]
    print(f"t = {t:4d}  alpha_bar {ab:.4f}  signal x0 * {np.sqrt(ab):.4f}  noise eps * {np.sqrt(1 - ab):.4f}  SNR {ab / (1 - ab):.4g}")
t =    1  alpha_bar 0.9999  signal x0 * 0.9999  noise eps * 0.0100  SNR 9999
t =  250  alpha_bar 0.5241  signal x0 * 0.7239  noise eps * 0.6899  SNR 1.101
t =  500  alpha_bar 0.0786  signal x0 * 0.2803  noise eps * 0.9599  SNR 0.08529
t = 1000  alpha_bar 0.0000  signal x0 * 0.0064  noise eps * 1.0000  SNR 4.036e-05

At t=250t = 250 signal and noise are about equal (SNR 1.1); by t=500t = 500 only 28 % of x0x_0's scale is left, and at t=1000t = 1000 the sample is pure noise for all practical purposes. That is why sampling can start from N(0,I)\mathcal{N}(0, I).

Exercise 26: One GCN propagation, and choosing an architecture

  1. For the path graph 0 - 1 - 2 with self-loops, compute the GCN propagation matrix D^−1/2(A+I)D^−1/2\hat{D}^{-1/2} (A + I) \hat{D}^{-1/2} and apply it once and twice to the feature x=(1,0,0)x = (1, 0, 0).
  2. Pick a first architecture for: (a) sensor readings of 12 machines, one row per machine-day, 30 columns; (b) 50,000 product photos with 20 classes; (c) customer support tickets to route to 8 teams; (d) molecules to classify as toxic or not; (e) synthetic but realistic face images for a privacy study.
Answer
  1. The degrees with self-loops are 2, 3, 2, so each entry is 1/didj1/\sqrt{d_i d_j}:
python · try it yourself
import numpy as np

A = np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]], dtype=float)   # path graph 0 - 1 - 2
A_hat = A + np.eye(3)                                          # self-loops
d = A_hat.sum(axis=1)
N = A_hat / np.sqrt(np.outer(d, d))                            # D^(-1/2) (A + I) D^(-1/2)
print("degrees with self-loops:", d.tolist())
print(np.round(N, 4))
x = np.array([1.0, 0.0, 0.0])
print("one propagation of x = [1, 0, 0]:", np.round(N @ x, 4).tolist())
print("two propagations:", np.round(N @ N @ x, 4).tolist())
degrees with self-loops: [2.0, 3.0, 2.0]
[[0.5    0.4082 0.    ]
 [0.4082 0.3333 0.4082]
 [0.     0.4082 0.5   ]]
one propagation of x = [1, 0, 0]: [0.5, 0.4082, 0.0]
two propagations: [0.4167, 0.3402, 0.1667]

After one propagation node 1 has received part of node 0's feature (0.40820.4082); after two, node 2 has too (0.16670.1667). Each layer spreads information one hop, so kk layers see the kk-hop neighbourhood, and many layers smooth every node towards the same value (over-smoothing).

  1. (a) Gradient-boosted trees, then an MLP with embeddings if needed. (b) A pretrained CNN or ViT, fine-tuned (transfer learning). (c) A pretrained transformer encoder fine-tuned for classification, or sentence embeddings with a linear head. (d) A graph neural network on the atoms and bonds, with a graph-level readout. (e) A diffusion model (or a GAN), with a privacy review of the training data.

Test yourself

A linear layer maps a batch XX of shape (N,din)(N, d_{in}) with WW of shape (din,dout)(d_{in}, d_{out}). What is the shape of ∂L/∂W\partial L / \partial W?

  1. (N,dout)(N, d_{out})
  2. (din,dout)(d_{in}, d_{out}), the shape of WW
  3. (dout,din)(d_{out}, d_{in})
  4. (N,din)(N, d_{in})

A model stores its hidden layers in a plain Python list. What happens during training?

  1. Nothing, PyTorch finds them anyway
  2. Those layers are not registered, so the optimizer never updates them and state_dict() does not save them
  3. Training raises an error at once
  4. The layers are trained twice

How many parameters does nn.LSTM(10, 20) have (one layer, PyTorch's two bias vectors)?

  1. 640
  2. 1920
  3. 2560
  4. 3200

A 10-class classifier's loss before the first update is about 2.3. What does that tell you?

  1. The model has already learned
  2. The output is close to uniform, as expected at initialisation: ln⁡10≈2.303\ln 10 \approx 2.303
  3. The learning rate is too high
  4. The labels are wrong