Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 23

Neural Network Fundamentals: Forward and Backward Propagation

This lesson is built with resources from duchesnay.github.io and uvadlc-notebooks.readthedocs.io.

Hello! Welcome back to our fourth module, Deep Learning with PyTorch.

In our last two lessons, we assembled the fundamental building blocks of a neural network: we defined the architecture with layers and neurons, and then explored how activation functions introduce the non-linearity that gives these networks their power. We now have a static blueprint of a model.

Today, we'll bring that blueprint to life. This lesson addresses the learning outcome: Implement forward propagation and explain the backpropagation algorithm conceptually. We will first implement the forward pass, where input data flows through the network to generate a prediction. Then, we will uncover the learning mechanism itself—backpropagation—the algorithm that allows the network to learn from its mistakes. Your background as a software engineer will be particularly helpful here, as you'll see how PyTorch elegantly abstracts complex mathematical operations into a clean, intuitive API.

1. Implementing Forward Propagation

Forward propagation (or the forward pass) is the process of passing an input through the network, layer by layer, to compute an output. We've already seen all the components; now we just need to assemble them within a formal PyTorch model structure.

In PyTorch, a model is defined as a class that inherits from torch.nn.Module. This class has two essential methods:

  • __init__(): This is the constructor where you define and initialize the layers of your network (e.g., nn.Linear, nn.ReLU).
  • forward(): This method defines the sequence of operations for the forward pass. You take the input x and pass it through the layers you defined in __init__.

Let's see how this is done in practice.

Tutorial 2: Introduction to PyTorch — UvA DL Notebooks

The following tutorial from the UvA Deep Learning course demonstrates how to define a simple neural network class. It's a perfect, practical example of implementing a forward pass.

Please read the section 'The model', focusing on the 'nn.Module' and 'Simple classifier' subsections. Pay close attention to how the SimpleClassifier class is structured: see how nn.Linear and nn.Tanh are defined in __init__ and then called in sequence within the forward method. This is the implementation of forward propagation.

The code in the reading defines a forward pass like this:

  1. The input x goes into the first linear layer (self.linear1).
  2. The result is passed through a Tanh activation function (self.act_fn).
  3. That result is then passed through the second linear layer (self.linear2) to produce the final output.

This flow—from input to output—is forward propagation. Now that we can get a prediction, how do we know if it's right or wrong, and how do we fix it?


2. The Concept of Backpropagation: How Networks Learn

After the forward pass, we compare the model's prediction with the true label to calculate a loss (or error). Our goal is to adjust the model's weights to minimize this loss.

The key question is: how much should each weight in the network be adjusted to reduce the loss?

This is where backpropagation comes in. It is an algorithm that efficiently calculates the gradient of the loss function with respect to every single weight and bias in the network. A gradient tells us the direction of the steepest ascent for the loss function; by moving in the opposite direction, we can effectively minimize the loss.

Backpropagation works by applying the chain rule from calculus, starting from the final loss and moving backward through the network, layer by layer.

Backpropagation in a Feedforward Neural Network
A feedforward neural network showing the two main phases. **Forward propagation** (black arrows) moves from input to output to make a prediction. **Backpropagation** (purple arrows) moves from the calculated error back through the network to update the weights.

To understand this process intuitively, we can think of the network as a computational graph. Each operation (addition, multiplication, activation function) is a node in the graph.

Computational Graph with Forward and Backward Pass
A simple computational graph for the function `f = (x + y) * z`. The forward pass (green) calculates the output. The backward pass (red) computes the gradients. Backpropagation uses the chain rule to calculate the gradient of `f` with respect to each input (`x`, `y`, `z`) by first calculating the gradient with respect to intermediate values like `q`.

In this graph, backpropagation calculates how a small change in an input (like x) affects the final output f by propagating gradients backward through the intermediate nodes (q). A neural network is just a much larger and more complex version of this graph.

Let's dive into a more formal, yet still conceptual, explanation.

Backpropagation — Statistics and Machine Learning in Python

This resource provides a clear, step-by-step breakdown of backpropagation using the chain rule for a simple two-layer network.

Read the section 'Backpropagation and chain rule'. Focus on understanding the two main passes: the Forward pass, where the output is computed, and the Backward pass, where the gradients (like ∂L/∂w) are computed by applying the chain rule. You don't need to memorize the equations, but rather follow the logic of how the error from the loss L is propagated backward to find the gradients for w^(2) and then w^(1).


3. From Concept to Code: PyTorch's autograd

Manually calculating gradients for a deep neural network would be incredibly complex and error-prone. As a software engineer, you'll be glad to know you'll almost never have to do it. This is where PyTorch's autograd engine comes in.

When you perform operations on PyTorch tensors that have requires_grad=True, PyTorch builds a dynamic computation graph in the background, just like the one we saw earlier. It remembers every operation performed.

When you finally call .backward() on your loss tensor, PyTorch traverses this graph in reverse, automatically computing the gradients for all tensors that contributed to the loss.

Tutorial 2: Introduction to PyTorch — UvA DL Notebooks

Let's return to the UvA notebook to see how PyTorch's autograd works. This reading explains the magic behind .backward().

Read the section 'Dynamic Computation Graph and Backpropagation'. Focus on how PyTorch tracks operations on tensors with requires_grad=True to build the graph, and how calling y.backward() automatically computes the gradients, which are then stored in the .grad attribute of the input tensors (e.g., x.grad).

This automated process is the heart of what makes modern deep learning frameworks so powerful and easy to use. It allows you to define complex architectures and let the framework handle the calculus.


4. The Complete Training Loop

Now we can combine forward propagation and backpropagation into a standard training loop. A training loop iterates over the dataset, and for each batch of data, it performs these five crucial steps:

  1. Zero the gradients: optimizer.zero_grad()
  2. Perform a forward pass: preds = model(inputs)
  3. Compute the loss: loss = loss_module(preds, labels)
  4. Perform backpropagation: loss.backward()
  5. Update the weights: optimizer.step()

The following resource shows how these steps come together in a complete training function.

Tutorial 2: Introduction to PyTorch — UvA DL Notebooks

This final reading shows a complete training function in PyTorch, putting all the pieces together.

First, read the 'Optimization' section to understand what loss_module and optimizer are. Then, study the train_model function in the 'Training' section. Identify the five key steps of the training loop listed above inside the for loop.

Test your understanding!

In the standard PyTorch training loop, what is the purpose of optimizer.zero_grad()? What would happen if you forgot to include this line?

Show answer

The purpose of optimizer.zero_grad() is to clear the gradients from the previous iteration.

If you forgot to include it, PyTorch would accumulate the new gradients with the gradients from all previous steps. This is because loss.backward() adds the newly computed gradients to the existing .grad attributes. This accumulation would corrupt the gradient calculation for the current step, causing the optimizer to update the weights in a completely wrong direction and preventing the model from learning correctly.


Conclusion

In this lesson, we bridged the gap between a static model definition and a dynamic learning process. You now understand the two-stroke engine of deep learning: the forward pass to make a prediction and the backward pass to learn from the error.

Key Takeaways:

  • Forward Propagation: The process of passing input data through the network's layers and activation functions to produce an output. In PyTorch, this is implemented in the forward method of an nn.Module class.
  • Backpropagation: A powerful algorithm that uses the chain rule to efficiently compute the gradient of the loss function with respect to every model parameter. It works by propagating the error signal backward through the network.
  • PyTorch autograd: PyTorch's automatic differentiation engine that builds a computation graph and automatically computes all gradients when .backward() is called on a loss tensor.
  • The Training Loop: A five-step process (zero_grad, forward pass, loss calculation, backward, step) that is the standard recipe for training most neural networks.

Next up:

We have now covered all the core theoretical components and their PyTorch implementations needed to train a simple model. In the next lesson, we will put everything together to build a neural network model for a classification task using PyTorch. We'll handle everything from loading data to training the model and evaluating its performance, giving you a complete, end-to-end practical example.