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

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