Adam Optimizer
Key idea: first moment (momentum) + second moment (per-parameter scale) with bias correction for the zero initialization. Test it on an ill-conditioned quadratic where plain SGD with the same step is slow.
import numpy as np
class Adam:
def __init__(self, lr=0.1, b1=0.9, b2=0.999, eps=1e-8):
self.lr, self.b1, self.b2, self.eps, self.t, self.m, self.v = lr, b1, b2, eps, 0, 0, 0
def step(self, w, g):
self.t += 1
self.m = self.b1 * self.m + (1 - self.b1) * g
self.v = self.b2 * self.v + (1 - self.b2) * g * g
mhat = self.m / (1 - self.b1 ** self.t)
vhat = self.v / (1 - self.b2 ** self.t)
return w - self.lr * mhat / (np.sqrt(vhat) + self.eps)
A = np.diag([100.0, 1.0]) # f(w) = 0.5 wᵀAw, minimum at 0
grad = lambda w: A @ w
w, opt = np.array([1.0, 1.0]), Adam(lr=0.05)
for _ in range(500):
w = opt.step(w, grad(w))
assert np.linalg.norm(w) < 1e-2
print("ok", w.round(5))