Hello! Welcome back to our journey into Deep Learning with PyTorch.
In the last lesson, we constructed the "skeleton" of a neural network by defining its architecture as a Python class inheriting from torch.nn.Module. You learned how to assemble layers and define the forward pass. However, a model with randomly initialized weights is not yet useful.
Today, we'll give that skeleton a "brain" and teach it how to learn. This lesson focuses on the heart of the training process: implementing a complete training loop, including loss calculation and weight updates. You'll see how PyTorch elegantly combines the model, a loss function, and an optimizer to iteratively improve performance. This process is a structured algorithm, which should feel familiar given your background in software engineering.
1. The Three Pillars of Model Training
Before we write the loop itself, let's understand the three essential components that make training possible.
Pillar 1: The Loss Function (Criterion)
The loss function measures how far the model's prediction is from the actual target (the "ground truth"). The goal of training is to minimize this value. A smaller loss means a better model. PyTorch provides many standard loss functions in its torch.nn module.
For the classification tasks we've been discussing:
- Binary Classification: We typically use
nn.BCELoss(Binary Cross-Entropy Loss). This is used with a model that outputs a single probability value (via aSigmoidactivation). - Multi-Class Classification: The standard is
nn.CrossEntropyLoss. This function is highly optimized and combinesnn.LogSoftmaxandnn.NLLLoss. A crucial practical detail: when usingnn.CrossEntropyLoss, your model should output raw scores (called logits), meaning you should not have aSoftmaxlayer at the end of your model.
# Example of initializing a loss function
# For a multi-class classification problem
loss_fn = nn.CrossEntropyLoss()
Pillar 2: The Optimizer
If the loss function is the measure of "how wrong" the model is, the optimizer is the mechanism that corrects it. It implements an optimization algorithm (like Stochastic Gradient Descent) that updates the model's weights in the direction that most reduces the loss.
The most critical parameter you'll provide to an optimizer is the learning rate. This determines the size of the steps the optimizer takes to update the weights.
PyTorch's torch.optim package contains a variety of optimizers. Adam is a very popular and effective default choice. To initialize an optimizer, you must tell it which parameters (weights and biases) it is responsible for updating. This is done by passing model.parameters() to its constructor.
# model is an instance of a nn.Module class
# The learning rate (lr) is a hyperparameter you'll often tune.
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
The combination of a loss function and an optimizer provides the core mechanics for a single learning step.
2. The Training Loop Algorithm
A single learning step isn't enough; we need to repeat this process for our entire dataset multiple times. This is done inside a training loop. A full pass over the entire dataset is called an epoch. Datasets are often too large to process at once, so we process them in smaller mini-batches.
The training process for each mini-batch consists of five fundamental steps. The following diagram provides a fantastic visual summary of this flow.

Let's break down each step in the code:
-
optimizer.zero_grad(): Before calculating the gradients for the current batch, we must explicitly reset them to zero. This is because PyTorch accumulates gradients on subsequent.backward()calls. If we didn't zero them, we'd be mixing gradients from previous batches, which would corrupt the learning process. -
outputs = model(inputs): This is the forward pass you learned about in the last lesson. We feed a batch of input data to the model to get its predictions. -
loss = loss_fn(outputs, labels): We use the loss function to compare the model'soutputswith thelabels(the ground truth) and compute a single scalar value representing the batch's loss. -
loss.backward(): This is where PyTorch'sautogradengine does its work. It automatically calculates the gradient of the loss with respect to every learnable parameter in the model (all the tensors you created withrequires_grad=True). -
optimizer.step(): The optimizer uses the gradients computed in the previous step to update the model's parameters (e.g.,weights = weights - learning_rate * gradient).
To see this in action, let's turn to the official documentation, which shows exactly how an optimizer automates the weight update step.
Learning PyTorch with Examples
The official PyTorch documentation provides excellent, concise examples that build up the training loop concept by concept. We'll focus on the part where the optimizer is introduced, as this is the final piece of our training loop puzzle.
Please read the section titled 'PyTorch: optim'. This section shows how to replace the manual weight update seen in the prior section with a PyTorch optimizer. Pay close attention to the five key lines in the training loop: initializing the optimizer, optimizer.zero_grad(), loss.backward(), and optimizer.step(), and how they form a complete learning step.
3. Assembling the Complete Script
Now that you understand the core iteration, let's put it into a complete script structure with epochs and batches. You will typically wrap the five-step process inside two for loops.
- The outer loop iterates over the
num_epochs. - The inner loop iterates over the
train_loader, which yields one mini-batch of data at a time.
Before starting the training for an epoch, it is standard practice to call model.train(). This puts the model in "training mode." While it doesn't matter for simple linear layers, it's crucial for certain layers like Dropout or BatchNorm, which behave differently during training versus evaluation.
The following resource provides a clean, well-structured template for this.
Creating a Training Loop for PyTorch Models
Now let's see how these steps fit into a full training script. This article provides a clear template for a typical training loop, including iterating over epochs and data batches.
Read the section 'Core Training Loop Structure' and study the 'Basic Loop Outline' code block. Notice the outer for loop for epochs and the inner for loop for batches from the train_loader. See how the five steps we discussed are nested inside this inner loop, along with a call to model.train().
Test your understanding!
Let's bring everything together. Below is the setup for a training process. You have a model, some dummy data, a loss function, and an optimizer. Your task is to fill in the ... placeholders in the training loop to correctly implement the five core steps.
import torch
import torch.nn as nn
# 1. Model, Data, and Setup
# (This part is provided for you)
class SimpleClassifier(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(10, 2) # 10 features in, 2 classes out
def forward(self, x):
return self.linear(x)
model = SimpleClassifier()
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
# Dummy data for one batch
inputs = torch.randn(8, 10) # Batch of 8 samples, 10 features each
labels = torch.randint(0, 2, (8,)) # 8 labels (0 or 1)
# 2. The Training Step
# Put the model in training mode
model.train()
# --- YOUR CODE GOES HERE ---
# TODO: Zero out the gradients
...
# TODO: Perform the forward pass to get model outputs
...
# TODO: Calculate the loss
...
# TODO: Perform backpropagation to compute gradients
...
# TODO: Update the model's weights
...
# -------------------------
print("Training step completed!")
# Let's check the loss
final_loss = loss_fn(model(inputs), labels)
print(f"Loss after one training step: {final_loss.item()}")
Show answer
Here is the completed training step. The five lines directly map to the algorithm we've discussed.
import torch
import torch.nn as nn
# 1. Model, Data, and Setup
class SimpleClassifier(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(10, 2)
def forward(self, x):
return self.linear(x)
model = SimpleClassifier()
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
inputs = torch.randn(8, 10)
labels = torch.randint(0, 2, (8,))
# 2. The Training Step
model.train()
# --- SOLUTION ---
# Zero out the gradients
optimizer.zero_grad()
# Perform the forward pass to get model outputs
outputs = model(inputs)
# Calculate the loss
loss = loss_fn(outputs, labels)
# Perform backpropagation to compute gradients
loss.backward()
# Update the model's weights
optimizer.step()
# ----------------
print("Training step completed!")
final_loss = loss_fn(model(inputs), labels)
print(f"Loss after one training step: {final_loss.item()}")
If you run this code multiple times, you should see the loss generally decrease, as the model learns from the same batch of data with each step.
Conclusion
Congratulations! You've now implemented the most fundamental process in deep learning. While more advanced techniques exist, they are all built upon the foundation of this training loop.
Key Takeaways:
- Training Components: A successful training process requires a model, a loss function to quantify error, and an optimizer to update the weights.
- The Five Steps: Every PyTorch training iteration for a batch involves a sequence of five crucial steps:
optimizer.zero_grad(), forward pass, loss calculation,loss.backward(), andoptimizer.step(). - Epochs and Batches: Training is structured into epochs (full passes over the dataset) and batches (the smaller chunks of data processed in each iteration of the inner loop).
model.train()Mode: Setting your model to training mode is essential for ensuring layers like Dropout and BatchNorm function correctly.
Next up:
We can now train a model, but how do we know if it's actually any good? Just watching the training loss decrease isn't enough. In the next lesson, we will learn how to evaluate a classification model using standard metrics such as accuracy, precision, recall, and F1-score, giving us a much clearer picture of its real-world performance.