Chapter 16 — Lab: Training Deep Networks
Lab Overview¶
You will write, in NumPy, the pieces that make deep networks trainable: the optimisers’ updates, an initialisation, batch normalisation, dropout, gradient clipping, and a monitor that reads a loss curve.
| Exercise | Topic | Points |
|---|---|---|
| 1 | A momentum step | 10 |
| 2 | An Adam step | 20 |
| 3 | He initialisation | 10 |
| 4 | Batch normalisation, training and evaluation | 20 |
| 5 | Inverted dropout | 15 |
| 6 | Clipping by the global norm | 10 |
| 7 | Reading a loss curve | 15 |
| Challenge | Warm-up and cosine decay | +10 |
How it works. Each exercise has a function to complete where you see # TODO. Run the check cell under it: ✅ means your function is right, ❌ tells you what is wrong. Use NumPy only. Do not change the check cells.
import math
import numpy as np
def check(name, test):
"""Run one self-check: test() must return True; any exception or False is reported."""
try:
ok = test()
except NotImplementedError:
print(f'❌ {name}: not implemented yet'); return
except Exception as e:
print(f'❌ {name}: {type(e).__name__}: {e}'); return
print(f'✅ {name}' if ok else f'❌ {name}: wrong result')
rng = np.random.default_rng(0)
print('Setup complete')Exercise 1: A Momentum Step (10 points)¶
momentum_step(w, g, v, lr, mu) updates the velocity, , then the weights, , and returns (w, v). Do not modify the arrays you are given: return new ones.
def momentum_step(w, g, v, lr, mu=0.9):
# TODO
raise NotImplementedErrorw, v = momentum_step(np.array([1.0, 2.0]), np.array([0.5, -1.0]), np.array([1.0, 0.0]), lr=0.1, mu=0.9)
check('one step by hand', lambda: np.allclose(v, [1.4, -1.0]) and np.allclose(w, [0.86, 2.1]))
def steady():
w, v = np.zeros(1), np.zeros(1)
for _ in range(200): w, v = momentum_step(w, np.ones(1), v, lr=1.0, mu=0.9)
return np.isclose(v[0], 10.0)
check('a constant gradient: the velocity tends to 1 / (1 - mu) = 10', steady)
check('the inputs are not modified', lambda: (lambda a: (momentum_step(a, np.ones(2), np.ones(2), 0.1), np.allclose(a, [5, 5]))[1])(np.array([5.0, 5.0])))Exercise 2: An Adam Step (20 points)¶
adam_step(w, g, m, v, t, lr, b1, b2, eps) is step number t (counted from 1) of Adam:
It returns (w, m, v), with the uncorrected m and v (the next step needs them).
def adam_step(w, g, m, v, t, lr=1e-3, b1=0.9, b2=0.999, eps=1e-8):
# TODO
raise NotImplementedErrorw1, m1, v1 = adam_step(np.zeros(3), np.array([0.001, 1.0, 1000.0]), np.zeros(3), np.zeros(3), t=1, lr=0.01)
check('the first step has size lr whatever the gradient (bias correction)', lambda: np.allclose(w1, -0.01, atol=1e-6))
check('the uncorrected moments are returned', lambda: np.allclose(m1, [0.0001, 0.1, 100.0]) and np.allclose(v1, [1e-9, 0.001, 1000.0]))
def converges():
w, m, v = np.array([5.0, -3.0]), np.zeros(2), np.zeros(2)
for t in range(1, 3001):
w, m, v = adam_step(w, 2 * w * np.array([1.0, 100.0]), m, v, t, lr=0.01)
return np.all(np.abs(w) < 0.05)
check('it minimises a badly scaled quadratic', converges)Exercise 3: He Initialisation (10 points)¶
he_init(n_in, n_out, rng) returns an (n_in, n_out) weight matrix drawn from a normal distribution with mean 0 and standard deviation .
def he_init(n_in, n_out, rng):
# TODO
raise NotImplementedErrorW = he_init(512, 300, np.random.default_rng(1))
check('the shape', lambda: W.shape == (512, 300))
check('the standard deviation is sqrt(2 / 512)', lambda: abs(W.std() - np.sqrt(2 / 512)) < 0.002)
def keeps_scale():
r = np.random.default_rng(2); x = r.normal(size=(1000, 256))
for _ in range(20):
x = np.maximum(0, x @ he_init(256, 256, r))
return 0.3 < np.sqrt((x ** 2).mean()) < 3
check('20 ReLU layers keep the activations on the same scale', keeps_scale)Exercise 4: Batch Normalisation (20 points)¶
batchnorm_train(x, gamma, beta, eps) normalises each column of the batch x (shape (n, d)) with that column’s mean and variance over the batch (the variance divides by ), then returns gamma * x_hat + beta together with the batch’s mean and var.
batchnorm_eval(x, gamma, beta, mean, var, eps) does the same with the given (running) mean and var.
def batchnorm_train(x, gamma, beta, eps=1e-5):
# TODO
raise NotImplementedError
def batchnorm_eval(x, gamma, beta, mean, var, eps=1e-5):
# TODO
raise NotImplementedErrorxb = rng.normal(5, 3, size=(64, 4))
out, mu, var = batchnorm_train(xb, np.ones(4), np.zeros(4))
check('each column has mean 0 and variance 1', lambda: np.allclose(out.mean(0), 0, atol=1e-7) and np.allclose(out.var(0), 1, atol=1e-3))
check('the batch statistics are returned', lambda: np.allclose(mu, xb.mean(0)) and np.allclose(var, xb.var(0)))
out2, _, _ = batchnorm_train(xb, np.array([2.0, 1, 1, 1]), np.array([0.0, 0, 0, 7]))
check('gamma scales and beta shifts', lambda: np.isclose(out2[:, 0].std(), 2, atol=1e-3) and np.isclose(out2[:, 3].mean(), 7))
one = xb[:1]
check('evaluation: one example uses the running statistics', lambda: np.allclose(batchnorm_eval(one, np.ones(4), np.zeros(4), mu, var), out[:1]))
check('evaluation does not depend on the batch', lambda: np.allclose(batchnorm_eval(xb[:3], np.ones(4), np.zeros(4), mu, var)[0], batchnorm_eval(one, np.ones(4), np.zeros(4), mu, var)[0]))Exercise 5: Inverted Dropout (15 points)¶
dropout(x, p, rng, train): in training, keep each value with probability (draw rng.random(x.shape) >= p) and divide the kept values by ; return (out, mask) where mask is the 0/1 array of kept values. In evaluation, return (x, None) unchanged.
def dropout(x, p, rng, train=True):
# TODO
raise NotImplementedErrorxd = np.ones((2000, 50))
out, mask = dropout(xd, 0.5, np.random.default_rng(3))
check('about half the values are dropped', lambda: abs(mask.mean() - 0.5) < 0.01)
check('kept values are scaled by 1 / (1 - p)', lambda: set(np.unique(out)) == {0.0, 2.0})
check('the expected value is unchanged', lambda: abs(out.mean() - 1) < 0.02)
check('the same mask as drawing rng.random(x.shape) >= p', lambda: np.array_equal(mask, np.random.default_rng(3).random(xd.shape) >= 0.5))
check('evaluation leaves x unchanged', lambda: dropout(xd, 0.5, rng, train=False)[0] is xd)Exercise 6: Clipping by the Global Norm (10 points)¶
clip_by_norm(grads, c) takes a list of gradient arrays. Their global norm is over all arrays. If it exceeds c, scale every array by c / norm; otherwise return them unchanged. Return (clipped_list, norm).
def clip_by_norm(grads, c):
# TODO
raise NotImplementedErrorgs = [np.array([3.0, 0.0]), np.array([[0.0], [4.0]])]
cl, n = clip_by_norm(gs, 1.0)
check('the global norm is 5', lambda: np.isclose(n, 5.0))
check('clipped to norm 1, direction kept', lambda: np.allclose(cl[0], [0.6, 0]) and np.allclose(cl[1], [[0], [0.8]]))
check('a small gradient is unchanged', lambda: np.allclose(clip_by_norm(gs, 10.0)[0][1], gs[1]))
check('scaled together, not array by array', lambda: np.isclose(np.sqrt(sum((g ** 2).sum() for g in clip_by_norm([np.ones(4), 10 * np.ones(1)], 2.0)[0])), 2.0))Exercise 7: Reading a Loss Curve (15 points)¶
diagnose(losses, n_classes) takes the training loss after each epoch and returns one word, checking in this order:
'diverged'if any value is not finite, or the last value is more than twice the first;'stuck'if every value is within 0.02 of ;'unstable'if the loss went up from one epoch to the next more than a third of the time;'converging'otherwise.
def diagnose(losses, n_classes):
# TODO
raise NotImplementedErrorcheck('a run that becomes NaN', lambda: diagnose([2.3, 1.5, float('nan')], 10) == 'diverged')
check('a run that blows up', lambda: diagnose([2.3, 3.0, 9.0], 10) == 'diverged')
check('a dead network at ln 10', lambda: diagnose([2.305, 2.303, 2.302, 2.302], 10) == 'stuck')
check('a dead network at ln 2, for 2 classes', lambda: diagnose([0.70, 0.69, 0.693], 2) == 'stuck')
check('a bouncing run (the lr 1.0 run of the chapter)', lambda: diagnose([2.77, 1.87, 2.0, 2.3, 1.92, 2.2, 2.1, 2.05, 1.65, 1.95], 10) == 'unstable')
check('a healthy run with one small bump', lambda: diagnose([1.62, 0.97, 0.62, 0.45, 0.36, 0.30, 0.27, 0.28, 0.22, 0.19], 10) == 'converging')Challenge: Warm-Up and Cosine Decay (+10 points)¶
lr_at(t, base, warm, total) gives the learning rate at step t (from 0): linear warm-up for , then cosine decay .
def lr_at(t, base, warm, total):
# TODO
raise NotImplementedErrorcheck('starts at 0', lambda: lr_at(0, 0.1, 10, 100) == 0)
check('halfway through the warm-up: half the rate', lambda: math.isclose(lr_at(5, 0.1, 10, 100), 0.05))
check('the peak at the end of the warm-up', lambda: math.isclose(lr_at(10, 0.1, 10, 100), 0.1))
check('half the rate halfway through the decay', lambda: math.isclose(lr_at(55, 0.1, 10, 100), 0.05))
check('ends at 0', lambda: abs(lr_at(100, 0.1, 10, 100)) < 1e-12)Lab Report¶
Submit this notebook with:
every check cell showing ✅,
one paragraph: in Exercise 2, why does the first Adam step have size
lrwhatever the gradient? What would happen to the first steps without the bias correction?