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