TExcelTAD

The Same Loop in PyTorch

You have written the training loop twice in NumPy, and each time most of the code was the backward pass: the gradients of every parameter, derived by hand. A deep-learning framework removes exactly that part. In PyTorch you write the forward pass, and autograd records the operations and computes all the gradients with one call to loss.backward(). The rest of the loop (batches, epochs, the update, validation, checkpoints) is still yours, and it maps line by line onto the nine boxes of the training loop.

The examples on this page are recorded: PyTorch does not run in the browser, so they show the output of a real run on a CPU (see the note on each example). The NumPy lessons before this one run live.

The PyTorch names for the nine boxes

Box NumPy (previous lesson) PyTorch
1 batch order = rng.permutation(n), X[idx] DataLoader(dataset, batch_size=32, shuffle=True)
2-3 forward, prediction forward(P, X) logits = model(xb), a nn.Module
4 loss bce(p, y) loss_fn(logits, yb) with nn.BCEWithLogitsLoss()
5 backprop backward(P, X, y, p, cache) loss.backward() fills param.grad
6 update P[k] - lr * grads[k] optimizer.step(), after optimizer.zero_grad()
8 validation evaluate(P, X_val, y_val) model.eval() and with torch.no_grad():
9 save best = P (new dict each step) torch.save(model.state_dict(), buffer)

Three details have no NumPy counterpart:

  • optimizer.zero_grad(). PyTorch adds new gradients to param.grad. Without zeroing, every step would use the sum of all gradients so far.
  • model.train() and model.eval(). They switch layers that behave differently in training and inference, such as dropout and batch normalisation. This tiny network has neither, but the habit matters.
  • torch.no_grad(). Inside it, autograd records nothing, so validation uses less memory and cannot leak into the gradients.

nn.BCEWithLogitsLoss takes the logit zz rather than the probability: it computes log⁡(1+ez)−yz\log(1 + e^{z}) - yz in a numerically stable way, so the model's last layer has no sigmoid.

The idiomatic loop

The same moons, split and network as in the NumPy MLP lesson: 400 training points, 100 for validation, 100 for the test, a 2-16-1 ReLU network, SGD with learning rate 0.3, batch size 32, 150 epochs. The best weights are saved with torch.save into an in-memory buffer (in a real project, a file such as best.pt) and loaded back before the test.

python · try it yourself
import io
import numpy as np
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split

torch.manual_seed(0)
X, y = make_moons(n_samples=600, noise=0.25, random_state=0)
X_tr, X_tmp, y_tr, y_tmp = train_test_split(X, y, test_size=200, random_state=0)
X_val, X_te, y_val, y_te = train_test_split(X_tmp, y_tmp, test_size=100, random_state=0)
mu, sd = X_tr.mean(axis=0), X_tr.std(axis=0)
to_t = lambda a: torch.tensor(a, dtype=torch.float32)
X_tr, X_val, X_te = (to_t((a - mu) / sd) for a in (X_tr, X_val, X_te))
y_tr, y_val, y_te = (to_t(a) for a in (y_tr, y_val, y_te))

train_loader = DataLoader(TensorDataset(X_tr, y_tr), batch_size=32, shuffle=True)
model = nn.Sequential(nn.Linear(2, 16), nn.ReLU(), nn.Linear(16, 1))
loss_fn = nn.BCEWithLogitsLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.3)
print("parameters:", sum(p.numel() for p in model.parameters()))

def evaluate(X, y):
    model.eval()                                    # inference mode for dropout / batch norm
    with torch.no_grad():                           # no graph, no gradients
        logits = model(X).squeeze(1)
        return loss_fn(logits, y).item(), ((logits > 0).float() == y).float().mean().item()

best_loss, buffer = float("inf"), io.BytesIO()
for epoch in range(1, 151):
    model.train()
    for xb, yb in train_loader:                     # 1 batch
        logits = model(xb).squeeze(1)               # 2-3 forward
        loss = loss_fn(logits, yb)                  # 4 loss
        optimizer.zero_grad()                       # clear old gradients
        loss.backward()                             # 5 backprop (autograd)
        optimizer.step()                            # 6 update
    val_loss, val_acc = evaluate(X_val, y_val)      # 8 validation
    if val_loss < best_loss:                        # 9 checkpoint
        best_loss, best_epoch = val_loss, epoch
        buffer.seek(0); buffer.truncate()
        torch.save(model.state_dict(), buffer)
    if epoch in (1, 30, 150):
        tr_loss, tr_acc = evaluate(X_tr, y_tr)
        print(f"epoch {epoch:3d}  train loss {tr_loss:.4f} acc {tr_acc:.3f}   val loss {val_loss:.4f} acc {val_acc:.3f}")

buffer.seek(0)
model.load_state_dict(torch.load(buffer))           # restore the best checkpoint
print("best epoch", best_epoch, " val loss", round(best_loss, 4))
te_loss, te_acc = evaluate(X_te, y_te)
print(f"test (once): loss {te_loss:.4f}  accuracy {te_acc:.3f}")
parameters: 65
epoch   1  train loss 0.4180 acc 0.842   val loss 0.4051 acc 0.850
epoch  30  train loss 0.2217 acc 0.908   val loss 0.2750 acc 0.880
epoch 150  train loss 0.1128 acc 0.955   val loss 0.1929 acc 0.900
best epoch 139  val loss 0.1783
test (once): loss 0.2481  accuracy 0.910

The run looks like the NumPy one without being identical: PyTorch starts from its own random weights (a uniform distribution scaled by the fan-in) and shuffles with its own generator, so after the first epoch the validation loss is 0.4051 rather than 0.3195. It ends in the same place: training accuracy 0.955, the best validation loss 0.1783 at epoch 139, and 0.910 test accuracy on the 100 held-out points (the NumPy run had 0.920, a difference of one point). Two runs of the same recipe with different seeds differ by about that much, which is worth remembering before you declare one model better than another.

Same model, same numbers

Is PyTorch doing the same arithmetic as the NumPy loop? Give it the same starting weights, the same batch order and the same precision (float64), and the losses must agree. This run draws the initial weights and the batch permutations from the same NumPy generator as the NumPy lesson, copies the weights into the nn.Linear layers (PyTorch stores a weight matrix as output by input, the transpose of the NumPy W1W_1), and feeds the batches through a DataLoader with an explicit batch_sampler.

python · try it yourself
import numpy as np
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split

X, y = make_moons(n_samples=600, noise=0.25, random_state=0)
X_tr, X_tmp, y_tr, y_tmp = train_test_split(X, y, test_size=200, random_state=0)
X_val, X_te, y_val, y_te = train_test_split(X_tmp, y_tmp, test_size=100, random_state=0)
mu, sd = X_tr.mean(axis=0), X_tr.std(axis=0)
X_tr, X_val = torch.tensor((X_tr - mu) / sd), torch.tensor((X_val - mu) / sd)   # float64
y_tr, y_val = torch.tensor(y_tr, dtype=torch.float64), torch.tensor(y_val, dtype=torch.float64)

rng = np.random.default_rng(0)                     # same generator, same draws as the NumPy lesson
W1, w2 = rng.normal(0, 1, (2, 16)), rng.normal(0, np.sqrt(1 / 16), 16)
model = nn.Sequential(nn.Linear(2, 16), nn.ReLU(), nn.Linear(16, 1)).double()
with torch.no_grad():
    model[0].weight.copy_(torch.tensor(W1.T)); model[0].bias.zero_()
    model[2].weight.copy_(torch.tensor(w2[None, :])); model[2].bias.zero_()

loss_fn = nn.BCEWithLogitsLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.3)
data = TensorDataset(X_tr, y_tr)
for epoch in range(1, 151):
    order = rng.permutation(len(y_tr))
    batches = [order[s:s + 32].tolist() for s in range(0, len(order), 32)]
    model.train()
    for xb, yb in DataLoader(data, batch_sampler=batches):
        loss = loss_fn(model(xb).squeeze(1), yb)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
    if epoch in (1, 10, 30, 60, 100, 150):
        model.eval()
        with torch.no_grad():
            tr = loss_fn(model(X_tr).squeeze(1), y_tr).item()
            va = loss_fn(model(X_val).squeeze(1), y_val).item()
        print(f"epoch {epoch:3d}  train loss {tr:.4f}   val loss {va:.4f}")
epoch   1  train loss 0.3101   val loss 0.3195
epoch  10  train loss 0.2370   val loss 0.3028
epoch  30  train loss 0.1596   val loss 0.2148
epoch  60  train loss 0.1220   val loss 0.1889
epoch 100  train loss 0.1119   val loss 0.2022
epoch 150  train loss 0.1089   val loss 0.1871

Every line equals the NumPy run to four decimals, from 0.3101 after the first epoch to 0.1089 / 0.1871 after the last. The hand-written backward pass and autograd computed the same gradients for 1950 updates. That is the payoff of the NumPy lessons: PyTorch is not a different algorithm, it is the same loop with the bookkeeping automated.

Pitfalls

  • Forgetting optimizer.zero_grad(). Gradients accumulate across steps; training still "works" for a while, with an effective step that keeps growing. (Accumulating on purpose over several small batches is a real technique, gradient accumulation, but then you zero after the update.)
  • Validating in train mode. With dropout active, the validation loss is noisy and too high; with batch norm, validation batches change the running statistics. Call model.eval(), and model.train() again before the next epoch.
  • Saving model.state_dict() by reference. best = model.state_dict() holds references to the live tensors, which keep changing. Serialise it (torch.save to a file or buffer) or copy.deepcopy it.
  • Applying a sigmoid before BCEWithLogitsLoss. The loss applies its own; a double sigmoid squashes the gradients and trains badly without any error message.
  • float32 versus float64. PyTorch defaults to 32-bit floats and NumPy to 64-bit. Mixed inputs raise a dtype error; silently converted ones give results that differ in the fourth or fifth digit.

Practice

  1. Rewrite the inner loop for gradient accumulation over 4 batches: the parameters are updated once every 4 batches with the average gradient.
Answer
python
optimizer.zero_grad()
for i, (xb, yb) in enumerate(train_loader):
    loss = loss_fn(model(xb).squeeze(1), yb) / 4      # average over 4 batches
    loss.backward()                                   # adds to .grad
    if (i + 1) % 4 == 0:
        optimizer.step()
        optimizer.zero_grad()

Accumulation simulates a 4 times larger batch when the large batch does not fit in memory.

  1. Why does the first example print a different validation loss at epoch 1 than the second (and the NumPy lesson)?
Answer

It uses PyTorch's own random initialisation (nn.Linear draws from a uniform distribution based on the fan-in), PyTorch's shuffling and 32-bit floats. Same model and data, different random start and batch order, so the trajectory differs. Only when all three are matched, as in the second example, do the numbers agree.

  1. Which line of the PyTorch loop corresponds to the function backward you wrote in NumPy, and what does it produce?
Answer

loss.backward(). It walks the recorded graph from the loss back to the parameters and stores ∂L/∂θ\partial L / \partial \theta in each parameter's .grad attribute, which optimizer.step() then reads.

Test yourself

What does loss.backward() do?

  1. Updates the parameters
  2. Computes the gradient of the loss with respect to every parameter and adds it to .grad
  3. Reverses the last update
  4. Evaluates the model on the validation set

Why must optimizer.zero_grad() be called every step?

  1. To reset the learning rate
  2. Because PyTorch accumulates gradients in .grad instead of overwriting them
  3. To free the model's memory
  4. To switch to evaluation mode

What does with torch.no_grad(): change during validation?

  1. It sets dropout to inference mode
  2. Autograd records no operations, so no gradients are computed and memory is saved
  3. It freezes the batch-norm statistics
  4. It disables the loss function

Why does the last layer of the model have no sigmoid?

  1. Sigmoids are not available in PyTorch
  2. nn.BCEWithLogitsLoss applies the sigmoid inside the loss, in a numerically stable form
  3. The network predicts regression targets
  4. A sigmoid would make the model linear