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

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """ test_cell_bprop """
  16. import numpy as np
  17. import pytest
  18. import mindspore as ms
  19. import mindspore.common.dtype as mstype
  20. import mindspore.nn as nn
  21. from mindspore import Parameter, ParameterTuple
  22. from mindspore import context
  23. from mindspore.common.initializer import initializer
  24. from mindspore.common.tensor import Tensor
  25. from mindspore.ops import composite as C
  26. from mindspore.ops import operations as P
  27. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  28. grad_all = C.GradOperation(get_all=True)
  29. class MulAdd(nn.Cell):
  30. def construct(self, x, y):
  31. return 2 * x + y
  32. def bprop(self, x, y, out, dout):
  33. # In this test case, The user defined bprop is wrong defined purposely to distinguish from ad result
  34. return 2 * dout, 2 * y
  35. @pytest.mark.level0
  36. @pytest.mark.platform_x86_ascend_training
  37. @pytest.mark.env_onecard
  38. def test_grad_mul_add():
  39. mul_add = MulAdd()
  40. x = Tensor(1, dtype=ms.int32)
  41. y = Tensor(2, dtype=ms.int32)
  42. assert grad_all(mul_add)(x, y) == (2, 4)
  43. class InlineMulADD(nn.Cell):
  44. def __init__(self):
  45. super(InlineMulADD, self).__init__()
  46. self.mul_add = MulAdd()
  47. self.param = 2
  48. def construct(self, x, y):
  49. return self.mul_add(x, y) + x + self.param * y
  50. @pytest.mark.level0
  51. @pytest.mark.platform_x86_ascend_training
  52. @pytest.mark.env_onecard
  53. def test_grad_inline_mul_add():
  54. inline_mul_add = InlineMulADD()
  55. x = Tensor(1, dtype=ms.int32)
  56. y = Tensor(2, dtype=ms.int32)
  57. assert grad_all(inline_mul_add)(x, y) == (3, 6)
  58. class WithParameter(nn.Cell):
  59. def __init__(self):
  60. super(WithParameter, self).__init__()
  61. self.param1 = Parameter(1, 'param1')
  62. self.param2 = Parameter(2, 'param2')
  63. def construct(self, x, y):
  64. return self.param1 * self.param2 * x + y
  65. def bprop(self, x, y, out, dout):
  66. # In this test case, The user defined bprop is wrong defined purposely to distinguish from ad result
  67. return self.param1 * self.param2 * dout, 2 * y
  68. @pytest.mark.level0
  69. @pytest.mark.platform_x86_ascend_training
  70. @pytest.mark.env_onecard
  71. def test_with_param():
  72. with_param = WithParameter()
  73. with pytest.raises(RuntimeError):
  74. grad_all(with_param)(1, 2)
  75. class WithNoBprop(nn.Cell):
  76. def construct(self, x, y):
  77. return 2 * x + y
  78. @pytest.mark.level0
  79. @pytest.mark.platform_x86_ascend_training
  80. @pytest.mark.env_onecard
  81. def test_with_no_bprop():
  82. with_no_bprop = WithNoBprop()
  83. x = Tensor(1, dtype=ms.int32)
  84. y = Tensor(2, dtype=ms.int32)
  85. assert grad_all(with_no_bprop)(x, y) == (2, 1)
  86. @pytest.mark.level0
  87. @pytest.mark.platform_x86_ascend_training
  88. @pytest.mark.env_onecard
  89. def test_grad_in_bprop_1():
  90. class GradInBprop_1(nn.Cell):
  91. def __init__(self):
  92. super(GradInBprop_1, self).__init__()
  93. self.relu = P.ReLU()
  94. def construct(self, x, y):
  95. return self.relu(x)
  96. class GradInBprop_2(nn.Cell):
  97. def __init__(self):
  98. super(GradInBprop_2, self).__init__()
  99. self.f = GradInBprop_1()
  100. def construct(self, x, y):
  101. return self.f(x, y), grad_all(self.f)(x, y)
  102. def bprop(self, x, y, out, dout):
  103. grads = grad_all(self.f)(x, y)
  104. return out[1][0], grads[1]
  105. class GradInBprop_3(nn.Cell):
  106. def __init__(self):
  107. super(GradInBprop_3, self).__init__()
  108. self.f = GradInBprop_2()
  109. def construct(self, x, y):
  110. return self.f(x, y)
  111. grad_in_bprop = GradInBprop_3()
  112. grads = grad_all(grad_in_bprop)(Tensor(np.ones([2, 2]).astype(np.float32)),
  113. Tensor(np.ones([2, 2]).astype(np.float32)))
  114. assert (grads[0].asnumpy() == np.ones([2, 2]).astype(np.float32)).all()
  115. assert (grads[1].asnumpy() == np.zeros([2, 2]).astype(np.float32)).all()
  116. @pytest.mark.level0
  117. @pytest.mark.platform_x86_ascend_training
  118. @pytest.mark.env_onecard
  119. def test_grad_in_bprop_2():
  120. class GradInBprop_1(nn.Cell):
  121. def __init__(self):
  122. super(GradInBprop_1, self).__init__()
  123. self.relu = P.ReLU()
  124. def construct(self, x, y):
  125. return self.relu(x)
  126. def bprop(self, x, y, out, dout):
  127. return x * y, y + x
  128. class GradInBprop_2(nn.Cell):
  129. def __init__(self):
  130. super(GradInBprop_2, self).__init__()
  131. self.f = GradInBprop_1()
  132. def construct(self, x, y):
  133. return self.f(x, y), grad_all(self.f)(x, y)
  134. def bprop(self, x, y, out, dout):
  135. grads = grad_all(self.f)(x, y)
  136. return out[1][0], grads[1]
  137. class GradInBprop_3(nn.Cell):
  138. def __init__(self):
  139. super(GradInBprop_3, self).__init__()
  140. self.f = GradInBprop_2()
  141. def construct(self, x, y):
  142. return self.f(x, y)
  143. grad_in_bprop = GradInBprop_3()
  144. grads = grad_all(grad_in_bprop)(Tensor(np.ones([2, 2]).astype(np.float32)),
  145. Tensor(np.ones([2, 2]).astype(np.float32)))
  146. assert (grads[0].asnumpy() == np.ones([2, 2]).astype(np.float32)).all()
  147. assert (grads[1].asnumpy() == np.array([[2, 2], [2, 2]]).astype(np.float32)).all()
  148. @pytest.mark.level0
  149. @pytest.mark.platform_x86_ascend_training
  150. @pytest.mark.env_onecard
  151. def test_grad_in_bprop_3():
  152. class GradInBprop_1(nn.Cell):
  153. def __init__(self):
  154. super(GradInBprop_1, self).__init__()
  155. self.relu = P.ReLU()
  156. def construct(self, x, y):
  157. return self.relu(x)
  158. class GradInBprop_2(nn.Cell):
  159. def __init__(self):
  160. super(GradInBprop_2, self).__init__()
  161. self.f = GradInBprop_1()
  162. def construct(self, x, y):
  163. return self.f(x, y), grad_all(self.f)(x, y)
  164. def bprop(self, x, y, out, dout):
  165. grads = grad_all(self.f)(x, y)
  166. return out[1][0], grads[1]
  167. class GradInBprop_3(nn.Cell):
  168. def __init__(self):
  169. super(GradInBprop_3, self).__init__()
  170. self.f = GradInBprop_2()
  171. def construct(self, x, y):
  172. return self.f(x, y)
  173. def bprop(self, x, y, out, dout):
  174. return x + y + y + out[0], x + x + y + y + dout[0]
  175. grad_in_bprop = GradInBprop_3()
  176. grads = grad_all(grad_in_bprop)(Tensor(np.ones([2, 2]).astype(np.float32)),
  177. Tensor(np.ones([2, 2]).astype(np.float32)))
  178. assert (grads[0].asnumpy() == np.array([[4, 4], [4, 4]]).astype(np.float32)).all()
  179. assert (grads[1].asnumpy() == np.array([[5, 5], [5, 5]]).astype(np.float32)).all()
  180. class OneInputBprop(nn.Cell):
  181. def __init__(self):
  182. super().__init__()
  183. self.op = P.ReLU()
  184. def construct(self, x):
  185. return self.op(x)
  186. def bprop(self, x, out, dout):
  187. return (5 * x,)
  188. @pytest.mark.level0
  189. @pytest.mark.platform_x86_ascend_training
  190. @pytest.mark.env_onecard
  191. def test_grad_one_input_bprop():
  192. net = OneInputBprop()
  193. input1 = Tensor(np.ones([2, 2]).astype(np.float32))
  194. grad = grad_all(net)(input1)
  195. assert (grad[0].asnumpy() == np.array([5, 5]).astype(np.float32)).all()
  196. class TwoInput(nn.Cell):
  197. def construct(self, x, y):
  198. return x * y
  199. class InlineBpropTwoInput(nn.Cell):
  200. def __init__(self):
  201. super().__init__()
  202. self.f = TwoInput()
  203. def construct(self, x, y):
  204. return self.f(x, y), grad_all(self.f)(x, y)
  205. def bprop(self, x, y, out, dout):
  206. grads = grad_all(self.f)(x, y)
  207. return grads[0] * 2, grads[1] * 2
  208. @pytest.mark.level0
  209. @pytest.mark.platform_x86_ascend_training
  210. @pytest.mark.env_onecard
  211. def test_grad_inline_bprop_two_input():
  212. net = InlineBpropTwoInput()
  213. input1 = Tensor(np.ones([2, 2]).astype(np.float32))
  214. input2 = Tensor(np.ones([2, 2]).astype(np.float32))
  215. grads = grad_all(net)(input1, input2)
  216. assert (grads[0].asnumpy() == np.array([2, 2]).astype(np.float32)).all()
  217. assert (grads[1].asnumpy() == np.array([2, 2]).astype(np.float32)).all()
  218. assert len(grads) == 2
  219. class TwoInputBprop(nn.Cell):
  220. def __init__(self):
  221. super().__init__()
  222. self.op = P.Mul()
  223. def construct(self, x, y):
  224. return self.op(x, y)
  225. def bprop(self, x, y, out, dout):
  226. return 5 * x, 8 * y
  227. class TwoInputWithParameter(nn.Cell):
  228. def __init__(self):
  229. super().__init__()
  230. self.op = P.Mul()
  231. self.inputdata = Parameter(initializer(1, (2, 2), mstype.float32), name="global_step")
  232. def construct(self, x, y):
  233. x = self.inputdata + x
  234. return self.op(x, y)
  235. class TwoInputWithOnlyInitParameterBprop(nn.Cell):
  236. def __init__(self):
  237. super().__init__()
  238. self.op = P.Mul()
  239. self.inputdata = Parameter(initializer(1, (2, 2), mstype.float32), name="global_step")
  240. def construct(self, x, y):
  241. return self.op(x, y)
  242. def bprop(self, x, y, out, dout):
  243. return 5 * x, 8 * y
  244. class InlineMutilTwoInputParameterCell(nn.Cell):
  245. def __init__(self):
  246. super().__init__()
  247. self.f1 = TwoInputBprop()
  248. self.f2 = TwoInput()
  249. self.f3 = TwoInputWithParameter()
  250. self.f4 = TwoInputWithOnlyInitParameterBprop()
  251. def construct(self, x, y):
  252. output = self.f1(x, y) + self.f2(x, y) + self.f3(x, y) + self.f4(x, y)
  253. return output
  254. @pytest.mark.level0
  255. @pytest.mark.platform_x86_ascend_training
  256. @pytest.mark.env_onecard
  257. def test_grad_inline_bprop_multi_input():
  258. net = InlineMutilTwoInputParameterCell()
  259. input1 = Tensor(np.ones([2, 2]).astype(np.float32))
  260. input2 = Tensor(np.ones([2, 2]).astype(np.float32))
  261. net.init_parameters_data()
  262. grads = grad_all(net)(input1, input2)
  263. assert (grads[0].asnumpy() == np.array([[12, 12], [12, 12]]).astype(np.float32)).all()
  264. assert (grads[1].asnumpy() == np.array([[19, 19], [19, 19]]).astype(np.float32)).all()
  265. assert len(grads) == 2
  266. class MulAddWithParam(nn.Cell):
  267. def __init__(self):
  268. super(MulAddWithParam, self).__init__()
  269. self.mul_add = MulAdd()
  270. self.param = Parameter(Tensor(np.array([[3, 2]], np.float32)), 'param')
  271. def construct(self, x):
  272. return self.mul_add(self.param, x)
  273. @pytest.mark.level0
  274. @pytest.mark.platform_x86_ascend_training
  275. @pytest.mark.env_onecard
  276. def test_refkey_bprop():
  277. grad_by_list = C.GradOperation(get_all=True, get_by_list=True)
  278. class GradWrap(nn.Cell):
  279. def __init__(self, network):
  280. super(GradWrap, self).__init__()
  281. self.network = network
  282. self.weights = ParameterTuple(filter(lambda x: x.requires_grad, network.get_parameters()))
  283. def construct(self, x):
  284. weights = self.weights
  285. grads = grad_by_list(self.network, weights)(x)
  286. return grads
  287. network = GradWrap(MulAddWithParam())
  288. input_data = Tensor(np.array([2, 2], np.float32))
  289. grads = network(input_data)
  290. assert (grads[0][0].asnumpy() == np.array([4, 4]).astype(np.float32)).all()
  291. assert (grads[1][0].asnumpy() == np.array([2, 2]).astype(np.float32)).all()
  292. class MulAddWithWrongOutputNum(nn.Cell):
  293. def construct(self, x, y):
  294. return 2 * x + y
  295. def bprop(self, x, y, out, dout):
  296. return (2 * dout,)
  297. @pytest.mark.level0
  298. @pytest.mark.platform_x86_ascend_training
  299. @pytest.mark.env_onecard
  300. def test_grad_mul_add_with_wrong_output_num():
  301. context.set_context(check_bprop=True)
  302. mul_add = MulAddWithWrongOutputNum()
  303. with pytest.raises(TypeError):
  304. grad_all(mul_add)(1, 2)
  305. class MulAddWithWrongOutputType(nn.Cell):
  306. def construct(self, x, y):
  307. return 2 * x + y
  308. def bprop(self, x, y, out, dout):
  309. return 2 * dout, 2
  310. @pytest.mark.level0
  311. @pytest.mark.platform_x86_ascend_training
  312. @pytest.mark.env_onecard
  313. def test_grad_mul_add_with_wrong_output_type():
  314. context.set_context(check_bprop=True)
  315. mul_add = MulAddWithWrongOutputType()
  316. with pytest.raises(TypeError):
  317. grad_all(mul_add)(1, Tensor(np.ones([2, 2])))
  318. class MulAddWithWrongOutputShape(nn.Cell):
  319. def __init__(self):
  320. super(MulAddWithWrongOutputShape, self).__init__()
  321. self.ones = Tensor(np.ones([2,]))
  322. def construct(self, x, y):
  323. return 2 * x + y
  324. def bprop(self, x, y, out, dout):
  325. return 2, self.ones
  326. @pytest.mark.level0
  327. @pytest.mark.platform_x86_ascend_training
  328. @pytest.mark.env_onecard
  329. def test_grad_mul_add_with_wrong_output_shape():
  330. context.set_context(check_bprop=True)
  331. mul_add = MulAddWithWrongOutputShape()
  332. with pytest.raises(TypeError):
  333. grad_all(mul_add)(1, Tensor(np.ones([2, 2])))