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