TExcelTAD
Home › Deep Learning: Neural Networks, Architectures & PyTorch › Backpropagation, Layer by Layer

Backpropagation, Layer by Layer

In the training-loop course you wrote backpropagation for one fixed network: a single backward function that knew every layer by name. That does not scale. Add a layer and the whole function has to be rewritten; swap ReLU for tanh and you edit lines in the middle. Frameworks solve this by making every layer a module that knows only its own local rule, and letting a container call those rules in reverse order.

This lesson builds that design in about 50 lines of NumPy: classes Linear, ReLU, SoftmaxCrossEntropy and Sequential, each with a forward that caches what it will need and a backward(grad) that returns the gradient for its input and stores the gradients of its parameters. It is the same contract as PyTorch's torch.autograd.Function and close to how early frameworks (Torch7, Caffe) worked. The chain-rule derivation for an MLP is in backpropagation in an MLP; here you turn it into reusable code.

The module contract

Each module sees only two things during the backward pass: what it cached in the forward pass, and G=∂L/∂YG = \partial L / \partial Y, the gradient of the loss with respect to its own output. From those it must produce ∂L/∂X\partial L / \partial X for the module before it. That is the chain rule applied once per module, and it is why the modules can be chained in any order.

X Linear 1 ReLU Linear 2 Softmax CE loss X Z1 A1 Z2 L caches X stores dW1, db1 caches mask caches A1 stores dW2, db2 caches P, y dX dZ1 dA1 dZ2 1 forward: each module computes its output and caches what backward needs backward: each module turns dL/d(output) into dL/d(input) and stores its parameter gradients

For a linear layer Y=XW+bY = XW + b with X∈Rn×dX \in \mathbb{R}^{n \times d}, W∈Rd×hW \in \mathbb{R}^{d \times h} and G∈Rn×hG \in \mathbb{R}^{n \times h}:

∂L∂W=X⊤G,∂L∂b=∑i=1nGi,:,∂L∂X=GW⊤\frac{\partial L}{\partial W} = X^\top G, \qquad \frac{\partial L}{\partial b} = \sum_{i=1}^{n} G_{i,:}, \qquad \frac{\partial L}{\partial X} = G W^\top

Each formula can be checked by shapes alone: X⊤GX^\top G is (d,n)(n,h)=(d,h)(d, n)(n, h) = (d, h), the shape of WW; the bias gradient sums over the batch because the same bias was added to every row; GW⊤G W^\top is (n,h)(h,d)=(n,d)(n, h)(h, d) = (n, d), the shape of XX. Note what each needs from the forward pass: ∂L/∂W\partial L / \partial W needs the cached input XX, ∂L/∂X\partial L / \partial X needs only the weights.

For ReLU, Y=max⁡(X,0)Y = \max(X, 0) elementwise, so the gradient passes where the input was positive and stops elsewhere:

∂L∂X=G⊙1[X>0]\frac{\partial L}{\partial X} = G \odot \mathbb{1}[X > 0]

The forward pass caches the mask. For softmax with cross-entropy, fused into one module as in the previous lesson, the loss is the end of the chain, so its backward takes no argument and returns (P−Y)/n(P - Y)/n.

The layer API in NumPy

The four classes, a forward and a backward pass through a small 4-6-3 network, and a gradient check that nudges every parameter and every input by ±10−6\pm 10^{-6} and compares the central difference with the analytic gradient (the method of gradient checking):

python · try it yourself
import numpy as np

class Linear:
    def __init__(self, d_in, d_out, rng):
        self.W = rng.normal(0, np.sqrt(2 / d_in), (d_in, d_out))   # He init
        self.b = np.zeros(d_out)
    def forward(self, X):
        self.X = X                                  # cache the input for backward
        return X @ self.W + self.b
    def backward(self, G):                          # G = dL/dY, shape (n, d_out)
        self.dW = self.X.T @ G                      # (d_in, d_out)
        self.db = G.sum(axis=0)                     # (d_out,)
        return G @ self.W.T                         # dL/dX, shape (n, d_in)
    def params(self):
        return [(self.W, self.dW), (self.b, self.db)]

class ReLU:
    def forward(self, X):
        self.mask = X > 0
        return X * self.mask
    def backward(self, G):
        return G * self.mask
    def params(self):
        return []

class SoftmaxCrossEntropy:                          # fused: logits in, mean loss out
    def forward(self, Z, y):
        Z = Z - Z.max(axis=1, keepdims=True)
        self.P = np.exp(Z) / np.exp(Z).sum(axis=1, keepdims=True)
        self.y = y
        return float(-np.log(self.P[np.arange(len(y)), y]).mean())
    def backward(self):
        G = self.P.copy()
        G[np.arange(len(self.y)), self.y] -= 1
        return G / len(self.y)

class Sequential:
    def __init__(self, *layers):
        self.layers = layers
    def forward(self, X):
        for layer in self.layers:
            X = layer.forward(X)
        return X
    def backward(self, G):
        for layer in reversed(self.layers):
            G = layer.backward(G)
        return G
    def params(self):
        return [pg for layer in self.layers for pg in layer.params()]

# one forward and one backward pass on a tiny problem
rng = np.random.default_rng(0)
net = Sequential(Linear(4, 6, rng), ReLU(), Linear(6, 3, rng))
loss_fn = SoftmaxCrossEntropy()
X = rng.normal(size=(5, 4)); y = np.array([0, 2, 1, 1, 0])
loss = loss_fn.forward(net.forward(X), y)
dX = net.backward(loss_fn.backward())
print("loss", round(loss, 4), "  shapes:", [g.shape for _, g in net.params()], " dX", dX.shape)

# gradient check: nudge every parameter (and every input) and compare
def numeric(arr, h=1e-6):
    g = np.zeros_like(arr)
    for idx in np.ndindex(arr.shape):
        old = arr[idx]
        arr[idx] = old + h; up = loss_fn.forward(net.forward(X), y)
        arr[idx] = old - h; down = loss_fn.forward(net.forward(X), y)
        arr[idx] = old
        g[idx] = (up - down) / (2 * h)
    return g

names = ["W1", "b1", "W2", "b2"]
for name, (p, g) in zip(names, net.params()):
    n = numeric(p)
    rel = np.abs(g - n).max() / max(np.abs(g).max(), 1e-12)
    print(f"{name}: largest gradient {np.abs(g).max():.4f}, relative error < 1e-7: {bool(rel < 1e-7)}")
n = numeric(X)
print("dX: relative error < 1e-7:", bool(np.abs(dX - n).max() / np.abs(dX).max() < 1e-7))
loss 1.1618   shapes: [(4, 6), (6,), (6, 3), (3,)]  dX (5, 4)
W1: largest gradient 0.4659, relative error < 1e-7: True
b1: largest gradient 0.1373, relative error < 1e-7: True
W2: largest gradient 0.2647, relative error < 1e-7: True
b2: largest gradient 0.2828, relative error < 1e-7: True
dX: relative error < 1e-7: True

Sequential.backward is four lines: it walks the layers in reverse and hands each one the gradient returned by the next. The four parameter gradients have exactly the shapes of their parameters, (4,6)(4, 6), (6,)(6,), (6,3)(6, 3) and (3,)(3,), and all of them, as well as the input gradient dX, agree with the numerical derivatives to a relative error below 10−710^{-7}. The input gradient is not needed for training this network, but it is what lets modules be stacked: for Linear 1, dX is what a module in front of it would receive.

Training with it

params() returns pairs of (parameter, gradient) arrays, so an SGD step is one loop that updates the arrays in place. Here is a 64-64-10 ReLU network on the course's Digits split (1077 training, 360 validation images, pixels scaled to [0,1][0, 1]), He-initialised, batch size 32, learning rate 0.1, 20 epochs. Model choices are judged on validation; the test set is kept for the end of the lesson after next.

python · try it yourself
import numpy as np

class Linear:
    def __init__(self, d_in, d_out, rng):
        self.W = rng.normal(0, np.sqrt(2 / d_in), (d_in, d_out))   # He init
        self.b = np.zeros(d_out)
    def forward(self, X):
        self.X = X                                  # cache the input for backward
        return X @ self.W + self.b
    def backward(self, G):                          # G = dL/dY, shape (n, d_out)
        self.dW = self.X.T @ G                      # (d_in, d_out)
        self.db = G.sum(axis=0)                     # (d_out,)
        return G @ self.W.T                         # dL/dX, shape (n, d_in)
    def params(self):
        return [(self.W, self.dW), (self.b, self.db)]

class ReLU:
    def forward(self, X):
        self.mask = X > 0
        return X * self.mask
    def backward(self, G):
        return G * self.mask
    def params(self):
        return []

class SoftmaxCrossEntropy:                          # fused: logits in, mean loss out
    def forward(self, Z, y):
        Z = Z - Z.max(axis=1, keepdims=True)
        self.P = np.exp(Z) / np.exp(Z).sum(axis=1, keepdims=True)
        self.y = y
        return float(-np.log(self.P[np.arange(len(y)), y]).mean())
    def backward(self):
        G = self.P.copy()
        G[np.arange(len(self.y)), self.y] -= 1
        return G / len(self.y)

class Sequential:
    def __init__(self, *layers):
        self.layers = layers
    def forward(self, X):
        for layer in self.layers:
            X = layer.forward(X)
        return X
    def backward(self, G):
        for layer in reversed(self.layers):
            G = layer.backward(G)
        return G
    def params(self):
        return [pg for layer in self.layers for pg in layer.params()]

from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)

rng = np.random.default_rng(0)
net = Sequential(Linear(64, 64, rng), ReLU(), Linear(64, 10, rng))
loss_fn = SoftmaxCrossEntropy()
lr, batch = 0.1, 32
for epoch in range(1, 21):
    order = rng.permutation(len(y_tr))
    for s in range(0, len(order), batch):
        idx = order[s:s + batch]
        loss_fn.forward(net.forward(X_tr[idx]), y_tr[idx])
        net.backward(loss_fn.backward())
        for p, g in net.params():
            p -= lr * g                              # in-place SGD step
    if epoch in (1, 5, 10, 20):
        tr = loss_fn.forward(net.forward(X_tr), y_tr)
        va = loss_fn.forward(net.forward(X_va), y_va)
        acc = (net.forward(X_va).argmax(1) == y_va).mean()
        print(f"epoch {epoch:2d}  train loss {tr:.4f}  val loss {va:.4f}  val acc {acc:.3f}")
epoch  1  train loss 1.3564  val loss 1.3616  val acc 0.756
epoch  5  train loss 0.3381  val loss 0.3610  val acc 0.925
epoch 10  train loss 0.1805  val loss 0.2117  val acc 0.947
epoch 20  train loss 0.1038  val loss 0.1516  val acc 0.964

After one epoch the validation accuracy is 0.756; after 20 it is 0.964 with a validation loss of 0.1516. Nothing in the loop knows that there are two linear layers. Insert another Linear and ReLU into the Sequential and the same loop trains the deeper network. Keep these numbers in mind: two lessons from now the same model is trained by an autograd engine and then by PyTorch, and the losses come out the same.

Checked against PyTorch autograd

PyTorch has no hand-written backward for your network: autograd records the operations of the forward pass and applies each operation's local rule in reverse, the same contract as above at the level of single operations. With identical float64 weights (copied as W.T, since PyTorch stores out by in) and the first training batch, all gradients should agree. A recorded example:

python · try it yourself
import numpy as np

class Linear:
    def __init__(self, d_in, d_out, rng):
        self.W = rng.normal(0, np.sqrt(2 / d_in), (d_in, d_out))   # He init
        self.b = np.zeros(d_out)
    def forward(self, X):
        self.X = X                                  # cache the input for backward
        return X @ self.W + self.b
    def backward(self, G):                          # G = dL/dY, shape (n, d_out)
        self.dW = self.X.T @ G                      # (d_in, d_out)
        self.db = G.sum(axis=0)                     # (d_out,)
        return G @ self.W.T                         # dL/dX, shape (n, d_in)
    def params(self):
        return [(self.W, self.dW), (self.b, self.db)]

class ReLU:
    def forward(self, X):
        self.mask = X > 0
        return X * self.mask
    def backward(self, G):
        return G * self.mask
    def params(self):
        return []

class SoftmaxCrossEntropy:                          # fused: logits in, mean loss out
    def forward(self, Z, y):
        Z = Z - Z.max(axis=1, keepdims=True)
        self.P = np.exp(Z) / np.exp(Z).sum(axis=1, keepdims=True)
        self.y = y
        return float(-np.log(self.P[np.arange(len(y)), y]).mean())
    def backward(self):
        G = self.P.copy()
        G[np.arange(len(self.y)), self.y] -= 1
        return G / len(self.y)

class Sequential:
    def __init__(self, *layers):
        self.layers = layers
    def forward(self, X):
        for layer in self.layers:
            X = layer.forward(X)
        return X
    def backward(self, G):
        for layer in reversed(self.layers):
            G = layer.backward(G)
        return G
    def params(self):
        return [pg for layer in self.layers for pg in layer.params()]
import torch
from torch import nn
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)

rng = np.random.default_rng(0)
net = Sequential(Linear(64, 64, rng), ReLU(), Linear(64, 10, rng))
loss_fn = SoftmaxCrossEntropy()
idx = rng.permutation(len(y_tr))[:32]                    # the first training batch
xb, yb = X_tr[idx], y_tr[idx]
loss_np = loss_fn.forward(net.forward(xb), yb)
dX_np = net.backward(loss_fn.backward())

model = nn.Sequential(nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 10)).double()
with torch.no_grad():                                    # same weights; PyTorch stores W.T
    for t_lin, np_lin in [(model[0], net.layers[0]), (model[2], net.layers[2])]:
        t_lin.weight.copy_(torch.tensor(np_lin.W.T)); t_lin.bias.copy_(torch.tensor(np_lin.b))
xt = torch.tensor(xb, requires_grad=True)
loss_t = nn.functional.cross_entropy(model(xt), torch.tensor(yb))
loss_t.backward()

print("loss numpy", round(loss_np, 6), " torch", round(loss_t.item(), 6))
pairs = [("W1", net.layers[0].dW, model[0].weight.grad.T), ("b1", net.layers[0].db, model[0].bias.grad),
         ("W2", net.layers[2].dW, model[2].weight.grad.T), ("b2", net.layers[2].db, model[2].bias.grad),
         ("dX", dX_np, xt.grad)]
for name, g_np, g_t in pairs:
    print(f"{name}: shape {str(g_np.shape):8s} max |numpy - torch| < 1e-12: {bool(np.abs(g_np - g_t.numpy()).max() < 1e-12)}")
print("db2[:4] numpy", np.round(net.layers[2].db[:4], 5).tolist(), " torch", np.round(model[2].bias.grad[:4].numpy(), 5).tolist())
loss numpy 2.467399  torch 2.467399
W1: shape (64, 64) max |numpy - torch| < 1e-12: True
b1: shape (64,)    max |numpy - torch| < 1e-12: True
W2: shape (64, 10) max |numpy - torch| < 1e-12: True
b2: shape (10,)    max |numpy - torch| < 1e-12: True
dX: shape (32, 64) max |numpy - torch| < 1e-12: True
db2[:4] numpy [-0.07434, -0.12068, -0.05475, 0.00067]  torch [-0.07434, -0.12068, -0.05475, 0.00067]

The loss is 2.467399 in both, and every gradient, including the (32,64)(32, 64) gradient with respect to the input batch, agrees to better than 10−1210^{-12}. The first four bias gradients of the output layer are −0.07434,−0.12068,−0.05475,0.00067-0.07434, -0.12068, -0.05475, 0.00067 in both. PyTorch's weight.grad is the transpose of the NumPy dW, just like the weight itself.

Pitfalls

  • Caching by reference and then modifying. self.X = X stores a reference. If a later module changes its input in place (an in-place ReLU, X *= mask), the cached array changes too and the weight gradient is wrong. Either never modify inputs in place or cache a copy; PyTorch detects this case with version counters and raises an error.
  • Forgetting to sum the bias gradient over the batch. self.db = G has shape (n, h). The in-place update b -= lr * db then fails with a broadcasting error, and the out-of-place b = b - lr * db silently turns the bias into a matrix. Check every gradient shape against its parameter.
  • Dividing by nn twice, or not at all. The mean over the batch belongs in exactly one place, here the loss module. If the loss returns a sum, the effective learning rate grows with the batch size.
  • Calling backward without a matching forward. The caches belong to the last forward pass. Evaluating the validation set between a training forward and its backward overwrites them; finish the training step first.
  • Gradient checks in float32 or with ReLU kinks. Central differences need float64 and a step that does not cross x=0x = 0 of a ReLU; a few mismatched entries next to the kink are expected and not a bug.

Practice

  1. Write a Tanh module for this API.
Answer
python
class Tanh:
    def forward(self, X):
        self.Y = np.tanh(X)
        return self.Y
    def backward(self, G):
        return G * (1 - self.Y ** 2)
    def params(self):
        return []

Caching the output rather than the input is enough, because tanh⁡′(x)=1−tanh⁡2x\tanh'(x) = 1 - \tanh^2 x.

  1. Why does Linear.backward compute G @ self.W.T with the weights from before the update, and what would go wrong if the SGD step ran inside backward?
Answer

The chain rule needs the weights that produced the forward pass. If a layer updated WW before returning GW⊤G W^\top, the earlier layers would receive gradients for a different network. Computing all gradients first and then updating, as Sequential.backward followed by the SGD loop does, keeps them consistent; PyTorch enforces the same order with loss.backward() before optimizer.step().

  1. Add an MSE loss module with forward(Y_hat, Y) and backward() for regression.
Answer
python
class MSE:
    def forward(self, Y_hat, Y):
        self.diff = Y_hat - Y
        return float((self.diff ** 2).mean())
    def backward(self):
        return 2 * self.diff / self.diff.size

With .mean() over all entries, the divisor is the number of entries, nkn k for kk outputs.

  1. In the gradient check the input gradient dX was checked too. Name a real use of the gradient with respect to the input of a trained network.
Answer

Saliency maps (which pixels change the prediction most), adversarial examples (step the input along the sign of the gradient), and the gradient penalty in some GAN losses. All of them call the same backward and read the gradient of the first module's input instead of the parameters.

Test yourself

For Y=XW+bY = XW + b with upstream gradient GG, what is ∂L/∂W\partial L / \partial W?

  1. GW⊤G W^\top
  2. X⊤GX^\top G
  3. GX⊤G X^\top
  4. W⊤GW^\top G

What does the ReLU module need to cache in its forward pass?

  1. Nothing
  2. Where its input was positive (the mask)
  3. The weights of the next layer
  4. The loss value

Why does every module's backward return the gradient with respect to its input?

  1. To update the input data
  2. So that the module before it can continue the chain rule
  3. Because the optimizer needs it
  4. To check for overflow

How is the bias gradient of a linear layer computed from GG of shape (n,h)(n, h)?

  1. GG itself
  2. The mean of GG over the outputs
  3. The sum of GG over the batch axis, shape (h,)(h,)
  4. G⊤GG^\top G