tests/test_optim.py49 linesGitHub: tests/test_optim.py1import numpy as np23from optim import Adam, lr_schedule, clip_grad_norm456def test_adam_two_step_hand_trace():7 # theta0 = 1, lr = 0.1, g = 0.5 then 0.258 params = {"w": np.array([1.0])}9 opt = Adam(params)10 opt.step(params, {"w": np.array([0.5])}, lr=0.1)11 assert np.isclose(params["w"][0], 0.9000, atol=1e-4)12 opt.step(params, {"w": np.array([0.25])}, lr=0.1)13 assert np.isclose(params["w"][0], 0.8068, atol=1e-4)141516def test_adam_first_step_is_lr_times_sign_of_gradient():17 # bias correction makes mhat/sqrt(vhat) = g/|g| at t = 1, whatever the size of g18 for g in (1e-4, 3.0, -250.0):19 params = {"w": np.array([0.0])}20 Adam(params).step(params, {"w": np.array([g])}, lr=0.01)21 assert np.isclose(params["w"][0], -0.01 * np.sign(g), atol=1e-6)222324def test_weight_decay_only_touches_matrices():25 params = {"W": np.ones((2, 2)), "b": np.ones(2)}26 zeros = {k: np.zeros_like(v) for k, v in params.items()}27 Adam(params, weight_decay=0.1).step(params, zeros, lr=0.5)28 assert np.allclose(params["W"], 1 - 0.5 * 0.1) # shrunk29 assert np.allclose(params["b"], 1.0) # untouched303132def test_lr_schedule_values():33 # W = 10, Ttot = 100, lr_max = 1e-3, lr_min = 1e-4, step is 1-based34 got = [lr_schedule(t, 10, 100, 1e-3, 1e-4) for t in (1, 5, 10, 55, 100)]35 assert np.allclose(got, [1e-4, 5e-4, 1e-3, 5.5e-4, 1e-4])363738def test_clip_rescales_all_tensors_together():39 grads = {"a": np.array([3.0, 4.0]), "b": np.array([0.0])}40 norm = clip_grad_norm(grads, 1.0)41 assert np.isclose(norm, 5.0) # norm BEFORE clipping42 assert np.allclose(grads["a"], [0.6, 0.8])43 assert np.isclose(np.sqrt(sum((g ** 2).sum() for g in grads.values())), 1.0)444546def test_clip_leaves_small_gradients_alone():47 grads = {"a": np.array([0.3, 0.4])}48 clip_grad_norm(grads, 1.0)49 assert np.allclose(grads["a"], [0.3, 0.4])