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

Function test_clear_grad

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

Source from the content-addressed store, hash-verified

264
265
266def test_clear_grad():
267 class StopGradient(Function):
268 def forward(self, a):
269 return a
270
271 def backward(self, *_):
272 return None
273
274 class Simple(Module):
275 def __init__(self, a):
276 super().__init__()
277 self.a = Parameter(a, dtype=np.float32)
278 self.layer = StopGradient()
279
280 def forward(self):
281 b = self.a * 3.0
282 c = self.a * 4.0
283 return self.layer(b) + c
284
285 a = tensor(np.array([1.0], dtype=np.float32))
286 net = Simple(a)
287 optim = optimizer.SGD(net.parameters(), lr=1.0)
288 gm = ad.GradManager().attach(net.parameters())
289 optim.clear_grad()
290
291 with gm:
292 loss = net()
293 gm.backward(loss.sum())
294 optim.step()
295 np.testing.assert_almost_equal(
296 net.a.numpy(), np.array([1.0 - 4.0], dtype=np.float32),
297 )
298
299
300def test_throw_on_non_tensor_argument():

Callers

nothing calls this directly

Calls 11

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

Tested by

no test coverage detected