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.
What runs in CodeSplash
- DNN001Multilayer perceptron (MLP) Runs in CodeSplash
- Deep neural network (torch MLP) Verified in Python and R
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
Backward, one layer at a time
ReadBackpropagationBackpropagationReverse-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:
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?
Each step processes one operation, from the loss back toward the inputs.
Activation
Gradient-check step ε
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 to see the result.
What the backward pass remembers
ReadThe 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.
What runs here
Read| Entry | In 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 |
Check gradients with central differences
ReadA 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:
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.
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)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.
Watch it train
ExploreDExplorable · 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?
Data
Activation
Commit your prediction above to see the result
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.
Break the backward pass
PredictPredict 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?
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.
Check: backpropagation
CheckpointCheck 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.
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