1. Home
  2. Explore
  3. Computer Science
  4. Backpropagation and Neural Networks

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Backpropagation and Neural Networks

Backpropagation and Automatic Differentiation

Purpose of Backpropagation

Training a neural network requires computing how the loss changes when its parameters change. Backpropagation is an efficient algorithm for computing the gradient of a loss with respect to model parameters. It applies the chain rule repeatedly through the operations that make up the model.

Backpropagation is also an instance of automatic differentiation: once a function is built from differentiable operations, a system can compute its derivatives by applying the local derivative rules for those operations. The same ideas apply to many differentiable computations, not only neural networks.


Loss Functions and Stochastic Gradient Descent

Let θ\thetaθ denote the model parameters. For an example with input xix_ixi​ and label yiy_iyi​, the model produces an output hθ(xi)h_\theta(x_i)hθ​(xi​), which is compared with the label using an individual-example loss, such as cross-entropy.

The overall loss is often the average of the losses across a dataset:

L(θ)=1M∑i=1Mℓ(hθ(xi),yi),L(\theta)=\frac{1}{M}\sum_{i=1}^{M}\ell\bigl(h_\theta(x_i),y_i\bigr),L(θ)=M1​∑i=1M​ℓ(hθ​(xi​),yi​),

where MMM is the number of examples and ℓ\ellℓ is the loss for one example.

In stochastic gradient descent (SGD), a training step uses a randomly sampled example or a small batch to estimate the gradient. For a sampled example indexed by kkk, a basic update is

θ←θ−η ∇θℓ(hθ(xk),yk),\theta \leftarrow \theta-\eta\,\nabla_\theta \ell\bigl(h_\theta(x_k),y_k\bigr),θ←θ−η∇θ​ℓ(hθ​(xk​),yk​),

where η\etaη is the learning rate. The central computational problem is to evaluate the gradient with respect to all parameters efficiently, even when the model is a large composition of layers and operations.


Differentiable Computations as Circuits

A computation can be represented as a computational graph or circuit. Its nodes are inputs, intermediate values, and operations; its edges show which values each operation uses.

Operations can include:

  • Arithmetic, such as addition, subtraction, multiplication, and division.

  • Elementary differentiable functions, such as exponentials, cosine, and sigmoid.

  • Neural-network operations, such as matrix multiplication and activation functions.

A circuit can reuse an intermediate result in several later computations. A formula, in contrast, would have to expand and repeat that computation each time it is used. This sharing makes the circuit representation useful for describing efficient computations.

The gradient-computation principle

Suppose a differentiable circuit with NNN operations computes a scalar-valued function fff of LLL inputs:

f:RL→R.f:\mathbb{R}^{L}\rightarrow\mathbb{R}.f:RL→R.

The gradient has one component for each input,

∇f∈RL,\nabla f\in\mathbb{R}^{L},∇f∈RL,

but all of its components can be computed in time proportional to the circuit size, or O(N)O(N)O(N), assuming each basic operation takes constant time. Evaluating the function itself also takes O(N)O(N)O(N) time.

This is the key efficiency result behind backpropagation: computing the gradient of a scalar output can take time on the same order as evaluating the computation that produced it. The gradient can itself be represented through a circuit.

Application to neural networks

A neural network and its loss can be viewed as a differentiable circuit. In this setting:

  • The circuit inputs of interest are the parameters θ\thetaθ.

  • The scalar output is usually the loss.

  • The circuit operations are the layers and other computations used to evaluate the model.

For many commonly used network operations, the number of arithmetic operations required for a forward evaluation is proportional to the number of parameters or other relevant model dimensions. The gradient can therefore be computed with comparable asymptotic cost.

For example, multiplying a D×DD\times DD×D matrix by a vector involves D2D^2D2 parameters and takes O(D2)O(D^2)O(D2) arithmetic operations. Its backward computations also take time proportional to D2D^2D2.


Forward and Backward Passes

The forward pass evaluates the model and computes its outputs or loss. The backward pass computes derivatives by moving backward through the computational graph.

Backpropagation works because of the chain rule. Rather than repeatedly differentiating the entire model from scratch, each operation passes a derivative to the earlier values that influenced it. Each step needs only local information about that operation and the derivative arriving from later in the graph.


The Chain Rule as a Backward Transformation

Consider a function that maps an input vector z∈Rmz\in\mathbb{R}^{m}z∈Rm to an intermediate vector u∈Rnu\in\mathbb{R}^{n}u∈Rn, followed by a function that maps uuu to a scalar JJJ:

u=g(z),J=f(u).u=g(z), \qquad J=f(u).u=g(z),J=f(u).

Suppose the gradient of the final output with respect to the intermediate vector is known, ∇uJ\nabla_u J∇u​J. The chain rule gives the gradient with respect to the earlier input:

∇zJ=Jg(z)T∇uJ,\nabla_z J=J_g(z)^{\mathsf T}\nabla_u J,∇z​J=Jg​(z)T∇u​J,

where Jg(z)J_g(z)Jg​(z) is the Jacobian matrix of ggg. Its entry in row jjj and column iii is

[Jg(z)]ji=∂uj∂zi.\bigl[J_g(z)\bigr]_{ji}=\frac{\partial u_j}{\partial z_i}.[Jg​(z)]ji​=∂zi​∂uj​​.

The Jacobian has shape n×mn\times mn×m, so its transpose has shape m×nm\times nm×n. Multiplying it by the nnn-dimensional gradient ∇uJ\nabla_u J∇u​J produces the mmm-dimensional gradient ∇zJ\nabla_z J∇z​J.

In component form,

∂J∂zi=∑j=1n∂J∂uj∂uj∂zi.\frac{\partial J}{\partial z_i} = \sum_{j=1}^{n} \frac{\partial J}{\partial u_j} \frac{\partial u_j}{\partial z_i}.∂zi​∂J​=∑j=1n​∂uj​∂J​∂zi​∂uj​​.

Each input-coordinate derivative is a weighted sum of derivatives with respect to the intermediate coordinates.

Why the chain rule supports efficient computation

To compute ∇zJ\nabla_z J∇z​J, the backward step needs:

  • The local function ggg and its derivative at the point zzz.

  • The current value of zzz.

  • The incoming gradient ∇uJ\nabla_u J∇u​J.

It does not need to know the full internal structure of fff. All the effects of computations after uuu have already been summarized in ∇uJ\nabla_u J∇u​J. This allows a complex computation to be treated as a sequence of local backward steps.


Composing Backward Steps Across Layers

Suppose a computation applies a sequence of modules:

u1=m1(x),u2=m2(u1),J=m3(u2).u_1=m_1(x),\qquad u_2=m_2(u_1),\qquad J=m_3(u_2).u1​=m1​(x),u2​=m2​(u1​),J=m3​(u2​).

The backward computation proceeds in reverse order:

  1. Compute the local derivative of JJJ with respect to u2u_2u2​.

  2. Use the backward rule for m2m_2m2​ to obtain the derivative with respect to u1u_1u1​.

  3. Use the backward rule for m1m_1m1​ to obtain the derivative with respect to xxx.

The same procedure works for any number of modules. The modules need not be identical: one may be a matrix multiplication, another an activation function, and another a normalization operation. Each operation uses its own local derivative rule, and the rules are composed by passing gradients backward.


Gradients with Respect to Parameters

Neural-network layers depend on both intermediate activations and parameters, such as weights and biases. A layer can be viewed as a function of both its input and its parameters.

For example, a layer may map an activation zzz to uuu using parameters θℓ\theta_\ellθℓ​:

u=mℓ(z;θℓ).u=m_\ell(z;\theta_\ell).u=mℓ​(z;θℓ​).

The backward computation can produce gradients with respect to the input, ∇zJ\nabla_z J∇z​J, and with respect to the layer’s parameters, ∇θℓJ\nabla_{\theta_\ell}J∇θℓ​​J. Parameters are differentiated through the same chain-rule principle as activations: the layer’s output depends on both, so the incoming gradient is propagated to each relevant input.

A useful way to understand the computation is:

  1. Propagate gradients through activations. Starting from the loss, compute derivatives with respect to intermediate values as the calculation is traversed backward.

  2. Compute parameter gradients. At each layer, use the incoming gradient and the layer’s local dependence on its parameters to calculate derivatives with respect to those parameters.

These computations can be interleaved. Some parameter gradients can be calculated as soon as the needed activation and incoming gradient are available; they do not all have to wait until the gradient has reached the network’s original input.


Affine Layers: Matrix Multiplication and Bias

Consider an affine transformation

u=Wz+b,u=Wz+b,u=Wz+b,

where z∈Rmz\in\mathbb{R}^{m}z∈Rm, W∈Rn×mW\in\mathbb{R}^{n\times m}W∈Rn×m, and b∈Rnb\in\mathbb{R}^{n}b∈Rn. Let the incoming gradient be

δ=∇uJ∈Rn.\delta=\nabla_u J\in\mathbb{R}^{n}.δ=∇u​J∈Rn.

Gradient with respect to the input

The Jacobian of uuu with respect to zzz is WWW. Therefore,

∇zJ=WTδ.\nabla_z J=W^{\mathsf T}\delta.∇z​J=WTδ.

The backward rule for the input is multiplication by the transpose of the forward weight matrix.

Gradient with respect to the weights

For an individual weight WijW_{ij}Wij​,

∂J∂Wij=∂J∂ui∂ui∂Wij=δizj.\frac{\partial J}{\partial W_{ij}} = \frac{\partial J}{\partial u_i} \frac{\partial u_i}{\partial W_{ij}} = \delta_i z_j.∂Wij​∂J​=∂ui​∂J​∂Wij​∂ui​​=δi​zj​.

The full weight-gradient matrix is therefore the outer product

∇WJ=δzT.\nabla_W J=\delta z^{\mathsf T}.∇W​J=δzT.

The derivative with respect to each weight combines two quantities: the gradient arriving at the weight’s output-side unit and the activation entering on its input side.

Gradient with respect to the bias

Since uiu_iui​ depends on bib_ibi​ with derivative 111,

∇bJ=δ.\nabla_b J=\delta.∇b​J=δ.

Rank-one property for a single example

For a single example, the weight gradient δzT\delta z^{\mathsf T}δzT is an outer product, so it has rank at most one. This property can be useful in methods that exploit the structure of individual-example gradients.

When gradients are averaged across multiple examples, the result is generally a sum of outer products and need not be rank one.


Elementwise Activation Functions

Suppose an activation function is applied independently to each coordinate:

u=σ(z),u=\sigma(z),u=σ(z),

where σ\sigmaσ is a differentiable scalar function applied elementwise. Because output coordinate uiu_iui​ depends only on input coordinate ziz_izi​, the Jacobian is diagonal. Its diagonal entries are σ′(zi)\sigma'(z_i)σ′(zi​).

Given δ=∇uJ\delta=\nabla_u Jδ=∇u​J, the backward rule is

∇zJ=σ′(z)⊙δ,\nabla_z J=\sigma'(z)\odot\delta,∇z​J=σ′(z)⊙δ,

where ⊙\odot⊙ denotes elementwise multiplication. Thus, each incoming gradient is multiplied by the derivative of the activation at the corresponding input value.

The Jacobian does not need to be explicitly constructed: the elementwise products compute its effect directly. Common activation functions have different forms, but their backward computations follow this same principle.


Computational Cost of the Backward Pass

For an affine layer with W∈Rn×mW\in\mathbb{R}^{n\times m}W∈Rn×m:

  • The forward matrix-vector product costs O(nm)O(nm)O(nm).

  • Computing the input gradient WTδW^{\mathsf T}\deltaWTδ costs O(nm)O(nm)O(nm).

  • Computing the weight gradient δzT\delta z^{\mathsf T}δzT requires producing nmnmnm entries and costs O(nm)O(nm)O(nm).

For an elementwise activation of dimension mmm:

  • The forward computation takes O(m)O(m)O(m) time.

  • The backward computation also takes O(m)O(m)O(m) time.

Consequently, the backward pass for these operations has the same asymptotic cost as the forward pass. Its exact runtime and memory use depend on the operations and implementation, but it remains on the same order for standard layers.


Computational Graphs, Memory, and Scheduling

The graph structure determines which intermediate values and gradients depend on one another. This affects how computations can be scheduled and how memory can be used.

  • Some calculations can proceed independently once their required values are available, allowing parallel execution.

  • Intermediate activations may need to be retained because later backward computations use them—for example, the weight gradient for an affine layer needs its input zzz.

  • Once a stored value is no longer needed, it can be discarded to free memory.

  • In multi-processor or multi-GPU systems, the dependency graph helps determine when values must be communicated.

Thus, backpropagation is not only a rule for calculating derivatives; the dependencies in its computational graph also shape practical decisions about execution, parallelism, and memory.


Applications Beyond Ordinary First-Order Training

Automatic differentiation can be applied to computations that themselves contain gradient calculations or optimization steps, as long as the resulting computation is differentiable.

Differentiating through an optimization step

Suppose one gradient-descent step defines updated parameters

θ′=θ−η∇θL(θ).\theta'=\theta-\eta\nabla_\theta L(\theta).θ′=θ−η∇θ​L(θ).

An outer objective can evaluate the loss after this update, such as L(θ′)L(\theta')L(θ′). This outer objective is a function of the original θ\thetaθ because θ′\theta'θ′ depends on θ\thetaθ. Automatic differentiation can differentiate through the update rule and compute the outer gradient.

The same idea extends to running an algorithm for multiple steps and then measuring its final result. The sequence of updates becomes part of the computational graph. This is useful in settings such as meta-learning, where an algorithm or training procedure is itself treated as something to optimize.

Hessian-vector products

Let f(x)f(x)f(x) be a scalar function and let vvv be a fixed vector. Define

g(x)=∇f(x)Tv.g(x)=\nabla f(x)^{\mathsf T}v.g(x)=∇f(x)Tv.

Differentiating ggg gives

∇g(x)=∇2f(x) v,\nabla g(x)=\nabla^2 f(x)\,v,∇g(x)=∇2f(x)v,

where ∇2f(x)\nabla^2 f(x)∇2f(x) is the Hessian matrix. This computes a Hessian-vector product without constructing the entire Hessian.

The product can be computed efficiently by differentiating through a computation for ggg. The full Hessian may be too large to form explicitly, but its product with a vector can be practical. Such computations support some second-order methods and other advanced optimization procedures, although many commonly used optimizers do not require them.

Higher-order differentiation

The same principle can be applied repeatedly: if a derivative computation is itself expressed as a differentiable program, automatic differentiation can differentiate through it. This makes some higher-order derivatives accessible without explicitly building every large derivative matrix.


Key Takeaways

Backpropagation computes gradients by repeatedly applying local chain-rule transformations in reverse through a computational graph.

  • A scalar-valued differentiable circuit with NNN operations can have its gradient computed in time proportional to NNN.

  • The gradient passed backward summarizes the effect of all later computations, so each local step needs only its own operation and the incoming gradient.

  • For an affine layer u=Wz+bu=Wz+bu=Wz+b, the backward rules are ∇zJ=WT∇uJ\nabla_zJ=W^{\mathsf T}\nabla_uJ∇z​J=WT∇u​J, ∇WJ=(∇uJ)zT\nabla_WJ=(\nabla_uJ)z^{\mathsf T}∇W​J=(∇u​J)zT, and ∇bJ=∇uJ\nabla_bJ=\nabla_uJ∇b​J=∇u​J.

  • For an elementwise activation u=σ(z)u=\sigma(z)u=σ(z), the backward rule is ∇zJ=σ′(z)⊙∇uJ\nabla_zJ=\sigma'(z)\odot\nabla_uJ∇z​J=σ′(z)⊙∇u​J.

  • Standard layers have backward computations with the same asymptotic cost as their forward computations.

  • Because gradient calculations can themselves be differentiated, automatic differentiation also supports computations such as gradients through optimization steps and Hessian-vector products.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent