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

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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. @ms_function
  73. def grad_fx_cast(input_x):
  74. return C.grad(fx_cast)(input_x)
  75. gfn = grad_fx_cast(input_x)
  76. expect_dx = 1
  77. assert gfn == expect_dx
  78. @non_graph_engine
  79. def test_reshape_grad():
  80. """ test_reshape_grad """
  81. input_tensor = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]))
  82. shp = (3, 2)
  83. reshape = P.Reshape()
  84. def fn(x):
  85. output = reshape(x, shp)
  86. return output
  87. out = fn(input_tensor)
  88. gfn = grad_all_with_sens(fn)
  89. sens = Tensor(np.ones_like(out.asnumpy()))
  90. args = [input_tensor, sens]
  91. gout = gfn(*args)
  92. expect = np.ones([2, 3])
  93. assert np.all(gout[0].asnumpy() == expect)
  94. def test_transpose_grad():
  95. """ test_transpose_grad """
  96. input_tensor = Tensor(np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]))
  97. perm = (0, 2, 1)
  98. transpose = P.Transpose()
  99. def fn(x):
  100. output = transpose(x, perm)
  101. return output
  102. out = fn(input_tensor)
  103. gfn = grad_all_with_sens(fn)
  104. sens = Tensor(np.ones_like(out.asnumpy()))
  105. args = [input_tensor, sens]
  106. gout = gfn(*args)
  107. expect = np.ones([2, 2, 3])
  108. assert np.all(gout[0].asnumpy() == expect)
  109. def test_select_grad():
  110. """ test_select_grad """
  111. select = P.Select()
  112. cond = Tensor(np.array([[True, False, False], [False, True, True]]))
  113. x = Tensor(np.array([[1, 2, 3], [4, 5, 6]]).astype(np.float32))
  114. y = Tensor(np.array([[7, 8, 9], [10, 11, 12]]).astype(np.float32))
  115. def fn(cond, x, y):
  116. output = select(cond, x, y)
  117. return output
  118. out = fn(cond, x, y)
  119. gfn = grad_all_with_sens(fn)
  120. sens = Tensor(np.ones_like(out.asnumpy()).astype(np.float32))
  121. args = [cond, x, y, sens]
  122. gout = gfn(*args)
  123. expect_cond = np.zeros_like(cond.asnumpy())
  124. expect_x = np.array([[1, 0, 0], [0, 1, 1]])
  125. expect_y = np.array([[0, 1, 1], [1, 0, 0]])
  126. assert np.all(gout[0].asnumpy() == expect_cond)
  127. assert np.all(gout[1].asnumpy() == expect_x)
  128. assert np.all(gout[2].asnumpy() == expect_y)
  129. @non_graph_engine
  130. def test_squeeze_grad():
  131. """ test_squeeze_grad """
  132. input_tensor = Tensor(np.ones(shape=[3, 2, 1]))
  133. squeeze = P.Squeeze(2)
  134. def fn(x):
  135. output = squeeze(x)
  136. return output
  137. out = fn(input_tensor)
  138. gfn = grad_all_with_sens(fn)
  139. sens = Tensor(np.ones_like(out.asnumpy()))
  140. args = [input_tensor, sens]
  141. gout = gfn(*args)
  142. expect = np.ones([3, 2, 1])
  143. assert np.all(gout[0].asnumpy() == expect)
  144. def test_SubGrad():
  145. """ test_SubGrad """
  146. input_x = Tensor(np.array([[2, 2]]))
  147. input_y = Tensor(np.array([[2, 2], [2, 2]]))
  148. sub = P.Sub()
  149. def fn(x, y):
  150. output = sub(x, y)
  151. return output
  152. out = fn(input_x, input_y)
  153. gfn = grad_all_with_sens(fn)
  154. sens = Tensor(np.ones_like(out.asnumpy()))
  155. args = [input_x, input_y, sens]
  156. gout = gfn(*args)
  157. expect_dx = np.ones([1, 2]).astype(np.int32) * 2 # reduce sum dout to the shape of x
  158. expect_dy = np.ones([2, 2]).astype(np.int32) * (-1)
  159. assert np.array_equal(gout[0].asnumpy(), expect_dx)
  160. assert np.array_equal(gout[1].asnumpy(), expect_dy)
  161. def test_MulGrad():
  162. """ test_MulGrad """
  163. input_x = Tensor(np.array([[2, 2], [2, 2]], np.float32))
  164. input_y = Tensor(np.array([[3, 3], [3, 3]], np.float32))
  165. mymul = P.Mul()
  166. def fn(x, y):
  167. output = mymul(x, y)
  168. return output
  169. out = fn(input_x, input_y)
  170. gfn = grad_all_with_sens(fn)
  171. sens = Tensor(np.ones_like(out.asnumpy()) * 3)
  172. args = [input_x, input_y, sens]
  173. gout = gfn(*args)
  174. expect_dx = np.ones([2, 2], np.float32) * 9
  175. expect_dy = np.ones([2, 2], np.float32) * 6
  176. assert np.all(gout[0].asnumpy().shape == expect_dx.shape)
  177. assert np.all(gout[0].asnumpy() == expect_dx)
  178. assert np.all(gout[1].asnumpy().shape == expect_dy.shape)
  179. assert np.all(gout[1].asnumpy() == expect_dy)