Simple Algorithm
Deep Learning · Representation · 22 min

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 (N×C×H×WN\times C\times H\times W images, B×T×dB\times T\times d 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:

DataLayout in PyTorchExample
imagesN×C×H×WN\times C\times H\times W: batch, channels, height, width64 RGB images of 224×224224\times224 pixels: 64×3×224×22464\times3\times224\times224
sequencesB×T×dB\times T\times d: batch, position, features32 sequences of 512 tokens of width 768: 32×512×76832\times512\times768
tabular featuresB×dB\times d128 rows of 20 features: 128×20128\times20
class labelsBB integers in {0,…,K−1}\{0,\dots,K-1\}what F.cross_entropy expects next to B×KB\times K logits
The first axis is almost always the batch, and layers act on the trailing axes: nn.Linear on the last one, nn.Conv2d on C×H×WC\times H\times W. One exception to watch: PyTorch's recurrent layers and nn.MultiheadAttention expect T×B×dT\times B\times d 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 (d)(d) is added to every row of a (B,d)(B,d) batch. The same rule produces a classic silent bug:

python
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 error

Nothing 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.

Check your understanding

You want to subtract each example's largest logit from its own row of logits, a tensor of shape (32,10)(32,10). What shape must the tensor of maxima have?

  1. (32)(32), one maximum per example
  2. (32,1)(32,1), as in logits.max(dim=1, keepdim=True).values
  3. (10)(10), one maximum per class
  4. (1,10)(1,10)
Show the answer

B. (32,1)(32,1), as in logits.max(dim=1, keepdim=True).values

Aligned from the right, (32,10)(32,10) and (32,1)(32,1) 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, x~=(x−μtrain)/strain\tilde x=(x-\mu_{\text{train}})/s_{\text{train}}, and apply the same μtrain\mu_{\text{train}} and strains_{\text{train}} 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 BB examples, and each training step processes one, so an epoch takes ⌈n/B⌉\lceil n/B\rceil steps. Small batches give noisy gradient estimates, whose noise falls like 1/B1/\sqrt B, but many steps per epoch; large batches use parallel hardware better. Mini-Batch SGD & Momentum works out the trade-off.

python
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 here

shuffle=True draws a new order every epoch. drop_last=True discards a final partial batch so every step sees BB 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:

python
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 seeLikely causeWhat to try
training loss stuck at its starting value, about log⁡K\log K for KK balanced classesa bug (no gradient reaches the weights, labels misaligned) or a learning rate far too smalloverfit one batch; check that gradients are nonzero
slow, steady, almost linear declinelearning rate too smallraise it by factors of 3 to 10
fast early drop, then large oscillations or sudden jumpslearning rate too largelower it; add warmup or gradient clipping
loss shoots up to inf or NaNdivergence, or a numerical fault such as log⁡0\log0 or overflowlower the rate; find the first NaN
training and validation loss both high and closeunderfitting: model too small, or training too shortbigger model, longer training
training loss falls while validation loss risesoverfittingearly stopping, regularization, more data or augmentation
a plateau, then a sudden dropa learning-rate decay step, or a hard feature finally being learnednothing, if expected
a jagged curvemini-batch noise, which shrinks as the batch growssmooth with a moving average before judging
Curves are evidence, not proof. Before concluding that one setting beats another, compare several runs (Benchmarking Deep Learning Fairly).
Predict before you look

A classifier over K=10K=10 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 1/101/10, so the loss is −log⁡(1/10)=ln⁡10≈2.30-\log(1/10)=\ln10\approx2.30. A starting loss far above this means the network begins confidently wrong, usually a scaling or initialization problem. For 2 classes it would be ln⁡2≈0.69\ln2\approx0.69.

A recipe, and the memory bill

Experienced practitioners converge on the same habits (Bengio, 2012; Karpathy, 2019; Godbole et al., 2023):

  1. Check the loss at initialization: about log⁡K\log K for KK balanced classes; for squared error, about the variance of the targets if the output bias starts at their mean.
  2. 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.
  3. Start from a baseline. Copy the simplest architecture and settings known to work on a similar problem, and get them working before customizing anything.
  4. Change one thing at a time, and keep a change only if it helps by more than the run-to-run noise.
  5. 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 NN parameters trained by Adam in 32-bit floats: the parameters (4N4N bytes), their gradients (4N4N) and Adam's two moment estimates (8N8N), 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).

Predict before you look

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 10910^9 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 N×C×H×WN\times C\times H\times W and sequences B×T×dB\times T\times d. Broadcasting aligns shapes from the right and can silently turn (B,1)−(B)(B,1)-(B) into a (B,B)(B,B) matrix.
  • The loop is forward pass, loss on raw logits, zero_grad, backward, step. train() and eval() switch dropout and batch normalization, no_grad switches off the graph, and a checkpoint saves model and optimizer state.
  • Loss curves diagnose: stuck near log⁡K\log K (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.

Question 1

A training loop calls loss.backward() and opt.step() every step but never opt.zero_grad(). What happens?

  1. Nothing: PyTorch clears gradients automatically after each step
  2. Training raises an error on the second step
  3. The gradients add up across steps, so each update uses the sum of all past gradients
  4. 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.

Question 2

With fixed weights, a network's validation accuracy changes when you change the evaluation batch size. What is the most likely cause?

  1. The model is still in training mode, so batch normalization uses each batch's own statistics
  2. Evaluation ran without torch.no_grad()
  3. The learning rate is too high
  4. 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.

Question 3

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?

  1. Underfitting: train a larger model
  2. The learning rate is too large: lower it
  3. A bug in the validation code: the two losses should always move together
  4. 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.

Question 4

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?

  1. None, as long as the same statistics are applied to every split
  2. Information about the test set leaks into training, so the test estimate becomes optimistic
  3. Standardization should be applied only to the test set
  4. 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

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.