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 3.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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 platform
  9. import numpy as np
  10. import pytest
  11. import megengine as mge
  12. import megengine.distributed as dist
  13. import megengine.functional as F
  14. import megengine.module as M
  15. import megengine.optimizer as optim
  16. from megengine.autodiff import GradManager
  17. from megengine.core._imperative_rt.imperative import sync
  18. from megengine.distributed.helper import get_device_count_by_fork
  19. def test_basic():
  20. x = mge.tensor([1.0, 3.0, 5.0]).reshape(1, 3)
  21. w = mge.tensor([2.0, 4.0, 6.0]).reshape(3, 1)
  22. b = mge.tensor(-1.0)
  23. gm = GradManager().attach([w, b])
  24. gm.record()
  25. p = F.matmul(x, w)
  26. y = p + b
  27. gm.backward(y)
  28. gm.release() # is not necessary
  29. np.testing.assert_equal(w.grad.numpy(), [[1], [3], [5]])
  30. np.testing.assert_equal(b.grad.numpy(), [1])
  31. gm.clear_grad()
  32. with gm:
  33. p = F.matmul(x, w)
  34. y = p + b
  35. gm.backward(y)
  36. np.testing.assert_equal(w.grad.numpy(), [[1], [3], [5]])
  37. np.testing.assert_equal(b.grad.numpy(), [1])
  38. def test_attach_in_with_block():
  39. a = mge.Parameter([1.0])
  40. gm = GradManager()
  41. with gm:
  42. b = a * 3
  43. gm.attach(b)
  44. c = b + 1
  45. gm.backward(c)
  46. assert int(b.grad.numpy()) == 1
  47. @pytest.mark.skipif(
  48. platform.system() == "Darwin", reason="do not imp GPU mode at macos now"
  49. )
  50. @pytest.mark.skipif(
  51. platform.system() == "Windows", reason="windows disable MGB_ENABLE_OPR_MM"
  52. )
  53. @pytest.mark.skipif(get_device_count_by_fork("gpu") < 2, reason="need more gpu device")
  54. @pytest.mark.isolated_distributed
  55. def test_remote_grad():
  56. @dist.launcher
  57. def worker():
  58. rank = dist.get_rank()
  59. size = dist.get_world_size()
  60. x = mge.tensor(np.random.randn(1, rank * 2 + 2), dtype=np.float32)
  61. m = M.Linear(rank * 2 + 2, rank * 2 + 4)
  62. gm = GradManager().attach(m.parameters())
  63. opt = optim.SGD(m.parameters(), 1e-3, momentum=0.9)
  64. def train_func(x):
  65. if rank != 0:
  66. x = dist.functional.remote_recv(
  67. rank - 1, shape=(1, rank * 2 + 2), dtype=np.float32
  68. )
  69. print(rank, "x", x)
  70. y = m(x)
  71. print(rank, "y", y)
  72. if rank != size - 1:
  73. y = dist.functional.remote_send(y, dest_rank=rank + 1)
  74. return y
  75. with gm:
  76. y = train_func(x)
  77. if rank == size - 1:
  78. y = y.mean()
  79. gm.backward(y)
  80. else:
  81. gm.backward()
  82. opt.step().clear_grad()
  83. # sync because send is the last job
  84. sync()
  85. worker()

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