A model may have millions of parameters and produce one number you want to improve. During training, that number is the loss. You need to know how changing each parameter would change the loss, even though the loss function sees only the model's final output. Backpropagation computes those sensitivities by starting from the loss and reusing work as it moves backward through the model.

You will compute gradients through a shared dependency and a two-layer network by hand. Then you will implement the same operations with a scalar Python graph and a batched NumPy network. You will also learn to supply a vector seed in PyTorch and diagnose gradients that are missing, zero, or unexpectedly large.

This lesson builds on Derivatives and Gradients for Machine Learning. Keep the row and column conventions from Vectors, Matrices, and Operations nearby. Here a conceptual vector is a column. A batch stores one example per row. Every Jacobian uses output rows and input columns.

Use the chain rule as a local computation#

Suppose z=f(x) and L=g(z), where x and z are scalars and L is a scalar loss. The rate of change of L with respect to x is the product of the rate from x to z and the rate from z to L.

dL/dx = (dL/dz) × (dz/dx)

The factor dz/dx belongs to the local operation f. Evaluate it at the current input x. The factor dL/dz summarizes everything downstream of z. For example, if increasing x by a small amount increases z at a rate of 3, and increasing z increases the loss at a rate of 2, the loss increases at a rate of 6 with respect to x. If the local derivative is zero, no first-order sensitivity passes through that route at the evaluation point.

Now let L depend on two values u and v, each of which depends on x. An increase in x can change u and v together. The chain rule accounts for both changes.

dL/dx = (∂L/∂u) × (du/dx) + (∂L/∂v) × (dv/dx)

Each partial derivative of L holds the other argument fixed. The two terms multiply along their own paths and add when those paths share the same input. The contributions can have opposite signs. A zero total can therefore reflect cancellation between active paths, in addition to an inactive path or a flat local function.

Work a shared dependency by hand#

Let a=2 and b=3. Define the shared product t=ab, the square u=t², the linear term v=3t, and the final loss L=u+v. Forward evaluation yields t=6, u=36, v=18, and L=54. All values are dimensionless in this example. Treat the two uses of t as two separate edges in the computation graph.

Architecture canvasOne product used by two downstream operationsThe product t = ab feeds a square and a multiply by three. Their sum is L. In reverse, add the two contributions at t before computing either input gradient.
One product used by two downstream operationsThe product t = ab feeds a square and a multiply by three. Their sum is L. In reverse, add the two contributions at t before computing either input gradient.Inputsa = 2, b = 3Product tt = 6Square uu = 36Linear term vv = 18Sum LL = 54
Diagram key and text version
  • Entry
  • Process
  • Outcome
  1. Inputs → Product t
  2. Product t → Square u
  3. Product t → Linear term v
  4. Square u → Sum L
  5. Linear term v → Sum L

The arrows show the order of the forward dependencies. The reverse calculation starts with dL/dL=1. The sum sends a copy of that sensitivity to each of its two arguments, so dL/du=1 and dL/dv=1. The square contributes 1 × 2t=12 to dL/dt, and the linear term contributes 1 × 3=3. The shared product's total sensitivity is 15.

For the product t=ab, holding b fixed gives ∂t/∂a=b. Holding a fixed gives ∂t/∂b=a. The gradients are therefore dL/da=15 × 3=45 and dL/db=15 × 2=30. The product operation uses its operands from the forward evaluation. The backward pass also reuses the accumulated 15 for both gradients.

A computation graph for one evaluation is a directed acyclic graph. A parent node is an input to the operation that created its child. Process nodes in an order where every consumer is processed before its inputs. That reverse topological order ensures a shared input receives all contributions before it propagates any of them to its own inputs. When an operation uses the same input twice, keep both edges. For x × x, each operand contributes x and the sum is 2x.

Build a small reverse-mode engine#

A scalar node can hold its forward value and a list of pairs containing a parent node and its local derivative. For an addition both local derivatives are 1. For a multiplication each derivative equals the other input's forward value. The following loop is the core of the downloadable Python engine. Its forward_order lists parents before consumers, with each node appearing once. Its adjoints dictionary maps a node to the derivative of the final result with respect to that node.

adjoints = {output: 1.0}
for node in reversed(forward_order):
    upstream = adjoints.get(node, 0.0)
    for parent, local_derivative in node.inputs:
        adjoints[parent] = (
            adjoints.get(parent, 0.0) + upstream * local_derivative
        )

The engine in the lab discovers the reachable nodes from the output. A fresh dictionary makes each call an independent derivative evaluation. Within that call, additions to the dictionary combine dependency paths. A production framework may also accumulate into parameter gradient buffers across calls. That is a separate mechanism with its own lifetime.

The adjoint at a scalar node is its accumulated loss sensitivity. For an array node, its adjoint is an array with the same shape, holding a sensitivity per entry. Automatic differentiation uses the local rules for operations that took place in the forward computation. It evaluates derivatives at concrete inputs with ordinary floating-point error and the operation's chosen derivative convention at a kink. Finite differences estimate a derivative by perturbing inputs and re-running the function. Symbolic differentiation constructs a derivative expression. The local-rule engine needs neither input perturbations nor a single expanded expression for the whole derivative.

Read a vector–Jacobian product by shape#

Let y=f(x), where x has n elements and y has m. The Jacobian J has shape [m,n]. Its entry in output row i and input column j is ∂yᵢ/∂xⱼ. Forward mode propagates an input direction d by computing Jd, a Jacobian–vector product or JVP with m entries. Reverse mode takes a column vector g of sensitivities for the m outputs and computes Jᵀg, with n entries. This is the column-vector form of the VJP, whose row-vector form is gᵀJ.

Work it out for f(a,b)=(ab,a+b) at (2,3). The two rows of J are (3,2) and (1,1). Choose a downstream scalar objective L=2y₁-y₂, where y₁ and y₂ are the two outputs. Then g=(2,-1)ᵀ. Multiply the first Jacobian row by 2 and the second by −1. Adding the rows gives (5,3), so ∂L/∂a=5 and ∂L/∂b=3. Forward mode seeded with d=(1,0)ᵀ instead gives (3,1)ᵀ, the effect of nudging just a on both outputs.

Each output seed selects a weighted combination of the rows. One reverse pass seeded with 1 suffices for all the input sensitivities of a scalar loss. Building a whole Jacobian generally needs an independent seed for each output row in reverse mode or each input column in forward mode, though implementations can vectorize those products. A local operation such as matrix multiplication can compute its VJP using matrix products directly. It need not store even its local Jacobian as a dense matrix. This is especially valuable when the model has many parameters and its training objective is one scalar.

Backpropagate through a two-layer network#

Use an input column x=(2,-1)ᵀ, a first weight matrix W₁ with rows (1,2) and (-1,1), and hidden bias b₁=(1,1)ᵀ. Rows of W₁ represent hidden units. Compute the hidden preactivation z=W₁x+b₁=(1,-2)ᵀ. The rectified linear unit, or ReLU, acts elementwise as max(0,z), so the hidden activation is h=(1,0)ᵀ. Let the output weight row W₂ be (3,-2) and the output bias b₂=1. The prediction p=W₂h+b₂ is 4. With target y=2, the half-squared loss L=0.5(p-y)² is 2.

  1. The output sensitivity dL/dp is the residual p-y=2. The factor one-half cancels the derivative's factor two.
  2. The output weight gradient is (dL/dp)hᵀ=(2,0). Changing the second output weight has no local effect because its input activation is zero. The output bias gradient is 2.
  3. The hidden activation gradient is W₂ᵀ(dL/dp)=(6,-4)ᵀ. The negative preactivation is in the flat region of ReLU. Applying the ReLU derivative elementwise sends (6,0)ᵀ to the preactivations.
  4. Each first-layer weight multiplies one input element. The first-layer weight gradient is the outer product of (6,0)ᵀ with the row (2,-1), yielding rows (12,-6) and (0,0). The hidden bias gradient is (6,0)ᵀ. The input gradient is W₁ᵀ(6,0)ᵀ=(6,12)ᵀ.

The derivative of ReLU is one above zero and zero below zero. At exactly zero the left and right slopes differ, so the classical derivative is undefined. The examples and gradient checks here avoid that point. PyTorch's backward rule selects zero there. A central difference at exactly zero for ReLU evaluates to one-half, so disagreement at that point is expected.

Move from one example to a batch#

Let B count examples, D input features, and H hidden units. The batch X has shape [B,D], W₁ has shape [H,D], and W₂ has shape [1,H]. The forward pass is Z=XW₁ᵀ+b₁, A=max(0,Z), and P=AW₂ᵀ+b₂, where A is the hidden activation array. Each prediction and target is stored as a row with one column. The preceding gradient lesson stored its scalar predictions as a one-dimensional array. Here both predictions and targets have shape [B,1], so subtraction pairs each prediction with its own target. Define the batch loss as the mean of the B individual half-squared losses.

QuantityShapeComputation
Prediction gradient G[B,1](P-Y)/B, with Y the target batch
Output weight gradient[1,H]GᵀA
Output bias gradient[1]Sum G over the batch axis
Hidden preactivation gradient Q[B,H]Multiply G W₂ elementwise by Z>0
Hidden weight gradient[H,D]QᵀX
Hidden bias gradient[H]Sum Q over the batch axis
Input gradient[B,D]QW₁

A single bias value affects every row of its output. Broadcasting repeats that value in the forward computation. Its backward rule sums sensitivity over the repeated axis. The division by B happens once in G. Dividing each parameter gradient again would shrink the gradient by another factor of B. If you replaced the mean reduction with a sum, the factor in G would disappear. For multiple prediction columns, explicitly decide whether you mean over all elements or over examples after summing within each row.

z = x @ w1.T + b1
hidden = np.maximum(z, 0)
prediction = hidden @ w2.T + b2
residual = prediction - targets
loss = 0.5 * np.mean(residual**2)

output_grad = residual / len(x)
preactivation_grad = (output_grad @ w2) * (z > 0)
dw2 = output_grad.T @ hidden
db2 = output_grad.sum(axis=0)
dw1 = preactivation_grad.T @ x
db1 = preactivation_grad.sum(axis=0)

The lab checks those gradients against the hand example and central differences on a second batch. The finite difference changes one parameter entry by +ε and -ε, then divides the difference of the losses by 2ε, where ε is a small positive step. That approximation can drift for steps too large to remain local or too small for the precision of the loss calculation. Check more than one step size when diagnosing a mismatch. The fixture uses floating-point double precision and preactivations away from zero.

Run the equivalent reverse computations in PyTorch#

To see the seed explicitly, use the earlier two-output function. The inputs are leaves created with requires_grad=True. torch.autograd.grad returns their gradients as values. For this example it leaves their .grad buffers unset.

import torch

a = torch.tensor(2.0, dtype=torch.float64, requires_grad=True)
b = torch.tensor(3.0, dtype=torch.float64, requires_grad=True)
outputs = torch.stack((a * b, a + b))
seed = torch.tensor([2.0, -1.0], dtype=outputs.dtype)
da, db = torch.autograd.grad(outputs, (a, b), grad_outputs=seed)
assert (da.item(), db.item()) == (5.0, 3.0)

For ordinary training, call loss.backward() on a scalar loss. That uses the seed 1 and, by default, accumulates into eligible leaf tensors' .grad buffers. Call optimizer.zero_grad(set_to_none=True) before starting a step whose gradients should be independent of the previous step. Then run the new forward pass, call backward, and let optimizer.step() use the gradients. Backward computes sensitivities. The optimizer decides how to update parameters.

Microbatch accumulation intentionally makes several backward calls before the optimizer step. If two microbatches contain different numbers of examples and each loss is already averaged, weight each microbatch loss by its share of the total example count before backward. Otherwise their gradients contribute equally even when one microbatch represents more data. If the training loss averages only valid tokens, use the valid-token counts for that denominator. This matters in language model training, where padded batches can contain very different numbers of learning targets.

Run the standard lab with Python and NumPy, and add --torch to compare the NumPy gradients with a fresh PyTorch forward and reverse pass. The PyTorch check also shows accumulation from two fresh forward graphs and clearing before a new step. Run python3 09-chain-rule-autodiff-backprop.py from the download directory, or add --torch once PyTorch is installed.

Debug gradient failures by tracing the graph#

Start with a single deterministic example and the same reduction, dtype, input shapes, and parameter values used by the model. Store gradients by parameter name and record which tensors are supposed to receive them. For a custom operation, test the backward output with a nonuniform downstream seed. Testing only a sum, which uses all ones as the seed, can hide a transposed Jacobian or accidentally broadcast axis.

  • A leaf gradient is missing. Check requires_grad, then trace backward from the loss to the leaf. Detaching an intermediate, using .item() and rebuilding a tensor from the returned number, or evaluating a training forward pass inside torch.no_grad() can break the recorded connection. Use retain_grad() on a non-leaf tensor when you need to inspect its intermediate gradient.
  • Gradients are bigger than expected. Reproduce one isolated step after clearing leaf buffers, and compare sum versus mean reductions. Log gradient norms by layer. In a deep stack of maps, each reverse rule multiplies by a local derivative; several expansive maps can amplify sensitivities.
  • Gradients are very small. Inspect activation values and gradient norms at each stage. Several local maps can shrink sensitivities, and a masked or inactive branch can have a derivative of exactly zero. For a residual block y=x+F(x) with a compatible shape, the input gradient includes the direct g term as well as J_Fᵀg. That direct route is useful, but the two terms can still interact.
  • Backward needs a saved value that changed. Keep saved inputs intact until backward completes. Prefer out-of-place operations in new code. In PyTorch, mutating a tensor that a backward rule saved can trigger a version-counter error when the engine attempts to use it.
  • One forward pass needs a second backward call. By default, backward releases saved state as it becomes unnecessary. Use a fresh forward pass or combine scalar objectives when possible. Retaining the graph keeps saved state alive for another pass and increases its lifetime. Collect scalar logging values without retaining their graph references.
  • The backward pass exceeds memory. Investigate which activations are saved and whether gradient recording is needed in the region. Activation checkpointing trades extra forward computation during backward for reduced activation storage. Full Jacobians are rarely an economical substitute for the products in the training loop.

Try it yourself

Find the exact cancellation

For t=ab and L=t²-12t, evaluate the two contributions to dL/dt at a=2, b=3. What happens to the gradients of a and b?

Reveal solution

The square contributes 2t=12 and the linear term contributes -12. They sum to zero. The local derivatives of multiplication are still b=3 and a=2. Multiplying either by the zero accumulated sensitivity gives zero.

Try it yourself

Change the loss reduction

Duplicate the hand-worked network example so the batch has two identical rows. What happens to the gradient on the first output weight if the loss averages the two examples? What if it sums them?

Reveal solution

Each single-example loss contributes 2 to that weight's gradient. Under the mean, each row contributes 1 and the total stays 2. With the sum, each contributes 2 and the total is 4. Bias gradients follow the same reduction.

What should the reverse pass do when two downstream operations depend on the same node?

A function has 50 inputs and 3 outputs. Which shape does a single VJP return under the column-vector convention?

Two fresh forward graphs use the same PyTorch parameters. Both scalar losses call backward before gradients are cleared. What does the leaf gradient buffer contain?

Memory chart#

SituationWhat to carry forward
Scalar chainMultiply sensitivities by local derivatives
Shared nodeAdd the contributions before using its local rule
Forward modeSeed input directions and compute Jd
Reverse modeSeed output sensitivities and compute Jᵀg
Broadcast parameterSum along the axes on which the parameter was reused
Training stepClear, compute loss, backpropagate, then apply the optimizer

Next, The Gradient Descent Family takes these gradients and turns them into parameter updates. You will compare full-batch and minibatch updates, learn what momentum keeps from previous steps, and see how adaptive methods scale individual coordinates.

References#