The chain rule as one move: each step multiplies the gradient from above by its own slope
Place every transpose and every sum by matching shapes, with no indices
Why softmax and cross-entropy together give softmax minus one-hot, divided by N
Take the ReLU mask from the input, and sum each bias gradient over the batch
Keep the loss finite with logits in the tens of thousands
Prove it all with a central-difference check, then answer the follow-ups on vanishing gradients, the max shift and layer norm
Part 1 of 6about 15 min
The chain rule
Backprop by hand, for a two-layer network
One OpenAI ML engineer candidate reports an ML coding round on a matrix multiplication's forward pass and backprop, written in PyTorch from a code skeleton (1 report). The same candidate says NumPy fluency was essential (1 report). Backprop by hand prepares you for both, and the practice problem asks for it on the smallest network that has every part. Our version reads like this:
Here's a two-layer network in NumPy: a linear layer, a ReLU, a second linear layer, and the mean softmax cross-entropy over the batch. Write forward_backward(params, x, y). Return the loss and a gradient for each of W1, b1, W2 and b2, with no autograd. Then show me it's right.
Array
Shape
x
(N, D): N examples of D numbers
W1 and b1
(D, H) and (H,)
W2 and b2
(H, K) and (K,)
y
(N,): one label per example, from 0 to K - 1
The practice comes in four levels. Level 1 checks only the loss. Level 2 checks every gradient against nudging each weight, then trains the network on three blobs of points. Level 3 multiplies W2 by 10,000, so the logits reach the tens of thousands and the loss must stay finite. Level 4 writes one training step that clips all the gradients together by their total length.
You don't write it yet. The lesson starts with what backprop computes and the one rule behind every step, then builds each gradient in the order the backward pass needs them. At the end you solve the whole problem, level by level, in an interview simulation with a 45-minute timer.
This lesson builds on the NumPy lesson's shapes and broadcasting, and on the softmax from the attention lessons. The matmul backward lesson comes next and writes a backward pass of your own in PyTorch, the round the report describes.
What backprop computes
Start from the forward pass, because the backward pass reads it in reverse.
import numpy as nprng = np.random.default_rng(0)N, D, H, K = 6, 4, 5, 3x = rng.normal(size=(N, D))y = rng.integers(0, K, size=N)W1, b1 = rng.normal(size=(D, H)), np.zeros(H)W2, b2 = rng.normal(size=(H, K)), np.zeros(K)# hidden layer, before the ReLUpre = x @ W1 + b1# after the ReLUh = np.maximum(pre, 0)# one score per classlogits = h @ W2 + b2print(pre.shape, h.shape, logits.shape)
Predict
x is (6, 4), W1 is (4, 5) and W2 is (5, 3). What shapes are pre, h and logits?
Pick one to see what it prints.
This is the network from the practice problem: 6 examples, 4 inputs, 5 hidden units and 3 classes. Step through its whole forward pass, top to bottom:
The forward passInteractive
→
→
→
→
x (N, D) = 6 rows of 4 numbers. One row per example.
The letters: N examples, D input numbers per example, H hidden units and K classes. The labels y are N whole numbers, each from 0 to K - 1.
Training needs one number per weight: how much the loss moves when that weight moves a little. That number is the weight's gradient. Backprop, short for back-propagation, finds every gradient in one sweep from the loss back down to the input.
Rumelhart, Hinton and Williams described the method in 1986. It adjusts the weights again and again, so that the network's output gets closer to the output you want.
Your job is four gradients, one each for W1, b1, W2 and b2. Keep pre after the forward pass. The backward pass needs it.
In the editor, write forward(params, x): the three lines above as a function. Return pre with the rest, because the backward pass needs it.
Each step multiplies the gradient from above by its own slope
Start smaller: three numbers and two steps.
a, b, c = 2.0, -3.0, 10.0e = a * bL = e + cdL = 1.0 # start at the loss# an add passes the gradient throughde = dLdc = dL# a multiply sends each input the other inputda = de * bdb = de * aprint(L, da, db, dc)
Predict
a = 2, b = -3, c = 10, then e = a * b and L = e + c. What are da, db and dc?
Pick one to see what it prints.
The forward pass computes the values and keeps them. The backward pass starts from 1 at the loss and runs the steps in reverse. Step through both:
e = a × b, then L = e + cInteractive
forward, values backward, gradients
Forward: e = a × b = 2 × -3 = -6.
Each step has a local derivative: how its output moves when its input moves, with everything else held still. The backward pass visits the steps in reverse. Each step takes the gradient that arrives from above, multiplies it by its local derivative, and hands the result to its inputs.
That one move is the chain rule:
∂x∂L=∂y∂L⋅∂x∂y
In words: the gradient at a step's input x is the gradient at its output y times the step's own slope.
In the editor, write grads(a, b, c) for a different pair of steps, an add and then a multiply. Start from 1 at the loss and apply each step's rule in reverse.
Karpathy backpropagates through a small expression by hand, each step the local derivative times the gradient from above, and checks the results by nudging the inputs.
The spelled-out intro to neural networks and backpropagation: building micrograd · Andrej Karpathy · Aug 2022YouTube
Pick an answer above to see the rest
Six rules cover every step in this network
Write dX for the gradient of the loss with respect to X. It's an array with the same shape as X.
Forward
Backward, given dout
out = a + b
da = dout, db = dout
out = a * b (elementwise)
da = dout * b, db = dout * a
out = np.maximum(a, 0)
da = dout * (a > 0)
out = a @ W
da = dout @ W.T, dW = a.T @ dout
out = a + b, with b broadcast over rows
db = dout.sum(axis=0)
a feeds two operations
da is the sum of what each one sends back
An add passes the gradient through, unchanged.
A multiply swaps: each input gets the other input times the gradient.
ReLU is a gate. The gradient passes where the input was positive and stops everywhere else.
A matmul is a multiply for whole arrays, so it swaps too. The shapes tell you where the transposes go.
The last row of the table needs a picture. A value that feeds two steps gets a gradient back from each:
One value, two stepsInteractive
forward, values backward, gradients
a feeds two steps: y = a × 4 = 12 and z = a + 1 = 4. Then L = y + z = 16.
That's why an autograd engine, the code that runs the backward pass for you in PyTorch, adds into each gradient instead of overwriting it.
In the editor, write grads(a, b) for L = a * b + a, where a is used twice.
The inner N's meet and are summed away, which leaves (5, 3): the shape of W2. This is the gradient.
A gradient always has the shape of the thing it's the gradient of.
dW2 must be (H, K), like W2. The only product of h at (N, H) and dlogits at (N, K) with that shape is h.T @ dlogits.
dh must be (N, H), like h. From dlogits at (N, K) and W2 at (H, K), that's dlogits @ W2.T.
So you rarely need to write out indices. Match the shapes, and the transposes place themselves.
The matmul in h.T @ dlogits also adds something up. Each example gives its own (H, K) piece, its row of h times its row of dlogits, and the matmul sums the N pieces:
by_example = sum(np.outer(h[n], dlogits[n]) for n in range(N))print(np.allclose(dW2, by_example))
Pick an answer above to see the rest
Predict
Add up one outer product per example, row n of h times row n of dlogits. Does the sum equal h.T @ dlogits?
Pick one to see what it prints.
Your solution doesn't need np.outer. It's here to show what the matmul adds up.
Before any code, the shapes. In the editor, fill in shapes: the shape of every gradient in the network, as tuples of the letters.
b2 is (3,), added to all 6 rows. What shape is dlogits.sum(axis=0)?
Pick one to see what it prints.
In the forward pass, broadcasting added the same b2 to every one of the N rows, as if it had been copied N times. Each copy gets its own row of dlogits as its gradient. All the copies are the same b2, so its gradient is the sum of those rows, down each column:
db2 = dlogits.sum(axis=0)Interactive
dlogits.sum(axis=0)
class 0class 1class 2example 0example 1example 2↓↓↓sum
shape(3, 3)→(3,)the 3 examples are gone
class 0: 0.1 + 0.4 + -0.2 = 0.3
Use a plain .sum(axis=0), with no keepdims, because the result has to be (K,) like b2. The same goes for b1: db1 = dpre.sum(axis=0).
In the editor, write linear_backward(a, W, dout) for one linear layer, out = a @ W + b. Return da, dW and db, each shaped like the thing it's the gradient of.
CheckpointBackward through a linear layer
Write linear_backward(a, W, dout) for out = a @ W + b, where a is (N, D_in), W is (D_in, D_out) and dout is (N, D_out). Return (da, dW, db), each shaped like the thing it's the gradient of. The tests use the practice's last layer: 6 examples, 5 hidden units, 3 classes.
Pick an answer above to see the rest
The backward pass is the forward pass read bottom to top
Here is every gradient in the practice problem, from the loss down, with the rule that makes it. Step through it:
The backward passInteractive
→
→
→
→
→
dlogits (N, K) = softmax minus one-hot, over N. The next part derives it. Here it's given.
Every gradient comes from a rule you already have: the shape rule places a matmul's transpose, the bias rule sums over the batch, and the ReLU gate multiplies by the mask from the table of six rules. Only dlogits is new, and it gets the next part.
In the editor, write backward(params, x, pre, h, dlogits): every gradient in the flow, from dlogits down to dW1 and db1.
Example 2 has logits [1, -1], label 1 and softmax [0.88, 0.12]. What is its row of dlogits, with the batch of 2?
Pick one to see what it prints.
Pick a row to see what it sends back:
What each row sends backInteractive
class 0class 1, label
logits1-1
p0.880.12
one-hot01
p - one-hot0.88-0.88
÷ N = 20.44-0.44
the push on each logit
down 0.44
up 0.44
class 0class 1
Class 1 is the label and gets -0.44, so training pushes its logit up. Class 0 gets +0.44 and is pushed down. The row sums to 0. Most of the weight sat on a wrong class, so this row sends back the most.
Training moves each logit against its gradient, so a positive entry pushes its logit down. Read a row:
The right class's logit is pushed up, by 1 - p for that class.
Each wrong class's logit is pushed down, by its own probability.
The pushes cancel, so every row sums to zero.
Pick an answer above to see the rest
Predict
Which example sends back the biggest gradient?
Here is why, in two lines. Take one example with logits z and label c, and let p be the softmax of z. The loss is minus the log of the label's probability:
L=−logpc=−zc+logj∑ezj
The first term, −zc, has slope -1 at the label and 0 everywhere else. The second term's slope at zk is ezk/∑jezj, which is just pk. Add the two:
∂zk∂L={pk−1pkif k=cotherwise
The practice loss is the mean over N examples, so each row also carries a factor of 1/N. With P the (N, K) probabilities and Y the one-hot labels, dlogits = (P - Y) / N.
In the editor, write row_grad(p, label): one row's gradient, the softmax p with 1 subtracted at the label.
The cross-entropy loss differentiated by hand and collapsed into the same three lines (softmax, subtract 1 at the label, divide by n), then a look at one row, which sums to zero.
Building makemore Part 4: Becoming a Backprop Ninja · Andrej Karpathy · Oct 2022YouTube
Pick an answer above to see the rest
A loss that survives huge logits
Subtract each row's max, and np.exp can't overflow
The practice tests push the logits into the tens of thousands, and np.exp has a limit.
What do np.exp(709.0) and np.exp(710.0) print in float64?
Pick one to see what it prints.
The practice tests multiply W2 by 10,000, which puts the logits in the tens of thousands, up to about 100,000. So subtract each row's largest logit first:
Class 0
Class 1
Class 2
logits
30000
30002
29999
z, minus the max
-2
0
-3
exp(z)
0.14
1.00
0.05
The largest is now 0, and nothing overflows. After the shift the largest exponent is e0=1, so the sum, 1.19 here, always lies between 1 and K. The shift doesn't change the softmax either. The follow-ups at the end come back to why.
In the editor, write softmax(z) with the shift: each row's own max, lined up with keepdims=True.
Do the softmax and the log as one step, and nothing divides by zero
You could run the log's backward and then the softmax's backward, one at a time. The math is the same. But the log's backward divides by pc, the label's probability, and that can be 0:
p_c = np.exp(-800.0). What do p_c, -1 / p_c and -1 / p_c * p_c print?
Pick one to see what it prints.
A NaN spreads to every gradient it touches. The fused form, softmax minus one-hot, never divides. That's why frameworks compute the two as one step.
In the editor, write dlogits(logits, y): the whole gradient at the logits, the softmax minus the one-hot, over N. Your stable softmax from the last step is written for you.
CheckpointSoftmax minus one-hot, over N
Write dlogits(logits, y): the gradient of the mean softmax cross-entropy with respect to logits, which is (N, K), with y holding the (N,) integer labels. A stable softmax over the rows is in the stub.
Pick an answer above to see the rest
Take the log of a sum, never the log of a probability
Subtracting each row's max keeps np.exp finite. The log has a trap of its own.
z = np.array([0.0, -40000.0, 3.0])z = z - z.max()probs = np.exp(z) / np.exp(z).sum()print(probs)print(-np.log(probs[1]))log_probs = z - np.log(np.exp(z).sum())print(-log_probs[1])
Predict
The label is class 1, whose logit sits 40,003 below the top. Its probability rounds to 0.0. What do -np.log(probs[1]) and the log-space line give?
Pick one to see what it prints.
Route
What you hold for label 1
Loss
The log of a probability
p = 0.0 in float64
-log(0.0) = inf
Log space, never forming p
log p = -40003 - 0.05
40003.05
The log-space formula, for each logit zk in a row:
logpk=(zk−m)−logj∑ezj−m
Here m is the row's largest logit, and the sum runs over the row's K logits. The code above does it for one row. For a batch of rows, take the max and the sum along axis 1, with keepdims=True so each row's max and each row's sum stay lined up with that row.
This happens in the practice tests. With W2 scaled up, one example has a label probability of about e−39241, which underflows to exactly 0.0. np.log(probs) turns that into -inf and the loss into inf. The log-space formula reports that example's loss as 39,241 and the batch mean as 6,540.2.
The gradient is safe either way. It needs only the probabilities, np.exp(log_probs). One that underflows to 0 just makes that entry of dlogits equal to (0−1)/N.
PyTorch takes the same route. Its CrossEntropyLoss expects raw logits and applies the log-softmax itself. Hand it logits, never probabilities.
In the editor, write mean_cross_entropy(logits, y): the log-space formula for every row, then the mean of minus each label's log-probability.
CheckpointCross-entropy in log space
Write mean_cross_entropy(logits, y) for (N, K) logits and (N,) integer labels. It has to stay finite with logits in the tens of thousands, and when a label's probability underflows to 0.
Pick an answer above to see the rest
Part 3 done
Part 4 of 6about 19 min
The ReLU mask, and a worked example
The ReLU mask
The mask comes from pre, never from h
You've used the ReLU gate once already. One detail of it decides whether your gradients come out right.
pre is [1.5, -0.5, 2.0, -3.0] and dh is [0.1, 0.2, 0.3, 0.4]. What is dh * (pre > 0)?
Pick one to see what it prints.
dh * (pre > 0) is right. The gradient passes where pre was positive and stops where it wasn't. Try the other two masks:
Where the gradient gets throughInteractive
unit 0unit 1unit 2unit 3
pre1.5-0.52-3
h1.5020
pre > 0onoffonoff
dh0.10.20.30.4
dpre0.100.30
The gradient passes where pre was positive and stops where it wasn't, so units 1 and 3 pass nothing back.
ReLU's local derivative is 1 where its input was positive and 0 where it wasn't. So dpre = dh * (pre > 0).
At exactly 0 the slope isn't defined, and pre > 0 uses 0 there, the usual choice. A real-valued pre is almost never exactly 0.0, so the choice rarely matters.
The third line is the trap. ReLU's output is never negative, so h >= 0 is True everywhere, and nothing gets masked.
h > 0 happens to equal pre > 0 for ReLU, but the habit breaks on the next activation you meet. GELU dips below zero and comes back up. Its output is -0.10 at both -0.25 and -1.5, where its slopes are +0.30 and -0.13. The output can't tell you which slope applies. Save the input in the forward pass and mask with it.
In the editor, write relu_backward(dh, pre): the gate, with the mask taken from pre.
A unit that's off for the whole batch gets no gradient
The mask has a side effect worth naming in an interview.
Unit 1 was off for every example
dpre (3, 3)
unit 0unit 1unit 2example 00.30-0.1example 1-0.200.4example 20.500.2
Unit 1's column is all 0. So its column of W1, from x.T @ dpre, gets 0. Its entry of b1, from dpre.sum(axis=0), gets 0. Its row of W2, from h.T @ dlogits, gets 0 too, since its h is 0.
A unit that's off for every example in the batch gets an all-zero column in dpre. So its column of W1 and its entry of b1 get no gradient. Its row of W2 gets none either, because its column of h is 0.
If no input ever turns it back on, it never learns again. That's a dead ReLU.
In the editor, write hidden_backward(dh, pre, x, W1): the gate, then the linear layer below it. linear_backward from earlier is written for you.
CheckpointBack through the ReLU
The hidden layer is pre = x @ W1 + b1, then h = np.maximum(pre, 0). Write hidden_backward(dh, pre, x, W1): given dh, the (N, H) gradient at h, return (dx, dW1, db1). Your linear_backward from earlier is in the stub.
A worked example
These numbers are small enough to check by hand: two examples, two inputs, two hidden units, two classes, and biases at zero.
Example 2's second hidden unit had pre = -1. What does dpre hold there?
Pick one to see what it prints.
The first grid is dpre, one row per example, and the second is dW1. Follow example 2 down through the forward pass, then back up:
Example 2, label 1
Forward, read down
Backward, read up
pre and dpre
[1, -1]
[0.88, 0], masked
h and dh
[1, 0], unit 2 off
[0.88, -0.44]
logits and dlogits
[1, -1]
[0.44, -0.44]
probs
[0.88, 0.12], wrong
Loss
2.13
Example 1's row of dlogits is ([0.5,0.5]−[1,0])/2=[−0.25,0.25]. Example 2's row is bigger, because it's more wrong.
The mask zeroes the one entry where pre was negative.
Then the parameter gradients:
Gradient
Value
dW2 = h.T @ dlogits
[[0.19, -0.19], [-0.50, 0.50]]
db2 = dlogits.sum(axis=0)
[0.19, -0.19]
dW1 = x.T @ dpre
[[0.38, 0.25], [2.26, -0.25]]
db1 = dpre.sum(axis=0)
[0.38, 0.25]
The second row of dW2 comes from example 1 alone, because hidden unit 2 was 0 for example 2.
Drop the mask and the second column of dW1 becomes [-0.19, -1.13] instead of [0.25, -0.25]. The dead unit gets blamed for example 2's mistake, and the top entry flips sign.
In the editor, finish grads() on the worked example. Your numbers should match the table.
def loss_at(W1: np.ndarray) -> float: """W1: (2, 2). The worked example's mean loss with this W1.""" logits = np.maximum(x @ W1, 0) @ W2 z = logits - logits.max(axis=1, keepdims=True) return np.mean(np.log(np.exp(z).sum(axis=1)) - z[np.arange(2), y])down, up = W1.copy(), W1.copy()down[1, 0] -= 1e-6up[1, 0] += 1e-6print(f"{loss_at(down):.9f} {loss_at(up):.9f}")print(f"{(loss_at(up) - loss_at(down)) / 2e-6:.10f}")print(f"{(x.T @ dpre)[1, 0]:.10f}")
Predict
Nudge W1[1, 0] by ±1e-6 and divide the change in the loss by 2e-6. How close does it come to backprop's 2.2615941560?
Pick one to see what it prints.
Nudging both ways and dividing the change in the loss by the distance between the two points, 2ϵ, is a central difference. The next part shows why it beats a nudge in one direction.
In the editor, write slope_at(i, j, eps): the same measurement for any entry of W1.
Nudge a weight both ways, and the loss gives its gradient
You can't eyeball a gradient, but you can measure one. Try it on v3 at v=2, whose true slope is 12:
def cube(v: float) -> float: """Returns v cubed. Its slope at v is 3 v².""" return v ** 3for eps in [1e-2, 1e-4, 1e-6]: central = (cube(2 + eps) - cube(2 - eps)) / (2 * eps) one_sided = (cube(2 + eps) - cube(2)) / eps print(f"{eps:.0e} {abs(central - 12):.0e} {abs(one_sided - 12):.0e}")
Predict
The slope of v³ at 2 is 12. With a nudge of 1e-4, how far off are the central estimate, which nudges both ways, and the one-sided one, which nudges only up?
Pick one to see what it prints.
Each line is the nudge size ε, then the error of the central difference and of the one-sided difference.
Here are both as lines through the curve. Shrink ε and watch the errors:
Two ways to measure a slopeInteractive
true slope, 12 one-sided central
One-sided slope
15.25
One-sided error
3.25
Central slope
12.25
Central error
0.250
At ε = 0.50 the one-sided line is off by 3.25, and the central one by 0.250. Halve ε and the one-sided error roughly halves, while the central error drops to a quarter: the curve's bend adds an error on each side, and the central line's two errors cancel.
On each side the curve's bend adds an error. In the central version those two errors cancel, so what's left shrinks like ϵ2. The one-sided error shrinks only like ϵ: make ε 100 times smaller, and the one-sided error drops 100 times, the central one 10,000 times.
At ϵ=10−6 the central error stops at 8e-10 instead of 1e-12. Rounding has taken over, and the next part shows why.
For a network, nudge one parameter at a time:
∂θi∂L≈2ϵL(θ+ϵei)−L(θ−ϵei)
Here θ is every parameter laid out as one long vector, θi is one entry of it, and ϵ is the size of the nudge. ei is all zeros except a 1 at position i, so θ±ϵei moves that one entry and leaves the rest alone.
In the editor, write errors(f, true_slope, v, eps): how far each estimate lands from the true slope.
Too small an ϵ fails the other way. Each loss is only accurate to about float64's rounding, and you divide that rounding error by 2ϵ.
Predict
Run the check in float32 at ε = 1e-6, on a network whose largest gradient entry is 0.64. How far off is the worst entry?
Here is the worst error over all 43 parameters of the network in the practice tests:
ϵ
float64, central
float64, one-sided
float32, central
1e-2
2.1e-5
6.7e-3
2.2e-5
1e-4
2.1e-9
6.7e-5
6.1e-4
1e-5
2.9e-11
6.7e-6
6.5e-3
1e-6
1.7e-10
6.7e-7
6.3e-2
1e-8
1.6e-8
2.6e-8
6.4e-1
1e-10
9.8e-7
3.1e-6
6.4e-1
The float64 central column falls, then climbs again.
In float64 the sweet spot is 10−5 to 10−6. That's near the cube root of float64's machine epsilon, the gap between 1 and the next float64. That cube root is about 6×10−6. The tests use 10−6.
In float32 the error never gets below 2e-5.
Run the check in float64. PyTorch's own gradcheck docs say the same: its defaults are built for double precision, and the check will likely fail in lower precision.
In the editor, write central(f, v, eps, dtype), and see the float32 column of the table for yourself.
Here is the check on every parameter of the practice network. numeric_grad is the part you write next:
_, grads = forward_backward(params, x, y)for name, p in params.items(): num = numeric_grad(lambda w: forward_backward({**params, name: w}, x, y)[0], p.copy()) assert grads[name].shape == p.shape, name assert np.allclose(grads[name], num, rtol=1e-5, atol=1e-7), name
How it works:
numeric_grad(f, w) measures the slope of f along every entry of w, one entry at a time: a central difference for each.
np.ndindex(w.shape) gives every index of an array of any shape, so one loop visits every entry.
The lambda takes an array w, runs forward_backward with w in place of that one parameter, and keeps item [0], the loss.
np.allclose passes when every entry is within atol + rtol * abs(num) of the numerical value.
Callable[[np.ndarray], float], in the stub, is the type of a function that takes an array and returns a float.
Three things to watch:
Kinks. A nudge that carries pre across 0 crosses ReLU's corner, and the check can fail on correct code. PyTorch's gradcheck docs warn about the same thing at points with no derivative. In the test network the pre value nearest zero is 0.16 away, far beyond any 10−6 nudge.
Cost. Two loss evaluations per entry: 86 for the test network, two billion for a billion-parameter model. On a real model, check a random sample of entries.
Coverage. Check every parameter, and check its shape before its values.
In the editor, write numeric_grad(f, x, eps): the central difference of f along every entry of x, for any function and any array.
CheckpointA central-difference check
Write numeric_grad(f, x, eps=1e-6): the central-difference gradient of a scalar function f at the float64 array x, any shape. Nudge one entry at a time, and leave x as you found it.
Each test catches bugs the others miss
The practice tests pair the gradient check with a test at huge logits and a training run on three blobs of points. You've met five bugs in this lesson:
no division by N
b2 averaged twice
no ReLU mask
the mask from h >= 0
no max subtraction
Predict
Each of the five bugs goes through the training run. How many still reach 98.3% accuracy, the same as correct code?
Each bug's mistake box in this lesson said which test catches it. Think about the other two tests too: does the loss stay finite, and does training still fit?
In the editor, fill in catches: which tests fail on each bug. The next step has the full table.
Here is what each test sees, from running every bug through the practice tests:
Bug
Gradient check
Huge logits
Training run
No division by N
fails, all 6x
passes
fails, NaN
b2 averaged twice
fails on b2
passes
passes, 98.3%
No ReLU mask
fails on W1, b1
passes
passes, 98.3%
Mask from h >= 0
fails on W1, b1
passes
passes, 98.3%
No max subtraction
passes
fails, inf
passes, 98.3%
The gradient check can't see overflow, so it needs the huge-logit test beside it.
Part 5 done
Part 6 of 6about 19 min
What interviewers ask next
What interviewers ask next
Deep stacks multiply many factors, so gradients vanish or explode
Once your gradients pass the check, the questions turn to deeper networks.
print(round(0.9 ** 50, 3), round(1.1 ** 50))
Predict
Fifty layers each scale the gradient by 0.9, or each by 1.1. What reaches the bottom?
Pick one to see what it prints.
The gradient that reaches layer 1 has been multiplied by one local derivative for each layer above it. Pick a factor per layer and follow the gradient down fifty layers:
The gradient on its way downInteractive
0.9^50 = 0.0052.Each layer shrinks the gradient a little, and fifty shrinks multiply: it vanished.
For a ReLU layer, the factor depends on the scale of the weights:
The weights have standard deviation c/n, where n is the layer's width and c is a number you choose.
About half the units are on.
So each layer multiplies the gradient's variance by about c/2.
Fifty layers scale the gradient's size by (c/2)25.
The practice problem's init_params uses c=1, weights with standard deviation 1/n. That's harmless at two layers, and not at fifty.
Pick an answer above to see the rest
Predict
50 ReLU layers of width 256, with c = 1, so each layer halves the gradient's variance. How big is the gradient at the bottom, against the top?
Simulated, against the prediction:
Weight std
Per layer
Predicted
Measured, 5 seeds
1/n
1/2
3.0e-8
1.9e-8 to 4.3e-8
2/n
1
1
0.65 to 1.43
2.5/n
1.25
265
171 to 379
The first row is the practice's init_params.
The middle row is He initialization. He et al. (2015) built it for ReLU networks: the factor of 2 cancels ReLU's halving.
Saturating activations are worse. A sigmoid's slope is at most 0.25, so ten sigmoid layers multiply the gradient by at most 0.2510≈10−6 from the activations alone.
In the editor, write bottom_scale(c, layers), and reproduce the predicted column of the table.
Four fixes for a gradient that vanishes or explodes
Deep networks still train, because four fixes keep that product of factors in check. One of them is a new path for the gradient.
Predict
A residual block outputs x + f(x). What is its slope?
The fixes, and what each one targets:
Initialization sets each layer's factor to 1 at the start, as He init did in the last step.
Residual connections give the gradient a path with no factor at all. He et al. (2016) showed that with identity skip connections, the signal passes directly between any two blocks, forward and backward.
Normalization layers reset each layer's inputs to mean 0 and variance 1 before a learned scale, so the scale can't compound layer after layer.
Gradient clipping handles explosions after the fact. Pascanu et al. (2012) proposed it: when the size of the whole gradient passes a threshold, scale every gradient down by the same factor.
Pick an answer above to see the rest
Clipping shrinks every gradient by the same factor
Clipping is the fix you apply after the fact, when a step explodes anyway.
grads = {"W": np.array([[3.0, 0.0], [0.0, 4.0]]), "b": np.array([12.0])}max_norm = 6.5norm = np.sqrt(sum((g ** 2).sum() for g in grads.values()))clipped = clip(grads, max_norm)print(norm)print(clipped["W"].tolist(), clipped["b"].tolist())
Predict
The gradients' total length is 13, and max_norm is 6.5. What does clipping do to W's 3 and 4 and b's 12?
Pick one to see what it prints.
Read the norm line inside out: square every entry of each gradient, sum each array, add those sums across all the parameters, and take the square root. That's the length of all the gradients laid end to end as one vector.
All the gradients as one vector, before and after
before (1, 5)
WWWWb300412
after (1, 5)
WWWWb1.50026
Before, the length is 13. Every entry is multiplied by 6.5 / 13 = 0.5, so the length becomes 6.5 and the direction stays the same.
In the editor, write clip(grads, max_norm): one length for all the gradients, and one factor for all of them. Level 4 of the practice uses it.
Shifting a row's logits changes nothing in the gradient
A common follow-up: why doesn't subtracting the max change the gradient?
row = np.array([2.0, 1.0, -1.0])for shift in [0.0, -2.0, 5.0]: e = np.exp(row + shift) print((e / e.sum()).round(3))
Predict
Add 0, then -2, then 5 to every logit in [2, 1, -1]. What does the softmax give?
Pick one to see what it prints.
So the loss doesn't move either. Now follow that shift through the gradient. Shift every logit in a row by a small c, and the loss moves by c times the sum of that row of dlogits:
ΔL≈c(d0+d1+⋯+dK−1)
The loss can't move, so that sum must be 0. That's why every row of dlogits sums to zero.
Subtracting the max is one such shift. So the gradient that would flow back through the max is exactly zero, and you can treat the max as a constant. That's also why np.max having no derivative at ties never causes trouble.
On the practice network the row sums come out around 10−17, and a central difference on the shift gives exactly 0. The shift exists only for the forward pass, to keep np.exp finite.
In the editor, write shift_slope(z, label, eps): move the whole row both ways, and measure the loss.
Layer norm's backward mixes every feature in a row
Layer norm and batch norm both subtract a mean and divide by a spread. They differ only in the axis. Layer norm takes the mean across each row, axis 1. Batch norm takes it down each column, axis 0:
Layer norm reads across a row, batch norm down a columnInteractive
Here μ is the row's mean, σ2 its variance, s its spread with a small constant added, and x^ the row rescaled to mean 0 and spread 1. γ and β are the learned scale and shift, C numbers each, and ⊙ multiplies entry by entry.
Ba et al. (2016) built it this way: the mean and variance come from one example's own features, never from the rest of the batch. Three things change in the backward pass.
First, the local derivative isn't entry by entry anymore. Every output in a row depends on every input in that row, through μ and σ. You don't build the full C×C table of slopes. You use its short closed form. Write g=γ⊙dy, and take both means over the features:
dxa=s1(g−mean(g)−x^⊙a)=mean(g⊙x^)
Drop the paths through μ and σ and treat it as an entry-by-entry scale by γ/s, and in a small test the input gradient is off by up to 1.5 on entries no bigger than 3.8.
Second, γ and β are one per feature, broadcast over the batch. So their gradients sum over the batch, like a bias: dgamma = (dy * xhat).sum(axis=0) and dbeta = dy.sum(axis=0).
Third, each row of dx sums to zero, like each row of dlogits.
Pick an answer above to see the rest
Predict
Why does each row of layer norm's dx sum to zero?
In the editor, write layernorm_backward(dy, xhat, s, gamma) from the closed form above.
Batch norm is axis 0 in the layer norm step's figure. It uses the same formula, with the means taken over the batch axis instead of the features. Ioffe and Szegedy (2015) built the normalization over each training mini-batch into the model itself.
Predict
Batch norm: give one example a zero gradient from above. Is its dx zero?
Batch norm also behaves differently at inference. There it uses running averages, and its backward is a plain per-feature scale. Layer norm does exactly the same computation at training and at test time.
Pick an answer above to see the rest
The practice problem, start to finish
That's every piece the practice problem needs. It asks for the four levels from the start of the lesson, from a blank file, and the interviewer follows up after each one.
Check yourself
5 questions
1.Your gradient check fails, and every analytic gradient is exactly 6 times its finite-difference value. The batch has 6 examples. What's the bug?
2.dlogits is (N, K) and already divided by N. Which line gives db2?
3.You write the ReLU backward as dh * (h >= 0), where h = np.maximum(pre, 0). What does it compute?
4.You forgot the ReLU mask entirely. Which of the practice tests fail?
5.You skip the max subtraction, and the test pushes the logits up to about 100,000. What comes back?
Where this shows up
The reports behind this lesson, each with its source.
Same report, ML coding round: matrix multiplication forward pass and backprop in PyTorch, from a given code skeleton.
Candidate report·PracHub (first-person report, curated and edited by the site)·2026-08-24Source
Same MLE report, onsite ML coding: NumPy fluency was essential.
Candidate report·PracHub (first-person report, curated and edited by the site)·2026-08-25Source
“The procedure repeatedly adjusts the weights of the connections in the network so as to minimize a measure of the difference between the actual output vector of the net and the desired output vector.”
“we derive a robust initialization method that particularly considers the rectifier nonlinearities. This method enables us to train extremely deep rectified models directly from scratch”
“the forward and backward signals can be directly propagated from one block to any other block, when using identity mappings as the skip connections and after-addition activation”
“we transpose batch normalization into layer normalization by computing the mean and variance used for normalization from all of the summed inputs to the neurons in a layer on a single training case.”
“Our method draws its strength from making normalization a part of the model architecture and performing the normalization for each training mini-batch.”