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