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_stop_gradient.py 12 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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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_stop_gradient """
  16. import numpy as np
  17. import pytest
  18. import mindspore.common.dtype as mstype
  19. import mindspore.nn as nn
  20. from mindspore import Parameter, ParameterTuple
  21. from mindspore import Tensor
  22. from mindspore import context
  23. from mindspore.common.api import ms_function
  24. from mindspore.ops import composite as C
  25. from mindspore.ops import operations as P
  26. from mindspore.ops.functional import stop_gradient
  27. from mindspore.ops.primitive import prim_attr_register, PrimitiveWithInfer
  28. from ..ut_filter import non_graph_engine
  29. from ....mindspore_test_framework.utils.bprop_util import bprop
  30. def setup_module(module):
  31. context.set_context(mode=context.PYNATIVE_MODE)
  32. def stop_func(x, y):
  33. """ stop_func"""
  34. c = x * y
  35. c_s = x + y
  36. return c_s, c
  37. def stop_test1(x, y):
  38. """ stop_test1 """
  39. c = x * y
  40. c_s = stop_gradient(c)
  41. return c_s
  42. def stop_test2(x, y):
  43. """ stop_test2 """
  44. c = x * y
  45. c_s = stop_gradient(c)
  46. d = c_s + x * y
  47. return d * y
  48. def stop_test3(x, y):
  49. """ stop_test3 """
  50. x = x * y
  51. z = stop_test1(x, y)
  52. k = z * y
  53. return k
  54. def stop_test5(x, y):
  55. """ stop_test3 """
  56. x = x + y
  57. o1, o2 = stop_func(x, y)
  58. c = stop_gradient(o1)
  59. c = o2 + c
  60. return c
  61. def stop_test4(x, y):
  62. """ stop_test4 """
  63. c = x + y
  64. c_s = stop_gradient(c)
  65. e = c + c_s
  66. return e
  67. def grad_stop_test(x, y):
  68. """ grad_stop_test """
  69. return C.grad_all(stop_test2)(x, y)
  70. def grad_stop_test1(x, y):
  71. """ grad_stop_test1 """
  72. return C.grad_all(stop_test3)(x, y)
  73. def test_stop():
  74. """ test_stop """
  75. print("test_stop:", grad_stop_test(1, 1))
  76. def test_stop1():
  77. """ test_stop1 """
  78. print("test_stop1:", grad_stop_test1(2, 3))
  79. def test_stop5():
  80. """ test_stop1 """
  81. print("test_stop5:", C.grad_all(stop_test5)(2, 3))
  82. class GradWrap(nn.Cell):
  83. """ GradWrap definition """
  84. def __init__(self, network):
  85. super(GradWrap, self).__init__()
  86. self.network = network
  87. self.weights = ParameterTuple(network.get_parameters())
  88. @ms_function
  89. def construct(self, x, label):
  90. weights = self.weights
  91. return C.grad_by_list(self.network, weights)(x, label)
  92. @non_graph_engine
  93. def test_softmaxloss_grad():
  94. """ test_softmaxloss_grad """
  95. class NetWithLossClass(nn.Cell):
  96. """ NetWithLossClass definition """
  97. def __init__(self, network):
  98. super(NetWithLossClass, self).__init__()
  99. self.loss = nn.SoftmaxCrossEntropyWithLogits()
  100. self.network = network
  101. @ms_function
  102. def construct(self, x, label):
  103. predict = self.network(x)
  104. return self.loss(predict, label)
  105. class Net(nn.Cell):
  106. """ Net definition """
  107. def __init__(self):
  108. super(Net, self).__init__()
  109. self.weight = Parameter(Tensor(np.ones([64, 10])), name="weight")
  110. self.bias = Parameter(Tensor(np.ones([10]).astype(np.float32)), name="bias")
  111. self.fc = P.MatMul()
  112. self.fc2 = nn.Dense(10, 10)
  113. self.biasAdd = P.BiasAdd()
  114. self.relu = nn.ReLU()
  115. self.cast = P.Cast()
  116. @ms_function
  117. def construct(self, x):
  118. x = self.fc(x, self.weight)
  119. x = self.cast(x, mstype.float32)
  120. x = self.relu(self.fc2(x))
  121. x = self.fc2(x)
  122. x = stop_gradient(x)
  123. x = self.biasAdd(x, self.bias)
  124. return x
  125. net = GradWrap(NetWithLossClass(Net()))
  126. predict = Tensor(np.ones([1, 64]))
  127. label = Tensor(np.zeros([1, 10]).astype(np.float32))
  128. print("pynative run")
  129. out = net(predict, label)
  130. print("out:", out)
  131. def test_stop_gradient_1():
  132. class Mul(nn.Cell):
  133. def __init__(self):
  134. super(Mul, self).__init__()
  135. @ms_function
  136. def construct(self, x, y):
  137. ret = x * y
  138. ret = stop_gradient(ret)
  139. return ret
  140. dx, dy = bprop(Mul(), Tensor(np.ones([2, 2]).astype(np.float32)),
  141. Tensor(np.ones([2, 2]).astype(np.float32)), wrt=['inputs'])
  142. expect = np.zeros([2, 2])
  143. assert (dx.asnumpy() == expect).all()
  144. assert (dy.asnumpy() == expect).all()
  145. def test_stop_gradient_2():
  146. class Mul(nn.Cell):
  147. def __init__(self):
  148. super(Mul, self).__init__()
  149. @ms_function
  150. def construct(self, x, y):
  151. c = x * y
  152. z = x * y
  153. return c, z
  154. class MulAdd(nn.Cell):
  155. def __init__(self):
  156. super(MulAdd, self).__init__()
  157. self.mul = Mul()
  158. @ms_function
  159. def construct(self, x, y):
  160. u = x + y
  161. v = x - y
  162. c, z = self.mul(u, v)
  163. c = stop_gradient(c)
  164. ret1 = c + x + y
  165. ret2 = z + y + y
  166. return ret1, ret2
  167. dx = bprop(MulAdd(), Tensor(np.ones([2, 2]).astype(np.float32)),
  168. Tensor(np.ones([2, 2]).astype(np.float32)))
  169. expect = np.array([[3.0, 3.0], [3.0, 3.0]])
  170. assert (dx.asnumpy() == expect).all()
  171. def test_stop_gradient_3():
  172. class TupleGetItem(nn.Cell):
  173. def __init__(self):
  174. super(TupleGetItem, self).__init__()
  175. @ms_function
  176. def construct(self, x1, x2, x3, x4, x5):
  177. z1 = x1 + x1
  178. z2 = x1 * x2
  179. t = (z1, z2, x3, x4, x5)
  180. z2 = t[1]
  181. z2 = stop_gradient(z2)
  182. return z1, z2, x3, x4, x5
  183. dx = bprop(TupleGetItem(),
  184. Tensor(np.ones([2]).astype(np.float32)),
  185. Tensor(np.ones([2]).astype(np.float32)),
  186. Tensor(np.ones([2]).astype(np.float32)),
  187. Tensor(np.ones([2]).astype(np.float32)),
  188. Tensor(np.ones([2]).astype(np.float32)))
  189. expect = np.array([[2.0, 2.0], [2.0, 2.0]])
  190. assert (dx.asnumpy() == expect).all()
  191. def test_stop_gradient_4():
  192. def stop_test(x):
  193. return stop_gradient(x)
  194. assert C.grad_all(stop_test)(1) == (0,)
  195. def test_stop_gradient_5():
  196. def stop_test(x):
  197. y = x + x
  198. y = stop_gradient(y)
  199. ret = x + y
  200. return ret
  201. assert C.grad_all(stop_test)(1) == (1,)
  202. def test_stop_gradient_6():
  203. def stop_test(x, y):
  204. ret = x * y
  205. ret = stop_gradient(ret)
  206. return ret
  207. assert C.grad_all(stop_test)(1, 3) == (0, 0)
  208. class PrimWithMultiOutputs(PrimitiveWithInfer):
  209. @prim_attr_register
  210. def __init__(self):
  211. """init"""
  212. def __call__(self, x, y):
  213. """Implement by vm mode."""
  214. return x, y
  215. def infer_shape(self, x_shape, y_shape):
  216. return x_shape, y_shape
  217. def infer_dtype(self, x_type, y_type):
  218. return x_type, y_type
  219. def get_bprop(self):
  220. def bprop(x, y, out, dout):
  221. return (dout[0], dout[1])
  222. return bprop
  223. def test_stop_gradient_7():
  224. class PrimWithMultiOutputs_(nn.Cell):
  225. def __init__(self):
  226. super(PrimWithMultiOutputs_, self).__init__()
  227. self.prim_with_multi_outputs = PrimWithMultiOutputs()
  228. @ms_function
  229. def construct(self, x1, x2):
  230. x1, x2 = self.prim_with_multi_outputs(x1, x2)
  231. x1 = stop_gradient(x1)
  232. return x1, x2
  233. dx, dy = bprop(PrimWithMultiOutputs_(), Tensor(np.ones([2]).astype(np.float32)),
  234. Tensor(np.ones([2]).astype(np.float32)), wrt=['inputs'])
  235. expect_dx = np.zeros([2])
  236. expect_dy = np.ones([2])
  237. assert (dx.asnumpy() == expect_dx).all()
  238. assert (dy.asnumpy() == expect_dy).all()
  239. def test_stop_gradient_8():
  240. class PrimWithMultiOutputs_(nn.Cell):
  241. def __init__(self):
  242. super(PrimWithMultiOutputs_, self).__init__()
  243. self.prim_with_multi_output = PrimWithMultiOutputs()
  244. @ms_function
  245. def construct(self, x1, x2):
  246. x1, x2 = stop_gradient(self.prim_with_multi_output(x1, x2))
  247. return x1, x2
  248. dx, dy = bprop(PrimWithMultiOutputs_(), Tensor(np.ones([2]).astype(np.float32)),
  249. Tensor(np.ones([2]).astype(np.float32)), wrt=['inputs'])
  250. expect_dx = np.zeros([2])
  251. expect_dy = np.zeros([2])
  252. assert (dx.asnumpy() == expect_dx).all()
  253. assert (dy.asnumpy() == expect_dy).all()
  254. def test_stop_gradient_9():
  255. class Mul(nn.Cell):
  256. def __init__(self):
  257. super(Mul, self).__init__()
  258. @ms_function
  259. def construct(self, x, y):
  260. c = x * y
  261. z = x * y
  262. return c, z
  263. class MulAdd(nn.Cell):
  264. def __init__(self):
  265. super(MulAdd, self).__init__()
  266. self.mul = Mul()
  267. @ms_function
  268. def construct(self, x, y):
  269. u = x + y
  270. v = x - y
  271. c, z = self.mul(u, v)
  272. c1 = stop_gradient(c)
  273. c2 = c
  274. ret1 = c1 + x + y + c2
  275. ret2 = z + y + y
  276. return ret1, ret2
  277. dx = bprop(MulAdd(), Tensor(np.ones([2, 2]).astype(np.float32)),
  278. Tensor(np.ones([2, 2]).astype(np.float32)))
  279. expect = np.array([[5.0, 5.0], [5.0, 5.0]])
  280. assert (dx.asnumpy() == expect).all()
  281. class PrimWithNoBprop(PrimitiveWithInfer):
  282. @prim_attr_register
  283. def __init__(self):
  284. """init"""
  285. def __call__(self, x, y):
  286. """Implement by vm mode."""
  287. return x, y
  288. def infer_shape(self, x_shape, y_shape):
  289. return x_shape, y_shape
  290. def infer_dtype(self, x_type, y_type):
  291. return x_type, y_type
  292. def test_stop_gradient_10():
  293. class PrimWithNoBprop_(nn.Cell):
  294. def __init__(self):
  295. super(PrimWithNoBprop_, self).__init__()
  296. self.prim_with_no_bprop = PrimWithNoBprop()
  297. @ms_function
  298. def construct(self, x, y):
  299. x = x * y
  300. x, y = self.prim_with_no_bprop(x, y)
  301. x = stop_gradient(x)
  302. y = stop_gradient(y)
  303. return x, y
  304. dx = bprop(PrimWithNoBprop_(), Tensor(np.ones([2]).astype(np.float32)),
  305. Tensor(np.ones([2]).astype(np.float32)))
  306. expect_dx = np.zeros([2])
  307. assert (dx.asnumpy() == expect_dx).all()
  308. def test_stop_gradient_11():
  309. class PrimWithNoBprop_(nn.Cell):
  310. def __init__(self):
  311. super(PrimWithNoBprop_, self).__init__()
  312. self.prim_with_no_bprop = PrimWithNoBprop()
  313. @ms_function
  314. def construct(self, x, y):
  315. x, y = self.prim_with_no_bprop(x, y)
  316. x = stop_gradient(x)
  317. return x, y
  318. with pytest.raises(RuntimeError):
  319. bprop(PrimWithNoBprop_(), Tensor(np.ones([2]).astype(np.float32)),
  320. Tensor(np.ones([2]).astype(np.float32)))
  321. def test_stop_print():
  322. class StopPrint(nn.Cell):
  323. def __init__(self):
  324. super(StopPrint, self).__init__()
  325. self.printm = P.Print()
  326. def construct(self, x, y):
  327. self.printm("StopPrint", x)
  328. self.printm(y)
  329. return x, y
  330. C.grad_all(StopPrint())(Tensor(np.ones([2]).astype(np.float32)),
  331. Tensor(np.ones([2]).astype(np.float32)))