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 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.)
Why raise the learning rate when you raise the batch size?
- One step on a batch of \(B\) examples moves the weights by \(\eta\) times the batch's average gradient.
- \(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.
- 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.
- 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
- The curvature limit. The learning rate can't grow forever: past \(2 / \lambda_{\max}\) (calculus 3) training explodes, however big the batch.
- Past the critical batch size. Once the batch gradient's noise is small next to its size, doubling the batch doubles the work per step but barely cuts the number of steps. Each problem has a batch size beyond which more hardware stops buying speed.
- Early training. At the start the gradient changes fast, so step 2 of the argument fails. Big-batch recipes ramp the learning rate up over the first few hundred steps (warmup, calculus 3).
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).
| NumPy | PyTorch | what it does |
|---|---|---|
np.array([1., 2.]) | torch.tensor([1., 2.]) | make an array |
a @ b, a.T, a.shape | the same | matrix 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.grad | every 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?
- To reset the weights
- Because
.backward()adds to.grad: without clearing, every step would include all previous steps' gradients - To reset the learning rate
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?
- So batches differ each epoch and don't follow the file's order (e.g. all the 0s first), which would pull the model one way at a time
- To make the dataset bigger
- So the test score is fair
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?
7. Habits that save days
- Overfit one batch first. Train on a single batch for a few hundred steps: the loss should go to almost zero. If it can't, the bug is in the model or the loop, not the data size. It takes a minute and catches most bugs.
- Print shapes at every step of the forward pass the first time (deep networks, section 2).
- Loss is NaN or explodes: learning rate too high (calculus 3's 2/k limit), or a log of 0 somewhere.
- Loss doesn't move: learning rate too low, forgot
zero_grad/step, or the labels don't match the inputs. - Great training score, bad test score: overfitting (chapter 11), or
.eval()forgotten. - Save what you need to rebuild it:
torch.save(model.state_dict(), "model.pt")stores the weights; the code that builds the model, plus the preprocessing, must travel with them (Start 4).
A new model's loss won't drop below 2.3 on a 10-class problem, even on one batch. What's most likely?
- Overfitting
- Not enough data
- A bug: 2.3 = ln 10 is the loss of guessing uniformly, so nothing is being learned (often a missing optimizer step or zero_grad, or a learning rate of 0)
8. What to carry forward
- The loop: for each epoch, for each batch: forward, loss,
zero_grad,backward,step. - An epoch is one pass over the data; a batch is the handful used for one step. Steps per epoch = examples / batch size.
- Tensors are arrays that can live on a GPU and record operations for autograd.
- An nn.Module owns its parameters; switch
train()/eval(), and evaluate underno_grad(). - A Dataset serves one example; a DataLoader shuffles and batches.
- Overfit one batch first; know that ln(classes) means "learned nothing".
All lessons: AI from scratch. The official PyTorch "Learn the Basics" tutorial covers the same ground in more detail.
Last updated