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.py 6.4 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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_grad """
  16. import numpy as np
  17. import mindspore as ms
  18. import mindspore.ops.operations as P
  19. from mindspore import Tensor, context
  20. from mindspore.common.api import ms_function
  21. from mindspore.ops import composite as C
  22. from mindspore.ops import functional as F
  23. from ...ut_filter import non_graph_engine
  24. # pylint: disable=unused-argument
  25. def setup_module(module):
  26. context.set_context(mode=context.PYNATIVE_MODE)
  27. grad = C.GradOperation()
  28. grad_all_with_sens = C.GradOperation(get_all=True, sens_param=True)
  29. def mul(x, y):
  30. return x * y
  31. @ms_function
  32. def mainf(x, y):
  33. return grad(mul)(x, y)
  34. @non_graph_engine
  35. def test_grad():
  36. mainf(1, 2)
  37. @non_graph_engine
  38. def Xtest_expand_dims_grad():
  39. """ test_expand_dims_grad """
  40. input_tensor = Tensor(np.array([[2, 2], [2, 2]]))
  41. expand_dims = P.ExpandDims()
  42. def fn(x):
  43. output = expand_dims(x, 0)
  44. return output
  45. out = fn(input_tensor)
  46. gfn = grad_all_with_sens(fn)
  47. sens = Tensor(np.ones_like(out.asnumpy()))
  48. args = [input_tensor, sens]
  49. gout = gfn(*args)
  50. expect = np.ones([2, 2])
  51. assert np.all(gout[0].asnumpy() == expect)
  52. def test_cast_grad():
  53. """ test_cast_grad """
  54. input_np = np.random.randn(2, 3).astype(np.float32)
  55. input_x = Tensor(input_np)
  56. td = ms.int32
  57. cast = P.Cast()
  58. def fn(x):
  59. output = cast(x, td)
  60. return output
  61. out = fn(input_x)
  62. gfn = grad_all_with_sens(fn)
  63. sens = Tensor(np.ones_like(out.asnumpy()))
  64. args = [input_x, sens]
  65. gout = gfn(*args)
  66. expect = np.ones((2, 3), dtype=np.float32)
  67. assert np.all(gout[0].asnumpy() == expect)
  68. def test_scalar_cast_grad():
  69. """ test_scalar_cast_grad """
  70. input_x = 255.5
  71. input_t = ms.int8
  72. def fx_cast(x):
  73. output = F.scalar_cast(x, input_t)
  74. return output
  75. @ms_function
  76. def grad_fx_cast(input_x):
  77. return grad(fx_cast)(input_x)
  78. gfn = grad_fx_cast(input_x)
  79. expect_dx = 1
  80. assert gfn == expect_dx
  81. @non_graph_engine
  82. def test_reshape_grad():
  83. """ test_reshape_grad """
  84. input_tensor = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]))
  85. shp = (3, 2)
  86. reshape = P.Reshape()
  87. def fn(x):
  88. output = reshape(x, shp)
  89. return output
  90. out = fn(input_tensor)
  91. gfn = grad_all_with_sens(fn)
  92. sens = Tensor(np.ones_like(out.asnumpy()))
  93. args = [input_tensor, sens]
  94. gout = gfn(*args)
  95. expect = np.ones([2, 3])
  96. assert np.all(gout[0].asnumpy() == expect)
  97. def test_transpose_grad():
  98. """ test_transpose_grad """
  99. input_tensor = Tensor(np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]))
  100. perm = (0, 2, 1)
  101. transpose = P.Transpose()
  102. def fn(x):
  103. output = transpose(x, perm)
  104. return output
  105. out = fn(input_tensor)
  106. gfn = grad_all_with_sens(fn)
  107. sens = Tensor(np.ones_like(out.asnumpy()))
  108. args = [input_tensor, sens]
  109. gout = gfn(*args)
  110. expect = np.ones([2, 2, 3])
  111. assert np.all(gout[0].asnumpy() == expect)
  112. def test_select_grad():
  113. """ test_select_grad """
  114. select = P.Select()
  115. cond = Tensor(np.array([[True, False, False], [False, True, True]]))
  116. x = Tensor(np.array([[1, 2, 3], [4, 5, 6]]).astype(np.float32))
  117. y = Tensor(np.array([[7, 8, 9], [10, 11, 12]]).astype(np.float32))
  118. def fn(cond, x, y):
  119. output = select(cond, x, y)
  120. return output
  121. out = fn(cond, x, y)
  122. gfn = grad_all_with_sens(fn)
  123. sens = Tensor(np.ones_like(out.asnumpy()).astype(np.float32))
  124. args = [cond, x, y, sens]
  125. gout = gfn(*args)
  126. expect_cond = np.zeros_like(cond.asnumpy())
  127. expect_x = np.array([[1, 0, 0], [0, 1, 1]])
  128. expect_y = np.array([[0, 1, 1], [1, 0, 0]])
  129. assert np.all(gout[0].asnumpy() == expect_cond)
  130. assert np.all(gout[1].asnumpy() == expect_x)
  131. assert np.all(gout[2].asnumpy() == expect_y)
  132. @non_graph_engine
  133. def test_squeeze_grad():
  134. """ test_squeeze_grad """
  135. input_tensor = Tensor(np.ones(shape=[3, 2, 1]))
  136. squeeze = P.Squeeze(2)
  137. def fn(x):
  138. output = squeeze(x)
  139. return output
  140. out = fn(input_tensor)
  141. gfn = grad_all_with_sens(fn)
  142. sens = Tensor(np.ones_like(out.asnumpy()))
  143. args = [input_tensor, sens]
  144. gout = gfn(*args)
  145. expect = np.ones([3, 2, 1])
  146. assert np.all(gout[0].asnumpy() == expect)
  147. def test_SubGrad():
  148. """ test_SubGrad """
  149. input_x = Tensor(np.array([[2, 2]]))
  150. input_y = Tensor(np.array([[2, 2], [2, 2]]))
  151. sub = P.Sub()
  152. def fn(x, y):
  153. output = sub(x, y)
  154. return output
  155. out = fn(input_x, input_y)
  156. gfn = grad_all_with_sens(fn)
  157. sens = Tensor(np.ones_like(out.asnumpy()))
  158. args = [input_x, input_y, sens]
  159. gout = gfn(*args)
  160. expect_dx = np.ones([1, 2]).astype(np.int32) * 2 # reduce sum dout to the shape of x
  161. expect_dy = np.ones([2, 2]).astype(np.int32) * (-1)
  162. assert np.array_equal(gout[0].asnumpy(), expect_dx)
  163. assert np.array_equal(gout[1].asnumpy(), expect_dy)
  164. def test_MulGrad():
  165. """ test_MulGrad """
  166. input_x = Tensor(np.array([[2, 2], [2, 2]], np.float32))
  167. input_y = Tensor(np.array([[3, 3], [3, 3]], np.float32))
  168. mymul = P.Mul()
  169. def fn(x, y):
  170. output = mymul(x, y)
  171. return output
  172. out = fn(input_x, input_y)
  173. gfn = grad_all_with_sens(fn)
  174. sens = Tensor(np.ones_like(out.asnumpy()) * 3)
  175. args = [input_x, input_y, sens]
  176. gout = gfn(*args)
  177. expect_dx = np.ones([2, 2], np.float32) * 9
  178. expect_dy = np.ones([2, 2], np.float32) * 6
  179. assert np.all(gout[0].asnumpy().shape == expect_dx.shape)
  180. assert np.all(gout[0].asnumpy() == expect_dx)
  181. assert np.all(gout[1].asnumpy().shape == expect_dy.shape)
  182. assert np.all(gout[1].asnumpy() == expect_dy)