← Journal

Moving to PyTorch: write the training loop yourself

Week 8

I wrote a plain training loop for a small classifier instead of using a trainer wrapper. It was slower to start and taught me more.

for epoch in range(epochs):
    model.train()
    for xb, yb in train_loader:
        optimizer.zero_grad()
        loss = loss_fn(model(xb), yb)
        loss.backward()
        optimizer.step()

Debugging habit that paid off

When loss would not fall, I tried to overfit a single batch. If the model cannot memorise sixteen examples, the problem is in the code, not the data. Twice it was a missing zero_grad() and a wrong label dtype.

Also learned

Seed everything, log every run, and keep train and eval modes straight. Forgetting model.eval() gave me noisy validation numbers for a full day.