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_framstruct.py 21 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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  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_framstruct """
  16. import numpy as np
  17. import mindspore as ms
  18. import mindspore.nn as nn
  19. from mindspore import context
  20. from mindspore.common import dtype as mstype
  21. from mindspore.common.parameter import Parameter, ParameterTuple
  22. from mindspore.common.api import ms_function
  23. from mindspore.ops import composite as C
  24. from mindspore.ops import operations as P
  25. from ..ut_filter import non_graph_engine
  26. from ....mindspore_test_framework.utils.check_gradient import (
  27. check_jacobian, Tensor, NNGradChecker,
  28. OperationGradChecker, check_gradient)
  29. context.set_context(mode=context.PYNATIVE_MODE)
  30. def setup_module(module):
  31. context.set_context(mode=context.PYNATIVE_MODE)
  32. grad_all = C.GradOperation(get_all=True)
  33. grad_by_list = C.GradOperation(get_by_list=True)
  34. @ms_function
  35. def while_upper_bound(upper):
  36. rval = 2
  37. while rval < upper:
  38. rval = rval * rval
  39. return rval
  40. def test_while_upper_bound():
  41. res = while_upper_bound(10)
  42. assert res == 16
  43. @ms_function
  44. def while_lower_bound(lower):
  45. """ t_while """
  46. rval = lower
  47. while rval < 100:
  48. rval = rval * rval
  49. return rval
  50. def test_while_lower_bound():
  51. res = while_lower_bound(2)
  52. assert res == 256
  53. @ms_function
  54. def dynamic_make_tuple(x, lower, upper):
  55. out = ()
  56. i = lower
  57. while i < upper:
  58. out = out + (x,)
  59. i = i + 1
  60. return out
  61. def test_dynamic_make_tuple():
  62. assert dynamic_make_tuple(2, 1, 5) == (2, 2, 2, 2)
  63. def test_make_tuple():
  64. # Statically recursively creating static type is valid in mindspore.
  65. @ms_function
  66. def make_tuple(x):
  67. out = ()
  68. for i in range(3):
  69. out = out + (x,)
  70. return out
  71. res = make_tuple(5)
  72. assert res == (5, 5, 5)
  73. @ms_function
  74. def add(x, y):
  75. """ add """
  76. return x + y
  77. def mul(x, y):
  78. """ mul """
  79. return x * y
  80. def add_mul(x, y):
  81. """ add_mul """
  82. return (x + y) * y
  83. def mainf(x, y):
  84. """ mainf """
  85. return grad_all(mul)(x, y)
  86. def grad_add_mul(x, y):
  87. """ grad_add_mul """
  88. return grad_all(add_mul)(x, y)
  89. @ms_function
  90. def sub(x, y):
  91. """ sub """
  92. return x - y
  93. # pylint: disable=using-constant-test
  94. @ms_function
  95. def if_always_true(x):
  96. """ if_always_true """
  97. if True:
  98. return x
  99. else:
  100. return 0
  101. def test_add():
  102. """ test_add """
  103. res = add(2.5, 3)
  104. assert res == 5.5
  105. def test_sub():
  106. """ test_sub """
  107. res = sub(3.5, 3)
  108. assert res == 0.5
  109. @non_graph_engine
  110. def test_if_always_true():
  111. """ test_if_always_true """
  112. res = if_always_true(1)
  113. assert res == 1
  114. @non_graph_engine
  115. def test_f():
  116. """ test_f """
  117. res = mainf(Tensor(3, dtype=ms.int32), Tensor(2, dtype=ms.int32))
  118. assert res == (2, 3)
  119. @non_graph_engine
  120. def test_grad_add_mul():
  121. """ test_grad_add_mul """
  122. res = grad_add_mul(Tensor(3, dtype=ms.int32), Tensor(2, dtype=ms.int32))
  123. assert res == (2, 7)
  124. def f(x):
  125. if x > 0:
  126. return f(x - 1)
  127. return x
  128. @ms_function
  129. def list_subscript():
  130. """ list_subscript """
  131. x = [1, 2, 3]
  132. return x[0] * x[1]
  133. def test_list_subscript():
  134. """ test_list_subscript """
  135. res = list_subscript()
  136. assert res == 2
  137. @ms_function
  138. def ms_infer_for(xs, y):
  139. """ ms_infer_for """
  140. rval = y
  141. for x in xs:
  142. rval = rval + x
  143. return rval
  144. def test_infer_for():
  145. """ test_infer_for """
  146. t = (1, 2, 3)
  147. y = 4
  148. res = ms_infer_for(t, y)
  149. assert res == 10
  150. @ms_function
  151. def if_construct(a, b):
  152. z = a
  153. if a > b:
  154. z = a + b
  155. else:
  156. z = a * b
  157. if z > b:
  158. return z - a
  159. else:
  160. return a - b
  161. def test_if_construct():
  162. """ test_if_construct """
  163. res = if_construct(3, 6)
  164. assert res == 15
  165. @ms_function
  166. def if_scalar(a, b):
  167. """ if_abstract """
  168. if a:
  169. return a
  170. return b
  171. def test_if_scalar1():
  172. """ test_if_abstract """
  173. res = if_scalar(3, 6)
  174. assert res == 3
  175. def test_if_scalar2():
  176. """ test_if_abstract """
  177. res = if_scalar(0, 6)
  178. assert res == 6
  179. @ms_function
  180. def if_tensor(a, b):
  181. c = a
  182. if a < b:
  183. c = a + a
  184. if c < b:
  185. c = a + c
  186. else:
  187. c = a + b
  188. else:
  189. c = b + b
  190. out = c + c
  191. return out
  192. def test_if_tensor():
  193. res = if_tensor(Tensor(np.ones([1]).astype(np.int32)), Tensor(np.ones([1]).astype(np.int32)))
  194. assert res == Tensor(np.ones([1]).astype(np.int32) * 4)
  195. def rec(x):
  196. """ rec """
  197. if x > 0:
  198. return rec(x - 1)
  199. return x
  200. def test_me_rec():
  201. """ test_me_rec """
  202. res = rec(10)
  203. assert res == 0
  204. def t2_while(x, y):
  205. out = y - x
  206. i = 0
  207. while i < 10:
  208. out = mul(x, y)
  209. i = i + 1
  210. return out
  211. def test_while2():
  212. res = t2_while(2, 3)
  213. assert res == 6
  214. def if_test(a, b):
  215. """ if_test """
  216. if a > b:
  217. return 3 * a
  218. return 2 * b
  219. def grad_if(x, y):
  220. """ grad_if """
  221. return grad_all(if_test)(x, y)
  222. def test_grad_if():
  223. """ test_grad_if """
  224. assert grad_if(Tensor(5, dtype=ms.int32), Tensor(4, dtype=ms.int32)) == (3, 0)
  225. class ConvNet(nn.Cell):
  226. def __init__(self):
  227. super(ConvNet, self).__init__()
  228. out_channel = 16
  229. kernel_size = 3
  230. self.conv = P.Conv2D(out_channel,
  231. kernel_size,
  232. mode=1,
  233. pad_mode="pad",
  234. pad=0,
  235. stride=1,
  236. dilation=2,
  237. group=1)
  238. self.w = Parameter(Tensor(np.ones([16, 16, 3, 3]).astype(np.float32)), name='w')
  239. def construct(self, x):
  240. return self.conv(x, self.w)
  241. conv = ConvNet()
  242. c1 = Tensor([2], mstype.float32)
  243. c2 = Tensor([10], mstype.float32)
  244. c3 = Tensor([1], mstype.float32)
  245. @ms_function
  246. def t1_while(x, y, z):
  247. out = x
  248. i = c1
  249. while i < c2:
  250. out = out + conv(z)
  251. i = i + c3
  252. out = out + out
  253. return out
  254. def test_while_net():
  255. y = Tensor(np.ones([1, 3, 3, 4]).astype(np.float32))
  256. x = Tensor(np.ones([1, 16, 12, 12]).astype(np.float32))
  257. z = Tensor(np.ones([1, 16, 16, 16]).astype(np.float32))
  258. res = t1_while(x, y, z)
  259. assert np.all(res.asnumpy() == np.ones([1, 16, 12, 12]).astype(np.float32) * 2306.0)
  260. @ms_function
  261. def if_while(a, b, x, z):
  262. c = a
  263. i = c1
  264. out = x
  265. if a < b:
  266. c = a + a
  267. while i < c2:
  268. out = out + conv(z)
  269. i = i + c3
  270. else:
  271. c = b + b
  272. out = c + c
  273. return out
  274. def test_if_while():
  275. x = Tensor(np.random.randn(1, 16, 12, 12).astype(np.float32))
  276. z = Tensor(np.random.randn(1, 16, 16, 16).astype(np.float32))
  277. res = if_while(Tensor(np.ones([1]).astype(np.float32)), Tensor(np.ones([1]).astype(np.float32)), x, z)
  278. assert np.all(res.asnumpy() == np.ones([64, 10]).astype(np.float32) * 4.0)
  279. def _while(x):
  280. """ _while """
  281. ret = x * x
  282. i = 2
  283. while i <= 3:
  284. ret = ret * i
  285. i = i + 1
  286. return ret
  287. def grad_while(x):
  288. """ grad_while """
  289. return grad_all(_while)(x)
  290. def test_grad_while():
  291. """ test_grad_while """
  292. assert grad_while(Tensor(5, dtype=ms.int32)) == (60,)
  293. @ms_function
  294. def factorial(n):
  295. """ factorial """
  296. if n == 0:
  297. return 1
  298. return n * factorial(n - 1)
  299. def test_factorial():
  300. res = factorial(3)
  301. assert res == 6
  302. @ms_function
  303. def factorial2(n):
  304. """ factorial """
  305. if n != 0:
  306. return n * factorial2(n - 1)
  307. elif n == 1:
  308. return 1 * factorial2(n - 1)
  309. else:
  310. return 1
  311. def test_factorial2():
  312. res = factorial2(3)
  313. assert res == 6
  314. @ms_function
  315. def foo(n):
  316. if n <= 1:
  317. if n == 1:
  318. return foo(n - 1)
  319. else:
  320. return 1
  321. else:
  322. return foo(n - 1)
  323. def test_foo():
  324. res = foo(5)
  325. assert res == 1
  326. @ms_function
  327. def double_nested_loop(x):
  328. i = 0
  329. s = 0
  330. while i < x:
  331. j = 0
  332. i = i + 1
  333. while j < 3:
  334. j = j + 1
  335. s = s + j
  336. return s
  337. def test_nested_loop():
  338. res = double_nested_loop(3)
  339. assert res == 18
  340. @ms_function
  341. def double_nested_loop2(x):
  342. s = 0
  343. for i in range(x):
  344. for j in range(3):
  345. s = s + j
  346. return s
  347. def test_nested_loop2():
  348. res = double_nested_loop(1)
  349. assert res == 6
  350. def _for(x):
  351. """ _for """
  352. ret = x * x
  353. for i in (2, 3):
  354. ret = ret * i
  355. return ret
  356. @ms_function
  357. def grad_for(x):
  358. """ grad_for """
  359. return grad_all(_for)(x)
  360. @ms_function
  361. def try_tail(x):
  362. """ try_tail """
  363. return C.tail(x)
  364. @non_graph_engine
  365. def test_tail():
  366. """ test_tail """
  367. try_tail((0, 1, 2, 3))
  368. @ms_function
  369. def zero_like_tensor(x):
  370. """ zero_like_tensor """
  371. return C.zeros_like(x)
  372. def test_zeros():
  373. """ test_zeros """
  374. x = Tensor(np.ones([2, 3]).astype(np.int32))
  375. res = zero_like_tensor(x)
  376. assert np.all(res.asnumpy() == np.zeros([2, 3]).astype(np.int32))
  377. @ms_function
  378. def arithmetic_simplify_01(x, y):
  379. """ arithmetic_simplify_01 """
  380. return C.zeros_like(x) * y
  381. def test_arithmetic_simplify_01():
  382. """ test_arithmetic_simplify_01 """
  383. x = Tensor(np.ones([2, 3]).astype(np.int32))
  384. y = Tensor(np.array([[1, 2, 3], [4, 5, 6]]).astype(np.int32))
  385. res = arithmetic_simplify_01(x, y)
  386. expect = np.zeros([2, 3]).astype(np.int32)
  387. assert np.all(res.asnumpy() == expect)
  388. @ms_function
  389. def arithmetic_simplify_02(x, y):
  390. """ arithmetic_simplify_02 """
  391. return C.ones_like(x) * y
  392. def test_arithmetic_simplify_02():
  393. """ test_arithmetic_simplify_02 """
  394. x = Tensor(np.ones([2, 3]).astype(np.int32))
  395. y = Tensor(np.array([[1, 2, 3], [4, 5, 6]]).astype(np.int32))
  396. res = arithmetic_simplify_02(x, y)
  397. expect = np.array([[1, 2, 3], [4, 5, 6]]).astype(np.int32)
  398. assert np.all(res.asnumpy() == expect)
  399. @ms_function
  400. def arithmetic_simplify_03(x, y):
  401. """ arithmetic_simplify_03 """
  402. return x * C.ones_like(y)
  403. def test_arithmetic_simplify_03():
  404. """ test_arithmetic_simplify_03 """
  405. x = Tensor(np.ones([2, 3]).astype(np.int32))
  406. y = Tensor(np.array([[1, 2, 3], [4, 5, 6]]).astype(np.int32))
  407. res = arithmetic_simplify_03(x, y)
  408. expect = np.ones([2, 3]).astype(np.int32)
  409. assert np.all(res.asnumpy() == expect)
  410. @ms_function
  411. def arithmetic_simplify_04(x):
  412. """ arithmetic_simplify_04 """
  413. return x + 0
  414. def test_arithmetic_simplify_04():
  415. """ test_arithmetic_simplify_04 """
  416. x = Tensor(np.array([[1, 2, 3], [4, 5, 6]]).astype(np.int32))
  417. res = arithmetic_simplify_04(x)
  418. expect = np.array([[1, 2, 3], [4, 5, 6]]).astype(np.int32)
  419. assert np.all(res.asnumpy() == expect)
  420. @ms_function
  421. def arithmetic_simplify_05(x):
  422. """ arithmetic_simplify_05 """
  423. return x * 1
  424. def test_arithmetic_simplify_05():
  425. """ test_arithmetic_simplify_05 """
  426. x = Tensor(np.array([[1, 2, 3], [4, 5, 6]]).astype(np.int32))
  427. res = arithmetic_simplify_05(x)
  428. expect = np.array([[1, 2, 3], [4, 5, 6]]).astype(np.int32)
  429. assert np.all(res.asnumpy() == expect)
  430. @ms_function
  431. def arithmetic_simplify_06(x):
  432. """ arithmetic_simplify_06 """
  433. return x * 2 * 5
  434. def test_arithmetic_simplify_06():
  435. """ test_arithmetic_simplify_06 """
  436. x = Tensor(np.array([[1, 2, 3], [4, 5, 6]]).astype(np.int32))
  437. res = arithmetic_simplify_06(x)
  438. expect = np.array([[10, 20, 30], [40, 50, 60]]).astype(np.int32)
  439. assert np.all(res.asnumpy() == expect)
  440. @ms_function
  441. def arithmetic_simplify_07(x):
  442. """ arithmetic_simplify_07 """
  443. return (x + 1) * 2 * 5
  444. def test_arithmetic_simplify_07():
  445. """ test_arithmetic_simplify_07 """
  446. x = Tensor(np.array([[1, 2, 3], [4, 5, 6]]).astype(np.int32))
  447. res = arithmetic_simplify_07(x)
  448. expect = np.array([[20, 30, 40], [50, 60, 70]]).astype(np.int32)
  449. assert np.all(res.asnumpy() == expect)
  450. @ms_function
  451. def arithmetic_simplify_08(x, y):
  452. """ arithmetic_simplify_08 """
  453. return 1 * x * 1 * 1 + 1 * 0 * 1 + 0 + y * 1
  454. def test_arithmetic_simplify_08():
  455. """ test_arithmetic_simplify_08 """
  456. x = Tensor(np.array([[1, 2, 3], [4, 5, 6]]).astype(np.int32))
  457. y = Tensor(np.ones([2, 3]).astype(np.int32))
  458. res = arithmetic_simplify_08(x, y)
  459. expect = np.array([[2, 3, 4], [5, 6, 7]]).astype(np.int32)
  460. assert np.all(res.asnumpy() == expect)
  461. def test_GradCheckerPrimitive():
  462. """ test_GradCheckerPrimitive """
  463. matmul = P.MatMul()
  464. def prim_f(x, y):
  465. return matmul(x, y)
  466. check_gradient(prim_f, Tensor(np.array([[0.65, 0.8, 0.8]], np.float32)),
  467. Tensor(np.array([[0.1], [0.2], [-.1]], np.float32)),
  468. grad_checker_class=OperationGradChecker, sampling_times=2)
  469. def test_NNGradChecker():
  470. """ test_NNGradChecker """
  471. class Net(nn.Cell):
  472. """ Net definition """
  473. def __init__(self):
  474. super(Net, self).__init__()
  475. self.dense = nn.Dense(10, 10)
  476. def construct(self, x):
  477. out = self.dense(x)
  478. return out
  479. check_gradient(Net(), Tensor(np.random.rand(1, 10).astype(np.float32)),
  480. delta=1e-3,
  481. max_error=1e-3,
  482. grad_checker_class=NNGradChecker, sampling_times=3)
  483. def test_OperationGradChecker():
  484. """ test_OperationGradChecker """
  485. class Net(nn.Cell):
  486. """ Net definition """
  487. def __init__(self):
  488. super(Net, self).__init__()
  489. self.matmul = P.MatMul()
  490. self.z = Parameter(Tensor(np.array([1.0], np.float32)), name='z')
  491. def construct(self, x, y):
  492. x = x * self.z
  493. out = self.matmul(x, y)
  494. return out
  495. check_gradient(Net(), Tensor(np.array([[0.65, 0.8, 0.8]], np.float32)),
  496. Tensor(np.array([[0.1], [0.2], [-.1]], np.float32)), grad_checker_class=OperationGradChecker,
  497. input_selector=[1], sampling_times=2)
  498. def test_OperationJacobianChecker():
  499. """ test_OperationJacobianChecker """
  500. class Net(nn.Cell):
  501. """ Net definition """
  502. def __init__(self):
  503. super(Net, self).__init__()
  504. self.matmul = P.MatMul()
  505. self.z = Parameter(Tensor(np.array([1.0], np.float32)), name='z')
  506. def construct(self, x, y):
  507. x = x * self.z
  508. out = self.matmul(x, y)
  509. return x, out
  510. check_jacobian(Net(), Tensor(np.array([[0.65, 0.8, 0.8], [0.1, 0.2, 0.3]], np.float32)),
  511. Tensor(np.array([[0.1, 0.3], [0.2, 0.2], [-.1, 0.4]], np.float32)),
  512. grad_checker_class=OperationGradChecker, input_selector=[0],
  513. output_selector=[0])
  514. def test_NNJacobianChecker():
  515. """ test_NNJacobianChecker """
  516. class Net(nn.Cell):
  517. """ Net definition """
  518. def __init__(self):
  519. super(Net, self).__init__()
  520. self.dense = nn.Dense(10, 10)
  521. def construct(self, x):
  522. out = self.dense(x)
  523. return out, x
  524. check_jacobian(Net(), Tensor(np.random.rand(1, 10).astype(np.float32)),
  525. delta=1e-3,
  526. max_error=1e-7,
  527. grad_checker_class=NNGradChecker,
  528. input_selector=[1],
  529. output_selector=[0])
  530. def multi_outputs(x, y):
  531. z = x + y
  532. return 2 * z, 2 * z
  533. @ms_function
  534. def while_sp(x, y, z):
  535. out = x
  536. i = c3
  537. while i < c2:
  538. out = mul(x, out)
  539. i = i + c3
  540. return out
  541. def test_while_sp():
  542. y = Tensor(np.ones([1, 3]).astype(np.float32))
  543. z = Tensor(np.ones([1, 3]).astype(np.float32))
  544. x = Tensor(np.ones([1, 3]).astype(np.float32) * 2.0)
  545. res = while_sp(x, y, z)
  546. assert np.all(res.asnumpy() == np.ones([1, 3]).astype(np.float32) * 1024.0)
  547. def grad_refactor_simple_1(x, y):
  548. """ add """
  549. return x * x + 2 * y
  550. def test_grad_refactor_simple_1():
  551. assert grad_all(grad_refactor_simple_1)(Tensor(2, dtype=ms.int32), Tensor(1, dtype=ms.int32)) == (4, 2)
  552. def grad_refactor_simple_2(x, y, z):
  553. """ add """
  554. return x * y + z + x * y * z + x + x * y
  555. def test_grad_refactor_simple_2():
  556. x = Tensor(2, dtype=ms.int32)
  557. y = Tensor(3, dtype=ms.int32)
  558. z = Tensor(0, dtype=ms.int32)
  559. assert grad_all(grad_refactor_simple_2)(x, y, z) == (7, 4, 7)
  560. def grad_refactor_1(a, b):
  561. """ if_test """
  562. def inner(x, y):
  563. return x * y
  564. return inner(a, b)
  565. def test_grad_refactor_1():
  566. assert grad_all(grad_refactor_1)(Tensor(2, dtype=ms.int32), Tensor(3, dtype=ms.int32)) == (3, 2)
  567. def grad_refactor_2(a, b):
  568. """ if_test """
  569. def inner(x):
  570. return x * b
  571. return inner(b) * inner(a)
  572. def test_grad_refactor_2():
  573. assert grad_all(grad_refactor_2)(Tensor(2, dtype=ms.int32), Tensor(3, dtype=ms.int32)) == (27, 54)
  574. def grad_refactor_3(a):
  575. """ if_test """
  576. if a > 3:
  577. return 0
  578. return 3 * a
  579. def grad_refactor_4(a):
  580. """ if_test """
  581. if a > 3:
  582. return 3 * a
  583. return 0
  584. def test_grad_refactor_4():
  585. assert grad_all(grad_refactor_4)(Tensor(4, dtype=ms.int32)) == (3,)
  586. def grad_refactor_5(a):
  587. """ if_test """
  588. if a > 3:
  589. return 1
  590. return a
  591. def grad_refactor_6(a, b):
  592. """ if_test """
  593. if a > b:
  594. return 3 * a + b
  595. return 2 * b * a
  596. def test_grad_refactor_6():
  597. assert grad_all(grad_refactor_6)(Tensor(3, dtype=ms.int32), Tensor(2, dtype=ms.int32)) == (3, 1)
  598. def grad_refactor_while(x):
  599. """ grad_refactor_while """
  600. rval = x
  601. while rval < 4:
  602. rval = rval * rval
  603. return rval
  604. def grad_refactor__while_1(x):
  605. """ _while """
  606. ret = x * x
  607. i = 2
  608. while i <= 3:
  609. ret = ret * i
  610. i = i + 1
  611. return ret
  612. def test_grad_refactor_10():
  613. """ test_grad_while """
  614. assert grad_all(grad_refactor__while_1)(Tensor(5, dtype=ms.int32)) == (60,)
  615. def test_grad_refactor_11():
  616. class Net(nn.Cell):
  617. """ Net definition """
  618. def __init__(self):
  619. super(Net, self).__init__()
  620. def construct(self, x, y):
  621. return x * y * y
  622. net = Net()
  623. grad_all(net)(Tensor(np.ones([2]).astype(np.float32)), Tensor(np.ones([2]).astype(np.float32)))
  624. def test_grad_refactor_12():
  625. class Net(nn.Cell):
  626. """ Net definition """
  627. def __init__(self):
  628. super(Net, self).__init__()
  629. self.z = Parameter(Tensor(np.array([1.0], np.float32)), name='z')
  630. def construct(self, x, y):
  631. return x * self.z * y
  632. net = Net()
  633. grad_all(net)(Tensor(np.ones([2]).astype(np.float32)), Tensor(np.zeros([2]).astype(np.float32)))
  634. def test_grad_refactor_13():
  635. class Net(nn.Cell):
  636. """ Net definition """
  637. def __init__(self):
  638. super(Net, self).__init__()
  639. self.z = Parameter(Tensor(np.ones([2]).astype(np.float32)), name='z')
  640. def construct(self, x, y):
  641. return x * self.z * y
  642. net = Net()
  643. weights = ParameterTuple(net.trainable_params())
  644. grad_by_list(net, weights)(Tensor(np.ones([2]).astype(np.float32)), Tensor(np.zeros([2]).astype(np.float32)))
  645. def grad_refactor_14(a, b):
  646. """ if_test """
  647. def inner1(x):
  648. return x * b
  649. def inner2(x):
  650. return a * b
  651. def inner3(x):
  652. if x > 2:
  653. return a
  654. return b
  655. return inner1(b) + inner2(a) + inner3(a)
  656. # pylint: disable=using-constant-test
  657. class IfDeferInline(nn.Cell):
  658. def __init__(self, mul_size):
  659. super().__init__()
  660. self.mul_weight = Tensor(np.full(mul_size, 0.6, dtype=np.float32))
  661. self.mul = P.Mul()
  662. def construct(self, inputs):
  663. x = self.mul(inputs, self.mul_weight)
  664. if True:
  665. x = x
  666. return x
  667. def test_grad_if_defer_inline():
  668. """ test_grad_if_defer_inline """
  669. network = IfDeferInline([128, 96])
  670. network.add_flags(defer_inline=False)
  671. inp = Tensor(np.ones([128, 96]).astype(np.float32))
  672. grads = grad_all(network)(inp)
  673. assert np.all(grads[0].asnumpy() == np.full([128, 96], 0.6, dtype=np.float32))
  674. def test_dict_const():
  675. class Net(nn.Cell):
  676. def __init__(self):
  677. super(Net, self).__init__()
  678. self.res = {'1': 10}
  679. def construct(self):
  680. return self.res
  681. Net()()