Deep Learning2 min read

PyTorch: understand the gradient lifecycle

A small training loop explains why clearing gradients, backpropagation, and optimizer updates are different steps.

Written by Rajaram Lavudya November 15, 2026

Follow one batch

A training step starts with predictions and a loss. Autograd tracks operations involving tensors that require gradients, allowing the backward pass to calculate derivatives. Those derivatives describe how the current loss changes with the parameters. They do not update the model by themselves.

Separate calculation from update

Calling backward accumulates gradients. Clear them before each independent optimization step, calculate the loss, then ask the optimizer to update parameters. Accumulating across several batches can be intentional, but forgetting to clear them changes the training procedure.

optimizer.zero_grad()
predictions = model(inputs)
loss = loss_fn(predictions, targets)
loss.backward()
optimizer.step()

Debug before scaling

Start with a tiny batch and check that the loss is finite. Inspect whether the expected parameters receive gradients. If training fails, trace the tensor operations before adding a larger model or dataset. A disconnected computation graph cannot be repaired by training for more epochs.

Make a small experiment reproducible

Before changing an architecture, record the dataset split, preprocessing steps, batch size, learning rate, and initialization seed. Keep a small fixed batch available for debugging. Run a few iterations on that batch and inspect the loss and predictions together. If predictions have the wrong shape, do not interpret the loss curve yet. For classification, check that the target representation matches the chosen loss function. A tidy experiment log is more useful than a screenshot of a decreasing number without the settings that produced it.

Keep validation separate from training

Validation asks how the current model behaves without learning from the validation examples. Switch to evaluation mode and disable gradient recording for the validation pass, then return to training mode before the next training phase. These controls have different responsibilities: evaluation mode changes the behavior of relevant layers, while no_grad disables recording for gradient calculation. Keep the validation set out of parameter updates. When comparing experiments, evaluate on the same held-out examples rather than quietly changing the evaluation problem.

model.eval()
with torch.no_grad():
    validation_predictions = model(validation_inputs)
    validation_loss = loss_fn(
        validation_predictions, validation_targets
    )
model.train()

Read the failure before tuning

If a gradient is missing, check which parameters the optimizer owns and whether the loss depends on those parameters. If loss becomes non-finite, inspect the input range and intermediate outputs. If training improves while validation worsens, investigate the data split and model capacity rather than automatically increasing epochs. Save the configuration beside a checkpoint so that the result can be explained later. Treat each run as a hypothesis with a measurable outcome; changing five settings at once makes that hypothesis difficult to evaluate.