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_autodiff.py 6.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. import platform
  10. import weakref
  11. import numpy as np
  12. import pytest
  13. import megengine as mge
  14. import megengine.distributed as dist
  15. from megengine.core._imperative_rt import TensorAttr, imperative
  16. from megengine.core._imperative_rt.imperative import sync
  17. from megengine.core.autodiff.grad import Grad
  18. from megengine.core.ops.builtin import Elemwise
  19. from megengine.core.tensor.raw_tensor import as_raw_tensor
  20. from megengine.core.tensor.tensor import Tensor, apply
  21. from megengine.core.tensor.tensor_wrapper import TensorWrapper
  22. from megengine.functional.distributed import remote_recv, remote_send
  23. def _elwise(mode):
  24. op = Elemwise(mode=mode)
  25. def f(*args):
  26. (result,) = apply(op, *args)
  27. return result
  28. return f
  29. add = _elwise("add")
  30. mul = _elwise("mul")
  31. cos = _elwise("cos")
  32. relu = _elwise("relu")
  33. def as_tensor(x):
  34. return Tensor(as_raw_tensor(x, device=mge.device.get_default_device()))
  35. def save_to(self, name="grad"):
  36. def callback(tensor, grad):
  37. setattr(self, name, grad)
  38. return callback
  39. @pytest.mark.isolated_distributed
  40. @pytest.mark.skipif(
  41. platform.system() == "Windows", reason="windows disable MGB_ENABLE_OPR_MM"
  42. )
  43. def test_dist_grad():
  44. world_size = 2
  45. x_np = np.random.rand(10).astype("float32")
  46. port = dist.get_free_ports(1)[0]
  47. server = dist.Server(port)
  48. def worker0():
  49. dist.init_process_group("localhost", port, world_size, 0, 0)
  50. mge.device.set_default_device("gpu0")
  51. grad = Grad()
  52. x = as_tensor(x_np)
  53. grad.wrt(x, callback=save_to(x))
  54. # need a placeholder to trace operator
  55. send_x = remote_send(x, 1)
  56. recv_x = remote_recv(1, x_np.shape, x_np.dtype, "gpu0")
  57. y = recv_x * recv_x
  58. grad([y], [as_tensor(np.ones_like(x_np))])
  59. np.testing.assert_almost_equal(x.grad.numpy(), x.numpy() * 2)
  60. def worker1():
  61. dist.init_process_group("localhost", port, world_size, 1, 1)
  62. mge.device.set_default_device("gpu1")
  63. grad = Grad()
  64. recv_x = remote_recv(0, x_np.shape, x_np.dtype, "gpu1")
  65. send_x = remote_send(recv_x, 0)
  66. grad([], [])
  67. # sync because grad has a send operator
  68. sync()
  69. send_x.device._cn._sync_all()
  70. import multiprocessing as mp
  71. p0 = mp.Process(target=worker0)
  72. p1 = mp.Process(target=worker1)
  73. p0.start()
  74. p1.start()
  75. p0.join(10)
  76. p1.join(10)
  77. assert p0.exitcode == 0 and p1.exitcode == 0
  78. def test_grad():
  79. x_np = np.random.rand(10).astype("float32")
  80. x = as_tensor(x_np)
  81. grad = Grad().wrt(x, callback=save_to(x))
  82. y = cos(x)
  83. grad(y, as_tensor(np.ones_like(x_np)))
  84. np.testing.assert_almost_equal(x.grad.numpy(), -np.sin(x_np))
  85. def test_grad_2():
  86. x_np = np.random.rand(10).astype("float32")
  87. x = as_tensor(x_np)
  88. grad = Grad().wrt(x, callback=save_to(x))
  89. y = mul(x, x)
  90. y = mul(y, y)
  91. grad(y, as_tensor(np.ones_like(x_np)))
  92. np.testing.assert_almost_equal(x.grad.numpy(), 4 * x_np ** 3, decimal=6)
  93. @pytest.mark.skip(reason="high order gradient was not implemented yet")
  94. def test_2nd_grad():
  95. x_np = np.random.rand(10).astype("float32")
  96. x = as_tensor(x_np)
  97. ones = as_tensor(np.ones_like(x_np))
  98. grad = Grad().wrt(x, callback=save_to(x))
  99. grad2 = Grad().wrt(x, callback=save_to(x))
  100. y = cos(x)
  101. grad(y, ones)
  102. np.testing.assert_almost_equal(x.grad.numpy(), -np.sin(x_np), decimal=5)
  103. grad2(x.grad, ones)
  104. np.testing.assert_almost_equal(x.grad.numpy(), -np.cos(x_np))
  105. def test_grad_with_tensor_wrapper():
  106. x_np = np.random.rand(10).astype("float32")
  107. x = TensorWrapper(x_np)
  108. grad = Grad().wrt(x, callback=save_to(x))
  109. y = mul(x, x)
  110. y = mul(y, y)
  111. grad(y, TensorWrapper(np.ones_like(x_np)))
  112. np.testing.assert_almost_equal(x.grad.numpy(), 4 * x_np ** 3, decimal=6)
  113. def test_grad_inplace():
  114. x_np = np.random.rand(10).astype("float32")
  115. x = TensorWrapper(x_np)
  116. grad = Grad().wrt(x, callback=save_to(x))
  117. y = mul(x, x)
  118. y *= y
  119. grad(y, TensorWrapper(np.ones_like(x_np)))
  120. np.testing.assert_almost_equal(x.grad.numpy(), 4 * x_np ** 3, decimal=6)
  121. def test_elemwise_add():
  122. x_np = np.random.rand(10).astype("float32")
  123. y_np = np.random.rand(10, 10).astype("float32")
  124. dz_np = np.random.rand(10, 10).astype("float32")
  125. x = TensorWrapper(x_np)
  126. y = TensorWrapper(y_np)
  127. dz = TensorWrapper(dz_np)
  128. refs = {}
  129. def f(x, y):
  130. x = x * 2
  131. refs["x"] = weakref.ref(x.__wrapped__)
  132. refs["y"] = weakref.ref(y.__wrapped__)
  133. return x + y
  134. grad = Grad().wrt(x, callback=save_to(x))
  135. z = f(x, y)
  136. del y
  137. for k, r in refs.items():
  138. assert r() is None
  139. grad(z, dz)
  140. np.testing.assert_almost_equal(x.grad.numpy(), dz_np.sum(0) * 2, decimal=5)
  141. def test_elemwise_relu():
  142. x_np = [1.0, -1.0]
  143. dz_np = [1.0]
  144. x = TensorWrapper(x_np)
  145. dz = TensorWrapper(dz_np)
  146. refs = {}
  147. def f(x):
  148. x = x * 2
  149. refs["x"] = weakref.ref(x.__wrapped__)
  150. return relu(x)
  151. grad = Grad().wrt(x, callback=save_to(x))
  152. z = f(x)
  153. assert refs["x"]() is None
  154. grad(z, dz)
  155. np.testing.assert_almost_equal(x.grad.numpy(), [2.0, 0])
  156. def test_elemwise_relu_backward_fn():
  157. op = Elemwise(mode="relu").to_c()
  158. attr = TensorAttr()
  159. attr.dtype = "float32"
  160. attr.comp_node = "xpux"
  161. result = imperative.make_backward_graph(op, [attr], [True], [True])
  162. backward_graph, save_for_backward_mask, input_has_grad = result
  163. assert save_for_backward_mask == [False, True, True], save_for_backward_mask

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