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_tracing.py 17 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  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 inspect
  10. import io
  11. import itertools
  12. from tempfile import mkstemp
  13. import numpy as np
  14. import pytest
  15. import megengine.core.tensor.megbrain_graph as G
  16. import megengine.functional as F
  17. import megengine.optimizer as optim
  18. import megengine.utils.comp_graph_tools as cgtools
  19. from megengine import Parameter, tensor
  20. from megengine.autodiff import GradManager
  21. from megengine.core._trace_option import set_symbolic_shape
  22. from megengine.core.ops import builtin as ops
  23. from megengine.core.ops.builtin import Elemwise
  24. from megengine.core.tensor.utils import isscalar
  25. from megengine.functional import exp, log
  26. from megengine.jit import GraphOptimizationConfig, exclude_from_trace, trace
  27. from megengine.module import Module
  28. from megengine.random import normal, uniform
  29. from megengine.utils.naming import AutoNaming
  30. @pytest.mark.parametrize("trace_mode", [False, True])
  31. @pytest.mark.parametrize("return_mode", ["Value", "Tuple", "List", "Dict"])
  32. def test_trace(trace_mode, return_mode):
  33. @trace(symbolic=trace_mode)
  34. def f(x):
  35. if return_mode == "Tuple":
  36. return (-x,)
  37. elif return_mode == "List":
  38. return [-x]
  39. elif return_mode == "Dict":
  40. return {"neg": -x}
  41. else:
  42. return -x
  43. def get_numpy(y):
  44. if return_mode == "Tuple" or return_mode == "List":
  45. return y[0].numpy()
  46. elif return_mode == "Dict":
  47. return y["neg"].numpy()
  48. return y.numpy()
  49. x = tensor([1])
  50. y = get_numpy(f(x))
  51. for i in range(3):
  52. np.testing.assert_equal(get_numpy(f(x)), y)
  53. def test_output_copy_trace():
  54. class Simple(Module):
  55. def __init__(self):
  56. super().__init__()
  57. self.a = Parameter([1.0], dtype=np.float32)
  58. def forward(self, x):
  59. x = x * self.a
  60. # will result into a copy of output in grad
  61. x = F.exp(x)
  62. return x
  63. ys = {False: [], True: []}
  64. for symbolic in [False, True]:
  65. net = Simple()
  66. gm = GradManager().attach(net.parameters())
  67. opt = optim.SGD(net.parameters(), 1e-3, momentum=0.9)
  68. data = tensor(np.arange(4).reshape(2, 2), dtype="float32")
  69. @trace(symbolic=symbolic)
  70. def train_func(d):
  71. with gm:
  72. loss = net(d)
  73. gm.backward(loss)
  74. opt.step().clear_grad()
  75. return loss
  76. for i in range(3):
  77. y = train_func(data).numpy()
  78. ys[symbolic].append(y)
  79. for i in range(3):
  80. np.testing.assert_equal(ys[False][i], ys[True][i])
  81. @pytest.mark.parametrize("trace_mode", [False, True])
  82. def test_tensor_detach(trace_mode):
  83. @trace(symbolic=True)
  84. def f(x):
  85. y = x.detach() ** 2
  86. z = y.detach() + 1
  87. return z.detach()
  88. x = tensor([1, 2, 3, 4])
  89. for _ in range(3):
  90. f(x).numpy()
  91. @pytest.mark.parametrize("trace_mode", [False, True])
  92. def test_exclude_from_trace(trace_mode):
  93. @trace(symbolic=trace_mode)
  94. def f(x):
  95. x = -x
  96. with exclude_from_trace():
  97. if i % 2:
  98. x = -x
  99. x = -x
  100. return x
  101. x = tensor([1])
  102. for i in range(3):
  103. y = f(x).numpy()
  104. np.testing.assert_equal(f(x).numpy(), y)
  105. @pytest.mark.parametrize("trace_mode", [False, True])
  106. def test_elemwise_fuse(trace_mode):
  107. # explicitly declare opt_level as 2
  108. @trace(symbolic=trace_mode, opt_level=2)
  109. def f(a, b):
  110. base = 0
  111. c = b - a
  112. _, idx = F.topk(c, 3)
  113. # internally, biased_idx will be idx as gopt will ignore the addition
  114. biased_idx = base + idx
  115. return biased_idx
  116. a = tensor(np.ones((7, 2)), dtype=np.int32)
  117. b = tensor(2 * np.ones((7, 2)), dtype=np.float32)
  118. for i in range(3):
  119. y = f(a, b)
  120. y.numpy()
  121. @pytest.mark.parametrize("trace_mode", [False, True])
  122. def test_elemwise_fuse_in_grad(trace_mode):
  123. w = Parameter(np.ones([4, 6]), dtype="float32")
  124. gm = GradManager().attach(w)
  125. opt = optim.SGD([w], lr=0.01, momentum=0.9, weight_decay=5e-4)
  126. # explicitly declare opt_level as 2
  127. @trace(symbolic=trace_mode, opt_level=2)
  128. def f():
  129. with gm:
  130. wm = F.sum(w ** 2, axis=1) ** 0.5
  131. loss = wm.mean()
  132. gm.backward(loss)
  133. opt.step().clear_grad()
  134. return loss
  135. for i in range(3):
  136. y = f()
  137. y.numpy()
  138. def test_print_in_trace():
  139. for symbolic in [False]: # cannot read value in symbolic mode
  140. @trace(symbolic=symbolic)
  141. def f(x):
  142. nonlocal buf
  143. x = -x
  144. buf = x.numpy()
  145. x = -x
  146. return x
  147. buf = None
  148. x = tensor([1])
  149. for i in range(3):
  150. y = f(x).numpy()
  151. z = buf
  152. buf = None
  153. np.testing.assert_equal(f(x).numpy(), y)
  154. np.testing.assert_equal(z, buf)
  155. @pytest.mark.parametrize(
  156. "dump_format",
  157. [
  158. "FBS",
  159. ],
  160. )
  161. def test_dump(dump_format):
  162. @trace(symbolic=True, capture_as_const=True)
  163. def f(a, b):
  164. return a + b
  165. # prevent from remaining scope from exception test
  166. AutoNaming.clear()
  167. a = tensor([2])
  168. b = tensor([4])
  169. y = f(a, b).numpy()
  170. for i in range(3):
  171. np.testing.assert_equal(f(a, b).numpy(), y)
  172. file = io.BytesIO()
  173. dump_info = f.dump(file, dump_format=dump_format)
  174. assert dump_info.nr_opr == 3
  175. np.testing.assert_equal(dump_info.inputs, ["arg_0", "arg_1"])
  176. np.testing.assert_equal(dump_info.outputs, ["ADD"])
  177. file.seek(0)
  178. infer_cg = cgtools.GraphInference(file)
  179. result = list((infer_cg.run(a, b)).values())[0]
  180. np.testing.assert_equal(result[0], y)
  181. def test_capture_dump():
  182. a = tensor([2])
  183. @trace(symbolic=True, capture_as_const=True)
  184. def f(x):
  185. return x * a
  186. x = tensor([3])
  187. y = f(x).numpy()
  188. for i in range(3):
  189. np.testing.assert_equal(f(x).numpy(), y)
  190. file = io.BytesIO()
  191. f.dump(file)
  192. file.seek(0)
  193. infer_cg = cgtools.GraphInference(file)
  194. result = list((infer_cg.run(x)).values())[0]
  195. np.testing.assert_equal(result[0], y)
  196. def test_dump_volatile():
  197. p = tensor([2])
  198. @trace(symbolic=True, capture_as_const=True)
  199. def f(x):
  200. return x * p
  201. x = tensor([3])
  202. y = f(x).numpy()
  203. for i in range(3):
  204. np.testing.assert_equal(f(x).numpy(), y)
  205. file = io.BytesIO()
  206. f.dump(file, optimize_for_inference=False)
  207. file.seek(0)
  208. (out,) = G.load_graph(file).output_vars_list
  209. assert (
  210. cgtools.get_owner_opr_type(cgtools.get_owner_opr_inputs(out)[1])
  211. == "ImmutableTensor"
  212. )
  213. def test_dump_backward_graph():
  214. x0 = tensor(np.random.randn(3, 4))
  215. x1 = tensor(np.random.randn(3, 4))
  216. gm = GradManager().attach(x0)
  217. @trace(symbolic=True, capture_as_const=True)
  218. def f(x0, x1):
  219. with gm:
  220. y = x0 * x1
  221. gm.backward(y, F.ones_like(y))
  222. dx0 = x0.grad
  223. return y, dx0
  224. y, dx0 = f(x0, x1)
  225. np.testing.assert_equal(dx0.numpy(), x1)
  226. file = io.BytesIO()
  227. f.dump(file, optimize_for_inference=False)
  228. file.seek(0)
  229. infer_cg = cgtools.GraphInference(file)
  230. results = list((infer_cg.run(x0, x1)).values())
  231. np.testing.assert_equal(results[0], y)
  232. np.testing.assert_equal(results[1], dx0)
  233. def test_dump_with_testcase():
  234. @trace(symbolic=True, capture_as_const=True)
  235. def f(x):
  236. return exp(x)
  237. f(tensor(1.0))
  238. file = io.BytesIO()
  239. f.dump(file, input_data=["#rand(0, 255, 1)"])
  240. @pytest.mark.parametrize("trace_mode", [False, True])
  241. def test_trace_profiler(trace_mode):
  242. @trace(symbolic=trace_mode, profiling=True)
  243. def f(x):
  244. return -x
  245. x = tensor([1])
  246. y = f(x).numpy()
  247. f(x)
  248. f(x) # XXX: has to run twice
  249. out = f.get_profile()
  250. assert out.get("profiler")
  251. def test_goptions():
  252. @trace(symbolic=True, opt_level=0, capture_as_const=True)
  253. def f(x):
  254. # directly return x / x will not trigger gopt
  255. # since there's no way to tell the two x are the same
  256. y = 2.0 * x
  257. return y / y
  258. @trace(symbolic=True, opt_level=1, capture_as_const=True)
  259. def g(x):
  260. y = 2.0 * x
  261. return y / y
  262. d = tensor(0.0)
  263. assert not np.isfinite(f(d).numpy())
  264. np.testing.assert_equal(g(d).numpy().item(), 1.0)
  265. def test_goptions_log_sum_exp():
  266. @trace(symbolic=True, opt_level=0, capture_as_const=True)
  267. def f(x, y):
  268. return log(exp(x) + exp(y))
  269. @trace(symbolic=True, opt_level=1, capture_as_const=True)
  270. def g(x, y):
  271. return log(exp(x) + exp(y))
  272. val = 1.0e4
  273. d = tensor(val)
  274. o = tensor(0.0)
  275. assert not np.isfinite(f(d, o).numpy())
  276. np.testing.assert_almost_equal(g(d, o), val)
  277. def test_goptions_log_exp():
  278. @trace(symbolic=True, opt_level=0, capture_as_const=True)
  279. def f(x):
  280. return log(exp(x))
  281. @trace(symbolic=True, opt_level=1, capture_as_const=True)
  282. def g(x):
  283. return log(exp(x))
  284. f(tensor(1.0))
  285. _, out = mkstemp()
  286. f.dump(out, optimize_for_inference=False)
  287. outputs = G.load_graph(out).output_vars_list
  288. oprs_1 = cgtools.get_oprs_seq(outputs)
  289. g(tensor(1.0))
  290. g.dump(out, optimize_for_inference=False)
  291. outputs = G.load_graph(out).output_vars_list
  292. oprs_2 = cgtools.get_oprs_seq(outputs)
  293. assert len(oprs_1) - len(oprs_2) == 2
  294. def test_optimize_for_inference():
  295. @trace(symbolic=True, capture_as_const=True)
  296. def f(x):
  297. return exp(x)
  298. _, out = mkstemp()
  299. f(tensor(5.0))
  300. f.dump(out, enable_io16xc32=True)
  301. res = G.load_graph(out)
  302. computing_input = res.output_vars_list[0].owner.inputs[0]
  303. assert computing_input.dtype == np.float16
  304. def test_optimize_for_inference_broadcast():
  305. a = tensor(np.ones(1, dtype=np.float32))
  306. @trace(capture_as_const=True, symbolic_shape=True)
  307. def f():
  308. return a._broadcast(tensor([1, 10], dtype=np.int32))
  309. f()
  310. f.dump(io.BytesIO())
  311. def test_trace_cvt_bool():
  312. x = tensor([0], dtype=np.int32)
  313. @trace(symbolic=True)
  314. def f(x):
  315. a = x.shape
  316. b = a[0]
  317. assert isscalar(b)
  318. return b == 0
  319. for i in range(3):
  320. np.testing.assert_equal(f(x).numpy(), False)
  321. @pytest.mark.parametrize("trace_mode", [False, True])
  322. def test_trace_reshape(trace_mode):
  323. x1 = tensor(np.random.randn(2, 10, 10))
  324. x2 = tensor(np.random.randn(4, 10, 10))
  325. x3 = tensor(np.random.randn(8, 10, 10))
  326. @trace(symbolic=trace_mode, capture_as_const=True)
  327. def f(x):
  328. y = x.reshape(x.shape[0], 100)
  329. return y
  330. f(x1)
  331. f(x2)
  332. f(x3)
  333. def test_trace_topk():
  334. x = tensor([5, 2, 7, 1, 0, 3, 2])
  335. @trace(symbolic=True)
  336. def f(x):
  337. y = F.topk(x, 3)
  338. np.testing.assert_equal(y[0].shape.numpy(), np.array([3,]))
  339. return y
  340. for i in range(3):
  341. f(x)
  342. def test_trace_warp_perspective():
  343. inp_shape = (1, 1, 4, 4)
  344. x = tensor(np.arange(16, dtype=np.float32).reshape(inp_shape))
  345. M_shape = (1, 3, 3)
  346. M = tensor(
  347. np.array(
  348. [[1.0, 0.0, 1.0], [0.0, 1.0, 1.0], [0.0, 0.0, 1.0]], dtype=np.float32
  349. ).reshape(M_shape)
  350. )
  351. @trace(symbolic=True)
  352. def f(x, M):
  353. out = F.vision.warp_perspective(x, M, (2, 2))
  354. np.testing.assert_equal(out.shape.numpy(), np.array([1, 1, 2, 2]))
  355. return out
  356. for i in range(3):
  357. f(x, M)
  358. def test_raise_on_trace():
  359. step_count = 0
  360. catch_count = 0
  361. bad_step = 10
  362. class CatchMe(Exception):
  363. pass
  364. a = tensor([1, 2, 3, 4])
  365. b = tensor([5, 6, 7, 8])
  366. c = tensor([9, 0, 1, 2])
  367. @trace
  368. def add_abc(a, b, c):
  369. ps = a + b
  370. result = ps + c
  371. if step_count == bad_step:
  372. raise CatchMe("catch me")
  373. return result
  374. for i in range(100):
  375. try:
  376. d = add_abc(a, b, c)
  377. except CatchMe as e:
  378. catch_count += 1
  379. else:
  380. np.testing.assert_equal(d.numpy(), (a + b + c).numpy())
  381. step_count += 1
  382. assert catch_count == 1
  383. @pytest.mark.parametrize("trace_mode", [False, True])
  384. def test_trace_broadcast(trace_mode):
  385. x1 = tensor(np.random.randn(3, 1, 1))
  386. x2 = tensor(np.random.randn(1, 4, 1))
  387. x3 = tensor(np.random.randn(1, 1, 5))
  388. @trace(symbolic=trace_mode, capture_as_const=True)
  389. def f(x):
  390. y = F.broadcast_to(x, (3, 4, 5))
  391. return y
  392. f(x1)
  393. f(x2)
  394. f(x3)
  395. def test_trace_nms():
  396. def make_inputs(n):
  397. boxes = np.zeros((n, 4))
  398. boxes[:, :2] = np.random.rand(n, 2) * 100
  399. boxes[:, 2:] = np.random.rand(n, 2) * 100 + 100
  400. scores = np.random.rand(n)
  401. return tensor(boxes), tensor(scores)
  402. @trace(symbolic=False)
  403. def f(boxes, scores):
  404. # with tracing, max_output must be specified
  405. results = F.vision.nms(boxes, scores=scores, iou_thresh=0.5, max_output=20)
  406. # without tracing, max output can be inferred inside nms
  407. with exclude_from_trace():
  408. _ = F.vision.nms(boxes, scores=scores, iou_thresh=0.5)
  409. return results
  410. f(*make_inputs(10))
  411. f(*make_inputs(20))
  412. f(*make_inputs(30))
  413. def test_trace_valid_broadcast():
  414. x1 = tensor(np.random.randn(1, 1))
  415. x2 = tensor(np.random.randn(1, 2))
  416. shape = (tensor([2]), tensor([2]))
  417. @trace(symbolic=False)
  418. def f(x, shape):
  419. y = F.broadcast_to(x, shape)
  420. return y
  421. f(x1, shape)
  422. f(x2, shape)
  423. @pytest.mark.parametrize("trace_mode", [False, True])
  424. def test_clip(trace_mode):
  425. x = tensor(np.random.randn(10, 10))
  426. @trace(symbolic=trace_mode)
  427. def f(x, lower, upper):
  428. y = F.clip(x, lower, upper)
  429. return y
  430. for i in range(3):
  431. f(x, tensor([0]), tensor([1]))
  432. for i in range(3):
  433. f(x, tensor([5]), tensor([4]))
  434. # test returning noncontiguous tensor from trace
  435. def test_slice():
  436. @trace
  437. def f(x):
  438. return x[:, 1::2]
  439. x = F.arange(8).reshape(2, 4)
  440. f(x)
  441. y = f(x)
  442. np.testing.assert_array_equal(y.numpy(), x.numpy()[:, 1::2])
  443. y + y
  444. @pytest.mark.parametrize("shape_mode", [False, True])
  445. def test_random(shape_mode):
  446. def run_test(op):
  447. @trace(symbolic=True, symbolic_shape=shape_mode)
  448. def f():
  449. out = op(size=[10, 10])
  450. out_shape = out.shape
  451. assert out_shape is not None
  452. if not isinstance(out_shape, tuple):
  453. assert out.shape.numpy() is not None
  454. return out
  455. for _ in range(3):
  456. f()
  457. run_test(uniform)
  458. run_test(normal)
  459. @pytest.mark.parametrize("shape_mode", [False, True])
  460. def test_trace_advance_indexing(shape_mode):
  461. funcs = [
  462. lambda x, i: x[i],
  463. lambda x, i, j: x[i, j],
  464. lambda x, i, j: x[i, :, j, ...],
  465. lambda x, start, end: x[start:end],
  466. lambda x, start, end: x[:, 0, start:end, ..., 1],
  467. lambda x, vec: x[vec],
  468. lambda x, vec: x[vec, ..., 0, 1:3],
  469. lambda x, vec: x[vec, vec[0], vec[1]],
  470. # lambda x, i, start, end, vec: x[i, ..., :, vec, start:end], # FIXME
  471. lambda x, mask: x[mask],
  472. ]
  473. inputs = {
  474. "x": np.random.randn(5, 5, 5, 5, 5).astype("float32"),
  475. "i": 4,
  476. "j": 2,
  477. "start": 1,
  478. "end": 3,
  479. "vec": [1, 2, 3],
  480. "mask": np.random.randn(5, 5, 5, 5, 5) >= 0,
  481. }
  482. for f in funcs:
  483. sig = inspect.signature(f)
  484. param_names = list(sig._parameters.keys())
  485. params = {}
  486. params_np = {}
  487. f_traced = trace(f, symbolic=False, symbolic_shape=shape_mode)
  488. for name in param_names:
  489. params[name] = tensor(inputs[name])
  490. params_np[name] = inputs[name]
  491. expected = f(**params_np)
  492. result_imperative = f(**params)
  493. np.testing.assert_equal(expected, result_imperative.numpy())
  494. for _ in range(3):
  495. result_trace = f_traced(**params)
  496. np.testing.assert_equal(expected, result_trace.numpy())
  497. @pytest.mark.require_ngpu(1) # nvrtc backend
  498. def test_trace_jit_config():
  499. def run(fuse_dimshuffle, fuse_reduce):
  500. config = GraphOptimizationConfig()
  501. config.jit_fuse_dimshuffle = fuse_dimshuffle
  502. config.jit_fuse_reduce = fuse_reduce
  503. # set opt_level = 1 to avoid fusing dimshuffle and reduce at the same time
  504. @trace(opt_level=1, graph_opt_config=config)
  505. def func(x):
  506. return x + 1
  507. x = tensor(2)
  508. y = func(x)
  509. func._compile()
  510. options = func._graph.options
  511. mapping = {None: 0, False: 1, True: 2}
  512. assert options.graph_opt.jit == 0
  513. assert options.graph_opt.jit_config.fuse_dimshuffle == mapping[fuse_dimshuffle]
  514. assert options.graph_opt.jit_config.fuse_reduce == mapping[fuse_reduce]
  515. for fuse_dimshuffle in [None, False, True]:
  516. for fuse_reduce in [None, False, True]:
  517. run(fuse_dimshuffle, fuse_reduce)

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