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