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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. w.grad = None
  26. b.grad = None
  27. with gm:
  28. p = F.matmul(x, w)
  29. y = p + b
  30. gm.backward(y)
  31. np.testing.assert_equal(w.grad.numpy(), [[1], [3], [5]])
  32. np.testing.assert_equal(b.grad.numpy(), [1])
  33. def test_attach_in_with_block():
  34. a = mge.Parameter([1.0])
  35. gm = GradManager()
  36. with gm:
  37. b = a * 3
  38. gm.attach(b)
  39. c = b + 1
  40. gm.backward(c)
  41. assert int(b.grad.numpy()) == 1

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