MCPcopy Create free account
hub / github.com/MegEngine/MegEngine / test_multiple_grad

Function test_multiple_grad

imperative/python/test/unit/core/test_function.py:314–349  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

312
313
314def 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
352def test_inplace_forward():

Callers

nothing calls this directly

Calls 11

parametersMethod · 0.80
SimpleClass · 0.70
astypeMethod · 0.45
attachMethod · 0.45
GradManagerMethod · 0.45
SGDMethod · 0.45
clear_gradMethod · 0.45
backwardMethod · 0.45
sumMethod · 0.45
stepMethod · 0.45
numpyMethod · 0.45

Tested by

no test coverage detected