You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_ai.py 1.2 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. import numpy as np
  10. import megengine
  11. import megengine.autodiff as ad
  12. import megengine.optimizer as optimizer
  13. from megengine import Parameter, tensor
  14. from megengine.module import Module
  15. class Simple(Module):
  16. def __init__(self):
  17. super().__init__()
  18. self.a = Parameter([1.0], dtype=np.float32)
  19. def forward(self, x):
  20. x = x[:, 0] * self.a
  21. return x
  22. def test_ai():
  23. net = Simple()
  24. gm = ad.GradManager().attach(net.parameters())
  25. optim = optimizer.SGD(net.parameters(), lr=1.0)
  26. optim.clear_grad()
  27. dshape = (10, 10)
  28. data = tensor(np.ones(dshape).astype(np.float32))
  29. with gm:
  30. loss = net(data).sum()
  31. gm.backward(loss)
  32. optim.step()
  33. np.testing.assert_almost_equal(
  34. net.a.numpy(), np.array([1.0 - dshape[0]]).astype(np.float32)
  35. )