Homework · Runs in your browser

Backpropagation from scratch, with a gradient check

Build the pieces that make a small neural network checkable with nothing but the standard library: a stable softmax cross-entropy, the forward and backward pass of a 2-layer ReLU network, and a central-difference gradient check. Edit starter.py, then run the tests. In the browser runner, press Run tests. In Colab or on your own machine, put starter.py and test_starter.py in one folder and run pytest. Nothing needs installing except pytest.

Hints:

  • Softmax and cross-entropy: subtract the largest logit first. Compute the loss as logsumexp(z) - z[y], never as the log of a softmax output.
  • Backward pass order: dz2 = p - onehot(y), dW2 = dz2 a1^T, db2 = dz2, da1 = W2^T dz2, dz1 = da1 where z1 > 0 and 0 elsewhere, dW1 = dz1 x^T, db1 = dz1.
  • Lesson check: weights W1 = [[0.5, 0.25], [-1, 0.5]], b1 = [0, -0.5], W2 = [[1, 0.5], [-1, -0.25]], b2 = [0, 0], input [1, 2] and label 1 give loss 2.1269 and a hidden gradient db1 = [1.7616, 0].
  • Numerical gradient: central difference (loss(w + h) - loss(w - h)) / (2h), one number at a time, and put each number back.
  • Try it: replace one line of your backward pass with a wrong one (drop the ReLU mask, or use W2 where W2 transposed is needed) and watch max_relative_error jump from about 1e-11 to 0.75 or more.

Running the tests needs JavaScript. You can still read the starter code below and run it on your own machine with pytest.

Tab inserts 4 spaces. To move on with the keyboard, press Esc, then Tab. Shift+Tab always moves back.

Show a solution

Try it yourself first. This site is static, so the solution is sent to your browser with the page; it is hidden here, not secret.

import math


def matvec(W, v):
    """Matrix (list of rows) times vector."""
    return [sum(w * x for w, x in zip(row, v)) for row in W]


def softmax(z):
    """Numerically stable softmax: subtract the maximum before exponentiating."""
    m = max(z)
    e = [math.exp(v - m) for v in z]
    s = sum(e)
    return [v / s for v in e]


def cross_entropy_from_logits(z, y):
    """-log softmax(z)[y], computed as logsumexp(z) - z[y] so large logits do not break it."""
    m = max(z)
    return m + math.log(sum(math.exp(v - m) for v in z)) - z[y]


def forward_backward(params, x, y):
    """Loss and gradients of a 2-layer ReLU network with softmax cross-entropy.

    params = (W1, b1, W2, b2); x is one input vector; y is the true class index.
    Returns (loss, (dW1, db1, dW2, db2)) with the same shapes as params.
    """
    W1, b1, W2, b2 = params
    z1 = [s + b for s, b in zip(matvec(W1, x), b1)]
    a1 = [max(0.0, v) for v in z1]
    z2 = [s + b for s, b in zip(matvec(W2, a1), b2)]
    p = softmax(z2)
    loss = cross_entropy_from_logits(z2, y)

    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))]
    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 loss, (dW1, dz1, dW2, dz2)


def flatten(tensors):
    """Flatten (W1, b1, W2, b2) or its gradients into one list, in that order."""
    out = []
    for t in tensors:
        if isinstance(t[0], list):
            out.extend(v for row in t for v in row)
        else:
            out.extend(t)
    return out


def numeric_gradient(params, x, y, h=1e-5):
    """Central-difference gradient, flattened in the order of flatten(params).

    Change one number at a time by +h and -h, read the loss, put the number back.
    """
    grads = []
    for t in params:
        rows = t if isinstance(t[0], list) else [t]
        for row in rows:
            for j in range(len(row)):
                old = row[j]
                row[j] = old + h
                up = forward_backward(params, x, y)[0]
                row[j] = old - h
                down = forward_backward(params, x, y)[0]
                row[j] = old
                grads.append((up - down) / (2 * h))
    return grads


def max_relative_error(a, b, floor=1e-8):
    """Largest |a_i - b_i| / max(|a_i|, |b_i|, floor) over the two flat lists."""
    return max(abs(u - v) / max(abs(u), abs(v), floor) for u, v in zip(a, b))
Show the tests (test_starter.py)

Python

import math
import random

from starter import (
    cross_entropy_from_logits,
    flatten,
    forward_backward,
    max_relative_error,
    numeric_gradient,
    softmax,
)


def lesson_params():
    return (
        [[0.5, 0.25], [-1.0, 0.5]],
        [0.0, -0.5],
        [[1.0, 0.5], [-1.0, -0.25]],
        [0.0, 0.0],
    )


def random_params(rng, n_in, n_hidden, n_out):
    return (
        [[rng.gauss(0, 1) for _ in range(n_in)] for _ in range(n_hidden)],
        [rng.gauss(0, 1) for _ in range(n_hidden)],
        [[rng.gauss(0, 1) for _ in range(n_hidden)] for _ in range(n_out)],
        [rng.gauss(0, 1) for _ in range(n_out)],
    )


def test_softmax_sums_to_one_and_matches_lesson():
    p = softmax([1.0, -1.0])
    assert math.isclose(sum(p), 1.0)
    assert math.isclose(p[0], 0.8807970780, abs_tol=1e-9), "the lesson's logits [1, -1] give 0.8808"


def test_softmax_survives_large_logits():
    p = softmax([1000.0, 0.0])
    assert math.isclose(p[0], 1.0) and p[1] == 0.0, "subtract the maximum first"
    q = softmax([1000.0, 1000.0])
    assert math.isclose(q[0], 0.5), "equal huge logits must give 0.5 each"


def test_cross_entropy_matches_lesson_and_large_logits():
    assert math.isclose(cross_entropy_from_logits([1.0, -1.0], 1), 2.1269280110, abs_tol=1e-9)
    assert math.isclose(cross_entropy_from_logits([1000.0, 0.0], 1), 1000.0), "logsumexp - z[y] = 1000, no log(0)"
    assert math.isclose(cross_entropy_from_logits([0.0, 0.0, 0.0], 2), math.log(3)), "a uniform guess costs ln(classes)"


def test_forward_backward_loss_and_output_gradients():
    loss, (dW1, db1, dW2, db2) = forward_backward(lesson_params(), [1.0, 2.0], 1)
    assert math.isclose(loss, 2.1269280110, abs_tol=1e-9)
    assert math.isclose(db2[0], 0.8807970780, abs_tol=1e-9) and math.isclose(db2[1], -0.8807970780, abs_tol=1e-9)
    assert math.isclose(dW2[0][0], 0.8807970780, abs_tol=1e-9), "dW2 = dz2 a1^T, and a1 = [1, 0]"
    assert dW2[0][1] == 0.0 and dW2[1][1] == 0.0, "the dead unit has activation 0, so its output weights get no gradient"


def test_forward_backward_hidden_gradients_use_w2_transpose_and_relu_mask():
    _, (dW1, db1, dW2, db2) = forward_backward(lesson_params(), [1.0, 2.0], 1)
    assert math.isclose(db1[0], 1.7615941560, abs_tol=1e-9), "da1[0] = 1*0.8808 + (-1)(-0.8808) = 1.7616"
    assert db1[1] == 0.0, "da1[1] = 0.6606 but z1[1] < 0, so the ReLU blocks it"
    assert math.isclose(dW1[0][0], 1.7615941560, abs_tol=1e-9) and math.isclose(dW1[0][1], 3.5231883120, abs_tol=1e-9)
    assert dW1[1] == [0.0, 0.0]


def test_analytic_gradient_matches_numeric_on_a_non_square_network():
    rng = random.Random(7)
    params = random_params(rng, 3, 5, 4)
    x, y = [0.3, -1.2, 0.8], 2
    _, grads = forward_backward(params, x, y)
    numeric = numeric_gradient(params, x, y)
    assert len(numeric) == 3 * 5 + 5 + 4 * 5 + 4
    assert max_relative_error(flatten(grads), numeric) < 1e-6


def test_numeric_gradient_is_central_and_restores_parameters():
    params = lesson_params()
    before = flatten(params)
    numeric = numeric_gradient(params, [1.0, 2.0], 1, h=1e-3)
    assert flatten(params) == before, "put every number back after perturbing it"
    exact = flatten(forward_backward(params, [1.0, 2.0], 1)[1])
    assert max(abs(a - b) for a, b in zip(numeric, exact)) < 1e-5, "h = 1e-3 central difference: error is about h squared"


def test_max_relative_error_basic_cases():
    assert max_relative_error([1.0, 2.0], [1.0, 2.0]) == 0.0
    assert math.isclose(max_relative_error([1.0, 0.0], [1.0, 1.0]), 1.0), "analytic 0 against numeric 1 is a 100% error"
    assert max_relative_error([0.0], [1e-12]) < 1e-3, "two tiny numbers are not a big relative error (the floor)"
    assert math.isclose(max_relative_error([1000.0], [1001.0]), 1.0 / 1001.0), "relative, not absolute: 1 out of 1000"


def test_a_wrong_gradient_is_caught():
    params = lesson_params()
    wrong = flatten(forward_backward(params, [1.0, 2.0], 1)[1])
    wrong[8] = -wrong[8]
    assert max_relative_error(wrong, numeric_gradient(params, [1.0, 2.0], 1)) > 0.5


def test_label_zero_gives_the_signs_reversed_error():
    _, (dW1, db1, dW2, db2) = forward_backward(lesson_params(), [1.0, 2.0], 0)
    assert math.isclose(db2[0], -0.1192029220, abs_tol=1e-9) and math.isclose(db2[1], 0.1192029220, abs_tol=1e-9)
    assert math.isclose(db1[0], -0.2384058440, abs_tol=1e-9) and db1[1] == 0.0