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_network_node.py 20 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  1. import io
  2. import os
  3. import platform
  4. import numpy as np
  5. import pytest
  6. import megengine.core.tensor.dtype as dtype
  7. import megengine.core.tensor.megbrain_graph as G
  8. import megengine.functional as F
  9. import megengine.module as M
  10. import megengine.random as rand
  11. from megengine.core._imperative_rt.core2 import apply
  12. from megengine.core._wrap import Device
  13. from megengine.core.ops import builtin
  14. from megengine.device import get_device_count, is_cuda_available
  15. from megengine.functional.debug_param import (
  16. get_execution_strategy,
  17. set_execution_strategy,
  18. )
  19. from megengine.functional.external import tensorrt_runtime_opr
  20. from megengine.jit.tracing import trace
  21. from megengine.tensor import Tensor
  22. from megengine.utils.comp_graph_tools import GraphInference
  23. from megengine.utils.network import Network as Net
  24. def check_pygraph_dump(trace_func, inp_data, expect_results, max_err=None):
  25. orig_model = io.BytesIO()
  26. inp_size = len(inp_data)
  27. out_size = len(expect_results)
  28. arg_names = ["arg_{}".format(i) for i in range(inp_size)]
  29. output_names = ["out_{}".format(i) for i in range(out_size)]
  30. trace_func.dump(
  31. orig_model,
  32. arg_names=arg_names,
  33. output_names=output_names,
  34. optimize_for_inference=False,
  35. )
  36. orig_model.seek(0)
  37. net = Net.load(orig_model)
  38. file = io.BytesIO()
  39. net.dump(file, optimize_for_inference=False)
  40. file.seek(0)
  41. graph = GraphInference(file)
  42. inp_dict = dict([(arg_names[i], inp_data[i].numpy()) for i in range(inp_size)])
  43. results = graph.run(inp_dict=inp_dict)
  44. for ind, tensor in enumerate(expect_results):
  45. if max_err:
  46. np.testing.assert_almost_equal(
  47. tensor.numpy(), results[output_names[ind]], max_err
  48. )
  49. else:
  50. np.testing.assert_equal(tensor.numpy(), results[output_names[ind]])
  51. assert tensor.dtype == results[output_names[ind]].dtype
  52. def test_elemwise():
  53. @trace(symbolic=True, capture_as_const=True)
  54. def fwd(x, y):
  55. z1 = x * y
  56. z2 = x + y
  57. z3 = z1 / z2
  58. z3 = z3 ** 3
  59. return z3
  60. x = Tensor([1.0, 2.0])
  61. y = Tensor([3.0, 5.0])
  62. result = fwd(x, y)
  63. check_pygraph_dump(fwd, [x, y], [result])
  64. def test_reduce():
  65. @trace(symbolic=True, capture_as_const=True)
  66. def fwd(data):
  67. x = data.sum(axis=2)
  68. x = x.mean(axis=1)
  69. return x
  70. data = Tensor(np.random.random((1, 32, 32)))
  71. result = fwd(data)
  72. check_pygraph_dump(fwd, [data], [result])
  73. def test_typecvt():
  74. @trace(symbolic=True, capture_as_const=True)
  75. def fwd(data):
  76. return data.astype(dtype.qint8(0.8))
  77. x = Tensor(np.random.random((2, 3)) * 255)
  78. result = fwd(x)
  79. check_pygraph_dump(fwd, [x], [result])
  80. def test_matinv():
  81. @trace(symbolic=True, capture_as_const=True)
  82. def fwd(data):
  83. return F.matinv(data)
  84. data = Tensor(np.random.random((5, 5)))
  85. result = fwd(data)
  86. check_pygraph_dump(fwd, [data], [result])
  87. @pytest.mark.parametrize(
  88. "execution_strategy", ["HEURISTIC_REPRODUCIBLE", "PROFILE_REPRODUCIBLE"]
  89. )
  90. def test_matmul(execution_strategy):
  91. @trace(symbolic=True, capture_as_const=True)
  92. def fwd(data1, data2):
  93. return F.matmul(data1, data2)
  94. old = get_execution_strategy()
  95. set_execution_strategy(execution_strategy)
  96. max_err = None
  97. if execution_strategy == "PROFILE_REPRODUCIBLE":
  98. max_err = 1e-5
  99. data1 = Tensor(np.random.random((32, 64)))
  100. data2 = Tensor(np.random.random((64, 16)))
  101. result = fwd(data1, data2)
  102. check_pygraph_dump(fwd, [data1, data2], [result], max_err=max_err)
  103. set_execution_strategy(old)
  104. def test_batchmatmul():
  105. @trace(symbolic=True, capture_as_const=True)
  106. def fwd(x, y):
  107. return F.matmul(x, y)
  108. x = Tensor(np.random.random((3, 3, 5)))
  109. y = Tensor(np.random.random((3, 5, 3)))
  110. result = fwd(x, y)
  111. check_pygraph_dump(fwd, [x, y], [result])
  112. def test_dot():
  113. @trace(symbolic=True, capture_as_const=True)
  114. def fwd(x, y):
  115. return F.dot(x, y)
  116. x = Tensor([1.0, 2.0, 3.0])
  117. y = Tensor([3.0, 4.0, 5.0])
  118. result = fwd(x, y)
  119. check_pygraph_dump(fwd, [x, y], [result])
  120. def test_svd():
  121. @trace(symbolic=True, capture_as_const=True)
  122. def fwd(data):
  123. _, out, _ = F.svd(data)
  124. return out
  125. input = Tensor(np.random.random((1, 1, 3, 3)))
  126. result = fwd(input)
  127. check_pygraph_dump(fwd, [input], [result])
  128. def test_conv():
  129. conv = M.Conv2d(3, 32, 3)
  130. @trace(symbolic=True, capture_as_const=True)
  131. def fwd(data):
  132. return conv(data)
  133. data = Tensor(np.random.random((1, 3, 32, 32)))
  134. result = fwd(data)
  135. check_pygraph_dump(fwd, [data], [result])
  136. def test_deformable_conv():
  137. if not is_cuda_available():
  138. return
  139. conv = M.DeformableConv2d(3, 32, 3)
  140. @trace(symbolic=True, capture_as_const=True)
  141. def fwd(data, offset, mask):
  142. return conv(data, offset, mask)
  143. data = Tensor(np.random.random((1, 3, 32, 32)))
  144. offset = Tensor(np.ones((32, 3 * 3 * 2, 30, 30)).astype("int32") * 5)
  145. mask = Tensor(np.ones((32, 3 * 3, 30, 30)).astype("int32"))
  146. out = fwd(data, offset, mask)
  147. check_pygraph_dump(fwd, [data, offset, mask], [out])
  148. def test_convtranspose():
  149. deconv = M.ConvTranspose2d(32, 32, 3)
  150. @trace(symbolic=True, capture_as_const=True)
  151. def fwd(data):
  152. return deconv(data)
  153. data = Tensor(np.random.random((1, 32, 32, 32)))
  154. result = fwd(data)
  155. # cu111 has 1e-7 diff
  156. check_pygraph_dump(fwd, [data], [result], 5)
  157. @pytest.mark.skip(reason="pytest aborted")
  158. def test_grouplocal():
  159. n = M.LocalConv2d(3, 32, 32, 32, 3)
  160. @trace(symbolic=True, capture_as_const=True)
  161. def fwd(data):
  162. return n(data)
  163. input = Tensor(np.random.random((1, 3, 32, 32)))
  164. result = fwd(input)
  165. check_pygraph_dump(fwd, [input], [result])
  166. def test_pooling():
  167. @trace(symbolic=True, capture_as_const=True)
  168. def fwd(data):
  169. out = F.max_pool2d(data, 2, 2)
  170. out = F.avg_pool2d(out, 2, 2)
  171. return out
  172. data = Tensor(np.random.random((1, 3, 64, 64)))
  173. result = fwd(data)
  174. check_pygraph_dump(fwd, [data], [result])
  175. def test_adaptivepooling():
  176. pool1 = M.AdaptiveMaxPool2d((2, 2))
  177. pool2 = M.AdaptiveAvgPool2d((2, 2))
  178. @trace(symbolic=True, capture_as_const=True)
  179. def fwd(data):
  180. out = pool1(data)
  181. out = pool2(out)
  182. return out
  183. input = Tensor(np.random.random((1, 3, 32, 32)))
  184. result = fwd(input)
  185. check_pygraph_dump(fwd, [input], [result])
  186. def test_roipooling():
  187. inp = Tensor(np.random.random((1, 1, 128, 128)))
  188. rois = Tensor(np.random.random((4, 5)))
  189. @trace(symbolic=True, capture_as_const=True)
  190. def fwd(inp, rois):
  191. return F.vision.roi_pooling(inp, rois, (2, 2), scale=2.0)
  192. output = fwd(inp, rois)
  193. check_pygraph_dump(fwd, [inp, rois], [output])
  194. def test_deformable_ps_roi_pooling():
  195. inp = Tensor(np.random.random((1, 256, 64, 64)).astype("float32"))
  196. rois = Tensor(np.random.random((1, 5)).astype("float32"))
  197. trans = Tensor(np.random.random((24, 2, 7, 7)).astype("float32"))
  198. pooled_h = 7
  199. pooled_w = 7
  200. sample_per_part = 4
  201. no_trans = False
  202. part_size = 7
  203. spatial_scale = 1.0 / 64
  204. trans_std = 0.1
  205. @trace(symbolic=True, capture_as_const=True)
  206. def fwd(inp, rois, trans):
  207. y = F.deformable_psroi_pooling(
  208. inp,
  209. rois,
  210. trans,
  211. no_trans,
  212. part_size,
  213. pooled_h,
  214. pooled_w,
  215. sample_per_part,
  216. spatial_scale,
  217. trans_std,
  218. )
  219. return y
  220. result = fwd(inp, rois, trans)
  221. check_pygraph_dump(fwd, [inp, rois, trans], [result])
  222. @pytest.mark.skipif(
  223. get_device_count("gpu") > 0,
  224. reason="does not support int8 when gpu compute capability less than 6.1",
  225. )
  226. def test_convbias():
  227. @trace(symbolic=True, capture_as_const=True)
  228. def fwd(inp, weight, bias):
  229. return F.quantized.conv_bias_activation(
  230. inp, weight, bias, dtype=dtype.qint8(scale=1.0), nonlinear_mode="relu"
  231. )
  232. inp = Tensor(np.random.random((1, 3, 64, 64)), dtype=dtype.qint8(scale=1.0))
  233. weight = Tensor(np.random.random((32, 3, 3, 3)), dtype=dtype.qint8(scale=1.0))
  234. bias = Tensor(np.random.random((1, 32, 1, 1)), dtype=dtype.qint32(scale=1.0))
  235. result = fwd(inp, weight, bias)
  236. check_pygraph_dump(fwd, [inp, weight, bias], [result])
  237. def test_batch_convbias():
  238. if is_cuda_available():
  239. return
  240. @trace(symbolic=True, capture_as_const=True)
  241. def fwd(inp, weight, bias):
  242. return F.quantized.batch_conv_bias_activation(
  243. inp, weight, bias, dtype=dtype.qint8(scale=1.0), nonlinear_mode="relu"
  244. )
  245. inp = Tensor(np.random.random((1, 3, 64, 64)), dtype=dtype.qint8(scale=1.0))
  246. weight = Tensor(np.random.random((1, 32, 3, 3, 3)), dtype=dtype.qint8(scale=1.0))
  247. bias = Tensor(np.random.random((1, 32, 1, 1)), dtype=dtype.qint32(scale=1.0))
  248. result = fwd(inp, weight, bias)
  249. check_pygraph_dump(fwd, [inp, weight, bias], [result])
  250. def test_batchnorm():
  251. bn = M.BatchNorm2d(32)
  252. bn.eval()
  253. @trace(symbolic=True, capture_as_const=True)
  254. def fwd(data):
  255. return bn(data)
  256. data = Tensor(np.random.random((1, 32, 32, 32)))
  257. result = fwd(data)
  258. check_pygraph_dump(fwd, [data], [result])
  259. def test_roialign():
  260. inp = Tensor(np.random.randn(1, 1, 128, 128))
  261. rois = Tensor(np.random.random((4, 5)))
  262. @trace(symbolic=True, capture_as_const=True)
  263. def fwd(inp, rois):
  264. return F.vision.roi_align(inp, rois, (2, 2))
  265. output = fwd(inp, rois)
  266. check_pygraph_dump(fwd, [inp, rois], [output])
  267. def test_warpperspective():
  268. inp_shape = (1, 1, 4, 4)
  269. x = Tensor(np.arange(16, dtype=np.float32).reshape(inp_shape))
  270. M_shape = (1, 3, 3)
  271. # M defines a translation: dst(1, 1, h, w) = rst(1, 1, h+1, w+1)
  272. M = Tensor(
  273. np.array(
  274. [[1.0, 0.0, 1.0], [0.0, 1.0, 1.0], [0.0, 0.0, 1.0]], dtype=np.float32
  275. ).reshape(M_shape)
  276. )
  277. @trace(symbolic=True, capture_as_const=True)
  278. def fwd(x, M):
  279. return F.vision.warp_perspective(x, M, (2, 2))
  280. result = fwd(x, M)
  281. check_pygraph_dump(fwd, [x, M], [result])
  282. def test_warpaffine():
  283. inp_shape = (1, 3, 3, 3)
  284. x = Tensor(np.arange(27, dtype=np.float32).reshape(inp_shape))
  285. weightv = Tensor([[[1.26666667, 0.6, -83.33333333], [-0.33333333, 1, 66.66666667]]])
  286. @trace(symbolic=True, capture_as_const=True)
  287. def fwd(x, weightv):
  288. return F.vision.warp_affine(x, weightv, (2, 2), border_mode="wrap")
  289. outp = fwd(x, weightv)
  290. check_pygraph_dump(fwd, [x, weightv], [outp])
  291. def test_remap():
  292. inp_shape = (1, 1, 4, 4)
  293. inp = Tensor(np.arange(16, dtype=np.float32).reshape(inp_shape))
  294. map_xy_shape = (1, 2, 2, 2)
  295. map_xy = Tensor(
  296. np.array(
  297. [[[1.0, 0.0], [0.0, 1.0]], [[0.0, 1.0], [0.0, 1.0]]], dtype=np.float32
  298. ).reshape(map_xy_shape)
  299. )
  300. @trace(symbolic=True, capture_as_const=True)
  301. def fwd(inp, map_xy):
  302. return F.vision.remap(inp, map_xy)
  303. out = fwd(inp, map_xy)
  304. check_pygraph_dump(fwd, [inp, map_xy], [out])
  305. def test_resize():
  306. x = Tensor(np.random.randn(10, 3, 32, 32))
  307. @trace(symbolic=True, capture_as_const=True)
  308. def fwd(x):
  309. return F.vision.interpolate(x, size=(16, 16), mode="bilinear")
  310. out = fwd(x)
  311. check_pygraph_dump(fwd, [x], [out])
  312. def test_index_onehot():
  313. src = Tensor([[1.0, 2.0]])
  314. index = Tensor([0])
  315. @trace(symbolic=True, capture_as_const=True)
  316. def fwd(src, index):
  317. return F.indexing_one_hot(src, index)
  318. out = fwd(src, index)
  319. check_pygraph_dump(fwd, [src, index], [out])
  320. def test_set_onehot():
  321. x = Tensor(np.arange(1, 4, dtype=np.int32))
  322. @trace(symbolic=True, capture_as_const=True)
  323. def fwd(x):
  324. return F.one_hot(x, num_classes=4)
  325. out = fwd(x)
  326. check_pygraph_dump(fwd, [x], [out])
  327. def test_copy():
  328. x = Tensor([1, 2, 3])
  329. @trace(symbolic=True, capture_as_const=True)
  330. def fwd(x):
  331. return x.to("cpu0:0")
  332. o = fwd(x)
  333. check_pygraph_dump(fwd, [x], [o])
  334. def test_argsort():
  335. @trace(symbolic=True, capture_as_const=True)
  336. def fwd(data):
  337. return F.argsort(data, True)
  338. data = Tensor([1.0, 2.0, 3.0, 5.0])
  339. result = fwd(data)
  340. check_pygraph_dump(fwd, [data], [result])
  341. def test_argmax_min():
  342. @trace(symbolic=True, capture_as_const=True)
  343. def fwd(data):
  344. return F.argmax(data), F.argmin(data)
  345. data = Tensor(np.random.random((10, 10)))
  346. result = fwd(data)
  347. check_pygraph_dump(fwd, [data], result)
  348. def test_condtake():
  349. mask = Tensor(np.array([[True, False], [False, True]], dtype=np.bool_))
  350. x = Tensor(np.array([[1, np.inf], [np.nan, 4]], dtype=np.float32))
  351. @trace(symbolic=True, capture_as_const=True)
  352. def fwd(mask, x):
  353. v, index = F.cond_take(mask, x)
  354. return v, index
  355. v, index = fwd(mask, x)
  356. check_pygraph_dump(fwd, [mask, x], [v, index])
  357. def test_topk():
  358. x = Tensor(np.array([2, 4, 6, 8, 7, 5, 3, 1], dtype=np.float32))
  359. @trace(symbolic=True, capture_as_const=True)
  360. def fwd(x):
  361. top, indices = F.topk(x, 5)
  362. return top, indices
  363. top, indices = fwd(x)
  364. check_pygraph_dump(fwd, [x], [top, indices])
  365. def test_random():
  366. @trace(symbolic=True, capture_as_const=True)
  367. def fwd():
  368. x = rand.uniform(size=(2, 2))
  369. y = rand.normal(size=(1, 3, 3, 3))
  370. return x, y
  371. x, y = fwd()
  372. check_pygraph_dump(fwd, [], [x, y])
  373. def test_tensor_gen():
  374. @trace(symbolic=True, capture_as_const=True)
  375. def fwd():
  376. a = F.linspace(3, 10, 3, device=Device("xpux").to_c())
  377. b = F.eye(3, device=Device("xpux").to_c())
  378. return a, b
  379. a, b = fwd()
  380. check_pygraph_dump(fwd, [], [a, b])
  381. def test_getvarshape():
  382. op = builtin.GetVarShape(axis=1)
  383. @trace(symbolic=True, capture_as_const=True)
  384. def fwd(data):
  385. return apply(op, data)[0]
  386. data = Tensor(np.random.random((1, 2, 3, 4)))
  387. result = fwd(data)
  388. check_pygraph_dump(fwd, [data], [result])
  389. def test_concat():
  390. @trace(symbolic=True, capture_as_const=True)
  391. def fwd(data1, data2):
  392. return F.concat([data1, data2], axis=1)
  393. x = Tensor(np.random.random((2, 3)))
  394. y = Tensor(np.random.random((2, 5)))
  395. result = fwd(x, y)
  396. check_pygraph_dump(fwd, [x, y], [result])
  397. def test_broadcast():
  398. inp = Tensor([[1], [2], [3], [4]])
  399. @trace(symbolic=True, capture_as_const=True)
  400. def fwd(inp):
  401. return F.broadcast_to(inp, (4, 4))
  402. out = fwd(inp)
  403. check_pygraph_dump(fwd, [inp], [out])
  404. def test_identity():
  405. @trace(symbolic=True, capture_as_const=True)
  406. def fwd(data):
  407. return F.copy(data)
  408. data = Tensor([1.0, 2.0])
  409. result = fwd(data)
  410. check_pygraph_dump(fwd, [data], [result])
  411. @pytest.mark.skip(reason="advance indexing trace error")
  412. def test_nms():
  413. x = np.zeros((100, 4))
  414. np.random.seed(42)
  415. x[:, :2] = np.random.rand(100, 2) * 20
  416. x[:, 2:] = np.random.rand(100, 2) * 20 + 100
  417. scores = Tensor(np.random.rand(100))
  418. inp = Tensor(x)
  419. @trace(symbolic=True, capture_as_const=True)
  420. def fwd(inp, scores):
  421. return F.nn.nms(inp, scores, iou_thresh=0.7, max_output=3)
  422. result = fwd(inp, scores)
  423. check_pygraph_dump(fwd, [inp, scores], [result])
  424. def test_dimshuffle():
  425. inp = Tensor([1, 2, 3, 4])
  426. @trace(symbolic=True, capture_as_const=True)
  427. def fwd(inp):
  428. return inp.T
  429. out = fwd(inp)
  430. check_pygraph_dump(fwd, [inp], [out])
  431. def test_reshape():
  432. @trace(symbolic=True, capture_as_const=True)
  433. def fwd(data):
  434. return data.reshape((1, 8))
  435. data = Tensor(np.random.random((1, 2, 2, 2)))
  436. result = fwd(data)
  437. check_pygraph_dump(fwd, [data], [result])
  438. def test_add_remove_axis():
  439. @trace(symbolic=True, capture_as_const=True)
  440. def fwd(data):
  441. x = F.expand_dims(data, [0, 0])
  442. y = F.squeeze(x, 0)
  443. return y
  444. data = Tensor([1.0, 2.0])
  445. result = fwd(data)
  446. check_pygraph_dump(fwd, [data], [result])
  447. @pytest.mark.parametrize("mode", ["get", "set", "inc"])
  448. def test_subtensor(mode):
  449. items = [[0, True, True, True, False], [1, False, False, False, True]]
  450. data = [Tensor(np.random.random((5, 5))), Tensor(np.random.random(2))]
  451. if mode == "get":
  452. op = builtin.Subtensor(items)
  453. data = data[:1]
  454. if mode == "set":
  455. op = builtin.SetSubtensor(items)
  456. if mode == "inc":
  457. op = builtin.IncrSubtensor(items)
  458. tensors = [Tensor(0), Tensor(4), Tensor(2), Tensor(3)]
  459. @trace(symbolic=True, capture_as_const=True)
  460. def fwd(*tensors):
  461. return apply(op, *tensors)[0]
  462. result = fwd(*data, *tensors)
  463. check_pygraph_dump(fwd, data + tensors, [result])
  464. @pytest.mark.parametrize("mode", ["get", "set", "inc"])
  465. def test_advance_indexing(mode):
  466. items = [[0, False, False, False, True]]
  467. tensors = [Tensor([0, 4, 2])]
  468. data = [Tensor(np.random.random((5, 5))), Tensor(np.random.random((3, 5)))]
  469. if mode == "get":
  470. op = builtin.IndexingMultiAxisVec(items)
  471. data = data[:1]
  472. if mode == "set":
  473. op = builtin.IndexingSetMultiAxisVec(items)
  474. if mode == "inc":
  475. op = builtin.IndexingIncrMultiAxisVec(items)
  476. @trace(symbolic=True, capture_as_const=True)
  477. def fwd(*tensors):
  478. return apply(op, *tensors)[0]
  479. result = fwd(*data, *tensors)
  480. check_pygraph_dump(fwd, data + tensors, [result])
  481. @pytest.mark.parametrize("mode", ["get", "set", "inc"])
  482. def test_mesh_indexing(mode):
  483. items = [[0, True, True, True, False], [1, False, False, False, True]]
  484. tensors = [Tensor(0), Tensor(5), Tensor(2), Tensor([1, 3])]
  485. data = [Tensor(np.random.random((5, 5))), Tensor(np.random.random((3, 2)))]
  486. if mode == "get":
  487. op = builtin.IndexingMultiAxisVec(items)
  488. data = data[:1]
  489. if mode == "set":
  490. op = builtin.IndexingSetMultiAxisVec(items)
  491. if mode == "inc":
  492. op = builtin.IndexingIncrMultiAxisVec(items)
  493. @trace(symbolic=True, capture_as_const=True)
  494. def fwd(*tensors):
  495. return apply(op, *tensors)[0]
  496. result = fwd(*data, *tensors)
  497. check_pygraph_dump(fwd, data + tensors, [result])
  498. @pytest.mark.parametrize("mode", ["get", "set", "inc"])
  499. def test_batch_mesh_indexing(mode):
  500. items = [[1, False, False, False, True], [2, False, False, False, True]]
  501. tensors = [Tensor([[0, 2], [0, 2]]), Tensor([[0, 1, 2], [1, 2, 3]])]
  502. data = [Tensor(np.random.random((2, 3, 4))), Tensor(np.random.random((2, 2, 3)))]
  503. if mode == "get":
  504. op = builtin.BatchedMeshIndexing(items)
  505. data = data[:1]
  506. if mode == "set":
  507. op = builtin.BatchedSetMeshIndexing(items)
  508. if mode == "inc":
  509. op = builtin.BatchedIncrMeshIndexing(items)
  510. @trace(symbolic=True, capture_as_const=True)
  511. def fwd(*tensors):
  512. return apply(op, *tensors)[0]
  513. result = fwd(*data, *tensors)
  514. check_pygraph_dump(fwd, data + tensors, [result])
  515. @pytest.mark.skip(reason="tmp skip")
  516. def test_assert_equal():
  517. g = G.Graph()
  518. inp1 = g.make_h2d(dtype=np.float32, device="xpux")
  519. inp2 = g.make_h2d(dtype=np.float32, device="xpux")
  520. op = builtin.AssertEqual(maxerr=1e-5)
  521. out = G.apply_normal_varnode(op, inp1._node, inp2._node)[0]
  522. print(out)
  523. g.compile(out)
  524. file = io.BytesIO()
  525. out_model = G.dump_graph([out])
  526. file.write(out_model[0])
  527. file.seek(0)
  528. net = Net.load(file)
  529. dump_file = io.BytesIO()
  530. net.dump(dump_file)
  531. dump_file.seek(0)
  532. g = GraphInference(dump_file)
  533. g.run(np.array([1.0, 2.0]), np.array([1.0, 2.0]))
  534. def test_elemwise_multitype():
  535. op = builtin.ElemwiseMultiType(mode="qadd", dtype=dtype.qint32(2.0))
  536. @trace(symbolic=True, capture_as_const=True)
  537. def fwd(x, y):
  538. return apply(op, x, y)[0]
  539. x = Tensor(np.random.random(10) * 10, dtype=dtype.qint8(2.0))
  540. y = Tensor(np.random.random(10) * 10, dtype=dtype.qint8(2.0))
  541. result = fwd(x, y)
  542. check_pygraph_dump(fwd, [x, y], [result])
  543. def test_cvtcolor():
  544. inp = np.random.randn(3, 3, 3, 3).astype(np.float32)
  545. x = Tensor(inp)
  546. @trace(symbolic=True, capture_as_const=True)
  547. def fwd(inp):
  548. return F.vision.cvt_color(inp, mode="RGB2GRAY")
  549. result = fwd(x)
  550. check_pygraph_dump(fwd, [x], [result])

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