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 18 kB

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