Teach DL/ML Foundations

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.

One learning rate, three optimisers

0.06

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

Why Teach It Back

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.

Place each question on the loop

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.

  1. Read a chapter and operate its device.
  2. Press its Teach button and explain the question on the whiteboard.
  3. Replay your answer. Check it against the hint in the whiteboard panel.

The road

  1. Gradient descent and momentum: step downhill, and roll through dips (Q1).
  2. Backpropagation: trace blame backward with the chain rule (Q2).
  3. Adam and schedules: give each weight its own step, and change the rate over time (Q3, Q4).
  4. Cross-entropy: score a probability guess (Q5).
  5. Bias and variance: split test error into three parts (Q6).
  6. Regularisation: charge the model for large weights (Q7).
  7. Activations, skips and batch norm: keep the gradient alive in deep stacks (Q8 to Q10).
  8. Convolutions and CNNs: slide one small kernel over an image (Q11, Q12).
  9. RNNs, LSTMs and attention: carry information across a sequence (Q13 to Q15).
  10. The field guide: the three architectures, the full pipeline, the numbers and the code (Q16, Q17).
What does recording yourself explaining a topic measure that rereading does not?

Chapter 1

Gradient Descent and Momentum

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.

Say it aloud

w at t plus one equals w-t minus eta times the gradient of L at w-t.

wt+1
w at t plus one the weights after this step.
wt
w-t the weights now, at step t.
η
eta the learning rate: a small positive number such as 0.1.
∇L(wt)
the gradient of L at w-t the slope of the loss at the current weights. It points uphill, so we subtract it.
In plain words

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 numbers

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.

Release the ball with momentum

The ball starts high on the left. A shallow dip waits first, the deep valley lies past a bump. Set β and press Release.

0.90

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.

Near a saddle point the gradient is almost zero. Why does momentum still move the weights?

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

Backpropagation

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.

Step forward, then backward

Blue numbers flow forward. Pink gradients flow back. Press Step eight times, then drag w1 below zero and watch the ReLU block the gradient.

0.50

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.

Say it aloud

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.

∂L/∂w1
dL by d-w-one how much the loss changes for a small change in w1. This is what we want.
∂L/∂ŷ
dL by d-y-hat the error of the guess, ŷ − y.
∂ŷ/∂h
d-y-hat by d-h equals w2.
∂h/∂z
d-h by d-z the ReLU slope: 1 if z is positive, 0 if not.
∂z/∂w1
d-z by d-w-one equals x, the input.
In plain words

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.

With numbers

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.

In the toy network, w1 = −0.5, so z is negative. What is dL by d-w-one?

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

Adam and Learning-Rate Schedules

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.

Say it aloud

w at t plus one equals w-t minus eta times m-hat-t, over the square root of v-hat-t plus epsilon.

wt+1
w at t plus one one weight after the step.
wt
w-t the same weight now.
η
eta the base step, often 0.001.
m̂t
m-hat-t the running average of this weight's gradient, bias corrected (factor β1 = 0.9).
√
the square root of turns the average squared gradient back into a typical gradient size.
v̂t
v-hat-t the running average of the squared gradient, bias corrected (factor β2 = 0.999).
ε
epsilon a tiny number, such as 0.00000001, that stops a division by zero.
In plain words

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.

With numbers

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.

ScheduleShapeGood for
Constantflatquick tests
Step decaydivide by 10 at fixed stepsclassic image models
Warmup + cosineramp up, then a smooth half cosine to 0transformers, large batches

Pick a schedule, watch the floor

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.

0.20

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.

On its first step, why does Adam move a steep weight and a flat weight by the same amount?

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

Cross-Entropy Loss

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.

Say it aloud

L equals minus the log of p-y.

L
L the loss for one example.
−
minus flips the sign, so a small loss means a good guess.
log
the log of the natural logarithm. For a probability it is zero or negative.
py
p-y the probability the model gives to the true class y.
In plain words

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.

With numbers

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.

Make the model confidently wrong

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.

2.0

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.

The model gives the true class a probability of 0.01. What is the cross-entropy loss?

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

The Bias–Variance Trade-off

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.

Say it aloud

The expected value of y minus f-hat of x, squared, equals bias squared plus variance plus sigma squared.

E[ ]
the expected value of the average over many training sets and many fresh labels.
y
y a fresh noisy label at input x.
f̂(x)
f-hat of x the trained model's prediction at x.
Bias²
bias squared (average prediction minus the true value), squared.
Var
variance the average of (prediction minus average prediction), squared.
σ²
sigma squared the variance of the label noise.
In plain words

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 numbers

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.

Raise the degree, split the error

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.

3

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.

A model scores 99% on training data and 70% on validation data. Which part of the error is most likely too large?

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

Regularisation: L1, L2, Dropout, Augmentation

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.

Say it aloud

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.

J(w)
J of w the total that training minimises.
L(w)
L of w the data loss, such as cross-entropy.
λ
lambda the penalty strength, zero or more.
R(w)
R of w the penalty on the size of the weights.
Σ|wi|
the sum of the absolute values of w-i the L1 penalty.
Σwi²
the sum of w-i squared the L2 penalty.
In plain words

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.

With numbers

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.

Shrink eight weights

Faint bars are the weights without a penalty. Solid bars are the weights after it. Pick L1 or L2, then raise lambda.

0.50

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.

Which penalty sets small weights to exactly zero, and why?

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

Activations, Skip Connections and Batch Norm

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.

ActivationFormulaLargest slopeWeak spot
Sigmoid1/(1 + e−x)0.25flat at both ends
Tanh(ex − e−x)/(ex + e−x)1flat at both ends
ReLUmax(0, x)1slope 0 below zero: a unit can die
GELUx · Φ(x)about 1.13a 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.

Send a gradient down a deep stack

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.

30

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.

Say it aloud

y-i equals gamma times x-i minus mu-B, over the square root of sigma-B squared plus epsilon, plus beta.

yi
y-i the output for example i.
γ
gamma a learned scale.
xi
x-i this feature's value for example i.
μB
mu-B the mean of the feature over the batch.
σB²
sigma-B squared the variance of the feature over the batch.
ε
epsilon a small constant, such as 0.00001.
β
beta a learned shift.
In plain words

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.

With numbers

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.

Why does a 30-layer sigmoid network train its first layers so slowly?

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

Convolutions and CNNs

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.

Say it aloud

O equals the floor of W minus K plus two P, over S, plus one.

O
O the output width, in cells.
⌊ ⌋
the floor of round down to a whole number.
W
W the input width.
K
K the kernel width.
P
P the padding: rings of zeros added on each side.
S
S the stride: how many cells the kernel jumps.
In plain words

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.

With numbers

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.

Slide the kernel

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.

6

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.

StageOutput shapeParameters
Input224 × 224 × 30
Conv 3×3, 64, padding 1224 × 224 × 641,792
Max pool 2×2112 × 112 × 640
Conv 3×3, 128, padding 1112 × 112 × 12873,856
Max pool 2×256 × 56 × 1280
Global average pool1280
Fully connected + softmax1000129,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.

A 7 by 7 input, a 3 by 3 kernel, padding 0, stride 2. What is the output width?

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

RNNs, LSTMs and Self-Attention

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.

Say it aloud

Attention of Q, K, V equals softmax of Q times K-transpose over the square root of d-k, times V.

Attn
attention the output: one new vector per token, shape n by dv.
softmax
softmax, row by row turns each row of scores into weights that add to 1.
Q
Q the queries, one row per token, shape n by dk.
KT
K-transpose the keys turned on their side, so QKT is n by n: query i dotted with key j.
√dk
root d-k the square root of the key length. It keeps the scores near size 1.
V
V the values, one row per token.
In plain words

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 numbers

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.

Scale the scores, or not

Rows are queries, columns are keys; darker means more weight. Raise dk with the scaling off and watch each row collapse onto one key.

512

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.

Why divide the scores by the square root of dk?

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

The Field Guide

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.

CNN, RNN, Transformer (Q16)

FamilyCore operationBuilt-in assumptionRuns in parallel?Weak spot
CNNa small kernel slid over the inputnearby things matteryeslong-range links need many layers
RNN / LSTMone state updated per steporder mattersno, step by stepslow; gradients fade over long spans
Transformerevery token attends to every tokenfew; position must be addedyescost grows with n²

The pipeline, end to end (Q17)

  1. Split the data into train, validation and test, for example 80/10/10. Touch the test set once.
  2. Augment the training images: random crop, flip, colour jitter.
  3. Choose a model that fits the data: a ResNet for images, a transformer for text.
  4. Choose the loss: cross-entropy for classes, squared error for numbers.
  5. Choose the optimiser and schedule: AdamW at about 0.0003 with warmup and cosine is a common start.
  6. Train: forward, loss, backward, step, then zero the gradients.
  7. Watch validation loss each epoch and keep the best weights (early stopping).
  8. Tune the learning rate, weight decay and batch size on validation, never on test.
  9. Test once and report that number.
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()

Terms and numbers

TermOne lineNumber to remember
Gradient descentstep against the slopew = 3, η = 0.1 on w² gives 2.4
Momentuma velocity that keeps old stepsβ = 0.9 gives up to 10 times the step
SGD limitsteepest curvature caps ηη < 2/25 = 0.08 in the hero valley
Adamper-weight step from m-hat over root v-hatfirst step is about η for every weight
Cross-entropyminus the log of p-yp-y 0.659 gives 0.417; 0.01 gives 4.61
Bias, variancemiss of the average, scatter of the fits0.25 + 0.06 + 0.04 = 0.35
L1 vs L2zeros vs shrinkagea = 0.3, λ = 0.5: 0 vs 0.15
Sigmoid depthslope at most 0.25 per layer0.2510 is about 0.000001
Conv sizefloor((W − K + 2P)/S) + 16, 3, 0, 2 gives 2
Attentionsoftmax(QKT/√dk)Vn = 1,000 tokens: 1 million scores

Checklist before you teach

Keep going

The takeaway. Every foundation question is one stage of the same loop. If you can draw the loop, write the stage's equation, read it aloud and work one number through it, you can teach it.
In the training loop, what must happen between two calls to 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.

Credit

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.

Teach: DL/ML Foundations
Back to Gleams