| 101 | |
| 102 | @pytest.mark.require_higher_order_directive() |
| 103 | def test_2nd_grad(): |
| 104 | x_np = np.random.rand(10).astype("float32") |
| 105 | x = as_tensor(x_np) |
| 106 | ones = as_tensor(np.ones_like(x_np)) |
| 107 | |
| 108 | with Grad("grad2") as grad2: |
| 109 | with Grad("grad") as grad: |
| 110 | grad2.wrt(x, callback=save_to(x)) |
| 111 | grad.wrt(x, callback=save_to(x)) |
| 112 | y = cos(x) |
| 113 | grad(y, ones) |
| 114 | z = x.grad |
| 115 | np.testing.assert_almost_equal(x.grad.numpy(), -np.sin(x_np), decimal=5) |
| 116 | |
| 117 | x.grad = None |
| 118 | grad2(z, ones) |
| 119 | |
| 120 | np.testing.assert_almost_equal(x.grad.numpy(), -np.cos(x_np), decimal=5) |
| 121 | |
| 122 | |
| 123 | def test_grad_with_tensor_wrapper(): |