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