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.py 12 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. """
  16. @File : test_tensor.py
  17. @Author:
  18. @Date : 2019-03-14
  19. @Desc : test mindspore tensor's operation
  20. """
  21. import numpy as np
  22. import pytest
  23. import mindspore as ms
  24. import mindspore.common.api as me
  25. import mindspore.nn as nn
  26. from mindspore.common.parameter import Parameter
  27. from mindspore.common.initializer import initializer
  28. from ..ut_filter import non_graph_engine
  29. ndarr = np.ones((2, 3))
  30. def test_tensor_flatten():
  31. with pytest.raises(AttributeError):
  32. lst = [1, 2, 3, 4,]
  33. tensor_list = ms.Tensor(lst, ms.float32)
  34. tensor_list = tensor_list.Flatten()
  35. print(tensor_list)
  36. def test_tensor_list():
  37. lst = [[1.0, 2.0, 1.0], [1.0, 10.0, 9.0]]
  38. tensor_list = ms.Tensor(lst, ms.float32)
  39. print(tensor_list)
  40. def test_tensor():
  41. """test_tensor"""
  42. t1 = ms.Tensor(ndarr)
  43. assert isinstance(t1, ms.Tensor)
  44. assert t1.dtype() == ms.float64
  45. t2 = ms.Tensor(np.zeros([1, 2, 3]), ms.float32)
  46. assert isinstance(t2, ms.Tensor)
  47. assert t2.shape() == (1, 2, 3)
  48. assert t2.dtype() == ms.float32
  49. t3 = ms.Tensor(0.1)
  50. assert isinstance(t3, ms.Tensor)
  51. assert t3.dtype() == ms.float64
  52. t4 = ms.Tensor(1)
  53. assert isinstance(t4, ms.Tensor)
  54. assert t4.dtype() == ms.int64
  55. def test_tensor_type_float16():
  56. t_float16 = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float16))
  57. assert isinstance(t_float16, ms.Tensor)
  58. assert t_float16.shape() == (2, 3)
  59. assert t_float16.dtype() == ms.float16
  60. def test_tensor_type_float32():
  61. t_float32 = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32))
  62. assert isinstance(t_float32, ms.Tensor)
  63. assert t_float32.shape() == (2, 3)
  64. assert t_float32.dtype() == ms.float32
  65. def test_tensor_type_float32_user_define():
  66. t = ms.Tensor(np.zeros([1, 2, 3]), ms.float32)
  67. assert isinstance(t, ms.Tensor)
  68. assert t.shape() == (1, 2, 3)
  69. assert t.dtype() == ms.float32
  70. def test_tensor_type_float64():
  71. t = ms.Tensor([[1.0, 2, 3], [4, 5, 6]])
  72. assert isinstance(t, ms.Tensor)
  73. assert t.shape() == (2, 3)
  74. assert t.dtype() == ms.float64
  75. t_zero = ms.Tensor(np.zeros([1, 2, 3]))
  76. assert isinstance(t_zero, ms.Tensor)
  77. assert t_zero.shape() == (1, 2, 3)
  78. assert t_zero.dtype() == ms.float64
  79. def test_tensor_type_float64_user_define():
  80. t = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=float))
  81. assert isinstance(t, ms.Tensor)
  82. assert t.shape() == (2, 3)
  83. assert t.dtype() == ms.float64
  84. t_float64 = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]]), ms.float64)
  85. assert isinstance(t_float64, ms.Tensor)
  86. assert t_float64.shape() == (2, 3)
  87. assert t_float64.dtype() == ms.float64
  88. def test_tensor_type_bool():
  89. # init a tensor with bool type
  90. ts_bool_array = ms.Tensor(np.zeros([2, 3], np.bool), ms.bool_)
  91. assert isinstance(ts_bool_array, ms.Tensor)
  92. assert ts_bool_array.dtype() == ms.bool_
  93. t_bool = ms.Tensor(True)
  94. assert isinstance(t_bool, ms.Tensor)
  95. assert t_bool.dtype() == ms.bool_
  96. t_bool_array = ms.Tensor(np.array([[True, False, True], [False, False, False]]))
  97. assert isinstance(t_bool_array, ms.Tensor)
  98. assert t_bool_array.shape() == (2, 3)
  99. assert t_bool_array.dtype() == ms.bool_
  100. def test_tensor_type_int8():
  101. t_int8_array = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int8))
  102. assert isinstance(t_int8_array, ms.Tensor)
  103. assert t_int8_array.shape() == (2, 3)
  104. assert t_int8_array.dtype() == ms.int8
  105. def test_tensor_type_int16():
  106. t_int16_array = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int16))
  107. assert isinstance(t_int16_array, ms.Tensor)
  108. assert t_int16_array.shape() == (2, 3)
  109. assert t_int16_array.dtype() == ms.int16
  110. def test_tensor_type_int32():
  111. t_int = ms.Tensor([[1, 2, 3], [4, 5, 6]])
  112. assert isinstance(t_int, ms.Tensor)
  113. assert t_int.shape() == (2, 3)
  114. assert t_int.dtype() == ms.int64
  115. t_int_array = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32))
  116. assert isinstance(t_int_array, ms.Tensor)
  117. assert t_int_array.shape() == (2, 3)
  118. assert t_int_array.dtype() == ms.int32
  119. def test_tensor_type_int64():
  120. t_int64 = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int64))
  121. assert isinstance(t_int64, ms.Tensor)
  122. assert t_int64.shape() == (2, 3)
  123. assert t_int64.dtype() == ms.int64
  124. def test_tensor_type_uint8():
  125. t_uint8_array = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint8))
  126. assert isinstance(t_uint8_array, ms.Tensor)
  127. assert t_uint8_array.shape() == (2, 3)
  128. assert t_uint8_array.dtype() == ms.uint8
  129. def test_tensor_type_uint16():
  130. t_uint16_array = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint16))
  131. assert isinstance(t_uint16_array, ms.Tensor)
  132. assert t_uint16_array.shape() == (2, 3)
  133. assert t_uint16_array.dtype() == ms.uint16
  134. def test_tensor_type_uint32():
  135. t_uint32_array = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint32))
  136. assert isinstance(t_uint32_array, ms.Tensor)
  137. assert t_uint32_array.shape() == (2, 3)
  138. assert t_uint32_array.dtype() == ms.uint32
  139. def test_tensor_type_uint64():
  140. t_uint64 = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint64))
  141. assert isinstance(t_uint64, ms.Tensor)
  142. assert t_uint64.shape() == (2, 3)
  143. assert t_uint64.dtype() == ms.uint64
  144. def test_set_type():
  145. t = ms.Tensor(ndarr)
  146. t.set_dtype(ms.float32)
  147. assert t.dtype() == ms.float32
  148. @non_graph_engine
  149. def test_add():
  150. x = ms.Tensor(ndarr)
  151. y = ms.Tensor(ndarr)
  152. z = x + y
  153. assert isinstance(z, ms.Tensor)
  154. @non_graph_engine
  155. def test_sub():
  156. x = ms.Tensor(ndarr)
  157. y = ms.Tensor(ndarr)
  158. z = x - y
  159. assert isinstance(z, ms.Tensor)
  160. @non_graph_engine
  161. def test_div():
  162. x = ms.Tensor(np.array([[2,6,10],[12, 4, 8]]).astype(np.float32))
  163. y = ms.Tensor(np.array([[2,2,5],[6, 1, 2]]).astype(np.float32))
  164. z = x / y
  165. z2 = x / 2
  166. assert isinstance(z, ms.Tensor)
  167. assert isinstance(z2, ms.Tensor)
  168. @non_graph_engine
  169. def test_parameter():
  170. x = Parameter(initializer(1, [1], ms.float32), name="beta1_power")
  171. z = x / 2
  172. print(z)
  173. class Net(nn.Cell):
  174. """Net definition"""
  175. def __init__(self, dim):
  176. super(Net, self).__init__()
  177. self.dim = dim
  178. def construct(self, input_x):
  179. return input_x
  180. @non_graph_engine
  181. def test_return_tensor():
  182. """test_return_tensor"""
  183. net = Net(0)
  184. input_data = ms.Tensor(np.array([[1.2, 2.1], [2.2, 3.2]]).astype('float32'))
  185. input_data.set_dtype(ms.float32)
  186. exe = me._executor
  187. exe.compile(net, input_data)
  188. tensor_ = exe(net, input_data)
  189. # get shape
  190. shape_ = tensor_.shape()
  191. print("shape = ", shape_)
  192. # get type
  193. type_ = tensor_.dtype()
  194. print("type = ", type_)
  195. # get value
  196. value_ = tensor_.asnumpy()
  197. print("numpy value = ", value_)
  198. def test_tensor_contiguous():
  199. """test_tensor_contiguous"""
  200. input_c = np.arange(6).reshape(2, 3)
  201. input_f = input_c.T
  202. np.ascontiguousarray(input_c, dtype=np.float32)
  203. assert True, input_c.flags['C_CONTIGUOUS']
  204. print("input_f flags = ", input_f.flags)
  205. assert True, input_f.flags['F_CONTIGUOUS']
  206. tensor_f_float32 = ms.Tensor(input_f)
  207. rt_f = tensor_f_float32.asnumpy()
  208. assert True, rt_f.flags['C_CONTIGUOUS']
  209. print("rt_f flags = ", rt_f.flags)
  210. def test_tensor_contiguous2():
  211. input_data = np.random.randn(32, 112, 112, 3).astype(np.float32)
  212. input_me = input_data.transpose(0, 3, 1, 2)
  213. print("input_me flags = ", input_me.flags)
  214. tensor_f_float32 = ms.Tensor(input_me)
  215. out_f = tensor_f_float32.asnumpy()
  216. print("out_f flags = ", out_f.flags)
  217. def test_tensor_input_string():
  218. with pytest.raises(TypeError):
  219. input_data = 'ccc'
  220. ms.Tensor(input_data)
  221. def test_tensor_input_tuple_string():
  222. with pytest.raises(TypeError):
  223. input_data = (2, 3, '4', 5)
  224. ms.Tensor(input_data)
  225. def test_tensor_input_list_string():
  226. with pytest.raises(TypeError):
  227. input_data = [[2, 3, '4', 5], [1, 2, 3, 4]]
  228. ms.Tensor(input_data)
  229. def test_tensor_input_none():
  230. with pytest.raises(TypeError):
  231. input_data = None
  232. ms.Tensor(input_data, np.int64)
  233. # pylint: disable=no-value-for-parameter
  234. def test_tensor_input_empty():
  235. with pytest.raises(TypeError):
  236. ms.Tensor()
  237. def test_tensor_input_ndarray_str():
  238. with pytest.raises(TypeError):
  239. inp = np.array(["88", 2, 4])
  240. ms.Tensor(inp)
  241. def test_tensor_input_ndarray_bool():
  242. inp = np.array([True, 2, 4])
  243. ms.Tensor(inp)
  244. inp = np.array([False, 2, 4])
  245. ms.Tensor(inp)
  246. def test_tensor_input_ndarray_complex():
  247. with pytest.raises(TypeError):
  248. inp = np.array([20j, 2, 4])
  249. ms.Tensor(inp)
  250. def test_tensor_input_ndarray_none():
  251. with pytest.raises(TypeError):
  252. inp = np.array([None, 2, 4])
  253. ms.Tensor(inp)
  254. def test_tensor_input_ndarray_dict():
  255. with pytest.raises(TypeError):
  256. inp = {'a': 6, 'b': 7}
  257. ms.Tensor(inp)
  258. def test_tensor_input_np_nan():
  259. with pytest.raises(TypeError):
  260. input_data = (1, 2, 3, np.nan)
  261. ms.Tensor(input_data, np.int64)
  262. def test_tensor_input_tuple_inf():
  263. with pytest.raises(TypeError):
  264. input_data = (1, 2, 3, float("inf"))
  265. ms.Tensor(input_data, np.int64)
  266. def test_tensor_input_dict():
  267. with pytest.raises(TypeError):
  268. input_data = {'a': 6, 'b': 7}
  269. ms.Tensor(input_data, np.int64)
  270. def test_tensor_input_complex():
  271. with pytest.raises(TypeError):
  272. input_data = (1, 2j, 3)
  273. ms.Tensor(input_data, np.int64)
  274. def test_tensor_dtype_np_float():
  275. with pytest.raises(TypeError):
  276. input_data = np.random.randn(32, 112, 112, 3).astype(np.float)
  277. ms.Tensor(input_data, np.float)
  278. def test_tensor_dtype_np_float16():
  279. with pytest.raises(TypeError):
  280. input_data = np.random.randn(32, 112, 112, 3).astype(np.float16)
  281. ms.Tensor(input_data, np.float16)
  282. def test_tensor_dtype_np_float32():
  283. with pytest.raises(TypeError):
  284. input_data = np.random.randn(32, 112, 112, 3).astype(np.float32)
  285. ms.Tensor(input_data, np.float32)
  286. def test_tensor_dtype_np_float64():
  287. with pytest.raises(TypeError):
  288. input_data = np.random.randn(32, 112, 112, 3).astype(np.float64)
  289. ms.Tensor(input_data, np.float64)
  290. def test_tensor_dtype_np_int():
  291. with pytest.raises(TypeError):
  292. input_data = np.random.randn(32, 112, 112, 3).astype(np.int)
  293. ms.Tensor(input_data, np.int)
  294. def test_tensor_dtype_np_int8():
  295. with pytest.raises(TypeError):
  296. input_data = np.random.randn(32, 112, 112, 3).astype(np.int8)
  297. ms.Tensor(input_data, np.int8)
  298. def test_tensor_dtype_np_int16():
  299. with pytest.raises(TypeError):
  300. input_data = np.random.randn(32, 112, 112, 3).astype(np.int16)
  301. ms.Tensor(input_data, np.int16)
  302. def test_tensor_dtype_np_int32():
  303. with pytest.raises(TypeError):
  304. input_data = np.random.randn(32, 112, 112, 3).astype(np.int32)
  305. ms.Tensor(input_data, np.int32)
  306. def test_tensor_dtype_np_int64():
  307. with pytest.raises(TypeError):
  308. input_data = np.random.randn(32, 112, 112, 3).astype(np.int64)
  309. ms.Tensor(input_data, np.int64)
  310. def test_tensor_dtype_fp32_to_bool():
  311. with pytest.raises(RuntimeError):
  312. input = np.random.randn(2, 3, 4, 5).astype(np.float32)
  313. input = ms.Tensor(input)
  314. input_me = ms.Tensor(input, dtype=ms.bool_)