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_control_ops.py 17 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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 control ops """
  16. import numpy as np
  17. import pytest
  18. import mindspore as ms
  19. from mindspore import Tensor
  20. from mindspore import context
  21. from mindspore import nn
  22. from mindspore.common import dtype as mstype
  23. from mindspore.ops import composite as C
  24. from mindspore.ops import functional as F
  25. from mindspore.ops import operations as P
  26. from mindspore.common.parameter import Parameter, ParameterTuple
  27. from mindspore.common import ms_function
  28. context.set_context(mode=context.GRAPH_MODE)
  29. def cond_data_test(x_init, y_init):
  30. class Net(nn.Cell):
  31. def __init__(self):
  32. """"""
  33. super(Net, self).__init__()
  34. self.square = P.Square()
  35. self.add = P.TensorAdd()
  36. self.value = Tensor(3, dtype=ms.float32)
  37. self.switch = P.GeSwitch()
  38. self.merge = P.Merge()
  39. self.less = P.Less()
  40. def construct(self, x, y):
  41. cond = self.less(x, y)
  42. st1, _ = self.switch(x, cond)
  43. st2, _ = self.switch(y, cond)
  44. add_ret = self.add(st1, st2)
  45. _, sf3 = self.switch(self.value, cond)
  46. sq_ret = self.square(sf3)
  47. ret = self.merge((add_ret, sq_ret))
  48. return ret[0]
  49. x = Tensor(x_init, dtype=ms.float32)
  50. y = Tensor(y_init, dtype=ms.float32)
  51. net = Net()
  52. output = net(x, y)
  53. return output
  54. def test_cond_data_true():
  55. output = cond_data_test(3, 8)
  56. print("test_cond_data_true:", output)
  57. def test_cond_data_false():
  58. output = cond_data_test(8, 3)
  59. print("test_cond_data_false:", output)
  60. def if_compile_test(x_init, y_init):
  61. class Net(nn.Cell):
  62. def __init__(self):
  63. """"""
  64. super(Net, self).__init__()
  65. self.square = P.Square()
  66. self.add = P.TensorAdd()
  67. self.value = Tensor(3, dtype=ms.float32)
  68. self.switch = P.GeSwitch()
  69. self.merge = P.Merge()
  70. self.less = P.Less()
  71. def construct(self, x, y):
  72. cond = self.less(x, y)
  73. ret = self.value
  74. if cond:
  75. ret = self.add(x, ret)
  76. ret = self.add(y, ret)
  77. else:
  78. ret = self.square(self.value)
  79. return ret
  80. x = Tensor(x_init, dtype=ms.float32)
  81. y = Tensor(y_init, dtype=ms.float32)
  82. net = Net()
  83. output = net(x, y)
  84. return output
  85. def test_if_none():
  86. class Net(nn.Cell):
  87. def __init__(self, z: None):
  88. """"""
  89. super(Net, self).__init__()
  90. self.z = z
  91. def construct(self, x, y):
  92. if self.z:
  93. ret = x
  94. else:
  95. ret = y
  96. return ret
  97. x = Tensor(np.ones([6, 8, 10], np.int32))
  98. y = Tensor(np.zeros([3, 4, 5], np.int32))
  99. z = None
  100. net = Net(z)
  101. assert net(x, y) == y
  102. def test_if_str_is_not_none_right():
  103. class Net(nn.Cell):
  104. def __init__(self, z: str):
  105. """"""
  106. super(Net, self).__init__()
  107. self.z = z
  108. def construct(self, x, y):
  109. if self.z is None:
  110. ret = x
  111. else:
  112. ret = y
  113. return ret
  114. x = Tensor(np.ones([6, 8, 10], np.int32))
  115. y = Tensor(np.zeros([3, 4, 5], np.int32))
  116. z = "ok"
  117. net = Net(z)
  118. assert net(x, y) == y
  119. def test_if_str_is_not_none_left():
  120. class Net(nn.Cell):
  121. def __init__(self, z: str):
  122. """"""
  123. super(Net, self).__init__()
  124. self.z = z
  125. def construct(self, x, y):
  126. if self.z is None:
  127. ret = x
  128. else:
  129. ret = y
  130. return ret
  131. x = Tensor(np.ones([6, 8, 10], np.int32))
  132. y = Tensor(np.zeros([3, 4, 5], np.int32))
  133. z = "ok"
  134. net = Net(z)
  135. assert net(x, y) == y
  136. def test_if_none_equal_none():
  137. class Net(nn.Cell):
  138. def __init__(self, z: None):
  139. """"""
  140. super(Net, self).__init__()
  141. self.z = z
  142. def construct(self, x, y):
  143. if self.z is None:
  144. ret = x
  145. else:
  146. ret = y
  147. return ret
  148. x = Tensor(np.ones([6, 8, 10], np.int32))
  149. y = Tensor(np.zeros([3, 4, 5], np.int32))
  150. z = None
  151. net = Net(z)
  152. assert net(x, y) == x
  153. def test_if_str_is_null():
  154. class Net(nn.Cell):
  155. def __init__(self, z: str):
  156. """"""
  157. super(Net, self).__init__()
  158. self.z = z
  159. def construct(self, x, y):
  160. if self.z:
  161. ret = x
  162. else:
  163. ret = y
  164. return ret
  165. x = Tensor(np.ones([6, 8, 10], np.int32))
  166. y = Tensor(np.zeros([3, 4, 5], np.int32))
  167. z = ""
  168. net = Net(z)
  169. assert net(x, y) == y
  170. def test_if_str_is_true():
  171. class Net(nn.Cell):
  172. def __init__(self, z: str):
  173. """"""
  174. super(Net, self).__init__()
  175. self.z = z
  176. def construct(self, x, y):
  177. if self.z:
  178. ret = x
  179. else:
  180. ret = y
  181. return ret
  182. x = Tensor(np.ones([6, 9, 10], np.int32))
  183. y = Tensor(np.zeros([3, 4, 5], np.int32))
  184. z = "ok"
  185. net = Net(z)
  186. assert net(x, y) == x
  187. def test_if_str_equal():
  188. class Net(nn.Cell):
  189. def __init__(self, z: str):
  190. """"""
  191. super(Net, self).__init__()
  192. self.z = z
  193. def construct(self, x, y):
  194. if self.z == "ok":
  195. ret = x
  196. else:
  197. ret = y
  198. return ret
  199. x = Tensor(np.ones([6, 8, 10], np.int32))
  200. y = Tensor(np.zeros([3, 4, 5], np.int32))
  201. z = "ok"
  202. net = Net(z)
  203. assert net(x, y) == x
  204. def test_if_tuple_is_null():
  205. class Net(nn.Cell):
  206. def __init__(self, z: tuple):
  207. """"""
  208. super(Net, self).__init__()
  209. self.z = z
  210. def construct(self, x, y):
  211. if self.z:
  212. ret = x
  213. else:
  214. ret = y
  215. return ret
  216. x = Tensor(np.ones([6, 8, 10], np.int32))
  217. y = Tensor(np.zeros([3, 4, 5], np.int32))
  218. z = ()
  219. net = Net(z)
  220. assert net(x, y) == y
  221. def test_if_tuple_is_not_null():
  222. class Net(nn.Cell):
  223. def __init__(self, z: tuple):
  224. """"""
  225. super(Net, self).__init__()
  226. self.z = z
  227. def construct(self, x, y):
  228. if self.z:
  229. ret = x
  230. else:
  231. ret = y
  232. return ret
  233. x = Tensor(np.ones([6, 8, 10], np.int32))
  234. y = Tensor(np.zeros([3, 4, 5], np.int32))
  235. z = (1, 2, 3)
  236. net = Net(z)
  237. assert net(x, y) == x
  238. def test_if_dict_is_null():
  239. class Net(nn.Cell):
  240. def __init__(self, z: dict):
  241. """"""
  242. super(Net, self).__init__()
  243. self.z = z
  244. def construct(self, x, y):
  245. if self.z:
  246. ret = x
  247. else:
  248. ret = y
  249. return ret
  250. x = Tensor(np.ones([6, 8, 10], np.int32))
  251. y = Tensor(np.zeros([3, 4, 5], np.int32))
  252. z = {}
  253. net = Net(z)
  254. assert net(x, y) == y
  255. def test_if_dict_is_not_null():
  256. class Net(nn.Cell):
  257. def __init__(self, z: dict):
  258. """"""
  259. super(Net, self).__init__()
  260. self.z = z
  261. def construct(self, x, y):
  262. if self.z:
  263. ret = x
  264. else:
  265. ret = y
  266. return ret
  267. x = Tensor(np.ones([6, 8, 10], np.int32))
  268. y = Tensor(np.zeros([3, 4, 5], np.int32))
  269. z = {"one": 1, "two": 2}
  270. net = Net(z)
  271. assert net(x, y) == x
  272. def test_if_else_assign():
  273. class Net(nn.Cell):
  274. def __init__(self, m: list):
  275. """"""
  276. super(Net, self).__init__()
  277. self.m = m
  278. self.n = [4, 5, 6]
  279. def construct(self, x, y):
  280. exp_1 = self.m if self.m else self.n
  281. exp_2 = self.m if exp_1 == self.n else self.n
  282. if exp_2 == self.m:
  283. if self.m:
  284. ret = x
  285. else:
  286. ret = y
  287. else:
  288. if self.m:
  289. ret = x
  290. else:
  291. ret = y
  292. return ret
  293. x = Tensor(np.ones([6, 8, 10], np.int32))
  294. y = Tensor(np.zeros([3, 4, 5], np.int32))
  295. z = [1, 2]
  296. net = Net(z)
  297. assert net(x, y) == x
  298. def test_if_compile_true():
  299. output = if_compile_test(3, 8)
  300. print("test_if_compile_true:", output)
  301. def test_if_compile_false():
  302. output = if_compile_test(8, 3)
  303. print("test_if_compile_false:", output)
  304. def test_switch_layer():
  305. class Layer1(nn.Cell):
  306. def __init__(self):
  307. super(Layer1, self).__init__()
  308. self.z1 = Parameter(
  309. Tensor(np.full([128, 96], 0.6, dtype=np.float32)), name='z1')
  310. def construct(self, x):
  311. return x * self.z1
  312. class Layer2(nn.Cell):
  313. def __init__(self):
  314. super(Layer2, self).__init__()
  315. self.z2 = Parameter(
  316. Tensor(np.full([128, 96], 0.6, dtype=np.float32)), name='z2')
  317. def construct(self, x):
  318. return x * self.z2
  319. class SwitchLayerCell(nn.Cell):
  320. def __init__(self):
  321. super(SwitchLayerCell, self).__init__()
  322. self.layers = (Layer1(), Layer2())
  323. self.z3 = Parameter(
  324. Tensor(np.full([128, 96], 0.6, dtype=np.float32)), name='z3')
  325. def construct(self, index, x):
  326. ret = F.switch_layer(index, self.layers)(x) * self.z3
  327. return ret
  328. index = Tensor(0)
  329. net = SwitchLayerCell()
  330. net(index, Tensor(np.full([128, 96], 0.6, dtype=np.float32)))
  331. C.grad_by_list(net, ParameterTuple(net.trainable_params()))(index,
  332. Tensor(np.full([128, 96], 0.6, dtype=np.float32)))
  333. C.grad_all(net)(index, Tensor(np.full([128, 96], 0.6, dtype=np.float32)))
  334. def test_index_to_switch_layer():
  335. class Layer1(nn.Cell):
  336. def __init__(self):
  337. super(Layer1, self).__init__()
  338. self.z1 = Parameter(
  339. Tensor(np.full([128, 96], 0.6, dtype=np.float32)), name='z1')
  340. def construct(self, x):
  341. return x * self.z1
  342. class Layer2(nn.Cell):
  343. def __init__(self):
  344. super(Layer2, self).__init__()
  345. self.z2 = Parameter(
  346. Tensor(np.full([128, 96], 0.6, dtype=np.float32)), name='z2')
  347. def construct(self, x):
  348. return x * self.z2
  349. class SwitchLayerCell(nn.Cell):
  350. def __init__(self):
  351. super(SwitchLayerCell, self).__init__()
  352. self.layers = (Layer1(), Layer2())
  353. self.z3 = Parameter(
  354. Tensor(np.full([128, 96], 0.6, dtype=np.float32)), name='z3')
  355. def construct(self, index, x):
  356. ret = self.layers[index](x) * self.z3
  357. return ret
  358. index = Tensor(0)
  359. net = SwitchLayerCell()
  360. net(index, Tensor(np.full([128, 96], 0.6, dtype=np.float32)))
  361. C.grad_by_list(net, ParameterTuple(net.trainable_params()))(index,
  362. Tensor(np.full([128, 96], 0.6, dtype=np.float32)))
  363. C.grad_all(net)(index, Tensor(np.full([128, 96], 0.6, dtype=np.float32)))
  364. def test_control_depend_check():
  365. with pytest.raises(TypeError) as e:
  366. P.ControlDepend(0.0)
  367. print(e)
  368. with pytest.raises(ValueError) as e:
  369. P.ControlDepend(2)
  370. print(e)
  371. with pytest.raises(TypeError) as e:
  372. P.ControlDepend((2,))
  373. print(e)
  374. def test_if_nested_compile():
  375. class Net(nn.Cell):
  376. def __init__(self, auto_prefix=True):
  377. super().__init__(auto_prefix=auto_prefix)
  378. self.squre = P.Square()
  379. self.value = Tensor(3, dtype=ms.float32)
  380. def construct(self, x, y):
  381. res = self.value
  382. if x <= y:
  383. res = x + res
  384. res = y + res
  385. else:
  386. if x == y:
  387. res = self.squre(self.value * y)
  388. else:
  389. res = self.squre(self.value)
  390. return res
  391. x = Tensor(1.0, dtype=ms.float32)
  392. y = Tensor(2.0, dtype=ms.float32)
  393. net = Net()
  394. net(x, y)
  395. def test_if_inside_for():
  396. class Net(nn.Cell):
  397. def __init__(self, auto_prefix=True):
  398. super().__init__(auto_prefix=auto_prefix)
  399. self.squre = P.Square()
  400. self.value = Tensor(3, dtype=ms.float32)
  401. self.count = 4
  402. def construct(self, x, y):
  403. res = 0
  404. for i in range(self.count):
  405. if i == x:
  406. res = res + x
  407. else:
  408. res = res - y
  409. return res
  410. c1 = Tensor(1, dtype=ms.int32)
  411. c2 = Tensor(1, dtype=ms.int32)
  412. net = Net()
  413. net(c1, c2)
  414. def test_while_in_while():
  415. c1 = Tensor(1, dtype=ms.int32)
  416. c2 = Tensor(2, dtype=ms.int32)
  417. c3 = Tensor(3, dtype=ms.int32)
  418. c4 = Tensor(4, dtype=ms.int32)
  419. @ms_function
  420. def while_in_while(x, y, z, u):
  421. out = c4
  422. while x < y:
  423. z = c4 + c4
  424. while z < y:
  425. z = z + 1
  426. out = out + 1
  427. x = x + 1
  428. out = out + 3
  429. return out
  430. while_in_while(c1, c2, c3, c4)
  431. def test_tensor_cond():
  432. class Net(nn.Cell):
  433. def __init__(self):
  434. super(Net, self).__init__()
  435. self.t = Tensor(np.array(0, np.bool))
  436. self.t1 = Tensor(np.array([True], np.bool))
  437. def construct(self, x, y):
  438. t = 0
  439. if self.t:
  440. t = t - x * y
  441. else:
  442. t = t - x / y
  443. if self.t1:
  444. t = t + x / y
  445. else:
  446. t = t + x * y
  447. return t
  448. x = Tensor(np.ones([6, 8, 10], np.int32))
  449. y = Tensor(np.ones([6, 8, 10], np.int32))
  450. net = Net()
  451. out = net(x, y)
  452. def test_tensor_cond_exception():
  453. class Net(nn.Cell):
  454. def __init__(self):
  455. super(Net, self).__init__()
  456. self.t = Tensor(np.array([True, False], np.bool))
  457. def construct(self, x, y):
  458. t = 0
  459. if self.t:
  460. t = t - x * y
  461. else:
  462. t = t - x / y
  463. return t
  464. x = Tensor(np.ones([6, 8, 10], np.int32))
  465. y = Tensor(np.ones([6, 8, 10], np.int32))
  466. net = Net()
  467. with pytest.raises(ValueError):
  468. out = net(x, y)
  469. def test_while_scalar():
  470. class Net(nn.Cell):
  471. def __init__(self):
  472. super(Net, self).__init__()
  473. self.x = 10
  474. def construct(self, x, y):
  475. i = 0
  476. t = 0
  477. while (i < 10):
  478. t = t + x + y
  479. i = i + 1
  480. return t
  481. net = Net()
  482. x = Tensor(np.ones([6, 8, 10], np.int32))
  483. y = Tensor(np.ones([6, 8, 10], np.int32))
  484. out = net(x, y)
  485. def test_while_tensor():
  486. class Net(nn.Cell):
  487. def __init__(self):
  488. super(Net, self).__init__()
  489. self.t = Tensor(np.ones([6, 8, 10], np.int32))
  490. self.count = Tensor(np.array([10], np.int32))
  491. def construct(self, x, y):
  492. i = 0
  493. t = self.t
  494. while (i < self.count):
  495. t = t + x + y
  496. i = i + 1
  497. return t
  498. net = Net()
  499. x = Tensor(np.ones([6, 8, 10], np.int32))
  500. y = Tensor(np.ones([6, 8, 10], np.int32))
  501. out = net(x, y)
  502. def test_large_for_loop():
  503. class Net(nn.Cell):
  504. def __init__(self):
  505. super(Net, self).__init__()
  506. self.flatten = P.ReLU() #nn.Flatten()
  507. def construct(self, x):
  508. for elem in range(1, 19000):
  509. x = self.flatten(x + elem)
  510. return x
  511. t = Tensor(np.ones([2, 3], dtype=np.float32))
  512. net = Net()
  513. net(t)
  514. def test_large_for_loop_with_continue_break():
  515. class Net(nn.Cell):
  516. def __init__(self):
  517. super(Net, self).__init__()
  518. self.flatten = P.ReLU() #nn.Flatten()
  519. def construct(self, x):
  520. idx = 0
  521. for elem1 in range(200):
  522. idx = idx + 1
  523. if idx < 10:
  524. x = x + 0.5
  525. continue
  526. if idx > 500:
  527. break
  528. x = self.flatten(x + elem1)
  529. return x
  530. t = Tensor(np.ones([2, 3], dtype=np.float32))
  531. net = Net()
  532. net(t)
  533. def test_mixed_precision_cast():
  534. x = Tensor(np.ones([2, 3], dtype=np.float32))
  535. z = F.mixed_precision_cast(mstype.float16, x)
  536. assert z.dtype == mstype.float16