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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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 mindspore.nn as nn
  18. from mindspore.ops import composite as C
  19. from mindspore.ops import operations as P
  20. from mindspore import Parameter
  21. from mindspore.common.tensor import Tensor
  22. import mindspore.common.dtype as mstype
  23. from mindspore.common.initializer import initializer
  24. from mindspore import context
  25. from ....mindspore_test_framework.utils.bprop_util import bprop
  26. import pytest
  27. def setup_module(module):
  28. context.set_context(mode=context.PYNATIVE_MODE)
  29. class MulAdd(nn.Cell):
  30. def __init__(self):
  31. super(MulAdd, self).__init__()
  32. def construct(self, x, y):
  33. return 2 * x + y
  34. def bprop(self, x, y, out, dout):
  35. # In this test case, The user defined bprop is wrong defined purposely to distinguish from ad result
  36. return 2 * dout, 2 * y
  37. def test_grad_mul_add():
  38. mul_add = MulAdd()
  39. assert C.grad_all(mul_add)(1, 2) == (2, 4)
  40. class InlineMulADD(nn.Cell):
  41. def __init__(self):
  42. super(InlineMulADD, self).__init__()
  43. self.mul_add = MulAdd()
  44. self.param = Parameter(2, 'param')
  45. def construct(self, x, y):
  46. return self.mul_add(x, y) + x + self.param * y
  47. def test_grad_inline_mul_add():
  48. inline_mul_add = InlineMulADD()
  49. assert C.grad_all(inline_mul_add)(1, 2) == (3, 6)
  50. class WithParameter(nn.Cell):
  51. def __init__(self):
  52. super(WithParameter, self).__init__()
  53. self.param = Parameter(2, 'param')
  54. def construct(self, x, y):
  55. return self.param * x + y
  56. def bprop(self, x, y, out, dout):
  57. # In this test case, The user defined bprop is wrong defined purposely to distinguish from ad result
  58. return self.param * dout, 2 * y
  59. def test_with_param():
  60. with_param = WithParameter()
  61. with pytest.raises(RuntimeError):
  62. C.grad_all(with_param)(1, 2)
  63. class WithNoBprop(nn.Cell):
  64. def __init__(self):
  65. super(WithNoBprop, self).__init__()
  66. def construct(self, x, y):
  67. return 2 * x + y
  68. def test_with_no_bprop():
  69. with_no_bprop = WithNoBprop()
  70. C.grad_all(with_no_bprop)(1, 2) == (2, 1)
  71. def test_grad_in_bprop_1():
  72. class GradInBprop_1(nn.Cell):
  73. def __init__(self):
  74. super(GradInBprop_1, self).__init__()
  75. self.relu = P.ReLU()
  76. def construct(self, x, y):
  77. return self.relu(x)
  78. class GradInBprop_2(nn.Cell):
  79. def __init__(self):
  80. super(GradInBprop_2, self).__init__()
  81. self.f = GradInBprop_1()
  82. def construct(self, x, y):
  83. return self.f(x, y), C.grad_all(self.f)(x, y)
  84. def bprop(self, x, y, out, dout):
  85. grads = C.grad_all(self.f)(x, y)
  86. return out[1][0], grads[1]
  87. class GradInBprop_3(nn.Cell):
  88. def __init__(self):
  89. super(GradInBprop_3, self).__init__()
  90. self.f = GradInBprop_2()
  91. def construct(self, x, y):
  92. return self.f(x, y)
  93. grad_in_bprop = GradInBprop_3()
  94. grads = C.grad_all(grad_in_bprop)(Tensor(np.ones([2, 2]).astype(np.float32)),
  95. Tensor(np.ones([2, 2]).astype(np.float32)))
  96. assert (grads[0].asnumpy() == np.ones([2, 2]).astype(np.float32)).all()
  97. assert (grads[1].asnumpy() == np.zeros([2, 2]).astype(np.float32)).all()
  98. def test_grad_in_bprop_2():
  99. class GradInBprop_1(nn.Cell):
  100. def __init__(self):
  101. super(GradInBprop_1, self).__init__()
  102. self.relu = P.ReLU()
  103. def construct(self, x, y):
  104. return self.relu(x)
  105. def bprop(self, x, y, out, dout):
  106. return x * y, y + x
  107. class GradInBprop_2(nn.Cell):
  108. def __init__(self):
  109. super(GradInBprop_2, self).__init__()
  110. self.f = GradInBprop_1()
  111. def construct(self, x, y):
  112. return self.f(x, y), C.grad_all(self.f)(x, y)
  113. def bprop(self, x, y, out, dout):
  114. grads = C.grad_all(self.f)(x, y)
  115. return out[1][0], grads[1]
  116. class GradInBprop_3(nn.Cell):
  117. def __init__(self):
  118. super(GradInBprop_3, self).__init__()
  119. self.f = GradInBprop_2()
  120. def construct(self, x, y):
  121. return self.f(x, y)
  122. grad_in_bprop = GradInBprop_3()
  123. grads = C.grad_all(grad_in_bprop)(Tensor(np.ones([2, 2]).astype(np.float32)),
  124. Tensor(np.ones([2, 2]).astype(np.float32)))
  125. assert (grads[0].asnumpy() == np.ones([2, 2]).astype(np.float32)).all()
  126. assert (grads[1].asnumpy() == np.array([[2, 2], [2, 2]]).astype(np.float32)).all()
  127. def test_grad_in_bprop_3():
  128. class GradInBprop_1(nn.Cell):
  129. def __init__(self):
  130. super(GradInBprop_1, self).__init__()
  131. self.relu = P.ReLU()
  132. def construct(self, x, y):
  133. return self.relu(x)
  134. class GradInBprop_2(nn.Cell):
  135. def __init__(self):
  136. super(GradInBprop_2, self).__init__()
  137. self.f = GradInBprop_1()
  138. def construct(self, x, y):
  139. return self.f(x, y), C.grad_all(self.f)(x, y)
  140. def bprop(self, x, y, out, dout):
  141. grads = C.grad_all(self.f)(x, y)
  142. return out[1][0], grads[1]
  143. class GradInBprop_3(nn.Cell):
  144. def __init__(self):
  145. super(GradInBprop_3, self).__init__()
  146. self.f = GradInBprop_2()
  147. def construct(self, x, y):
  148. return self.f(x, y)
  149. def bprop(self, x, y, out, dout):
  150. return x + y + y + out[0], x + x + y + y + dout[0]
  151. grad_in_bprop = GradInBprop_3()
  152. grads = C.grad_all(grad_in_bprop)(Tensor(np.ones([2, 2]).astype(np.float32)),
  153. Tensor(np.ones([2, 2]).astype(np.float32)))
  154. assert (grads[0].asnumpy() == np.array([[4, 4], [4, 4]]).astype(np.float32)).all()
  155. assert (grads[1].asnumpy() == np.array([[5, 5], [5, 5]]).astype(np.float32)).all()
  156. class OneInputBprop(nn.Cell):
  157. def __init__(self):
  158. super().__init__()
  159. self.op = P.ReLU()
  160. def construct(self, x):
  161. return self.op(x)
  162. def bprop(self, x, out, dout):
  163. return 5 * x,
  164. def test_grad_one_input_bprop():
  165. net = OneInputBprop()
  166. input = Tensor(np.ones([2, 2]).astype(np.float32))
  167. grad = C.grad_all(net)(input)
  168. assert (grad[0].asnumpy() == np.array([5, 5]).astype(np.float32)).all()
  169. class TwoInput(nn.Cell):
  170. def __init__(self):
  171. super().__init__()
  172. def construct(self, x, y):
  173. return x * y
  174. class InlineBpropTwoInput(nn.Cell):
  175. def __init__(self):
  176. super().__init__()
  177. self.f = TwoInput()
  178. def construct(self, x, y):
  179. return self.f(x, y), C.grad_all(self.f)(x, y)
  180. def bprop(self, x, y, out, dout):
  181. grads = C.grad_all(self.f)(x, y)
  182. return grads[0] * 2, grads[1] * 2
  183. def test_grad_inline_bprop_two_input():
  184. net = InlineBpropTwoInput()
  185. input1 = Tensor(np.ones([2, 2]).astype(np.float32))
  186. input2 = Tensor(np.ones([2, 2]).astype(np.float32))
  187. grads = C.grad_all(net)(input1, input2)
  188. assert (grads[0].asnumpy() == np.array([2, 2]).astype(np.float32)).all()
  189. assert (grads[1].asnumpy() == np.array([2, 2]).astype(np.float32)).all()
  190. assert (len(grads) == 2)
  191. class TwoInputBprop(nn.Cell):
  192. def __init__(self):
  193. super().__init__()
  194. self.op = P.Mul()
  195. def construct(self, x, y):
  196. return self.op(x, y)
  197. def bprop(self, x, y, out, dout):
  198. return 5 * x, 8 * y
  199. class TwoInput(nn.Cell):
  200. def __init__(self):
  201. super().__init__()
  202. self.op = P.Mul()
  203. def construct(self, x, y):
  204. return self.op(x, y)
  205. class TwoInputWithParameter(nn.Cell):
  206. def __init__(self):
  207. super().__init__()
  208. self.op = P.Mul()
  209. self.inputdata = Parameter(initializer(1, (2,2), mstype.float32),name="global_step")
  210. def construct(self, x, y):
  211. x = self.inputdata + x
  212. return self.op(x, y)
  213. class TwoInputWithOnlyInitParameterBprop(nn.Cell):
  214. def __init__(self):
  215. super().__init__()
  216. self.op = P.Mul()
  217. self.inputdata = Parameter(initializer(1, (2,2), mstype.float32),name="global_step")
  218. def construct(self, x, y):
  219. return self.op(x, y)
  220. def bprop(self, x, y, out, dout):
  221. return 5*x, 8*y
  222. class InlineMutilTwoInputParameterCell(nn.Cell):
  223. def __init__(self):
  224. super().__init__()
  225. self.f1 = TwoInputBprop()
  226. self.f2 = TwoInput()
  227. self.f3 = TwoInputWithParameter()
  228. self.f4 = TwoInputWithOnlyInitParameterBprop()
  229. def construct(self, x, y):
  230. output = self.f1(x,y)+self.f2(x,y)+self.f3(x,y)+self.f4(x,y)
  231. return output
  232. def test_grad_inline_bprop_multi_input():
  233. net = InlineMutilTwoInputParameterCell()
  234. input1 = Tensor(np.ones([2, 2]).astype(np.float32))
  235. input2 = Tensor(np.ones([2, 2]).astype(np.float32))
  236. grads = C.grad_all(net)(input1, input2)
  237. assert (grads[0].asnumpy() == np.array([[12, 12], [12, 12]]).astype(np.float32)).all()
  238. assert (grads[1].asnumpy() == np.array([[19, 19], [19, 19]]).astype(np.float32)).all()
  239. assert (len(grads) == 2)
  240. class MulAddWithParam(nn.Cell):
  241. def __init__(self):
  242. super(MulAddWithParam, self).__init__()
  243. self.mul_add = MulAdd()
  244. self.param = Parameter(Tensor(np.array([[3, 2]], np.float32)), 'param')
  245. def construct(self, x):
  246. return self.mul_add(self.param, x)
  247. def test_refkey_bprop():
  248. net = MulAddWithParam()
  249. input_data = Tensor(np.array([2, 2], np.float32))
  250. grads = bprop(net, input_data,
  251. grads_wrt_outputs=(Tensor(np.ones([1, 2]).astype(np.float32))),
  252. wrt=['params', 'inputs'],
  253. params=net.trainable_params())
  254. assert (grads[0][0].asnumpy() == np.array([4, 4]).astype(np.float32)).all()
  255. assert (grads[1][0].asnumpy() == np.array([2, 2]).astype(np.float32)).all()
  256. class MulAddWithWrongOutputNum(nn.Cell):
  257. def __init__(self):
  258. super(MulAddWithWrongOutputNum, self).__init__()
  259. def construct(self, x, y):
  260. return 2 * x + y
  261. def bprop(self, x, y, out, dout):
  262. return 2 * dout, 2 * y, out
  263. def test_grad_mul_add_with_wrong_output_num():
  264. mul_add = MulAddWithWrongOutputNum()
  265. C.grad_all(mul_add)(1, 2)