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_grad_manger.py 1.3 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  2. #
  3. # Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
  4. #
  5. # Unless required by applicable law or agreed to in writing,
  6. # software distributed under the License is distributed on an
  7. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8. import numpy as np
  9. import pytest
  10. import megengine as mge
  11. import megengine.functional as F
  12. from megengine.autodiff import GradManager
  13. def test_basic():
  14. x = mge.tensor([1.0, 3.0, 5.0]).reshape(1, 3)
  15. w = mge.tensor([2.0, 4.0, 6.0]).reshape(3, 1)
  16. b = mge.tensor(-1.0)
  17. gm = GradManager().attach([w, b])
  18. gm.record()
  19. p = F.matmul(x, w)
  20. y = p + b
  21. gm.backward(y)
  22. gm.release() # is not necessary
  23. np.testing.assert_equal(w.grad.numpy(), [[1], [3], [5]])
  24. np.testing.assert_equal(b.grad.numpy(), [1])
  25. gm.clear_grad()
  26. with gm:
  27. p = F.matmul(x, w)
  28. y = p + b
  29. gm.backward(y)
  30. np.testing.assert_equal(w.grad.numpy(), [[1], [3], [5]])
  31. np.testing.assert_equal(b.grad.numpy(), [1])
  32. def test_attach_in_with_block():
  33. a = mge.Parameter([1.0])
  34. gm = GradManager()
  35. with gm:
  36. b = a * 3
  37. gm.attach(b)
  38. c = b + 1
  39. gm.backward(c)
  40. assert int(b.grad.numpy()) == 1

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台