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

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

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