Neural networks and backpropagation: gradients, checks and initialisation

  • Intermediate
  • 1 h
  • Lesson 1 of 4 in Deep learning and transformers
  • Last verified

Open slides(19 slides)

Before you start

You will be able to

  • Explain why a network needs non-linear activations, choose between ReLU, GELU, sigmoid and tanh by how they saturate, and give the shape of every tensor and the parameter count of a 2-layer network.
  • Work backpropagation by hand through a 2-layer ReLU network with softmax cross-entropy using the chain rule, and verify the result with a central-difference gradient check.
  • Explain vanishing and exploding gradients as products of per-layer factors, and say how the choice of activation and of Xavier or He initialisation changes those factors.

Concept

A neural network is the same three pieces as every model so far: a function, a loss and an optimizer. The function is a stack of layers, each a linear map followed by a non-linear activation. The loss is one you know, such as cross-entropy. The optimizer is gradient descent. What is new is how the gradient is computed for millions of parameters: backpropagation is the chain rule applied from the output backwards, reusing the numbers saved on the way forward.

In the linear-models lesson the gradient of the loss with respect to the score was prediction minus target, p−yp-y; in a network that quantity appears at the last layer and backpropagation carries it back. That lesson deferred AdamW, learning-rate schedules and gradient clipping, and the first lesson listed early stopping among the fixes for overfitting; they are paid off in the next lesson, which is about keeping a network trainable. This lesson is about how the gradient is computed, checked and kept from vanishing or exploding.

Diagram: The forward pass runs left to right: 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 runs left to right: a linear map, a ReLU, a second linear map, a softmax and the loss. The backward pass runs right to left. It 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.

Why It Matters

Most of the work of getting a network to train is knowing why the loss is flat, why the gradients are zero in the first layers, and whether your backward pass is even correct. Each has a mechanism that fits in a few lines, and these are standard interview questions (common industry pattern).

Mental Model

Picture a relay of 20 people, each multiplying the message by a number before passing it on. If the numbers are a little below 1 the message fades; a little above 1 and it becomes a shout. Forward, the message is the activation. Backward, the relay runs in reverse and the message is the gradient. Initialisation sets the typical multiplier and activations decide how much gets through. Normalisation, which resets the volume, and clipping, which caps the shout, come in the next lesson.

Neurons, layers and shapes

A neuron computes a=ϕ(w⊤x+b)a=\phi(w^{\top}x+b): a weighted sum plus a bias, passed through an activation ϕ\phi. A layer is many neurons reading the same input, which is one matrix multiply: a=ϕ(Wx+b)a=\phi(Wx+b). For one input x∈Rdx\in\mathbb R^{d}, hh hidden units and kk classes:

TensorShapeMeaning
xxddOne input
W1, b1W_1,\ b_1h×d, hh\times d,\ hFirst layer
z1, a1z_1,\ a_1h, hh,\ hPre-activation and activation
W2, b2W_2,\ b_2k×h, kk\times h,\ kOutput layer
z2z_2kkLogits

For a batch of nn inputs stacked as rows, each vector gains a leading nn and Z1=XW1⊤+b1Z_1=XW_1^{\top}+b_1 has shape n×hn\times h. The parameter count is h(d+1)+k(h+1)h(d+1)+k(h+1): 101,770 for 784 inputs, 128 hidden units and 10 classes.

Why a non-linearity is required

An affine function of an affine function is itself affine (Dive into Deep Learning, MLPs): 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). The script checks it on random matrices and finds the two forms differ by about 10−1510^{-15}, which is rounding error. A stack of linear layers is one linear layer with extra parameters.

XOR shows the cost. Write the rule as w1a+w2c+b>0w_1a+w_2c+b>0. The four points require b≤0b\le 0, w1+b>0w_1+b>0, w2+b>0w_2+b>0 and w1+w2+b≤0w_1+w_2+b\le 0. Adding the middle two gives w1+w2+2b>0w_1+w_2+2b>0, so w1+w2+b>−b≥0w_1+w_2+b>-b\ge0, a contradiction (derived here). A search over 15,625 linear rules gets at most 3 of 4 points. Two ReLU units, h1=ReLU(a+c)h_1=\mathrm{ReLU}(a+c) and h2=ReLU(a+c−1)h_2=\mathrm{ReLU}(a+c-1), with output h1−2h2h_1-2h_2, return [0,1,1,0][0,1,1,0] exactly. One hidden layer with enough units can in principle approximate any continuous function (the standard universal approximation statement; the textbook words it more loosely as any function), but finding the weights is the hard part (Dive into Deep Learning, MLPs); the rest of the lesson is about that second problem.

Choosing an activation

ActivationFormulaGradient behaviourTypical use
Sigmoid1/(1+e−z)1/(1+e^{-z})At most 0.25, near 0 for large ∣z∣\lvert z\rvertBinary output; gating (common practice)
Tanhtanh⁡z\tanh zAt most 1, near 0 for large ∣z∣\lvert z\rvertOlder hidden layers; squashing values in recurrent cells (common practice)
ReLUmax⁡(0,z)\max(0,z)1 for z>0z>0, 0 for z<0z<0Default hidden layer
GELUz Φ(z)z\,\Phi(z)Smooth, small non-zero values for negative zzWidely used in transformer language models (common practice)

The sigmoid’s derivative peaks at 0.25 and tanh’s at 1 (Dive into Deep Learning, MLPs). Saturation is the problem: far from zero both flatten. The script prints sigmoid derivatives of 0.25 at z=0z=0, 0.105 at 2, 0.0066 at 5 and 4.5×10−54.5\times10^{-5} at 10, and tanh derivatives of 1, 0.071, 1.8×10−41.8\times10^{-4} and 8.2×10−98.2\times10^{-9}. Over ten sigmoid layers the activation-derivative part of the gradient shrinks by at least 0.2510≈9.5×10−70.25^{10}\approx9.5\times10^{-7}.

ReLU does not saturate for positive inputs and is cheap, but its derivative is exactly 0 for negative zz. A unit that is negative for every input in the data gets no gradient and cannot recover: a dead ReLU (derived here). GELU is zΦ(z)z\Phi(z) with Φ\Phi the standard normal CDF, so it weights inputs by value instead of gating by sign (Hendrycks and Gimpel); the script gives −0.004-0.004 at −3-3 and −0.159-0.159 at −1-1, damped and not zeroed.

One place the non-linearity pays off: a network trained to reproduce its own input through a narrow middle layer is an autoencoder, which can be read as a non-linear counterpart of the PCA in the unsupervised lesson (a loose analogy).

Backpropagation by the chain rule

Training needs ∂L/∂θ\partial L/\partial\theta for every parameter. Backpropagation evaluates the chain-rule product from the output towards the input, so each layer reuses the gradient already computed for the layer after it, and the activations saved in the forward pass (Dive into Deep Learning, backpropagation). One backward sweep gives every parameter’s gradient.

The recipe

For z1=W1x+b1z_1=W_1x+b_1, a1=ReLU(z1)a_1=\mathrm{ReLU}(z_1), z2=W2a1+b2z_2=W_2a_1+b_2, p=softmax(z2)p=\mathrm{softmax}(z_2) and loss L=−log⁡pyL=-\log p_y:

δ2=∂L/∂z2=p−onehot(y)∂L/∂W2=δ2 a1⊤,∂L/∂b2=δ2∂L/∂a1=W2⊤δ2δ1=∂L/∂z1=(W2⊤δ2)⊙1[z1>0]∂L/∂W1=δ1 x⊤,∂L/∂b1=δ1\begin{aligned} \delta_2 &= \partial L/\partial z_2 = p-\mathrm{onehot}(y) \\ \partial L/\partial W_2 &= \delta_2\,a_1^{\top}, \qquad \partial L/\partial b_2=\delta_2 \\ \partial L/\partial a_1 &= W_2^{\top}\delta_2 \\ \delta_1 &= \partial L/\partial z_1=(W_2^{\top}\delta_2)\odot\mathbb 1[z_1>0] \\ \partial L/\partial W_1 &= \delta_1\,x^{\top}, \qquad \partial L/\partial b_1=\delta_1 \end{aligned}

The first line is the softmax result from the linear-models lesson, which carries over to a network’s last layer (Dive into Deep Learning, softmax regression). The pattern repeats: a weight gradient is the error at the layer’s output times its input, and the error goes back through the transposed weights and the activation’s derivative. The ReLU derivative is a mask that passes the gradient where z1>0z_1>0.

Counting multiply-adds (derived here): forward does one matrix-vector product per layer, backward does two of the same size, one for ∂L/∂W\partial L/\partial W and one for ∂L/∂a\partial L/\partial a, so backward costs about twice forward. Memory is the other bill: the saved activations stay until the backward pass finishes and grow with layers and batch size, which is why training needs more memory than prediction (Dive into Deep Learning, backpropagation).

Worked example: one input, two layers

Take 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}, b2=(0,0)b_2=(0,0), input x=(1,2)x=(1,2) and true class y=1y=1 (the second class, counting from 0). The script prints every number below.

StepValue
z1=W1x+b1z_1=W_1x+b_1(1.0, −0.5)(1.0,\ -0.5)
a1=ReLU(z1)a_1=\mathrm{ReLU}(z_1)(1, 0)(1,\ 0)
z2=W2a1+b2z_2=W_2a_1+b_2(1, −1)(1,\ -1)
p=softmax(z2)p=\mathrm{softmax}(z_2)(0.8808, 0.1192)(0.8808,\ 0.1192)
Loss −log⁡p1-\log p_12.1269
δ2=p−y\delta_2=p-y(0.8808, −0.8808)(0.8808,\ -0.8808)
∂L/∂W2\partial L/\partial W_2rows (0.8808, 0)(0.8808,\ 0) and (−0.8808, 0)(-0.8808,\ 0)
W2⊤δ2W_2^{\top}\delta_2(1.7616, 0.6606)(1.7616,\ 0.6606)
δ1\delta_1 after the mask(1.7616, 0)(1.7616,\ 0)
∂L/∂W1\partial L/\partial W_1rows (1.7616, 3.5232)(1.7616,\ 3.5232) and (0, 0)(0,\ 0)

The model puts 88% on the wrong class, so the loss and δ2\delta_2 are large. The second hidden unit was inactive (z1=−0.5z_1=-0.5): it passed nothing forward, so its output weights get zero gradient, and the mask blocks the 0.6606 arriving from above, so its input weights get zero too. One step at learning rate 0.1 takes the loss from 2.1269 to 0.6089.

Checking gradients numerically

A hand-written backward pass is easy to get subtly wrong, and a wrong gradient still gives a loss that moves. The test is the definition of a derivative: nudge one parameter by ±h\pm h and compare. The central difference (L(θ+h)−L(θ−h))/2h(L(\theta+h)-L(\theta-h))/2h has error shrinking as h2h^2, against hh for a one-sided difference. CS231n’s rules of thumb for the relative error: above 10−210^{-2} the gradient is probably wrong, 10−710^{-7} or below is good, and larger values can be acceptable where the function has kinks. Errors build up with depth, so for a 10-layer network 1e-2 may be acceptable. It recommends double precision, and a few data points, because a nudge across a ReLU kink makes the two gradients legitimately disagree (CS231n).

On the worked example with h=10−5h=10^{-5}, all 12 parameters agree to a maximum relative error of 2.4×10−112.4\times10^{-11}. Three plausible bugs in the backward pass only:

BugMax relative error
Correct code2.4×10−112.4\times10^{-11}
ReLU mask forgotten1.00
W2W_2 used where W2⊤W_2^{\top} is needed0.75
Sign of p−yp-y flipped2.00

The check costs two forward passes per parameter, so use it on a tiny network when you write a new layer. Two cheaper checks: the initial loss should be about ln⁡C\ln C (2.3026 for 10 classes), and the model must overfit a tiny batch to near zero loss (CS231n; Karpathy). In the script’s two-class network with the output weights scaled by 0.01 the initial loss is 0.693, which is ln⁡2\ln 2, against 0.990 for ordinary output initialisation. Four training points reach a loss of 0.0067 after 300 epochs.

Vanishing and exploding gradients

Through LL layers the gradient is a product of LL per-layer factors, each made of weights and an activation derivative. Below 1 the product shrinks exponentially; above 1 it grows exponentially. The early layers either learn nothing or receive updates large enough to destroy the model (Dive into Deep Learning, numerical stability). The same arithmetic applies forward to the activations.

Initialisation: Xavier and He

Initialisation sets the typical factor before training. All-zero (or any constant) weights are a trap: every hidden unit computes and receives the same thing, so the symmetry never breaks (Dive into Deep Learning, numerical stability). Small random weights break it, and their scale decides whether signals survive depth. Glorot and Bengio found the logistic sigmoid poorly suited to deep networks with random initialisation, because its non-zero mean can push the top hidden layer into saturation (Glorot and Bengio).

Both standard schemes choose the weight variance so activation variance stays roughly constant across layers. Xavier (Glorot) uses variance 2/(nin+nout)2/(n_{in}+n_{out}) (PyTorch, nn.init), which is 1/n1/n for a square layer. It does not account for ReLU, which zeroes about half the pre-activations and halves the mean square, so He initialisation doubles the variance to 2/nin2/n_{in} (derived here; He et al. derived an initialisation for rectifiers). PyTorch’s Kaiming initialiser uses a gain of 2\sqrt2 for ReLU, with standard deviation gain over fan\sqrt{\text{fan}}.

The script tests it: 20 layers of width 64, eight random inputs, the rms activation at layers 1 and 20, and the rms of the gradient at the input over its rms at the output.

Activation and weight scaleActivation rms, layer 1 to 20Gradient rms, input over outputGradient factor per layer
tanh, std 0.010.081 to 1.1×10−221.1\times10^{-22}6.5×10−236.5\times10^{-23}0.078
tanh, Xavier0.64 to 0.160.1150.898
tanh, std 1.00.96 to 0.94 (saturated)6.7×1056.7\times10^{5}1.955
sigmoid, Xavier0.53 to 0.521.3×10−131.3\times10^{-13}0.227
ReLU, std 0.010.056 to 1.1×10−251.1\times10^{-25}3.1×10−253.1\times10^{-25}0.059
ReLU, Xavier0.70 to 9.3×10−49.3\times10^{-4}2.7×10−32.7\times10^{-3}0.744
ReLU, He0.99 to 0.952.71.052
ReLU, 2 times He2.0 to 1.0×1061.0\times10^{6}2.9×1062.9\times10^{6}2.103

The gradient column stays within a factor of about 3 across weight seeds 0, 1 and 2 (the script prints all three). What it shows:

  • Scale decides. Too small and the signal vanishes both ways; too large and it explodes. A factor of two in variance separates ReLU with He (stable) from ReLU with Xavier, whose activation rms is multiplied by about 0.71 per layer (it keeps 71%), matching 1/2\sqrt{1/2}.
  • Sigmoid vanishes even at a sensible scale. The gradient is multiplied by about 0.23 per layer; ten layers give a factor near 4×10−74\times10^{-7} (derived here).
  • Saturation does not guarantee vanishing. The per-layer factor is the weight scale times the activation derivative. With tanh at std 1.0 the activations sit near ±1\pm1 where the derivative is small, yet the gradient grows by 6.7×1056.7\times10^{5} towards the input, because the large weights outweigh it.

Remedies: ReLU-family activations, a scale-aware initialisation and, covered in the next lesson, normalisation layers and gradient clipping. Residual connections give the gradient a path around layers; they belong with architectures later in this module.

Code

This standard-library script produced every number in the lesson. It has fixed seeds and runs in about 2 seconds (Python 3.14). Another Python version may draw different random data, which moves the exact numbers in sections 4 and 5 but not their orders of magnitude or the pattern.

Python

import itertools
import math
import random
import statistics
import time

T0 = time.time()


def matvec(W, v):
    return [sum(w * x for w, x in zip(row, v)) for row in W]


def softmax(z):
    m = max(z)
    e = [math.exp(a - m) for a in z]
    s = sum(e)
    return [a / s for a in e]


def rms(v):
    return math.sqrt(sum(a * a for a in v) / len(v))


# ---- a 2-layer network: x -> ReLU(W1 x + b1) -> softmax(W2 a1 + b2) ----
def forward(P, x, mask=None):
    W1, b1, W2, b2 = P
    z1 = [s + b for s, b in zip(matvec(W1, x), b1)]
    a1 = [max(0.0, z) for z in z1]
    if mask:
        a1 = [a * m for a, m in zip(a1, mask)]
    z2 = [s + b for s, b in zip(matvec(W2, a1), b2)]
    return z1, a1, z2, softmax(z2)


def loss_of(P, x, y):
    return -math.log(forward(P, x)[3][y])


def backward(P, x, y, cache, mask=None):
    W1, b1, W2, b2 = P
    z1, a1, z2, p = cache
    dz2 = [pk - (1.0 if k == y else 0.0) 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))]
    if mask:
        da1 = [d * m for d, m in zip(da1, mask)]
    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], dz2, da1, dz1


def cells(T):
    for t in T:
        if isinstance(t[0], list):
            for row in t:
                for j in range(len(row)):
                    yield row, j
        else:
            for j in range(len(t)):
                yield t, j


def numeric_grad(P, x, y, h=1e-5):
    out = []
    for c, j in cells(P):
        old = c[j]
        c[j] = old + h
        up = loss_of(P, x, y)
        c[j] = old - h
        dn = loss_of(P, x, y)
        c[j] = old
        out.append((up - dn) / (2 * h))
    return out


def rel_err(a, n):
    return abs(a - n) / max(abs(a), abs(n), 1e-8)


print("== 1. Worked example: 2 inputs, 2 ReLU units, 2 classes, label y = class 1 ==")
P = [[[0.5, 0.25], [-1.0, 0.5]], [0.0, -0.5], [[1.0, 0.5], [-1.0, -0.25]], [0.0, 0.0]]
x, y = [1.0, 2.0], 1
cache = forward(P, x)
z1, a1, z2, p = cache
G, dz2, da1, dz1 = backward(P, x, y, cache)
print("z1", z1, "a1", a1, "z2", z2)
print("p", [round(v, 4) for v in p], "loss", round(loss_of(P, x, y), 4))
print("dz2 = p - y", [round(v, 4) for v in dz2])
print("dW2", [[round(v, 4) for v in r] for r in G[2]], "db2", [round(v, 4) for v in G[3]])
print("da1 = W2^T dz2", [round(v, 4) for v in da1], " dz1 = da1 * 1[z1>0]", [round(v, 4) for v in dz1])
print("dW1", [[round(v, 4) for v in r] for r in G[0]], "db1", [round(v, 4) for v in G[1]])
flat = [g for c, j in cells(G) for g in [c[j]]]
num = numeric_grad(P, x, y)
print("gradient check, 12 parameters, central difference h=1e-5: max abs diff %.1e, max relative error %.1e"
      % (max(abs(a - n) for a, n in zip(flat, num)), max(rel_err(a, n) for a, n in zip(flat, num))))
# the same check on three plausible bugs
def check(G_bad):
    f = [g for c, j in cells(G_bad) for g in [c[j]]]
    return max(rel_err(a, n) for a, n in zip(f, num))
no_mask = [[[d * xi for xi in x] for d in da1], da1, G[2], G[3]]
flipped = [[[-v for v in r] for r in G[0]], [-v for v in G[1]], [[-v for v in r] for r in G[2]], [-v for v in G[3]]]
W2 = P[2]
wrong = [W2[0][0] * dz2[0] + W2[0][1] * dz2[1], W2[1][0] * dz2[0] + W2[1][1] * dz2[1]]  # rows, not columns
dz1_t = [d if z > 0 else 0.0 for d, z in zip(wrong, z1)]
wrongT = [[[d * xi for xi in x] for d in dz1_t], dz1_t, G[2], G[3]]
print("bug: ReLU mask forgotten      -> max relative error %.2f" % check(no_mask))
print("bug: sign of p - y flipped    -> max relative error %.2f" % check(flipped))
print("bug: W2 used where W2^T needed -> max relative error %.2f" % check(wrongT))
lr = 0.1
Q = [[r[:] for r in P[0]], P[1][:], [r[:] for r in P[2]], P[3][:]]
for (c, j), (g, k) in zip(cells(Q), cells(G)):
    c[j] -= lr * g[k]
print("after one step lr=0.1: loss %.4f -> %.4f" % (loss_of(P, x, y), loss_of(Q, x, y)))

print("\n== 2. Why a non-linearity ==")
rng = random.Random(0)
A1 = [[rng.gauss(0, 1) for _ in range(3)] for _ in range(4)]
c1 = [rng.gauss(0, 1) for _ in range(4)]
A2 = [[rng.gauss(0, 1) for _ in range(4)] for _ in range(2)]
c2 = [rng.gauss(0, 1) for _ in range(2)]
A = [[sum(A2[i][k] * A1[k][j] for k in range(4)) for j in range(3)] for i in range(2)]
cc = [sum(A2[i][k] * c1[k] for k in range(4)) + c2[i] for i in range(2)]
worst = 0.0
for _ in range(5):
    v = [rng.gauss(0, 1) for _ in range(3)]
    two = [s + b for s, b in zip(matvec(A2, [s + b for s, b in zip(matvec(A1, v), c1)]), c2)]
    one = [s + b for s, b in zip(matvec(A, v), cc)]
    worst = max(worst, max(abs(a - b) for a, b in zip(two, one)))
print("two stacked linear layers vs one layer (A2 A1)x + (A2 c1 + c2): max difference %.1e" % worst)
pts = [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 0)]
best = 0
grid = [i / 4 for i in range(-12, 13)]
for w1, w2, b in itertools.product(grid, repeat=3):
    best = max(best, sum((w1 * a + w2 * c + b > 0) == bool(t) for (a, c), t in pts))
print("XOR: best linear rule found on a 25^3 grid classifies %d of 4" % best)
xor_out = []
for (a, c), t in pts:
    h1, h2 = max(0, a + c), max(0, a + c - 1)
    xor_out.append(h1 - 2 * h2)
print("XOR with hidden relu(a+c), relu(a+c-1), output h1 - 2 h2:", xor_out)

print("parameters of 784 -> 128 -> 10:", 128 * (784 + 1) + 10 * (128 + 1))

print("\n== 3. Derivatives and saturation ==")
sig = lambda z: 1 / (1 + math.exp(-z))
for z in (0, 2, 5, 10):
    print("z=%2d sigmoid' %.2e   tanh' %.2e" % (z, sig(z) * (1 - sig(z)), 1 - math.tanh(z) ** 2))
print("best-case product of 10 sigmoid derivatives: 0.25**10 = %.2e" % 0.25 ** 10)
gelu = lambda z: z * 0.5 * (1 + math.erf(z / math.sqrt(2)))
print("GELU at -3, -1, 0, 1, 3:", [round(gelu(z), 4) for z in (-3, -1, 0, 1, 3)])

print("\n== 4. Signal through 20 layers of width 64 (8 random inputs, rms of the activations) ==")
def deep(act, std_fn, depth=20, width=64, seed=0):
    rng = random.Random(seed)
    Ws = [[[rng.gauss(0, std_fn(width)) for _ in range(width)] for _ in range(width)] for _ in range(depth)]
    fwd, bwd = [], []
    for _ in range(8):
        a = [rng.gauss(0, 1) for _ in range(width)]
        zs = []
        acts = [a]
        for W in Ws:
            z = matvec(W, a)
            a = [act(v) for v in z]
            zs.append(z)
            acts.append(a)
        fwd.append([rms(v) for v in acts])
        g = [1.0] * width  # d(sum of last activations)/d(last activations)
        norms = [rms(g)]
        for l in range(depth - 1, -1, -1):
            dz = [gi * (1 - math.tanh(z) ** 2 if act is math.tanh else (sig(z) * (1 - sig(z)) if act is sig else (1.0 if z > 0 else 0.0))) for gi, z in zip(g, zs[l])]
            g = [sum(Ws[l][i][j] * dz[i] for i in range(width)) for j in range(width)]
            norms.append(rms(g))
        bwd.append(norms[::-1])
    mean = lambda rows, i: statistics.mean(r[i] for r in rows)
    return [mean(fwd, i) for i in (1, 5, 10, 20)], mean(bwd, 0) / mean(bwd, 20), (mean(fwd, 20) / mean(fwd, 1)) ** (1 / 19)
relu = lambda v: max(0.0, v)
rows = [
    ("tanh, std 0.01", math.tanh, lambda n: 0.01),
    ("tanh, Xavier sqrt(1/n)", math.tanh, lambda n: math.sqrt(1 / n)),
    ("tanh, std 1.0", math.tanh, lambda n: 1.0),
    ("sigmoid, Xavier sqrt(1/n)", sig, lambda n: math.sqrt(1 / n)),
    ("ReLU, std 0.01", relu, lambda n: 0.01),
    ("ReLU, Xavier sqrt(1/n)", relu, lambda n: math.sqrt(1 / n)),
    ("ReLU, He sqrt(2/n)", relu, lambda n: math.sqrt(2 / n)),
    ("ReLU, 2x He sqrt(8/n)", relu, lambda n: math.sqrt(8 / n)),
]
print("activation rms at layers 1, 5, 10, 20 | gradient rms at input / at output | activation factor per layer | gradient factor per layer")
for name, act, sd in rows:
    f, b, pl = deep(act, sd)
    print("%-26s %s | %.2e | %.3f | %.3f" % (name, ["%.2e" % v for v in f], b, pl, b ** (1 / 20)))

print("same gradient ratio with weight seeds 0, 1, 2:")
for name, act, sd in rows:
    print("  %-26s %s" % (name, ["%.1e" % deep(act, sd, seed=k)[1] for k in (0, 1, 2)]))


# ---- a small data set: two moons ----
def moons(n, noise, rng):
    X, Y = [], []
    for i in range(n):
        c, t = i % 2, rng.uniform(0, math.pi)
        px, py = (math.cos(t), math.sin(t)) if c == 0 else (1 - math.cos(t), 0.5 - math.sin(t))
        X.append([px + rng.gauss(0, noise), py + rng.gauss(0, noise)])
        Y.append(c)
    return X, Y

def init(rng, H, d=2, k=2, out_scale=1.0):
    return [[[rng.gauss(0, math.sqrt(2 / d)) for _ in range(d)] for _ in range(H)], [0.0] * H,
            [[rng.gauss(0, math.sqrt(2 / H) * out_scale) for _ in range(H)] for _ in range(k)], [0.0] * k]

def evaluate(P, X, Y):
    L, ok = 0.0, 0
    for x, y in zip(X, Y):
        p = forward(P, x)[3]
        L -= math.log(max(p[y], 1e-12))
        ok += p.index(max(p)) == y
    return L / len(X), ok / len(X)

print("\n== 5. Initial loss and overfitting a tiny batch (two-moons data) ==")
rng = random.Random(3)
Xs, Ys = moons(200, 0.35, rng)
for scale in (1.0, 0.01):
    print("initial loss on 200 points, output weights x%s: mean over 8 seeds %.3f" % (scale, statistics.fmean(evaluate(init(random.Random(s), 16, out_scale=scale), Xs, Ys)[0] for s in range(8))))
Xt, Yt = Xs[:4], Ys[:4]
Pt = init(random.Random(0), 16)
for ep in range(300):
    for x, y in zip(Xt, Yt):
        G = backward(Pt, x, y, forward(Pt, x))[0]
        for (c, j), (g, k) in zip(cells(Pt), cells(G)):
            c[j] -= 0.5 * g[k] / 4
print("4 points, 300 epochs, lr 0.5: loss %.4f, accuracy %.2f" % evaluate(Pt, Xt, Yt))
print("total %.1f s" % (time.time() - T0))

What to look for: section 1 (the worked example, the gradient check and the three bugs), section 2 (stacked linear layers collapse, XOR, and the parameter count), section 3 (derivatives, saturation and GELU), section 4 (the table of initialisations and the three weight seeds), section 5 (initial loss and overfitting four points). In PyTorch the equivalents are nn.Linear, loss.backward(), torch.autograd.gradcheck and nn.init.kaiming_normal_.

Real-World Application

A sound first step with any new network: check that the initial loss is near ln⁡C\ln C, overfit a handful of examples, and gradient-check any layer you wrote yourself. When a deep network does not train, print the activation and gradient scale per layer before touching the learning rate: a scale that collapses or grows by a constant factor per layer points to initialisation or activation choice, as in the table above. The next lesson covers what keeps a run stable once the gradients flow.

Interview Perspective

Expect “derive backpropagation for a two-layer network”, “why do we need non-linear activations”, “what causes vanishing gradients and how do you fix them” and “why not initialise all weights to zero”. A strong answer writes the forward pass, goes backwards with the chain rule, names the mask and the transposed weights, and adds a check. A weak answer recites “use ReLU” without saying what it changes.

Provenance: Common industry pattern. These are standard fundamentals for ML roles, not a verified list for any named company.

Practice Questions

  • Basic: Why can a network with ten layers and no activation functions not learn XOR?
  • Intermediate: Write the backward pass for a 2-layer ReLU network with softmax cross-entropy, including the shape of every gradient.
  • Intermediate: A 30-layer ReLU network is initialised with Xavier weights and the first layer’s gradient is a thousand times smaller than the last. What do you change, and what per-layer factor do you expect afterwards?
  • Advanced: Your gradient check reports a relative error of 3e-3 on a 20-layer ReLU network. What do you do before declaring a bug?
  • Product-Company (Generated practice): A teammate’s custom layer trains but the model is worse than a baseline. How do you decide whether the layer’s backward pass is correct?

Activity

Redo the worked example by hand with the label changed to class 0, then run the script’s section 1 with y = 0 and compare. Next, change the first bias to [0.0, 1.0] so both hidden units are active and find which gradient entries stop being zero. Finally, introduce a deliberate bug in the backward pass, predict whether the gradient check will catch it, and then run it.

Homework

Implement the pieces that make a small network checkable: a stable softmax cross-entropy, the forward and backward pass of a 2-layer ReLU network, and a central-difference gradient check with a relative-error measure. The code is in homework/; run the tests until they pass.

Quick Revision

  • A network is stacked linear maps and activations; without the activation it collapses to one linear map, and XOR cannot be solved linearly.
  • Backprop: δ2=p−y\delta_2=p-y, ∂L/∂W2=δ2a1⊤\partial L/\partial W_2=\delta_2a_1^{\top}, δ1=(W2⊤δ2)⊙1[z1>0]\delta_1=(W_2^{\top}\delta_2)\odot\mathbb 1[z_1>0], ∂L/∂W1=δ1x⊤\partial L/\partial W_1=\delta_1x^{\top}. Cache the forward values.
  • Check new gradients with a central difference; relative error near 10−710^{-7} or lower is good, above 10−210^{-2} is probably a bug (deeper nets accumulate error). Check the initial loss against ln⁡C\ln C and overfit a tiny batch.
  • Gradients are products of per-layer factors. Sigmoid is at most 0.25 per layer. He (2/nin2/n_{in}) for ReLU, Xavier (2/(nin+nout)2/(n_{in}+n_{out})) for roughly linear activations; equal weights never break symmetry.

Check yourself

  • Walk-through: Without notes, derive δ1\delta_1 and ∂L/∂W1\partial L/\partial W_1 for the 2-layer ReLU network, then say how you would check the result.
  • Variation: Replace ReLU with sigmoid in a 10-layer network. Which factor shrinks the gradient, by how much at best, and what two changes would you try?
  • Common misconception: “Zero initialisation is fine because the gradients will differ”, and “ReLU never has vanishing gradients”.

Resources & Further Reading

Checked sources to go deeper. The essential ones come first in each group.

Further reading

Research papers

More for this module: Deep learning and transformers resources

Practice

Test what you just read. Quizzes and cards are grouped by module: Deep learning and transformers.

Check yourself12 questions on what this lesson set out to teach

Checking answers needs JavaScript. You can still read every question and option below.

0 of 12 answered

Keyboard: arrow keys move between options. Space or Enter selects the focused option.

ObjectiveExplain why a network needs non-linear activations, choose between ReLU, GELU, sigmoid and tanh by how they saturate, and give the shape of every tensor and the parameter count of a 2-layer network.

  1. Question 1 of 12A classifier takes 20 input features, has one hidden layer of 50 units, and predicts 4 classes. Every layer has a bias. How many trainable parameters does it have?

    Choose one answer.

  2. Question 2 of 12A hidden ReLU unit's pre-activation is negative for every example in the training set. What happens to that unit's own weights during training?

    Choose one answer.

  3. Question 3 of 12Which of these statements about activations and depth are true? Select all that apply.

    Choose all that apply.

  4. Question 4 of 12A mini-batch X has 32 rows and 784 columns, and W1 has shape 128 x 784 (hidden units by inputs). What is the shape of the hidden pre-activation Z1 = X W1^T + b1?

    Choose one answer.

ObjectiveWork backpropagation by hand through a 2-layer ReLU network with softmax cross-entropy using the chain rule, and verify the result with a central-difference gradient check.

  1. Question 5 of 12In a classifier the logits z2 have 3 entries and the hidden activation a1 has 5. What is the shape of dL/dW2, and how is it formed?

    Choose one answer.

  2. Question 6 of 12Use the lesson's worked-example network and input, but now the true class is 0. The softmax output is still (0.8808, 0.1192). What is the error delta1 at the hidden pre-activations?

    Choose one answer.

  3. Question 7 of 12You compare a hand-written backward pass with a central-difference check on a small ReLU network in double precision. The maximum relative error is 0.4. What is the best conclusion?

    Choose one answer.

  4. Question 8 of 12Which statements about the backward pass of the lesson's 2-layer network are true? Select all that apply.

    Choose all that apply.

ObjectiveExplain vanishing and exploding gradients as products of per-layer factors, and say how the choice of activation and of Xavier or He initialisation changes those factors.

  1. Question 9 of 12A 40-layer, width-64 ReLU network is initialised with Xavier weights (variance 1/n for square layers). The loss does not move and the gradients in the first layers are close to zero. What is the most likely cause?

    Choose one answer.

  2. Question 10 of 12A 20-layer tanh network has weights drawn with standard deviation 1.0 at every layer (width 64). Which observations agree with the lesson's experiment? Select all that apply.

    Choose all that apply.

  3. Question 11 of 12A 12-layer sigmoid network with Xavier weights trains slowly: the gradient at the first layer is roughly 1e-8 of the gradient at the last. Which change addresses the cause?

    Choose one answer.

  4. Question 12 of 12Every weight in a small network, in all layers, is initialised to 0.1, with zero biases. After training, all hidden units in a layer still have identical weights. Why?

    Choose one answer.