AI from scratch · Stage 2: how a network learns

Training in PyTorch

You've built networks and their backward pass by hand. Real training adds a few things: data in small batches, many passes over it, an optimizer, and a framework that computes every gradient for you. This lesson takes them one at a time: each idea as a picture, then in NumPy you can run here, then the PyTorch line that does the same job (PyTorch is too big to run inside a web page, so those blocks are for reading; the practice notebook runs them on a GPU).

1. The loop, in five lines

Every PyTorch training script, from a digit reader to a large language model, has this shape:

for each epoch→for each batch→forward: predictions→loss→zero old gradients→backward→optimizer step
for epoch in range(epochs):              # one epoch = one pass over all the training data
    for x, y in train_loader:            # one batch at a time
        loss = loss_fn(model(x), y)      # forward pass and loss
        optimizer.zero_grad()            # clear last step's gradients (they'd add up otherwise)
        loss.backward()                  # backprop: every parameter gets its .grad
        optimizer.step()                 # move every parameter downhill

The rest of this lesson is about each word in it.

2. Epochs and batches

Chapter 2's gradient descent used every example for every step. With a million examples that's slow, so training uses a minibatch: a small random handful per step. The gradient from a batch is a noisy guess of the full one (calculus 4 showed the noise shrinks like \(1/\sqrt{B}\)), but you get many more steps for the same work. One pass over all the data, batch by batch, is an epoch. Below, 120 noisy points and a line learning them: the yellow dots are the current batch.

Try batch size 1: each step looks at one point, so the line jitters, yet it gets close quickly. Try 120 (all of them): smooth, but one step per epoch. Most real training sits in between, 32 to a few thousand examples, chosen to fill the GPU. Then try learning rate 0.04: it blows up, because the steepest curvature here is about 76 and calculus 3's limit is 2/76 ≈ 0.026. And notice the slope settles fast but the intercept crawls: km runs from 0 to 10 while the intercept's "feature" is always 1, a stretched valley (condition number about 166). Scaling the input, which stage 4 makes routine, would fix that.

A minibatch step trades an exact gradient for a noisy one and many more steps per pass over the data. Batches of 32 to a few thousand are the usual middle.

MNIST has 60,000 training images. With batches of 128, how many steps is one epoch? (The last batch is smaller.)

\(60{,}000 / 128 = 468.75\), so 469 steps: 468 full batches and one of 96. Ten epochs is 4,690 steps.
Why raise the learning rate when you raise the batch size?
  1. One step on a batch of \(B\) examples moves the weights by \(\eta\) times the batch's average gradient.
  2. \(B\) steps of batch size 1 move them by \(\eta\) times the sum of \(B\) single-example gradients, as long as those gradients barely change over the \(B\) small steps. That sum is \(B\) times the average.
  3. So to cover the same ground per example seen, a batch \(B\) times bigger needs a learning rate about \(B\) times bigger: the linear scaling rule. It also gets \(\sqrt B\) times less noise, and the GPU does the \(B\) examples in about the time of one.
  4. The rule leans on "the gradient barely changes", which holds only for small steps. That's where it breaks.
Where it breaks: when bigger batches stop paying

A tensor is an array that can live on a GPU and remember how it was made, so backward() can run the chain rule for you.

3. Tensors: arrays that remember

A PyTorch tensor is a NumPy array with two extra powers: it can live on a GPU, and if you ask, it records every operation done to it, so .backward() can run chapter 4's relay of blame automatically (autograd).

NumPyPyTorchwhat it does
np.array([1., 2.])torch.tensor([1., 2.])make an array
a @ b, a.T, a.shapethe samematrix product, transpose, shape
a.mean(axis=0)a.mean(dim=0)reduce along an axis
(no GPU)a.to("cuda")move to the GPU
(gradients by hand)torch.zeros(3, requires_grad=True)record operations for autograd
(gradients by hand)loss.backward(); w.gradevery gradient, computed for you
np.asarray(t)t.detach().cpu().numpy()back to NumPy
w = torch.zeros(1, requires_grad=True)
loss = ((w * x + b - y) ** 2).mean()     # PyTorch records the operations…
loss.backward()                          # …and runs them backwards
print(w.grad)                            # ∂loss/∂w: what you derived by hand in chapter 2

Why must training call optimizer.zero_grad() every step?

Adding up is the right rule inside one backward pass (a value used twice collects blame from both uses, chapter 4), so PyTorch always adds. Between steps you clear it yourself. Forgetting is a classic bug: training goes haywire with no error message.

4. A model is an nn.Module

A module is a layer, or a stack of them, that owns its parameters. You list the layers in __init__ and say how data flows in forward; PyTorch finds every weight inside for the optimizer, moves them all to the GPU with one call, and saves them in one file.

Python note: class. A class is a recipe for objects that carry their own data and functions. __init__ runs when you make one, and self is the object being made, so self.value = ... stores something on it. A function inside a class, a method, gets the object as self too, so it can use what's stored. Run this, then read the model below it.

class MLP(nn.Module) below means "an MLP is a kind of Module": it gets everything a Module already does (finding parameters, moving to the GPU, saving), and super().__init__() lets Module set itself up first.

from torch import nn

class MLP(nn.Module):
    def __init__(self):
        super().__init__()
        self.layers = nn.Sequential(
            nn.Flatten(),                    # 28×28 image → 784 numbers
            nn.Linear(784, 128), nn.ReLU(),  # deep networks, section 1: W x + b, then a bend
            nn.Linear(128, 10))              # 10 scores, one per class
    def forward(self, x):
        return self.layers(x)

model = MLP()
print(sum(p.numel() for p in model.parameters()))   # 101,770: the count from chapter 1

Two modes matter: model.train() while training and model.eval() when measuring or serving. Some layers (dropout, batch norm; stage 4) behave differently in each, and forgetting .eval() gives quietly worse test numbers. Wrap evaluation in with torch.no_grad(): so PyTorch doesn't record operations it will never backpropagate.

Python note: with. with something: switches something on for its indented block only, and switches it back off afterwards, even if the block fails. with torch.no_grad(): turns recording off for the block; with open("notes.txt", "w") as f: opens a file and closes it at the end.

5. Dataset and DataLoader

A Dataset answers two questions: how many examples, and what is example number i. A DataLoader wraps it: shuffles each epoch, groups examples into batches, and can load the next batch on other CPU cores while the GPU works. Here is the same idea in a few lines of plain Python:

from torch.utils.data import DataLoader
from torchvision import datasets, transforms

train = datasets.FashionMNIST("data", train=True, download=True, transform=transforms.ToTensor())
train_loader = DataLoader(train, batch_size=128, shuffle=True, num_workers=2)
x, y = next(iter(train_loader))      # x: (128, 1, 28, 28) images, y: (128,) labels

Why shuffle the training data every epoch?

Data files are often sorted by class or date. Unshuffled, each batch would contain one kind of example and the gradient would swing between them. The test loader doesn't shuffle: order doesn't matter when you only measure.

6. The optimizer

The optimizer turns gradients into weight updates. torch.optim.SGD(model.parameters(), lr=0.1) is chapter 2's rule; torch.optim.AdamW(model.parameters(), lr=1e-3) adds momentum and a separate step size per weight, and is the usual default (stage 4 races them against each other). Either way, the loop doesn't change: zero_grad, backward, step.

The optimizer turns gradients into steps. AdamW adds momentum and a separate step size for each weight, and it's the usual default.

A config says lr=1e-3. What is that as a plain number?

\(10^{-3} = 0.001\) (Start 3's scientific notation). 1e-3 for Adam and 0.1 for plain SGD are common starting points.

7. Habits that save days

A new model's loss won't drop below 2.3 on a 10-class problem, even on one batch. What's most likely?

Knowing the "knows nothing" loss, \(\ln(\text{number of classes})\), is a quick check that training started at all.

8. What to carry forward

All lessons: AI from scratch. The official PyTorch "Learn the Basics" tutorial covers the same ground in more detail.

Last updated