A wrong backward pass never crashes. It trains garbage in silence. Nudge each input by 0.00001 and measure the slope. A correct layer agrees with its own gradient to one part in a billion. A buggy one misses by 50 to 100 percent.
Pick a layer. Switch between its correct backward pass and its classic bug, and watch the measured slopes (blue) part from the claimed gradient (warm). Then we build every layer of CS231n Assignment 2, piece by piece: affine, ReLU, softmax, the optimizers, batch norm, dropout, convolution and pooling.
You need some Python, a matrix multiply, and the idea that a derivative is a slope. We build the chain rule and the rest from zero.
A practice companion for Assignment 2 of Stanford CS231n: Deep Learning for Computer Vision (course notes at cs231n.github.io). The function names follow the assignment's starter code. The explanations, toy numbers and devices are our own, and every Code Lab runs numpy in your browser.
Your browser computes every number live. The layer runs forward on small random arrays and its backward pass returns a gradient. A central difference with a nudge of 0.00001 measures each slope. Relative error is CS231n's measure: the largest |a − n| / (|a| + |n|) over the entries.
Chapter 0
See why a straight line fails, why depth fixes it, and why depth needs a better way to write code
You have a pile of 32 × 32 colour photos and ten labels. The first try is one matrix multiply: flatten each photo to 3,072 numbers, multiply by a weight matrix, read ten scores. That is a linear classifier: it cuts the input space with straight lines. Cats and dogs do not sit on two sides of a straight line.
The device has the same problem in two dimensions. One class sits inside a ring of the other. No straight line separates them.
Teal dots are class A, warm dots class B. The shading is what the trained net predicts. At 0 hidden units it is a linear classifier. Add units and watch the boundary close around the centre.
Illustrative toy: 140 points, a two-layer ReLU net trained here for 400 full-batch Adam steps from a fixed seed. Accuracies are training accuracy on this toy.
A hidden layer is a matrix multiply followed by a bend. With 0 hidden units the net scores 56% on this ring. With 1 unit it scores 71%, with 2 units 87%, and with 3 units 100%: three bends make a triangle that encloses the centre.
Training needs the gradient: how the loss moves when each weight moves. Write the whole deep net as one function, and you must derive the gradient of the whole thing by hand. Add a fifth layer or batch norm, and you derive it again.
Drop one term in that derivation and nothing crashes. The loss falls slowly, or not at all, and no error points at the term. The fix is the design of Assignment 2: build each operation as a small layer with its own forward and backward pass, then stack layers. Check each layer alone with a numerical gradient check: nudge an input, measure the slope, compare. The hero runs that check.
The Forge Studio (the Build button) asks you to write all nine kernels of the assignment on live instruments. The four Code Labs on this page cover the hardest four.
Chapter 1
Give every layer the same two functions and one memory, and let the chain rule assemble the gradient
Every layer in the assignment keeps the same contract. The forward pass takes an input x and the parameters, returns an output out, and saves a cache: the values the backward pass will need. The backward pass takes dout, the gradient of the loss with respect to out, plus the cache. It returns dx, and dw and db if the layer has parameters.
pythondef layer_forward(x, w): out = ... # compute the output cache = (x, w) # keep what backward needs return out, cache def layer_backward(dout, cache): x, w = cache dx = ... # dout routed through this layer's local slope dw = ... return dx, dw
Why does this compose? A layer sees only its own input and output. Call the loss L, the layer's input x and its output out. The upstream gradient dout says how L moves when out moves. The layer knows its local slope: how out moves when x moves.
d-x equals d-out times the partial of out with respect to x.
Take the gradient dout that reached your output. Multiply it by your own local slope. Pass the result dx down. Each layer does this once, and the product along the path is the gradient of the whole net.
With made-up numbers: x = 2, an affine layer a = 1.5x − 1 = 2, a ReLU r = 2, and a loss L = r²/2 = 2. Backward: dout at r is r = 2. The ReLU is open, so its slope is 1 and da = 2. The affine slope is 1.5, so dx = 2 × 1.5 = 3. Nudging x to 2.00001 moves L by 0.00003, a slope of 3.
Press Step. Teal values flow right through the boxes, then warm gradients flow left. Drag x below 0.67 and watch the ReLU close.
Toy chain: affine with w = 1.5 and b = −1, then ReLU, then L = r²/2. The affine box also returns dw = x × da and db = da.
The symptom is a backward pass with nothing to work with: it recomputes values wrong, or it errors on a missing name. To measure, list what the backward formula reads, and check that the cache holds each item. The fix is to cache inputs in forward: ReLU keeps x, affine keeps x, w, b, batch norm keeps x̂ and the variance.
Common pairs come as a sandwich: affine_relu_forward calls affine then ReLU and keeps both caches. Its backward calls them in reverse order.
Chapter 2
Build the matrix multiply and the bend, and route the gradient back through each
A fully connected net uses two layers. The affine layer mixes every input feature into every output. The ReLU bends the result. Stack them and you have the net from Chapter 0.
Take a batch of N examples, each with D features, and an affine layer with M outputs. Call the inputs x, the weights w and the bias b.
Out equals x times w, plus b.
x.reshape(N, -1) flattens an image batch.For each example, multiply its features x by each column of w and add them. Then add that output's bias b. The result is out.
With made-up numbers: x = [[1, 2, 3], [4, 5, 6]], w = [[1, 0], [0, 1], [1, 1]], b = [0.5, −0.5]. Row one: 1 + 3 + 0.5 = 4.5 and 2 + 3 − 0.5 = 4.5. Row two gives 10.5 and 10.5.
Backward has three inputs to serve, so it returns three gradients. Each one routes dout, shape (N, M), back through the multiply.
| Gradient | Code | Why | With dout all ones |
|---|---|---|---|
| dx | (dout @ w.T).reshape(x.shape) | w carried x forward; w transposed carries the gradient back. | [[1, 1, 2], [1, 1, 2]] |
| dw | x_flat.T @ dout | Weight w[d, m] met x[:, d] in every example, so add over the batch. | [[5, 5], [7, 7], [9, 9]] |
| db | dout.sum(axis=0) | numpy copied b to every row. The reverse of a copy is a sum. | [2, 2] |
Each row of dout is one example's gradient. Change the batch size, then switch on the bug and compare the shape of db with the shape of b.
Illustrative dout values from a fixed seed, M = 2 outputs.
ReLU is max(0, z). Forward, it zeroes negatives. Backward, it is a gate: dz = dout * (z > 0). The gradient passes where the input was positive and stops where it was not. So ReLU caches z. A unit that is negative for every input gets zero gradient forever: a dead ReLU.
The symptom of the db bug is a shape error, or worse, a silent broadcast. To measure, assert db.shape == b.shape. The fix is dout.sum(axis=0).
affine_backward, why is db = dout.sum(axis=0) and not dout?Chapter 3
Turn scores into probabilities, score the batch with one number, and get its clean gradient
The net gives each example a row of class scores: any real numbers. Training needs one number that says how wrong the batch was. Softmax turns a row of scores into probabilities: raise e to each score and divide by the row's sum. Call the probability of class c for example i Pi,c, and the true class of example i yi.
L equals minus one over N, times the sum over i of the log of P-i-y-i.
For each example, find the probability P the net gave the right answer. Take its log, which is negative. Average over the N examples and flip the sign. That is L.
With made-up numbers: one example, scores [2.0, 1.0, 0.1], true class first. e to the scores: 7.39, 2.72, 1.11, sum 11.21. P = [0.659, 0.242, 0.099]. L = −log 0.659 = 0.417.
The gradient with respect to the scores is short. Call the gradient at score c of example i dsi,c, and the true-class marker 1[c = yi].
d-s-i-c equals P-i-c minus one-if-c-is-y-i, all over N.
Copy the probabilities P. Subtract 1 at the true class. Divide by N. A negative ds raises that score on the next step; a positive ds lowers it.
Same example, N = 1: ds = [0.659 − 1, 0.242, 0.099] = [−0.341, 0.242, 0.099]. The row sums to 0. A central difference on each score gives the same three numbers.
Teal bars are the probabilities P. Warm bars are the gradient ds. Drag the true-class score and watch its gradient shrink toward 0 as P nears 1.
One example, N = 1, the other two scores fixed at 1.0 and 0.1.
Two traps live here. Subtract each row's maximum before you raise e to the scores: e1000 overflows, and the shift does not change P. And keep the 1/N. Drop it, and the gradient is N times too large, so a learning rate that worked now blows up.
The full net is now in reach: affine and ReLU sandwiches, a last affine for the scores, then softmax. Add L2 regularization, 0.5 × reg × the sum of w², to L, and reg × w to each dw.
Chapter 4
Race four update rules down one narrow valley and see what each one fixes
You now have dw for every weight. Plain SGD steps against it: w ← w − lr × dw, where lr is the learning rate. In a long, narrow valley this fails twice. Across the valley the slope is steep, so SGD bounces from wall to wall. Along the valley the slope is gentle, so SGD crawls.
The contours are a valley 40 times more curved across than along. Press Play. Then switch off Adam's bias correction and race again.
Illustrative valley f = 0.05x² + 2y², start (−4.5, 1.2). Learning rates: SGD 0.4, momentum 0.05 with μ = 0.9, RMSProp 0.1 with decay 0.9, Adam 0.3 with β1 = 0.9, β2 = 0.999.
Momentum keeps a running velocity. Call it v, the memory factor μ (mu, often 0.9), and the gradient dw. Each step updates v, then moves w by v.
v becomes mu times v, minus l-r times d-w.
Keep 90% of the last velocity v. Add a small step lr × dw against the gradient. Move w by v. Steps that agree add up; steps that alternate cancel.
With made-up numbers: lr = 0.1, μ = 0.9, dw = 1 on every step. v goes −0.1, −0.19, −0.271, and tends to −lr / (1 − μ) = −1. A steady slope ends up 10 times faster.
RMSProp keeps a running average of dw² for each weight and divides the step by its square root. Steep directions get small steps, flat directions get large ones. Adam does both: a momentum average m of dw and an RMSProp average v of dw². Both start at 0, so early on they read too low. Adam fixes this with a bias correction. Call the step count t and the decay of m β1.
m-hat equals m divided by one minus beta-one to the t.
After t steps, m holds only the share 1 − β1t of the real average. Divide by that share. Do the same for v with β2. Then step by lr × m̂ / (√v̂ + ε).
With made-up numbers: step t = 1, dw = 0.5. m = 0.1 × 0.5 = 0.05, so m̂ = 0.05 / 0.1 = 0.5. v = 0.001 × 0.25 = 0.00025, so v̂ = 0.25. The step is lr × 0.5 / 0.5 = lr. Without the correction it is lr × 0.05 / 0.0158 = 3.16 lr.
So the correction stops early steps that are too large, not too small. With β2 = 0.999, the uncorrected step is 3 to 6.6 times too big for the first 20 steps. In the device, uncorrected Adam overshoots to x = 2.76. The symptom is a loss spike at the start; log the first step sizes against lr to see it.
Chapter 5
Rescale each feature over the batch, keep running statistics for test time, and route the coupled gradient
Stack six affine and ReLU layers and the activations drift: their mean and spread change as the layers below learn. Each layer chases a moving target. Batch normalization rescales each feature to mean 0 and spread 1 over the batch, then lets the net choose its own scale and shift. For one feature, call the batch mean μ, the batch variance σ², the learned scale γ and the learned shift β.
Out equals gamma times x minus mu, over the square root of sigma squared plus epsilon, plus beta.
Subtract the batch mean μ from x and divide by the spread. Call that x̂ (x-hat). Multiply by γ and add β.
With made-up numbers: a batch [1, 2, 3, 6]. μ = 3, σ² = (4 + 1 + 0 + 9) / 4 = 3.5, spread 1.871. x̂ = [−1.07, −0.53, 0, 1.60]. With γ = 2 and β = 0.5, out = [−1.64, −0.57, 0.5, 3.71].
Top line: raw values. Bottom line: the output. Drag the drift and the dots move, but the output stays put. Then pick a test mode.
Illustrative batch from a fixed seed; β = 0. The running averages use momentum 0.9 and here have settled on the training batch.
At test time you may have one example and no batch. So in training, batch norm also keeps running averages: running_mean ← 0.9 × running_mean + 0.1 × μ. From 0 with μ = 3, one step gives 0.3. Test mode uses only these. The symptom of mixing the modes up is good training accuracy and a test output stuck at β. The fix is one mode flag and two code paths.
μ and σ² depend on every example, so nudging one input moves every output. Call the gradient at x̂ dx̂ = dout × γ, and the batch size N.
d-x equals N times d-x-hat, minus the sum of d-x-hat, minus x-hat times the sum of d-x-hat times x-hat, all over N times the spread.
Start from N × dx̂. Subtract the batch sum of dx̂, for the mean. Subtract x̂ times the batch sum of dx̂ × x̂, for the variance. Divide by N times the spread.
Batch [1, 2, 3, 6], γ = 1, dout = [1, 0, 0, 0]. Σdx̂ = 1 and Σ(dx̂·x̂) = −1.069. dx = [0.248, −0.210, −0.134, 0.095], which sums to 0. A central difference agrees. Treating μ and σ as constants gives [0.535, 0, 0, 0]: wrong.
The parameter gradients are short: dγ = the sum of dout × x̂, and dβ = the sum of dout, both over the batch.
Chapter 6
Normalize each example on its own, and switch off random units while keeping the average output fixed
Batch norm needs a batch. With 2 examples its mean is noise, and at test time it needs running averages. Layer normalization swaps the axis: it normalizes each example over its own features. A row [1, 3, 5] has mean 3 and variance 2.67, so it becomes [−1.22, 0, 1.22], whatever else is in the batch.
| Layer | Mean and variance over | Needs running stats | The axis bug |
|---|---|---|---|
| Batch norm | the batch, one pair per feature (axis=0) | yes | normalize over features: that is layer norm |
| Layer norm | the features, one pair per example (axis=1) | no | normalize over the batch: that is batch norm |
Layer norm is batch norm on the transpose, so the assignment can reuse the batch-norm backward. Same in train and test: no mode flag.
Dropout is a regularizer. In training, it sets each unit to 0 at random, so no unit can rely on one partner. Call the input x, the chance to keep a unit p, and a random mask m that is 1 with chance p and 0 otherwise.
Out equals x times m, divided by p.
np.random.rand(*x.shape) < p, kept in the cache.Draw a fresh mask m. Zero the dropped units. Divide the kept ones by p. A unit's average output stays x, so test time can skip dropout. Backward is dx = dout × m / p.
With made-up numbers: x = [2, 2, 2, 2], p = 0.5, m = [1, 0, 1, 0]. out = [4, 0, 4, 0], mean 2. Without the / p, out = [2, 0, 2, 0], mean 1: test time would see twice the signal training saw.
This scheme is inverted dropout: all the scaling happens in training. The symptom of a missing / p is a net that does well in training and badly at test. To measure, compare the mean activation in train and test mode.
Twelve units, each with input 1. Press Play to draw a new mask each beat. Watch the running mean against the dashed test-time line, then switch on the bug.
Your browser draws the masks live with Math.random; the running mean averages every output since the last change.
Chapter 7
Slide one small filter over the image, size the output, and scatter the gradient back
An affine layer flattens the image and forgets which pixels are neighbours. A convolutional layer keeps the grid. It slides a small filter over the input. At each position it takes the dot product of the filter with the patch under it, and adds a bias. The input has shape (N, C, H, W): batch, channels, height, width. F filters have shape (F, C, HH, WW), and each one makes one output channel.
The purple square is the filter's patch. Drag the position to fill the output map. Change stride and padding and watch the output size.
Illustrative 6 × 6 image with a bright right half; the filter [[1, 0, −1]] repeated on three rows finds vertical edges; bias 0.
How big is the output? Call the input height H and the filter height HH. The padding P is the rings of zeros around the border. The stride S is how far the filter jumps.
H-prime equals H plus two P minus H-H, over S, plus one.
Pad the input. Subtract the filter height HH: that is the room the filter can travel. Divide by the stride S to count the jumps, and add 1 for the first position.
CIFAR-10 images, H = 32, with 7 × 7 filters, P = 3, S = 1: (32 + 6 − 7) / 1 + 1 = 32. The device: H = 6, HH = 3, P = 0, S = 1 gives 4. With S = 2 it gives 2.5: the filter does not fit.
A filter uses the same weights at every position: weight sharing. 32 filters of 3 × 7 × 7 cost 32 × 147 + 32 = 4,736 parameters. An affine layer from the 3,072 pixels to the same 32 × 32 × 32 output would need 100,696,064.
Forward gathers a patch. Backward scatters. Each output cell sends dout × w[f] into the patch of dx under it. It also sends dout × patch into dw[f]. db[f] is the sum of dout over channel f. With stride 1 and a 3 × 3 filter, an inner pixel sits under 9 positions, so its gradient is a sum of 9 parts. The classic bug writes dx[...] = ... where it needs +=. It passes when the stride equals the filter size, and fails a gradient check when patches overlap.
Chapter 8
Shrink a feature map by keeping each window's winner, and reuse batch norm with one reshape
Max pooling slides a window, usually 2 × 2 with stride 2, over each channel and keeps the largest value. It halves the height and the width, has no parameters, and forgets small shifts in position.
The backward pass follows from the forward. Only the winner of a window changed the output; nudge any other cell a little and the output stays the same. So the whole of dout goes to the winner's cell, and every other cell gets 0. The forward pass caches the input so backward can find each window's winner again.
Forward rings each window's winner. Backward sends dout to that one cell. The bug spreads dout over the whole window, which is the backward of average pooling.
Illustrative 4 × 4 map and dout = [[2.0, −0.5], [0.25, 1.0]].
With numbers: a window holds [1, 3; 2, 9] and its dout is 2.0. The winner is 9, so dx = [0, 0; 0, 2.0]. The spread bug gives 0.5 to each cell. A gradient check catches it: the measured slope at the cell holding 1 is exactly 0.
For images, the unit to normalize is a channel. Every pixel of channel c, in every image of the batch, shares one mean and one variance. Spatial batch norm gets there with a reshape around the batch norm you built.
x.transpose(0, 2, 3, 1) gives (N, H, W, C)..reshape(-1, C) gives (N·H·W, C).batchnorm_forward: each of the C columns gets its own mean and variance.For N = 2, C = 3 and a 4 × 4 map, step 3 gives a (32, 3) array: 32 values per channel. The symptom of the axis bug is one mean for all channels; a channel of large values then drowns the others. To measure, print the output mean of each channel: each should be about 0. The fix is the transpose before the reshape. Reshape without it and the columns mix channels.
Chapter 9
Train a tiny ConvNet in your browser, then break one backward pass and watch what changes
Every layer so far now runs together. The task: tell vertical bars from horizontal bars in noisy 6 × 6 images. The net is conv (2 filters, 3 × 3) → ReLU → average pool → affine (2 to 2) → softmax loss. Each arrow is a forward pass on the way in and a backward pass on the way out.
Press Train. Watch the loss (warm) fall, the test accuracy (green) rise, and the two filters take shape. Then pick a bug, reset, and train again.
Real training in your browser: 32 training and 32 test images from a fixed seed. Plain SGD, lr 0.8, full batch, 200 steps. The numbers in the text come from this exact run.
Read the four runs. With no bug, the loss falls from 0.68 to 0.013 in 200 steps and the net gets 30 of 32 test images right (94%). Each run starts from the same weights, so only the bug differs.
| Bug | Loss after 200 steps | Test accuracy | What happened |
|---|---|---|---|
| None | 0.013 | 94% | Learns. |
| Conv dw overwrites | 0.63 | 81% | dw keeps one position of one image, so the filters barely learn and the loss stalls. |
| Softmax drops / N | 8.5 | 50% | Every gradient is 32 times too big, the steps overshoot, and the loss climbs. |
| ReLU passes all | 0.090 | 88% | Still learns, slower. The wrong gradient points roughly the right way. |
The last row is the dangerous one. A bug that only slows training looks like a bad learning rate. You tune for a week and never find it. Only a gradient check on each layer says which backward pass lies. None of the four runs crashed.
The assignment's three-layer ConvNet has the same shape at a larger size, on CIFAR-10. Its stack: conv with 32 filters of 7 × 7, ReLU, 2 × 2 max pool, affine, ReLU, affine, softmax.
Chapter 10
Match a symptom to its layer, keep the formulas on one card, and know where to go next
Every layer is a forward pass, a cache and a backward pass. A gradient check proves each one alone, and a net of proven layers learns. When a net will not learn, the symptom usually names the layer.
| Symptom | Likely cause | Fix |
|---|---|---|
| Gradient check fails on one layer | a missing sum, transpose or coupling term in its backward | trust the check; re-derive that layer's local slope |
| Loss and gradients N times too big | softmax sums instead of averaging | divide the loss and the score gradient by N |
| Shape error in affine backward | db not summed over the batch | db = dout.sum(axis=0) |
| Many ReLU units never fire | dead ReLUs, often from a learning rate that is too high | lower lr, better initialization |
| Loss spikes in the first Adam steps | no bias correction | divide m by 1 − β1t and v by 1 − β2t |
| Good train accuracy, test output stuck at β | batch norm uses batch stats at test | test mode uses running stats only |
| Train and test activations differ by a factor p | dropout without / p, or dropout left on at test | divide by p in training; identity at test |
| Conv check fails only when patches overlap | = instead of += in the scatter | accumulate into dx and dw |
| Spatial batch norm has one mean for all channels | wrong axes in the reshape | transpose C last, reshape to (N·H·W, C) |
| Quantity | Value |
|---|---|
| Nudge in a central difference | 0.00001 |
| Relative error of a correct layer | about 1e−9 or smaller |
| Relative error of a buggy layer | 0.5 to 1 |
| Momentum speed-up at μ = 0.9 | 10 times |
| Adam first step without bias correction (β1 = 0.9, β2 = 0.999) | 3.16 times too large |
| Conv layer, 32 filters of 3 × 7 × 7 | 4,736 parameters |
pythonimport numpy as np def affine_backward(dout, cache): x, w, b = cache dx = (dout @ w.T).reshape(x.shape) dw = x.reshape(x.shape[0], -1).T @ dout db = dout.sum(axis=0) # reverse of the bias copy return dx, dw, db def softmax_loss(s, y): p = np.exp(s - s.max(axis=1, keepdims=True)) p /= p.sum(axis=1, keepdims=True) N = s.shape[0] loss = -np.log(p[np.arange(N), y]).mean() ds = p.copy(); ds[np.arange(N), y] -= 1 return loss, ds / N # keep the / N def batchnorm_backward(dout, cache): xh, gamma, sd = cache N = dout.shape[0] dxh = dout * gamma dx = (N * dxh - dxh.sum(0) - xh * (dxh * xh).sum(0)) / (N * sd) return dx, (dout * xh).sum(0), dout.sum(0) # dx, dgamma, dbeta def grad_check(f, x, analytic, h=1e-5): num = np.zeros_like(x) for i in np.ndindex(x.shape): old = x[i] x[i] = old + h; fp = f() x[i] = old - h; fm = f() x[i] = old num[i] = (fp - fm) / (2 * h) return np.max(np.abs(num - analytic) / np.maximum(1e-8, np.abs(num) + np.abs(analytic)))
The next assignment is CS231n A3: sequences. For the pieces in more depth, read Backpropagation, Optimizers, Normalization, Dropout variants, Convolutional networks and Loss functions. Where ConvNets went next: the Vision Transformer and the Transformer.
Now press Present or Teach and explain from memory: the layer contract, the db sum, the softmax gradient, the batch-norm coupling and the conv scatter. Then open the Build studio and write all nine kernels. Or go back to the hero, break each layer, and say why the check fails.
This page is a practice companion for Assignment 2 of Stanford CS231n, Deep Learning for Computer Vision. The course site is cs231n.stanford.edu and the notes are at cs231n.github.io. The function names follow the assignment. The explanations, toy numbers, devices and Code Labs are our own and run at browser scale.