TExcelTAD
Home › Deep Learning: Neural Networks, Architectures & PyTorch › A CNN in NumPy, then in PyTorch

A CNN in NumPy, then in PyTorch

The previous two lessons built the parts: a convolution as one matrix product (im2col), pooling, and the shape arithmetic. This lesson assembles them into a complete convolutional network for the Digits images, writes its backward pass by hand, checks every gradient numerically, and trains it in the browser. Then the same network is built in PyTorch, trained longer, and compared honestly with an MLP of the same size. The comparison holds a surprise worth understanding.

The derivation of the convolution's gradients is in backpropagation through convolutions, and the softmax-cross-entropy gradient in its own lesson. Here the job is to turn them into code that is correct.

The network

digit1 x 8 x 8 conv 3x38 x 8 x 880 params ReLU, pool 28 x 4 x 4 linear128 to 101290 params softmax CEloss L D = p - onehotdW2 = h^T Dto max, Z > 0dW1 = dZ cols^T

One convolution with 8 filters of 3 ×\times 3 and zero padding 1 keeps the 8 ×\times 8 size, ReLU, a 2 ×\times 2 max pool, and a linear layer from the 128 pooled values to 10 logits: 8⋅9+8=808 \cdot 9 + 8 = 80 convolution parameters and 128⋅10+10=1290128 \cdot 10 + 10 = 1290 in the head, 1370 in total. Small enough to train in seconds in the browser, big enough to show what a convolution buys.

Forward and backward

The forward pass, for a batch of NN images turned into patch columns XcolX_\text{col} of shape (N,9,64)(N, 9, 64):

Z=W1Xcol+b1(N,8,64), the convolutionA=max⁡(Z,0)ReLUh=maxpool⁡2×2(A)(N,8,4,4)→(N,128)s=hW2+b2,L=−1N∑nlog⁡softmax⁡(sn)ynhead and loss\begin{aligned} Z &= W_1 X_\text{col} + b_1 && (N, 8, 64),\ \text{the convolution} \\ A &= \max(Z, 0) && \text{ReLU} \\ h &= \operatorname{maxpool}_{2 \times 2}(A) && (N, 8, 4, 4) \to (N, 128) \\ s &= h W_2 + b_2, \quad L = -\frac{1}{N} \sum_n \log \operatorname{softmax}(s_n)_{y_n} && \text{head and loss} \end{aligned}

The backward pass runs the same steps in reverse. With D=∂L/∂s=(p−onehot(y))/ND = \partial L / \partial s = (p - \text{onehot}(y))/N:

∂L∂W2=h⊤D,∂L∂b2=∑nDn,∂L∂h=DW2⊤∂L∂A=the gradient of h placed at each window’s maximum, 0 elsewhere∂L∂Z=∂L∂A⊙[Z>0]∂L∂W1=∑n∂L∂ZnXcol,n⊤,∂L∂b1=∑n, p∂L∂Zn,:,p\begin{aligned} \frac{\partial L}{\partial W_2} &= h^\top D, \qquad \frac{\partial L}{\partial b_2} = \textstyle\sum_n D_n, \qquad \frac{\partial L}{\partial h} = D W_2^\top \\ \frac{\partial L}{\partial A} &= \text{the gradient of } h \text{ placed at each window's maximum, 0 elsewhere} \\ \frac{\partial L}{\partial Z} &= \frac{\partial L}{\partial A} \odot [Z > 0] \\ \frac{\partial L}{\partial W_1} &= \sum_n \frac{\partial L}{\partial Z_n} X_{\text{col},n}^\top, \qquad \frac{\partial L}{\partial b_1} = \sum_{n,\,p} \frac{\partial L}{\partial Z_{n,:,p}} \end{aligned}

The weight gradient of a convolution is again a matrix product, of the output gradient with the same patch matrix the forward pass built: im2col pays off twice. The gradient with respect to the input image is not needed here, because the convolution is the first layer; in a deeper network it would be W1⊤∂L/∂ZW_1^\top \partial L / \partial Z scattered back from columns to pixels ("col2im", the adjoint of im2col).

The NumPy code, gradient-checked

Every example below starts with the same block: the Digits split from the course recipe (1077 training, 360 validation, 360 test images, pixels scaled to [0,1][0, 1]), im2col for padding 1, an initialiser (He-scaled normal weights, see weight initialisation), and forward / loss_and_grads. Max pooling stores which of the four pixels won (argmax) so the backward pass can route the gradient to it; np.put_along_axis does the routing.

The check compares each analytic gradient with a central difference L(θ+ϵ)−L(θ−ϵ)2ϵ\frac{L(\theta + \epsilon) - L(\theta - \epsilon)}{2\epsilon} on 20 images, as in gradient checking:

python · try it yourself
import numpy as np
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)
X_tr, X_va = X_tr.reshape(-1, 8, 8), X_va.reshape(-1, 8, 8)

def im2col(x):
    """(N, 8, 8) -> (N, 9, 64): the 3 x 3 patch around every pixel (zero padding 1)."""
    N, H, W = x.shape
    xp = np.pad(x, ((0, 0), (1, 1), (1, 1)))
    cols = np.empty((N, 3, 3, H, W))
    for a in range(3):
        for c in range(3):
            cols[:, a, c] = xp[:, a:a + H, c:c + W]
    return cols.reshape(N, 9, H * W)

def init(rng, F=8):
    return {"W1": rng.normal(0, np.sqrt(2 / 9), (F, 9)), "b1": np.zeros(F),
            "W2": rng.normal(0, np.sqrt(2 / (F * 16)), (F * 16, 10)), "b2": np.zeros(10)}

def forward(P, cols):
    N, F = cols.shape[0], P["W1"].shape[0]
    z = P["W1"] @ cols + P["b1"][:, None]                 # conv as a matmul: (N, F, 64)
    a = np.maximum(z, 0)                                  # ReLU
    win = a.reshape(N, F, 4, 2, 4, 2).transpose(0, 1, 2, 4, 3, 5).reshape(N, F, 4, 4, 4)
    idx = win.argmax(axis=-1)                             # which of the 4 pixels won
    h = np.take_along_axis(win, idx[..., None], -1).reshape(N, F * 16)   # 2x2 max pool, flatten
    logits = h @ P["W2"] + P["b2"]                        # linear head
    return logits, (z, idx, h)

def loss_and_grads(P, cols, y):
    logits, (z, idx, h) = forward(P, cols)
    N, F = len(y), P["W1"].shape[0]
    e = np.exp(logits - logits.max(1, keepdims=True))
    prob = e / e.sum(1, keepdims=True)
    loss = -np.log(prob[np.arange(N), y]).mean()
    d = prob.copy(); d[np.arange(N), y] -= 1; d /= N      # softmax-CE gradient w.r.t. logits
    g = {"W2": h.T @ d, "b2": d.sum(0)}
    dh = (d @ P["W2"].T).reshape(N, F, 4, 4)
    dwin = np.zeros((N, F, 4, 4, 4))
    np.put_along_axis(dwin, idx[..., None], dh[..., None], -1)   # route to the max only
    da = dwin.reshape(N, F, 4, 4, 2, 2).transpose(0, 1, 2, 4, 3, 5).reshape(N, F, 64)
    dz = da * (z > 0)                                     # ReLU backward
    g["W1"] = np.einsum("nfp,nkp->fk", dz, cols)          # conv weight gradient
    g["b1"] = dz.sum(axis=(0, 2))
    return loss, g

def check(P, cols, yb, names, rng, trials=5):
    _, g = loss_and_grads(P, cols, yb)
    for name in names:
        worst = 0.0
        for _ in range(trials):
            i = tuple(int(rng.integers(s)) for s in P[name].shape)
            old = P[name][i]
            P[name][i] = old + 1e-5; lp, _ = loss_and_grads(P, cols, yb)
            P[name][i] = old - 1e-5; lm, _ = loss_and_grads(P, cols, yb)
            P[name][i] = old
            num = (lp - lm) / 2e-5
            worst = max(worst, abs(num - g[name][i]) / max(1e-8, abs(num) + abs(g[name][i])))
        print(f"  {name}: shape {P[name].shape}, worst relative error " + ("below 1e-7" if worst < 1e-7 else f"{worst:.2f}"))

rng = np.random.default_rng(0)
P = init(rng)
cols, yb = im2col(X_tr[:20]), y_tr[:20]
print("parameters:", sum(v.size for v in P.values()))
print("b1 = 0 (blank patches sit exactly on the ReLU kink):")
check(P, cols, yb, ["b1"], rng)
P["b1"][:] = 0.1                                      # move them off the kink
print("b1 = 0.1:")
check(P, cols, yb, ["W1", "b1", "W2", "b2"], rng)
parameters: 1370
b1 = 0 (blank patches sit exactly on the ReLU kink):
  b1: shape (8,), worst relative error 0.61
b1 = 0.1:
  W1: shape (8, 9), worst relative error below 1e-7
  b1: shape (8,), worst relative error below 1e-7
  W2: shape (128, 10), worst relative error below 1e-7
  b2: shape (10,), worst relative error below 1e-7

The first line is a real failure and a lesson in itself. With b1=0b_1 = 0, every blank 3 ×\times 3 patch of background gives Z=0Z = 0 exactly, which is the kink of the ReLU: moving b1b_1 up by ϵ\epsilon switches those units on, moving it down leaves them off, and the central difference measures half of a one-sided slope. The analytic code uses the convention ReLU′(0)=0\text{ReLU}'(0) = 0, so the two disagree by a relative error of 0.61. The code is not wrong; the check point is. Moving the biases to 0.1 puts every unit off the kink, and all four parameter groups then agree to better than 10−710^{-7}. Digit images, with many exactly-zero pixels, hit this case all the time; a gradient check should always use a point where no ReLU input is exactly 0.

Training in the browser

SGD with momentum 0.9, learning rate 0.1, batches of 32, 8 epochs, accuracy on the 360 validation images after each epoch. The patch matrices are built once for the whole set.

python · try it yourself
import numpy as np
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)
X_tr, X_va = X_tr.reshape(-1, 8, 8), X_va.reshape(-1, 8, 8)

def im2col(x):
    """(N, 8, 8) -> (N, 9, 64): the 3 x 3 patch around every pixel (zero padding 1)."""
    N, H, W = x.shape
    xp = np.pad(x, ((0, 0), (1, 1), (1, 1)))
    cols = np.empty((N, 3, 3, H, W))
    for a in range(3):
        for c in range(3):
            cols[:, a, c] = xp[:, a:a + H, c:c + W]
    return cols.reshape(N, 9, H * W)

def init(rng, F=8):
    return {"W1": rng.normal(0, np.sqrt(2 / 9), (F, 9)), "b1": np.zeros(F),
            "W2": rng.normal(0, np.sqrt(2 / (F * 16)), (F * 16, 10)), "b2": np.zeros(10)}

def forward(P, cols):
    N, F = cols.shape[0], P["W1"].shape[0]
    z = P["W1"] @ cols + P["b1"][:, None]                 # conv as a matmul: (N, F, 64)
    a = np.maximum(z, 0)                                  # ReLU
    win = a.reshape(N, F, 4, 2, 4, 2).transpose(0, 1, 2, 4, 3, 5).reshape(N, F, 4, 4, 4)
    idx = win.argmax(axis=-1)                             # which of the 4 pixels won
    h = np.take_along_axis(win, idx[..., None], -1).reshape(N, F * 16)   # 2x2 max pool, flatten
    logits = h @ P["W2"] + P["b2"]                        # linear head
    return logits, (z, idx, h)

def loss_and_grads(P, cols, y):
    logits, (z, idx, h) = forward(P, cols)
    N, F = len(y), P["W1"].shape[0]
    e = np.exp(logits - logits.max(1, keepdims=True))
    prob = e / e.sum(1, keepdims=True)
    loss = -np.log(prob[np.arange(N), y]).mean()
    d = prob.copy(); d[np.arange(N), y] -= 1; d /= N      # softmax-CE gradient w.r.t. logits
    g = {"W2": h.T @ d, "b2": d.sum(0)}
    dh = (d @ P["W2"].T).reshape(N, F, 4, 4)
    dwin = np.zeros((N, F, 4, 4, 4))
    np.put_along_axis(dwin, idx[..., None], dh[..., None], -1)   # route to the max only
    da = dwin.reshape(N, F, 4, 4, 2, 2).transpose(0, 1, 2, 4, 3, 5).reshape(N, F, 64)
    dz = da * (z > 0)                                     # ReLU backward
    g["W1"] = np.einsum("nfp,nkp->fk", dz, cols)          # conv weight gradient
    g["b1"] = dz.sum(axis=(0, 2))
    return loss, g

rng = np.random.default_rng(0)
P = init(rng)
V = {k: np.zeros_like(v) for k, v in P.items()}          # momentum buffers
cols_tr, cols_va = im2col(X_tr), im2col(X_va)
lr, beta, bs = 0.1, 0.9, 32
for epoch in range(1, 9):
    order = rng.permutation(len(y_tr))
    total = 0.0
    for s in range(0, len(order), bs):
        b = order[s:s + bs]
        loss, g = loss_and_grads(P, cols_tr[b], y_tr[b])
        total += loss * len(b)
        for k in P:
            V[k] = beta * V[k] - lr * g[k]
            P[k] += V[k]
    acc = (forward(P, cols_va)[0].argmax(1) == y_va).mean()
    print(f"epoch {epoch}  train loss {total / len(y_tr):.4f}  val accuracy {acc:.3f}")
epoch 1  train loss 1.3274  val accuracy 0.867
epoch 2  train loss 0.3567  val accuracy 0.950
epoch 3  train loss 0.1561  val accuracy 0.953
epoch 4  train loss 0.0978  val accuracy 0.947
epoch 5  train loss 0.0862  val accuracy 0.958
epoch 6  train loss 0.0680  val accuracy 0.975
epoch 7  train loss 0.0680  val accuracy 0.961
epoch 8  train loss 0.0611  val accuracy 0.969

After one epoch the validation accuracy is 0.867, after two 0.950, and it reaches 0.975 at epoch 6 before settling at 0.969 after 8 epochs. The training loss falls from 1.3274 to 0.0611. A hand-written backward pass trains a working image classifier in a few seconds of browser time.

The same CNN in PyTorch

In PyTorch the network is five modules: nn.Conv2d(1, 8, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2), nn.Flatten(), nn.Linear(128, 10), and autograd replaces loss_and_grads. The recorded run below (CPU) trains it with Adam (learning rate 0.01, batch 32) for 40 epochs, keeps the epoch with the best validation accuracy, and repeats for three seeds. The comparison model is an MLP 64-18-10 with 1360 parameters, ten fewer than the CNN, trained the same way. Model choice uses the validation set only; the test set is evaluated once at the end. As an extra probe, both models also see the validation digits shifted one pixel to the right.

python · try it yourself
import copy
import numpy as np
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader
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)
img = lambda a: torch.tensor(a, dtype=torch.float32).reshape(-1, 1, 8, 8)
X_tr, X_va, X_te = img(X_tr), img(X_va), img(X_te)
y_tr, y_va, y_te = (torch.tensor(a) for a in (y_tr, y_va, y_te))

def cnn():
    return nn.Sequential(nn.Conv2d(1, 8, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
                         nn.Flatten(), nn.Linear(8 * 4 * 4, 10))

def mlp():
    return nn.Sequential(nn.Flatten(), nn.Linear(64, 18), nn.ReLU(), nn.Linear(18, 10))

def accuracy(model, X, y):
    model.eval()
    with torch.no_grad():
        return (model(X).argmax(1) == y).float().mean().item()

def fit(make, seed, epochs=40):
    torch.manual_seed(seed)
    model = make()
    opt = torch.optim.Adam(model.parameters(), lr=0.01)
    loader = DataLoader(TensorDataset(X_tr, y_tr), batch_size=32, shuffle=True)
    best = (-1.0, 0, None)
    for epoch in range(1, epochs + 1):
        model.train()
        for xb, yb in loader:
            loss = nn.functional.cross_entropy(model(xb), yb)
            opt.zero_grad(); loss.backward(); opt.step()
        acc = accuracy(model, X_va, y_va)
        if acc > best[0]:
            best = (acc, epoch, copy.deepcopy(model.state_dict()))
    model.load_state_dict(best[2])
    return model, best[0], best[1]

X_shift = torch.zeros_like(X_va)
X_shift[..., 1:] = X_va[..., :-1]                 # every validation digit moved 1 pixel right

final = {}
for name, make in [("CNN", cnn), ("MLP", mlp)]:
    n = sum(p.numel() for p in make().parameters())
    runs = [fit(make, seed) for seed in (0, 1, 2)]
    vals = [r[1] for r in runs]
    print(f"{name}: {n} parameters, best val accuracy per seed {[round(v, 3) for v in vals]}, "
          f"mean {np.mean(vals):.3f}")
    shifted = [accuracy(r[0], X_shift, y_va) for r in runs]
    print(f"  shifted 1 px right: val accuracy {[round(v, 3) for v in shifted]}, mean {np.mean(shifted):.3f}")
    final[name] = runs[0][0]
print(f"test accuracy, seed 0 (measured once): CNN {accuracy(final['CNN'], X_te, y_te):.3f}, "
      f"MLP {accuracy(final['MLP'], X_te, y_te):.3f}")
CNN: 1370 parameters, best val accuracy per seed [0.978, 0.969, 0.972], mean 0.973
  shifted 1 px right: val accuracy [0.55, 0.522, 0.619], mean 0.564
MLP: 1360 parameters, best val accuracy per seed [0.975, 0.972, 0.975], mean 0.974
  shifted 1 px right: val accuracy [0.419, 0.4, 0.467], mean 0.429
test accuracy, seed 0 (measured once): CNN 0.981, MLP 0.956

On the validation set the two are tied: the CNN's best accuracies are 0.978, 0.969 and 0.972 (mean 0.973), the MLP's 0.975, 0.972 and 0.975 (mean 0.974). The Digits images are tiny, centred and size-normalised, so the MLP gets almost no disadvantage from ignoring spatial structure, and three seeds cannot separate a difference this small. The shifted digits tell the two apart: the CNN keeps a mean of 0.564, the MLP drops to 0.429. Neither is robust, because this CNN's linear head still reads each pooled position with its own weights (only the convolution is shared), but the shared filters do carry over to the new positions. The single test measurement at the end gives 0.981 for the seed-0 CNN and 0.956 for the seed-0 MLP; with 360 test images one image is 0.0028, so that gap is 9 images, larger than the validation gap and a reminder that one test number from one seed is noisy.

What to take from it: a convolution's advantage grows with the image size and with the variation in position and scale. On 8 ×\times 8 centred digits it is small; on 224 ×\times 224 photos an MLP cannot compete at any parameter budget. To make a CNN robust to shifts, add data augmentation (random shifts and crops) and end with global average pooling rather than a position-specific linear head (the previous lesson).

Pitfalls

  • Gradient checks at a kink. ReLU and max pooling are not differentiable at ties and at 0. Check at a point with non-zero pre-activations and no tied window maxima, or the "error" is the check's, not yours.
  • Max-pool ties in the backward pass. If two pixels of a window are equal, route the gradient to one of them (as argmax does); x == max masks would send it to both and double it.
  • Wrong flatten order. h.reshape(N, -1) in NumPy and nn.Flatten() in PyTorch both flatten channel-first (C, H, W); mixing layouts silently scrambles the head's inputs when you copy weights between the two.
  • Comparing on one seed. Differences under about 1 % on 360 images are within seed noise; repeat the run or use more data before choosing.
  • Peeking at the test set. Pick the epoch and the model on validation; look at the test set once.

Practice

  1. Replace the max pool in the NumPy network by 2 ×\times 2 average pooling. What changes in forward and in the backward routing?
  2. Add a second convolution layer (8 to 8 channels) before the pool. Which extra function do you need for its input gradient, and what shapes does it take and return?
  3. In the PyTorch example, replace nn.Flatten(), nn.Linear(128, 10) by nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(8, 10). How many parameters does the model have, and what do you expect for the shifted validation accuracy?
Answer
  1. Forward: h = win.mean(axis=-1) instead of the argmax / take_along_axis pair. Backward: every pixel of a window gets a quarter of the window's gradient, dwin = np.repeat(dh[..., None], 4, axis=-1) / 4, with no index to store.
  2. You need col2im, the adjoint of im2col: it takes the column gradient W.T @ dz of shape (N, C_in*9, 64) and adds each column entry back to the pixel it was copied from, returning (N, C_in, 8, 8) (then drop the padding border).
  3. 80+8⋅10+10=17080 + 8 \cdot 10 + 10 = 170 parameters. The head no longer depends on position, so the model is close to shift-invariant and its shifted accuracy should stay near its normal accuracy, but with only 8 averaged features its normal accuracy will be lower than 0.97; try it.

Test yourself

In the NumPy CNN, how is the gradient of the convolution weights W1W_1 computed?

  1. By looping over every output pixel and kernel weight
  2. As a matrix product of the output gradient with the same im2col patch matrix used in the forward pass
  3. By flipping the kernel and convolving the input
  4. It is not needed because the first layer is frozen

The gradient check of b1b_1 reported a relative error of 0.61 with b1=0b_1 = 0 and agreement below 10−710^{-7} with b1=0.1b_1 = 0.1. Why?

  1. The backward pass has a bug that only shows at zero bias
  2. Blank patches give pre-activations exactly at the ReLU kink, where the central difference is not a derivative
  3. Float64 is not precise enough
  4. The learning rate was too high

The CNN (1370 parameters) and the MLP (1360) reached mean validation accuracies of 0.973 and 0.974. What separated them?

  1. Nothing: they behaved the same everywhere
  2. Accuracy on digits shifted by one pixel: 0.564 for the CNN, 0.429 for the MLP
  3. Training speed only
  4. The MLP could not reach 0.9

When max pooling's backward pass meets a window with two equal maxima, what should it do?

  1. Send the full gradient to both
  2. Send the gradient to one of them (e.g. the first argmax)
  3. Send no gradient
  4. Average over all four pixels