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_manager.py 13 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. import os
  2. import platform
  3. import weakref
  4. import numpy as np
  5. import pytest
  6. import megengine as mge
  7. import megengine.core.tensor.dtype as dtype
  8. import megengine.distributed as dist
  9. import megengine.functional as F
  10. import megengine.module as M
  11. import megengine.optimizer as optim
  12. from megengine.autodiff import Function, GradManager
  13. from megengine.jit import trace
  14. def test_basic():
  15. x = mge.tensor([1.0, 3.0, 5.0]).reshape(1, 3)
  16. w = mge.tensor([2.0, 4.0, 6.0]).reshape(3, 1)
  17. b = mge.tensor(-1.0)
  18. gm = GradManager().attach([w, b])
  19. gm.record()
  20. p = F.matmul(x, w)
  21. y = p + b
  22. gm.backward(y)
  23. gm.release() # is not necessary
  24. np.testing.assert_equal(w.grad.numpy(), [[1], [3], [5]])
  25. np.testing.assert_equal(b.grad.numpy(), [1])
  26. w.grad = None
  27. b.grad = None
  28. with gm:
  29. p = F.matmul(x, w)
  30. y = p + b
  31. gm.backward(y)
  32. np.testing.assert_equal(w.grad.numpy(), [[1], [3], [5]])
  33. np.testing.assert_equal(b.grad.numpy(), [1])
  34. def test_dy():
  35. x = mge.tensor([1.0, 3.0, 5.0]).reshape(1, 3)
  36. w = mge.tensor([2.0, 4.0, 6.0]).reshape(3, 1)
  37. b = mge.tensor(-1.0)
  38. gm = GradManager().attach([w, b])
  39. def get_grad(grad, dy, idx):
  40. if isinstance(dy, (list, tuple)):
  41. return np.array(grad) * dy[idx]
  42. else:
  43. return np.array(grad) * dy
  44. # dy's shape should be the same as y's
  45. dy = mge.tensor(2.5).reshape(1, 1)
  46. w.grad = None
  47. b.grad = None
  48. with gm:
  49. p = F.matmul(x, w)
  50. y = p + b
  51. gm.backward(y, dy=dy)
  52. np.testing.assert_equal(w.grad.numpy(), [[1], [3], [5]] * dy.numpy())
  53. np.testing.assert_equal(b.grad.numpy(), [1] * dy.numpy())
  54. def test_attach_in_with_block():
  55. a = mge.Parameter([1.0])
  56. gm = GradManager()
  57. with gm:
  58. b = a * 3
  59. gm.attach(b)
  60. c = b + 1
  61. gm.backward(c)
  62. assert int(b.grad.numpy()) == 1
  63. def test_attach_temporary():
  64. w = mge.Parameter(2.0)
  65. gm = GradManager()
  66. gm.attach(w)
  67. def cb(x, g):
  68. assert x is ref()
  69. cb.called = True
  70. for i in range(3):
  71. with gm:
  72. cb.called = False
  73. x = mge.Tensor(i, dtype="float32")
  74. gm.attach(x, callbacks=cb)
  75. ref = weakref.ref(x)
  76. y = x * w
  77. gm.backward(y)
  78. assert cb.called
  79. del x
  80. assert ref() is None
  81. # NOTE: does not guarantee timely release when recording
  82. # for i in range(3):
  83. # with gm:
  84. # x = mge.Tensor(i, dtype='float32')
  85. # gm.attach(x)
  86. # ref = weakref.ref(x)
  87. # y = x * w
  88. # del x
  89. # assert ref() is None
  90. # gm.backward(y)
  91. def test_attached_tensors():
  92. w1 = mge.Parameter(2.0)
  93. w2 = mge.Parameter(2.0)
  94. gm = GradManager()
  95. def check(expected):
  96. actual = gm.attached_tensors()
  97. assert len(expected) == len(actual)
  98. for exp, act in zip(expected, actual):
  99. assert exp is act
  100. gm.attach(w1)
  101. check([w1])
  102. gm.attach(w2)
  103. check([w1, w2])
  104. gm.attach(w1)
  105. check([w1, w2])
  106. def test_no_dependency():
  107. x = mge.tensor(3)
  108. w = mge.Parameter(1.0)
  109. w_no_dep = mge.Parameter(1.0)
  110. gm = GradManager()
  111. gm.attach(w)
  112. gm.attach(w_no_dep)
  113. with gm:
  114. out1 = x * w
  115. out2 = w_no_dep * out1
  116. gm.backward(out1.sum())
  117. assert w.grad is not None
  118. assert w_no_dep.grad is None
  119. def test_regression_1762():
  120. x = F.ones((10, 10, 3, 3))
  121. conv = M.Conv2d(10, 10, kernel_size=3, padding=1)
  122. t_shape = (1, 10, 1, 1)
  123. weight = mge.Parameter(np.ones(t_shape, dtype=np.float32))
  124. bias = mge.Parameter(np.zeros(t_shape, dtype=np.float32))
  125. gm = GradManager()
  126. gm.attach(list(conv.parameters()) + [weight, bias])
  127. with gm:
  128. out1 = conv(x)
  129. out2 = F.batch_norm(out1, None, None, weight, bias, training=True,)
  130. # Weird error only occur when this action is placed after BN
  131. # Op type is not relevant
  132. loss = out1 + 1
  133. gm.backward(loss)
  134. def test_empty_grad_in_backward():
  135. x = mge.Parameter(F.full(100, 0.5))
  136. y = mge.Parameter(F.ones(100))
  137. gm = GradManager()
  138. gm.attach([x, y])
  139. with gm:
  140. z = F.where(x > 0.7, x, y)
  141. loss = z.sum()
  142. gm.backward(loss)
  143. assert np.all(x.grad.numpy() == 0)
  144. assert np.all(y.grad.numpy() == 1)
  145. @pytest.mark.require_ngpu(2)
  146. @pytest.mark.isolated_distributed
  147. @pytest.mark.parametrize(
  148. "trace_mode", [True, False, None], ids=["symbolic", "trace", "no_trace"]
  149. )
  150. def test_remote_grad(trace_mode):
  151. @dist.launcher
  152. def worker():
  153. rank = dist.get_rank()
  154. size = dist.get_world_size()
  155. x = mge.tensor(np.random.randn(1, rank * 2 + 2), dtype=np.float32)
  156. m = M.Linear(rank * 2 + 2, rank * 2 + 4)
  157. gm = GradManager().attach(m.parameters())
  158. opt = optim.SGD(m.parameters(), 1e-3, momentum=0.9)
  159. def train_func(x):
  160. with gm:
  161. if rank != 0:
  162. x = dist.functional.remote_recv(rank - 1)
  163. y = m(x)
  164. if rank != size - 1:
  165. x = dist.functional.remote_send(y, dest_rank=rank + 1)
  166. gm.backward()
  167. else:
  168. y = y.mean()
  169. gm.backward(y)
  170. opt.step().clear_grad()
  171. if trace_mode is not None:
  172. train_func = trace(symbolic=trace_mode)(train_func)
  173. for i in range(1):
  174. train_func(x)
  175. worker()
  176. @pytest.mark.require_ngpu(3)
  177. @pytest.mark.isolated_distributed
  178. @pytest.mark.parametrize(
  179. "trace_mode", [True, False, None], ids=["symbolic", "trace", "no_trace"]
  180. )
  181. def test_gather_grad(trace_mode):
  182. @dist.launcher(n_gpus=3)
  183. def worker():
  184. m = M.Linear(10, 10)
  185. x = F.ones([3, 10], dtype="float32")
  186. def func():
  187. with GradManager().attach(m.parameters()) as gm:
  188. y = m(x)
  189. y = F.distributed.gather(y)
  190. if dist.get_rank() == 0:
  191. loss = (2 * y + 1).mean()
  192. gm.backward(loss)
  193. else:
  194. gm.backward()
  195. if trace_mode is not None:
  196. func = trace(symbolic=trace_mode)(func)
  197. func()
  198. worker()
  199. @pytest.mark.require_ngpu(3)
  200. @pytest.mark.isolated_distributed
  201. @pytest.mark.parametrize(
  202. "trace_mode", [True, False, None], ids=["symbolic", "trace", "no_trace"]
  203. )
  204. def test_scatter_grad(trace_mode):
  205. @dist.launcher(n_gpus=3)
  206. def worker():
  207. x = F.ones([3, 10], dtype="float32")
  208. m = M.Linear(10, 10)
  209. def func():
  210. with GradManager().attach(m.parameters()) as gm:
  211. if dist.get_rank() == 0:
  212. y = m(x)
  213. else:
  214. y = x
  215. y = F.distributed.scatter(y)
  216. gm.backward(y)
  217. if trace_mode is not None:
  218. func = trace(symbolic=trace_mode)(func)
  219. func()
  220. worker()
  221. @pytest.mark.require_ngpu(3)
  222. @pytest.mark.isolated_distributed
  223. @pytest.mark.parametrize(
  224. "trace_mode", [True, False, None], ids=["symbolic", "trace", "no_trace"]
  225. )
  226. def test_reduce_grad(trace_mode):
  227. @dist.launcher(n_gpus=3)
  228. def worker():
  229. m = M.Linear(10, 10)
  230. x = F.ones([3, 10], dtype="float32")
  231. def func():
  232. with GradManager().attach(m.parameters()) as gm:
  233. y = m(x)
  234. y = F.distributed.reduce_sum(y)
  235. if dist.get_rank() == 0:
  236. loss = (2 * y + 1).mean()
  237. gm.backward(loss)
  238. else:
  239. gm.backward()
  240. if trace_mode is not None:
  241. func = trace(symbolic=trace_mode)(func)
  242. func()
  243. worker()
  244. @pytest.mark.require_ngpu(3)
  245. @pytest.mark.isolated_distributed
  246. @pytest.mark.parametrize(
  247. "trace_mode", [True, False, None], ids=["symbolic", "trace", "no_trace"]
  248. )
  249. def test_broadcast_grad(trace_mode):
  250. @dist.launcher(n_gpus=3)
  251. def worker():
  252. x = F.ones([3, 10], dtype="float32")
  253. m = M.Linear(10, 10)
  254. def func():
  255. with GradManager().attach(m.parameters()) as gm:
  256. if dist.get_rank() == 0:
  257. y = m(x)
  258. else:
  259. y = x
  260. y = F.distributed.broadcast(y)
  261. gm.backward(y)
  262. if trace_mode is not None:
  263. func = trace(symbolic=trace_mode)(func)
  264. func()
  265. worker()
  266. def test_2nd_grad_with_manager():
  267. x_np = np.random.rand(10).astype("float32")
  268. x = mge.tensor(x_np)
  269. gm = GradManager().attach([x])
  270. gm2 = GradManager().attach([x])
  271. with gm:
  272. with gm2:
  273. y = F.cos(x)
  274. gm2.backward(y)
  275. np.testing.assert_almost_equal(x.grad.numpy(), -np.sin(x_np), decimal=5)
  276. gm.backward(x.grad)
  277. np.testing.assert_almost_equal(
  278. x.grad.numpy(), -np.sin(x_np) - np.cos(x_np), decimal=5
  279. )
  280. def test_grad_manager_group():
  281. x_np = np.random.rand(10).astype("float32")
  282. x = mge.tensor(x_np)
  283. gm = GradManager().attach([x])
  284. gm2 = GradManager().attach([x])
  285. with gm | gm2:
  286. y = F.cos(x)
  287. gm.backward(y)
  288. gm2.backward(y)
  289. np.testing.assert_almost_equal(x.grad.numpy(), -2 * np.sin(x_np), decimal=5)
  290. x.grad = None
  291. def test_grad_manager_group_visibility():
  292. x_np = np.random.rand(10).astype("float32")
  293. x = mge.tensor(x_np)
  294. gm = GradManager().attach([x])
  295. gm2 = GradManager().attach([x])
  296. with gm | gm2:
  297. y = F.cos(x)
  298. gm2.backward(y)
  299. np.testing.assert_almost_equal(x.grad.numpy(), -np.sin(x_np), decimal=5)
  300. gm.backward(x.grad)
  301. np.testing.assert_almost_equal(x.grad.numpy(), -np.sin(x_np), decimal=5)
  302. def test_grad_manager_visibility_by_order():
  303. x_np = np.random.rand(10).astype("float32")
  304. x = mge.tensor(x_np)
  305. gm = GradManager().attach([x])
  306. gm2 = GradManager().attach([x])
  307. with gm2:
  308. with gm:
  309. y = F.cos(x)
  310. gm2.backward(y)
  311. np.testing.assert_almost_equal(x.grad.numpy(), -np.sin(x_np), decimal=5)
  312. gm.backward(x.grad)
  313. np.testing.assert_almost_equal(x.grad.numpy(), -np.sin(x_np), decimal=5)
  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)
  334. def test_2nd_grad_with_custom_gradient():
  335. class MySin(Function):
  336. def forward(self, x):
  337. self.inp = x
  338. x = mge.Tensor(x.numpy())
  339. y = F.sin(x)
  340. return y
  341. def backward(self, dy):
  342. dx = F.cos(self.inp) * dy
  343. return dx
  344. class MyCos(Function):
  345. def forward(self, x):
  346. self.inp = x
  347. x = mge.Tensor(x.numpy())
  348. y = F.cos(x)
  349. return y
  350. def backward(self, dy):
  351. if dy is None:
  352. return None
  353. dx = -MySin()(self.inp) * dy
  354. return dx
  355. x_np = np.random.rand(10).astype("float32")
  356. x = mge.tensor(x_np)
  357. gm = GradManager().attach([x])
  358. gm2 = GradManager().attach([x])
  359. with gm:
  360. with gm2:
  361. y = MyCos()(x)
  362. gm2.backward(y)
  363. np.testing.assert_almost_equal(x.grad.numpy(), -np.sin(x_np), decimal=5)
  364. gm.backward(x.grad)
  365. np.testing.assert_almost_equal(
  366. x.grad.numpy(), -np.sin(x_np) - np.cos(x_np), decimal=5
  367. )
  368. @pytest.mark.parametrize("invalid_dtype", [np.uint8, np.int8, np.int32])
  369. def test_attach_invalid_tensor_dtype(invalid_dtype):
  370. gm = GradManager()
  371. x = mge.tensor([1], dtype=invalid_dtype)
  372. with pytest.raises(AssertionError):
  373. gm.attach([x])
  374. @pytest.mark.parametrize("differentible_dtype", [np.float32, np.float16])
  375. def test_attach_differentible_tensor_dtype(differentible_dtype):
  376. gm = GradManager()
  377. x = mge.tensor([1], dtype=differentible_dtype)
  378. gm.attach([x])