Training a Network in Practice
Tensors, mini-batches, the training loop and reading loss curves.
Everything in this course ends up as a short loop of code that runs millions of times: load a batch, compute the loss, take its gradient, step. Writing the loop is easy. Getting it right, and telling from a loss curve whether it is right, is the craft this lesson teaches.
What you’ll learn
- Track tensor shapes through a model ( images, sequences) and use broadcasting deliberately, including the case where it silently does the wrong thing.
- Build a data pipeline (splits, normalization with training statistics, shuffled mini-batches) and write a PyTorch training loop with evaluation, train and eval modes, and checkpoints.
- Read loss curves: tell underfitting, overfitting, divergence, plateaus and noise apart, and recognize a learning rate that is too large or too small.
- Follow a working recipe (check the initial loss, overfit one batch, start from a baseline, change one thing at a time) and estimate the memory taken by parameters, gradients, optimizer state and activations.
Tensors and shapes
A tensor is a multidimensional array with a shape and a data type. Much of deep learning code is bookkeeping of shapes, and a few conventions cover most of it:
| Data | Layout in PyTorch | Example |
|---|---|---|
| images | : batch, channels, height, width | 64 RGB images of pixels: |
| sequences | : batch, position, features | 32 sequences of 512 tokens of width 768: |
| tabular features | 128 rows of 20 features: | |
| class labels | integers in | what F.cross_entropy expects next to logits |
nn.Linear on the last one, nn.Conv2d on . One exception to watch: PyTorch's recurrent layers and nn.MultiheadAttention expect unless they are created with batch_first=True.Broadcasting combines tensors of different shapes without copying: align the shapes from the right; each pair of sizes must be equal or contain a 1, and a size-1 axis is stretched to match. That is how a bias of shape is added to every row of a batch. The same rule produces a classic silent bug:
import torch
B = 4
pred = torch.randn(B, 1) # model output: one number per example, kept 2-D
y = torch.randn(B) # targets loaded as a flat vector
diff = pred - y # (4, 1) with (4,) broadcasts to (4, 4)
loss = (diff ** 2).mean() # a scalar, but averaged over all 16 pairs (i, j)
print(diff.shape) # torch.Size([4, 4])
loss_ok = ((pred.squeeze(1) - y) ** 2).mean() # the intended errorNothing crashes: the loss is a scalar and training runs, but every prediction is pulled toward the mean of all targets, since that minimizes the average over every pair. F.mse_loss(pred, y) would at least warn about the size mismatch; a hand-written loss does not. Assert shapes where they matter.
You want to subtract each example's largest logit from its own row of logits, a tensor of shape . What shape must the tensor of maxima have?
- , one maximum per example
- , as in
logits.max(dim=1, keepdim=True).values - , one maximum per class
Show the answer
B. , as in logits.max(dim=1, keepdim=True).values
Aligned from the right, and match in the first axis and the size-1 axis stretches across the 10 classes, so each row loses its own maximum. Keeping the reduced axis with keepdim=True is the idiom.
From data to mini-batches
Splits. Split the data once, before looking at it closely: a training set to fit the parameters, a validation set to choose hyperparameters and decide when to stop, and a test set used once, at the end. Split by the unit you want to generalize over: by patient for medical images, by speaker for speech, by time for forecasting. Near-duplicates on both sides of a split inflate every score.
Input normalization. Standardize inputs with statistics of the training set only, , and apply the same and to validation and test data (for images, a mean and standard deviation per channel). Statistics computed on all the data leak information about the test set into training.
Mini-batches. Each epoch the training set is shuffled and cut into mini-batches of examples, and each training step processes one, so an epoch takes steps. Small batches give noisy gradient estimates, whose noise falls like , but many steps per epoch; large batches use parallel hardware better. Mini-Batch SGD & Momentum works out the trade-off.
from torch.utils.data import DataLoader, TensorDataset
mean, std = X_train.mean(dim=0), X_train.std(dim=0) # training statistics only
def norm(X):
return (X - mean) / (std + 1e-8)
train_ds = TensorDataset(norm(X_train), y_train)
val_ds = TensorDataset(norm(X_val), y_val)
train_loader = DataLoader(train_ds, batch_size=128, shuffle=True, drop_last=True)
val_loader = DataLoader(val_ds, batch_size=512) # order does not matter hereshuffle=True draws a new order every epoch. drop_last=True discards a final partial batch so every step sees examples, which keeps the gradient noise and batch-normalization statistics uniform.
The training loop
Here is the whole training loop for a classifier, with validation and a checkpoint every epoch. Every line has a job:
import torch
import torch.nn.functional as F
model = MyNet().to(device)
opt = torch.optim.AdamW(model.parameters(), lr=3e-4, weight_decay=0.01)
for epoch in range(num_epochs):
model.train() # dropout on; batchnorm uses batch statistics
for x, y in train_loader:
x, y = x.to(device), y.to(device)
logits = model(x) # forward pass, shape (B, K)
loss = F.cross_entropy(logits, y) # takes raw logits: softmax is inside
opt.zero_grad(set_to_none=True) # clear the previous step's gradients
loss.backward() # backward pass: fills p.grad
opt.step() # update the parameters
model.eval() # dropout off; batchnorm uses running stats
total = 0.0
with torch.no_grad(): # build no graph: less memory, faster
for x, y in val_loader:
logits = model(x.to(device))
total += F.cross_entropy(logits, y.to(device), reduction='sum').item()
val_loss = total / len(val_loader.dataset)
torch.save({'model': model.state_dict(), 'opt': opt.state_dict(),
'epoch': epoch}, 'checkpoint.pt')Save the optimizer's state with the model: AdamW's moment estimates are part of the training state, and resuming without them changes the run. Summing the validation loss with reduction='sum' and dividing by the dataset size keeps a smaller final batch from being overweighted.
Gradients accumulate. loss.backward() adds into each parameter's .grad. That is useful for summing gradients over several micro-batches before one step, and a bug when zero_grad is forgotten.
Modes and graphs are separate switches. model.train() and model.eval() change layers that behave differently in training and inference, such as dropout and batch normalization; they do not stop gradients. torch.no_grad() stops the autograd graph from being built; it does not change those layers. Evaluation needs both.
Reading loss curves
Log the training loss every few steps and the validation loss every epoch, on a logarithmic axis when the loss spans orders of magnitude. The shapes are diagnostic:
| What you see | Likely cause | What to try |
|---|---|---|
| training loss stuck at its starting value, about for balanced classes | a bug (no gradient reaches the weights, labels misaligned) or a learning rate far too small | overfit one batch; check that gradients are nonzero |
| slow, steady, almost linear decline | learning rate too small | raise it by factors of 3 to 10 |
| fast early drop, then large oscillations or sudden jumps | learning rate too large | lower it; add warmup or gradient clipping |
| loss shoots up to inf or NaN | divergence, or a numerical fault such as or overflow | lower the rate; find the first NaN |
| training and validation loss both high and close | underfitting: model too small, or training too short | bigger model, longer training |
| training loss falls while validation loss rises | overfitting | early stopping, regularization, more data or augmentation |
| a plateau, then a sudden drop | a learning-rate decay step, or a hard feature finally being learned | nothing, if expected |
| a jagged curve | mini-batch noise, which shrinks as the batch grows | smooth with a moving average before judging |
A classifier over balanced classes is initialized so that all its logits are nearly zero. What cross-entropy loss should it show before any training?
Show the answer
2.3
Equal logits give every class probability , so the loss is . A starting loss far above this means the network begins confidently wrong, usually a scaling or initialization problem. For 2 classes it would be .
A recipe, and the memory bill
Experienced practitioners converge on the same habits (Bengio, 2012; Karpathy, 2019; Godbole et al., 2023):
- Check the loss at initialization: about for balanced classes; for squared error, about the variance of the targets if the output bias starts at their mean.
- Overfit one small batch. A handful of examples, many steps, no regularization: the training loss should go nearly to zero. If it cannot, there is a bug.
- Start from a baseline. Copy the simplest architecture and settings known to work on a similar problem, and get them working before customizing anything.
- Change one thing at a time, and keep a change only if it helps by more than the run-to-run noise.
- Log everything: configuration, code version, random seeds, losses, learning rate and gradient norms. A result you cannot reproduce cannot be trusted.
The memory bill. Training keeps four kinds of numbers in memory. With parameters trained by Adam in 32-bit floats: the parameters ( bytes), their gradients () and Adam's two moment estimates (), 16 bytes per parameter before any data is touched. On top come the activations the forward pass saves for the backward pass, which grow linearly with the batch size and the depth. When memory runs out, shrink the batch (keeping the effective batch by accumulating gradients over several micro-batches before each step), recompute activations instead of storing them (gradient checkpointing), or use lower-precision formats (Hardware, Precision & Parallelism).
How many gigabytes do the parameters, gradients and Adam state of a model with one billion parameters occupy in 32-bit floats, before counting activations?
Show the answer
16 GB
16 bytes per parameter times parameters is 16 GB. Mixed precision does not shrink this state: 2 bytes each for the 16-bit weights and gradients plus 12 bytes for the 32-bit master copy and Adam's two moments still total about 16 bytes per parameter. Splitting this state across devices is the subject of Data, Tensor & Pipeline Parallelism.
Key takeaways
- Get the shapes right first: images are and sequences . Broadcasting aligns shapes from the right and can silently turn into a matrix.
- The loop is forward pass, loss on raw logits,
zero_grad,backward,step.train()andeval()switch dropout and batch normalization,no_gradswitches off the graph, and a checkpoint saves model and optimizer state. - Loss curves diagnose: stuck near (a bug), a slow linear decline (rate too small), oscillation or explosion (rate too large), training falling while validation rises (overfitting), both high (underfitting).
- Work incrementally: check the initial loss, overfit one batch, start from a baseline, change one thing at a time, log everything, and tune the learning rate first.
- Adam in 32-bit floats needs 16 bytes per parameter before activations, which grow with batch size and depth.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A training loop calls loss.backward() and opt.step() every step but never opt.zero_grad(). What happens?
- Nothing: PyTorch clears gradients automatically after each step
- Training raises an error on the second step
- The gradients add up across steps, so each update uses the sum of all past gradients
- Only the first step updates the weights
Show the answer
C. The gradients add up across steps, so each update uses the sum of all past gradients
backward() accumulates into .grad. Without clearing, the update direction becomes a running sum of old gradients and the effective step grows every iteration. Accumulation is deliberate only when summing micro-batches before one step.
With fixed weights, a network's validation accuracy changes when you change the evaluation batch size. What is the most likely cause?
- The model is still in training mode, so batch normalization uses each batch's own statistics
- Evaluation ran without
torch.no_grad() - The learning rate is too high
- The validation set was shuffled
Show the answer
A. The model is still in training mode, so batch normalization uses each batch's own statistics
In train() mode, batch normalization standardizes with the current batch's mean and variance, and dropout is active, so outputs depend on batch composition and randomness. model.eval() switches to the running statistics and disables dropout.
The training loss keeps falling, while the validation loss falls for 10 epochs and then rises steadily. What is happening, and what is a sensible response?
- Underfitting: train a larger model
- The learning rate is too large: lower it
- A bug in the validation code: the two losses should always move together
- Overfitting: stop near the validation minimum, regularize, or add data
Show the answer
D. Overfitting: stop near the validation minimum, regularize, or add data
A widening gap between a falling training loss and a rising validation loss is the signature of overfitting. Keep the checkpoint with the lowest validation loss (early stopping) and add regularization, augmentation or data.
Before splitting your data into training, validation and test sets, you compute each feature's mean and standard deviation on all of it and standardize every example with them. What goes wrong?
- None, as long as the same statistics are applied to every split
- Information about the test set leaks into training, so the test estimate becomes optimistic
- Standardization should be applied only to the test set
- The model will not train, because standardized inputs have zero mean
Show the answer
B. Information about the test set leaks into training, so the test estimate becomes optimistic
The preprocessing has seen the test data. With a large dataset the effect may be small, but the habit matters: fit every preprocessing statistic on the training set alone and apply it unchanged to the other splits.
Go deeper
- Diagnosing Training Failures · Loss curves, gradient statistics, NaNs and the tests that catch silent bugs.
- Tuning Deep Networks on a Budget · Which hyperparameters matter, in what order, and how to search them.
- Benchmarking Deep Learning Fairly · Seed variance, tuning budgets and time-to-result: comparing training methods honestly.
Further reading
- A. Zhang, Z. C. Lipton, M. Li & A. J. Smola, Dive into Deep Learning (Cambridge University Press, 2023), free at d2l.ai.
- I. Goodfellow, Y. Bengio & A. Courville, Deep Learning, ch. 11 "Practical Methodology" (MIT Press, 2016).
- Y. Bengio, "Practical recommendations for gradient-based training of deep architectures," in Neural Networks: Tricks of the Trade, 2nd ed. (Springer, 2012); arXiv:1206.5533.
- A. Karpathy, "A recipe for training neural networks," blog post (2019).
- V. Godbole, G. E. Dahl, J. Gilmer, C. J. Shallue & Z. Nado, Deep Learning Tuning Playbook, version 1 (2023), github.com/google-research/tuning_playbook.