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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  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 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_exclude_from_trace(trace_mode):
  83. @trace(symbolic=trace_mode)
  84. def f(x):
  85. x = -x
  86. with exclude_from_trace():
  87. if i % 2:
  88. x = -x
  89. x = -x
  90. return x
  91. x = tensor([1])
  92. for i in range(3):
  93. y = f(x).numpy()
  94. np.testing.assert_equal(f(x).numpy(), y)
  95. @pytest.mark.parametrize("trace_mode", [False, True])
  96. def test_elemwise_fuse(trace_mode):
  97. # explicitly declare opt_level as 2
  98. @trace(symbolic=trace_mode, opt_level=2)
  99. def f(a, b):
  100. base = 0
  101. c = b - a
  102. _, idx = F.topk(c, 3)
  103. # internally, biased_idx will be idx as gopt will ignore the addition
  104. biased_idx = base + idx
  105. return biased_idx
  106. a = tensor(np.ones((7, 2)), dtype=np.int32)
  107. b = tensor(2 * np.ones((7, 2)), dtype=np.float32)
  108. for i in range(3):
  109. y = f(a, b)
  110. y.numpy()
  111. @pytest.mark.parametrize("trace_mode", [False, True])
  112. def test_elemwise_fuse_in_grad(trace_mode):
  113. w = Parameter(np.ones([4, 6]), dtype="float32")
  114. gm = GradManager().attach(w)
  115. opt = optim.SGD([w], lr=0.01, momentum=0.9, weight_decay=5e-4)
  116. # explicitly declare opt_level as 2
  117. @trace(symbolic=trace_mode, opt_level=2)
  118. def f():
  119. with gm:
  120. wm = F.sum(w ** 2, axis=1) ** 0.5
  121. loss = wm.mean()
  122. gm.backward(loss)
  123. opt.step().clear_grad()
  124. return loss
  125. for i in range(3):
  126. y = f()
  127. y.numpy()
  128. def test_print_in_trace():
  129. for symbolic in [False]: # cannot read value in symbolic mode
  130. @trace(symbolic=symbolic)
  131. def f(x):
  132. nonlocal buf
  133. x = -x
  134. buf = x.numpy()
  135. x = -x
  136. return x
  137. buf = None
  138. x = tensor([1])
  139. for i in range(3):
  140. y = f(x).numpy()
  141. z = buf
  142. buf = None
  143. np.testing.assert_equal(f(x).numpy(), y)
  144. np.testing.assert_equal(z, buf)
  145. def test_dump():
  146. @trace(symbolic=True, capture_as_const=True)
  147. def f(a, b):
  148. return a + b
  149. # prevent from remaining scope from exception test
  150. AutoNaming.clear()
  151. a = tensor([2])
  152. b = tensor([4])
  153. y = f(a, b).numpy()
  154. for i in range(3):
  155. np.testing.assert_equal(f(a, b).numpy(), y)
  156. file = io.BytesIO()
  157. dump_info = f.dump(file)
  158. assert dump_info.nr_opr == 3
  159. np.testing.assert_equal(dump_info.inputs, ["arg_0", "arg_1"])
  160. np.testing.assert_equal(dump_info.outputs, ["ADD"])
  161. file.seek(0)
  162. infer_cg = cgtools.GraphInference(file)
  163. result = list((infer_cg.run(a, b)).values())[0]
  164. np.testing.assert_equal(result[0], y)
  165. def test_capture_dump():
  166. a = tensor([2])
  167. @trace(symbolic=True, capture_as_const=True)
  168. def f(x):
  169. return x * a
  170. x = tensor([3])
  171. y = f(x).numpy()
  172. for i in range(3):
  173. np.testing.assert_equal(f(x).numpy(), y)
  174. file = io.BytesIO()
  175. f.dump(file)
  176. file.seek(0)
  177. infer_cg = cgtools.GraphInference(file)
  178. result = list((infer_cg.run(x)).values())[0]
  179. np.testing.assert_equal(result[0], y)
  180. def test_dump_volatile():
  181. p = tensor([2])
  182. @trace(symbolic=True, capture_as_const=True)
  183. def f(x):
  184. return x * p
  185. x = tensor([3])
  186. y = f(x).numpy()
  187. for i in range(3):
  188. np.testing.assert_equal(f(x).numpy(), y)
  189. file = io.BytesIO()
  190. f.dump(file, optimize_for_inference=False)
  191. file.seek(0)
  192. cg, _, outputs = G.load_graph(file)
  193. (out,) = outputs
  194. assert (
  195. cgtools.get_owner_opr_type(cgtools.get_owner_opr_inputs(out)[1])
  196. == "ImmutableTensor"
  197. )
  198. def test_dump_backward_graph():
  199. x0 = tensor(np.random.randn(3, 4))
  200. x1 = tensor(np.random.randn(3, 4))
  201. gm = GradManager().attach(x0)
  202. @trace(symbolic=True, capture_as_const=True)
  203. def f(x0, x1):
  204. with gm:
  205. y = x0 * x1
  206. gm.backward(y, F.ones_like(y))
  207. dx0 = x0.grad
  208. return y, dx0
  209. y, dx0 = f(x0, x1)
  210. np.testing.assert_equal(dx0.numpy(), x1)
  211. file = io.BytesIO()
  212. f.dump(file, optimize_for_inference=False)
  213. file.seek(0)
  214. infer_cg = cgtools.GraphInference(file)
  215. results = list((infer_cg.run(x0, x1)).values())
  216. np.testing.assert_equal(results[0], y)
  217. np.testing.assert_equal(results[1], dx0)
  218. @pytest.mark.parametrize("trace_mode", [False, True])
  219. def test_trace_profiler(trace_mode):
  220. @trace(symbolic=trace_mode, profiling=True)
  221. def f(x):
  222. return -x
  223. x = tensor([1])
  224. y = f(x).numpy()
  225. f(x)
  226. f(x) # XXX: has to run twice
  227. out = f.get_profile()
  228. assert out.get("profiler")
  229. def test_goptions():
  230. @trace(symbolic=True, opt_level=0, capture_as_const=True)
  231. def f(x):
  232. # directly return x / x will not trigger gopt
  233. # since there's no way to tell the two x are the same
  234. y = 2.0 * x
  235. return y / y
  236. @trace(symbolic=True, opt_level=1, capture_as_const=True)
  237. def g(x):
  238. y = 2.0 * x
  239. return y / y
  240. d = tensor(0.0)
  241. assert not np.isfinite(f(d).numpy())
  242. np.testing.assert_equal(g(d).numpy().item(), 1.0)
  243. def test_goptions_log_sum_exp():
  244. @trace(symbolic=True, opt_level=0, capture_as_const=True)
  245. def f(x, y):
  246. return log(exp(x) + exp(y))
  247. @trace(symbolic=True, opt_level=1, capture_as_const=True)
  248. def g(x, y):
  249. return log(exp(x) + exp(y))
  250. val = 1.0e4
  251. d = tensor(val)
  252. o = tensor(0.0)
  253. assert not np.isfinite(f(d, o).numpy())
  254. np.testing.assert_almost_equal(g(d, o), val)
  255. def test_goptions_log_exp():
  256. @trace(symbolic=True, opt_level=0, capture_as_const=True)
  257. def f(x):
  258. return log(exp(x))
  259. @trace(symbolic=True, opt_level=1, capture_as_const=True)
  260. def g(x):
  261. return log(exp(x))
  262. f(tensor(1.0))
  263. _, out = mkstemp()
  264. f.dump(out, optimize_for_inference=False)
  265. *_, outputs = G.load_graph(out)
  266. oprs_1 = cgtools.get_oprs_seq(outputs)
  267. g(tensor(1.0))
  268. g.dump(out, optimize_for_inference=False)
  269. *_, outputs = G.load_graph(out)
  270. oprs_2 = cgtools.get_oprs_seq(outputs)
  271. assert len(oprs_1) - len(oprs_2) == 2
  272. def test_optimize_for_inference():
  273. @trace(symbolic=True, capture_as_const=True)
  274. def f(x):
  275. return exp(x)
  276. _, out = mkstemp()
  277. f(tensor(5.0))
  278. f.dump(out, enable_io16xc32=True)
  279. res = G.load_graph(out)
  280. computing_input = res.output_vars_list[0].owner.inputs[0]
  281. assert computing_input.dtype == np.float16
  282. def test_optimize_for_inference_broadcast():
  283. a = tensor(np.ones(1, dtype=np.float32))
  284. @trace(capture_as_const=True, symbolic_shape=True)
  285. def f():
  286. return a._broadcast(tensor([1, 10], dtype=np.int32))
  287. f()
  288. f.dump(io.BytesIO())
  289. def test_trace_cvt_bool():
  290. x = tensor([0], dtype=np.int32)
  291. @trace(symbolic=True)
  292. def f(x):
  293. a = x.shape
  294. b = a[0]
  295. assert isscalar(b)
  296. return b == 0
  297. for i in range(3):
  298. np.testing.assert_equal(f(x).numpy(), False)
  299. @pytest.mark.parametrize("trace_mode", [False, True])
  300. def test_trace_reshape(trace_mode):
  301. x1 = tensor(np.random.randn(2, 10, 10))
  302. x2 = tensor(np.random.randn(4, 10, 10))
  303. x3 = tensor(np.random.randn(8, 10, 10))
  304. @trace(symbolic=trace_mode, capture_as_const=True)
  305. def f(x):
  306. y = x.reshape(x.shape[0], 100)
  307. return y
  308. f(x1)
  309. f(x2)
  310. f(x3)
  311. def test_trace_topk():
  312. x = tensor([5, 2, 7, 1, 0, 3, 2])
  313. @trace(symbolic=True)
  314. def f(x):
  315. y = F.topk(x, 3)
  316. np.testing.assert_equal(y[0].shape.numpy(), np.array([3,]))
  317. return y
  318. for i in range(3):
  319. f(x)
  320. def test_trace_warp_perspective():
  321. inp_shape = (1, 1, 4, 4)
  322. x = tensor(np.arange(16, dtype=np.float32).reshape(inp_shape))
  323. M_shape = (1, 3, 3)
  324. M = tensor(
  325. np.array(
  326. [[1.0, 0.0, 1.0], [0.0, 1.0, 1.0], [0.0, 0.0, 1.0]], dtype=np.float32
  327. ).reshape(M_shape)
  328. )
  329. @trace(symbolic=True)
  330. def f(x, M):
  331. out = F.vision.warp_perspective(x, M, (2, 2))
  332. np.testing.assert_equal(out.shape.numpy(), np.array([1, 1, 2, 2]))
  333. return out
  334. for i in range(3):
  335. f(x, M)
  336. def test_raise_on_trace():
  337. step_count = 0
  338. catch_count = 0
  339. bad_step = 10
  340. class CatchMe(Exception):
  341. pass
  342. a = tensor([1, 2, 3, 4])
  343. b = tensor([5, 6, 7, 8])
  344. c = tensor([9, 0, 1, 2])
  345. @trace
  346. def add_abc(a, b, c):
  347. ps = a + b
  348. result = ps + c
  349. if step_count == bad_step:
  350. raise CatchMe("catch me")
  351. return result
  352. for i in range(100):
  353. try:
  354. d = add_abc(a, b, c)
  355. except CatchMe as e:
  356. catch_count += 1
  357. else:
  358. np.testing.assert_equal(d.numpy(), (a + b + c).numpy())
  359. step_count += 1
  360. assert catch_count == 1
  361. @pytest.mark.parametrize("trace_mode", [False, True])
  362. def test_trace_broadcast(trace_mode):
  363. x1 = tensor(np.random.randn(3, 1, 1))
  364. x2 = tensor(np.random.randn(1, 4, 1))
  365. x3 = tensor(np.random.randn(1, 1, 5))
  366. @trace(symbolic=trace_mode, capture_as_const=True)
  367. def f(x):
  368. y = F.broadcast_to(x, (3, 4, 5))
  369. return y
  370. f(x1)
  371. f(x2)
  372. f(x3)
  373. def test_trace_nms():
  374. def make_inputs(n):
  375. boxes = np.zeros((n, 4))
  376. boxes[:, :2] = np.random.rand(n, 2) * 100
  377. boxes[:, 2:] = np.random.rand(n, 2) * 100 + 100
  378. scores = np.random.rand(n)
  379. return tensor(boxes), tensor(scores)
  380. @trace(symbolic=False)
  381. def f(boxes, scores):
  382. # with tracing, max_output must be specified
  383. results = F.vision.nms(boxes, scores=scores, iou_thresh=0.5, max_output=20)
  384. # without tracing, max output can be inferred inside nms
  385. with exclude_from_trace():
  386. _ = F.vision.nms(boxes, scores=scores, iou_thresh=0.5)
  387. return results
  388. f(*make_inputs(10))
  389. f(*make_inputs(20))
  390. f(*make_inputs(30))
  391. def test_trace_valid_broadcast():
  392. x1 = tensor(np.random.randn(1, 1))
  393. x2 = tensor(np.random.randn(1, 2))
  394. shape = (tensor([2]), tensor([2]))
  395. @trace(symbolic=False)
  396. def f(x, shape):
  397. y = F.broadcast_to(x, shape)
  398. return y
  399. f(x1, shape)
  400. f(x2, shape)
  401. def test_clip():
  402. x = tensor(np.random.randn(10, 10))
  403. @trace(symbolic=True)
  404. def f(x, lower, upper):
  405. y = F.clip(x, lower, upper)
  406. return y
  407. for i in range(3):
  408. f(x, tensor([0]), tensor([1]))
  409. # test returning noncontiguous tensor from trace
  410. def test_slice():
  411. @trace
  412. def f(x):
  413. return x[:, 1::2]
  414. x = F.arange(8).reshape(2, 4)
  415. f(x)
  416. y = f(x)
  417. np.testing.assert_array_equal(y.numpy(), x.numpy()[:, 1::2])
  418. y + y
  419. @pytest.mark.parametrize("shape_mode", [False, True])
  420. def test_random(shape_mode):
  421. def run_test(op):
  422. @trace(symbolic=True, symbolic_shape=shape_mode)
  423. def f():
  424. out = op(size=[10, 10])
  425. out_shape = out.shape
  426. assert out_shape is not None
  427. if not isinstance(out_shape, tuple):
  428. assert out.shape.numpy() is not None
  429. return out
  430. for _ in range(3):
  431. f()
  432. run_test(uniform)
  433. run_test(normal)
  434. @pytest.mark.parametrize("shape_mode", [False, True])
  435. def test_trace_advance_indexing(shape_mode):
  436. funcs = [
  437. lambda x, i: x[i],
  438. # lambda x, i, j: x[i, j], # FIXME
  439. lambda x, i, j: x[i, :, j, ...],
  440. # lambda x, start, end: x[start:end], # FIXME
  441. lambda x, start, end: x[:, 0, start:end, ..., 1],
  442. lambda x, vec: x[vec],
  443. lambda x, vec: x[vec, ..., 0, 1:3],
  444. lambda x, vec: x[vec, vec[0], vec[1]],
  445. # lambda x, i, start, end, vec: x[i, ..., :, vec, start:end], # FIXME
  446. lambda x, mask: x[mask],
  447. ]
  448. inputs = {
  449. "x": np.random.randn(5, 5, 5, 5, 5).astype("float32"),
  450. "i": 0,
  451. "j": 2,
  452. "start": 1,
  453. "end": 3,
  454. "vec": [1, 2, 3],
  455. "mask": np.random.randn(5, 5, 5, 5, 5) >= 0,
  456. }
  457. for f in funcs:
  458. sig = inspect.signature(f)
  459. param_names = list(sig._parameters.keys())
  460. params = {}
  461. params_np = {}
  462. f_traced = trace(f, symbolic=False, symbolic_shape=shape_mode)
  463. for name in param_names:
  464. params[name] = tensor(inputs[name])
  465. params_np[name] = inputs[name]
  466. expected = f(**params_np)
  467. result_imperative = f(**params)
  468. np.testing.assert_equal(expected, result_imperative.numpy())
  469. for _ in range(3):
  470. result_trace = f_traced(**params)
  471. np.testing.assert_equal(expected, result_trace.numpy())

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