Skip to content

Backpropagation through layers, and how to check it

Follow the gradient backward through a dense network one layer at a time, see what the backward pass must remember, and verify hand-written gradients with central differences.

Applied ~14 min8 steps

What runs in CodeSplash

You will be able to

  • Write the backward pass of a dense layer in terms of the upstream gradient
  • Explain why training memory grows with batch size, width and depth
  • Run a central-difference gradient check and read its scaled error
  • Name what a passing gradient check does not prove

Read first

01

Backward, one layer at a time

Read

BackpropagationBackpropagationReverse-mode autodiff for networks: the forward pass saves values, the backward pass chains derivatives from the loss to every weight. is the chain ruleChain ruleThe derivative of a composition is the product of the derivatives of its pieces, taken along the path. run from the loss back to the first layer. For softmax with cross-entropy the gradient at the logits is p − y, divided by the batch size. Each dense layer then turns the gradient arriving from above, δ, into three things:

∂L∂W=Hin⊤δ,∂L∂b=∑rowsδ,δbelow=(δW⊤)⊙ϕ′(A)\frac{\partial L}{\partial W} = H_{\text{in}}^\top \delta, \qquad \frac{\partial L}{\partial b} = \textstyle\sum_{\text{rows}} \delta, \qquad \delta_{\text{below}} = (\delta W^\top) \odot \phi'(A)

H_in is the layer's input and A its value before the activation. Every weight gets a gradient from one matrix product.

DExplorable · Backprop, one step at a time

How does the chain rule send a loss's gradient back to every weight?

h reaches the output twice: through v·h and through the skip connection. What should its gradient be?

How sure?
0

Each step processes one operation, from the loss back toward the inputs.

Activation

1.5
−0.5
0.8
−1.2
0.1
0.5
0.2

Gradient-check step ε

x₁1.50w₁0.80x₂−0.50w₂−1.20b0.10×1.20×0.60+1.80+ b1.90tanh0.96v0.50× v0.48+ h1.43y0.20− y1.23L = ²1.52∂ 1.000

Each box shows a value from the forward pass; the number under it is ∂L/∂(that value), filled in as the backward pass reaches it. A value used twice collects gradient from both uses.

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

02

What the backward pass remembers

Read

The formulas need H_in and A from the forward pass, for every layer and every row of the batch. A framework keeps them until the backward pass is done. Training memory therefore grows with batch size × width × depth, on top of the weights, their gradients and the optimizer's state. Adam keeps two extra numbers per weight.

When a network runs out of memory, halving the batch is the first thing to try. It changes the noise in each step, so revisit the learning rate.

03

What runs here

Read
EntryIn CodeSplash
MLP trained by backpropagation (DNN001)Runs in CodeSplash: every torch learner computes gradients with autograd. A hand-written backward pass and its gradient check are code you run in a Python or R notebook
04

Check gradients with central differences

Read

A hand-written backward pass can be wrong and still train a little. A gradient checkGradient checkCompare autodiff gradients with finite differences, (f(θ+h) − f(θ−h)) ÷ 2h, to catch a wrong backward pass. nudges one weight up and down by a small h and compares the slope with your gradient:

gjFD=L(θ+hej)−L(θ−hej)2h,error=∣gjFD−gj∣max⁡(1,∣gjFD∣,∣gj∣)g^{\text{FD}}_j = \frac{L(\theta + h e_j) - L(\theta - h e_j)}{2h}, \qquad \text{error} = \frac{|g^{\text{FD}}_j - g_j|}{\max(1, |g^{\text{FD}}_j|, |g_j|)}

Check a few weights in every array, biases included, in float64 with h near 10⁻⁵. Hold any randomness fixed while you nudge: a new dropout mask in each of the two evaluations ruins the comparison.

Python
import numpy as np

rng = np.random.default_rng(1)
X = rng.normal(size=(8, 3)); y = rng.integers(0, 2, 8).astype(float)
W1 = rng.normal(size=(3, 4)) * 0.5; b1 = np.zeros(4)
w2 = rng.normal(size=4) * 0.5; b2 = 0.0

def loss(W1):
    o = np.tanh(X @ W1 + b1) @ w2 + b2
    return np.mean(np.logaddexp(0, o) - y * o)        # logistic loss on logits

def grad_W1(W1):
    h = np.tanh(X @ W1 + b1); o = h @ w2 + b2
    d_o = (1 / (1 + np.exp(-o)) - y) / len(y)          # dL/d(logit)
    d_a = np.outer(d_o, w2) * (1 - h ** 2)             # back through tanh
    return X.T @ d_a

g, h_step, worst = grad_W1(W1), 1e-5, 0.0
for i in range(3):
    for j in range(4):
        E = np.zeros_like(W1); E[i, j] = h_step
        fd = (loss(W1 + E) - loss(W1 - E)) / (2 * h_step)
        worst = max(worst, abs(fd - g[i, j]) / max(1, abs(fd), abs(g[i, j])))
print("largest scaled error", worst)
R
set.seed(1)
X <- matrix(rnorm(24), 8, 3); y <- rbinom(8, 1, 0.5)
W1 <- matrix(rnorm(12), 3, 4) * 0.5; b1 <- rep(0, 4)
w2 <- rnorm(4) * 0.5; b2 <- 0

loss <- function(W1) {
  o <- drop(tanh(sweep(X %*% W1, 2, b1, "+")) %*% w2) + b2
  mean(pmax(o, 0) + log1p(exp(-abs(o))) - y * o)       # logistic loss on logits
}
grad_W1 <- function(W1) {
  h <- tanh(sweep(X %*% W1, 2, b1, "+")); o <- drop(h %*% w2) + b2
  d_o <- (1 / (1 + exp(-o)) - y) / length(y)
  d_a <- outer(d_o, w2) * (1 - h^2)
  t(X) %*% d_a
}
g <- grad_W1(W1); h_step <- 1e-5; worst <- 0
for (i in 1:3) for (j in 1:4) {
  E <- matrix(0, 3, 4); E[i, j] <- h_step
  fd <- (loss(W1 + E) - loss(W1 - E)) / (2 * h_step)
  worst <- max(worst, abs(fd - g[i, j]) / max(1, abs(fd), abs(g[i, j])))
}
cat("largest scaled error", worst, "\n")

The two programs draw different random data, so their printed errors differ. Both should be far below 10⁻⁶; a gap near the size of the gradient itself means a bug.

05

Watch it train

Explore

DExplorable · Neural network playground

How do hidden units combine straight lines into curved boundaries?

Each hidden unit can draw one straight line. How accurate will this network be on new data?

0.70
How sure?

Data

4
1

Activation

0.50
500
0.000
0.10
120
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

The playground trains by exactly these formulas, written out in Python and R under See the code: forward through each layer, then δ backward, then a gradient step. Train it, then set Learning rate near its maximum and watch the loss curve jump instead of fall.

06

Break the backward pass

Predict

Predict first

Someone forgets the factor (1 − h²), the derivative of tanh, in the line d_a = …. The output weights' gradients don't use that line. What does the gradient check report?

The check passes; the bug is too small to seeThe check fails for W1 onlyThe check fails for every array
Reveal

It fails for W1 only. The output weights' gradients are computed before the bug and still match. That is why you check a few entries in every array: a check on the last layer alone would pass.

07

Check: backpropagation

Checkpoint

Check yourself

In a dense layer, what is the gradient of the loss with respect to the bias b?

Show the answer

Answer: a

Each row adds b once, so its gradient collects δ from every row. The weight gradient is Hᵀδ.

Check yourself

Which change roughly halves the memory a training step needs for stored activations?

Show the answer

Answer: a

Stored activations scale with rows in the batch × width × depth. Epochs and the learning rate don't change what one step holds.

Check yourself

Your gradient check fails only when dropout is on. What's the most likely cause?

Show the answer

Answer: b

Fix the mask (or the random seed) for both evaluations. Then the check compares like with like.

Check yourself

A gradient check passes at 10⁻⁹. What does that establish?

Show the answer

Answer: a

It's local evidence about derivatives. Convergence, a sensible loss and held-out accuracy each need their own check.

08

Recap

Recap
  • A dense layer's backward pass is three matrix expressions: Hᵀδ, the column sums of δ, and (δWᵀ) ⊙ φ′(A).
  • The backward pass needs every layer's stored activations, so memory grows with batch × width × depth.
  • Central differences in float64, a few entries per array, randomness fixed: that's a gradient check.
  • CodeSplash's torch learners get gradients from autograd and write the Adam steps out, so Python and R train the same network.

Concepts in this lesson