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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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):
  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. return a
  102. class TensorAssignWithSlice(Cell):
  103. def __init__(self):
  104. super(TensorAssignWithSlice, self).__init__()
  105. self.c = 2
  106. def construct(self, a, b):
  107. a[1:3,::] = b
  108. a[2:3:,3:] = b
  109. a[::] = b
  110. a[::] = self.c
  111. a[::,::] = b
  112. a[::,::] = self.c
  113. a[2:3:,0:, 4:1:-1] = b
  114. a[2:3:,0:, 4:1:-1] = self.c
  115. z = a
  116. return z
  117. def test_tensor_assign():
  118. context.set_context(mode=context.GRAPH_MODE, save_graphs=True)
  119. net = TensorAssignWithSlice()
  120. net2= TensorAssignWithSlice2()
  121. net_e1 = TensorAssignWithSliceError1()
  122. net_e2 = TensorAssignWithSliceError2()
  123. a = np.arange(60).reshape(3,4,5)
  124. b = Tensor([1])
  125. Ta = Tensor(a)
  126. Ta4d = Tensor(a.reshape(1,3,4,5))
  127. Tb= Tensor([1,3])
  128. Tc= Tensor([])
  129. t = Tensor([1, 2, 3, 4, 5, 6, 7, 8])
  130. net(Ta, b)
  131. net2(t, b)
  132. # Error for A[Slice] = Number
  133. # 1. A[Slice] = Number, Slice error
  134. with pytest.raises(ValueError):
  135. net_e2(t, 2)
  136. # Error for A[Slice] = U, U is a Tensor
  137. # 1. A[Slice] = U, u.size is error
  138. with pytest.raises(ValueError):
  139. net2(t, Tb)
  140. # 2. A[Slice] = U, U is empty
  141. with pytest.raises(ValueError):
  142. net2(t, Tc)
  143. # 3. A[Slice] = U, U.size error
  144. with pytest.raises(ValueError):
  145. net2(t, Tb)
  146. # Error for A[Tuple(Slice...)] = Tensor
  147. # 1. A[Tuple(Slice...)] = U, U is empty
  148. with pytest.raises(ValueError):
  149. net(Ta, Tc)
  150. # 2. A[Tuple(Slice...)] = U, U.size error
  151. with pytest.raises(ValueError):
  152. net(Ta, Tb)
  153. # 3. A[Tuple(Slice...)] = U, Slice error
  154. with pytest.raises(ValueError):
  155. net_e1(Ta, b)
  156. # Error for A[Tuple(Slice...)] = Number
  157. # 1. A[Tuple(Slice...)] = Number, Slice error
  158. with pytest.raises(ValueError):
  159. net_e1(Ta, 2)
  160. net = TensorAssignWithInteger()
  161. # Error for A[Number] = scalar/Tensor
  162. # 1. A[Number] = U, U is a Tensor, u.size not match
  163. with pytest.raises(ValueError):
  164. net(Ta, Tb)
  165. with pytest.raises(ValueError):
  166. net(Ta, Tc)
  167. # 2. A[Number] = U, the number index error
  168. with pytest.raises(IndexError):
  169. net(Ta4d, b)
  170. # Error for A[(n,m)] = scalar/Tensor
  171. # 1. A[(n,m)] = U, U is a tensor. u.size not match
  172. net = TensorAssignWithTupleInteger()
  173. with pytest.raises(ValueError):
  174. net(Ta, Tc)
  175. with pytest.raises(ValueError):
  176. net(Ta, Tb)
  177. # 2. A[(n,m)] = U, the number index error
  178. with pytest.raises(IndexError):
  179. net(Ta4d, b)
  180. class TensorAssignWithInteger(Cell):
  181. def __init__(self):
  182. super(TensorAssignWithInteger, self).__init__()
  183. def construct(self, a, b):
  184. a[1] = 1
  185. a[0] = b
  186. return a
  187. class TensorAssignWithTupleInteger(Cell):
  188. def __init__(self):
  189. super(TensorAssignWithTupleInteger, self).__init__()
  190. def construct(self, a, b):
  191. a[(1)] = 1
  192. a[(1)] = b
  193. a[(1,1)] = b
  194. a[(1,1)] = 1
  195. return a
  196. class TensorAssignWithBoolTensorIndex(Cell):
  197. def __init__(self):
  198. super(TensorAssignWithBoolTensorIndex, self).__init__()
  199. self.t = Tensor(np.arange(60).reshape([3,4,5]), dtype = mstype.float64)
  200. def construct(self, a, b, c, u_tensor, _scalar):
  201. a[c] = u_scalar
  202. a[b] = u_tensor
  203. z = a + self.t
  204. return z
  205. class TensorAssignWithBoolTensorIndexError(Cell):
  206. def __init__(self):
  207. super(TensorAssignWithBoolTensorIndexError, self).__init__()
  208. def construct(self, a, b, c, u_tensor):
  209. a[b][c] = u_tensor
  210. return a
  211. class TensorAssignWithBoolTensorIndex2(Cell):
  212. def __init__(self):
  213. super(TensorAssignWithBoolTensorIndex2, self).__init__()
  214. self.t = Tensor(np.arange(6).reshape([2, 3]), dtype=mstype.float64)
  215. self.t = Tensor(np.arange(60).reshape([3,4,5]), dtype = mstype.float64)
  216. def construct(self, a, u_tensor, _scalar):
  217. a[a > 8] = u_tensor
  218. a[a >= 6] = u_scalar
  219. a[a < 3] = u_scalar
  220. a[a <= 5] = u_tensor
  221. a[a == 5] = u_scalar
  222. z = a + self.t
  223. return z
  224. class TensorAssignWithBoolTensorIndex2Error(Cell):
  225. def __init__(self):
  226. super(TensorAssignWithBoolTensorIndex2Error, self).__init__()
  227. def construct(self, a, u_tensor):
  228. a[a > 8][a > 5] = u_tensor
  229. return a
  230. a = np.random.uniform(1,10,[3,4,5])
  231. b = a > 5
  232. c = a < 3
  233. Ta = Tensor(a)
  234. Tb = Tensor(b)
  235. Tc = Tensor(c)
  236. Td = Tensor([True, True])
  237. u_tensor = Tensor([1])
  238. u_tensor_error = Tensor([1, 2])
  239. t_1d = Tensor([1, 2, 3, 4, 5, 6, 7, 8])
  240. u_scalar = 5
  241. def test_tensor_assign_bool_index():
  242. net1 = TensorAssignWithBoolTensorIndex()
  243. net2 = TensorAssignWithBoolTensorIndex2()
  244. net1(Ta, Tb, Tc, u_tensor, u_scalar)
  245. net1(Ta, Tb, Tc, u_tensor, u_scalar)
  246. with pytest.raises(ValueError):
  247. net1(Ta, Td, Tc, u_tensor, u_scalar)
  248. with pytest.raises(ValueError):
  249. net1(Ta, u_tensor, Tc, u_tensor, u_scalar)
  250. with pytest.raises(ValueError):
  251. net1(Ta, Tb, Td, u_tensor, u_scalar)
  252. with pytest.raises(ValueError):
  253. net1(Ta, Tb, Ta, u_tensor, u_scalar)
  254. with pytest.raises(ValueError):
  255. net1(Ta, Tb, Tc, u_tensor_error, u_scalar)
  256. # net1(Ta, u_tensor, Tc, u_tensor_error, u_scalar)
  257. with pytest.raises(ValueError):
  258. net2(Ta, u_tensor_error, u_scalar)
  259. net3 = TensorAssignWithBoolTensorIndexError()
  260. with pytest.raises(AttributeError):
  261. net3(Ta, Tb, Tc, u_tensor)
  262. with pytest.raises(AttributeError):
  263. net3(Ta, Tb, Tc, u_scalar)
  264. net4 = TensorAssignWithBoolTensorIndex2Error()
  265. with pytest.raises(AttributeError):
  266. net4(Ta, u_tensor)
  267. with pytest.raises(AttributeError):
  268. net4(Ta, u_scalar)
  269. test_cases = [
  270. ('TensorAssignWithTupleInteger', {
  271. 'block': TensorAssignWithTupleInteger(),
  272. 'desc_inputs': [Ta, u_tensor],
  273. }),
  274. ('TensorAssignWithInteger', {
  275. 'block': TensorAssignWithInteger(),
  276. 'desc_inputs': [Ta, u_tensor],
  277. }),
  278. ('TensorAssignWithSlice', {
  279. 'block': TensorAssignWithSlice(),
  280. 'desc_inputs': [Ta, u_tensor],
  281. }),
  282. ('TensorAssignWithSlice2', {
  283. 'block': TensorAssignWithSlice2(),
  284. 'desc_inputs': [t_1d, u_tensor],
  285. }),
  286. ('TensorAssignWithBoolTensorIndex', {
  287. 'block': TensorAssignWithBoolTensorIndex(),
  288. 'desc_inputs': [Ta, Tb, Tc, u_tensor, u_scalar],
  289. }),
  290. ('TensorAssignWithBoolTensorIndex2', {
  291. 'block': TensorAssignWithBoolTensorIndex2(),
  292. 'desc_inputs': [Ta, u_tensor, u_scalar],
  293. }),
  294. ('SlicePositive', {
  295. 'block': NetWorkSlicePositive(),
  296. 'desc_inputs': [Tensor(np.ones([6, 8, 10], np.int32))],
  297. }),
  298. ('SliceReduceDimension', {
  299. 'block': NetWorkReduceDimension(),
  300. 'desc_inputs': [Tensor(np.ones([6, 8, 10], np.int32))],
  301. }),
  302. ('SliceNegative', {
  303. 'block': NetWorkStepNegative(),
  304. 'desc_inputs': [Tensor(np.ones([6, 8, 10], np.int32))],
  305. }),
  306. ('SliceReduceToScalar', {
  307. 'block': NetWorkReduceToScalar(),
  308. 'desc_inputs': [Tensor(np.ones([6, 8, 10], np.int32))],
  309. }),
  310. ('TensorSliceEllipsis', {
  311. 'block': NetWorkSliceEllipsis(),
  312. 'desc_inputs': [Tensor(np.ones([6, 7, 8, 9], np.int32))],
  313. }),
  314. ]
  315. @mindspore_test(pipeline_for_compile_forward_ge_graph_for_case_by_case_config)
  316. def test_compile():
  317. context.set_context(mode=context.GRAPH_MODE)
  318. return test_cases
  319. def test_tensor_slice_reduce_out_of_bounds_neg():
  320. class NetWork(Cell):
  321. def __init__(self):
  322. super(NetWork, self).__init__()
  323. self.tensor_ret = Tensor(np.array(9, np.int32))
  324. def construct(self, tensor):
  325. ret = tensor[-7, 3, 4]
  326. return ret
  327. input_tensor = Tensor(np.ones([6, 8, 10], np.int32))
  328. net = NetWork()
  329. with pytest.raises(ValueError) as ex:
  330. net(input_tensor)
  331. assert "For 'StridedSlice' the `begin[0]` should be an int and must greater or equal to -6, but got `-7`" in str(ex.value)
  332. def test_tensor_slice_reduce_out_of_bounds_positive():
  333. class NetWork(Cell):
  334. def __init__(self):
  335. super(NetWork, self).__init__()
  336. self.tensor_ret = Tensor(np.array(9, np.int32))
  337. def construct(self, tensor):
  338. ret = tensor[6, 3, 4]
  339. return ret
  340. input_tensor = Tensor(np.ones([6, 8, 10], np.int32))
  341. net = NetWork()
  342. with pytest.raises(ValueError) as ex:
  343. net(input_tensor)
  344. assert "For 'StridedSlice' the `begin[0]` should be an int and must less than 6, but got `6`" in str(ex.value)