The earlier lessons of this course each built one piece: backpropagation, mini-batches, Adam. Here they run together for the first time, joined by what makes a run trustworthy: a starting point that can train, an L2 penalty, a held-out set and a checkpoint. This capstone pairs with Lab 1 and Lab 2 of CMU's 11-785 (Fall 2026), the course's recorded lab sessions on a first MLP in code and on debugging a model, linked under Watch & read. You build init_mlp, forward, loss_and_grads, evaluate and train, and the tests compare every update with PyTorch.
Start with the weights, because they decide whether training can begin. Set every weight and bias to zero and every hidden unit computes the same value, 0. The output weights then see all-zero inputs, so their gradient is zero, and they pass no error down. Only the last bias moves, so the network can learn nothing beyond how often each class occurs.
import numpy as np
x = np.array([[1.0, -1.0], [0.5, 2.0], [-1.0, 0.0]])
y = np.array([0, 1, 1])
W1, W2 = np.zeros((4, 2)), np.zeros((2, 4))
a = np.maximum(x @ W1.T, 0) # the hidden activations
delta = np.full((3, 2), 0.5) # zero logits: every probability is 1/2
delta[np.arange(3), y] -= 1
delta /= 3 # (p - y) / N
print(a.any(), (delta.T @ a).any(), (delta @ W2).any())
print(delta.sum(axis=0).round(3).tolist()) # db of the last layerThe three False values say that no hidden unit is active, the output weights get no gradient and no error reaches the hidden layer. The last line is the gradient of the last bias, the only one that is not zero.
Weights that are too large fail the other way. In a ReLU layer about half of the units are on, so a layer multiplies the size of its signal by σ·√(fan_in / 2), where σ is the weight standard deviation. He initialisation sets σ = √(2 / fan_in), which makes that factor 1; init_mlp scales standard normal draws by it and sets biases to zero. The snippet sends 2000 random inputs through 8 layers of width 100, with weights at half, exactly and twice that scale, and prints each layer's pre-activation standard deviation.
import numpy as np
x = np.random.default_rng(0).standard_normal((2000, 100))
for scale in (0.5, 1.0, 2.0): # multiples of He's sqrt(2 / fan_in)
rng, a, stds = np.random.default_rng(1), x, []
for _ in range(8):
z = a @ (rng.standard_normal((100, 100)) * np.sqrt(2 / 100) * scale)
stds.append(round(float(z.std()), 3))
a = np.maximum(z, 0)
print(scale, stds)At half the scale the signal shrinks by about 2 per layer; at twice the scale it grows by about 2 per layer, to 277. With He's scale it stays between 1.08 and 1.41.
Make three checks before you trust a run, each isolating a different fault.
- The loss before any update sits near log C when the output weights are small. On the three-class spiral data of the tests, He initialisation starts between 1.07 and 1.35 over eight seeds, against log 3 = 1.099, because its logits are not tiny; scaling the output layer by 0.01 gives 1.096 to 1.100. A start of 9 on ten classes means the logits are far apart.
- The gradient, compared with finite differences or autograd. A falling loss is weak evidence: a gradient with a missing term can still point downhill.
- A handful of examples. Twelve points should reach a loss near zero; in the tests a [2, 16, 16, 3] network gets below 0.01 within 200 full-batch epochs. If yours cannot, look for a bug before tuning anything.
One epoch is one pass over a fresh permutation of the N examples, cut into consecutive slices of batch_size. The last slice may be shorter: with N = 50 and a batch size of 16 the slices hold 16, 16, 16 and 2 rows, so an epoch makes four updates. Adam's step counter t counts every update of the whole run and is never reset, since the bias corrections 1 - β₁ᵗ and 1 - β₂ᵗ depend on it.
Weight decay is an L2 penalty: ½λ times the sum of every squared weight, biases excluded, is added to the loss. Its derivative adds λW to the gradient of each weight matrix and nothing to the biases.
import numpy as np
W, lam = np.array([[3.0, -4.0]]), 0.01
print(round(0.5 * lam * float((W ** 2).sum()), 4)) # added to the loss
print((lam * W).round(4).tolist()) # added to dWThis is the update torch.optim.Adam(weight_decay=λ) makes, with one parameter group for the weights and one without decay for the biases; the tests use it as the oracle. AdamW applies the decay outside the adaptive step, a different update that is not built here. evaluate leaves the penalty out, so training and validation losses stay comparable.
Training loss can keep falling while the loss on held-out data turns upward. The curves below come from the reference solution on a noisy problem: 40 training points in two overlapping clusters, a quarter of the labels flipped, a [2, 64, 64, 2] network, learning rate 0.003, batches of 8, and 200 held-out points with their true labels. Validation loss is lowest at epoch 4: 0.437, with accuracy 0.805. By epoch 200 the training loss is 0.115 and training accuracy 0.975, but validation loss is 1.126 and accuracy 0.635. The network has memorised the flipped labels, so train returns the parameters of the epoch with the lowest validation loss (the earliest on a tie), not the last ones.
train returns.Two slips are worth knowing; the bug hunts use both. The first is keeping the best weights by reference. Updates are in place, so list(params) copies the list and not the arrays: later steps overwrite the saved weights, and train returns the last ones. Copy every array. The second is a penalty that is added to the loss but not to the gradient. The loss looks right and falls, yet the decay never happens; autograd or finite differences expose it.
The loss and every gradient agree with autograd for one to three hidden layers, with and without a penalty, and the whole run agrees with PyTorch's Adam after every epoch, to rounding error. That establishes the arithmetic, not that the model generalises. The data is tiny and two-dimensional, and choosing the epoch by validation loss makes that loss a little optimistic, so a real project keeps a third set for the final number. Real training adds data loading, learning-rate schedules, normalization layers and a GPU.