30 Mins

5. Training Loops & Optimizers

The Anatomy of a Training Step

A training step in PyTorch is an iterative process that refines model weights to minimize an error function. It begins with the zero_grad() method, which is crucial because PyTorch accumulates gradients by default. If you do not clear them, gradients from previous batches would be added to the current ones, resulting in incorrect parameter updates.

Following the zeroing of gradients, the model executes a forward pass where input data propagates through the layers to generate predictions. The loss function then quantifies the discrepancy between these predictions and the target labels. Once the loss is computed, the backward() call performs backpropagation, calculating the gradient of the loss with respect to every model parameter. Finally, optimizer.step() updates the model parameters based on the stored gradients and the specific optimization algorithm's logic.

Operator Note: Always call zero_grad() before calculating the loss. In some complex architectures like RNNs or GANs, you might need to perform zero_grad() at different stages of the loop.
Python 3
import torch
import torch.nn as nn
import torch.optim as optim

# Dummy data and model
model = nn.Linear(10, 1)
optimizer = optim.SGD(model.parameters(), lr=0.01)
criterion = nn.MSELoss()

# Mock training step
inputs = torch.randn(32, 10)
targets = torch.randn(32, 1)

optimizer.zero_grad() # Clear previous gradients
outputs = model(inputs) # Forward pass
loss = criterion(outputs, targets) # Loss calculation
loss.backward() # Backward pass (compute gradients)
optimizer.step() # Update parameters

Configuring Optimizers and Learning Rates

Optimizers are the engines that drive weight updates. SGD (Stochastic Gradient Descent) is the foundational optimizer that updates parameters by shifting them in the opposite direction of the gradient, scaled by the learning rate. While reliable, it can be sensitive to the choice of learning rate, often requiring learning rate schedulers to reach global minima efficiently.

Conversely, Adaptive Optimizers like Adam (Adaptive Moment Estimation) maintain per-parameter learning rates by tracking the first and second moments of the gradients. Adam is generally more robust to initial hyperparameter settings, making it the preferred choice for most deep learning applications. Understanding how to instantiate these objects with model parameters and learning rates is essential for convergence management.

Operator Note: A learning rate that is too high will cause loss divergence (exploding gradients), while a rate that is too low will lead to excruciatingly slow convergence or premature stalling in local minima.
Python 3
model = nn.Linear(5, 2)

# SGD with momentum helps overcome local minima
opt_sgd = optim.SGD(model.parameters(), lr=0.01, momentum=0.9)

# Adam is generally more stable for large models
opt_adam = optim.Adam(model.parameters(), lr=0.001, betas=(0.9, 0.999))

print(f'Using optimizer: {type(opt_adam).__name__}')

Selecting Loss Functions for Tasks

Choosing the right objective function is as important as the model architecture itself. For regression tasks where the output is a continuous value, nn.MSELoss (Mean Squared Error) is standard. It heavily penalizes outliers due to the squaring of differences, which can be both a strength and a weakness depending on your noise distribution.

For classification tasks, nn.CrossEntropyLoss is the industry standard. Notably, PyTorch's CrossEntropyLoss integrates the LogSoftmax and NLLLoss (Negative Log Likelihood) into a single, numerically stable implementation. When using this, ensure your final layer has no activation function (like Softmax), as it is handled internally by the loss function.

Operator Note: In PyTorch's nn.CrossEntropyLoss, input tensors must be logits (raw values), not probabilities. Never apply torch.softmax before passing outputs into this loss function.
Python 3
import torch.nn.functional as F

# Regression Example
loss_reg = nn.MSELoss()

# Classification Example: Raw logits output expected
loss_cls = nn.CrossEntropyLoss()
logits = torch.randn(3, 5, requires_grad=True) # 3 samples, 5 classes
targets = torch.tensor([1, 0, 4]) # Ground truth indices

output_loss = loss_cls(logits, targets)
print(f'Cross Entropy Loss: {output_loss.item()}')

Knowledge Check

Ready to test your understanding of 5. Training Loops & Optimizers?

Back