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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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 Function, 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. def test_empty_grad_in_backward():
  141. x = mge.Parameter(F.full(100, 0.5))
  142. y = mge.Parameter(F.ones(100))
  143. gm = GradManager()
  144. gm.attach([x, y])
  145. with gm:
  146. z = F.where(x > 0.7, x, y)
  147. loss = z.sum()
  148. gm.backward(loss)
  149. assert np.all(x.grad.numpy() == 0)
  150. assert np.all(y.grad.numpy() == 1)
  151. @pytest.mark.require_ngpu(2)
  152. @pytest.mark.isolated_distributed
  153. @pytest.mark.parametrize(
  154. "trace_mode", [True, False, None], ids=["symbolic", "trace", "no_trace"]
  155. )
  156. def test_remote_grad(trace_mode):
  157. @dist.launcher
  158. def worker():
  159. rank = dist.get_rank()
  160. size = dist.get_world_size()
  161. x = mge.tensor(np.random.randn(1, rank * 2 + 2), dtype=np.float32)
  162. m = M.Linear(rank * 2 + 2, rank * 2 + 4)
  163. gm = GradManager().attach(m.parameters())
  164. opt = optim.SGD(m.parameters(), 1e-3, momentum=0.9)
  165. def train_func(x):
  166. with gm:
  167. if rank != 0:
  168. x = dist.functional.remote_recv(rank - 1)
  169. y = m(x)
  170. if rank != size - 1:
  171. x = dist.functional.remote_send(y, dest_rank=rank + 1)
  172. gm.backward()
  173. else:
  174. y = y.mean()
  175. gm.backward(y)
  176. opt.step().clear_grad()
  177. if trace_mode is not None:
  178. train_func = trace(symbolic=trace_mode)(train_func)
  179. for i in range(1):
  180. train_func(x)
  181. worker()
  182. @pytest.mark.require_ngpu(3)
  183. @pytest.mark.isolated_distributed
  184. @pytest.mark.parametrize(
  185. "trace_mode", [True, False, None], ids=["symbolic", "trace", "no_trace"]
  186. )
  187. def test_gather_grad(trace_mode):
  188. @dist.launcher(n_gpus=3)
  189. def worker():
  190. m = M.Linear(10, 10)
  191. x = F.ones([3, 10], dtype="float32")
  192. def func():
  193. with GradManager().attach(m.parameters()) as gm:
  194. y = m(x)
  195. y = F.distributed.gather(y)
  196. if dist.get_rank() == 0:
  197. loss = (2 * y + 1).mean()
  198. gm.backward(loss)
  199. else:
  200. gm.backward()
  201. if trace_mode is not None:
  202. func = trace(symbolic=trace_mode)(func)
  203. func()
  204. worker()
  205. @pytest.mark.require_ngpu(3)
  206. @pytest.mark.isolated_distributed
  207. @pytest.mark.parametrize(
  208. "trace_mode", [True, False, None], ids=["symbolic", "trace", "no_trace"]
  209. )
  210. def test_scatter_grad(trace_mode):
  211. @dist.launcher(n_gpus=3)
  212. def worker():
  213. x = F.ones([3, 10], dtype="float32")
  214. m = M.Linear(10, 10)
  215. def func():
  216. with GradManager().attach(m.parameters()) as gm:
  217. if dist.get_rank() == 0:
  218. y = m(x)
  219. else:
  220. y = x
  221. y = F.distributed.scatter(y)
  222. gm.backward(y)
  223. if trace_mode is not None:
  224. func = trace(symbolic=trace_mode)(func)
  225. func()
  226. worker()
  227. @pytest.mark.require_ngpu(3)
  228. @pytest.mark.isolated_distributed
  229. @pytest.mark.parametrize(
  230. "trace_mode", [True, False, None], ids=["symbolic", "trace", "no_trace"]
  231. )
  232. def test_reduce_grad(trace_mode):
  233. @dist.launcher(n_gpus=3)
  234. def worker():
  235. m = M.Linear(10, 10)
  236. x = F.ones([3, 10], dtype="float32")
  237. def func():
  238. with GradManager().attach(m.parameters()) as gm:
  239. y = m(x)
  240. y = F.distributed.reduce_sum(y)
  241. if dist.get_rank() == 0:
  242. loss = (2 * y + 1).mean()
  243. gm.backward(loss)
  244. else:
  245. gm.backward()
  246. if trace_mode is not None:
  247. func = trace(symbolic=trace_mode)(func)
  248. func()
  249. worker()
  250. @pytest.mark.require_ngpu(3)
  251. @pytest.mark.isolated_distributed
  252. @pytest.mark.parametrize(
  253. "trace_mode", [True, False, None], ids=["symbolic", "trace", "no_trace"]
  254. )
  255. def test_broadcast_grad(trace_mode):
  256. @dist.launcher(n_gpus=3)
  257. def worker():
  258. x = F.ones([3, 10], dtype="float32")
  259. m = M.Linear(10, 10)
  260. def func():
  261. with GradManager().attach(m.parameters()) as gm:
  262. if dist.get_rank() == 0:
  263. y = m(x)
  264. else:
  265. y = x
  266. y = F.distributed.broadcast(y)
  267. gm.backward(y)
  268. if trace_mode is not None:
  269. func = trace(symbolic=trace_mode)(func)
  270. func()
  271. worker()
  272. def test_2nd_grad_with_manager():
  273. x_np = np.random.rand(10).astype("float32")
  274. x = mge.tensor(x_np)
  275. gm = GradManager().attach([x])
  276. gm2 = GradManager().attach([x])
  277. with gm:
  278. with gm2:
  279. y = F.cos(x)
  280. gm2.backward(y)
  281. np.testing.assert_almost_equal(x.grad.numpy(), -np.sin(x_np), decimal=5)
  282. gm.backward(x.grad)
  283. np.testing.assert_almost_equal(
  284. x.grad.numpy(), -np.sin(x_np) - np.cos(x_np), decimal=5
  285. )
  286. def test_grad_manager_group():
  287. x_np = np.random.rand(10).astype("float32")
  288. x = mge.tensor(x_np)
  289. gm = GradManager().attach([x])
  290. gm2 = GradManager().attach([x])
  291. with gm | gm2:
  292. y = F.cos(x)
  293. gm.backward(y)
  294. gm2.backward(y)
  295. np.testing.assert_almost_equal(x.grad.numpy(), -2 * np.sin(x_np), decimal=5)
  296. x.grad = None
  297. def test_grad_manager_group_visibility():
  298. x_np = np.random.rand(10).astype("float32")
  299. x = mge.tensor(x_np)
  300. gm = GradManager().attach([x])
  301. gm2 = GradManager().attach([x])
  302. with gm | gm2:
  303. y = F.cos(x)
  304. gm2.backward(y)
  305. np.testing.assert_almost_equal(x.grad.numpy(), -np.sin(x_np), decimal=5)
  306. gm.backward(x.grad)
  307. np.testing.assert_almost_equal(x.grad.numpy(), -np.sin(x_np), decimal=5)
  308. def test_grad_manager_visibility_by_order():
  309. x_np = np.random.rand(10).astype("float32")
  310. x = mge.tensor(x_np)
  311. gm = GradManager().attach([x])
  312. gm2 = GradManager().attach([x])
  313. with gm2:
  314. with gm:
  315. y = F.cos(x)
  316. gm2.backward(y)
  317. np.testing.assert_almost_equal(x.grad.numpy(), -np.sin(x_np), decimal=5)
  318. gm.backward(x.grad)
  319. np.testing.assert_almost_equal(x.grad.numpy(), -np.sin(x_np), decimal=5)
  320. @pytest.mark.parametrize("target", [F.cos, F.sin, lambda x: x * 2 + 1])
  321. def test_emulate_forward_mode_with_reverse_mode(target):
  322. def jvp(inp, expr):
  323. with GradManager() as gm:
  324. with GradManager().attach([inp]) as gm2:
  325. oup = expr(inp)
  326. oup_grad = F.zeros_like(oup)
  327. gm.attach(oup_grad)
  328. gm2.backward(oup, oup_grad)
  329. gm.backward(inp.grad)
  330. return oup, oup_grad.grad
  331. def fake_jvp(inp, expr):
  332. delta = 0.001
  333. return expr(inp), (expr(inp + delta) - expr(inp - delta)) / (2 * delta)
  334. x_np = np.random.rand(10).astype("float32")
  335. x = mge.tensor(x_np)
  336. y, dy = jvp(x, target)
  337. y1, dy1 = fake_jvp(x, target)
  338. np.testing.assert_almost_equal(y.numpy(), y1.numpy(), decimal=5)
  339. np.testing.assert_almost_equal(dy.numpy(), dy1.numpy(), decimal=3)
  340. def test_2nd_grad_with_custom_gradient():
  341. class MySin(Function):
  342. def forward(self, x):
  343. self.inp = x
  344. x = mge.Tensor(x.numpy())
  345. y = F.sin(x)
  346. return y
  347. def backward(self, dy):
  348. dx = F.cos(self.inp) * dy
  349. return dx
  350. class MyCos(Function):
  351. def forward(self, x):
  352. self.inp = x
  353. x = mge.Tensor(x.numpy())
  354. y = F.cos(x)
  355. return y
  356. def backward(self, dy):
  357. dx = -MySin()(self.inp) * dy
  358. return dx
  359. x_np = np.random.rand(10).astype("float32")
  360. x = mge.tensor(x_np)
  361. gm = GradManager().attach([x])
  362. gm2 = GradManager().attach([x])
  363. with gm:
  364. with gm2:
  365. y = MyCos()(x)
  366. gm2.backward(y)
  367. np.testing.assert_almost_equal(x.grad.numpy(), -np.sin(x_np), decimal=5)
  368. gm.backward(x.grad)
  369. np.testing.assert_almost_equal(
  370. x.grad.numpy(), -np.sin(x_np) - np.cos(x_np), decimal=5
  371. )