Skip to main content

Welcome to a Grasp lesson

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

Lesson 42

Backpropagation: The Chain Rule in Action

Recommended resources

Introduction

In our previous lesson, we built the core machinery for the backward pass, using the multivariable chain rule to calculate how the final loss is affected by any intermediate variable in a computation graph. We established the fundamental pattern: the gradient flowing into a node from its "downstream" (output side) is the product of the "upstream" gradient (from the next node in the backward pass) and the node's local gradient.

Today, we will complete the picture. The learnable parameters of a model—its weights and biases—are simply the input nodes of this very same graph. By extending the backward pass all the way to these inputs, we can compute the gradient of the loss with respect to every single parameter. This complete, efficient, two-pass algorithm is known as backpropagation. By the end of this lesson, you will be able to trace this entire process, understanding precisely how a neural network computes the signals it needs to learn from data.


Backpropagation: The Algorithm

At its heart, backpropagation is an ingenious application of an algorithm called "reverse-mode automatic differentiation." It's designed to be incredibly efficient for functions, like a neural network's loss function, that take a vast number of inputs (the parameters) and produce a single scalar output (the loss).

Let's explore why this "reverse mode" is such a computational victory.

Calculus on Computational Graphs: Backpropagation - Colah's Blog

This section of Christopher Olah's blog post masterfully explains the efficiency of backpropagation (reverse-mode differentiation) compared to the more intuitive "forward-mode."

Please read the section titled "Computational Victories." The key insight is in the comparison between forward-mode, which computes the derivative with respect to one input in a single pass, and reverse-mode, which computes the derivatives with respect to all inputs in a single pass. Pay close attention to the paragraph starting When training neural networks, which connects this directly to machine learning.

As the reading highlights, for a model with millions of parameters, computing the full gradient would require millions of forward passes. Backpropagation, however, achieves the same result in just one forward pass and one backward pass.

The full algorithm proceeds as follows:

  1. Forward Pass: We feed an input (e.g., a data sample from your cancer dataset) and the current parameters (weights and biases) into the network. We compute the value of each node in the graph, progressing from inputs to the final loss. Crucially, we cache the values of any intermediate variables that will be needed to calculate local gradients in the next step.
  2. Backward Pass: We initiate the process by setting the gradient of the loss with respect to itself to 1 (i.e., ). Then, we traverse the graph in reverse order. At each node, we compute the gradient of the loss with respect to the node's inputs by applying the chain rule: This process is repeated until we reach the parameter nodes, giving us the gradient of the loss with respect to every weight and bias.
This diagram from Colah's blog visualizes the full backward pass. Starting from the final output `e`, where the gradient is 1, the algorithm works backward, applying the chain rule at each node to compute the gradient of `e` with respect to all preceding nodes, including the inputs `a` and `b`.

A Practical Walkthrough: Staged Computation

To make this concrete, let's trace backpropagation on a more complex function, similar to what you might find inside a neural network. A key practical technique is staged computation, where we break down the forward pass into a sequence of simple, intermediate steps. This makes the backward pass much more manageable, as we only need to compute simple local gradients at each stage.

Neural Networks: Backpropagation

The "CS231n" course notes provide an excellent, code-based walkthrough of backpropagation on a complex function, demonstrating the power of staged computation.

Read the section titled Backprop in practice. First, trace the forward pass code block, observing how the complex function f(x,y) is broken down into eight simple steps. Then, carefully trace the backward pass code block. For each line (e.g., dnum = invden), identify the corresponding forward pass step it's "backpropping" through. Notice the pattern: the downstream gradient (e.g., dinvden) is multiplied by the local gradient of that specific step (e.g., -1.0/(den**2)) to get the new upstream gradient (dden). Pay special attention to the comment "Notice += !!". The variables x and y appear multiple times in the forward pass, creating forks in the computation graph. The multivariable chain rule ("sum over paths") dictates that we must add the gradients flowing back from these different branches. The += operator correctly accumulates these gradient contributions.

This staged approach is exactly how modern deep learning frameworks are designed. The framework builds the computation graph during the forward pass, caching necessary values. The backward pass then automatically applies the chain rule through this recorded graph.


From Graphs to Code: The Forward/Backward API

The logic of backpropagation is beautifully modular. Each "gate" or "layer" in a neural network can be thought of as an object that knows how to perform two tasks:

  1. forward(): Given inputs, compute the output and cache any values needed for the backward pass.
  2. backward(): Given the gradient of the loss with respect to its output (the "upstream" gradient), compute the gradient of the loss with respect to its inputs and pass it backward.

Andrej Karpathy's lecture provides a clear illustration of how this API forms the backbone of deep learning libraries.

CS231n Winter 2016: Lecture 4: Backpropagation, Neural Networks 1

This excerpt from the CS231n lecture explains how the concept of backpropagation is encapsulated in the forward/backward API of layers in deep learning frameworks.

First, watch the section from how this is implemented. This will show you pseudocode for a MultiplyGate and explain how the net object orchestrates the forward and backward passes by calling the respective methods on each gate in the correct order. The key takeaway is that the complexity is managed locally within each gate. Then, watch the concluding advice from training a two layer neural network. This reinforces the importance of staging your computation when you implement these algorithms yourself. Rather than deriving one massive, error-prone equation for a weight's gradient, you should think in terms of backpropagating through intermediate results (like scores and activations).


Conclusion

We have now assembled the full backpropagation algorithm. By combining the forward pass, which computes the output and caches values, with the backward pass, which recursively applies the chain rule, we can efficiently calculate the gradient of the loss function with respect to every parameter in the model. This gradient vector, , is the essential ingredient for optimization algorithms like gradient descent, telling us exactly how to adjust our weights and biases to improve the model's performance.

Key Takeaways:

  • Backpropagation is a two-pass algorithm (forward and backward) that efficiently computes the gradient of a scalar loss function with respect to a vector of parameters.
  • It is an application of reverse-mode differentiation, which is exceptionally efficient for the "many-to-one" structure of neural network loss functions.
  • The core of the backward pass is the recursive application of the chain rule: downstream_grad = upstream_grad * local_grad.
  • When a variable is used in multiple computations (a "fork"), its total gradient is the sum of the gradients from each branch.
  • In practice, deep learning frameworks implement this via a forward/backward API, where each layer is responsible for its local gradient computation.

In this lesson, we focused on the mechanics of gradient calculation. In our next lesson, we will analyze the components of this calculation more closely, specifically the activation functions (like Sigmoid, Tanh, and ReLU). We'll investigate how the choice of activation function impacts the flow of gradients through the network—a critical factor in training deep models effectively.