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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  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 while_upper_bound(upper):
  39. rval = 2
  40. while rval < upper:
  41. rval = rval * rval
  42. return rval
  43. def test_while_upper_bound():
  44. res = while_upper_bound(10)
  45. assert res == 16
  46. @ms_function
  47. def while_lower_bound(lower):
  48. """ t_while """
  49. rval = lower
  50. while rval < 100:
  51. rval = rval * rval
  52. return rval
  53. def test_while_lower_bound():
  54. res = while_lower_bound(2)
  55. assert res == 256
  56. @ms_function
  57. def dynamic_make_tuple(x, lower, upper):
  58. out = ()
  59. i = lower
  60. while i < upper:
  61. out = out + (x,)
  62. i = i + 1
  63. return out
  64. def test_dynamic_make_tuple():
  65. # Dynamicly recursively creating static type is invalid in mindspore, as mindspore is a static language.
  66. with pytest.raises(RuntimeError):
  67. dynamic_make_tuple(2, 1, 5)
  68. def test_make_tuple():
  69. # Staticly recursively creating static type is valid in mindspore.
  70. @ms_function
  71. def make_tuple(x):
  72. out = ()
  73. for i in range(3):
  74. out = out + (x,)
  75. return out
  76. res = make_tuple(5)
  77. assert res == (5, 5, 5)
  78. @ms_function
  79. def add(x, y):
  80. """ add """
  81. return x + y
  82. def mul(x, y):
  83. """ mul """
  84. return x * y
  85. def add_mul(x, y):
  86. """ add_mul """
  87. return (x + y) * y
  88. def mainf(x, y):
  89. """ mainf """
  90. return C.grad_all(mul)(x, y)
  91. def grad_add_mul(x, y):
  92. """ grad_add_mul """
  93. return C.grad_all(add_mul)(x, y)
  94. @ms_function
  95. def sub(x, y):
  96. """ sub """
  97. return x - y
  98. @ms_function
  99. def if_always_true(x):
  100. """ if_always_true """
  101. if True:
  102. return x
  103. else:
  104. return 0
  105. def test_add():
  106. """ test_add """
  107. res = add(2.5, 3)
  108. assert res == 5.5
  109. def test_sub():
  110. """ test_sub """
  111. res = sub(3.5, 3)
  112. assert res == 0.5
  113. @non_graph_engine
  114. def test_if_always_true():
  115. """ test_if_always_true """
  116. res = if_always_true(1)
  117. assert res == 1
  118. @non_graph_engine
  119. def test_f():
  120. """ test_f """
  121. res = mainf(3, 2)
  122. assert res == (2, 3)
  123. @non_graph_engine
  124. def test_grad_add_mul():
  125. """ test_grad_add_mul """
  126. res = grad_add_mul(3, 2)
  127. assert res == (2, 7)
  128. def f(x):
  129. if x > 0:
  130. return f(x-1)
  131. return x
  132. @ms_function
  133. def list_subscript():
  134. """ list_subscript """
  135. x= [1, 2, 3]
  136. return x[0] * x[1]
  137. def test_list_subscript():
  138. """ test_list_subscript """
  139. res = list_subscript()
  140. assert res == 2
  141. @ms_function
  142. def ms_infer_for(xs, y):
  143. """ ms_infer_for """
  144. rval = y
  145. for x in xs:
  146. rval = rval + x
  147. return rval
  148. def test_infer_for():
  149. """ test_infer_for """
  150. t = (1, 2, 3)
  151. y = 4
  152. res = ms_infer_for(t, y)
  153. assert res == 10
  154. @ms_function
  155. def if_construct(a, b):
  156. z = a
  157. if a > b:
  158. z = a+b
  159. else:
  160. z = a*b
  161. if z > b:
  162. return z-a
  163. else:
  164. return a-b
  165. def test_if_construct():
  166. """ test_if_construct """
  167. res = if_construct(3, 6)
  168. assert res == 15
  169. @ms_function
  170. def if_scalar(a, b):
  171. """ if_abstract """
  172. if a:
  173. return a
  174. return b
  175. def test_if_scalar1():
  176. """ test_if_abstract """
  177. res = if_scalar(3, 6)
  178. assert res == 3
  179. def test_if_scalar2():
  180. """ test_if_abstract """
  181. res = if_scalar(0, 6)
  182. assert res == 6
  183. @ms_function
  184. def if_tensor(a, b):
  185. c = a
  186. if a < b:
  187. c = a+a
  188. if c < b:
  189. c = a+c
  190. else:
  191. c = a+b
  192. else:
  193. c = b+b
  194. out = c + c
  195. return out
  196. def test_if_tensor():
  197. res = if_tensor(Tensor(np.ones([64, 10]).astype(np.int32)), Tensor(np.ones([64, 10]).astype(np.int32)))
  198. assert res == Tensor(np.ones([64, 10]).astype(np.int32) * 4)
  199. @ms_function
  200. def rec(x):
  201. """ rec """
  202. if x > 0:
  203. return rec(x-1)
  204. return x
  205. def test_grad_rec():
  206. """ test_grad_rec """
  207. res = C.grad(rec)(10)
  208. assert res == 1
  209. def test_me_rec():
  210. """ test_me_rec """
  211. res = rec(10)
  212. assert res == 0
  213. @ms_function
  214. def t2_while(x, y):
  215. out = y - x
  216. i = 0
  217. while i < 10:
  218. out = mul(x, y)
  219. i = i + 1
  220. return out
  221. def test_while2():
  222. res = t2_while(2, 3)
  223. assert res == 6
  224. def test_grad_while2():
  225. res = C.grad(t2_while)(2, 3)
  226. assert res == 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(5, 4) == (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([64, 10]).astype(np.float32)), Tensor(np.ones([64, 10]).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(5) == (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. res = C.grad(factorial)(3)
  331. assert res == 11
  332. def _for(x):
  333. """ _for """
  334. ret = x * x
  335. for i in (2, 3):
  336. ret = ret * i
  337. return ret
  338. def grad_for(x):
  339. """ grad_for """
  340. return C.grad_all(_for)(x)
  341. def test_grad_for():
  342. """ test_grad_for """
  343. assert grad_for(5) == (60,)
  344. @ms_function
  345. def try_tail(x):
  346. """ try_tail """
  347. return C.tail(x)
  348. @non_graph_engine
  349. def test_tail():
  350. """ test_tail """
  351. try_tail((0, 1, 2, 3))
  352. @ms_function
  353. def zero_like_tensor(x):
  354. """ zero_like_tensor """
  355. return C.zeros_like(x)
  356. def test_zeros():
  357. """ test_zeros """
  358. x = Tensor(np.ones([2, 3]).astype(np.int32))
  359. res = zero_like_tensor(x)
  360. assert res == Tensor(np.zeros([2, 3]).astype(np.int32))
  361. def test_ScalarGradChecker():
  362. """ test_ScalarGradChecker """
  363. def scalar_f(x, y):
  364. return x * y
  365. check_gradient(scalar_f, 1.0, 4.0, grad_checker_class=ScalarGradChecker, sampling_times=1)
  366. def test_GradCheckerPrimitive():
  367. """ test_GradCheckerPrimitive """
  368. matmul = P.MatMul()
  369. def prim_f(x, y):
  370. return matmul(x, y)
  371. check_gradient(prim_f, Tensor(np.array([[0.65, 0.8, 0.8]], np.float32)),
  372. Tensor(np.array([[0.1], [0.2], [-.1]], np.float32)),
  373. grad_checker_class=OperationGradChecker, sampling_times=2)
  374. def test_NNGradChecker():
  375. """ test_NNGradChecker """
  376. class Net(nn.Cell):
  377. """ Net definition """
  378. def __init__(self):
  379. super(Net, self).__init__()
  380. self.dense = nn.Dense(10, 10)
  381. def construct(self, x):
  382. out = self.dense(x)
  383. return out
  384. check_gradient(Net(), Tensor(np.random.rand(1, 10).astype(np.float32)),
  385. delta=1e-3,
  386. max_error=1e-3,
  387. grad_checker_class=NNGradChecker, sampling_times=3)
  388. def test_OperationGradChecker():
  389. """ test_OperationGradChecker """
  390. class Net(nn.Cell):
  391. """ Net definition """
  392. def __init__(self):
  393. super(Net, self).__init__()
  394. self.matmul = P.MatMul()
  395. self.z = Parameter(Tensor(np.array([1.0], np.float32)), name='z')
  396. def construct(self, x, y):
  397. x = x * self.z
  398. out = self.matmul(x, y)
  399. return out
  400. check_gradient(Net(), Tensor(np.array([[0.65, 0.8, 0.8]], np.float32)),
  401. Tensor(np.array([[0.1], [0.2], [-.1]], np.float32)), grad_checker_class=OperationGradChecker,
  402. input_selector=[1], sampling_times=2)
  403. def test_ScalarJacobianChecker():
  404. """ test_ScalarJacobianChecker """
  405. def scalar_f(x, y):
  406. return x * y
  407. check_jacobian(scalar_f, 1.0, 4.0, grad_checker_class=ScalarGradChecker, input_selector=[0])
  408. def test_OperationJacobianChecker():
  409. """ test_OperationJacobianChecker """
  410. class Net(nn.Cell):
  411. """ Net definition """
  412. def __init__(self):
  413. super(Net, self).__init__()
  414. self.matmul = P.MatMul()
  415. self.z = Parameter(Tensor(np.array([1.0], np.float32)), name='z')
  416. def construct(self, x, y):
  417. x = x * self.z
  418. out = self.matmul(x, y)
  419. return x, out
  420. check_jacobian(Net(), Tensor(np.array([[0.65, 0.8, 0.8], [0.1, 0.2, 0.3]], np.float32)),
  421. Tensor(np.array([[0.1, 0.3], [0.2, 0.2], [-.1, 0.4]], np.float32)),
  422. grad_checker_class=OperationGradChecker, input_selector=[0],
  423. output_selector=[0])
  424. def test_NNJacobianChecker():
  425. """ test_NNJacobianChecker """
  426. class Net(nn.Cell):
  427. """ Net definition """
  428. def __init__(self):
  429. super(Net, self).__init__()
  430. self.dense = nn.Dense(10, 10)
  431. def construct(self, x):
  432. out = self.dense(x)
  433. return out, x
  434. check_jacobian(Net(), Tensor(np.random.rand(1, 10).astype(np.float32)),
  435. delta=1e-3,
  436. max_error=1e-7,
  437. grad_checker_class=NNGradChecker,
  438. input_selector=[1],
  439. output_selector=[0])
  440. def multi_outputs(x, y):
  441. z = x + y
  442. return 2 * z, 2 * z
  443. def test_grad_multi_outputs():
  444. assert C.grad_all_with_sens(multi_outputs)(2, 3, (1, 1)) == (4, 4)
  445. @ms_function
  446. def while_sp(x, y, z):
  447. out = x
  448. i = c3
  449. while i < c2:
  450. out = mul(x, out)
  451. i = i + c3
  452. return out
  453. def test_while_sp():
  454. y = Tensor(np.ones([1, 3]).astype(np.float32))
  455. z = Tensor(np.ones([1, 3]).astype(np.float32))
  456. x = Tensor(np.ones([1, 3]).astype(np.float32) * 2.0)
  457. res = while_sp(x, y, z)
  458. assert res == Tensor(np.ones([1, 3]).astype(np.float32) * 1024.0)
  459. def grad_refactor_simple_1(x, y):
  460. """ add """
  461. return x * x + 2 * y
  462. def test_grad_refactor_simple_1():
  463. assert C.grad_all(grad_refactor_simple_1)(2, 1) == (4, 2)
  464. def grad_refactor_simple_2(x, y, z):
  465. """ add """
  466. return x * y + z + x * y * z + x + x * y
  467. def test_grad_refactor_simple_2():
  468. assert C.grad_all(grad_refactor_simple_2)(2, 3, 0) == (7, 4, 7)
  469. def grad_refactor_1(a, b):
  470. """ if_test """
  471. def inner(x, y):
  472. return x * y
  473. return inner(a, b)
  474. def test_grad_refactor_1():
  475. assert C.grad_all(grad_refactor_1)(2, 3) == (3, 2)
  476. def grad_refactor_2(a, b):
  477. """ if_test """
  478. def inner(x):
  479. return x * b
  480. return inner(b) * inner(a)
  481. def test_grad_refactor_2():
  482. assert C.grad_all(grad_refactor_2)(2, 3) == (27, 54)
  483. def grad_refactor_3(a):
  484. """ if_test """
  485. if a > 3:
  486. return 0
  487. return 3 * a
  488. def test_grad_refactor_3():
  489. assert C.grad_all(grad_refactor_3)(3) == (3,)
  490. def grad_refactor_4(a):
  491. """ if_test """
  492. if a > 3:
  493. return 3 * a
  494. return 0
  495. def test_grad_refactor_4():
  496. assert C.grad_all(grad_refactor_4)(4) == (3,)
  497. def grad_refactor_5(a):
  498. """ if_test """
  499. if a > 3:
  500. return 1
  501. return a
  502. def test_grad_refactor_5():
  503. assert C.grad_all(grad_refactor_5)(1) == (1,)
  504. def grad_refactor_6(a, b):
  505. """ if_test """
  506. if a > b:
  507. return 3 * a + b
  508. return 2 * b * a
  509. def test_grad_refactor_6():
  510. C.grad_all(grad_refactor_6)(3, 2) == (3, 1)
  511. def grad_refactor_while(x):
  512. """ grad_refactor_while """
  513. rval = x
  514. while rval < 4:
  515. rval = rval * rval
  516. return rval
  517. def test_grad_refactor_9():
  518. assert C.grad_all(grad_refactor_while)(3) == (6,)
  519. def grad_refactor__while_1(x):
  520. """ _while """
  521. ret = x * x
  522. i = 2
  523. while i <= 3:
  524. ret = ret * i
  525. i = i + 1
  526. return ret
  527. def test_grad_refactor_10():
  528. """ test_grad_while """
  529. assert C.grad_all(grad_refactor__while_1)(5) == (60,)
  530. def test_grad_refactor_11():
  531. class Net(nn.Cell):
  532. """ Net definition """
  533. def __init__(self):
  534. super(Net, self).__init__()
  535. def construct(self, x, y):
  536. return x * y * y
  537. net = Net()
  538. C.grad_all(net)(Tensor(np.ones([2]).astype(np.float32)), Tensor(np.ones([2]).astype(np.float32)))
  539. def test_grad_refactor_12():
  540. class Net(nn.Cell):
  541. """ Net definition """
  542. def __init__(self):
  543. super(Net, self).__init__()
  544. self.z = Parameter(Tensor(np.array([1.0], np.float32)), name='z')
  545. def construct(self, x, y):
  546. return x * self.z * y
  547. net = Net()
  548. C.grad_all(net)(Tensor(np.ones([2]).astype(np.float32)), Tensor(np.zeros([2]).astype(np.float32)))
  549. def test_grad_refactor_13():
  550. class Net(nn.Cell):
  551. """ Net definition """
  552. def __init__(self):
  553. super(Net, self).__init__()
  554. self.z = Parameter(Tensor(np.ones([2]).astype(np.float32)), name='z')
  555. def construct(self, x, y):
  556. return x * self.z * y
  557. net = Net()
  558. weights = ParameterTuple(net.trainable_params())
  559. C.grad_by_list(net, weights)(Tensor(np.ones([2]).astype(np.float32)), Tensor(np.zeros([2]).astype(np.float32)))
  560. def grad_refactor_14(a, b):
  561. """ if_test """
  562. def inner1(x):
  563. return x * b
  564. def inner2(x):
  565. return a * b
  566. def inner3(x):
  567. if (x > 2):
  568. return a
  569. return b
  570. return inner1(b) + inner2(a) + inner3(a)
  571. def test_grad_refactor_14():
  572. assert C.grad_all(grad_refactor_14)(2, 3) == (3, 9)
  573. class IfDeferInline(nn.Cell):
  574. def __init__(self, mul_size):
  575. super().__init__()
  576. self.mul_weight = Tensor(np.full(mul_size, 0.6, dtype=np.float32))
  577. self.mul = P.Mul()
  578. def construct(self, inputs):
  579. x = self.mul(inputs, self.mul_weight)
  580. if True:
  581. x = x
  582. return x
  583. def test_grad_if_defer_inline():
  584. """ test_grad_if_defer_inline """
  585. network = IfDeferInline([128, 96])
  586. network.add_flags(defer_inline=False)
  587. inp = Tensor(np.ones([128, 96]).astype(np.float32))
  588. grads = C.grad_all(network)(inp)
  589. assert grads == (Tensor(np.full([128, 96], 0.6, dtype=np.float32)),)