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.5 kB

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