Minimise a quadratic with AdamW, bias correction and a no-decay mask

HardOptimizersPro

Real training configs do not decay every parameter: biases and norm gains are usually excluded. This problem runs AdamW on a known quadratic so every number can be checked, with a mask that marks which parameters get weight decay.

Write adamw_quadratic(A, b, x0, lr, steps, wd, decay_mask, b1=0.9, b2=0.999, eps=1e-8).
- f(x) = 0.5 * x @ A @ x - b @ x with A symmetric (d, d), b and x0 of length d, decay_mask a length-d list of 0/1.
- m and v start at zero. For step t = 1..steps:
g = A @ x - b
m = b1 * m + (1 - b1) * g; v = b2 * v + (1 - b2) * g ** 2
m_hat = m / (1 - b1 ** t); v_hat = v / (1 - b2 ** t)
x = x - lr * m_hat / (sqrt(v_hat) + eps) - lr * wd * decay_mask * x_old, where x_old is x before this step.
- Weight decay must NOT be added to g (that would be L2 regularisation, not AdamW).
Return (x_final as an array, losses) where losses is the list of f(x) after each step (length steps). steps = 0 returns (x0, []).

Signaturedef adamw_quadratic(A, b, x0, lr, steps, wd, decay_mask, b1=0.9, b2=0.999, eps=1e-8)

Example

on the first step m_hat = g and v_hat = g ** 2, so each coordinate with nonzero gradient moves by almost exactly lr against the sign of its gradient.

Understand the idea

Adam scales each step by running averages of the gradient (m) and squared gradient (v). Both start at zero, so early averages are too small; bias correction divides by 1 - beta^t to fix that. AdamW then shrinks weights directly by lr * wd * x, outside the adaptive scaling, and a mask lets biases and norm gains skip decay. Worked example in 1-D: f(x) = 0.5 * x^2, so g = x. x0 = 2, lr = 0.1, wd = 0.1, mask 1. Step 1: g = 2, m = 0.2, v = 0.004, m_hat = 0.2 / 0.1 = 2, v_hat = 0.004 / 0.001 = 4, so the Adam step is 0.1 * 2 / 2 = 0.1. Decay is 0.1 * 0.1 * 2 = 0.02. x = 2 - 0.1 - 0.02 = 1.88, loss = 0.5 * 1.88^2 = 1.7672. With mask 0, x = 1.9. Rule: g = A x - b, update m and v, correct both, x = x - lr * m_hat / (sqrt(v_hat) + eps) - lr * wd * mask * x_old. Adding wd * x into g is L2, not AdamW. It is the default for transformers.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: zero stepsadamw_quadratic(_A, _b, _x0, 0.1, 0, 0.1, [1, 1, 0])
  • Sample 2: one step no decayadamw_quadratic(_A, _b, _x0, 0.1, 1, 0.0, [1, 1, 1])