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 30 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  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. grad_by_list = C.GradOperation(get_by_list=True)
  30. grad_all = C.GradOperation(get_all=True)
  31. grad_all_with_sens = C.GradOperation(get_all=True, sens_param=True)
  32. def cond_data_test(x_init, y_init):
  33. class Net(nn.Cell):
  34. def __init__(self):
  35. """"""
  36. super(Net, self).__init__()
  37. self.square = P.Square()
  38. self.add = P.TensorAdd()
  39. self.value = Tensor(3, dtype=ms.float32)
  40. self.switch = P.GeSwitch()
  41. self.merge = P.Merge()
  42. self.less = P.Less()
  43. def construct(self, x, y):
  44. cond = self.less(x, y)
  45. st1, _ = self.switch(x, cond)
  46. st2, _ = self.switch(y, cond)
  47. add_ret = self.add(st1, st2)
  48. _, sf3 = self.switch(self.value, cond)
  49. sq_ret = self.square(sf3)
  50. ret = self.merge((add_ret, sq_ret))
  51. return ret[0]
  52. x = Tensor(x_init, dtype=ms.float32)
  53. y = Tensor(y_init, dtype=ms.float32)
  54. net = Net()
  55. output = net(x, y)
  56. return output
  57. def test_cond_data_true():
  58. output = cond_data_test(3, 8)
  59. print("test_cond_data_true:", output)
  60. def test_cond_data_false():
  61. output = cond_data_test(8, 3)
  62. print("test_cond_data_false:", output)
  63. def if_compile_test(x_init, y_init):
  64. class Net(nn.Cell):
  65. def __init__(self):
  66. """"""
  67. super(Net, self).__init__()
  68. self.square = P.Square()
  69. self.add = P.TensorAdd()
  70. self.value = Tensor(3, dtype=ms.float32)
  71. self.switch = P.GeSwitch()
  72. self.merge = P.Merge()
  73. self.less = P.Less()
  74. def construct(self, x, y):
  75. cond = self.less(x, y)
  76. ret = self.value
  77. if cond:
  78. ret = self.add(x, ret)
  79. ret = self.add(y, ret)
  80. else:
  81. ret = self.square(self.value)
  82. return ret
  83. x = Tensor(x_init, dtype=ms.float32)
  84. y = Tensor(y_init, dtype=ms.float32)
  85. net = Net()
  86. output = net(x, y)
  87. return output
  88. def test_if_none():
  89. class Net(nn.Cell):
  90. def __init__(self, z: None):
  91. """"""
  92. super(Net, self).__init__()
  93. self.z = z
  94. def construct(self, x, y):
  95. if self.z:
  96. ret = x
  97. else:
  98. ret = y
  99. return ret
  100. x = Tensor(np.ones([6, 8, 10], np.int32))
  101. y = Tensor(np.zeros([3, 4, 5], np.int32))
  102. z = None
  103. net = Net(z)
  104. assert np.all(net(x, y).asnumpy() == y.asnumpy())
  105. def test_if_str_is_not_none_right():
  106. class Net(nn.Cell):
  107. def __init__(self, z: str):
  108. """"""
  109. super(Net, self).__init__()
  110. self.z = z
  111. def construct(self, x, y):
  112. if self.z is None:
  113. ret = x
  114. else:
  115. ret = y
  116. return ret
  117. x = Tensor(np.ones([6, 8, 10], np.int32))
  118. y = Tensor(np.zeros([3, 4, 5], np.int32))
  119. z = "ok"
  120. net = Net(z)
  121. assert np.all(net(x, y).asnumpy() == y.asnumpy())
  122. def test_if_str_is_not_none_left():
  123. class Net(nn.Cell):
  124. def __init__(self, z: str):
  125. """"""
  126. super(Net, self).__init__()
  127. self.z = z
  128. def construct(self, x, y):
  129. if self.z is None:
  130. ret = x
  131. else:
  132. ret = y
  133. return ret
  134. x = Tensor(np.ones([6, 8, 10], np.int32))
  135. y = Tensor(np.zeros([3, 4, 5], np.int32))
  136. z = "ok"
  137. net = Net(z)
  138. assert np.all(net(x, y).asnumpy() == y.asnumpy())
  139. def test_if_none_equal_none():
  140. class Net(nn.Cell):
  141. def __init__(self, z: None):
  142. """"""
  143. super(Net, self).__init__()
  144. self.z = z
  145. def construct(self, x, y):
  146. if self.z is None:
  147. ret = x
  148. else:
  149. ret = y
  150. return ret
  151. x = Tensor(np.ones([6, 8, 10], np.int32))
  152. y = Tensor(np.zeros([3, 4, 5], np.int32))
  153. z = None
  154. net = Net(z)
  155. assert np.all(net(x, y).asnumpy() == x.asnumpy())
  156. def test_if_str_is_null():
  157. class Net(nn.Cell):
  158. def __init__(self, z: str):
  159. """"""
  160. super(Net, self).__init__()
  161. self.z = z
  162. def construct(self, x, y):
  163. if self.z:
  164. ret = x
  165. else:
  166. ret = y
  167. return ret
  168. x = Tensor(np.ones([6, 8, 10], np.int32))
  169. y = Tensor(np.zeros([3, 4, 5], np.int32))
  170. z = ""
  171. net = Net(z)
  172. assert np.all(net(x, y).asnumpy() == y.asnumpy())
  173. def test_if_str_is_true():
  174. class Net(nn.Cell):
  175. def __init__(self, z: str):
  176. """"""
  177. super(Net, self).__init__()
  178. self.z = z
  179. def construct(self, x, y):
  180. if self.z:
  181. ret = x
  182. else:
  183. ret = y
  184. return ret
  185. x = Tensor(np.ones([6, 9, 10], np.int32))
  186. y = Tensor(np.zeros([3, 4, 5], np.int32))
  187. z = "ok"
  188. net = Net(z)
  189. assert np.all(net(x, y).asnumpy() == x.asnumpy())
  190. def test_if_str_equal():
  191. class Net(nn.Cell):
  192. def __init__(self, z: str):
  193. """"""
  194. super(Net, self).__init__()
  195. self.z = z
  196. def construct(self, x, y):
  197. if self.z == "ok":
  198. ret = x
  199. else:
  200. ret = y
  201. return ret
  202. x = Tensor(np.ones([6, 8, 10], np.int32))
  203. y = Tensor(np.zeros([3, 4, 5], np.int32))
  204. z = "ok"
  205. net = Net(z)
  206. assert np.all(net(x, y).asnumpy() == x.asnumpy())
  207. def test_if_tuple_is_null():
  208. class Net(nn.Cell):
  209. def __init__(self, z: tuple):
  210. """"""
  211. super(Net, self).__init__()
  212. self.z = z
  213. def construct(self, x, y):
  214. if self.z:
  215. ret = x
  216. else:
  217. ret = y
  218. return ret
  219. x = Tensor(np.ones([6, 8, 10], np.int32))
  220. y = Tensor(np.zeros([3, 4, 5], np.int32))
  221. z = ()
  222. net = Net(z)
  223. assert np.all(net(x, y).asnumpy() == y.asnumpy())
  224. def test_if_tuple_is_not_null():
  225. class Net(nn.Cell):
  226. def __init__(self, z: tuple):
  227. """"""
  228. super(Net, self).__init__()
  229. self.z = z
  230. def construct(self, x, y):
  231. if self.z:
  232. ret = x
  233. else:
  234. ret = y
  235. return ret
  236. x = Tensor(np.ones([6, 8, 10], np.int32))
  237. y = Tensor(np.zeros([3, 4, 5], np.int32))
  238. z = (1, 2, 3)
  239. net = Net(z)
  240. assert np.all(net(x, y).asnumpy() == x.asnumpy())
  241. def test_if_dict_is_null():
  242. class Net(nn.Cell):
  243. def __init__(self, z: dict):
  244. """"""
  245. super(Net, self).__init__()
  246. self.z = z
  247. def construct(self, x, y):
  248. if self.z:
  249. ret = x
  250. else:
  251. ret = y
  252. return ret
  253. x = Tensor(np.ones([6, 8, 10], np.int32))
  254. y = Tensor(np.zeros([3, 4, 5], np.int32))
  255. z = {}
  256. net = Net(z)
  257. assert np.all(net(x, y).asnumpy() == y.asnumpy())
  258. def test_if_dict_is_not_null():
  259. class Net(nn.Cell):
  260. def __init__(self, z: dict):
  261. """"""
  262. super(Net, self).__init__()
  263. self.z = z
  264. def construct(self, x, y):
  265. if self.z:
  266. ret = x
  267. else:
  268. ret = y
  269. return ret
  270. x = Tensor(np.ones([6, 8, 10], np.int32))
  271. y = Tensor(np.zeros([3, 4, 5], np.int32))
  272. z = {"one": 1, "two": 2}
  273. net = Net(z)
  274. assert np.all(net(x, y).asnumpy() == x.asnumpy())
  275. def test_if_else_assign():
  276. class Net(nn.Cell):
  277. def __init__(self, m: list):
  278. """"""
  279. super(Net, self).__init__()
  280. self.m = m
  281. self.n = [4, 5, 6]
  282. def construct(self, x, y):
  283. exp_1 = self.m if self.m else self.n
  284. exp_2 = self.m if exp_1 == self.n else self.n
  285. if exp_2 == self.m:
  286. if self.m:
  287. ret = x
  288. else:
  289. ret = y
  290. else:
  291. if self.m:
  292. ret = x
  293. else:
  294. ret = y
  295. return ret
  296. x = Tensor(np.ones([6, 8, 10], np.int32))
  297. y = Tensor(np.zeros([3, 4, 5], np.int32))
  298. z = [1, 2]
  299. net = Net(z)
  300. assert np.all(net(x, y).asnumpy() == x.asnumpy())
  301. def test_if_compile_true():
  302. output = if_compile_test(3, 8)
  303. print("test_if_compile_true:", output)
  304. def test_if_compile_false():
  305. output = if_compile_test(8, 3)
  306. print("test_if_compile_false:", output)
  307. def test_switch_layer():
  308. class Layer1(nn.Cell):
  309. def __init__(self):
  310. super(Layer1, self).__init__()
  311. self.z1 = Parameter(
  312. Tensor(np.full([128, 96], 0.6, dtype=np.float32)), name='z1')
  313. def construct(self, x):
  314. return x * self.z1
  315. class Layer2(nn.Cell):
  316. def __init__(self):
  317. super(Layer2, self).__init__()
  318. self.z2 = Parameter(
  319. Tensor(np.full([128, 96], 0.6, dtype=np.float32)), name='z2')
  320. def construct(self, x):
  321. return x * self.z2
  322. class SwitchLayerCell(nn.Cell):
  323. def __init__(self):
  324. super(SwitchLayerCell, self).__init__()
  325. self.layers = (Layer1(), Layer2())
  326. self.z3 = Parameter(
  327. Tensor(np.full([128, 96], 0.6, dtype=np.float32)), name='z3')
  328. def construct(self, index, x):
  329. ret = F.switch_layer(index, self.layers)(x) * self.z3
  330. return ret
  331. index = Tensor(0, dtype=mstype.int32)
  332. net = SwitchLayerCell()
  333. net(index, Tensor(np.full([128, 96], 0.6, dtype=np.float32)))
  334. grad_by_list(net, ParameterTuple(net.trainable_params()))(index,
  335. Tensor(np.full([128, 96], 0.6, dtype=np.float32)))
  336. grad_all(net)(index, Tensor(np.full([128, 96], 0.6, dtype=np.float32)))
  337. def test_index_to_switch_layer():
  338. class Layer1(nn.Cell):
  339. def __init__(self):
  340. super(Layer1, self).__init__()
  341. self.z1 = Parameter(
  342. Tensor(np.full([128, 96], 0.6, dtype=np.float32)), name='z1')
  343. def construct(self, x):
  344. return x * self.z1
  345. class Layer2(nn.Cell):
  346. def __init__(self):
  347. super(Layer2, self).__init__()
  348. self.z2 = Parameter(
  349. Tensor(np.full([128, 96], 0.6, dtype=np.float32)), name='z2')
  350. def construct(self, x):
  351. return x * self.z2
  352. class SwitchLayerCell(nn.Cell):
  353. def __init__(self):
  354. super(SwitchLayerCell, self).__init__()
  355. self.layers = (Layer1(), Layer2())
  356. self.z3 = Parameter(
  357. Tensor(np.full([128, 96], 0.6, dtype=np.float32)), name='z3')
  358. def construct(self, index, x):
  359. ret = self.layers[index](x) * self.z3
  360. return ret
  361. index = Tensor(0, dtype=mstype.int32)
  362. net = SwitchLayerCell()
  363. net(index, Tensor(np.full([128, 96], 0.6, dtype=np.float32)))
  364. grad_by_list(net, ParameterTuple(net.trainable_params()))(index,
  365. Tensor(np.full([128, 96], 0.6, dtype=np.float32)))
  366. grad_all(net)(index, Tensor(np.full([128, 96], 0.6, dtype=np.float32)))
  367. def test_parser_switch_layer_switch_in_bprop():
  368. class OneInputBprop(nn.Cell):
  369. def __init__(self, funcs):
  370. super(OneInputBprop, self).__init__()
  371. self.op = P.ReLU()
  372. self.funcs = funcs
  373. def construct(self, i, x):
  374. return self.op(x)
  375. def bprop(self, i, x, out, dout):
  376. return i, self.funcs[i](x, dout)
  377. class Add(nn.Cell):
  378. def __init__(self):
  379. super().__init__()
  380. self.op = P.TensorAdd()
  381. def construct(self, x, y):
  382. return self.op(x, y)
  383. class Mul(nn.Cell):
  384. def __init__(self):
  385. super().__init__()
  386. self.op = P.Mul()
  387. def construct(self, x, y):
  388. return self.op(x, y)
  389. func1 = Add()
  390. func2 = Mul()
  391. funcs = (func1, func2)
  392. net = OneInputBprop(funcs)
  393. input1 = Tensor(np.ones([2, 2]).astype(np.float32))
  394. grad = Tensor(np.random.randn(2, 2).astype(np.float32))
  395. i = Tensor(1, mstype.int32)
  396. grad_net = grad_all_with_sens(net)
  397. grad_net(i, input1, grad)
  398. def test_parser_switch_layer_inputs_tuple():
  399. class TwoInputTupleFinalNet(nn.Cell):
  400. def __init__(self, funcs):
  401. super().__init__()
  402. self.funcs = funcs
  403. def construct(self, i, inputa, inputb):
  404. inputs = (inputa, inputb)
  405. x = self.funcs[i](inputs)
  406. return x
  407. class Add(nn.Cell):
  408. def __init__(self):
  409. super().__init__()
  410. self.op = P.TensorAdd()
  411. def construct(self, x):
  412. y = self.op(x[0], x[1])
  413. return self.op(x[0], y)
  414. class Mul(nn.Cell):
  415. def __init__(self):
  416. super().__init__()
  417. self.op = P.Mul()
  418. def construct(self, x):
  419. y = self.op(x[0], x[1])
  420. return self.op(x[0], y)
  421. func1 = Add()
  422. func2 = Mul()
  423. funcs = (func1, func2)
  424. net = TwoInputTupleFinalNet(funcs)
  425. input1 = Tensor(np.random.randn(2, 3, 4, 5).astype(np.float32))
  426. input2 = Tensor(np.random.randn(2, 3, 4, 5).astype(np.float32))
  427. i = Tensor(1, mstype.int32)
  428. grad = Tensor(np.random.randn(2, 3, 4, 5).astype(np.float32))
  429. back_net = grad_all_with_sens(net)
  430. back_out = back_net(i, input1, input2, grad)
  431. def test_switch_layer_with_single_prim():
  432. class SwitchLayerCell(nn.Cell):
  433. def __init__(self):
  434. super(SwitchLayerCell, self).__init__()
  435. self.layers = (nn.ReLU(), nn.ReLU())
  436. self.z3 = Parameter(
  437. Tensor(np.full([128, 96], 0.6, dtype=np.float32)), name='z3')
  438. def construct(self, index, x):
  439. ret = self.layers[index](x) * self.z3
  440. return ret
  441. index = Tensor(0, dtype=mstype.int32)
  442. net = SwitchLayerCell()
  443. net(index, Tensor(np.full([128, 96], 0.6, dtype=np.float32)))
  444. grad_by_list(net, ParameterTuple(net.trainable_params()))(index,
  445. Tensor(np.full([128, 96], 0.6, dtype=np.float32)))
  446. grad_all(net)(index, Tensor(np.full([128, 96], 0.6, dtype=np.float32)))
  447. def test_switch_layer_env_eliminate():
  448. class Net(nn.Cell):
  449. def __init__(self):
  450. super(Net, self).__init__()
  451. self.conv = nn.Conv2d(1, 1, 3, pad_mode='same')
  452. self.conv2 = nn.Conv2d(1, 1, 5, pad_mode='same')
  453. self.funs = (self.conv, self.conv2)
  454. def construct(self, x, index):
  455. x = self.funs[index](x)
  456. return x
  457. class NetGrad(nn.Cell):
  458. def __init__(self, net):
  459. super(NetGrad, self).__init__()
  460. self.grad_op = C.GradOperation(get_by_list=True, sens_param=False)
  461. self.net = net
  462. self.weights = ParameterTuple(self.net.trainable_params())
  463. def construct(self, x, index):
  464. weights = self.weights
  465. grad = self.grad_op(self.net, weights)(x, index)
  466. return grad
  467. net = Net()
  468. net2 = NetGrad(net)
  469. x = Tensor(np.ones((3, 1, 12, 12)), ms.float32)
  470. i = Tensor(1, ms.int32)
  471. net2(x, i)
  472. def test_switch_layer_single_layer():
  473. class Net(nn.Cell):
  474. def __init__(self):
  475. super(Net, self).__init__()
  476. self.conv = nn.Conv2d(1, 1, 3, pad_mode='same')
  477. self.funs = (self.conv,)
  478. def construct(self, x, index):
  479. x = self.funs[index](x)
  480. return x
  481. class NetGrad(nn.Cell):
  482. def __init__(self, net):
  483. super(NetGrad, self).__init__()
  484. self.grad_op = C.GradOperation(get_by_list=True, sens_param=False)
  485. self.net = net
  486. self.weights = ParameterTuple(self.net.trainable_params())
  487. def construct(self, x, index):
  488. weights = self.weights
  489. grad = self.grad_op(self.net, weights)(x, index)
  490. return grad
  491. net = Net()
  492. net2 = NetGrad(net)
  493. x = Tensor(np.ones((3, 1, 12, 12)), ms.float32)
  494. i = Tensor(1, ms.int32)
  495. net2(x, i)
  496. def test_control_depend_check():
  497. with pytest.raises(TypeError) as e:
  498. P.ControlDepend(0.0)
  499. print(e)
  500. with pytest.raises(ValueError) as e:
  501. P.ControlDepend(2)
  502. print(e)
  503. with pytest.raises(TypeError) as e:
  504. P.ControlDepend((2,))
  505. print(e)
  506. def test_if_nested_compile():
  507. class Net(nn.Cell):
  508. def __init__(self, auto_prefix=True):
  509. super().__init__(auto_prefix=auto_prefix)
  510. self.squre = P.Square()
  511. self.value = Tensor(3, dtype=ms.float32)
  512. def construct(self, x, y):
  513. res = self.value
  514. if x <= y:
  515. res = x + res
  516. res = y + res
  517. else:
  518. if x == y:
  519. res = self.squre(self.value * y)
  520. else:
  521. res = self.squre(self.value)
  522. return res
  523. x = Tensor(1.0, dtype=ms.float32)
  524. y = Tensor(2.0, dtype=ms.float32)
  525. net = Net()
  526. net(x, y)
  527. def test_if_inside_for():
  528. class Net(nn.Cell):
  529. def __init__(self, auto_prefix=True):
  530. super().__init__(auto_prefix=auto_prefix)
  531. self.squre = P.Square()
  532. self.value = Tensor(3, dtype=ms.float32)
  533. self.count = 4
  534. def construct(self, x, y):
  535. res = 0
  536. for i in range(self.count):
  537. if i == x:
  538. res = res + x
  539. else:
  540. res = res - y
  541. return res
  542. c1 = Tensor(1, dtype=ms.int32)
  543. c2 = Tensor(1, dtype=ms.int32)
  544. net = Net()
  545. net(c1, c2)
  546. def test_while_in_while():
  547. c1 = Tensor(1, dtype=ms.int32)
  548. c2 = Tensor(2, dtype=ms.int32)
  549. c3 = Tensor(3, dtype=ms.int32)
  550. c4 = Tensor(4, dtype=ms.int32)
  551. @ms_function
  552. def while_in_while(x, y, z, u):
  553. out = c4
  554. while x < y:
  555. z = c4 + c4
  556. while z < y:
  557. z = z + 1
  558. out = out + 1
  559. x = x + 1
  560. out = out + 3
  561. return out
  562. while_in_while(c1, c2, c3, c4)
  563. def test_tensor_cond():
  564. class Net(nn.Cell):
  565. def __init__(self):
  566. super(Net, self).__init__()
  567. self.t = Tensor(np.array(0, np.bool))
  568. self.t1 = Tensor(np.array([True], np.bool))
  569. def construct(self, x, y):
  570. t = 0
  571. if self.t:
  572. t = t - x * y
  573. else:
  574. t = t - x / y
  575. if self.t1:
  576. t = t + x / y
  577. else:
  578. t = t + x * y
  579. return t
  580. x = Tensor(np.ones([6, 8, 10], np.int32))
  581. y = Tensor(np.ones([6, 8, 10], np.int32))
  582. net = Net()
  583. out = net(x, y)
  584. def test_tensor_cond_exception():
  585. class Net(nn.Cell):
  586. def __init__(self):
  587. super(Net, self).__init__()
  588. self.t = Tensor(np.array([True, False], np.bool))
  589. def construct(self, x, y):
  590. t = 0
  591. if self.t:
  592. t = t - x * y
  593. else:
  594. t = t - x / y
  595. return t
  596. x = Tensor(np.ones([6, 8, 10], np.int32))
  597. y = Tensor(np.ones([6, 8, 10], np.int32))
  598. net = Net()
  599. with pytest.raises(ValueError):
  600. out = net(x, y)
  601. def test_while_scalar():
  602. class Net(nn.Cell):
  603. def __init__(self):
  604. super(Net, self).__init__()
  605. self.x = 10
  606. def construct(self, x, y):
  607. i = 0
  608. t = 0
  609. while (i < 10):
  610. t = t + x + y
  611. i = i + 1
  612. return t
  613. net = Net()
  614. x = Tensor(np.ones([6, 8, 10], np.int32))
  615. y = Tensor(np.ones([6, 8, 10], np.int32))
  616. out = net(x, y)
  617. def test_while_tensor():
  618. class Net(nn.Cell):
  619. def __init__(self):
  620. super(Net, self).__init__()
  621. self.t = Tensor(np.ones([6, 8, 10], np.int32))
  622. self.count = Tensor(np.array([10], np.int32))
  623. def construct(self, x, y):
  624. i = 0
  625. t = self.t
  626. while (i < self.count):
  627. t = t + x + y
  628. i = i + 1
  629. return t
  630. net = Net()
  631. x = Tensor(np.ones([6, 8, 10], np.int32))
  632. y = Tensor(np.ones([6, 8, 10], np.int32))
  633. out = net(x, y)
  634. def test_large_for_loop():
  635. class Net(nn.Cell):
  636. def __init__(self):
  637. super(Net, self).__init__()
  638. self.flatten = P.ReLU() # nn.Flatten()
  639. def construct(self, x):
  640. for elem in range(1, 1900):
  641. x = self.flatten(x + elem)
  642. return x
  643. t = Tensor(np.ones([2, 3], dtype=np.float32))
  644. net = Net()
  645. old_max_call_depth = context.get_context('max_call_depth')
  646. context.set_context(max_call_depth=60)
  647. with pytest.raises(RuntimeError) as err:
  648. net(t)
  649. context.set_context(max_call_depth=old_max_call_depth)
  650. assert 'Exceed function call depth limit 60' in str(err.value)
  651. def test_large_for_loop_with_continue_break():
  652. class Net(nn.Cell):
  653. def __init__(self):
  654. super(Net, self).__init__()
  655. self.flatten = P.ReLU() # nn.Flatten()
  656. def construct(self, x):
  657. idx = 0
  658. for elem1 in range(200):
  659. idx = idx + 1
  660. if idx < 10:
  661. x = x + 0.5
  662. continue
  663. if idx > 500:
  664. break
  665. x = self.flatten(x + elem1)
  666. return x
  667. old_max_call_depth = context.get_context('max_call_depth')
  668. context.set_context(max_call_depth=2000)
  669. t = Tensor(np.ones([2, 3], dtype=np.float32))
  670. net = Net()
  671. net(t)
  672. context.set_context(max_call_depth=old_max_call_depth)
  673. def test_mixed_precision_cast():
  674. x = Tensor(np.ones([2, 3], dtype=np.float32))
  675. z = F.mixed_precision_cast(mstype.float16, x)
  676. assert z.dtype == mstype.float16
  677. def test_while_concat():
  678. class Net(nn.Cell):
  679. def __init__(self, data):
  680. super(Net, self).__init__()
  681. self.start = Tensor(0, dtype=mstype.int32)
  682. self.end = Tensor(2, dtype=mstype.int32)
  683. self.out = Tensor(np.zeros([2, 3], dtype=np.float32))
  684. self.concat = P.Concat()
  685. def construct(self, inputs):
  686. idx = self.start
  687. end = self.end
  688. out = self.out
  689. while idx < end:
  690. xi = inputs[idx, :, :]
  691. out = self.concat((out, xi))
  692. idx = idx + 1
  693. return out
  694. x = Tensor(np.arange(10 * 2 * 3).reshape(10, 2, 3).astype(np.float32))
  695. net = Net(x)
  696. net(x)
  697. def test_tensor_all_construct_lack_branch():
  698. class NetConditionLackBranch(nn.Cell):
  699. def __init__(self):
  700. super(NetConditionLackBranch, self).__init__()
  701. self.logicaland = P.LogicalAnd()
  702. self.logicalor = P.LogicalOr()
  703. def construct(self, input1, input2):
  704. if input1.all():
  705. return self.logicaland(input1, input2)
  706. while input1.any():
  707. return self.logicalor(input1, input2)
  708. # NOTICE: here missing return statement, default return None
  709. input_np_1 = np.random.choice([True], size=(2, 3, 4, 5))
  710. input_tensor_1 = Tensor(input_np_1)
  711. input_np_2 = np.random.choice([True, False], size=(2, 3, 4, 5))
  712. input_tensor_2 = Tensor(input_np_2)
  713. net = NetConditionLackBranch()
  714. with pytest.raises(Exception):
  715. net(input_tensor_1, input_tensor_2)
  716. def test_parser_switch_layer_func_primitive():
  717. class FinalNet(nn.Cell):
  718. def __init__(self, funcs):
  719. super().__init__()
  720. self.funcs = funcs
  721. def construct(self, i, input1):
  722. x = self.funcs[i](input1)
  723. return x
  724. func1 = P.ReLU()
  725. func2 = P.Softmax()
  726. funcs = (func1, func2)
  727. net = FinalNet(funcs)
  728. input1 = Tensor(np.random.randn(2, 3, 4, 5).astype(np.float32))
  729. i = Tensor(1, mstype.int32)
  730. with pytest.raises(ValueError):
  731. net(i, input1)
  732. def test_recursive_call():
  733. class Net(nn.Cell):
  734. """ Net definition """
  735. def __init__(self):
  736. super(Net, self).__init__()
  737. self.fc = nn.Dense(10, 10) # padding=0
  738. # self.net2 = Net2()
  739. def construct(self, x):
  740. net2 = Net2()
  741. x = net2(x)
  742. out = self.fc(x)
  743. return out
  744. class Net2(nn.Cell):
  745. def __init__(self):
  746. super(Net2, self).__init__()
  747. self.net = Net()
  748. self.fc = nn.Dense(10, 10)
  749. def construct(self, x):
  750. x = self.net(x)
  751. out = self.fc(x)
  752. return out
  753. context.set_context(mode=context.GRAPH_MODE, save_graphs=False)
  754. old_max_call_depth = context.get_context('max_call_depth')
  755. context.set_context(max_call_depth=80)
  756. input_data = Tensor(np.identity(10).astype(np.float32))
  757. net = Net2()
  758. with pytest.raises(RuntimeError):
  759. net(input_data)
  760. context.set_context(max_call_depth=old_max_call_depth)
  761. def test_switch_layer_shape_join_failed():
  762. class AddFuncNet(nn.Cell):
  763. def __init__(self, funcs, new_func):
  764. super(AddFuncNet, self).__init__()
  765. self.funcs = funcs
  766. self.new_func = new_func
  767. def construct(self, i, inputs):
  768. final_funcs = self.funcs + (self.new_func,)
  769. x = final_funcs[i](inputs)
  770. return x
  771. class ReLUTuple(nn.Cell):
  772. def __init__(self):
  773. super(ReLUTuple, self).__init__()
  774. self.op = nn.ReLU()
  775. def construct(self, x):
  776. return self.op(x[0])
  777. func1 = nn.Softmax()
  778. func2 = nn.ReLU()
  779. func3 = ReLUTuple()
  780. funcs = (func1, func2)
  781. net = AddFuncNet(funcs, func3)
  782. inp = Tensor(np.random.randn(2, 3, 4, 5).astype(np.float32))
  783. i = Tensor(1, mstype.int32)
  784. with pytest.raises(ValueError) as err:
  785. net(i, inp)
  786. def test_switch_layer_dtype_join_failed():
  787. class Cast(nn.Cell):
  788. def __init__(self, dtype):
  789. super(Cast, self).__init__()
  790. self.op = P.Cast()
  791. self.dtype = dtype
  792. def construct(self, x):
  793. y = self.op(x, self.dtype)
  794. return y + y
  795. class SwitchNegNet(nn.Cell):
  796. def __init__(self, funcs):
  797. super(SwitchNegNet, self).__init__()
  798. self.funcs = funcs
  799. self.op = P.Neg()
  800. def construct(self, i, inputs):
  801. x = self.funcs[i](inputs)
  802. x = self.op(x)
  803. return x
  804. func1 = nn.ReLU()
  805. func2 = Cast(mstype.int32)
  806. funcs = (func1, func2)
  807. net = SwitchNegNet(funcs)
  808. inp = Tensor(np.random.randn(2, 3, 4, 5).astype(np.float32))
  809. i = Tensor(0, mstype.int32)
  810. with pytest.raises(TypeError) as err:
  811. net(i, inp)
  812. def test_large_for_loop_case2():
  813. class Menet(nn.Cell):
  814. def __init__(self, axis, flag_boottom, flag_top):
  815. super(Menet, self).__init__()
  816. self.squeeze = P.Squeeze(axis)
  817. self.expanddims = P.ExpandDims()
  818. self.flatten = nn.Flatten()
  819. self.neg = P.Neg()
  820. self.axis = axis
  821. self.flag_boottom = flag_boottom
  822. self.flag_top = flag_top
  823. def construct(self, x):
  824. if self.flag_boottom:
  825. x = self.neg(x)
  826. for i in range(0, 1500):
  827. x = self.expanddims(x, self.axis)
  828. x = self.squeeze(x)
  829. x = self.flatten(x)
  830. if self.flag_top:
  831. x = self.neg(x)
  832. return x
  833. x = Tensor(np.ones([2, 3], dtype=np.float32))
  834. net = Menet(axis=0, flag_boottom=True, flag_top=True)
  835. old_max_call_depth = context.get_context('max_call_depth')
  836. context.set_context(max_call_depth=80)
  837. with pytest.raises(RuntimeError) as err:
  838. net(x)
  839. context.set_context(max_call_depth=old_max_call_depth)
  840. assert 'Exceed function call depth limit 80' in str(err.value)