Assignment 2: Build the Layers

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.

Check a layer's gradient

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

The Tangle

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.

Add hidden units and retrain

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.

0

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.

The trap

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 road

  1. The layer contract: forward, cache, backward, and the chain rule.
  2. Affine and ReLU: the two layers of a fully connected net.
  3. Softmax loss: where the gradient starts.
  4. Optimizers: momentum, RMSProp, Adam.
  5. Batch norm: normalize over the batch, and the coupled backward.
  6. Layer norm and dropout: normalize per example, and drop units.
  7. Convolution: one filter slid over the image.
  8. Pooling and spatial batch norm: shrink the map, normalize per channel.
  9. A ConvNet learns: every layer together, and what one bug does.
  10. Field guide: symptoms, the card of formulas, links.

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.

Why does Assignment 2 build a network from small layers, each with a forward and a backward function?

Chapter 1

The Layer Contract

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.

Say it aloud

d-x equals d-out times the partial of out with respect to x.

dx
d-x how much the loss L moves per unit change of the input x. The layer hands it to the layer below.
dout
d-out how much L moves per unit change of the output. It arrives from the layer above.
∂out / ∂x
the partial of out with respect to x the local slope: how much out moves per unit change of x, with everything else held still.
In plain words

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 numbers

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.

Step the chain forward, then back

Press Step. Teal values flow right through the boxes, then warm gradients flow left. Drag x below 0.67 and watch the ReLU close.

2.0

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 failure, as symptom, measurement and fix

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.

A layer gets dout = 4 and its local slope at the current input is 0.25. What dx does it pass down?

Chapter 2

Affine and ReLU

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.

Say it aloud

Out equals x times w, plus b.

out
out the scores, shape (N, M): one row per example.
x
x the inputs, flattened to shape (N, D). x.reshape(N, -1) flattens an image batch.
w
w the weights, shape (D, M): one column per output.
b
b the bias, shape (M,). numpy adds the same b to every row.
In plain words

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 numbers

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.

GradientCodeWhyWith 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]]
dwx_flat.T @ doutWeight w[d, m] met x[:, d] in every example, so add over the batch.[[5, 5], [7, 7], [9, 9]]
dbdout.sum(axis=0)numpy copied b to every row. The reverse of a copy is a sum.[2, 2]

Collapse dout into db

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.

3

Illustrative dout values from a fixed seed, M = 2 outputs.

ReLU: a gate

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).

In affine_backward, why is db = dout.sum(axis=0) and not dout?

Chapter 3

Softmax Loss: Where the Gradient Starts

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.

Say it aloud

L equals minus one over N, times the sum over i of the log of P-i-y-i.

L
L the cross-entropy loss of the batch. 0 is perfect.
1/N
one over N the average over the N examples of the batch.
Σi
the sum over i add one term for each example.
Pi, yi
P-i-y-i the probability the net gave to the true class of example i.
In plain words

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 numbers

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].

Say it aloud

d-s-i-c equals P-i-c minus one-if-c-is-y-i, all over N.

dsi,c
d-s-i-c how much L moves when score c of example i moves.
Pi,c
P-i-c the softmax probability of class c for example i.
1[c = yi]
one if c is y-i 1 at the true class, 0 at every other class.
N
N the batch size, from the average in L.
In plain words

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.

With numbers

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.

Raise the true-class score

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.

2.0

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.

The net gives the true class P = 0.7 in a batch of N = 10. What is ds at the true class?

Chapter 4

Optimizers: Turning a Gradient into a Step

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.

Race four optimizers

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.

Say it aloud

v becomes mu times v, minus l-r times d-w.

v
v the new velocity. Then w ← w + v.
μ
mu how much of the old velocity survives each step, here 0.9.
v
v the velocity from the last step. It starts at 0.
lr
l-r the learning rate.
dw
d-w the gradient of the loss for this weight.
In plain words

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 numbers

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.

Say it aloud

m-hat equals m divided by one minus beta-one to the t.

m̂
m-hat the corrected average of the gradient.
m
m the running average: m ← β1m + (1 − β1)dw, starting at 0.
β1t
beta-one to the t 0.9 multiplied by itself t times. It falls toward 0 as steps pass.
In plain words

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 numbers

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.

With μ = 0.9 and a constant gradient, how much faster does momentum move than plain SGD with the same lr, once it settles?

Chapter 5

Batch Normalization

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 β.

Say it aloud

Out equals gamma times x minus mu, over the square root of sigma squared plus epsilon, plus beta.

out
out the normalized, rescaled feature.
γ
gamma a learned scale, one per feature, starting at 1.
x
x one example's value of the feature.
μ
mu the mean of the feature over the batch.
√(σ² + ε)
root of sigma squared plus epsilon the spread of the feature; ε (epsilon, about 0.00001) stops a divide by zero.
β
beta a learned shift, one per feature, starting at 0.
In plain words

Subtract the batch mean μ from x and divide by the spread. Call that x̂ (x-hat). Multiply by γ and add β.

With numbers

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].

Normalize a batch, then test on one

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.

2.0
1.0

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.

The coupled backward pass

μ and σ² depend on every example, so nudging one input moves every output. Call the gradient at x̂ dx̂ = dout × γ, and the batch size N.

Say it aloud

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.

dx
d-x the gradient for each input of the batch.
N
N the batch size.
dx̂
d-x-hat dout times γ: the gradient at the normalized value.
Σdx̂
the sum of d-x-hat over the batch. This term pays for moving the mean.
x̂
x-hat this input after normalizing.
Σ(dx̂·x̂)
the sum of d-x-hat times x-hat over the batch. This term pays for moving the variance.
√(σ²+ε)
the spread from the forward pass, read from the cache.
In plain words

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.

With numbers

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.

A batch-norm layer in test mode sees one example and normalizes it with that one example's own mean and variance. What does it output?

Chapter 6

Layer Norm and Dropout

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.

LayerMean and variance overNeeds running statsThe axis bug
Batch normthe batch, one pair per feature (axis=0)yesnormalize over features: that is layer norm
Layer normthe features, one pair per example (axis=1)nonormalize 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

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.

Say it aloud

Out equals x times m, divided by p.

out
out the training output. At test time, out = x.
x
x the activations coming in.
m
m the mask: np.random.rand(*x.shape) < p, kept in the cache.
p
p the keep probability, from 0 to 1.
In plain words

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 numbers

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.

Drop units, keep the mean

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.

0.50

Your browser draws the masks live with Math.random; the running mean averages every output since the last change.

Why does inverted dropout divide the kept units by p during training?

Chapter 7

Convolution

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.

Slide the filter

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.

0

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.

Say it aloud

H-prime equals H plus two P minus H-H, over S, plus one.

H′
H-prime the output height. Width works the same way.
H
H the input height in pixels.
P
P the padding on each side, so the padded height is H + 2P.
HH
H-H the filter height.
S
S the stride.
In plain words

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.

With numbers

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.

Backward: scatter, and add

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.

A 5 × 5 input, a 3 × 3 filter, padding 1, stride 2. What is the output height?

Chapter 8

Max Pooling and Spatial Batch Norm

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.

Pool forward, route backward

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.

Spatial batch norm

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.

  1. Start from x with shape (N, C, H, W).
  2. Move the channels last: x.transpose(0, 2, 3, 1) gives (N, H, W, C).
  3. Flatten the rest: .reshape(-1, C) gives (N·H·W, C).
  4. Run batchnorm_forward: each of the C columns gets its own mean and variance.
  5. Undo the reshape and the transpose.

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.

In max pool backward, where does a window's dout go?

Chapter 9

A ConvNet Learns, Until One Layer Lies

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.

Train it, then break one layer

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.

BugLoss after 200 stepsTest accuracyWhat happened
None0.01394%Learns.
Conv dw overwrites0.6381%dw keeps one position of one image, so the filters barely learn and the loss stalls.
Softmax drops / N8.550%Every gradient is 32 times too big, the steps overshoot, and the loss climbs.
ReLU passes all0.09088%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.

Training is slow but the loss does fall. Which test tells you whether a backward pass is wrong?

Chapter 10

Field Guide

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.

SymptomLikely causeFix
Gradient check fails on one layera missing sum, transpose or coupling term in its backwardtrust the check; re-derive that layer's local slope
Loss and gradients N times too bigsoftmax sums instead of averagingdivide the loss and the score gradient by N
Shape error in affine backwarddb not summed over the batchdb = dout.sum(axis=0)
Many ReLU units never firedead ReLUs, often from a learning rate that is too highlower lr, better initialization
Loss spikes in the first Adam stepsno bias correctiondivide m by 1 − β1t and v by 1 − β2t
Good train accuracy, test output stuck at βbatch norm uses batch stats at testtest mode uses running stats only
Train and test activations differ by a factor pdropout without / p, or dropout left on at testdivide by p in training; identity at test
Conv check fails only when patches overlap= instead of += in the scatteraccumulate into dx and dw
Spatial batch norm has one mean for all channelswrong axes in the reshapetranspose C last, reshape to (N·H·W, C)

The numbers from this page

QuantityValue
Nudge in a central difference0.00001
Relative error of a correct layerabout 1e−9 or smaller
Relative error of a buggy layer0.5 to 1
Momentum speed-up at μ = 0.910 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 × 74,736 parameters

The core, as code

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)))

A checklist for each new layer

  1. Write the forward pass and print the output shape.
  2. Cache every value the backward formula reads.
  3. Write the backward pass; assert each gradient has its input's shape.
  4. Run a gradient check on small random inputs. Expect 1e−7 or smaller.
  5. If the layer has a mode (batch norm, dropout), test both modes.

Keep going

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.

The one idea. A wrong backward pass never crashes. Build small layers, check each one against measured slopes, and the network takes care of itself.
Why does Assignment 2 ask you to gradient-check every layer you write?

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.

Credit and source

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.

CS231n Assignment 2: Build the Layers
The course site · Course notes · Back to Gleams