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