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