Seventeen whiteboard questions cover the core of deep learning. If you can teach all seventeen from memory, with the numbers, you own the foundations.
Set one learning rate for three optimisers in a narrow valley, then press Run. Find the rate where plain SGD blows up and Adam does not. Each chapter below rehearses one or more questions, then hands you the whiteboard.
You need Python and what a slope is. We build the rest from zero.
Press Start Teaching to open the whiteboard at question 1, or Teach on any chapter to jump to its question. You can record each answer and export it as a video.
Illustrative toy: the loss is ½(x² + 25y²), 80 steps from (−4, 1.5). Momentum uses β = 0.9; Adam uses β1 = 0.9, β2 = 0.999. Your browser computes every number live.
Chapter 0
See why reading is not knowing, and find where each of the 17 questions sits in one training loop
You read about backpropagation last week. It made sense. Now someone hands you a marker and says: draw it for three layers and show where each gradient comes from. Most people stall after the first box.
Reading builds recognition: you know an idea when you see it. Teaching needs recall: you produce the idea from nothing, in order, with numbers. This page trains recall. It holds 17 whiteboard questions and a short rehearsal for each.
Every question sits in one loop. Data goes into a model. The model's output gives a loss. Backpropagation turns the loss into gradients. An optimiser turns the gradients into an update. Then the loop runs again.
Five stages form one training loop. Pick a stage to see which questions live there and which chapter rehearses them.
We place each question at the stage it mostly concerns. Some touch two stages: residual connections are part of the model and also of the gradient flow.
Plan the time. At 2 to 3 minutes for each answer, 17 questions take 34 to 51 minutes. So one full session is about 45 minutes.
The failure is the illusion of knowing. The symptom: the page feels familiar, but your recording stalls. To measure it, record two minutes on one question with no notes, then count the stalls and the wrong numbers. The fix: rehearse that chapter and record again.
Chapter 1
Step downhill on the loss, then add a velocity that carries you through small dips
You stand on a foggy hill and want the lowest point. You can feel only the slope under your feet. So you step downhill, feel again, and repeat. That is gradient descent.
Call the model's adjustable numbers the weights w. The loss L(w) says how wrong the model is. The gradient ∇L(w) is the slope; it points uphill. The learning rate η sets the length of each step.
w at t plus one equals w-t minus eta times the gradient of L at w-t.
Measure the slope of L at w-t. Step the other way, eta times the slope. The new point is w at t plus one.
With made-up numbers: L(w) = w², so the gradient is 2w. Start at w-t = 3 with eta = 0.1. The gradient is 6, the step is 0.6, and w at t plus one is 2.4. The loss falls from 9 to 5.76.
Plain descent stops wherever the slope is flat. That happens at a local minimum, a dip that is not the lowest point. It also happens near a saddle point, a flat spot that goes down in some directions. Momentum keeps a running velocity v. The momentum factor β, often 0.9, says how much old velocity survives each step.
vt+1 = β vt + ∇L(wt) wt+1 = wt − η vt+1
With a steady slope of 1 and β = 0.9, the velocity grows 1, 1.9, 2.71. On a long slope it nears 1/(1 − 0.9) = 10, ten times the plain step.
The ball starts high on the left. A shallow dip waits first, the deep valley lies past a bump. Set β and press Release.
Illustrative toy: L(w) = 0.1w⁴ − 0.6w² − 0.5w, start w = −3, η = 0.02, 800 steps. Below β = 0.85 the ball stays in the dip at w = −1.47; from 0.85 it reaches w = 1.91.
The failure is a learning rate that is too big. The symptom: the loss rises or prints NaN. To measure it, plot the loss for the first 100 steps. On L = w² with eta = 1.1, each step multiplies w by −1.2, so w goes 1, −1.2, 1.44, −1.73. The fix: divide eta by 3 to 10 and run again.
Teach it · Q1
Gradient descent landscape. Draw a loss surface with a global minimum, a local minimum and a saddle point. Show how plain descent and momentum move through each.
Chapter 2
Run the network forward, then walk back and multiply the local slopes to get every gradient
A network makes a wrong guess. Which weight should change, and by how much? Backpropagation answers this. It traces blame backward from the loss, one box at a time.
Take a network with two weights. The input x times w1 gives z. A ReLU keeps z if it is positive and gives 0 if not; call its output h. The guess is ŷ = w2 × h. The loss is L = ½(ŷ − y)², half the squared gap to the target y.
Blue numbers flow forward. Pink gradients flow back. Press Step eight times, then drag w1 below zero and watch the ReLU block the gradient.
Toy values: x = 2, w₂ = 1.5, target y = 1. The gradients are exact; a numerical check with a nudge of 0.000001 agrees to 4 decimals.
Each arrow has a local gradient: how much its output moves when its input moves a little. The chain rule says to multiply the local gradients along the path.
dL by d-w-one equals dL by d-y-hat, times d-y-hat by d-h, times d-h by d-z, times d-z by d-w-one.
Start at the loss with the error ŷ − y. Walk backward. At each box, multiply by that box's local gradient. When you reach w1, the product is dL by d-w-one.
Take x = 2, w1 = 0.5, w2 = 1.5, y = 1. Forward: z = 1, h = 1, ŷ = 1.5, L = 0.125. Backward: 0.5 × 1.5 × 1 × 2 = 1.5. So dL by d-w-one is 1.5, and dL by d-w-two is 0.5 × h = 0.5.
One descent step with eta = 0.1 moves w1 to 0.35 and w2 to 1.45. The loss falls from 0.125 to about 0.0001. The backward pass reuses each product on the way, so all the gradients together cost about as much as one or two forward passes.
In a deep network the path has one factor for each layer. If each factor is below 1, the product shrinks toward zero. Chapter 7 measures this.
The failure is a wrong hand-written gradient. The symptom: the loss falls slowly or not at all. To measure it, run a gradient check: nudge w1 up and down by 0.000001 and take (Lup − Ldown)/0.000002. Here it gives 1.5000, which matches. The fix: find the box whose local gradient disagrees.
Teach it · Q2
Backpropagation. Draw a small network, run the forward pass with numbers, then trace the backward pass and say why a long product of factors causes trouble.
Chapter 3
Give each weight a step sized to its own gradients, and shrink the rate as training settles
Go back to the hero. The valley is 25 times steeper across than along. Plain SGD must keep eta below 2/25 = 0.08, or it bounces out over the steep walls. At that size it crawls along the floor.
Adam gives each weight its own step size. For each weight it keeps m, a running average of the gradient, and v, a running average of the squared gradient. A hat on a letter means bias corrected: both averages start at zero, so Adam scales the early values up to fix that.
w at t plus one equals w-t minus eta times m-hat-t, over the square root of v-hat-t plus epsilon.
For each weight, divide its average gradient m-hat by its typical gradient size, the square root of v-hat. The ratio is about 1 in size on steep and flat weights alike. Multiply by eta and step.
First step, eta = 0.001. One weight has gradient 4 (steep), another 0.1 (flat). After bias correction, m-hat is the gradient and v-hat its square. Both steps are 0.001 × 4/4 = 0.001 and 0.001 × 0.1/0.1 = 0.001. Plain SGD would step 0.004 and 0.0001: a 40-fold gap.
A learning-rate schedule changes eta during training. Noisy gradients keep the loss bouncing above a floor, and that floor grows with eta. So a schedule starts large to travel fast and ends small to settle.
| Schedule | Shape | Good for |
|---|---|---|
| Constant | flat | quick tests |
| Step decay | divide by 10 at fixed steps | classic image models |
| Warmup + cosine | ramp up, then a smooth half cosine to 0 | transformers, large batches |
Top: eta over 100 steps. Bottom: the expected loss of a noisy toy problem, on a log scale. Pick a schedule and a peak eta.
Illustrative toy: SGD on ½w² with gradient noise of variance 1, starting at w = 2. Expected squared weight: Enext = (1 − η)²E + η². Step decay divides by 10 at steps 50 and 75; warmup lasts 5 steps.
Warmup raises eta from near zero over the first steps. At the start the weights are random and Adam's v is a poor estimate, so large early steps can throw training off. The toy has no such early danger, so it shows only the floor.
The failure: a loss spike in the first few hundred steps, or a loss that goes flat late. To measure it, plot eta next to the loss. The fix: add warmup for the spike, and decay eta for the plateau.
Teach it · Q3 and Q4
Adam vs SGD, then learning-rate schedules. Draw what each optimiser does in a narrow valley. Then sketch three schedules and the loss curve each one gives.
Chapter 4
Turn scores into probabilities, then charge the model by how little it trusted the right answer
A classifier looks at a photo and gives three scores, called logits: cat 2.0, dog 1.0, fox 0.1. Logits can be any number. Softmax turns them into probabilities: raise e to each logit, then divide by the total.
pk = ezk / Σj ezj
Here zk is the logit of class k and pk its probability. With these logits, e² = 7.39, e¹ = 2.72 and e0.1 = 1.11, total 11.21. So the probabilities are 0.659, 0.242 and 0.099.
Maximum likelihood says: choose the weights that make the true labels most probable. Over many photos that is a product of probabilities. A log turns the product into a sum, and a minus sign turns "make large" into "make small". For one photo the result is the cross-entropy loss.
L equals minus the log of p-y.
Find the probability the model gave to the correct class, p-y. Take its log and flip the sign. A sure right answer costs 0, and a sure wrong answer costs a lot.
The photo is a cat, so p-y = 0.659 and L = −log 0.659 = 0.417. If the model gave cat only 0.01, L would be 4.61. At 0.001, L is 6.91.
The one-hot label is 1 for the true class and 0 elsewhere. The gradient of L on the logits is p minus that label: (−0.341, 0.242, 0.099). It raises the cat logit and lowers the others. Each entry stays between −1 and 1, even when the loss is huge.
Left: softmax probabilities. Right: the loss against p(cat). Drag the cat logit down to −3 and compare the two pushes in the read-out.
Dog and fox logits stay at 1.0 and 0.1. "Squared error" here is the sum of (pk − labelk)² over the three softmax outputs; both gradients are on the cat logit.
With squared error on the softmax outputs, a confidently wrong model gets almost no push, because softmax is flat there. At a cat logit of −3, cross-entropy pushes about 25 times harder.
The failure: the loss prints NaN or inf. The cause is the log of a probability that rounded to 0. To measure it, print the smallest p-y in the batch. The fix: pass raw logits to a fused loss such as PyTorch's F.cross_entropy, which works in log space.
Teach it · Q5
Cross-entropy loss. Derive it from maximum likelihood, draw −log p against p, and say why it beats squared error for classification.
Chapter 5
Split test error into a miss, a scatter and noise, and see how model size moves each part
You fit a curve to 11 noisy points. A straight line misses the bend. A degree 10 polynomial passes through every point and swings wildly between them. Both predict new points badly, for opposite reasons.
Train the same model on many fresh datasets from one source. At one input x you get many predictions. Bias is how far their average sits from the truth. Variance is how much they scatter around their own average. Noise is the randomness in the labels that no model can predict.
The expected value of y minus f-hat of x, squared, equals bias squared plus variance plus sigma squared.
Collect the predictions f-hat of x from many training sets. Square the gap from their average to the truth: bias squared. Average their squared spread around that average: variance. Add the noise sigma squared to get the expected test error.
With made-up numbers: the truth at x is 2.0, and five training sets predict 2.6, 2.2, 2.9, 2.5, 2.3. The average is 2.5, so bias squared is 0.25. The variance is (0.01 + 0.09 + 0.16 + 0 + 0.04)/5 = 0.06. With sigma squared 0.04, the expected error is 0.35.
Thin blue curves are fits to 30 fresh datasets. The dashed curve is the truth. The bars split the expected error. Drag the degree from 0 to 10.
Illustrative toy: truth sin(πx), 11 evenly spaced points on [−1, 1], label noise with σ = 0.3, 30 seeded datasets. Bias and variance are the averages over x in [−0.95, 0.95].
Low degree gives high bias and low variance: underfitting. High degree gives low bias and high variance: overfitting. The lowest test error sits between them, near degree 3 here.
The failure is overfitting. The symptom: training loss keeps falling while validation loss rises. To measure it, plot both against training time or model size. The fix: more data, regularisation (Chapter 6) or a smaller model, and keep the weights from the lowest validation loss.
Teach it · Q6
Bias–variance trade-off. Draw test error against model complexity, split it into bias squared, variance and noise, mark underfitting and overfitting, then add double descent.
Chapter 6
Charge the model for large weights, and see why one charge gives exact zeros
Your model fits the training set perfectly and fails on new data. One fix is to charge it for large weights. Large weights let a model bend sharply to chase noise.
Call the data loss L(w). Add a penalty R(w), scaled by a strength λ. The L1 penalty is the sum of the absolute weights. The L2 penalty is the sum of the squared weights.
J of w equals L of w plus lambda times R of w. For L1, R is the sum of the absolute weights; for L2, the sum of the squared weights.
Add lambda times R to the data loss L. L1 charges the same for each unit of a weight, so small weights are cheapest to drop to zero. L2 charges little for small weights, so it shrinks them but rarely to zero.
One weight with data loss ½(w − a)², lambda = 0.5. L1: move a toward 0 by lambda, and stop at 0. L2: the best w is a/(1 + 2 × lambda). For a = 0.3: L1 gives 0, L2 gives 0.15. For a = 2: L1 gives 1.5, L2 gives 1.0.
Faint bars are the weights without a penalty. Solid bars are the weights after it. Pick L1 or L2, then raise lambda.
Illustrative toy: each weight has its own data loss ½(w − a)², so the penalised best value has the closed form above.
The picture behind it: the weights allowed by L1 form a diamond with corners on the axes. The loss contours usually touch it first at a corner, where some weights are exactly zero. The L2 region is a circle, with no corners.
Dropout zeroes each hidden unit with probability p during training and scales the rest by 1/(1 − p). With p = 0.5, an activation of 2 becomes 4 or 0, average 2. Each step trains a random sub-network; at test time all units stay on. Data augmentation adds flipped, cropped or recoloured copies of training images.
The failure is too much penalty. The symptom: training and validation loss both stay high. To measure it, sweep lambda over 0.00001 to 0.1 on a log grid and plot validation loss. The fix: pick the lambda at the lowest point.
Teach it · Q7
Regularisation arsenal. Compare L1, L2, dropout and augmentation. Draw the diamond and the circle, and say why L1 gives sparse weights.
Chapter 7
Keep the gradient alive through a deep stack with three parts of every modern network
Stack 30 layers and train. The last layers learn. The first barely move, because the gradient that reaches them is tiny. Three parts of a modern network fight this.
| Activation | Formula | Largest slope | Weak spot |
|---|---|---|---|
| Sigmoid | 1/(1 + e−x) | 0.25 | flat at both ends |
| Tanh | (ex − e−x)/(ex + e−x) | 1 | flat at both ends |
| ReLU | max(0, x) | 1 | slope 0 below zero: a unit can die |
| GELU | x · Φ(x) | about 1.13 | a little more compute |
Ten sigmoid layers, each at its best slope of 0.25, scale the gradient by 0.2510, about 0.000001. A ReLU passes a slope of exactly 1 for positive inputs. A unit whose input stays negative gets slope 0 forever: a dead ReLU. GELU multiplies x by Φ(x), the chance a standard normal is below x, so GELU(−1) = −0.16 still passes a little gradient.
A residual block outputs x + F(x): its input plus a learned correction. Its local gradient is 1 + ∂F/∂x. The 1 is an identity path, so the gradient reaches early layers through a sum, not only through a long product.
Each bar is the gradient size at one layer, on a log scale, from the output on the right to the input on the left. Pick a design and a depth.
Real backprop through random networks, 24 units wide, weights drawn with standard deviation 1/√24, averaged over 6 seeds. The skip design scales its residual branch by 0.3 at the start, a common trick.
Batch normalisation standardises each feature over the mini-batch, then lets the network rescale it.
y-i equals gamma times x-i minus mu-B, over the square root of sigma-B squared plus epsilon, plus beta.
Subtract the batch mean mu-B from each x-i. Divide by the batch standard deviation. Then multiply by gamma and add beta, two numbers the network learns.
Batch 2, 4, 6, 8. mu-B = 5 and sigma-B squared = 5, so the standardised values are −1.34, −0.45, 0.45, 1.34. With gamma = 2 and beta = 1, y is −1.68, 0.11, 1.89, 3.68.
At test time there may be one example, so batch norm uses running averages of mu and sigma saved during training. Its paper credited less "internal covariate shift"; later work (Santurkar et al., 2018) found it mainly smooths the loss surface, which allows larger learning rates.
The failure: a model that looks good in training mode does badly after model.eval(). The cause is running statistics from tiny batches. To measure it, compare outputs in both modes on one batch. The fix: larger batches, or LayerNorm or GroupNorm.
Teach it · Q8, Q9 and Q10
Batch normalisation, residual connections and activation functions. Draw each part, write its formula and say what it does for the gradient.
Chapter 8
Slide one small kernel over an image, count the output size, and track shapes through a whole network
A 224 by 224 colour image holds 150,528 numbers. A fully connected layer to only 64 outputs needs 9.6 million weights. It also ignores that nearby pixels belong together.
A convolution slides a small kernel, such as a 3 by 3 grid of weights, across the image. At each position it multiplies the kernel by the patch under it and adds the nine products. The same nine weights serve every position: parameter sharing.
O equals the floor of W minus K plus two P, over S, plus one.
Add the padding P to both sides of the width W. Count the kernel positions that fit when you jump S cells at a time. Drop a part window at the edge, so round down.
W = 6, K = 3. With P = 0 and S = 1: (6 − 3)/1 + 1 = 4. With S = 2: (6 − 3)/2 + 1 = 2.5, rounded down to 2. With P = 1 and S = 1: (6 − 3 + 2)/1 + 1 = 6, the input size.
The teal window is the 3 by 3 kernel. Each stop fills one blue output cell. Change the size, stride and padding, then press Slide.
Dashed cells are padding zeros. A dot marks each cell the kernel never covers.
Parameter sharing in numbers: a 3 by 3 kernel has 9 weights for any image size. A fully connected map from 36 inputs to 16 outputs has 576.
| Stage | Output shape | Parameters |
|---|---|---|
| Input | 224 × 224 × 3 | 0 |
| Conv 3×3, 64, padding 1 | 224 × 224 × 64 | 1,792 |
| Max pool 2×2 | 112 × 112 × 64 | 0 |
| Conv 3×3, 128, padding 1 | 112 × 112 × 128 | 73,856 |
| Max pool 2×2 | 56 × 56 × 128 | 0 |
| Global average pool | 128 | 0 |
| Fully connected + softmax | 1000 | 129,000 |
A conv layer has K × K × Cin × Cout weights, plus one bias per output channel. For the second conv: 3 × 3 × 64 × 128 + 128 = 73,856. Compute runs the other way: that layer does 925 million multiply-adds, the final layer only 128,000.
The failure: a shape error where the conv output meets the first linear layer. To measure it, print x.shape after each block on one dummy batch. The fix: use the formula, or a global average pool, which makes the head independent of image size.
Teach it · Q11 and Q12
The convolution operation, then a full CNN. Slide a kernel with stride 1 and 2, compute the sizes, then label every tensor shape for a 224 by 224 by 3 input.
Chapter 9
Carry information along a sequence step by step, then let every token look at every other token at once
A word at position 30 may refer to a noun at position 2, 28 steps back.
A recurrent network (RNN) reads one token per step. It updates a hidden state h: ht = tanh(Whh ht−1 + Wxh xt). The gradient from step 50 back to step 0 passes through 50 copies of Whh and the tanh slope. At 0.9 × 0.8 = 0.72 per step, 5 steps leave 0.19 and 50 steps leave 0.00000007.
An LSTM adds a cell state c that changes by addition: ct = f ⊙ ct−1 + i ⊙ c̃t. The forget gate f (0 to 1) says what to keep. The input gate i writes the candidate c̃. The output gate o says what to expose: ht = o ⊙ tanh(ct). With f = 0.95, 50 steps keep 0.9550 = 0.077 of the gradient, about a million times the RNN's share.
Self-attention skips the chain. Each token makes a query (what it looks for), a key (what it offers) and a value (what it passes on). Stack them as the rows of Q, K and V. dk is the length of each key.
Attention of Q, K, V equals softmax of Q times K-transpose over the square root of d-k, times V.
Score each query in Q against every key in K with a dot product. Divide by root d-k. Softmax each row into weights. Each output is the weighted average of the rows of V.
With made-up numbers: d-k = 2, query (1, 0), keys (1, 0), (0, 1), (1, 1), (−1, 0). Dot products 1, 0, 1, −1, over root 2: 0.71, 0, 0.71, −0.71. Softmax: 0.37, 0.18, 0.37, 0.09. Values 1, 2, 3, 4 give an output of 2.18.
Rows are queries, columns are keys; darker means more weight. Raise dk with the scaling off and watch each row collapse onto one key.
Illustrative toy: queries and keys are random vectors with entries of variance 1 (seeded). Their dot products then have variance dk.
The score matrix has one entry for each pair of tokens: 16 for 4 tokens, 1 million for 1,000. That is why attention costs grow with n².
The failure: attention rows that are almost one-hot from the start, and training stalls. To measure it, log the largest weight in each row. The fix: divide by root d-k, as the formula does.
Teach it · Q13, Q14 and Q15
RNN and vanishing gradients, LSTM gates and self-attention. Unroll an RNN, draw the LSTM cell, then compute attention for four tokens with every shape labelled.
Chapter 10
Compare the three architectures, run the whole pipeline once, and keep the numbers in one place
A network learns by one loop: forward, loss, backward, update. The layers decide what it can see. The loss decides what it aims at. The optimiser and schedule decide how it walks. Regularisation decides how much it trusts the training set.
| Family | Core operation | Built-in assumption | Runs in parallel? | Weak spot |
|---|---|---|---|---|
| CNN | a small kernel slid over the input | nearby things matter | yes | long-range links need many layers |
| RNN / LSTM | one state updated per step | order matters | no, step by step | slow; gradients fade over long spans |
| Transformer | every token attends to every token | few; position must be added | yes | cost grows with n² |
pythonimport torch, torch.nn.functional as F opt = torch.optim.AdamW(model.parameters(), lr=3e-4, weight_decay=0.05) sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=3e-4, total_steps=steps, pct_start=0.05, anneal_strategy='cos') # warmup, then cosine for x, y in loader: # x: (B, 3, 224, 224), y: (B,) class ids logits = model(x) # (B, 1000), raw scores, no softmax loss = F.cross_entropy(logits, y) # log-softmax inside: no NaN from log(0) opt.zero_grad() loss.backward() # backprop: one gradient per weight torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) opt.step(); sched.step()
| Term | One line | Number to remember |
|---|---|---|
| Gradient descent | step against the slope | w = 3, η = 0.1 on w² gives 2.4 |
| Momentum | a velocity that keeps old steps | β = 0.9 gives up to 10 times the step |
| SGD limit | steepest curvature caps η | η < 2/25 = 0.08 in the hero valley |
| Adam | per-weight step from m-hat over root v-hat | first step is about η for every weight |
| Cross-entropy | minus the log of p-y | p-y 0.659 gives 0.417; 0.01 gives 4.61 |
| Bias, variance | miss of the average, scatter of the fits | 0.25 + 0.06 + 0.04 = 0.35 |
| L1 vs L2 | zeros vs shrinkage | a = 0.3, λ = 0.5: 0 vs 0.15 |
| Sigmoid depth | slope at most 0.25 per layer | 0.2510 is about 0.000001 |
| Conv size | floor((W − K + 2P)/S) + 1 | 6, 3, 0, 2 gives 2 |
| Attention | softmax(QKT/√dk)V | n = 1,000 tokens: 1 million scores |
loss.backward() in PyTorch?Teach it · Q16 and Q17
CNN to RNN to Transformer, then training a model end to end. Draw the three columns, then the full pipeline with one decision at each stage.
Now press Start Teaching and go through all 17 questions in one sitting, about 45 minutes. Then go back to the hero and find the learning rate where momentum also breaks.
The 17 questions come from the original Engineermaxxing teaching session on deep learning foundations. This edition adds a rehearsal for each one. We rechecked every worked number on the page with a short numpy script.