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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. import os
  10. import platform
  11. import numpy as np
  12. import pytest
  13. from utils import opr_test
  14. import megengine.functional as F
  15. from megengine import tensor
  16. from megengine.core._trace_option import use_tensor_shape
  17. from megengine.core.tensor.utils import astensor1d
  18. from megengine.distributed.helper import get_device_count_by_fork
  19. def test_eye():
  20. dtype = np.float32
  21. cases = [{"input": [10, 20]}, {"input": [20, 30]}]
  22. for case in cases:
  23. np.testing.assert_allclose(
  24. F.eye(case["input"], dtype=dtype).numpy(),
  25. np.eye(*case["input"]).astype(dtype),
  26. )
  27. def test_concat():
  28. def get_data_shape(length: int):
  29. return (length, 2, 3)
  30. data1 = np.random.random(get_data_shape(5)).astype("float32")
  31. data2 = np.random.random(get_data_shape(6)).astype("float32")
  32. data3 = np.random.random(get_data_shape(7)).astype("float32")
  33. def run(data1, data2):
  34. return F.concat([data1, data2])
  35. cases = [{"input": [data1, data2]}, {"input": [data1, data3]}]
  36. opr_test(cases, run, ref_fn=lambda x, y: np.concatenate([x, y]))
  37. def test_concat_device():
  38. data1 = tensor(np.random.random((3, 2, 2)).astype("float32"), device="cpu0")
  39. data2 = tensor(np.random.random((2, 2, 2)).astype("float32"), device="cpu1")
  40. out = F.concat([data1, data2], device="cpu0")
  41. assert str(out.device).split(":")[0] == "cpu0"
  42. def test_stack():
  43. data1 = np.random.random((3, 2, 2)).astype("float32")
  44. data2 = np.random.random((3, 2, 2)).astype("float32")
  45. data3 = np.random.random((3, 2, 2)).astype("float32")
  46. cases = [{"input": [data1, data2]}, {"input": [data1, data3]}]
  47. for ai in range(3):
  48. def run(data1, data2):
  49. return F.stack([data1, data2], axis=ai)
  50. opr_test(cases, run, ref_fn=lambda x, y: np.stack([x, y], axis=ai))
  51. def test_split():
  52. data = np.random.random((2, 3, 4, 5)).astype(np.float32)
  53. mge_out1 = F.split(tensor(data), 2, axis=3)
  54. mge_out2 = F.split(tensor(data), [3, 5], axis=3)
  55. np_out = np.split(data, [3, 5], axis=3)
  56. np.testing.assert_equal(mge_out1[0].numpy(), mge_out2[0].numpy())
  57. np.testing.assert_equal(mge_out1[0].numpy(), np_out[0])
  58. def test_reshape():
  59. x = np.arange(6, dtype="float32")
  60. xx = tensor(x)
  61. y = x.reshape(1, 2, 3)
  62. for shape in [
  63. (1, 2, 3),
  64. (1, -1, 3),
  65. (1, tensor(-1), 3),
  66. np.array([1, -1, 3], dtype="int32"),
  67. tensor([1, -1, 3]),
  68. ]:
  69. yy = F.reshape(xx, shape)
  70. np.testing.assert_equal(yy.numpy(), y)
  71. def test_squeeze():
  72. x = np.arange(6, dtype="float32").reshape(1, 2, 3, 1)
  73. xx = tensor(x)
  74. for axis in [None, 3, -4, (3, -4)]:
  75. y = np.squeeze(x, axis)
  76. yy = F.squeeze(xx, axis)
  77. np.testing.assert_equal(y, yy.numpy())
  78. def test_expand_dims():
  79. x = np.arange(6, dtype="float32").reshape(2, 3)
  80. xx = tensor(x)
  81. for axis in [2, -3, (3, -4), (1, -4)]:
  82. y = np.expand_dims(x, axis)
  83. yy = F.expand_dims(xx, axis)
  84. np.testing.assert_equal(y, yy.numpy())
  85. def test_elemwise_dtype_promotion():
  86. x = np.random.rand(2, 3).astype("float32")
  87. y = np.random.rand(1, 3).astype("float16")
  88. xx = tensor(x)
  89. yy = tensor(y)
  90. z = xx * yy
  91. np.testing.assert_equal(z.numpy(), x * y)
  92. z = xx + y
  93. np.testing.assert_equal(z.numpy(), x + y)
  94. z = x - yy
  95. np.testing.assert_equal(z.numpy(), x - y)
  96. def test_linspace():
  97. cases = [
  98. {"input": [1, 9, 9]},
  99. {"input": [3, 10, 8]},
  100. ]
  101. opr_test(
  102. cases,
  103. F.linspace,
  104. ref_fn=lambda start, end, step: np.linspace(start, end, step, dtype=np.float32),
  105. )
  106. cases = [
  107. {"input": [9, 1, 9]},
  108. {"input": [10, 3, 8]},
  109. ]
  110. opr_test(
  111. cases,
  112. F.linspace,
  113. ref_fn=lambda start, end, step: np.linspace(start, end, step, dtype=np.float32),
  114. )
  115. def test_arange():
  116. cases = [
  117. {"input": [1, 9, 1]},
  118. {"input": [2, 10, 2]},
  119. ]
  120. opr_test(
  121. cases,
  122. F.arange,
  123. ref_fn=lambda start, end, step: np.arange(start, end, step, dtype=np.float32),
  124. )
  125. cases = [
  126. {"input": [9, 1, -1]},
  127. {"input": [10, 2, -2]},
  128. ]
  129. opr_test(
  130. cases,
  131. F.arange,
  132. ref_fn=lambda start, end, step: np.arange(start, end, step, dtype=np.float32),
  133. )
  134. cases = [
  135. {"input": [9.3, 1.2, -0.5]},
  136. {"input": [10.3, 2.1, -1.7]},
  137. ]
  138. opr_test(
  139. cases,
  140. F.arange,
  141. ref_fn=lambda start, end, step: np.arange(start, end, step, dtype=np.float32),
  142. )
  143. def test_round():
  144. data1_shape = (15,)
  145. data2_shape = (25,)
  146. data1 = np.random.random(data1_shape).astype(np.float32)
  147. data2 = np.random.random(data2_shape).astype(np.float32)
  148. cases = [{"input": data1}, {"input": data2}]
  149. opr_test(cases, F.round, ref_fn=np.round)
  150. def test_flatten():
  151. data0_shape = (2, 3, 4, 5)
  152. data1_shape = (4, 5, 6, 7)
  153. data0 = np.random.random(data0_shape).astype(np.float32)
  154. data1 = np.random.random(data1_shape).astype(np.float32)
  155. def compare_fn(x, y):
  156. assert x.shape[0] == y
  157. output0 = (2 * 3 * 4 * 5,)
  158. output1 = (4 * 5 * 6 * 7,)
  159. cases = [
  160. {"input": data0, "output": output0},
  161. {"input": data1, "output": output1},
  162. ]
  163. opr_test(cases, F.flatten, compare_fn=compare_fn)
  164. output0 = (2, 3 * 4 * 5)
  165. output1 = (4, 5 * 6 * 7)
  166. cases = [
  167. {"input": data0, "output": output0},
  168. {"input": data1, "output": output1},
  169. ]
  170. opr_test(cases, F.flatten, compare_fn=compare_fn, start_axis=1)
  171. output0 = (2, 3, 4 * 5)
  172. output1 = (4, 5, 6 * 7)
  173. cases = [
  174. {"input": data0, "output": output0},
  175. {"input": data1, "output": output1},
  176. ]
  177. opr_test(cases, F.flatten, compare_fn=compare_fn, start_axis=2)
  178. output0 = (2, 3 * 4, 5)
  179. output1 = (4, 5 * 6, 7)
  180. cases = [
  181. {"input": data0, "output": output0},
  182. {"input": data1, "output": output1},
  183. ]
  184. opr_test(cases, F.flatten, compare_fn=compare_fn, start_axis=1, end_axis=2)
  185. def test_broadcast():
  186. input1_shape = (20, 30)
  187. output1_shape = (30, 20, 30)
  188. data1 = np.random.random(input1_shape).astype(np.float32)
  189. input2_shape = (10, 1)
  190. output2_shape = (20, 10, 20)
  191. data2 = np.random.random(input2_shape).astype(np.float32)
  192. def compare_fn(x, y):
  193. assert x.shape[0] == y
  194. cases = [
  195. {"input": [data1, output1_shape], "output": output1_shape},
  196. {"input": [data2, output2_shape], "output": output2_shape},
  197. ]
  198. opr_test(cases, F.broadcast_to, compare_fn=compare_fn)
  199. x = F.ones((2, 1, 3))
  200. with pytest.raises(ValueError):
  201. F.broadcast_to(x, (2, 3, 4))
  202. with pytest.raises(ValueError):
  203. F.broadcast_to(x, (4, 1, 3))
  204. with pytest.raises(ValueError):
  205. F.broadcast_to(x, (1, 3))
  206. def test_utils_astensor1d():
  207. reference = tensor(0)
  208. # literal
  209. x = [1, 2, 3]
  210. for dtype in [None, "float32"]:
  211. xx = astensor1d(x, reference, dtype=dtype)
  212. assert type(xx) is tensor
  213. np.testing.assert_equal(xx.numpy(), x)
  214. # numpy array
  215. x = np.asarray([1, 2, 3], dtype="int32")
  216. for dtype in [None, "float32"]:
  217. xx = astensor1d(x, reference, dtype=dtype)
  218. assert type(xx) is tensor
  219. np.testing.assert_equal(xx.numpy(), x.astype(dtype) if dtype else x)
  220. # tensor
  221. x = tensor([1, 2, 3], dtype="int32")
  222. for dtype in [None, "float32"]:
  223. xx = astensor1d(x, reference, dtype=dtype)
  224. assert type(xx) is tensor
  225. np.testing.assert_equal(xx.numpy(), x.numpy())
  226. # mixed
  227. x = [1, tensor(2), 3]
  228. for dtype in [None, "float32"]:
  229. xx = astensor1d(x, reference, dtype=dtype)
  230. assert type(xx) is tensor
  231. np.testing.assert_equal(xx.numpy(), [1, 2, 3])
  232. def test_device():
  233. x = tensor([1, 2, 3], dtype="float32")
  234. y1 = F.eye(x.shape, dtype="float32")
  235. y2 = F.eye(x.shape, dtype="float32", device=None)
  236. np.testing.assert_almost_equal(y1.numpy(), y2.numpy())
  237. y3 = F.eye(x.shape, dtype="float32", device="xpux")
  238. y4 = F.eye(x.shape, dtype="float32", device=x.device.to_c())
  239. np.testing.assert_almost_equal(y3.numpy(), y4.numpy())
  240. y5 = F.full((3, 2), 4, device=x.device)
  241. y6 = F.full((3, 2), 4, device="xpux")
  242. np.testing.assert_almost_equal(y5.numpy(), y6.numpy())
  243. def test_identity():
  244. x = tensor(np.random.random((5, 10)).astype(np.float32))
  245. y = F.identity(x)
  246. np.testing.assert_equal(y.numpy(), x)
  247. def copy_test(dst, src):
  248. data = np.random.random((2, 3)).astype(np.float32)
  249. x = tensor(data, device=src)
  250. y = F.copy(x, dst)
  251. assert np.allclose(data, y.numpy())
  252. z = x.to(dst)
  253. assert np.allclose(data, z.numpy())
  254. @pytest.mark.skipif(
  255. platform.system() == "Darwin", reason="do not imp GPU mode at macos now"
  256. )
  257. @pytest.mark.skipif(
  258. platform.system() == "Windows", reason="do not imp GPU mode at Windows now"
  259. )
  260. @pytest.mark.skipif(get_device_count_by_fork("gpu") == 0, reason="CUDA is disabled")
  261. def test_copy_h2d():
  262. copy_test("cpu0", "gpu0")
  263. @pytest.mark.skipif(
  264. platform.system() == "Darwin", reason="do not imp GPU mode at macos now"
  265. )
  266. @pytest.mark.skipif(
  267. platform.system() == "Windows", reason="do not imp GPU mode at Windows now"
  268. )
  269. @pytest.mark.skipif(get_device_count_by_fork("gpu") == 0, reason="CUDA is disabled")
  270. def test_copy_d2h():
  271. copy_test("gpu0", "cpu0")
  272. @pytest.mark.skipif(
  273. platform.system() == "Darwin", reason="do not imp GPU mode at macos now"
  274. )
  275. @pytest.mark.skipif(
  276. platform.system() == "Windows", reason="do not imp GPU mode at Windows now"
  277. )
  278. @pytest.mark.skipif(get_device_count_by_fork("gpu") < 2, reason="need more gpu device")
  279. def test_copy_d2d():
  280. copy_test("gpu0", "gpu1")
  281. copy_test("gpu0:0", "gpu0:1")

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台