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_tensor_slice.py 15 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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_tensor_slice """
  16. import numpy as np
  17. import pytest
  18. from mindspore import Tensor
  19. from mindspore import context
  20. from mindspore import dtype as mstype
  21. from mindspore.nn import Cell
  22. from ....mindspore_test_framework.mindspore_test import mindspore_test
  23. from ....mindspore_test_framework.pipeline.forward.compile_forward \
  24. import pipeline_for_compile_forward_ge_graph_for_case_by_case_config
  25. class NetWorkSlicePositive(Cell):
  26. def __init__(self):
  27. super(NetWorkSlicePositive, self).__init__()
  28. self.tensor_ret0 = Tensor(np.ones([1, 2, 2], np.int32))
  29. self.tensor_ret1 = Tensor(np.ones([4, 7, 4], np.int32))
  30. self.tensor_ret2 = Tensor(np.ones([6, 8, 10], np.int32))
  31. self.tensor_ret3 = Tensor(np.ones([3, 8, 10], np.int32))
  32. def construct(self, tensor):
  33. ret0 = tensor[3:4:3, 1:5:2, 3:6:2] + self.tensor_ret0
  34. ret1 = tensor[-6:4:1, 7:-8:-1, ::3] + self.tensor_ret1
  35. ret2 = tensor[::, ::, ::] + self.tensor_ret2
  36. ret3 = tensor[::2] + self.tensor_ret3
  37. return ret0, ret1, ret2, ret3
  38. class NetWorkSliceEllipsis(Cell):
  39. def __init__(self):
  40. super(NetWorkSliceEllipsis, self).__init__()
  41. self.tensor_ret0 = Tensor(np.ones([2, 7, 8], np.int32))
  42. self.tensor_ret1 = Tensor(np.ones([6, 7, 8, 9], np.int32))
  43. self.tensor_ret2 = Tensor(np.ones([1, 6, 7, 8, 9], np.int32))
  44. def construct(self, tensor):
  45. ret0 = tensor[0:4:2, ..., 1] + self.tensor_ret0
  46. ret1 = tensor[...] + self.tensor_ret1
  47. ret2 = tensor[None] + self.tensor_ret2
  48. ret3 = tensor[True] + self.tensor_ret2
  49. return ret0, ret1, ret2, ret3
  50. class NetWorkReduceDimension(Cell):
  51. def __init__(self):
  52. super(NetWorkReduceDimension, self).__init__()
  53. self.tensor_ret0 = Tensor(np.ones([2, 4, 1], np.int32))
  54. self.tensor_ret1 = Tensor(np.ones([3, 4], np.int32))
  55. self.tensor_ret2 = Tensor(np.ones([6, 8], np.int32))
  56. self.tensor_ret3 = Tensor(np.array(8, np.int32))
  57. self.tensor_ret4 = Tensor(np.ones([8, 10], np.int32))
  58. def construct(self, tensor):
  59. ret0 = tensor[0:6:3, 1:5:1, 3:5:2] + self.tensor_ret0
  60. ret1 = tensor[::2, 1, ::3] + self.tensor_ret1
  61. ret2 = tensor[::, ::, 0] + self.tensor_ret2
  62. ret3 = tensor[3, 2, 5] + self.tensor_ret3
  63. ret4 = tensor[1] + self.tensor_ret4
  64. return ret0, ret1, ret2, ret3, ret4
  65. class NetWorkStepNegative(Cell):
  66. def __init__(self):
  67. super(NetWorkStepNegative, self).__init__()
  68. self.tensor_ret = Tensor(np.ones([6, 5, 10], np.int32))
  69. def construct(self, tensor):
  70. ret = tensor[::1, -5::, ::-1] + self.tensor_ret
  71. return ret
  72. class NetWorkReduceToScalar(Cell):
  73. def __init__(self):
  74. super(NetWorkReduceToScalar, self).__init__()
  75. self.tensor_ret = Tensor(np.array(9, np.int32))
  76. def construct(self, tensor):
  77. ret = tensor[2, 3, 4] + self.tensor_ret
  78. return ret
  79. class TensorAssignWithSliceError1(Cell):
  80. def __init__(self):
  81. super(TensorAssignWithSliceError1, self).__init__()
  82. def construct(self, a, b):
  83. a[1:3:-1,::] = b
  84. return a
  85. class TensorAssignWithSliceError2(Cell):
  86. def __init__(self):
  87. super(TensorAssignWithSliceError2, self).__init__()
  88. def construct(self, a, b):
  89. a[1:3:-1] = b
  90. return a
  91. class TensorAssignWithSlice2(Cell):
  92. def __init__(self):
  93. super(TensorAssignWithSlice2, self).__init__()
  94. def construct(self, a, b, ck):
  95. a[1:5] = b
  96. a[3:4] = 5
  97. a[-1:1:-1] = b
  98. a[-1:3:-1] = 5
  99. a[::] = b
  100. a[::] = 9
  101. z = a + ck
  102. return z
  103. class TensorAssignWithSlice(Cell):
  104. def __init__(self):
  105. super(TensorAssignWithSlice, self).__init__()
  106. self.c = 2
  107. def construct(self, a, b, ck):
  108. a[1:3,::] = b
  109. a[2:3:,3:] = b
  110. a[::] = b
  111. a[::] = self.c
  112. a[::,::] = b
  113. a[::,::] = self.c
  114. a[2:3:,0:, 4:1:-1] = b
  115. a[2:3:,0:, 4:1:-1] = self.c
  116. z = a + ck
  117. return z
  118. def test_tensor_assign():
  119. context.set_context(mode=context.GRAPH_MODE, save_graphs=True)
  120. net = TensorAssignWithSlice()
  121. net2= TensorAssignWithSlice2()
  122. net_e1 = TensorAssignWithSliceError1()
  123. net_e2 = TensorAssignWithSliceError2()
  124. a = np.arange(60).reshape(3,4,5)
  125. ck = np.arange(60).reshape(3,4,5)
  126. b = Tensor([1], dtype=mstype.float32)
  127. Ta = Tensor(a, dtype=mstype.float32)
  128. Tck = Tensor(ck, dtype=mstype.float32)
  129. Ta4d = Tensor(a.reshape(1,3,4,5), dtype=mstype.float32)
  130. Ta4d_ck = Tensor(ck.reshape(1,3,4,5), dtype=mstype.float32)
  131. Tb= Tensor([1,3], dtype=mstype.float32)
  132. Tc= Tensor([], dtype=mstype.float32)
  133. t = Tensor([1, 2, 3, 4, 5, 6, 7, 8], dtype=mstype.float32)
  134. tck = Tensor([1, 2, 3, 4, 5, 6, 7, 8], dtype=mstype.float32)
  135. net(Ta, b, Tck)
  136. net2(t, b, tck)
  137. # Error for A[Slice] = Number
  138. # 1. A[Slice] = Number, Slice error
  139. with pytest.raises(IndexError):
  140. net_e2(t, 2)
  141. # Error for A[Slice] = U, U is a Tensor
  142. # 1. A[Slice] = U, u.size is error
  143. with pytest.raises(ValueError):
  144. net2(t, Tb, tck)
  145. # 2. A[Slice] = U, U is empty
  146. with pytest.raises(ValueError):
  147. net2(t, Tc, tck)
  148. # 3. A[Slice] = U, U.size error
  149. with pytest.raises(ValueError):
  150. net2(t, Tb, tck)
  151. # Error for A[Tuple(Slice...)] = Tensor
  152. # 1. A[Tuple(Slice...)] = U, U is empty
  153. with pytest.raises(ValueError):
  154. net(Ta, Tc, Tck)
  155. # 2. A[Tuple(Slice...)] = U, U.size error
  156. with pytest.raises(ValueError):
  157. net(Ta, Tb, Tck)
  158. # 3. A[Tuple(Slice...)] = U, Slice error
  159. with pytest.raises(IndexError):
  160. net_e1(Ta, b)
  161. # Error for A[Tuple(Slice...)] = Number
  162. # 1. A[Tuple(Slice...)] = Number, Slice error
  163. with pytest.raises(IndexError):
  164. net_e1(Ta, 2)
  165. net = TensorAssignWithInteger()
  166. # Error for A[Number] = scalar/Tensor
  167. # 1. A[Number] = U, U is a Tensor, u.size not match
  168. with pytest.raises(ValueError):
  169. net(Ta, Tb, Tck)
  170. with pytest.raises(ValueError):
  171. net(Ta, Tc, Tck)
  172. # 2. A[Number] = U, the number index error
  173. with pytest.raises(IndexError):
  174. net(Ta4d, b, Ta4d_ck)
  175. # Error for A[(n,m)] = scalar/Tensor
  176. # 1. A[(n,m)] = U, U is a tensor. u.size not match
  177. net = TensorAssignWithTupleInteger()
  178. with pytest.raises(ValueError):
  179. net(Ta, Tc, Tck)
  180. with pytest.raises(ValueError):
  181. net(Ta, Tb, Tck)
  182. # 2. A[(n,m)] = U, the number index error
  183. with pytest.raises(IndexError):
  184. net(Ta4d, b, Ta4d_ck)
  185. #Error for A[...] = U or A[1:, ...] = u
  186. #1. A[...] = scalar/tensor
  187. net = TensorAssignWithEllipsis()
  188. net(Ta, Ta4d)
  189. with pytest.raises(ValueError):
  190. net(Ta, Tc)
  191. with pytest.raises(ValueError):
  192. net(Ta, Tb)
  193. #2. A[::, 1:, ...] = scalar/tensor
  194. net = TensorAssignWithTupleEllipsis()
  195. net(Ta, b)
  196. with pytest.raises(ValueError):
  197. net(Ta, Tc)
  198. with pytest.raises(ValueError):
  199. net(Ta, Tb)
  200. class TensorAssignWithTupleEllipsis2(Cell):
  201. def __init__(self):
  202. super(TensorAssignWithTupleEllipsis2, self).__init__()
  203. def construct(self, a, b):
  204. a[1:, ..., ::] = b
  205. return a
  206. class TensorAssignWithTupleEllipsis(Cell):
  207. def __init__(self):
  208. super(TensorAssignWithTupleEllipsis, self).__init__()
  209. def construct(self, a, b):
  210. a[:2, ...] = 1
  211. a[1:, ...] = b
  212. return a
  213. class TensorAssignWithEllipsis(Cell):
  214. def __init__(self):
  215. super(TensorAssignWithEllipsis, self).__init__()
  216. def construct(self, a, b):
  217. a[...] = 1
  218. a[...] = b
  219. return a
  220. class TensorAssignWithInteger(Cell):
  221. def __init__(self):
  222. super(TensorAssignWithInteger, self).__init__()
  223. def construct(self, a, b, ck):
  224. a[1] = 1
  225. a[0] = b
  226. z = a + ck
  227. return z
  228. class TensorAssignWithTupleInteger(Cell):
  229. def __init__(self):
  230. super(TensorAssignWithTupleInteger, self).__init__()
  231. def construct(self, a, b, ck):
  232. a[(1)] = 1
  233. a[(1)] = b
  234. a[(1,1)] = b
  235. a[(1,1)] = 1
  236. z = a + ck
  237. return z
  238. class TensorAssignWithBoolTensorIndex(Cell):
  239. def __init__(self):
  240. super(TensorAssignWithBoolTensorIndex, self).__init__()
  241. self.t = Tensor(np.arange(60).reshape([3,4,5]), dtype = mstype.float32)
  242. self.u_scalar = 5
  243. def construct(self, a, b, c, u_tensor):
  244. a[c] = self.u_scalar
  245. a[b] = u_tensor
  246. z = a + self.t
  247. return z
  248. class TensorAssignWithBoolTensorIndexError(Cell):
  249. def __init__(self):
  250. super(TensorAssignWithBoolTensorIndexError, self).__init__()
  251. def construct(self, a, b, c, u_tensor):
  252. a[b][c] = u_tensor
  253. return a
  254. class TensorAssignWithBoolTensorIndex2(Cell):
  255. def __init__(self):
  256. super(TensorAssignWithBoolTensorIndex2, self).__init__()
  257. self.t = Tensor(np.arange(6).reshape([2, 3]), dtype=mstype.float32)
  258. self.t = Tensor(np.arange(60).reshape([3,4,5]), dtype = mstype.float32)
  259. self.u_scalar = 5
  260. def construct(self, a, u_tensor):
  261. a[a > 8] = u_tensor
  262. a[a >= 6] = self.u_scalar
  263. a[a < 3] = self.u_scalar
  264. a[a <= 5] = u_tensor
  265. a[a == 5] = self.u_scalar
  266. z = a + self.t
  267. return z
  268. class TensorAssignWithBoolTensorIndex2Error(Cell):
  269. def __init__(self):
  270. super(TensorAssignWithBoolTensorIndex2Error, self).__init__()
  271. def construct(self, a, u_tensor):
  272. a[a > 8][a > 5] = u_tensor
  273. return a
  274. a = np.arange(60).reshape(3, 4, 5)
  275. ck = np.arange(60).reshape(3, 4, 5)
  276. a4 = np.arange(60).reshape(3, 2, 2, 5)
  277. b = a > 5
  278. c = a < 3
  279. Ta = Tensor(a, dtype=mstype.float32)
  280. Tck = Tensor(ck, dtype=mstype.float32)
  281. Ta4 = Tensor(a4, dtype=mstype.float32)
  282. Tb = Tensor(b)
  283. Tc = Tensor(c)
  284. Td = Tensor([True, True])
  285. u_tensor = Tensor([1], dtype=mstype.float32)
  286. u_tensor_error = Tensor([1, 2], dtype=mstype.float32)
  287. t_1d = Tensor([1, 2, 3, 4, 5, 6, 7, 8], dtype=mstype.float32)
  288. tck_1d = Tensor([1, 2, 3, 4, 5, 6, 7, 8], dtype=mstype.float32)
  289. u_scalar = 5
  290. def test_tensor_assign_bool_index():
  291. net1 = TensorAssignWithBoolTensorIndex()
  292. net2 = TensorAssignWithBoolTensorIndex2()
  293. net1(Ta, Tb, Tc, u_tensor)
  294. net1(Ta, Tb, Tc, u_tensor)
  295. with pytest.raises(ValueError):
  296. net1(Ta, Td, Tc, u_tensor)
  297. with pytest.raises(TypeError):
  298. net1(Ta, u_tensor, Tc, u_tensor)
  299. with pytest.raises(ValueError):
  300. net1(Ta, Tb, Td, u_tensor)
  301. with pytest.raises(TypeError):
  302. net1(Ta, Tb, Ta, u_tensor)
  303. with pytest.raises(ValueError):
  304. net1(Ta, Tb, Tc, u_tensor_error)
  305. # net1(Ta, u_tensor, Tc, u_tensor_error, u_scalar)
  306. with pytest.raises(ValueError):
  307. net2(Ta, u_tensor_error)
  308. net3 = TensorAssignWithBoolTensorIndexError()
  309. with pytest.raises(AttributeError):
  310. net3(Ta, Tb, Tc, u_tensor)
  311. with pytest.raises(AttributeError):
  312. net3(Ta, Tb, Tc, u_scalar)
  313. net4 = TensorAssignWithBoolTensorIndex2Error()
  314. with pytest.raises(AttributeError):
  315. net4(Ta, u_tensor)
  316. with pytest.raises(AttributeError):
  317. net4(Ta, u_scalar)
  318. test_cases = [
  319. ('TensorAssignWithTupleEllipsis2', {
  320. 'block': TensorAssignWithTupleEllipsis2(),
  321. 'desc_inputs': [Ta4, u_tensor],
  322. }),
  323. ('TensorAssignWithTupleEllipsis', {
  324. 'block': TensorAssignWithTupleEllipsis(),
  325. 'desc_inputs': [Ta, u_tensor],
  326. }),
  327. ('TensorAssignWithEllipsis', {
  328. 'block': TensorAssignWithEllipsis(),
  329. 'desc_inputs': [Ta, u_tensor],
  330. }),
  331. ('TensorAssignWithTupleInteger', {
  332. 'block': TensorAssignWithTupleInteger(),
  333. 'desc_inputs': [Ta, u_tensor, Tck],
  334. }),
  335. ('TensorAssignWithInteger', {
  336. 'block': TensorAssignWithInteger(),
  337. 'desc_inputs': [Ta, u_tensor, Tck],
  338. }),
  339. ('TensorAssignWithSlice', {
  340. 'block': TensorAssignWithSlice(),
  341. 'desc_inputs': [Ta, u_tensor, Tck],
  342. }),
  343. ('TensorAssignWithSlice2', {
  344. 'block': TensorAssignWithSlice2(),
  345. 'desc_inputs': [t_1d, u_tensor, tck_1d],
  346. }),
  347. ('TensorAssignWithBoolTensorIndex', {
  348. 'block': TensorAssignWithBoolTensorIndex(),
  349. 'desc_inputs': [Ta, Tb, Tc, u_tensor],
  350. }),
  351. ('TensorAssignWithBoolTensorIndex2', {
  352. 'block': TensorAssignWithBoolTensorIndex2(),
  353. 'desc_inputs': [Ta, u_tensor],
  354. }),
  355. ('SlicePositive', {
  356. 'block': NetWorkSlicePositive(),
  357. 'desc_inputs': [Tensor(np.ones([6, 8, 10], np.int32))],
  358. }),
  359. ('SliceReduceDimension', {
  360. 'block': NetWorkReduceDimension(),
  361. 'desc_inputs': [Tensor(np.ones([6, 8, 10], np.int32))],
  362. }),
  363. ('SliceNegative', {
  364. 'block': NetWorkStepNegative(),
  365. 'desc_inputs': [Tensor(np.ones([6, 8, 10], np.int32))],
  366. }),
  367. ('SliceReduceToScalar', {
  368. 'block': NetWorkReduceToScalar(),
  369. 'desc_inputs': [Tensor(np.ones([6, 8, 10], np.int32))],
  370. }),
  371. ('TensorSliceEllipsis', {
  372. 'block': NetWorkSliceEllipsis(),
  373. 'desc_inputs': [Tensor(np.ones([6, 7, 8, 9], np.int32))],
  374. }),
  375. ]
  376. @mindspore_test(pipeline_for_compile_forward_ge_graph_for_case_by_case_config)
  377. def test_compile():
  378. context.set_context(mode=context.GRAPH_MODE)
  379. return test_cases
  380. def test_tensor_slice_reduce_out_of_bounds_neg():
  381. class NetWork(Cell):
  382. def __init__(self):
  383. super(NetWork, self).__init__()
  384. self.tensor_ret = Tensor(np.array(9, np.int32))
  385. def construct(self, tensor):
  386. ret = tensor[-7, 3, 4]
  387. return ret
  388. input_tensor = Tensor(np.ones([6, 8, 10], np.int32))
  389. net = NetWork()
  390. with pytest.raises(ValueError) as ex:
  391. net(input_tensor)
  392. assert "For 'StridedSlice' the `begin[0]` should be an int and must greater or equal to -6, but got `-7`" in str(ex.value)
  393. def test_tensor_slice_reduce_out_of_bounds_positive():
  394. class NetWork(Cell):
  395. def __init__(self):
  396. super(NetWork, self).__init__()
  397. self.tensor_ret = Tensor(np.array(9, np.int32))
  398. def construct(self, tensor):
  399. ret = tensor[6, 3, 4]
  400. return ret
  401. input_tensor = Tensor(np.ones([6, 8, 10], np.int32))
  402. net = NetWork()
  403. with pytest.raises(ValueError) as ex:
  404. net(input_tensor)
  405. assert "For 'StridedSlice' the `begin[0]` should be an int and must less than 6, but got `6`" in str(ex.value)