Slides · Deep learning and transformers
Neural networks and backpropagation: gradients, checks and initialisation
1 / 19
Neural networks and backpropagation
The chain rule run backwards, a numerical check for it, and how activations and initialisation decide whether gradients survive depth.
Concept
Why this is worth an hour
- Most of training a network is diagnosis: zero gradients in the first layers, or a backward pass that is subtly wrong.
- Each has a mechanism that fits in a few lines, and the same questions come up in interviews (common industry pattern).
- The next lesson covers normalisation, regularisation, AdamW, schedules and NaN debugging.
Three things you will be able to do:
- Say why activations are required and count parameters.
- Work backprop on a 2-layer net and gradient-check it.
- Explain vanishing and exploding gradients and how initialisation changes them.
Diagram
Forward and backward
Compare
Layers and shapes
| Tensor | Shape |
|---|---|
| x | d |
| W1, b1 | h×d, h |
| z1, a1 | h |
| W2, b2 | k×h, k |
| z2 | k |
- Parameters: h(d+1)+k(h+1). For 784, 128 and 10 that is 101,770.
- A gradient has the shape of its parameter.
Source[1] Dive into Deep Learning, Multilayer perceptrons (hidden layers, activation functions)
Math
Without an activation, depth collapses
W2(W1x+b1)+b2=(W2W1)x+(W2b1+b2)- An affine function of an affine function is affine: many linear layers equal one.
- XOR needs the activation: h1=ReLU(a+c), h2=ReLU(a+c−1), output h1−2h2 gives [0,1,1,0].
- A search over 15,625 linear rules gets at most 3 of 4 points right.
Source[1] Dive into Deep Learning, Multilayer perceptrons (hidden layers, activation functions)
Compare
Choosing an activation
| Activation | Derivative | Watch for |
|---|---|---|
| Sigmoid | At most 0.25 | Saturation, vanishing gradients |
| Tanh | At most 1 | Saturation |
| ReLU | 1 or 0 | Dead units |
| GELU | Smooth | Small negative values, not zero |
- Sigmoid derivative: 0.25 at 0, 0.0066 at 5, 4.5×10−5 at 10.
- Ten sigmoid layers: derivative part at most 0.2510≈9.5×10−7.
Sources[1] Dive into Deep Learning, Multilayer perceptrons (hidden layers, activation functions)[2] Gaussian Error Linear Units (GELUs)
Check yourself
Check: remove the activations
To speed up a 12-layer model, a teammate removes every activation function and keeps the layers. What can the model represent now?
Answer
Only a single linear map of the input, however many layers remain. The 12 matrices multiply into one, so the extra parameters add no representational power. Keep the activations and shrink the model another way.
Math
The backward recipe
δ2=p−onehot(y),∂L/∂W2=δ2a1⊤,∂L/∂b2=δ2δ1=(W2⊤δ2)⊙1[z1>0],∂L/∂W1=δ1x⊤,∂L/∂b1=δ1- Chain rule from the output backwards; the forward values are cached and reused.
- Backward is about two matrix products per layer against one forward, so about twice the cost.
- Cached activations grow with depth and batch size: training needs more memory than prediction.
Sources[3] Dive into Deep Learning, Forward propagation, backward propagation and computational graphs[4] Dive into Deep Learning, Softmax Regression (softmax and cross-entropy loss, derivative with respect to the logits)
Worked example
Worked example
W1=(0.5−10.250.5), b1=(0,−0.5), W2=(1−10.5−0.25), input (1,2), true class 1.
| Quantity | Value |
|---|---|
| z1, a1 | (1,−0.5), (1,0) |
| p, loss | (0.8808,0.1192), 2.1269 |
| δ2 | (0.8808,−0.8808) |
| W2⊤δ2 | (1.7616, 0.6606) |
| δ1 (masked) | (1.7616, 0) |
| ∂L/∂W1 | (1.7616,3.5232) and (0,0) |
- One step at learning rate 0.1: loss 2.1269 to 0.6089.
Check yourself
Check: change the bias
Change the worked example to b1=(0,1). What happens to the second row of ∂L/∂W1?
Answer
Now z1=(1, 1): the second unit is active, the mask lets its gradient through, and that row is no longer zero. It equals δ1[1]⋅x⊤, with δ1[1] computed from the new forward pass. A gradient is zero because of the forward values, not because of the unit.
Concept
Gradient checking
2hL(θ+h)−L(θ−h) against the analytic gradient- Central difference: error shrinks as h2. Use double precision and a few examples.
- Relative error: 10−7 or less good, above 10−2 probably a bug (CS231n rules of thumb).
- Also: initial loss near lnC, and a tiny batch must overfit.
- In the example: 4 training points reach loss 0.0067; ordinary output init starts at 0.990, a small one at 0.693.
Sources[5] CS231n: Neural Networks Part 3, Learning and Evaluation (gradient checks and sanity checks)[6] A Recipe for Training Neural Networks
Worked example
Three plausible bugs
| Backward pass | Max relative error |
|---|---|
| Correct | 2.4×10−11 |
| ReLU mask forgotten | 1.00 |
| W2 instead of W2⊤ | 0.75 |
| Sign of p−y flipped | 2.00 |
- About ten orders of magnitude separate right from wrong.
- It costs two forward passes per parameter: use it on a tiny net when writing a new layer.
Concept
Gradients are products
- Through L layers the gradient is a product of L per-layer factors.
- Below 1 it vanishes, above 1 it explodes, both exponentially.
- Early layers either learn nothing or take destructive steps.
- Equal weights (zero included) make every unit in a layer identical: the symmetry never breaks.
Source[7] Dive into Deep Learning, Numerical stability and initialization
Worked example
20 layers, width 64
| Setting | Gradient rms, input over output | Per layer |
|---|---|---|
| tanh, std 0.01 | 6.5×10−23 | 0.078 |
| sigmoid, Xavier | 1.3×10−13 | 0.227 |
| ReLU, Xavier | 2.7×10−3 | 0.744 |
| ReLU, He | 2.7 | 1.052 |
| ReLU, 2 times He | 2.9×106 | 2.103 |
- Xavier: variance 2/(nin+nout). He: 2/nin, because ReLU halves the mean square.
- Per-layer factor = weight scale times derivative: saturation does not guarantee vanishing. Tanh at std 1.0 is saturated, yet the gradient grows by 6.7×105.
Sources[8] torch.nn.init[9] Understanding the difficulty of training deep feedforward neural networks[10] Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification
Check yourself
Check: a stuck deep net
A 30-layer ReLU network is initialised with standard deviation 0.01 at every layer. Training loss never moves. Which two quantities do you print first?
Answer
The activation rms and the gradient rms per layer. With std 0.01 both collapse towards zero within a few layers (in the experiment, rms 1.1×10−25 by layer 20). Fix the scale with He initialisation rather than raising the learning rate.
Code
The backward pass in a few lines
Python
def backward(W2, z1, a1, p, y, x):
dz2 = [pk - (k == y) for k, pk in enumerate(p)]
dW2 = [[d * a for a in a1] for d in dz2]
da1 = [sum(W2[k][j] * dz2[k] for k in range(len(dz2))) for j in range(len(a1))]
dz1 = [d if z > 0 else 0.0 for d, z in zip(da1, z1)]
dW1 = [[d * xi for xi in x] for d in dz1]
return dW1, dz1, dW2, dz2
- The homework adds the stable loss, the forward pass and a gradient check.
Summary
Recap
- Activations stop layers collapsing into one linear map; sigmoid and tanh saturate, ReLU can die.
- Backprop: δ2=p−y, send errors back through W⊤ and the ReLU mask, weight gradient = error times input. Gradient-check with a central difference.
- Gradients are products of per-layer factors; sigmoid is at most 0.25 per layer; He for ReLU, Xavier for roughly linear layers; equal weights never break symmetry.
- Next: normalisation, regularisation, AdamW and schedules, and a NaN checklist.
References
References & Sources (1 of 2)
Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book
https://d2l.ai/chapter_multilayer-perceptrons/mlp.html
Used for An affine function of an affine function is affine, so hidden layers without activations add no power; one hidden layer can in principle model any function given enough nodes, but learning the weights is the hard part; derivatives of the sigmoid (maximum 0.25) and tanh (maximum 1); the ReLU derivative convention at 0.
Gaussian Error Linear Units (GELUs) (opens in a new tab)
Dan Hendrycks, Kevin Gimpel2016arXiv:1606.08415Paper
https://arxiv.org/abs/1606.08415
Used for GELU is x times the standard Gaussian CDF of x; it weights inputs by their value rather than gating them by sign as ReLU does.
Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book
https://d2l.ai/chapter_multilayer-perceptrons/backprop.html
Used for Backpropagation traverses the network in reverse order from output to input, reuses stored forward values, and needs more memory in training than in prediction (stored values grow with layers and batch size).
Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book
https://d2l.ai/chapter_linear-classification/softmax-regression.html
Used for The derivative of the cross-entropy loss with respect to the logits is the softmax output minus the label.
Andrej Karpathy, Fei-Fei Li, Justin Johnson2026Book
https://cs231n.github.io/neural-networks-3/
Used for Gradient checks with the centred difference, relative-error thresholds (above 1e-2 probably wrong, 1e-7 or less good; 1e-2 may be acceptable for a 10-layer network because errors build up with depth), double precision, kinks and few data points; the initial loss of about -ln(1/C) = 2.302 for 10 classes; overfitting a tiny subset as a check.
References
References & Sources (2 of 2)
A Recipe for Training Neural Networks (opens in a new tab)
Andrej Karpathy2019Article
https://karpathy.github.io/2019/04/25/recipe/
Used for Verify the initial loss, and overfit a single small batch.
Dive into Deep Learning, Numerical stability and initialization (opens in a new tab)
Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book
https://d2l.ai/chapter_multilayer-perceptrons/numerical-stability-and-init.html
Used for Vanishing and exploding gradients in deep networks; equal-valued hidden weights never break symmetry; Xavier initialisation with variance 2/(n_in + n_out).
torch.nn.init (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/nn.init.html
Used for xavier_normal_ std = gain * sqrt(2/(fan_in + fan_out)); kaiming_normal_ std = gain / sqrt(fan); the ReLU gain is sqrt(2).
Understanding the difficulty of training deep feedforward neural networks (opens in a new tab)
Xavier Glorot, Yoshua Bengio2010AISTATS 2010 (PMLR 9:249-256)Paper
https://proceedings.mlr.press/v9/glorot10a.html
Used for The logistic sigmoid is unsuited to deep networks with random initialisation (abstract: non-zero mean can push the top hidden layer into saturation).
Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun2015arXiv:1502.01852 (ICCV 2015)Paper
https://arxiv.org/abs/1502.01852
Used for A weight initialisation derived for rectifier networks that allows very deep rectified models to be trained from scratch (abstract page only; the variance 2/n_in is derived in the lesson and matches PyTorch's ReLU gain).
Keys: ← → move, Home End first and last, F full screen.