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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  2. #
  3. # Copyright (c) 2014-2021 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.distributed.helper import get_device_count_by_fork
  19. from megengine.jit import trace
  20. def test_basic():
  21. x = mge.tensor([1.0, 3.0, 5.0]).reshape(1, 3)
  22. w = mge.tensor([2.0, 4.0, 6.0]).reshape(3, 1)
  23. b = mge.tensor(-1.0)
  24. gm = GradManager().attach([w, b])
  25. gm.record()
  26. p = F.matmul(x, w)
  27. y = p + b
  28. gm.backward(y)
  29. gm.release() # is not necessary
  30. np.testing.assert_equal(w.grad.numpy(), [[1], [3], [5]])
  31. np.testing.assert_equal(b.grad.numpy(), [1])
  32. w.grad = None
  33. b.grad = None
  34. with gm:
  35. p = F.matmul(x, w)
  36. y = p + b
  37. gm.backward(y)
  38. np.testing.assert_equal(w.grad.numpy(), [[1], [3], [5]])
  39. np.testing.assert_equal(b.grad.numpy(), [1])
  40. def test_attach_in_with_block():
  41. a = mge.Parameter([1.0])
  42. gm = GradManager()
  43. with gm:
  44. b = a * 3
  45. gm.attach(b)
  46. c = b + 1
  47. gm.backward(c)
  48. assert int(b.grad.numpy()) == 1
  49. def test_attach_temporary():
  50. w = mge.Parameter(2.0)
  51. gm = GradManager()
  52. gm.attach(w)
  53. def cb(x, g):
  54. assert x is ref()
  55. cb.called = True
  56. for i in range(3):
  57. with gm:
  58. cb.called = False
  59. x = mge.Tensor(i, dtype="float32")
  60. gm.attach(x, callbacks=cb)
  61. ref = weakref.ref(x)
  62. y = x * w
  63. gm.backward(y)
  64. assert cb.called
  65. del x
  66. assert ref() is None
  67. # NOTE: does not guarantee timely release when recording
  68. # for i in range(3):
  69. # with gm:
  70. # x = mge.Tensor(i, dtype='float32')
  71. # gm.attach(x)
  72. # ref = weakref.ref(x)
  73. # y = x * w
  74. # del x
  75. # assert ref() is None
  76. # gm.backward(y)
  77. def test_no_dependency():
  78. x = mge.tensor(3)
  79. w = mge.Parameter(1.0)
  80. w_no_dep = mge.Parameter(1.0)
  81. gm = GradManager()
  82. gm.attach(w)
  83. gm.attach(w_no_dep)
  84. with gm:
  85. out1 = x * w
  86. out2 = w_no_dep * out1
  87. gm.backward(out1.sum())
  88. assert w.grad is not None
  89. assert w_no_dep.grad is None
  90. def test_regression_1762():
  91. x = F.ones((10, 10, 3, 3))
  92. conv = M.Conv2d(10, 10, kernel_size=3, padding=1)
  93. t_shape = (1, 10, 1, 1)
  94. weight = mge.Parameter(np.ones(t_shape, dtype=np.float32))
  95. bias = mge.Parameter(np.zeros(t_shape, dtype=np.float32))
  96. gm = GradManager()
  97. gm.attach(list(conv.parameters()) + [weight, bias])
  98. with gm:
  99. out1 = conv(x)
  100. out2 = F.batch_norm(out1, None, None, weight, bias, training=True,)
  101. # Weird error only occur when this action is placed after BN
  102. # Op type is not relevant
  103. loss = out1 + 1
  104. gm.backward(loss)
  105. @pytest.mark.require_ngpu(2)
  106. @pytest.mark.isolated_distributed
  107. @pytest.mark.parametrize(
  108. "trace_mode", [True, False, None], ids=["symbolic", "trace", "no_trace"]
  109. )
  110. def test_remote_grad(trace_mode):
  111. @dist.launcher
  112. def worker():
  113. rank = dist.get_rank()
  114. size = dist.get_world_size()
  115. x = mge.tensor(np.random.randn(1, rank * 2 + 2), dtype=np.float32)
  116. m = M.Linear(rank * 2 + 2, rank * 2 + 4)
  117. gm = GradManager().attach(m.parameters())
  118. opt = optim.SGD(m.parameters(), 1e-3, momentum=0.9)
  119. def train_func(x):
  120. with gm:
  121. if rank != 0:
  122. x = dist.functional.remote_recv(
  123. rank - 1, shape=(1, rank * 2 + 2), dtype=np.float32
  124. )
  125. y = m(x)
  126. if rank != size - 1:
  127. dist.functional.remote_send(y, dest_rank=rank + 1)
  128. gm.backward()
  129. else:
  130. y = y.mean()
  131. gm.backward(y)
  132. opt.step().clear_grad()
  133. if trace_mode is not None:
  134. train_func = trace(symbolic=trace_mode)(train_func)
  135. for i in range(3):
  136. train_func(x)
  137. worker()

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