()
| 312 | |
| 313 | |
| 314 | def test_multiple_grad(): |
| 315 | data_shape = (9, 2, 6) |
| 316 | av = np.random.random(data_shape).astype(np.float32) |
| 317 | |
| 318 | class MulFunc(Function): |
| 319 | def forward(self, a): |
| 320 | self.a = a |
| 321 | return a * 10 |
| 322 | |
| 323 | def backward(self, grad_o): |
| 324 | return grad_o * 20 |
| 325 | |
| 326 | class Simple(Module): |
| 327 | def __init__(self, a): |
| 328 | super().__init__() |
| 329 | self.a = Parameter(a, dtype=np.float32) |
| 330 | self.layer1 = MulFunc() |
| 331 | |
| 332 | def forward(self): |
| 333 | x = self.layer1(self.a) |
| 334 | return x |
| 335 | |
| 336 | net = Simple(av) |
| 337 | gm = ad.GradManager().attach(net.parameters()) |
| 338 | gm2 = ad.GradManager().attach(net.parameters()) |
| 339 | opt = optimizer.SGD(net.parameters(), lr=1.0) |
| 340 | |
| 341 | opt.clear_grad() |
| 342 | with gm: |
| 343 | with gm2: |
| 344 | loss = net() |
| 345 | gm.backward(loss.sum()) |
| 346 | opt.step() |
| 347 | |
| 348 | np.testing.assert_almost_equal(loss.numpy(), (av * 10)) |
| 349 | np.testing.assert_almost_equal(net.a.numpy(), (av - 20)) |
| 350 | |
| 351 | |
| 352 | def test_inplace_forward(): |
nothing calls this directly
no test coverage detected