Backpropagation and Neural Networks


Backpropagation and Neural Networks

Maria
Last time, we looked at neural-network components and common architectures, especially for computer vision. Today, we’re focusing on backpropagation—the method that lets us calculate how the loss changes when we change a model’s parameters. We’ll need that whether we’re training a multilayer perceptron, a vision model, or a language model.

Corey
Let’s set up the training problem first. A model takes an example—an input and its label—and produces a loss, perhaps cross-entropy loss. The overall loss is usually the average of the losses across individual examples.

Maria
And in the simplest version of stochastic gradient descent, or SGD, we sample one example and update the parameters. We subtract the learning rate times the gradient of that example’s loss with respect to the parameters. The key question today is: how do we calculate that gradient efficiently when the model is a complicated composition of many operations?

Corey
It’s a practical question, not just mathematical bookkeeping. Every training job relies on these calculations under the hood. Software can automate them, but understanding the process helps you reason about how models train and how computation and memory are managed.

Maria
A useful way to begin is to think of a model as a differentiable circuit. It’s made from operations such as addition and multiplication, along with elementary functions like exponentials or sigmoid. The exact collection can vary, but the important idea is that we can compute the function by following its operations.

Corey
And a circuit can reuse an intermediate result. If you compute something once and use it in two later places, the circuit records that shared computation. A fully expanded formula would have to write that expression out each time, but the circuit doesn’t need to recompute it.

Maria
Here’s the central efficiency result. Suppose a differentiable circuit has size n, meaning it uses n operations, and computes a scalar-valued function from many inputs. Evaluating the function takes time proportional to n, and its gradient with respect to all the inputs can also be computed in time proportional to n.

Corey
That’s striking because the gradient has one entry for every input coordinate. You might expect calculating all those partial derivatives to require far more work than evaluating the function once. The result says that, for a circuit like this, the backward calculation can be done in roughly the same order of time as the forward calculation.

Maria
In deep learning, evaluating the model and loss is called the forward pass. Computing the gradient is the backward pass. Neural networks fit this circuit picture: matrix operations and activation functions are built from differentiable operations, and the network is a composition of them.

Corey
For most networks, the number of operations needed for a forward evaluation is proportional to the number of parameters. For example, a square matrix with dimension d has d squared entries, and multiplying it by a vector takes work proportional to d squared. So the circuit result tells us that the loss gradient can also be computed in time proportional to the number of parameters.

Maria
The general idea has uses beyond ordinary first-order training, too. You can differentiate through a computation that includes an optimization step—for instance, take a gradient step, evaluate the resulting loss, and then differentiate that loss with respect to the parameters you started with.

Corey
That makes it possible to optimize a process, not just a single model evaluation. The lecture points to uses such as meta-learning, tuning a learning rate by differentiating through an algorithm, and settings where a loss is defined by running an algorithm for several steps.

Maria
There’s also a useful second-order example. Let the loss be a function f, and take the gradient of f and multiply it by a vector v. If we then differentiate that result, we get the Hessian of f multiplied by v—a Hessian-vector product.

Corey
The full Hessian is a matrix with a number of entries that grows quadratically with the number of parameters, so explicitly forming it can be costly. But the Hessian-vector product can be computed efficiently using differentiation through the calculation. That’s useful to know, even though many commonly used optimizers don’t need to compute it.

Maria
Now to the mechanism behind all of this: the chain rule. Suppose an input vector z goes through a function g to produce an intermediate vector u, and then another function produces a scalar output J. If we already know how J changes with u, the chain rule tells us how to find the change in J with respect to z.

Corey
For an individual coordinate of z, the rule says to sum over the intermediate coordinates of u. For each one, multiply the derivative of J with respect to that coordinate of u by the derivative of that coordinate of u with respect to the z coordinate we care about.

Maria
In vector form, that’s a matrix multiplication: the gradient with respect to z is the transpose of g’s Jacobian, multiplied by the gradient with respect to u. The Jacobian describes how g’s outputs change with its inputs.

Corey
Here’s the key to making that local and reusable: this step needs information about g and the value of z, plus the gradient with respect to u. It doesn’t need to know how the later function produced J. Once we have the gradient arriving at u, we can forget the details of everything after g.

Maria
That’s why the calculation can be built out of local backward rules. Each module has a forward function that computes its output and a backward function that uses the incoming gradient to compute gradients for its inputs. Frameworks such as PyTorch implement these backward functions for their operations.

Corey
Picture a chain of modules: M1 produces u1, M2 produces u2, and M3 produces the final scalar loss J. We begin at the end, find the gradient with respect to u2, and use M2’s backward rule to get the gradient with respect to u1. Then M1’s backward rule gives us the gradient with respect to the original input.

Maria
The modules don’t have to be identical. One might be a matrix operation, another an activation function, and another a normalization operation. The same chain-rule procedure applies, using the appropriate local backward rule at each step.

Corey
There’s a further wrinkle: when training a network, we usually care about gradients with respect to its parameters, not just its input data. But the chain rule still applies. Treat a parameter as an input to the module that uses it, and differentiate that module’s output with respect to that parameter.

Maria
So a full backward pass tracks gradients with respect to intermediate activations, while also calculating gradients for the parameters. For a sequence of layers, the gradient flowing backward through the activations lets us calculate the parameter gradients at the layers along the way.

Corey
That dependency pattern matters for implementation. Once a needed gradient has been computed, some earlier intermediate calculations may no longer need to remain in memory. The order of computation, when memory can be freed, and how work is coordinated across GPUs all depend on the computation graph.

Maria
Let’s make the local rules concrete with an affine layer: u equals W times z plus b. Suppose z has m coordinates, u has n coordinates, W is an n-by-m matrix, and b has n coordinates. Given the gradient of J with respect to u, we can calculate gradients with respect to z, W, and b.

Corey
For the input gradient, the Jacobian of this affine operation with respect to z is W. Applying the chain rule gives the gradient with respect to z as W transposed times the gradient with respect to u. So the backward rule for the input is a multiplication by the transpose of the forward weight matrix.

Maria
For a particular weight, say the entry in row i and column j of W, its gradient is the gradient arriving at output coordinate i multiplied by input coordinate j. In words: take the signal at the output end of that connection and multiply it by the value at the input end.

Corey
That gives a helpful picture of a weight as a connection from an input coordinate to an output coordinate. The weight’s gradient combines the gradient at the output it feeds with the input value it receives. For one example, the gradient with respect to the whole weight matrix is an outer product, so it has rank one.

Maria
That rank-one fact applies to one example and one weight matrix. If we combine gradients across multiple examples, for instance by averaging them, the resulting gradient matrix doesn’t have to be rank one.

Corey
The bias gradient is simpler: each bias coordinate affects the corresponding output coordinate directly, so its gradient is the gradient arriving at that output coordinate.

Maria
Now consider an elementwise activation: u equals sigma of z, where sigma is applied separately to each coordinate. An output coordinate depends only on the matching input coordinate, so the Jacobian is diagonal. Its diagonal entries are the derivatives of sigma at the corresponding input values.

Corey
So to backpropagate through that activation, multiply each incoming gradient coordinate by the derivative of the activation at that coordinate. You don’t have to construct the diagonal matrix explicitly; you can do the coordinate-wise multiplication directly.

Maria
These local rules also explain the efficiency claim. The input-gradient calculation for a matrix operation uses a matrix multiplication of comparable size to the forward one. The weight-gradient calculation fills a matrix using an outer product, which takes work proportional to the number of entries in that matrix.

Corey
And for an elementwise activation, the forward and backward work both scale with the number of coordinates. So each operation’s backward computation has work comparable to its forward computation, and chaining those local rules gives us the full backward pass.

Maria
The activation itself can be any suitable differentiable function. The discussion mentions sigmoid as an example and notes that modern networks use a variety of activation functions, including gated combinations of outputs from multiple matrix operations.

Corey
So the big takeaway is that backpropagation isn’t a special trick tied to one neural-network architecture. It’s the chain rule organized over a computational graph: compute forward, pass gradients backward through local rules, and accumulate the gradients needed for the parameters.

Ask anything
We've read this whole study set, so questions about it get the best answers.