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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  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 get_var_value, make_tensor, 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 import megbrain_graph as G
  18. from megengine.core.tensor.utils import astensor1d
  19. from megengine.jit import trace
  20. from megengine.utils.network import Network, set_symbolic_shape
  21. from megengine.utils.network_node import VarNode
  22. def test_eye():
  23. dtypes = [np.float32, np.bool]
  24. cases = [{"input": [10, 20]}, {"input": [30]}]
  25. for dtype in dtypes:
  26. for case in cases:
  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(*case["input"], dtype=dtype).numpy(),
  33. np.eye(*case["input"]).astype(dtype),
  34. )
  35. np.testing.assert_allclose(
  36. F.eye(tensor(case["input"]), dtype=dtype).numpy(),
  37. np.eye(*case["input"]).astype(dtype),
  38. )
  39. def test_full():
  40. shape = (2, 3)
  41. values = [True, 4, 5.0]
  42. for value in values:
  43. np.testing.assert_allclose(F.full(shape, value).numpy(), np.full(shape, value))
  44. assert F.full(shape, value).dtype == tensor(value).dtype
  45. @pytest.mark.parametrize("is_varnode", [True, False])
  46. def test_concat(is_varnode):
  47. if is_varnode:
  48. network = Network()
  49. else:
  50. network = None
  51. def get_data_shape(length: int):
  52. return (length, 2, 3)
  53. data1 = np.random.random(get_data_shape(5)).astype("float32")
  54. data2 = np.random.random(get_data_shape(6)).astype("float32")
  55. data3 = np.random.random(get_data_shape(7)).astype("float32")
  56. def run(data1, data2):
  57. return F.concat([data1, data2])
  58. cases = [{"input": [data1, data2]}, {"input": [data1, data3]}]
  59. opr_test(cases, run, ref_fn=lambda x, y: np.concatenate([x, y]), network=network)
  60. @pytest.mark.parametrize("is_varnode", [True, False])
  61. def test_condtake(is_varnode):
  62. if is_varnode:
  63. network = Network()
  64. else:
  65. network = None
  66. x = np.array([[1, 2, 3], [4, 5, 6]]).astype("float32")
  67. y = np.array([[True, False, True], [False, True, True]])
  68. xx = make_tensor(x, network)
  69. yy = make_tensor(y, network)
  70. val, idx = F.cond_take(yy, xx)
  71. if is_varnode:
  72. np.testing.assert_equal(get_var_value(val), x[y])
  73. np.testing.assert_equal(get_var_value(idx), np.where(y.reshape(-1))[0])
  74. else:
  75. np.testing.assert_equal(val.numpy(), x[y])
  76. np.testing.assert_equal(idx.numpy(), np.where(y.reshape(-1))[0])
  77. @pytest.mark.parametrize("is_varnode", [True, False])
  78. def test_concat_device(is_varnode):
  79. if is_varnode:
  80. network = Network()
  81. else:
  82. network = None
  83. data1 = make_tensor(np.random.random((3, 2, 2)).astype("float32"), network, "cpu0")
  84. data2 = make_tensor(np.random.random((2, 2, 2)).astype("float32"), network, "cpu1")
  85. out = F.concat([data1, data2], device="cpu0")
  86. assert str(out.device).split(":")[0] == "cpu0"
  87. @pytest.mark.parametrize("is_varnode", [True, False])
  88. def test_stack(is_varnode):
  89. if is_varnode:
  90. network = Network()
  91. else:
  92. network = None
  93. data1 = np.random.random((3, 2, 2)).astype("float32")
  94. data2 = np.random.random((3, 2, 2)).astype("float32")
  95. data3 = np.random.random((3, 2, 2)).astype("float32")
  96. cases = [{"input": [data1, data2]}, {"input": [data1, data3]}]
  97. for ai in range(3):
  98. def run(data1, data2):
  99. return F.stack([data1, data2], axis=ai)
  100. opr_test(
  101. cases, run, ref_fn=lambda x, y: np.stack([x, y], axis=ai), network=network
  102. )
  103. @pytest.mark.parametrize("is_varnode", [True, False])
  104. def test_split_basic(is_varnode):
  105. if is_varnode:
  106. network = Network()
  107. saved_symbolic_shape = set_symbolic_shape(False)
  108. else:
  109. network = None
  110. data = np.random.random((2, 3, 4, 5)).astype(np.float32)
  111. inp = make_tensor(data, network)
  112. mge_out0 = F.split(inp, 2, axis=3)
  113. mge_out1 = F.split(inp, [3], axis=3)
  114. np_out = np.split(data, [3, 5], axis=3)
  115. assert len(mge_out0) == 2
  116. assert len(mge_out1) == 2
  117. np.testing.assert_equal(mge_out0[0].numpy(), np_out[0])
  118. np.testing.assert_equal(mge_out1[0].numpy(), np_out[0])
  119. np.testing.assert_equal(mge_out0[1].numpy(), np_out[1])
  120. np.testing.assert_equal(mge_out1[1].numpy(), np_out[1])
  121. try:
  122. F.split(inp, 4)
  123. assert False
  124. except ValueError as e:
  125. pass
  126. try:
  127. F.split(inp, [3, 2, 5], axis=3)
  128. assert False
  129. except ValueError as e:
  130. assert str(e) == "Invalid nsplits_or_secions: [3, 2, 5]"
  131. if is_varnode:
  132. set_symbolic_shape(saved_symbolic_shape)
  133. @pytest.mark.parametrize("symbolic", [None, False, True])
  134. def test_split(symbolic):
  135. inp1 = np.random.random((3, 4, 5, 6)).astype(np.float32)
  136. inp2 = np.random.random((0, 4, 5, 6)).astype(np.float32)
  137. def ref(inp, nsplits_or_sections, axis):
  138. return np.split(inp, nsplits_or_sections, axis)
  139. def func(inp, nsplits_or_sections, axis):
  140. return F.split(inp, nsplits_or_sections, axis)
  141. cases = [
  142. (inp1, 2, 3),
  143. (inp1, [3], 3),
  144. (inp1, [3, 3, 5], 3),
  145. (inp2, 2, 3),
  146. (inp2, [3], 3),
  147. (inp2, [3, 3, 5], 3),
  148. ]
  149. for case in cases:
  150. if symbolic is None:
  151. fn = func
  152. else:
  153. fn = trace(symbolic=symbolic)(func)
  154. for i in range(3 if symbolic is not None else 1):
  155. ref_out = ref(*case)
  156. out = fn(tensor(case[0]), case[1], case[2])
  157. assert len(ref_out) == len(out)
  158. for idx in range(len(ref_out)):
  159. np.testing.assert_equal(ref_out[idx], out[idx].numpy())
  160. @pytest.mark.parametrize("is_varnode", [True, False])
  161. def test_reshape(is_varnode):
  162. if is_varnode:
  163. network = Network()
  164. else:
  165. network = None
  166. x = np.arange(6, dtype="float32")
  167. xx = make_tensor(x, network)
  168. y = x.reshape(1, 2, 3)
  169. for shape in [
  170. (1, 2, 3),
  171. (1, -1, 3),
  172. (1, make_tensor(-1, network), 3),
  173. np.array([1, -1, 3], dtype="int32"),
  174. make_tensor([1, -1, 3], network),
  175. ]:
  176. yy = F.reshape(xx, shape)
  177. np.testing.assert_equal(yy.numpy(), y)
  178. @pytest.mark.parametrize("is_varnode", [True, False])
  179. def test_broadcast_auto_infer(is_varnode):
  180. if is_varnode:
  181. network = Network()
  182. else:
  183. network = None
  184. x = np.random.random((1, 2, 3)).astype(np.float32)
  185. xx = make_tensor(x, network)
  186. for shape in [
  187. (1, 2, 3),
  188. (1, None, 3),
  189. ]:
  190. yy = F.broadcast_to(xx, shape)
  191. np.testing.assert_equal(yy.numpy(), x)
  192. with pytest.raises(ValueError):
  193. F.broadcast_to(xx, (1, -1, 3))
  194. with pytest.raises(ValueError):
  195. F.broadcast_to(xx, (None, 1, 2, 3))
  196. F.broadcast_to(xx, (1, None, 2, 3))
  197. t = tensor(2, dtype=np.int32)
  198. F.broadcast_to(xx, (t, None, 2, 3))
  199. @pytest.mark.parametrize("is_trace", [True, False])
  200. def test_reshape_on_empty_tensor(is_trace):
  201. input1_shape = (100, 0, 1)
  202. output1_shape = (100, 0, 10)
  203. data1 = tensor(np.random.random(input1_shape).astype(np.float32))
  204. input2_shape = (10, 0)
  205. output2_shape = (0,)
  206. data2 = tensor(np.random.random(input2_shape).astype(np.float32))
  207. input3_shape = (10, 0, 10)
  208. output3_shape = (0, 1, 2, 3)
  209. data3 = tensor(np.random.random(input3_shape).astype(np.float32))
  210. def comp(out, target_shp):
  211. assert out._tuple_shape == target_shp
  212. def func(x, shp):
  213. return F.reshape(x, shp)
  214. cases = [
  215. [data1, output1_shape],
  216. [data2, output2_shape],
  217. [data3, output3_shape],
  218. ]
  219. def test(func, inp, comp, target_shp):
  220. out = func(inp, target_shp)
  221. comp(out, target_shp)
  222. if is_trace:
  223. for symbolic in [False, True]:
  224. for inp, target_shp in cases:
  225. func_traced = trace(symbolic=symbolic)(func)
  226. test(func_traced, inp, comp, target_shp)
  227. test(func_traced, inp, comp, target_shp)
  228. test(func_traced, inp, comp, target_shp)
  229. else:
  230. for inp, target_shp in cases:
  231. test(func, inp, comp, target_shp)
  232. @pytest.mark.parametrize("is_varnode", [True, False])
  233. def test_reshape_shape_inference(is_varnode):
  234. if is_varnode:
  235. network = Network()
  236. saved_symbolic_shape = set_symbolic_shape(False)
  237. else:
  238. network = None
  239. x_shape_known = make_tensor([1, 2, 3, 4], network)
  240. x_shape_unknown = F.broadcast_to(
  241. make_tensor([1.0], network), shape=make_tensor([1, 1, 1, 1], network).sum()
  242. )
  243. tshp_unknown = astensor1d(
  244. (make_tensor([2], network), make_tensor([2], network)), x_shape_known
  245. )
  246. tshp_known = astensor1d((2, 2), x_shape_known)
  247. tshp_known_unspec = astensor1d((2, -1), x_shape_known)
  248. def check_shape(output, target):
  249. source = output.shape
  250. if isinstance(source, tensor):
  251. source = source.numpy()
  252. np.testing.assert_equal(source, target)
  253. def func(x, target_shape):
  254. return x.reshape(target_shape)
  255. cases = [
  256. {"input": [x_shape_known, tshp_unknown], "output": [(2, 2),]},
  257. {"input": [x_shape_unknown, tshp_unknown], "output": [(2, 2),]},
  258. {"input": [x_shape_known, tshp_known], "output": [(2, 2),]},
  259. {"input": [x_shape_known, tshp_known_unspec], "output": [(2, 2),]},
  260. {"input": [x_shape_unknown, tshp_known], "output": [(2, 2),]},
  261. {"input": [x_shape_unknown, tshp_known_unspec], "output": [(2, 2),]},
  262. ]
  263. opr_test(cases, func, compare_fn=check_shape, test_trace=True, network=network)
  264. if is_varnode:
  265. set_symbolic_shape(saved_symbolic_shape)
  266. @pytest.mark.parametrize("is_varnode", [True, False])
  267. def test_squeeze(is_varnode):
  268. if is_varnode:
  269. network = Network()
  270. saved_symbolic_shape = set_symbolic_shape(False)
  271. else:
  272. network = None
  273. x = np.arange(6, dtype="float32").reshape(1, 2, 3, 1)
  274. xx = make_tensor(x, network)
  275. for axis in [None, 3, -4, (3, -4)]:
  276. y = np.squeeze(x, axis)
  277. yy = F.squeeze(xx, axis)
  278. np.testing.assert_equal(y, yy.numpy())
  279. if is_varnode:
  280. set_symbolic_shape(saved_symbolic_shape)
  281. @pytest.mark.parametrize("is_varnode", [True, False])
  282. def test_expand_dims(is_varnode):
  283. if is_varnode:
  284. network = Network()
  285. else:
  286. network = None
  287. x = np.arange(6, dtype="float32").reshape(2, 3)
  288. xx = make_tensor(x, network)
  289. for axis in [2, -3, (3, -4), (1, -4)]:
  290. y = np.expand_dims(x, axis)
  291. yy = F.expand_dims(xx, axis)
  292. np.testing.assert_equal(y, yy.numpy())
  293. def test_expand_dims_for_scalar():
  294. x = np.array(1, dtype="float32")
  295. xx = make_tensor(x, None)
  296. for axis in [0, -1, (0, 1), (-1, -2), (0, -1)]:
  297. y = np.expand_dims(x, axis)
  298. yy = F.expand_dims(xx, axis)
  299. np.testing.assert_equal(y, yy.numpy())
  300. for axis in [1, -2, (1, 2), (-2, -3)]:
  301. np.testing.assert_raises(np.AxisError, np.expand_dims, x, axis)
  302. np.testing.assert_raises(RuntimeError, F.expand_dims, xx, axis)
  303. @pytest.mark.parametrize("is_varnode", [True, False])
  304. def test_elemwise_dtype_promotion(is_varnode):
  305. if is_varnode:
  306. network = Network()
  307. else:
  308. network = None
  309. x = np.random.rand(2, 3).astype("float32")
  310. y = np.random.rand(1, 3).astype("float16")
  311. xx = make_tensor(x, network)
  312. yy = make_tensor(y, network)
  313. z = xx * yy
  314. np.testing.assert_equal(z.numpy(), x * y)
  315. z = xx + y
  316. np.testing.assert_equal(z.numpy(), x + y)
  317. z = x - yy
  318. np.testing.assert_equal(z.numpy(), x - y)
  319. @pytest.mark.parametrize("is_varnode", [True, False])
  320. def test_linspace(is_varnode):
  321. if is_varnode:
  322. network = Network()
  323. else:
  324. network = None
  325. cases = [
  326. {"input": [1, 9, 9]},
  327. {"input": [3, 10, 8]},
  328. ]
  329. opr_test(
  330. cases,
  331. F.linspace,
  332. ref_fn=lambda start, end, step: np.linspace(start, end, step, dtype=np.float32),
  333. network=network,
  334. )
  335. cases = [
  336. {"input": [9, 1, 9]},
  337. {"input": [10, 3, 8]},
  338. ]
  339. opr_test(
  340. cases,
  341. F.linspace,
  342. ref_fn=lambda start, end, step: np.linspace(start, end, step, dtype=np.float32),
  343. network=network,
  344. )
  345. cases = [
  346. {"input": [1, make_tensor(9, network), 9]},
  347. {"input": [make_tensor(1, network), 9, make_tensor(9, network)]},
  348. ]
  349. opr_test(
  350. cases,
  351. F.linspace,
  352. ref_fn=lambda start, end, step: np.linspace(1, 9, 9, dtype=np.float32),
  353. network=network,
  354. )
  355. @pytest.mark.parametrize("is_varnode", [True, False])
  356. def test_arange(is_varnode):
  357. if is_varnode:
  358. network = Network()
  359. else:
  360. network = None
  361. cases = [
  362. {"input": [1, 9, 1]},
  363. {"input": [2, 10, 2]},
  364. ]
  365. opr_test(
  366. cases,
  367. F.arange,
  368. ref_fn=lambda start, end, step: np.arange(start, end, step, dtype=np.float32),
  369. network=network,
  370. )
  371. cases = [
  372. {"input": [9, 1, -1]},
  373. {"input": [10, 2, -2]},
  374. ]
  375. opr_test(
  376. cases,
  377. F.arange,
  378. ref_fn=lambda start, end, step: np.arange(start, end, step, dtype=np.float32),
  379. network=network,
  380. )
  381. cases = [
  382. {"input": [9.3, 1.2, -0.5]},
  383. {"input": [10.3, 2.1, -1.7]},
  384. ]
  385. opr_test(
  386. cases,
  387. F.arange,
  388. ref_fn=lambda start, end, step: np.arange(start, end, step, dtype=np.float32),
  389. network=network,
  390. )
  391. @pytest.mark.parametrize("is_varnode", [True, False])
  392. def test_round(is_varnode):
  393. if is_varnode:
  394. network = Network()
  395. else:
  396. network = None
  397. data1_shape = (15,)
  398. data2_shape = (25,)
  399. data1 = np.random.random(data1_shape).astype(np.float32)
  400. data2 = np.random.random(data2_shape).astype(np.float32)
  401. cases = [{"input": data1}, {"input": data2}]
  402. opr_test(cases, F.round, ref_fn=np.round, network=network)
  403. @pytest.mark.parametrize("is_varnode", [True, False])
  404. def test_flatten(is_varnode):
  405. if is_varnode:
  406. network = Network()
  407. else:
  408. network = None
  409. data0_shape = (2, 3, 4, 5)
  410. data1_shape = (4, 5, 6, 7)
  411. data0 = np.random.random(data0_shape).astype(np.float32)
  412. data1 = np.random.random(data1_shape).astype(np.float32)
  413. def compare_fn(x, y):
  414. assert x._tuple_shape[0] == y
  415. output0 = (2 * 3 * 4 * 5,)
  416. output1 = (4 * 5 * 6 * 7,)
  417. cases = [
  418. {"input": data0, "output": output0},
  419. {"input": data1, "output": output1},
  420. ]
  421. opr_test(cases, F.flatten, compare_fn=compare_fn, network=network)
  422. output0 = (2, 3 * 4 * 5)
  423. output1 = (4, 5 * 6 * 7)
  424. cases = [
  425. {"input": data0, "output": output0},
  426. {"input": data1, "output": output1},
  427. ]
  428. opr_test(cases, F.flatten, compare_fn=compare_fn, start_axis=1, network=network)
  429. output0 = (2, 3, 4 * 5)
  430. output1 = (4, 5, 6 * 7)
  431. cases = [
  432. {"input": data0, "output": output0},
  433. {"input": data1, "output": output1},
  434. ]
  435. opr_test(cases, F.flatten, compare_fn=compare_fn, start_axis=2, network=network)
  436. output0 = (2, 3 * 4, 5)
  437. output1 = (4, 5 * 6, 7)
  438. cases = [
  439. {"input": data0, "output": output0},
  440. {"input": data1, "output": output1},
  441. ]
  442. opr_test(
  443. cases,
  444. F.flatten,
  445. compare_fn=compare_fn,
  446. start_axis=1,
  447. end_axis=2,
  448. network=network,
  449. )
  450. @pytest.mark.parametrize("is_varnode", [True, False])
  451. def test_broadcast(is_varnode):
  452. if is_varnode:
  453. network = Network()
  454. else:
  455. network = None
  456. input1_shape = (20, 30)
  457. output1_shape = (30, 20, 30)
  458. data1 = np.random.random(input1_shape).astype(np.float32)
  459. input2_shape = (10, 1)
  460. output2_shape = (20, 10, 20)
  461. data2 = np.random.random(input2_shape).astype(np.float32)
  462. input3_shape = (10, 10)
  463. output3_shape = (10, 10)
  464. data3 = np.random.random(input3_shape).astype(np.float32)
  465. def compare_fn(x, y):
  466. assert x._tuple_shape[0] == y
  467. cases = [
  468. {"input": [data1, output1_shape], "output": output1_shape},
  469. {"input": [data2, output2_shape], "output": output2_shape},
  470. {"input": [data3, output3_shape], "output": output3_shape},
  471. ]
  472. opr_test(cases, F.broadcast_to, compare_fn=compare_fn, network=network)
  473. x = F.ones((2, 1, 3))
  474. with pytest.raises(RuntimeError):
  475. F.broadcast_to(x, (2, 3, 4))
  476. with pytest.raises(RuntimeError):
  477. F.broadcast_to(x, (4, 1, 3))
  478. with pytest.raises(RuntimeError):
  479. F.broadcast_to(x, (1, 3))
  480. @pytest.mark.parametrize("is_trace", [True, False])
  481. def test_broadcast_on_empty_tensor(is_trace):
  482. input1_shape = (100, 0, 1)
  483. output1_shape = (100, 0, 10)
  484. data1 = tensor(np.random.random(input1_shape).astype(np.float32))
  485. input2_shape = (10, 0)
  486. output2_shape = (10, 10, 0)
  487. data2 = tensor(np.random.random(input2_shape).astype(np.float32))
  488. input3_shape = (0, 0, 1, 10)
  489. output3_shape = (10, 0, 0, 10, 10)
  490. data3 = tensor(np.random.random(input3_shape).astype(np.float32))
  491. def comp(out, target_shp):
  492. assert out._tuple_shape == target_shp
  493. def func(x, shp):
  494. return F.broadcast_to(x, shp)
  495. cases = [
  496. [data1, output1_shape],
  497. [data2, output2_shape],
  498. [data3, output3_shape],
  499. ]
  500. def test(func, inp, comp, target_shp):
  501. out = func(inp, target_shp)
  502. comp(out, target_shp)
  503. if is_trace:
  504. for symbolic in [False, True]:
  505. for inp, target_shp in cases:
  506. func_traced = trace(symbolic=symbolic)(func)
  507. test(func_traced, inp, comp, target_shp)
  508. test(func_traced, inp, comp, target_shp)
  509. test(func_traced, inp, comp, target_shp)
  510. else:
  511. for inp, target_shp in cases:
  512. test(func, inp, comp, target_shp)
  513. @pytest.mark.parametrize("is_varnode", [True, False])
  514. def test_utils_astensor1d(is_varnode):
  515. if is_varnode:
  516. network = Network()
  517. else:
  518. network = None
  519. reference = make_tensor(0, network)
  520. # literal
  521. x = [1, 2, 3]
  522. for dtype in [None, "float32"]:
  523. xx = astensor1d(x, reference, dtype=dtype)
  524. assert isinstance(xx, type(reference))
  525. np.testing.assert_equal(xx.numpy(), x)
  526. # numpy array
  527. x = np.asarray([1, 2, 3], dtype="int32")
  528. for dtype in [None, "float32"]:
  529. xx = astensor1d(x, reference, dtype=dtype)
  530. assert isinstance(xx, type(reference))
  531. np.testing.assert_equal(xx.numpy(), x.astype(dtype) if dtype else x)
  532. # tensor
  533. x = make_tensor([1, 2, 3], network)
  534. for dtype in [None, "float32"]:
  535. xx = astensor1d(x, reference, dtype=dtype)
  536. assert isinstance(xx, type(reference))
  537. np.testing.assert_equal(xx.numpy(), x.numpy())
  538. # mixed
  539. x = [1, make_tensor(2, network), 3]
  540. for dtype in [None, "float32"]:
  541. xx = astensor1d(x, reference, dtype=dtype)
  542. assert isinstance(xx, type(reference))
  543. np.testing.assert_equal(xx.numpy(), [1, 2, 3])
  544. def test_device():
  545. x = tensor([1, 2, 3], dtype="float32")
  546. y1 = F.eye(x.shape, dtype="float32")
  547. y2 = F.eye(x.shape, dtype="float32", device=None)
  548. np.testing.assert_almost_equal(y1.numpy(), y2.numpy())
  549. y3 = F.eye(x.shape, dtype="float32", device="xpux")
  550. y4 = F.eye(x.shape, dtype="float32", device=x.device)
  551. np.testing.assert_almost_equal(y3.numpy(), y4.numpy())
  552. y5 = F.full((3, 2), 4, device=x.device)
  553. y6 = F.full((3, 2), 4, device="xpux")
  554. np.testing.assert_almost_equal(y5.numpy(), y6.numpy())
  555. @pytest.mark.parametrize("is_varnode", [True, False])
  556. def test_identity(is_varnode):
  557. if is_varnode:
  558. network = Network()
  559. else:
  560. network = None
  561. x = make_tensor(np.random.random((5, 10)).astype(np.float32), network)
  562. y = F.copy(x)
  563. np.testing.assert_equal(y.numpy(), x)
  564. def copy_test(dst, src, network):
  565. data = np.random.random((2, 3)).astype(np.float32)
  566. x = make_tensor(data, device=src, network=network)
  567. y = F.copy(x, dst)
  568. assert np.allclose(data, y.numpy())
  569. if network is None:
  570. z = x.to(dst)
  571. assert np.allclose(data, z.numpy())
  572. @pytest.mark.require_ngpu(1)
  573. @pytest.mark.parametrize("is_varnode", [True, False])
  574. def test_copy_h2d(is_varnode):
  575. if is_varnode:
  576. network = Network()
  577. else:
  578. network = None
  579. copy_test("cpu0", "gpu0", network=network)
  580. @pytest.mark.require_ngpu(1)
  581. @pytest.mark.parametrize("is_varnode", [True, False])
  582. def test_copy_d2h(is_varnode):
  583. if is_varnode:
  584. network = Network()
  585. else:
  586. network = None
  587. copy_test("gpu0", "cpu0", network=network)
  588. @pytest.mark.require_ngpu(2)
  589. @pytest.mark.parametrize("is_varnode", [True, False])
  590. def test_copy_d2d(is_varnode):
  591. if is_varnode:
  592. network = Network()
  593. else:
  594. network = None
  595. copy_test("gpu0", "gpu1", network=network)
  596. copy_test("gpu0:0", "gpu0:1", network=network)
  597. @pytest.mark.require_ngpu(2)
  598. @pytest.mark.parametrize(
  599. "shape, device_src, device_dst",
  600. [
  601. ((0,), "cpu0", "cpu0"),
  602. ((10, 0), "cpu0", "cpu1"),
  603. ((2, 0, 3), "cpu0", "gpu0"),
  604. ((1, 0, 1, 0), "gpu0", "cpu0"),
  605. ((2, 3, 4, 5, 0), "gpu0", "gpu1"),
  606. ],
  607. )
  608. @pytest.mark.parametrize("is_symbolic", [None, True, False])
  609. def test_copy_empty(shape, device_src, device_dst, is_symbolic):
  610. inp = tensor(np.random.randn(*shape).astype("float32"), device=device_src)
  611. def func(inp):
  612. return F.copy(inp, device_dst)
  613. if is_symbolic is not None:
  614. func = trace(symbolic=is_symbolic)(func)
  615. for _ in range(3):
  616. out = func(inp)
  617. assert out.numpy().shape == shape
  618. assert out.device == device_dst
  619. if is_symbolic is None:
  620. break
  621. @pytest.mark.parametrize(
  622. "shape, repeats, axis",
  623. [
  624. ((2,), 2, 0),
  625. ((2, 3, 4, 5), 3, 0),
  626. ((2, 3, 4, 5), 4, 3),
  627. ((2,), 2, None),
  628. ((2, 3, 4, 5), 3, None),
  629. ((), 1, None),
  630. ((), 10, None),
  631. ],
  632. )
  633. @pytest.mark.parametrize("is_varnode", [True, False])
  634. def test_repeat(shape, repeats, axis, is_varnode):
  635. if is_varnode:
  636. network = Network()
  637. else:
  638. network = None
  639. def repeat_func(inp):
  640. return F.repeat(inp=inp, repeats=repeats, axis=axis)
  641. if shape != ():
  642. cases = [
  643. {"input": np.random.randn(*shape).astype("float32")},
  644. ]
  645. else:
  646. cases = [{"input": np.array(1.23)}]
  647. opr_test(
  648. cases,
  649. repeat_func,
  650. ref_fn=lambda inp: np.repeat(inp, repeats, axis),
  651. network=network,
  652. )
  653. @pytest.mark.parametrize(
  654. "shape, reps",
  655. [
  656. ((2,), (2,)),
  657. ((2, 3, 4, 5), (1, 1, 1, 1)),
  658. ((2, 3, 4, 5), (1, 2, 3, 4)),
  659. ((2, 3, 4, 5), (2, 2, 2, 2, 2, 2, 2)),
  660. ],
  661. )
  662. @pytest.mark.parametrize("is_varnode", [True])
  663. def test_tile(shape, reps, is_varnode):
  664. if is_varnode:
  665. network = Network()
  666. else:
  667. network = None
  668. def tile_func(inp):
  669. return F.tile(inp=inp, reps=reps)
  670. cases = [{"input": np.random.randn(*shape).astype("float32")}]
  671. opr_test(cases, tile_func, ref_fn=lambda inp: np.tile(inp, reps), network=network)
  672. @pytest.mark.parametrize(
  673. "shape, shifts, axis",
  674. [
  675. ((2, 3), 0, None),
  676. ((2, 3), 1, 0),
  677. ((2, 3), 100, 0),
  678. ((2, 3), -100, 0),
  679. ((2, 3, 4, 5), (-1, 1), (0, 1)),
  680. ((2, 3, 4, 5), (-2, 1, 2), (1, 2, 3)),
  681. ],
  682. )
  683. @pytest.mark.parametrize("is_varnode", [True, False])
  684. def test_roll(shape, shifts, axis, is_varnode):
  685. if is_varnode:
  686. network = Network()
  687. else:
  688. network = None
  689. inp = np.random.randn(*shape).astype("float32")
  690. def func(inp):
  691. return F.roll(inp, shifts, axis)
  692. cases = [
  693. {"input": inp},
  694. ]
  695. opr_test(
  696. cases, func, ref_fn=lambda inp: np.roll(inp, shifts, axis), network=network
  697. )
  698. @pytest.mark.parametrize(
  699. "shape, shifts, axis", [((10, 0), 5, 1), ((10, 0), -10, 1),],
  700. )
  701. @pytest.mark.parametrize("is_symbolic", [None, True, False])
  702. def test_roll_empty_tensor(shape, shifts, axis, is_symbolic):
  703. inp = tensor(np.random.randn(*shape).astype("float32"))
  704. def func(inp):
  705. return F.roll(inp, shifts, axis)
  706. if is_symbolic is not None:
  707. func = trace(symbolic=is_symbolic)(func)
  708. out_ref = np.roll(inp.numpy(), shifts, axis)
  709. for _ in range(3):
  710. out = F.roll(inp, shifts, axis)
  711. np.testing.assert_equal(out.numpy(), out_ref)
  712. if is_symbolic is None:
  713. break