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