Slides · Deep learning and transformers

Neural networks and backpropagation: gradients, checks and initialisation

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:

  1. Say why activations are required and count parameters.
  2. Work backprop on a 2-layer net and gradient-check it.
  3. Explain vanishing and exploding gradients and how initialisation changes them.

Diagram

Forward and backward

Diagram: The forward pass computes a linear map, a ReLU, a second linear map, a softmax and the loss.

dz2 = p - y

da1 = W2^T dz2

dz1 = da1 * 1[z1 > 0]

x

z1 = W1 x + b1

a1 = ReLU(z1)

z2 = W2 a1 + b2

p = softmax(z2)

Loss: -log p_y

Diagram summary: The forward pass computes a linear map, a ReLU, a second linear map, a softmax and the loss. The backward pass starts with p minus y at the logits, multiplies by the transposed weights to reach the hidden activations, and passes through the ReLU only where the pre-activation was positive.

Compare

Layers and shapes

TensorShape
xxdd
W1, b1W_1,\ b_1h×d, hh\times d,\ h
z1, a1z_1,\ a_1hh
W2, b2W_2,\ b_2k×h, kk\times h,\ k
z2z_2kk
  • Parameters: h(d+1)+k(h+1)h(d+1)+k(h+1). For 784, 128 and 10 that is 101,770.
  • A gradient has the shape of its parameter.

Source1 Dive into Deep Learning, Multilayer perceptrons (hidden layers, activation functions)

Math

Without an activation, depth collapses

W2(W1x+b1)+b2=(W2W1) x+(W2b1+b2)W_2(W_1x+b_1)+b_2=(W_2W_1)\,x+(W_2b_1+b_2)
  • An affine function of an affine function is affine: many linear layers equal one.
  • XOR needs the activation: h1=ReLU(a+c)h_1=\mathrm{ReLU}(a+c), h2=ReLU(a+c−1)h_2=\mathrm{ReLU}(a+c-1), output h1−2h2h_1-2h_2 gives [0,1,1,0][0,1,1,0].
  • A search over 15,625 linear rules gets at most 3 of 4 points right.

Source1 Dive into Deep Learning, Multilayer perceptrons (hidden layers, activation functions)

Compare

Choosing an activation

ActivationDerivativeWatch for
SigmoidAt most 0.25Saturation, vanishing gradients
TanhAt most 1Saturation
ReLU1 or 0Dead units
GELUSmoothSmall negative values, not zero
  • Sigmoid derivative: 0.25 at 0, 0.0066 at 5, 4.5×10−54.5\times10^{-5} at 10.
  • Ten sigmoid layers: derivative part at most 0.2510≈9.5×10−70.25^{10}\approx9.5\times10^{-7}.

Sources1 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\delta_2=p-\mathrm{onehot}(y),\quad \partial L/\partial W_2=\delta_2a_1^{\top},\quad \partial L/\partial b_2=\delta_2δ1=(W2⊤δ2)⊙1[z1>0],∂L/∂W1=δ1x⊤,∂L/∂b1=δ1\delta_1=(W_2^{\top}\delta_2)\odot\mathbb 1[z_1>0],\quad \partial L/\partial W_1=\delta_1x^{\top},\quad \partial L/\partial b_1=\delta_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.

Sources3 Dive into Deep Learning, Forward propagation, backward propagation and computational graphs4 Dive into Deep Learning, Softmax Regression (softmax and cross-entropy loss, derivative with respect to the logits)

Worked example

Worked example

W1=(0.50.25−10.5)W_1=\begin{pmatrix}0.5&0.25\\-1&0.5\end{pmatrix}, b1=(0,−0.5)b_1=(0,-0.5), W2=(10.5−1−0.25)W_2=\begin{pmatrix}1&0.5\\-1&-0.25\end{pmatrix}, input (1,2)(1,2), true class 1.

QuantityValue
z1, a1z_1,\ a_1(1,−0.5), (1,0)(1,-0.5),\ (1,0)
pp, loss(0.8808,0.1192)(0.8808,0.1192), 2.1269
δ2\delta_2(0.8808,−0.8808)(0.8808,-0.8808)
W2⊤δ2W_2^{\top}\delta_2(1.7616, 0.6606)(1.7616,\ 0.6606)
δ1\delta_1 (masked)(1.7616, 0)(1.7616,\ 0)
∂L/∂W1\partial L/\partial W_1(1.7616,3.5232)(1.7616,3.5232) and (0,0)(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)b_1=(0,1). What happens to the second row of ∂L/∂W1\partial L/\partial W_1?

Answer

Now z1=(1, 1)z_1=(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⊤\delta_1[1]\cdot x^{\top}, with δ1[1]\delta_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

L(θ+h)−L(θ−h)2h against the analytic gradient\frac{L(\theta+h)-L(\theta-h)}{2h}\ \text{against the analytic gradient}
  • Central difference: error shrinks as h2h^2. Use double precision and a few examples.
  • Relative error: 10−710^{-7} or less good, above 10−210^{-2} probably a bug (CS231n rules of thumb).
  • Also: initial loss near ln⁡C\ln C, 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.

Sources5 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 passMax relative error
Correct2.4×10−112.4\times10^{-11}
ReLU mask forgotten1.00
W2W_2 instead of W2⊤W_2^{\top}0.75
Sign of p−yp-y flipped2.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 LL layers the gradient is a product of LL 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.

Source7 Dive into Deep Learning, Numerical stability and initialization

Worked example

20 layers, width 64

SettingGradient rms, input over outputPer layer
tanh, std 0.016.5×10−236.5\times10^{-23}0.078
sigmoid, Xavier1.3×10−131.3\times10^{-13}0.227
ReLU, Xavier2.7×10−32.7\times10^{-3}0.744
ReLU, He2.71.052
ReLU, 2 times He2.9×1062.9\times10^{6}2.103
  • Xavier: variance 2/(nin+nout)2/(n_{in}+n_{out}). He: 2/nin2/n_{in}, 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×1056.7\times10^{5}.

Sources8 torch.nn.init9 Understanding the difficulty of training deep feedforward neural networks10 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−251.1\times10^{-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\delta_2=p-y, send errors back through W⊤W^{\top} 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)

  1. Dive into Deep Learning, Multilayer perceptrons (hidden layers, activation functions) (opens in a new tab)

    Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book

    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.

  2. Gaussian Error Linear Units (GELUs) (opens in a new tab)

    Dan Hendrycks, Kevin Gimpel2016arXiv:1606.08415Paper

    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.

  3. Dive into Deep Learning, Forward propagation, backward propagation and computational graphs (opens in a new tab)

    Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book

    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).

  4. Dive into Deep Learning, Softmax Regression (softmax and cross-entropy loss, derivative with respect to the logits) (opens in a new tab)

    Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book

    Used for The derivative of the cross-entropy loss with respect to the logits is the softmax output minus the label.

  5. CS231n: Neural Networks Part 3, Learning and Evaluation (gradient checks and sanity checks) (opens in a new tab)

    Andrej Karpathy, Fei-Fei Li, Justin Johnson2026Book

    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)

  1. A Recipe for Training Neural Networks (opens in a new tab)

    Andrej Karpathy2019Article

    Used for Verify the initial loss, and overfit a single small batch.

  2. Dive into Deep Learning, Numerical stability and initialization (opens in a new tab)

    Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book

    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).

  3. torch.nn.init (opens in a new tab)

    PyTorch2026Documentation

    Used for xavier_normal_ std = gain * sqrt(2/(fan_in + fan_out)); kaiming_normal_ std = gain / sqrt(fan); the ReLU gain is sqrt(2).

  4. Understanding the difficulty of training deep feedforward neural networks (opens in a new tab)

    Xavier Glorot, Yoshua Bengio2010AISTATS 2010 (PMLR 9:249-256)Paper

    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).

  5. Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification (opens in a new tab)

    Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun2015arXiv:1502.01852 (ICCV 2015)Paper

    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).