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 12 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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. from mindspore.ops.signature import sig_rw, sig_dtype, make_sig
  20. import mindspore as ms
  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.operations import _inner_ops as inner
  26. from mindspore.ops import prim_attr_register
  27. from mindspore.ops.primitive import PrimitiveWithInfer
  28. import mindspore.context as context
  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 RangeNet(Cell):
  245. def __init__(self):
  246. super(RangeNet, self).__init__()
  247. self.range_ops = inner.Range(1.0, 8.0, 2.0)
  248. def construct(self, x):
  249. return self.range_ops(x)
  250. test_case_array_ops = [
  251. ('CustNet1', {
  252. 'block': CustNet1(),
  253. 'desc_inputs': []}),
  254. ('CustNet2', {
  255. 'block': CustNet2(),
  256. 'desc_inputs': []}),
  257. ('CustNet3', {
  258. 'block': CustNet3(),
  259. 'desc_inputs': []}),
  260. ('MathBinaryNet1', {
  261. 'block': MathBinaryNet1(),
  262. 'desc_inputs': [Tensor(np.ones([2, 2]), dtype=ms.int32)]}),
  263. ('MathBinaryNet2', {
  264. 'block': MathBinaryNet2(),
  265. 'desc_inputs': [Tensor(np.ones([2, 2]), dtype=ms.int32)]}),
  266. ('BatchToSpaceNet', {
  267. 'block': BatchToSpaceNet(),
  268. 'desc_inputs': [Tensor(np.array([[[[1]]], [[[2]]], [[[3]]], [[[4]]]]).astype(np.float16))]}),
  269. ('SpaceToBatchNet', {
  270. 'block': SpaceToBatchNet(),
  271. 'desc_inputs': [Tensor(np.array([[[[1, 2], [3, 4]]]]).astype(np.float16))]}),
  272. ('PackNet', {
  273. 'block': PackNet(),
  274. 'desc_inputs': [Tensor(np.array([[[1, 2], [3, 4]]]).astype(np.float16))]}),
  275. ('UnpackNet', {
  276. 'block': UnpackNet(),
  277. 'desc_inputs': [Tensor(np.array([[1, 2], [3, 4]]).astype(np.float16))]}),
  278. ('SpaceToDepthNet', {
  279. 'block': SpaceToDepthNet(),
  280. 'desc_inputs': [Tensor(np.random.rand(1, 3, 2, 2).astype(np.float16))]}),
  281. ('DepthToSpaceNet', {
  282. 'block': DepthToSpaceNet(),
  283. 'desc_inputs': [Tensor(np.random.rand(1, 12, 1, 1).astype(np.float16))]}),
  284. ('SpaceToBatchNDNet', {
  285. 'block': SpaceToBatchNDNet(),
  286. 'desc_inputs': [Tensor(np.random.rand(1, 1, 2, 2).astype(np.float16))]}),
  287. ('BatchToSpaceNDNet', {
  288. 'block': BatchToSpaceNDNet(),
  289. 'desc_inputs': [Tensor(np.random.rand(4, 1, 1, 1).astype(np.float16))]}),
  290. ('RangeNet', {
  291. 'block': RangeNet(),
  292. 'desc_inputs': [Tensor(np.array([1, 2, 3, 2]), ms.int32)]}),
  293. ]
  294. test_case_lists = [test_case_array_ops]
  295. test_exec_case = functools.reduce(lambda x, y: x + y, test_case_lists)
  296. # use -k to select certain testcast
  297. # pytest tests/python/ops/test_ops.py::test_backward -k LayerNorm
  298. @non_graph_engine
  299. @mindspore_test(pipeline_for_compile_forward_ge_graph_for_case_by_case_config)
  300. def test_exec():
  301. context.set_context(mode=context.GRAPH_MODE)
  302. return test_exec_case
  303. raise_set = [
  304. ('Squeeze_1_Error', {
  305. 'block': (lambda x: P.Squeeze(axis=1.2), {'exception': TypeError}),
  306. 'desc_inputs': [Tensor(np.ones(shape=[3, 1, 5]))]}),
  307. ('Squeeze_2_Error', {
  308. 'block': (lambda x: P.Squeeze(axis=((1.2, 1.3))), {'exception': TypeError}),
  309. 'desc_inputs': [Tensor(np.ones(shape=[3, 1, 5]))]}),
  310. ('ReduceSum_Error', {
  311. 'block': (lambda x: P.ReduceSum(keep_dims=1), {'exception': TypeError}),
  312. 'desc_inputs': [Tensor(np.ones(shape=[3, 1, 5]))]}),
  313. ]
  314. @mindspore_test(pipeline_for_verify_exception_for_case_by_case_config)
  315. def test_check_exception():
  316. return raise_set