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

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