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.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  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 weakref
  10. import numpy as np
  11. import pytest
  12. import megengine as mge
  13. import megengine.distributed as dist
  14. import megengine.functional as F
  15. import megengine.module as M
  16. import megengine.optimizer as optim
  17. from megengine.autodiff import GradManager
  18. from megengine.core._imperative_rt.imperative import sync
  19. from megengine.distributed.helper import get_device_count_by_fork
  20. from megengine.jit import trace
  21. def test_basic():
  22. x = mge.tensor([1.0, 3.0, 5.0]).reshape(1, 3)
  23. w = mge.tensor([2.0, 4.0, 6.0]).reshape(3, 1)
  24. b = mge.tensor(-1.0)
  25. gm = GradManager().attach([w, b])
  26. gm.record()
  27. p = F.matmul(x, w)
  28. y = p + b
  29. gm.backward(y)
  30. gm.release() # is not necessary
  31. np.testing.assert_equal(w.grad.numpy(), [[1], [3], [5]])
  32. np.testing.assert_equal(b.grad.numpy(), [1])
  33. w.grad = None
  34. b.grad = None
  35. with gm:
  36. p = F.matmul(x, w)
  37. y = p + b
  38. gm.backward(y)
  39. np.testing.assert_equal(w.grad.numpy(), [[1], [3], [5]])
  40. np.testing.assert_equal(b.grad.numpy(), [1])
  41. def test_attach_in_with_block():
  42. a = mge.Parameter([1.0])
  43. gm = GradManager()
  44. with gm:
  45. b = a * 3
  46. gm.attach(b)
  47. c = b + 1
  48. gm.backward(c)
  49. assert int(b.grad.numpy()) == 1
  50. def test_attach_temporary():
  51. w = mge.Parameter(2.0)
  52. gm = GradManager()
  53. gm.attach(w)
  54. def cb(x, g):
  55. assert x is ref()
  56. cb.called = True
  57. for i in range(3):
  58. with gm:
  59. cb.called = False
  60. x = mge.Tensor(i, dtype="float32")
  61. gm.attach(x, callbacks=cb)
  62. ref = weakref.ref(x)
  63. y = x * w
  64. gm.backward(y)
  65. assert cb.called
  66. del x
  67. assert ref() is None
  68. # NOTE: does not guarantee timely release when recording
  69. # for i in range(3):
  70. # with gm:
  71. # x = mge.Tensor(i, dtype='float32')
  72. # gm.attach(x)
  73. # ref = weakref.ref(x)
  74. # y = x * w
  75. # del x
  76. # assert ref() is None
  77. # gm.backward(y)
  78. @pytest.mark.skipif(
  79. platform.system() == "Darwin", reason="do not imp GPU mode at macos now"
  80. )
  81. @pytest.mark.skipif(
  82. platform.system() == "Windows", reason="windows disable MGB_ENABLE_OPR_MM"
  83. )
  84. @pytest.mark.skipif(get_device_count_by_fork("gpu") < 2, reason="need more gpu device")
  85. @pytest.mark.isolated_distributed
  86. def test_remote_grad():
  87. @dist.launcher
  88. def worker():
  89. rank = dist.get_rank()
  90. size = dist.get_world_size()
  91. x = mge.tensor(np.random.randn(1, rank * 2 + 2), dtype=np.float32)
  92. m = M.Linear(rank * 2 + 2, rank * 2 + 4)
  93. gm = GradManager().attach(m.parameters())
  94. opt = optim.SGD(m.parameters(), 1e-3, momentum=0.9)
  95. def train_func(x):
  96. with gm:
  97. if rank != 0:
  98. x = dist.functional.remote_recv(
  99. rank - 1, shape=(1, rank * 2 + 2), dtype=np.float32
  100. )
  101. y = m(x)
  102. if rank != size - 1:
  103. dist.functional.remote_send(y, dest_rank=rank + 1)
  104. gm.backward()
  105. else:
  106. y = y.mean()
  107. gm.backward(y)
  108. opt.step().clear_grad()
  109. train_funcs = [
  110. train_func,
  111. trace(symbolic=False)(train_func),
  112. trace(symbolic=True)(train_func),
  113. ]
  114. for func in train_funcs:
  115. for i in range(3):
  116. func(x)
  117. sync()
  118. worker()

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