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

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

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