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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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 os
  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. import megengine.functional as F
  16. import megengine.module as M
  17. import megengine.optimizer as optim
  18. from megengine.autodiff import GradManager
  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_dy():
  41. x = mge.tensor([1.0, 3.0, 5.0]).reshape(1, 3)
  42. w = mge.tensor([2.0, 4.0, 6.0]).reshape(3, 1)
  43. b = mge.tensor(-1.0)
  44. gm = GradManager().attach([w, b])
  45. def get_grad(grad, dy, idx):
  46. if isinstance(dy, (list, tuple)):
  47. return np.array(grad) * dy[idx]
  48. else:
  49. return np.array(grad) * dy
  50. # dy's shape should be the same as y's
  51. dy = mge.tensor(2.5).reshape(1, 1)
  52. w.grad = None
  53. b.grad = None
  54. with gm:
  55. p = F.matmul(x, w)
  56. y = p + b
  57. gm.backward(y, dy=dy)
  58. np.testing.assert_equal(w.grad.numpy(), [[1], [3], [5]] * dy.numpy())
  59. np.testing.assert_equal(b.grad.numpy(), [1] * dy.numpy())
  60. def test_attach_in_with_block():
  61. a = mge.Parameter([1.0])
  62. gm = GradManager()
  63. with gm:
  64. b = a * 3
  65. gm.attach(b)
  66. c = b + 1
  67. gm.backward(c)
  68. assert int(b.grad.numpy()) == 1
  69. def test_attach_temporary():
  70. w = mge.Parameter(2.0)
  71. gm = GradManager()
  72. gm.attach(w)
  73. def cb(x, g):
  74. assert x is ref()
  75. cb.called = True
  76. for i in range(3):
  77. with gm:
  78. cb.called = False
  79. x = mge.Tensor(i, dtype="float32")
  80. gm.attach(x, callbacks=cb)
  81. ref = weakref.ref(x)
  82. y = x * w
  83. gm.backward(y)
  84. assert cb.called
  85. del x
  86. assert ref() is None
  87. # NOTE: does not guarantee timely release when recording
  88. # for i in range(3):
  89. # with gm:
  90. # x = mge.Tensor(i, dtype='float32')
  91. # gm.attach(x)
  92. # ref = weakref.ref(x)
  93. # y = x * w
  94. # del x
  95. # assert ref() is None
  96. # gm.backward(y)
  97. def test_attached_tensors():
  98. w1 = mge.Parameter(2.0)
  99. w2 = mge.Parameter(2.0)
  100. gm = GradManager()
  101. def check(expected):
  102. actual = gm.attached_tensors()
  103. assert len(expected) == len(actual)
  104. for exp, act in zip(expected, actual):
  105. assert exp is act
  106. gm.attach(w1)
  107. check([w1])
  108. gm.attach(w2)
  109. check([w1, w2])
  110. gm.attach(w1)
  111. check([w1, w2])
  112. def test_no_dependency():
  113. x = mge.tensor(3)
  114. w = mge.Parameter(1.0)
  115. w_no_dep = mge.Parameter(1.0)
  116. gm = GradManager()
  117. gm.attach(w)
  118. gm.attach(w_no_dep)
  119. with gm:
  120. out1 = x * w
  121. out2 = w_no_dep * out1
  122. gm.backward(out1.sum())
  123. assert w.grad is not None
  124. assert w_no_dep.grad is None
  125. def test_regression_1762():
  126. x = F.ones((10, 10, 3, 3))
  127. conv = M.Conv2d(10, 10, kernel_size=3, padding=1)
  128. t_shape = (1, 10, 1, 1)
  129. weight = mge.Parameter(np.ones(t_shape, dtype=np.float32))
  130. bias = mge.Parameter(np.zeros(t_shape, dtype=np.float32))
  131. gm = GradManager()
  132. gm.attach(list(conv.parameters()) + [weight, bias])
  133. with gm:
  134. out1 = conv(x)
  135. out2 = F.batch_norm(out1, None, None, weight, bias, training=True,)
  136. # Weird error only occur when this action is placed after BN
  137. # Op type is not relevant
  138. loss = out1 + 1
  139. gm.backward(loss)
  140. @pytest.mark.require_ngpu(2)
  141. @pytest.mark.isolated_distributed
  142. @pytest.mark.parametrize(
  143. "trace_mode", [True, False, None], ids=["symbolic", "trace", "no_trace"]
  144. )
  145. def test_remote_grad(trace_mode):
  146. @dist.launcher
  147. def worker():
  148. rank = dist.get_rank()
  149. size = dist.get_world_size()
  150. x = mge.tensor(np.random.randn(1, rank * 2 + 2), dtype=np.float32)
  151. m = M.Linear(rank * 2 + 2, rank * 2 + 4)
  152. gm = GradManager().attach(m.parameters())
  153. opt = optim.SGD(m.parameters(), 1e-3, momentum=0.9)
  154. def train_func(x):
  155. with gm:
  156. if rank != 0:
  157. x = dist.functional.remote_recv(rank - 1)
  158. y = m(x)
  159. if rank != size - 1:
  160. dist.functional.remote_send(y, dest_rank=rank + 1)
  161. gm.backward()
  162. else:
  163. y = y.mean()
  164. gm.backward(y)
  165. opt.step().clear_grad()
  166. if trace_mode is not None:
  167. train_func = trace(symbolic=trace_mode)(train_func)
  168. for i in range(3):
  169. train_func(x)
  170. worker()
  171. @pytest.mark.require_ngpu(3)
  172. @pytest.mark.isolated_distributed
  173. @pytest.mark.parametrize(
  174. "trace_mode", [True, False, None], ids=["symbolic", "trace", "no_trace"]
  175. )
  176. def test_gather_grad(trace_mode):
  177. @dist.launcher(n_gpus=3)
  178. def worker():
  179. m = M.Linear(10, 10)
  180. x = F.ones([3, 10], dtype="float32")
  181. def func():
  182. with GradManager().attach(m.parameters()) as gm:
  183. y = m(x)
  184. y = F.distributed.gather(y)
  185. if dist.get_rank() == 0:
  186. loss = (2 * y + 1).mean()
  187. gm.backward(loss)
  188. else:
  189. gm.backward()
  190. if trace_mode is not None:
  191. func = trace(symbolic=trace_mode)(func)
  192. func()
  193. worker()
  194. @pytest.mark.require_ngpu(3)
  195. @pytest.mark.isolated_distributed
  196. @pytest.mark.parametrize(
  197. "trace_mode", [True, False, None], ids=["symbolic", "trace", "no_trace"]
  198. )
  199. def test_scatter_grad(trace_mode):
  200. @dist.launcher(n_gpus=3)
  201. def worker():
  202. x = F.ones([3, 10], dtype="float32")
  203. m = M.Linear(10, 10)
  204. def func():
  205. with GradManager().attach(m.parameters()) as gm:
  206. if dist.get_rank() == 0:
  207. y = m(x)
  208. else:
  209. y = x
  210. y = F.distributed.scatter(y)
  211. gm.backward(y)
  212. if trace_mode is not None:
  213. func = trace(symbolic=trace_mode)(func)
  214. func()
  215. worker()
  216. @pytest.mark.require_ngpu(3)
  217. @pytest.mark.isolated_distributed
  218. @pytest.mark.parametrize(
  219. "trace_mode", [True, False, None], ids=["symbolic", "trace", "no_trace"]
  220. )
  221. def test_reduce_grad(trace_mode):
  222. @dist.launcher(n_gpus=3)
  223. def worker():
  224. m = M.Linear(10, 10)
  225. x = F.ones([3, 10], dtype="float32")
  226. def func():
  227. with GradManager().attach(m.parameters()) as gm:
  228. y = m(x)
  229. y = F.distributed.reduce_sum(y)
  230. if dist.get_rank() == 0:
  231. loss = (2 * y + 1).mean()
  232. gm.backward(loss)
  233. else:
  234. gm.backward()
  235. if trace_mode is not None:
  236. func = trace(symbolic=trace_mode)(func)
  237. func()
  238. worker()
  239. @pytest.mark.require_ngpu(3)
  240. @pytest.mark.isolated_distributed
  241. @pytest.mark.parametrize(
  242. "trace_mode", [True, False, None], ids=["symbolic", "trace", "no_trace"]
  243. )
  244. def test_broadcast_grad(trace_mode):
  245. @dist.launcher(n_gpus=3)
  246. def worker():
  247. x = F.ones([3, 10], dtype="float32")
  248. m = M.Linear(10, 10)
  249. def func():
  250. with GradManager().attach(m.parameters()) as gm:
  251. if dist.get_rank() == 0:
  252. y = m(x)
  253. else:
  254. y = x
  255. y = F.distributed.broadcast(y)
  256. gm.backward(y)
  257. if trace_mode is not None:
  258. func = trace(symbolic=trace_mode)(func)
  259. func()
  260. worker()
  261. @pytest.mark.require_higher_order_directive()
  262. def test_2nd_grad_with_manager():
  263. x_np = np.random.rand(10).astype("float32")
  264. x = mge.tensor(x_np)
  265. gm = GradManager().attach([x])
  266. gm2 = GradManager().attach([x])
  267. with gm:
  268. with gm2:
  269. y = F.cos(x)
  270. gm2.backward(y)
  271. np.testing.assert_almost_equal(x.grad.numpy(), -np.sin(x_np), decimal=5)
  272. gm.backward(x.grad)
  273. np.testing.assert_almost_equal(
  274. x.grad.numpy(), -np.sin(x_np) - np.cos(x_np), decimal=5
  275. )
  276. @pytest.mark.require_higher_order_directive()
  277. def test_grad_manager_group():
  278. x_np = np.random.rand(10).astype("float32")
  279. x = mge.tensor(x_np)
  280. gm = GradManager().attach([x])
  281. gm2 = GradManager().attach([x])
  282. with gm | gm2:
  283. y = F.cos(x)
  284. gm.backward(y)
  285. gm2.backward(y)
  286. np.testing.assert_almost_equal(x.grad.numpy(), -2 * np.sin(x_np), decimal=5)
  287. x.grad = None
  288. @pytest.mark.require_higher_order_directive()
  289. def test_grad_manager_group_visibility():
  290. x_np = np.random.rand(10).astype("float32")
  291. x = mge.tensor(x_np)
  292. gm = GradManager().attach([x])
  293. gm2 = GradManager().attach([x])
  294. with gm | gm2:
  295. y = F.cos(x)
  296. gm2.backward(y)
  297. np.testing.assert_almost_equal(x.grad.numpy(), -np.sin(x_np), decimal=5)
  298. gm.backward(x.grad)
  299. np.testing.assert_almost_equal(x.grad.numpy(), -np.sin(x_np), decimal=5)
  300. @pytest.mark.require_higher_order_directive()
  301. def test_grad_manager_visibility_by_order():
  302. x_np = np.random.rand(10).astype("float32")
  303. x = mge.tensor(x_np)
  304. gm = GradManager().attach([x])
  305. gm2 = GradManager().attach([x])
  306. with gm2:
  307. with gm:
  308. y = F.cos(x)
  309. gm2.backward(y)
  310. np.testing.assert_almost_equal(x.grad.numpy(), -np.sin(x_np), decimal=5)
  311. gm.backward(x.grad)
  312. np.testing.assert_almost_equal(x.grad.numpy(), -np.sin(x_np), decimal=5)
  313. @pytest.mark.require_higher_order_directive()
  314. @pytest.mark.parametrize("target", [F.cos, F.sin, lambda x: x * 2 + 1])
  315. def test_emulate_forward_mode_with_reverse_mode(target):
  316. def jvp(inp, expr):
  317. with GradManager() as gm:
  318. with GradManager().attach([inp]) as gm2:
  319. oup = expr(inp)
  320. oup_grad = F.zeros_like(oup)
  321. gm.attach(oup_grad)
  322. gm2.backward(oup, oup_grad)
  323. gm.backward(inp.grad)
  324. return oup, oup_grad.grad
  325. def fake_jvp(inp, expr):
  326. delta = 0.001
  327. return expr(inp), (expr(inp + delta) - expr(inp - delta)) / (2 * delta)
  328. x_np = np.random.rand(10).astype("float32")
  329. x = mge.tensor(x_np)
  330. y, dy = jvp(x, target)
  331. y1, dy1 = fake_jvp(x, target)
  332. np.testing.assert_almost_equal(y.numpy(), y1.numpy(), decimal=5)
  333. np.testing.assert_almost_equal(dy.numpy(), dy1.numpy(), decimal=3)

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