Training an MLP with Your Autograd
You now have every piece of a deep-learning framework in miniature: layers as matrix products (neurons and layers), a stable classification loss (output layers), and an engine that differentiates any graph of array operations (the autograd engine). This lesson assembles them into the shape PyTorch code has: a model object that owns its parameters, an optimizer with zero_grad() and step(), and a training loop that never mentions a gradient formula. It trains a classifier on the Digits images to above 96 % validation accuracy in the browser in a few seconds, and then runs the identical model in PyTorch to show that the numbers agree to four decimals.
The training loop itself (batches, epochs, validation, keeping the best checkpoint) is the one from the training-loop course; only the gradient computation is new.
Three objects, one loop
| Piece | This lesson | PyTorch |
|---|---|---|
| parameters | Tensor leaves with .data and .grad |
nn.Parameter (a tensor with requires_grad=True) |
| model | MLP with __call__ and parameters() |
nn.Module with forward and parameters() |
| loss | logits.cross_entropy(y) |
nn.CrossEntropyLoss()(logits, y) |
| gradients | loss.backward() |
loss.backward() |
| optimizer | SGD(params, lr) with zero_grad(), step() |
torch.optim.SGD(params, lr) |
The optimizer only needs a list of parameter tensors. step() applies plain stochastic gradient descent to each,
where the average over the mini-batch is already inside the loss (its mean), and zero_grad() resets every .grad to zero, because the engine, like PyTorch, adds new gradients to old ones. Momentum, Adam and the rest (optimisers) differ only in what step() does with the gradient.
The model is a 64-64-10 ReLU network: 8 8 pixels in, 64 hidden units, 10 logits out, parameters, He-initialised (, biases zero).
The whole thing in NumPy
The example repeats the parts of the engine this model uses (matrix product, bias add, ReLU, fused cross-entropy, backward), so it runs on its own. The data is the course's Digits split: 1077 training, 360 validation and 360 test images, pixels divided by 16. Training runs for 30 epochs with batches of 32 and learning rate 0.1. After every epoch the model is evaluated on the validation set, and the parameters of the best epoch are kept. Only at the very end is the test set used, once.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
# ---- the autograd engine from the previous lesson, only the ops this model needs ----
class Tensor:
def __init__(self, data, parents=()):
self.data = np.asarray(data, dtype=float)
self.grad = np.zeros_like(self.data)
self.parents = parents
self._backward = lambda: None
def __add__(self, other): # (n, h) + (h,): bias broadcast
out = Tensor(self.data + other.data, (self, other))
def _backward():
self.grad += out.grad
other.grad += out.grad.sum(axis=0) # un-broadcast the batch axis
out._backward = _backward
return out
def __matmul__(self, other):
out = Tensor(self.data @ other.data, (self, other))
def _backward():
self.grad += out.grad @ other.data.T
other.grad += self.data.T @ out.grad
out._backward = _backward
return out
def relu(self):
out = Tensor(np.maximum(self.data, 0), (self,))
def _backward():
self.grad += out.grad * (self.data > 0)
out._backward = _backward
return out
def cross_entropy(self, y):
Z = self.data - self.data.max(axis=1, keepdims=True)
P = np.exp(Z) / np.exp(Z).sum(axis=1, keepdims=True)
n = len(y)
out = Tensor(-np.log(P[np.arange(n), y]).mean(), (self,))
def _backward():
G = P.copy(); G[np.arange(n), y] -= 1
self.grad += out.grad * G / n
out._backward = _backward
return out
def backward(self):
order, seen = [], set()
def visit(t):
if id(t) not in seen:
seen.add(id(t))
for p in t.parents:
visit(p)
order.append(t)
visit(self)
self.grad = np.ones_like(self.data)
for t in reversed(order):
t._backward()
# ---- a model and an optimizer with the PyTorch interface ----
class MLP:
def __init__(self, sizes, rng):
self.layers = [(Tensor(rng.normal(0, np.sqrt(2 / d), (d, h))), Tensor(np.zeros(h)))
for d, h in zip(sizes[:-1], sizes[1:])]
def __call__(self, X):
h = Tensor(X)
for i, (W, b) in enumerate(self.layers):
h = h @ W + b
if i < len(self.layers) - 1:
h = h.relu()
return h
def parameters(self):
return [p for W, b in self.layers for p in (W, b)]
class SGD:
def __init__(self, params, lr):
self.params, self.lr = params, lr
def zero_grad(self):
for p in self.params:
p.grad = np.zeros_like(p.data)
def step(self):
for p in self.params:
p.data -= self.lr * p.grad
# ---- data: the course's Digits 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)
def evaluate(model, X, y): # no backward: the graph is just discarded
logits = model(X)
return float(logits.cross_entropy(y).data), float((logits.data.argmax(1) == y).mean())
rng = np.random.default_rng(0)
model = MLP([64, 64, 10], rng)
opt = SGD(model.parameters(), lr=0.1)
print("parameters:", sum(p.data.size for p in model.parameters()))
best = (0.0, 0, None)
for epoch in range(1, 31):
order = rng.permutation(len(y_tr))
for s in range(0, len(order), 32):
idx = order[s:s + 32]
loss = model(X_tr[idx]).cross_entropy(y_tr[idx])
opt.zero_grad()
loss.backward()
opt.step()
va_loss, va_acc = evaluate(model, X_va, y_va)
if va_acc > best[0]:
best = (va_acc, epoch, [p.data.copy() for p in model.parameters()])
if epoch in (1, 5, 10, 20, 30):
tr_loss, tr_acc = evaluate(model, X_tr, y_tr)
print(f"epoch {epoch:2d} train loss {tr_loss:.4f} acc {tr_acc:.3f} val loss {va_loss:.4f} acc {va_acc:.3f}")
for p, saved in zip(model.parameters(), best[2]):
p.data = saved # restore the best validation epoch
print(f"best val acc {best[0]:.3f} at epoch {best[1]}")
te_loss, te_acc = evaluate(model, X_te, y_te)
print(f"test (once, 360 images): loss {te_loss:.4f} accuracy {te_acc:.3f}")parameters: 4810
epoch 1 train loss 1.3564 acc 0.752 val loss 1.3616 acc 0.756
epoch 5 train loss 0.3381 acc 0.924 val loss 0.3610 acc 0.925
epoch 10 train loss 0.1805 acc 0.962 val loss 0.2117 acc 0.947
epoch 20 train loss 0.1038 acc 0.980 val loss 0.1516 acc 0.964
epoch 30 train loss 0.0735 acc 0.989 val loss 0.1316 acc 0.967
best val acc 0.972 at epoch 28
test (once, 360 images): loss 0.1683 accuracy 0.964
The loss falls from 1.3564 after the first epoch to 0.0735 on the training set after 30, and validation accuracy climbs from 0.756 to 0.967. The best validation accuracy, 0.972, comes at epoch 28, and those weights give 0.964 on the 360 test images, the number to report. Training and validation losses stay close (0.0735 against 0.1316), so the network is only mildly overfitting at this point.
Compare the first four lines with the output of the layer-by-layer lesson: the losses and accuracies at epochs 1, 5, 10 and 20 are identical, digit for digit. Both use the same random generator, the same initial weights and the same batch order, and the hand-written backward methods there compute exactly what autograd computes here. Autograd is not an approximation of backpropagation; it is backpropagation, organised by the graph instead of by you.
Note what the loop does not contain: no gradient formula, no list of layers in reverse, no shape bookkeeping. To make the network deeper, change [64, 64, 10] to [64, 128, 64, 10]; to add an L2 penalty, add (W * W).sum() * 1e-4 to the loss (with the mul and sum ops of the full engine). The engine follows.
evaluate builds a graph and then simply drops it without calling backward. That works, but it wastes memory on cached values nobody will use; PyTorch avoids it with torch.no_grad().
A library baseline in the browser
scikit-learn's MLPClassifier implements the same network with the same recipe: one hidden layer of 64 ReLU units, plain SGD with learning rate 0.1, batch size 32, no momentum, no weight decay, 30 epochs.
import warnings
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.exceptions import ConvergenceWarning
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)
warnings.simplefilter("ignore", ConvergenceWarning) # max_iter=30 stops "early" on purpose
clf = MLPClassifier(hidden_layer_sizes=(64,), activation="relu", solver="sgd", learning_rate_init=0.1,
momentum=0.0, batch_size=32, alpha=0.0, max_iter=30, random_state=0)
clf.fit(X_tr, y_tr)
print("scikit-learn MLP, same recipe: val acc", round(clf.score(X_va, y_va), 3), " final training loss", round(clf.loss_, 4))
print("weights:", [w.shape for w in clf.coefs_], " biases:", [b.shape for b in clf.intercepts_])scikit-learn MLP, same recipe: val acc 0.972 final training loss 0.0774
weights: [(64, 64), (64, 10)] biases: [(64,), (10,)]
It reaches 0.972 validation accuracy as well, with weight matrices of the same shapes. Its training loss after 30 epochs, 0.0774, is close to but not equal to the 0.0735 above: scikit-learn initialises with a scaled uniform distribution (Glorot) and shuffles with its own generator, so the trajectory differs while the destination is the same.
The identical model in PyTorch
To show that the two engines do the same arithmetic, the PyTorch run must start from the same weights, see the same batches in the same order and compute in the same precision. The recorded example draws the initial weights and every epoch's permutation from the same NumPy generator, copies the weights into nn.Linear layers (transposed: PyTorch stores out by in) and switches the model to float64 with .double(), the same technique as in the PyTorch loop of the training course. The recording ran on a CPU.
import copy
import numpy as np
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)
X_tr, X_va, X_te = (torch.tensor(a) for a in (X_tr, X_va, X_te)) # float64, like NumPy
y_tr, y_va, y_te = (torch.tensor(a) for a in (y_tr, y_va, y_te)) # int64 class indices
rng = np.random.default_rng(0) # the same draws as the NumPy run
model = nn.Sequential(nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 10)).double()
with torch.no_grad():
for layer, (d, h) in zip([model[0], model[2]], [(64, 64), (64, 10)]):
layer.weight.copy_(torch.tensor(rng.normal(0, np.sqrt(2 / d), (d, h)).T)) # (out, in)
layer.bias.zero_()
opt = torch.optim.SGD(model.parameters(), lr=0.1)
loss_fn = nn.CrossEntropyLoss()
def evaluate(X, y):
model.eval()
with torch.no_grad():
logits = model(X)
return loss_fn(logits, y).item(), (logits.argmax(1) == y).double().mean().item()
best = (0.0, 0, None)
for epoch in range(1, 31):
model.train()
order = rng.permutation(len(y_tr))
for s in range(0, len(order), 32):
idx = torch.from_numpy(order[s:s + 32])
loss = loss_fn(model(X_tr[idx]), y_tr[idx])
opt.zero_grad()
loss.backward()
opt.step()
va_loss, va_acc = evaluate(X_va, y_va)
if va_acc > best[0]:
best = (va_acc, epoch, copy.deepcopy(model.state_dict()))
if epoch in (1, 5, 10, 20, 30):
tr_loss, tr_acc = evaluate(X_tr, y_tr)
print(f"epoch {epoch:2d} train loss {tr_loss:.4f} acc {tr_acc:.3f} val loss {va_loss:.4f} acc {va_acc:.3f}")
model.load_state_dict(best[2])
print(f"best val acc {best[0]:.3f} at epoch {best[1]}")
te_loss, te_acc = evaluate(X_te, y_te)
print(f"test (once, 360 images): loss {te_loss:.4f} accuracy {te_acc:.3f}")epoch 1 train loss 1.3564 acc 0.752 val loss 1.3616 acc 0.756
epoch 5 train loss 0.3381 acc 0.924 val loss 0.3610 acc 0.925
epoch 10 train loss 0.1805 acc 0.962 val loss 0.2117 acc 0.947
epoch 20 train loss 0.1038 acc 0.980 val loss 0.1516 acc 0.964
epoch 30 train loss 0.0735 acc 0.989 val loss 0.1316 acc 0.967
best val acc 0.972 at epoch 28
test (once, 360 images): loss 0.1683 accuracy 0.964
Every line matches the NumPy run to four decimals: 1.3564 and 0.756 after the first epoch, 0.0735 and 0.967 after the last, the best validation accuracy 0.972 at epoch 28 and 0.964 on the test set. That is 1020 SGD updates (34 batches per epoch, 30 epochs) on which the gradients of the two engines never drifted apart. A separate float32 run (PyTorch's default precision) of this short training still agreed to four decimals; on longer or larger runs float32 rounding makes two correct implementations drift apart in the last digits, so compare them in float64.
Pitfalls
- Forgetting
zero_grad(). Remove it from the NumPy loop and the gradients of all previous batches pile up. In a separate run without it, the first epoch even looked better (training loss 0.7301 instead of 1.3564: the accumulated gradient acts like a very large momentum), but by epoch 5 the training loss had climbed to 3.4483 and validation accuracy had fallen to 0.586. The same holds in PyTorch. - Restoring the "best" model by reference.
best = model.parameters()keeps the live tensors, which go on changing. The example copiesp.data.copy(); in PyTorch usecopy.deepcopy(model.state_dict())ortorch.save. - Choosing anything on the test set. The epoch, the learning rate and the architecture are chosen on validation. The test set is used once, and if you go back and change something after seeing it, it has become a second validation set.
- Comparing implementations with different seeds or batch orders. Two correct implementations agree number for number only when initialisation, data order and precision are matched, as in the recorded example; otherwise compare the final accuracy within run-to-run noise.
- Building graphs during evaluation. In the NumPy engine every forward pass stores caches. On large validation sets, evaluate in batches, and in PyTorch wrap evaluation in
torch.no_grad()and callmodel.eval().
Practice
- Add momentum to the
SGDclass: , , astorch.optim.SGD(momentum=mu)does.
Answer
class SGD:
def __init__(self, params, lr, momentum=0.0):
self.params, self.lr, self.mu = params, lr, momentum
self.v = [np.zeros_like(p.data) for p in params]
def zero_grad(self):
for p in self.params:
p.grad = np.zeros_like(p.data)
def step(self):
for p, v in zip(self.params, self.v):
v *= self.mu
v += p.grad
p.data -= self.lr * vThe velocity is one array per parameter, the optimizer's state; it is what optimizer.state_dict() saves in PyTorch.
- How many parameter updates does the training run make, and how many examples does the last batch of each epoch contain?
Answer
batches per epoch, so updates. The last batch has examples; the mean in the loss makes its gradient comparable to the others.
- Why do the first four printed lines equal those of the layer-by-layer lesson, although that code has no autograd at all?
Answer
Same data, same initial weights (the same generator calls in the same order), same batch order, float64 everywhere, and gradients that are mathematically and numerically the same: the hand-written Linear.backward computes , and , and the autograd closures compute exactly those products. The only difference is who decides the order of the backward calls.
- Write the one line that makes the NumPy model predict the digit of a single image
xof shape(64,).
Answer
int(model(x[None]).data.argmax()): x[None] adds the batch axis to get shape (1, 64), and the argmax of the 10 logits is the predicted class. No softmax is needed for the class itself.
Test yourself
What does the optimizer's step() need to know about the model?
- Its architecture
- Only the list of parameter tensors, with their
.grad - The loss function
- The training data
The NumPy run and the PyTorch run print the same losses to four decimals. Which of these was NOT needed for that?
- The same initial weights
- The same batch order
- float64 in both
- The same Python version
Why is the test accuracy (0.964) computed only once, at the end?
- It is slow to compute
- Every decision (epoch, hyperparameters) was made on validation; using the test set for decisions would make it optimistic
- The test set is smaller
- PyTorch forbids evaluating twice
What happens if opt.zero_grad() is removed from the loop?
- Nothing, since
backward()overwrites the gradients - Gradients from all previous batches accumulate and the updates grow
- The loss is computed twice
- Only the biases stop learning