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