|
| 1 | +import pytest |
| 2 | + |
| 3 | +import micrograd_pp as mpp |
| 4 | + |
| 5 | +np = mpp.numpy |
| 6 | + |
| 7 | + |
| 8 | +@pytest.fixture(autouse=True) |
| 9 | +def run_before_and_after_tests(): |
| 10 | + np.random.seed(0) |
| 11 | + yield |
| 12 | + |
| 13 | + |
| 14 | +def _set_grad(param: mpp.Expr, grad: np.ndarray) -> None: |
| 15 | + param.zero_grad() |
| 16 | + param.update_grad(lambda: grad) |
| 17 | + |
| 18 | + |
| 19 | +def test_clip_grad_value_clamps_each_element() -> None: |
| 20 | + param = mpp.Parameter(np.array([0.0, 0.0, 0.0])) |
| 21 | + _set_grad(param, np.array([-2.0, 0.25, 3.0])) |
| 22 | + |
| 23 | + mpp.clip_grad_value_([param], clip_value=0.5) |
| 24 | + |
| 25 | + np.testing.assert_allclose(param.grad, np.array([-0.5, 0.25, 0.5])) |
| 26 | + |
| 27 | + |
| 28 | +def test_clip_grad_norm_scales_all_grads_by_common_factor() -> None: |
| 29 | + p1 = mpp.Parameter(np.zeros((2,))) |
| 30 | + p2 = mpp.Parameter(np.zeros((1,))) |
| 31 | + _set_grad(p1, np.array([3.0, 4.0])) |
| 32 | + _set_grad(p2, np.array([12.0])) |
| 33 | + |
| 34 | + total_norm = mpp.clip_grad_norm_([p1, p2], max_norm=6.5, norm_type=2.0) |
| 35 | + scale = 6.5 / (13.0 + 1e-6) |
| 36 | + |
| 37 | + np.testing.assert_allclose(total_norm, 13.0) |
| 38 | + np.testing.assert_allclose(p1.grad, np.array([3.0, 4.0]) * scale, atol=1e-12, rtol=0.0) |
| 39 | + np.testing.assert_allclose(p2.grad, np.array([12.0]) * scale, atol=1e-12, rtol=0.0) |
| 40 | + |
| 41 | + |
| 42 | +def test_clip_grad_norm_noop_when_within_threshold() -> None: |
| 43 | + p1 = mpp.Parameter(np.zeros((2,))) |
| 44 | + p2 = mpp.Parameter(np.zeros((1,))) |
| 45 | + _set_grad(p1, np.array([3.0, 4.0])) |
| 46 | + _set_grad(p2, np.array([12.0])) |
| 47 | + |
| 48 | + total_norm = mpp.clip_grad_norm_([p1, p2], max_norm=13.1, norm_type=2.0) |
| 49 | + |
| 50 | + np.testing.assert_allclose(total_norm, 13.0) |
| 51 | + np.testing.assert_allclose(p1.grad, np.array([3.0, 4.0]), atol=1e-12, rtol=0.0) |
| 52 | + np.testing.assert_allclose(p2.grad, np.array([12.0]), atol=1e-12, rtol=0.0) |
| 53 | + |
| 54 | + |
| 55 | +def test_clip_grad_norm_errors_on_nonfinite_if_requested() -> None: |
| 56 | + p = mpp.Parameter(np.zeros((1,))) |
| 57 | + _set_grad(p, np.array([np.inf])) |
| 58 | + |
| 59 | + with pytest.raises(RuntimeError): |
| 60 | + mpp.clip_grad_norm_([p], max_norm=1.0, error_if_nonfinite=True) |
0 commit comments