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_function.py 8.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  2. #
  3. # Copyright (c) 2014-2020 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 copy
  9. import numpy as np
  10. import megengine.autodiff as ad
  11. import megengine.functional as F
  12. import megengine.optimizer as optimizer
  13. from megengine import Parameter
  14. from megengine import Tensor as tensor
  15. from megengine import tensor
  16. from megengine.core.tensor.function import Function
  17. from megengine.module import Module
  18. def test_single_input():
  19. data_shape = (9, 2, 6)
  20. av = np.random.random(data_shape).astype(np.float32)
  21. class MulFunc(Function):
  22. def forward(self, a):
  23. self.a = a
  24. return a * 10
  25. def backward(self, grad_o):
  26. return grad_o * 10
  27. class Simple(Module):
  28. def __init__(self, a):
  29. super().__init__()
  30. self.a = Parameter(a, dtype=np.float32)
  31. self.layer1 = MulFunc()
  32. def forward(self):
  33. x = self.layer1(self.a)
  34. return x
  35. net = Simple(av)
  36. gm = ad.GradManager().attach(net.parameters())
  37. opt = optimizer.SGD(net.parameters(), lr=1.0)
  38. opt.clear_grad()
  39. with gm:
  40. loss = net()
  41. gm.backward(loss.sum())
  42. opt.step()
  43. np.testing.assert_almost_equal(loss.numpy(), (av * 10))
  44. np.testing.assert_almost_equal(net.a.numpy(), (av - 10))
  45. def test_multi_input():
  46. data_shape = (9, 2, 6)
  47. av = np.random.random(data_shape).astype(np.float32)
  48. bv = np.random.random(data_shape).astype(np.float32)
  49. class MulFunc(Function):
  50. def forward(self, a, b):
  51. self.a = a
  52. self.b = b
  53. return a * b
  54. def backward(self, grad_o):
  55. return grad_o * self.b * 2, grad_o * self.a * 3
  56. class Simple(Module):
  57. def __init__(self, a, b):
  58. super().__init__()
  59. self.a = Parameter(a, dtype=np.float32)
  60. self.b = Parameter(b, dtype=np.float32)
  61. self.layer1 = MulFunc()
  62. def forward(self):
  63. x = self.layer1(self.a, self.b)
  64. return x
  65. net = Simple(av, bv)
  66. gm = ad.GradManager().attach(net.parameters())
  67. opt = optimizer.SGD(net.parameters(), lr=1.0)
  68. opt.clear_grad()
  69. with gm:
  70. loss = net()
  71. gm.backward(loss.sum())
  72. opt.step()
  73. np.testing.assert_almost_equal(loss.numpy(), (av * bv))
  74. np.testing.assert_almost_equal(net.a.numpy(), (av - 2 * bv))
  75. np.testing.assert_almost_equal(net.b.numpy(), (bv - 3 * av))
  76. def test_multi_output():
  77. data_shape = (9, 2, 6)
  78. av = np.random.random(data_shape).astype(np.float32)
  79. bv = np.random.random(data_shape).astype(np.float32)
  80. class MulFunc(Function):
  81. def forward(self, a, b):
  82. self.a = a
  83. self.b = b
  84. return a * b, a + b
  85. def backward(self, grad_1, grad_2):
  86. return grad_1 * (self.b + 1), grad_2 * (self.a + 1)
  87. class Simple(Module):
  88. def __init__(self, a, b):
  89. super().__init__()
  90. self.a = Parameter(a, dtype=np.float32)
  91. self.b = Parameter(b, dtype=np.float32)
  92. self.layer1 = MulFunc()
  93. def forward(self):
  94. x, y = self.layer1(self.a, self.b)
  95. return x + y
  96. net = Simple(av, bv)
  97. gm = ad.GradManager().attach(net.parameters())
  98. opt = optimizer.SGD(net.parameters(), lr=1.0)
  99. opt.clear_grad()
  100. with gm:
  101. loss = net()
  102. gm.backward(loss.sum())
  103. opt.step()
  104. np.testing.assert_almost_equal(loss.numpy(), (av * bv + av + bv), decimal=6)
  105. np.testing.assert_almost_equal(net.a.numpy(), (av - bv - 1), decimal=6)
  106. np.testing.assert_almost_equal(net.b.numpy(), (bv - av - 1), decimal=6)
  107. def test_skip_invalid_grad():
  108. data_shape = (1, 9, 2, 6)
  109. av = np.random.random(data_shape).astype(np.float32)
  110. bv = np.random.random(data_shape).astype(np.float32)
  111. c = np.random.random(data_shape).astype(np.float32)
  112. cookie = tensor(c)
  113. class EqWithFakeGrad(Function):
  114. def forward(self, a, b):
  115. return a + b
  116. def backward(self, grad_o):
  117. _ = grad_o
  118. return cookie, cookie
  119. class Simple(Module):
  120. def __init__(self, a, b):
  121. super().__init__()
  122. self.a = Parameter(a, dtype=np.float32)
  123. self.b = Parameter(b, dtype=np.float32)
  124. self.layer1 = EqWithFakeGrad()
  125. def forward(self):
  126. x = self.layer1(self.a, self.b)
  127. return x
  128. net = Simple(av, bv)
  129. optim = optimizer.SGD(net.parameters(), lr=1.0)
  130. gm = ad.GradManager().attach(net.parameters())
  131. optim.clear_grad()
  132. with gm:
  133. loss = net().sum()
  134. gm.backward(loss)
  135. optim.step()
  136. np.testing.assert_almost_equal(net.a.numpy(), av - c)
  137. np.testing.assert_almost_equal(net.b.numpy(), bv - c)
  138. def test_ste():
  139. class STE(Function):
  140. def forward(self, x):
  141. maxv, minv = x.max(), x.min()
  142. scale = F.maximum(maxv, -minv) / 127
  143. return F.round(x / scale) * scale
  144. def backward(self, grad_y):
  145. return grad_y
  146. class Simple(Module):
  147. def __init__(self, a):
  148. super().__init__()
  149. self.a = Parameter(a, dtype=np.float32)
  150. self.layer1 = STE()
  151. def forward(self):
  152. x = self.layer1(self.a)
  153. x = (x * 2.0).sum()
  154. return x
  155. data_shape = (1, 9, 2, 6)
  156. av = np.random.random(data_shape).astype(np.float32)
  157. net = Simple(av)
  158. optim = optimizer.SGD(net.parameters(), lr=1.0)
  159. gm = ad.GradManager().attach(net.parameters())
  160. optim.clear_grad()
  161. with gm:
  162. loss = net()
  163. gm.backward(loss.sum())
  164. optim.step()
  165. np.testing.assert_almost_equal(
  166. net.a.numpy(),
  167. av - np.broadcast_to(np.array([2.0], dtype=np.float32), data_shape),
  168. )
  169. def test_deepcopy():
  170. class Sigmoid(Function):
  171. def __init__(self, param):
  172. super().__init__()
  173. self.param = param
  174. def forward(self, x):
  175. y = 1 / (1 + F.exp(-x))
  176. self.save_for_backward(y)
  177. return y
  178. def backward(self, grad_y):
  179. (y,) = self.saved_tensors
  180. return grad_y * y * (1 - y)
  181. origin = Sigmoid(0)
  182. new = copy.deepcopy(Sigmoid(0))
  183. assert new.param == origin.param
  184. def test_none_in_out_grad():
  185. class Test(Function):
  186. def forward(self, a, b):
  187. return a, b
  188. def backward(self, grad_a, grad_b):
  189. assert grad_b is None
  190. return (grad_a, 0.0)
  191. class Simple(Module):
  192. def __init__(self, a, b):
  193. super().__init__()
  194. self.a = Parameter(a, dtype=np.float32)
  195. self.b = Parameter(b, dtype=np.float32)
  196. self.layer = Test()
  197. def forward(self):
  198. aa, bb = self.layer(self.a, self.b)
  199. return aa, bb
  200. a = tensor(np.array([1.0], dtype=np.float32))
  201. b = tensor(np.array([2.0], dtype=np.float32))
  202. net = Simple(a, b)
  203. optim = optimizer.SGD(net.parameters(), lr=1.0)
  204. gm = ad.GradManager().attach(net.parameters())
  205. optim.clear_grad()
  206. with gm:
  207. loss, _ = net()
  208. gm.backward(loss)
  209. optim.step()
  210. np.testing.assert_almost_equal(
  211. net.a.numpy(), np.array([1.0 - 1.0], dtype=np.float32)
  212. )
  213. np.testing.assert_almost_equal(
  214. net.b.numpy(), np.array([2.0 - 0.0], dtype=np.float32)
  215. )
  216. def test_zero_grad():
  217. class StopGradient(Function):
  218. def forward(self, a):
  219. return a
  220. def backward(self, *_):
  221. return None
  222. class Simple(Module):
  223. def __init__(self, a):
  224. super().__init__()
  225. self.a = Parameter(a, dtype=np.float32)
  226. self.layer = StopGradient()
  227. def forward(self):
  228. b = self.a * 3.0
  229. c = self.a * 4.0
  230. return self.layer(b) + c
  231. a = tensor(np.array([1.0], dtype=np.float32))
  232. net = Simple(a)
  233. optim = optimizer.SGD(net.parameters(), lr=1.0)
  234. gm = ad.GradManager().attach(net.parameters())
  235. optim.clear_grad()
  236. with gm:
  237. loss = net()
  238. gm.backward(loss.sum())
  239. optim.step()
  240. np.testing.assert_almost_equal(
  241. net.a.numpy(), np.array([1.0 - 4.0], dtype=np.float32),
  242. )

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