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

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

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