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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 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. cases = [
  139. {"input": [1, tensor(9), 9]},
  140. {"input": [tensor(1), 9, tensor(9)]},
  141. ]
  142. opr_test(
  143. cases,
  144. F.linspace,
  145. ref_fn=lambda start, end, step: np.linspace(1, 9, 9, dtype=np.float32),
  146. )
  147. def test_arange():
  148. cases = [
  149. {"input": [1, 9, 1]},
  150. {"input": [2, 10, 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, 1, -1]},
  159. {"input": [10, 2, -2]},
  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. cases = [
  167. {"input": [9.3, 1.2, -0.5]},
  168. {"input": [10.3, 2.1, -1.7]},
  169. ]
  170. opr_test(
  171. cases,
  172. F.arange,
  173. ref_fn=lambda start, end, step: np.arange(start, end, step, dtype=np.float32),
  174. )
  175. def test_round():
  176. data1_shape = (15,)
  177. data2_shape = (25,)
  178. data1 = np.random.random(data1_shape).astype(np.float32)
  179. data2 = np.random.random(data2_shape).astype(np.float32)
  180. cases = [{"input": data1}, {"input": data2}]
  181. opr_test(cases, F.round, ref_fn=np.round)
  182. def test_flatten():
  183. data0_shape = (2, 3, 4, 5)
  184. data1_shape = (4, 5, 6, 7)
  185. data0 = np.random.random(data0_shape).astype(np.float32)
  186. data1 = np.random.random(data1_shape).astype(np.float32)
  187. def compare_fn(x, y):
  188. assert x.shape[0] == y
  189. output0 = (2 * 3 * 4 * 5,)
  190. output1 = (4 * 5 * 6 * 7,)
  191. cases = [
  192. {"input": data0, "output": output0},
  193. {"input": data1, "output": output1},
  194. ]
  195. opr_test(cases, F.flatten, compare_fn=compare_fn)
  196. output0 = (2, 3 * 4 * 5)
  197. output1 = (4, 5 * 6 * 7)
  198. cases = [
  199. {"input": data0, "output": output0},
  200. {"input": data1, "output": output1},
  201. ]
  202. opr_test(cases, F.flatten, compare_fn=compare_fn, start_axis=1)
  203. output0 = (2, 3, 4 * 5)
  204. output1 = (4, 5, 6 * 7)
  205. cases = [
  206. {"input": data0, "output": output0},
  207. {"input": data1, "output": output1},
  208. ]
  209. opr_test(cases, F.flatten, compare_fn=compare_fn, start_axis=2)
  210. output0 = (2, 3 * 4, 5)
  211. output1 = (4, 5 * 6, 7)
  212. cases = [
  213. {"input": data0, "output": output0},
  214. {"input": data1, "output": output1},
  215. ]
  216. opr_test(cases, F.flatten, compare_fn=compare_fn, start_axis=1, end_axis=2)
  217. def test_broadcast():
  218. input1_shape = (20, 30)
  219. output1_shape = (30, 20, 30)
  220. data1 = np.random.random(input1_shape).astype(np.float32)
  221. input2_shape = (10, 1)
  222. output2_shape = (20, 10, 20)
  223. data2 = np.random.random(input2_shape).astype(np.float32)
  224. def compare_fn(x, y):
  225. assert x.shape[0] == y
  226. cases = [
  227. {"input": [data1, output1_shape], "output": output1_shape},
  228. {"input": [data2, output2_shape], "output": output2_shape},
  229. ]
  230. opr_test(cases, F.broadcast_to, compare_fn=compare_fn)
  231. x = F.ones((2, 1, 3))
  232. with pytest.raises(RuntimeError):
  233. F.broadcast_to(x, (2, 3, 4))
  234. with pytest.raises(RuntimeError):
  235. F.broadcast_to(x, (4, 1, 3))
  236. with pytest.raises(RuntimeError):
  237. F.broadcast_to(x, (1, 3))
  238. def test_utils_astensor1d():
  239. reference = tensor(0)
  240. # literal
  241. x = [1, 2, 3]
  242. for dtype in [None, "float32"]:
  243. xx = astensor1d(x, reference, dtype=dtype)
  244. assert type(xx) is tensor
  245. np.testing.assert_equal(xx.numpy(), x)
  246. # numpy array
  247. x = np.asarray([1, 2, 3], dtype="int32")
  248. for dtype in [None, "float32"]:
  249. xx = astensor1d(x, reference, dtype=dtype)
  250. assert type(xx) is tensor
  251. np.testing.assert_equal(xx.numpy(), x.astype(dtype) if dtype else x)
  252. # tensor
  253. x = tensor([1, 2, 3], dtype="int32")
  254. for dtype in [None, "float32"]:
  255. xx = astensor1d(x, reference, dtype=dtype)
  256. assert type(xx) is tensor
  257. np.testing.assert_equal(xx.numpy(), x.numpy())
  258. # mixed
  259. x = [1, tensor(2), 3]
  260. for dtype in [None, "float32"]:
  261. xx = astensor1d(x, reference, dtype=dtype)
  262. assert type(xx) is tensor
  263. np.testing.assert_equal(xx.numpy(), [1, 2, 3])
  264. def test_device():
  265. x = tensor([1, 2, 3], dtype="float32")
  266. y1 = F.eye(x.shape, dtype="float32")
  267. y2 = F.eye(x.shape, dtype="float32", device=None)
  268. np.testing.assert_almost_equal(y1.numpy(), y2.numpy())
  269. y3 = F.eye(x.shape, dtype="float32", device="xpux")
  270. y4 = F.eye(x.shape, dtype="float32", device=x.device)
  271. np.testing.assert_almost_equal(y3.numpy(), y4.numpy())
  272. y5 = F.full((3, 2), 4, device=x.device)
  273. y6 = F.full((3, 2), 4, device="xpux")
  274. np.testing.assert_almost_equal(y5.numpy(), y6.numpy())
  275. def test_identity():
  276. x = tensor(np.random.random((5, 10)).astype(np.float32))
  277. y = F.copy(x)
  278. np.testing.assert_equal(y.numpy(), x)
  279. def copy_test(dst, src):
  280. data = np.random.random((2, 3)).astype(np.float32)
  281. x = tensor(data, device=src)
  282. y = F.copy(x, dst)
  283. assert np.allclose(data, y.numpy())
  284. z = x.to(dst)
  285. assert np.allclose(data, z.numpy())
  286. @pytest.mark.require_ngpu(1)
  287. def test_copy_h2d():
  288. copy_test("cpu0", "gpu0")
  289. @pytest.mark.require_ngpu(1)
  290. def test_copy_d2h():
  291. copy_test("gpu0", "cpu0")
  292. @pytest.mark.require_ngpu(2)
  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 平台