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

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