Homework · Runs in your browser
Training stability from scratch: L2, clipping, a schedule and AdamW
Build four training-stability pieces with nothing but the standard library: an L2 penalty with its gradient, gradient clipping by global norm, a warmup-plus-cosine learning-rate schedule, and a single Adam step that can use either an L2 penalty or AdamW’s decoupled decay. 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:
- L2: penalty = 0.5 * l2 * (sum of squares of every weight); the gradient is l2 * w for each weight.
- Clipping: compute one norm over all gradient numbers together; scale every entry by max_norm / norm only when the norm exceeds max_norm. (3, 4) with limit 1 gives (0.6, 0.8).
- Schedule: warmup rate is peak * (step + 1) / warmup; afterwards 0.5 * peak * (1 + cos(pi * c)) with c the fraction of the decay done. A quarter of the way down you should be at about 85% of the peak.
- Adam step: update m and v, divide by (1 - beta^t) to correct the bias, then w - lr * m_hat / (sqrt(v_hat) + eps). With an L2 penalty add wd * w to the gradient first. With decoupled=True shrink w by lr * wd * w first and leave the gradient alone.
- Try it: with a loss gradient of exactly 0 and weight 1, compare the two modes for wd = 0.01. The L2 mode moves the weight by about the learning rate; the decoupled mode by lr * wd = 1e-5.
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 l2_penalty_and_grads(matrices, l2):
"""L2 penalty 0.5 * l2 * (sum of squares of every weight) and its gradient.
matrices is a list of weight matrices (lists of rows). Returns (penalty, grads)
where grads has the same shapes and each entry is l2 * w.
"""
penalty = 0.5 * l2 * sum(w * w for m in matrices for row in m for w in row)
grads = [[[l2 * w for w in row] for row in m] for m in matrices]
return penalty, grads
def clip_global_norm(grads, max_norm):
"""Scale a flat list of gradients so its L2 norm is at most max_norm.
Gradients whose norm is already at most max_norm come back unchanged.
Returns (clipped_list, original_norm).
"""
norm = math.sqrt(sum(g * g for g in grads))
scale = max_norm / norm if norm > max_norm else 1.0
return [g * scale for g in grads], norm
def lr_at(step, total_steps, warmup_steps, peak_lr, floor_lr=0.0):
"""Linear warmup to peak_lr, then cosine decay to floor_lr.
Steps count from 0. During warmup the rate at `step` is peak_lr * (step + 1) / warmup_steps.
After warmup, with c = (step - warmup_steps) / (total_steps - warmup_steps), it is
floor_lr + 0.5 * (peak_lr - floor_lr) * (1 + cos(pi * c)).
"""
if step < warmup_steps:
return peak_lr * (step + 1) / warmup_steps
c = (step - warmup_steps) / (total_steps - warmup_steps)
return floor_lr + 0.5 * (peak_lr - floor_lr) * (1 + math.cos(math.pi * c))
def adam_step(w, g, m, v, t, lr=0.001, beta1=0.9, beta2=0.999, eps=1e-8, wd=0.0, decoupled=False):
"""One Adam step on flat lists w, g, m, v at step number t (counting from 1).
decoupled=False: wd is an L2 penalty, so wd * w is added to the gradient.
decoupled=True (AdamW): w is first shrunk to w - lr * wd * w, and the gradient is left alone.
Update: m = beta1 m + (1 - beta1) g; v = beta2 v + (1 - beta2) g^2;
m_hat = m / (1 - beta1^t); v_hat = v / (1 - beta2^t); w = w - lr * m_hat / (sqrt(v_hat) + eps).
Returns (new_w, new_m, new_v).
"""
new_w, new_m, new_v = [], [], []
for wi, gi, mi, vi in zip(w, g, m, v):
if decoupled:
wi = wi - lr * wd * wi
else:
gi = gi + wd * wi
mi = beta1 * mi + (1 - beta1) * gi
vi = beta2 * vi + (1 - beta2) * gi * gi
m_hat = mi / (1 - beta1 ** t)
v_hat = vi / (1 - beta2 ** t)
new_w.append(wi - lr * m_hat / (math.sqrt(v_hat) + eps))
new_m.append(mi)
new_v.append(vi)
return new_w, new_m, new_v
Show the tests (test_starter.py)
import math
from starter import adam_step, clip_global_norm, l2_penalty_and_grads, lr_at
W = [[[0.5, 0.25], [-1.0, 0.5]], [[1.0, 0.5], [-1.0, -0.25]]]
def test_l2_penalty_value_and_gradient():
penalty, grads = l2_penalty_and_grads(W, 0.1)
assert math.isclose(penalty, 0.19375, abs_tol=1e-12), "0.5 * 0.1 * (1.5625 + 2.3125)"
assert math.isclose(grads[1][1][0], -0.1) and math.isclose(grads[0][0][1], 0.025), "gradient is l2 * w, not 2 * l2 * w"
assert len(grads) == 2 and len(grads[0]) == 2 and len(grads[0][0]) == 2
def test_l2_penalty_is_zero_for_zero_strength():
penalty, grads = l2_penalty_and_grads(W, 0.0)
assert penalty == 0.0 and grads[0][0] == [0.0, 0.0]
def test_clip_scales_down_but_keeps_direction():
out, norm = clip_global_norm([3.0, 4.0], 1.0)
assert math.isclose(norm, 5.0)
assert math.isclose(out[0], 0.6) and math.isclose(out[1], 0.8)
def test_clip_uses_the_norm_of_all_numbers_together():
out, norm = clip_global_norm([2.0, 3.0, 6.0], 3.5)
assert math.isclose(norm, 7.0), "sqrt(4 + 9 + 36) = 7"
assert math.isclose(out[0], 1.0) and math.isclose(out[1], 1.5) and math.isclose(out[2], 3.0), "all scaled by 3.5 / 7"
def test_clip_leaves_small_gradients_alone():
out, norm = clip_global_norm([0.3, 0.4], 1.0)
assert out == [0.3, 0.4] and math.isclose(norm, 0.5)
out, _ = clip_global_norm([0.6, 0.8], 1.0)
assert math.isclose(out[0], 0.6) and math.isclose(out[1], 0.8), "a gradient already at the limit keeps its length"
def test_lr_warmup_is_linear_and_reaches_peak():
assert math.isclose(lr_at(0, 1000, 100, 1e-3), 1e-5)
assert math.isclose(lr_at(49, 1000, 100, 1e-3), 5e-4)
assert math.isclose(lr_at(99, 1000, 100, 1e-3), 1e-3)
def test_lr_cosine_decay_shape_not_linear():
assert math.isclose(lr_at(100, 1000, 100, 1e-3), 1e-3), "decay starts at the peak"
assert math.isclose(lr_at(325, 1000, 100, 1e-3), 0.5 * 1e-3 * (1 + math.cos(math.pi * 0.25)), rel_tol=1e-9)
assert lr_at(325, 1000, 100, 1e-3) > 0.85e-3, "a quarter of the way down, cosine is still at 85%, linear would be at 75%"
assert math.isclose(lr_at(550, 1000, 100, 1e-3), 5e-4)
assert lr_at(775, 1000, 100, 1e-3) < 0.15e-3, "three quarters of the way down, cosine is at 15%, linear would be at 25%"
def test_lr_floor_is_the_end_value():
assert math.isclose(lr_at(999, 1000, 100, 1e-3, floor_lr=1e-4), 1e-4 + 0.5 * 9e-4 * (1 + math.cos(math.pi * 899 / 900)))
assert math.isclose(lr_at(550, 1000, 100, 1e-3, floor_lr=1e-4), 5.5e-4)
def reference_adam(w, grads, lr=0.001, b1=0.9, b2=0.999, eps=1e-8):
"""Independent scalar Adam over a list of gradients, for the tests."""
m = v = 0.0
for t, g in enumerate(grads, start=1):
m = b1 * m + (1 - b1) * g
v = b2 * v + (1 - b2) * g * g
w = w - lr * (m / (1 - b1 ** t)) / (math.sqrt(v / (1 - b2 ** t)) + eps)
return w
def test_adam_two_steps_with_uneven_gradients():
w, m, v = [2.0], [0.0], [0.0]
for t, g in enumerate([0.3, 0.7], start=1):
w, m, v = adam_step(w, [g], m, v, t)
assert math.isclose(w[0], reference_adam(2.0, [0.3, 0.7]), abs_tol=1e-12)
assert math.isclose(m[0], 0.9 * 0.03 + 0.1 * 0.7, abs_tol=1e-12) and math.isclose(v[0], 0.999 * 0.00009 + 0.001 * 0.49, abs_tol=1e-12)
def test_adam_first_step_is_about_the_learning_rate_whatever_the_gradient():
for g in (0.001, 1.0, 100.0):
w, _, _ = adam_step([1.0], [g], [0.0], [0.0], 1)
assert math.isclose(1.0 - w[0], 0.001, rel_tol=1e-4), "bias-corrected first step is lr * sign(g)"
def test_l2_penalty_in_adam_is_normalised_with_the_gradient():
w, _, _ = adam_step([1.0], [0.0], [0.0], [0.0], 1, wd=0.01, decoupled=False)
assert math.isclose(1.0 - w[0], 0.001, rel_tol=1e-6), "zero loss gradient: the penalty alone becomes a full lr step"
w, _, _ = adam_step([1.0], [100.0], [0.0], [0.0], 1, wd=0.01, decoupled=False)
assert math.isclose(1.0 - w[0], 0.001, rel_tol=1e-6)
def test_adamw_decay_is_lr_times_wd_times_w_and_does_not_enter_the_moments():
w, m, v = adam_step([2.0], [0.0], [0.0], [0.0], 1, wd=0.01, decoupled=True)
assert math.isclose(2.0 - w[0], 0.001 * 0.01 * 2.0, abs_tol=1e-15), "zero loss gradient: only the decay moves w"
assert m == [0.0] and v == [0.0], "decoupled decay never touches the moment estimates"
w, m, v = adam_step([2.0], [0.5], [0.0], [0.0], 1, wd=0.01, decoupled=True)
shrunk = 2.0 - 0.001 * 0.01 * 2.0
assert math.isclose(w[0], shrunk - 0.001 * 0.5 / (0.5 + 1e-8), abs_tol=1e-13), "decay first, then the Adam step"
assert math.isclose(m[0], 0.05)
def test_adam_l2_two_steps_matches_adam_fed_the_penalised_gradient():
wd, grads = 0.1, [0.01, -0.03]
w, m, v = [1.0], [0.0], [0.0]
ref = 1.0
for t, g in enumerate(grads, start=1):
w, m, v = adam_step(w, [g], m, v, t, wd=wd, decoupled=False)
ref = reference_adam_step(ref, g + wd * ref, t)
assert math.isclose(w[0], ref, abs_tol=1e-12), "L2 mode must feed g + wd * w to Adam at every step"
def reference_adam_step(w, g, t, state={}):
"""Stateful single-parameter Adam, reset when t == 1; used only by the test above."""
if t == 1:
state.update(m=0.0, v=0.0)
state["m"] = 0.9 * state["m"] + 0.1 * g
state["v"] = 0.999 * state["v"] + 0.001 * g * g
return w - 0.001 * (state["m"] / (1 - 0.9 ** t)) / (math.sqrt(state["v"] / (1 - 0.999 ** t)) + 1e-8)