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_array_ops.py 13 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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 array ops """
  16. import functools
  17. import numpy as np
  18. import pytest
  19. import mindspore as ms
  20. import mindspore.context as context
  21. from mindspore import Tensor
  22. from mindspore.common import dtype as mstype
  23. from mindspore.nn import Cell
  24. from mindspore.ops import operations as P
  25. from mindspore.ops import prim_attr_register
  26. from mindspore.ops.operations import _inner_ops as inner
  27. from mindspore.ops.primitive import PrimitiveWithInfer
  28. from mindspore.ops.signature import sig_rw, sig_dtype, make_sig
  29. from ..ut_filter import non_graph_engine
  30. from ....mindspore_test_framework.mindspore_test import mindspore_test
  31. from ....mindspore_test_framework.pipeline.forward.compile_forward \
  32. import pipeline_for_compile_forward_ge_graph_for_case_by_case_config
  33. from ....mindspore_test_framework.pipeline.forward.verify_exception \
  34. import pipeline_for_verify_exception_for_case_by_case_config
  35. context.set_context(mode=context.PYNATIVE_MODE)
  36. def test_expand_dims():
  37. input_tensor = Tensor(np.array([[2, 2], [2, 2]]))
  38. expand_dims = P.ExpandDims()
  39. output = expand_dims(input_tensor, 0)
  40. assert output.asnumpy().shape == (1, 2, 2)
  41. def test_cast():
  42. input_np = np.random.randn(2, 3, 4, 5).astype(np.float32)
  43. input_x = Tensor(input_np)
  44. td = ms.int32
  45. cast = P.Cast()
  46. result = cast(input_x, td)
  47. expect = input_np.astype(np.int32)
  48. assert np.all(result.asnumpy() == expect)
  49. def test_ones():
  50. ones = P.Ones()
  51. output = ones((2, 3), mstype.int32)
  52. assert output.asnumpy().shape == (2, 3)
  53. assert np.sum(output.asnumpy()) == 6
  54. def test_ones_1():
  55. ones = P.Ones()
  56. output = ones(2, mstype.int32)
  57. assert output.asnumpy().shape == (2,)
  58. assert np.sum(output.asnumpy()) == 2
  59. def test_zeros():
  60. zeros = P.Zeros()
  61. output = zeros((2, 3), mstype.int32)
  62. assert output.asnumpy().shape == (2, 3)
  63. assert np.sum(output.asnumpy()) == 0
  64. def test_zeros_1():
  65. zeros = P.Zeros()
  66. output = zeros(2, mstype.int32)
  67. assert output.asnumpy().shape == (2,)
  68. assert np.sum(output.asnumpy()) == 0
  69. @non_graph_engine
  70. def test_reshape():
  71. input_tensor = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]))
  72. shp = (3, 2)
  73. reshape = P.Reshape()
  74. output = reshape(input_tensor, shp)
  75. assert output.asnumpy().shape == (3, 2)
  76. def test_transpose():
  77. input_tensor = Tensor(np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]))
  78. perm = (0, 2, 1)
  79. expect = np.array([[[1, 4], [2, 5], [3, 6]], [[7, 10], [8, 11], [9, 12]]])
  80. transpose = P.Transpose()
  81. output = transpose(input_tensor, perm)
  82. assert np.all(output.asnumpy() == expect)
  83. def test_squeeze():
  84. input_tensor = Tensor(np.ones(shape=[3, 2, 1]))
  85. squeeze = P.Squeeze(2)
  86. output = squeeze(input_tensor)
  87. assert output.asnumpy().shape == (3, 2)
  88. def test_invert_permutation():
  89. invert_permutation = P.InvertPermutation()
  90. x = (3, 4, 0, 2, 1)
  91. output = invert_permutation(x)
  92. expect = (2, 4, 3, 0, 1)
  93. assert np.all(output == expect)
  94. def test_select():
  95. select = P.Select()
  96. cond = Tensor(np.array([[True, False, False], [False, True, True]]))
  97. x = Tensor(np.array([[1, 2, 3], [4, 5, 6]]))
  98. y = Tensor(np.array([[7, 8, 9], [10, 11, 12]]))
  99. output = select(cond, x, y)
  100. expect = np.array([[1, 8, 9], [10, 5, 6]])
  101. assert np.all(output.asnumpy() == expect)
  102. def test_argmin_invalid_output_type():
  103. P.Argmin(-1, mstype.int64)
  104. P.Argmin(-1, mstype.int32)
  105. with pytest.raises(TypeError):
  106. P.Argmin(-1, mstype.float32)
  107. with pytest.raises(TypeError):
  108. P.Argmin(-1, mstype.float64)
  109. with pytest.raises(TypeError):
  110. P.Argmin(-1, mstype.uint8)
  111. with pytest.raises(TypeError):
  112. P.Argmin(-1, mstype.bool_)
  113. class CustomOP(PrimitiveWithInfer):
  114. __mindspore_signature__ = (sig_dtype.T, sig_dtype.T, sig_dtype.T1,
  115. sig_dtype.T1, sig_dtype.T2, sig_dtype.T2,
  116. sig_dtype.T2, sig_dtype.T3, sig_dtype.T4)
  117. @prim_attr_register
  118. def __init__(self):
  119. pass
  120. def __call__(self, p1, p2, p3, p4, p5, p6, p7, p8, p9):
  121. raise NotImplementedError
  122. class CustomOP2(PrimitiveWithInfer):
  123. __mindspore_signature__ = (
  124. make_sig('p1', sig_rw.RW_WRITE, dtype=sig_dtype.T),
  125. make_sig('p2', dtype=sig_dtype.T),
  126. make_sig('p3', dtype=sig_dtype.T),
  127. )
  128. @prim_attr_register
  129. def __init__(self):
  130. pass
  131. def __call__(self, p1, p2, p3):
  132. raise NotImplementedError
  133. class CustNet1(Cell):
  134. def __init__(self):
  135. super(CustNet1, self).__init__()
  136. self.op = CustomOP()
  137. self.t1 = Tensor(np.ones([2, 2]), dtype=ms.int32)
  138. self.t2 = Tensor(np.ones([1, 5]), dtype=ms.float16)
  139. self.int1 = 3
  140. self.float1 = 5.1
  141. def construct(self):
  142. x = self.op(self.t1, self.t1, self.int1,
  143. self.float1, self.int1, self.float1,
  144. self.t2, self.t1, self.int1)
  145. return x
  146. class CustNet2(Cell):
  147. def __init__(self):
  148. super(CustNet2, self).__init__()
  149. self.op = CustomOP2()
  150. self.t1 = Tensor(np.ones([2, 2]), dtype=ms.int32)
  151. self.t2 = Tensor(np.ones([1, 5]), dtype=ms.float16)
  152. self.int1 = 3
  153. def construct(self):
  154. return self.op(self.t1, self.t2, self.int1)
  155. class CustNet3(Cell):
  156. def __init__(self):
  157. super(CustNet3, self).__init__()
  158. self.op = P.ReduceSum()
  159. self.t1 = Tensor(np.ones([2, 2]), dtype=ms.int32)
  160. self.t2 = Tensor(np.ones([1, 5]), dtype=ms.float16)
  161. self.t2 = 1
  162. def construct(self):
  163. return self.op(self.t1, self.t2)
  164. class MathBinaryNet1(Cell):
  165. def __init__(self):
  166. super(MathBinaryNet1, self).__init__()
  167. self.add = P.Add()
  168. self.mul = P.Mul()
  169. self.max = P.Maximum()
  170. self.number = 3
  171. def construct(self, x):
  172. return self.add(x, self.number) + self.mul(x, self.number) + self.max(x, self.number)
  173. class MathBinaryNet2(Cell):
  174. def __init__(self):
  175. super(MathBinaryNet2, self).__init__()
  176. self.less_equal = P.LessEqual()
  177. self.greater = P.Greater()
  178. self.logic_or = P.LogicalOr()
  179. self.logic_and = P.LogicalAnd()
  180. self.number = 3
  181. self.flag = True
  182. def construct(self, x):
  183. ret_less_equal = self.logic_and(self.less_equal(x, self.number), self.flag)
  184. ret_greater = self.logic_or(self.greater(x, self.number), self.flag)
  185. return self.logic_or(ret_less_equal, ret_greater)
  186. class BatchToSpaceNet(Cell):
  187. def __init__(self):
  188. super(BatchToSpaceNet, self).__init__()
  189. block_size = 2
  190. crops = [[0, 0], [0, 0]]
  191. self.batch_to_space = P.BatchToSpace(block_size, crops)
  192. def construct(self, x):
  193. return self.batch_to_space(x)
  194. class SpaceToBatchNet(Cell):
  195. def __init__(self):
  196. super(SpaceToBatchNet, self).__init__()
  197. block_size = 2
  198. paddings = [[0, 0], [0, 0]]
  199. self.space_to_batch = P.SpaceToBatch(block_size, paddings)
  200. def construct(self, x):
  201. return self.space_to_batch(x)
  202. class PackNet(Cell):
  203. def __init__(self):
  204. super(PackNet, self).__init__()
  205. self.stack = P.Stack()
  206. def construct(self, x):
  207. return self.stack((x, x))
  208. class UnpackNet(Cell):
  209. def __init__(self):
  210. super(UnpackNet, self).__init__()
  211. self.unstack = P.Unstack()
  212. def construct(self, x):
  213. return self.unstack(x)
  214. class SpaceToDepthNet(Cell):
  215. def __init__(self):
  216. super(SpaceToDepthNet, self).__init__()
  217. block_size = 2
  218. self.space_to_depth = P.SpaceToDepth(block_size)
  219. def construct(self, x):
  220. return self.space_to_depth(x)
  221. class DepthToSpaceNet(Cell):
  222. def __init__(self):
  223. super(DepthToSpaceNet, self).__init__()
  224. block_size = 2
  225. self.depth_to_space = P.DepthToSpace(block_size)
  226. def construct(self, x):
  227. return self.depth_to_space(x)
  228. class BatchToSpaceNDNet(Cell):
  229. def __init__(self):
  230. super(BatchToSpaceNDNet, self).__init__()
  231. block_shape = [2, 2]
  232. crops = [[0, 0], [0, 0]]
  233. self.batch_to_space_nd = P.BatchToSpaceND(block_shape, crops)
  234. def construct(self, x):
  235. return self.batch_to_space_nd(x)
  236. class SpaceToBatchNDNet(Cell):
  237. def __init__(self):
  238. super(SpaceToBatchNDNet, self).__init__()
  239. block_shape = [2, 2]
  240. paddings = [[0, 0], [0, 0]]
  241. self.space_to_batch_nd = P.SpaceToBatchND(block_shape, paddings)
  242. def construct(self, x):
  243. return self.space_to_batch_nd(x)
  244. class TensorShapeNet(Cell):
  245. def __init__(self):
  246. super(TensorShapeNet, self).__init__()
  247. self.shape = P.TensorShape()
  248. self.unique = P.Unique()
  249. def construct(self, x):
  250. x, _ = self.unique(x)
  251. return self.shape(x)
  252. class RangeNet(Cell):
  253. def __init__(self):
  254. super(RangeNet, self).__init__()
  255. self.range_ops = inner.Range(1.0, 8.0, 2.0)
  256. def construct(self, x):
  257. return self.range_ops(x)
  258. test_case_array_ops = [
  259. ('CustNet1', {
  260. 'block': CustNet1(),
  261. 'desc_inputs': []}),
  262. ('CustNet2', {
  263. 'block': CustNet2(),
  264. 'desc_inputs': []}),
  265. ('CustNet3', {
  266. 'block': CustNet3(),
  267. 'desc_inputs': []}),
  268. ('MathBinaryNet1', {
  269. 'block': MathBinaryNet1(),
  270. 'desc_inputs': [Tensor(np.ones([2, 2]), dtype=ms.int32)]}),
  271. ('MathBinaryNet2', {
  272. 'block': MathBinaryNet2(),
  273. 'desc_inputs': [Tensor(np.ones([2, 2]), dtype=ms.int32)]}),
  274. ('BatchToSpaceNet', {
  275. 'block': BatchToSpaceNet(),
  276. 'desc_inputs': [Tensor(np.array([[[[1]]], [[[2]]], [[[3]]], [[[4]]]]).astype(np.float16))]}),
  277. ('SpaceToBatchNet', {
  278. 'block': SpaceToBatchNet(),
  279. 'desc_inputs': [Tensor(np.array([[[[1, 2], [3, 4]]]]).astype(np.float16))]}),
  280. ('PackNet', {
  281. 'block': PackNet(),
  282. 'desc_inputs': [Tensor(np.array([[[1, 2], [3, 4]]]).astype(np.float16))]}),
  283. ('UnpackNet', {
  284. 'block': UnpackNet(),
  285. 'desc_inputs': [Tensor(np.array([[1, 2], [3, 4]]).astype(np.float16))]}),
  286. ('SpaceToDepthNet', {
  287. 'block': SpaceToDepthNet(),
  288. 'desc_inputs': [Tensor(np.random.rand(1, 3, 2, 2).astype(np.float16))]}),
  289. ('DepthToSpaceNet', {
  290. 'block': DepthToSpaceNet(),
  291. 'desc_inputs': [Tensor(np.random.rand(1, 12, 1, 1).astype(np.float16))]}),
  292. ('SpaceToBatchNDNet', {
  293. 'block': SpaceToBatchNDNet(),
  294. 'desc_inputs': [Tensor(np.random.rand(1, 1, 2, 2).astype(np.float16))]}),
  295. ('BatchToSpaceNDNet', {
  296. 'block': BatchToSpaceNDNet(),
  297. 'desc_inputs': [Tensor(np.random.rand(4, 1, 1, 1).astype(np.float16))]}),
  298. ('RangeNet', {
  299. 'block': RangeNet(),
  300. 'desc_inputs': [Tensor(np.array([1, 2, 3, 2]), ms.int32)]}),
  301. ('TensorShapeNet', {'block': TensorShapeNet(), 'desc_inputs': [Tensor(np.array([1, 2, 3, 2]), ms.int32)]})
  302. ]
  303. test_case_lists = [test_case_array_ops]
  304. test_exec_case = functools.reduce(lambda x, y: x + y, test_case_lists)
  305. # use -k to select certain testcast
  306. # pytest tests/python/ops/test_ops.py::test_backward -k LayerNorm
  307. @non_graph_engine
  308. @mindspore_test(pipeline_for_compile_forward_ge_graph_for_case_by_case_config)
  309. def test_exec():
  310. context.set_context(mode=context.GRAPH_MODE)
  311. return test_exec_case
  312. raise_set = [
  313. ('Squeeze_1_Error', {
  314. 'block': (lambda x: P.Squeeze(axis=1.2), {'exception': TypeError}),
  315. 'desc_inputs': [Tensor(np.ones(shape=[3, 1, 5]))]}),
  316. ('Squeeze_2_Error', {
  317. 'block': (lambda x: P.Squeeze(axis=((1.2, 1.3))), {'exception': TypeError}),
  318. 'desc_inputs': [Tensor(np.ones(shape=[3, 1, 5]))]}),
  319. ('ReduceSum_Error', {
  320. 'block': (lambda x: P.ReduceSum(keep_dims=1), {'exception': TypeError}),
  321. 'desc_inputs': [Tensor(np.ones(shape=[3, 1, 5]))]}),
  322. ('TensorShapeNet_Error', {'block': (lambda x: P.TensorSHape(), {'exception': TypeError}),
  323. 'desc_inputs': [(Tensor(np.ones(shape=[3, 1, 5])), Tensor(np.ones(shape=[3, 1, 5])))]})
  324. ]
  325. @mindspore_test(pipeline_for_verify_exception_for_case_by_case_config)
  326. def test_check_exception():
  327. return raise_set