Write a PyTorch training loop from scratch
Train a small network on a CPU with tensors, a DataLoader, a forward pass, a loss, autograd and an optimiser.
By Invicly Tech, , in AI and Machine Learning with Python. About 11 minutes to read.
In short
A PyTorch training loop is a few lines you write yourself: take a batch, run the model forward, measure the loss, let autograd compute gradients, and let the optimiser nudge the weights. Writing it by hand on a CPU shows exactly where data, shapes and gradients flow, which makes every later bug easier to find.
Think of it like this: Training is like tuning a guitar by ear: play a note (forward), hear how far off it is (loss), work out which way to turn each peg (gradients), then turn them a little (optimiser step).
Explained simply
PyTorch is a Python library for building and training neural networks. Its core object is the tensor, which is an array like a NumPy array but able to remember the maths done to it. That memory is what lets PyTorch work out gradients automatically.
A neural network is a function with many adjustable numbers called weights. Training means showing it examples, measuring how wrong its answers are with a loss function, and changing the weights a little so the next answer is less wrong. You repeat that thousands of times.
Unlike scikit-learn, where fit() hides the work, PyTorch asks you to write the loop yourself. That feels like extra effort at first. In return you can see and change every step, print any shape, and stop to inspect a gradient when something looks odd.
You do not need a graphics card for this topic. A small network on a few thousand rows of tabular data, or on 28 by 28 pixel images, trains in seconds to a few minutes on an ordinary laptop CPU.
Press Play on a diagram to walk through it one step at a time.
- 1Get a batch
DataLoader yields inputs X and targets y
- 2Forward pass
logits = model(X)
- 3Loss
loss = loss_fn(logits, y)
- 4Backward
zero old gradients, then loss.backward()
- 5Optimiser step
optimizer.step() updates the weights
- Back to step 1
- 1Training loop
Your Python for-loop over epochs and batches
- 2Optimiser
torch.optim.SGD or AdamW updates parameters
- 3Model
An nn.Module with layers and a forward method
- 4DataLoader
Shuffles and batches samples from a Dataset
- 5Tensors and autograd
Arrays that remember how they were computed
- Shape errors
- Forgot to flatten images
- Wrong in_features on first layer
- Targets one-hot instead of indices
- Dtype errors
- float64 input with float32 weights
- Float targets for CrossEntropyLoss
- Loss flat
- Learning rate too low
- zero_grad or step missing
- Labels shuffled separately from inputs
- Loss explodes
- Learning rate too high
- Unscaled input features
In depth
Setting up a CPU-only environment
Create a fresh virtual environment and install PyTorch using the selector on the PyTorch Get Started page; choose your operating system, pip and CPU. On Linux the CPU-only wheels come from a separate package index and are much smaller than the default CUDA build. Pin the exact version in requirements.txt once it works, because behaviour and defaults change between releases.
Check the install with a two-line script: import torch, print torch.__version__ and torch.cuda.is_available(). On a laptop without an NVIDIA GPU the second value is False, which is fine. Write your code with a device variable so the same script runs on a GPU later without edits. To clean up, deactivate and delete the virtual environment folder; nothing is installed system-wide.
- python -m venv .venv, then activate it
- Install torch from the CPU index the selector shows
- device = "cuda" if torch.cuda.is_available() else "cpu"
- Move both model and batches with .to(device)
Tensors, shapes and dtypes
A batch of tabular data is a 2D tensor of shape (batch, features). A batch of greyscale images is 4D: (batch, channels, height, width), so 64 Fashion-MNIST images are (64, 1, 28, 28). A dense layer wants 2D input, so you flatten images to (64, 784) with nn.Flatten() or x.view(x.size(0), -1).
Dtypes matter too. Weights and inputs are usually float32. Classification targets for CrossEntropyLoss must be integer class indices (torch.long), not one-hot floats. Mixing float64 NumPy arrays with float32 weights raises a dtype error, so convert with torch.tensor(arr, dtype=torch.float32). When a line fails, printing x.shape and x.dtype just before it solves most problems.
- reshape and view change shape without changing data
- unsqueeze(0) adds a batch dimension of size 1
- Matrix multiply needs inner sizes to match: (64, 784) @ (784, 10)
- item() turns a one-element tensor into a Python number
Dataset and DataLoader
A Dataset is any class with __len__ and __getitem__ that returns one sample, such as (features, label). TensorDataset wraps tensors you already have, and torchvision.datasets.FashionMNIST downloads a ready image set of 60,000 training and 10,000 test images. The DataLoader takes a Dataset and yields batches, shuffling the training set each epoch so the model does not learn the order.
Keep shuffle=True for training and shuffle=False for validation. Start with num_workers=0 on a laptop; extra worker processes help with slow disk or heavy augmentation but add start-up time and platform quirks. A batch size of 32 to 128 is a good default for small CPU work.
- Training loop to DataLoader: next batch, please1next batch, please
- DataLoader to Dataset: __getitem__(i) for 64 shuffled indices2__getitem__(i) for 64 shuffled indices
- Dataset to DataLoader: 64 (x, y) samples364 (x, y) samples
- DataLoader to Training loop: stacked tensors X (64, ...) and y (64,)4stacked tensors X (64, ...) and y (64,)
Autograd and the optimiser step
Every parameter of an nn.Module has requires_grad=True. As the forward pass runs, autograd records a graph of the operations. Calling loss.backward() walks that graph from the loss back to each parameter and stores the gradient in param.grad. The optimiser then reads those gradients and updates the weights: plain SGD subtracts learning rate times gradient, while Adam and AdamW also keep running averages per parameter.
Gradients accumulate by design, which is useful for simulating big batches, so you must clear them with optimizer.zero_grad() each step. The order inside the loop is fixed: zero_grad, forward, loss, backward, step. Swapping backward and step means you update with stale gradients.
Evaluating honestly inside the loop
After each epoch, measure the model on a validation set it never trains on. Call model.eval() first so layers such as dropout and batch normalisation switch to inference behaviour, and wrap the loop in torch.no_grad() so no graph is built. Sum the loss and the number of correct predictions over all batches, then divide by the number of samples, not the number of batches, because the last batch is often smaller. Call model.train() again before the next training epoch. Compare the result with a simple baseline from earlier modules, such as logistic regression, so you know whether the network is earning its extra complexity.
Learn it in 5 short steps
About 50m each. Track them with a timer in your plan.
- 1Create and reshape tensors~50m
- 2Load batches with Dataset and DataLoader~50m
- 3Define a model with nn.Module~50m
- 4Compute loss and call backward~50m
- 5Step the optimiser and evaluate~50m
Key points
- A tensor is an n-dimensional array; most bugs are shape bugs, so print shapes early.
- Dataset returns one sample; DataLoader groups samples into shuffled batches.
- Call optimizer.zero_grad() every step, because PyTorch adds new gradients to old ones.
- Switch to model.eval() and torch.no_grad() when you measure validation loss.
- A small fully connected network trains in seconds on a laptop CPU; no GPU is needed.
Key terms
Tap a card to flip it. 0/6 known
Examples
import torch
from torch import nn
torch.manual_seed(0)
X = torch.randn(256, 4)
y = (X[:, 0] + X[:, 1] > 0).long()
model = nn.Sequential(nn.Linear(4, 16), nn.ReLU(), nn.Linear(16, 2))
opt = torch.optim.SGD(model.parameters(), lr=0.1)
loss_fn = nn.CrossEntropyLoss()
for epoch in range(50):
opt.zero_grad()
loss = loss_fn(model(X), y)
loss.backward()
opt.step()
print(f"final loss {loss.item():.3f}")A full-batch loop on synthetic data; the loss should fall well below its starting value of about 0.69.
Fashion-MNIST with a small dense network on a CPU
Prerequisites: a virtual environment with torch and torchvision. Step 1: download the dataset with ToTensor so pixels become floats between 0 and 1. Step 2: build DataLoaders with batch size 64. Step 3: define a model of Flatten, Linear(784, 128), ReLU, Linear(128, 10). Step 4: train for 3 epochs with SGD at lr 0.1. Expected evidence: training loss drops from about 2.3 (random guessing over 10 classes) towards 0.4, and test accuracy lands in the mid 80s percent. Each epoch takes well under a minute on a modern laptop. Cleanup: delete the data folder, about 80 MB once extracted.
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor
train = datasets.FashionMNIST("data", train=True, download=True, transform=ToTensor())
test = datasets.FashionMNIST("data", train=False, download=True, transform=ToTensor())
train_dl = DataLoader(train, batch_size=64, shuffle=True)
test_dl = DataLoader(test, batch_size=256)
model = nn.Sequential(nn.Flatten(), nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 10))Writing the evaluation function correctly
A team reported 97 percent accuracy, but they averaged per-batch accuracy and left dropout on. Step 1: switch to model.eval() and torch.no_grad(). Step 2: accumulate total loss weighted by batch size and the count of correct predictions. Step 3: divide by len(dataloader.dataset). Step 4: return to model.train() afterwards. With the fix the honest figure was a little lower and, more importantly, stable from run to run.
def evaluate(model, dl, loss_fn):
model.eval()
total, correct, n = 0.0, 0, 0
with torch.no_grad():
for X, y in dl:
logits = model(X)
total += loss_fn(logits, y).item() * len(y)
correct += (logits.argmax(1) == y).sum().item()
n += len(y)
model.train()
return total / n, correct / nQuick reference
- Step order: zero_grad, forward, loss, backward, step
- Images are (batch, channels, height, width); dense layers need (batch, features)
- CrossEntropyLoss takes raw logits and long class indices
- model.eval() plus torch.no_grad() for validation; model.train() before training
- Starting loss for k balanced classes is about ln(k): 0.69 for 2, 2.30 for 10
- Print x.shape and x.dtype right before the line that fails
- Keep a device variable so the same code runs on CPU or GPU
Common mistakes
- Forgetting optimizer.zero_grad(), so gradients pile up across steps and training goes unstable.
- Applying softmax before nn.CrossEntropyLoss, which already expects raw logits.
- Evaluating with dropout still active because model.eval() was never called.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Create a tensor of shape (8, 1, 28, 28), flatten it for a dense layer, and print both shapes.
- Exercise 2medium
Wrap synthetic tensors X (1000, 4) and y (1000,) in a TensorDataset, split 800/200 with random_split and a seeded generator, and build training and validation DataLoaders.
- Exercise 3hard
Write train_one_epoch(model, dl, opt, loss_fn) that returns the sample-weighted mean training loss, and use it with your evaluate function to print both losses for 10 epochs.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Do I need a GPU to learn PyTorch?
- No. Small models on tabular data or small images train fine on a CPU. A GPU matters for large images, long sequences or big models, and free hosted notebooks can provide one when you need it.
- Should I use SGD or Adam?
- Adam or AdamW usually converges faster with less tuning, so they are good defaults. Well-tuned SGD with momentum is still common for image models and sometimes generalises slightly better.
- What is the difference between PyTorch and scikit-learn?
- scikit-learn offers ready-made classical models with a fit and predict interface. PyTorch is a lower-level toolkit for building and training neural networks, where you write the training loop yourself.