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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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. @pytest.mark.parametrize("trace_mode", [False, True])
  30. @pytest.mark.parametrize("return_mode", ["Value", "Tuple", "List", "Dict"])
  31. def test_trace(trace_mode, return_mode):
  32. @trace(symbolic=trace_mode)
  33. def f(x):
  34. if return_mode == "Tuple":
  35. return (-x,)
  36. elif return_mode == "List":
  37. return [-x]
  38. elif return_mode == "Dict":
  39. return {"neg": -x}
  40. else:
  41. return -x
  42. def get_numpy(y):
  43. if return_mode == "Tuple" or return_mode == "List":
  44. return y[0].numpy()
  45. elif return_mode == "Dict":
  46. return y["neg"].numpy()
  47. return y.numpy()
  48. x = tensor([1])
  49. y = get_numpy(f(x))
  50. for i in range(3):
  51. np.testing.assert_equal(get_numpy(f(x)), y)
  52. def test_output_copy_trace():
  53. class Simple(Module):
  54. def __init__(self):
  55. super().__init__()
  56. self.a = Parameter([1.0], dtype=np.float32)
  57. def forward(self, x):
  58. x = x * self.a
  59. # will result into a copy of output in grad
  60. x = F.exp(x)
  61. return x
  62. ys = {False: [], True: []}
  63. for symbolic in [False, True]:
  64. net = Simple()
  65. gm = GradManager().attach(net.parameters())
  66. opt = optim.SGD(net.parameters(), 1e-3, momentum=0.9)
  67. data = tensor(np.arange(4).reshape(2, 2), dtype="float32")
  68. @trace(symbolic=symbolic)
  69. def train_func(d):
  70. with gm:
  71. loss = net(d)
  72. gm.backward(loss)
  73. opt.step().clear_grad()
  74. return loss
  75. for i in range(3):
  76. y = train_func(data).numpy()
  77. ys[symbolic].append(y)
  78. for i in range(3):
  79. np.testing.assert_equal(ys[False][i], ys[True][i])
  80. @pytest.mark.parametrize("trace_mode", [False, True])
  81. def test_exclude_from_trace(trace_mode):
  82. @trace(symbolic=trace_mode)
  83. def f(x):
  84. x = -x
  85. with exclude_from_trace():
  86. if i % 2:
  87. x = -x
  88. x = -x
  89. return x
  90. x = tensor([1])
  91. for i in range(3):
  92. y = f(x).numpy()
  93. np.testing.assert_equal(f(x).numpy(), y)
  94. def test_print_in_trace():
  95. for symbolic in [False]: # cannot read value in symbolic mode
  96. @trace(symbolic=symbolic)
  97. def f(x):
  98. nonlocal buf
  99. x = -x
  100. buf = x.numpy()
  101. x = -x
  102. return x
  103. buf = None
  104. x = tensor([1])
  105. for i in range(3):
  106. y = f(x).numpy()
  107. z = buf
  108. buf = None
  109. np.testing.assert_equal(f(x).numpy(), y)
  110. np.testing.assert_equal(z, buf)
  111. def test_dump():
  112. @trace(symbolic=True, capture_as_const=True)
  113. def f(a, b):
  114. return a + b
  115. a = tensor([2])
  116. b = tensor([4])
  117. y = f(a, b).numpy()
  118. for i in range(3):
  119. np.testing.assert_equal(f(a, b).numpy(), y)
  120. file = io.BytesIO()
  121. dump_info = f.dump(file)
  122. assert dump_info.nr_opr == 3
  123. np.testing.assert_equal(dump_info.inputs, ["arg_0", "arg_1"])
  124. np.testing.assert_equal(dump_info.outputs, ["ADD"])
  125. file.seek(0)
  126. infer_cg = cgtools.GraphInference(file)
  127. result = list((infer_cg.run(a, b)).values())[0]
  128. np.testing.assert_equal(result[0], y)
  129. def test_capture_dump():
  130. a = tensor([2])
  131. @trace(symbolic=True, capture_as_const=True)
  132. def f(x):
  133. return x * a
  134. x = tensor([3])
  135. y = f(x).numpy()
  136. for i in range(3):
  137. np.testing.assert_equal(f(x).numpy(), y)
  138. file = io.BytesIO()
  139. f.dump(file)
  140. file.seek(0)
  141. infer_cg = cgtools.GraphInference(file)
  142. result = list((infer_cg.run(x)).values())[0]
  143. np.testing.assert_equal(result[0], y)
  144. def test_dump_volatile():
  145. p = tensor([2])
  146. @trace(symbolic=True, capture_as_const=True)
  147. def f(x):
  148. return x * p
  149. x = tensor([3])
  150. y = f(x).numpy()
  151. for i in range(3):
  152. np.testing.assert_equal(f(x).numpy(), y)
  153. file = io.BytesIO()
  154. f.dump(file, optimize_for_inference=False)
  155. file.seek(0)
  156. cg, _, outputs = G.load_graph(file)
  157. (out,) = outputs
  158. assert (
  159. cgtools.get_owner_opr_type(cgtools.get_owner_opr_inputs(out)[1])
  160. == "ImmutableTensor"
  161. )
  162. @pytest.mark.parametrize("trace_mode", [False, True])
  163. def test_trace_profiler(trace_mode):
  164. @trace(symbolic=trace_mode, profiling=True)
  165. def f(x):
  166. return -x
  167. x = tensor([1])
  168. y = f(x).numpy()
  169. f(x)
  170. f(x) # XXX: has to run twice
  171. out = f.get_profile()
  172. assert out.get("profiler")
  173. @pytest.mark.skip(reason="force opt_level=0 when building graph")
  174. def test_goptions():
  175. @trace(symbolic=True, opt_level=0, capture_as_const=True)
  176. def f(x):
  177. # directly return x / x will not trigger gopt
  178. # since there's no way to tell the two x are the same
  179. y = 2.0 * x
  180. return y / y
  181. @trace(symbolic=True, opt_level=1, capture_as_const=True)
  182. def g(x):
  183. y = 2.0 * x
  184. return y / y
  185. d = tensor(0.0)
  186. assert not np.isfinite(f(d).numpy())
  187. np.testing.assert_equal(g(d).numpy().item(), 1.0)
  188. @pytest.mark.skip(reason="force opt_level=0 when building graph")
  189. def test_goptions_log_sum_exp():
  190. @trace(symbolic=True, opt_level=0, capture_as_const=True)
  191. def f(x, y):
  192. return log(exp(x) + exp(y))
  193. @trace(symbolic=True, opt_level=1, capture_as_const=True)
  194. def g(x, y):
  195. return log(exp(x) + exp(y))
  196. val = 1.0e4
  197. d = tensor(val)
  198. o = tensor(0.0)
  199. assert not np.isfinite(f(d, o).numpy())
  200. np.testing.assert_almost_equal(g(d, o), val)
  201. def test_goptions_log_exp():
  202. @trace(symbolic=True, opt_level=0, capture_as_const=True)
  203. def f(x):
  204. return log(exp(x))
  205. @trace(symbolic=True, opt_level=1, capture_as_const=True)
  206. def g(x):
  207. return log(exp(x))
  208. f(tensor(1.0))
  209. _, out = mkstemp()
  210. f.dump(out, optimize_for_inference=False)
  211. *_, outputs = G.load_graph(out)
  212. oprs_1 = cgtools.get_oprs_seq(outputs)
  213. g(tensor(1.0))
  214. g.dump(out, optimize_for_inference=False)
  215. *_, outputs = G.load_graph(out)
  216. oprs_2 = cgtools.get_oprs_seq(outputs)
  217. assert len(oprs_1) - len(oprs_2) == 2
  218. def test_optimize_for_inference():
  219. @trace(symbolic=True, capture_as_const=True)
  220. def f(x):
  221. return exp(x)
  222. _, out = mkstemp()
  223. f(tensor(5.0))
  224. f.dump(out, enable_io16xc32=True)
  225. res = G.load_graph(out)
  226. computing_input = res.output_vars_list[0].owner.inputs[0]
  227. assert computing_input.dtype == np.float16
  228. def test_optimize_for_inference_broadcast():
  229. a = tensor(np.ones(1, dtype=np.float32))
  230. @trace(capture_as_const=True, symbolic_shape=True)
  231. def f():
  232. return a._broadcast(tensor([1, 10], dtype=np.int32))
  233. f()
  234. f.dump(io.BytesIO())
  235. def test_trace_cvt_bool():
  236. x = tensor([0], dtype=np.int32)
  237. @trace(symbolic=True)
  238. def f(x):
  239. a = x.shape
  240. b = a[0]
  241. assert isscalar(b)
  242. return b == 0
  243. for i in range(3):
  244. np.testing.assert_equal(f(x).numpy(), False)
  245. @pytest.mark.parametrize("trace_mode", [False, True])
  246. def test_trace_reshape(trace_mode):
  247. x1 = tensor(np.random.randn(2, 10, 10))
  248. x2 = tensor(np.random.randn(4, 10, 10))
  249. x3 = tensor(np.random.randn(8, 10, 10))
  250. @trace(symbolic=trace_mode, capture_as_const=True)
  251. def f(x):
  252. y = x.reshape(x.shape[0], 100)
  253. return y
  254. f(x1)
  255. f(x2)
  256. f(x3)
  257. def test_trace_topk():
  258. x = tensor([5, 2, 7, 1, 0, 3, 2])
  259. @trace(symbolic=True)
  260. def f(x):
  261. y = F.topk(x, 3)
  262. np.testing.assert_equal(y[0].shape.numpy(), np.array([3,]))
  263. return y
  264. for i in range(3):
  265. f(x)
  266. def test_trace_warp_perspective():
  267. inp_shape = (1, 1, 4, 4)
  268. x = tensor(np.arange(16, dtype=np.float32).reshape(inp_shape))
  269. M_shape = (1, 3, 3)
  270. M = tensor(
  271. np.array(
  272. [[1.0, 0.0, 1.0], [0.0, 1.0, 1.0], [0.0, 0.0, 1.0]], dtype=np.float32
  273. ).reshape(M_shape)
  274. )
  275. @trace(symbolic=True)
  276. def f(x, M):
  277. out = F.warp_perspective(x, M, (2, 2))
  278. np.testing.assert_equal(out.shape.numpy(), np.array([1, 1, 2, 2]))
  279. return out
  280. for i in range(3):
  281. f(x, M)
  282. def test_raise_on_trace():
  283. step_count = 0
  284. catch_count = 0
  285. bad_step = 10
  286. class CatchMe(Exception):
  287. pass
  288. a = tensor([1, 2, 3, 4])
  289. b = tensor([5, 6, 7, 8])
  290. c = tensor([9, 0, 1, 2])
  291. @trace
  292. def add_abc(a, b, c):
  293. ps = a + b
  294. result = ps + c
  295. if step_count == bad_step:
  296. raise CatchMe("catch me")
  297. return result
  298. for i in range(100):
  299. try:
  300. d = add_abc(a, b, c)
  301. except CatchMe as e:
  302. catch_count += 1
  303. else:
  304. np.testing.assert_equal(d.numpy(), (a + b + c).numpy())
  305. step_count += 1
  306. assert catch_count == 1
  307. @pytest.mark.parametrize("trace_mode", [False, True])
  308. def test_trace_broadcast(trace_mode):
  309. x1 = tensor(np.random.randn(3, 1, 1))
  310. x2 = tensor(np.random.randn(1, 4, 1))
  311. x3 = tensor(np.random.randn(1, 1, 5))
  312. @trace(symbolic=trace_mode, capture_as_const=True)
  313. def f(x):
  314. y = F.broadcast_to(x, (3, 4, 5))
  315. return y
  316. f(x1)
  317. f(x2)
  318. f(x3)
  319. def test_trace_nms():
  320. def make_inputs(n):
  321. boxes = np.zeros((n, 4))
  322. boxes[:, :2] = np.random.rand(n, 2) * 100
  323. boxes[:, 2:] = np.random.rand(n, 2) * 100 + 100
  324. scores = np.random.rand(n)
  325. return tensor(boxes), tensor(scores)
  326. @trace(symbolic=False)
  327. def f(boxes, scores):
  328. # with tracing, max_output must be specified
  329. results = F.nn.nms(boxes, scores=scores, iou_thresh=0.5, max_output=20)
  330. # without tracing, max output can be inferred inside nms
  331. with exclude_from_trace():
  332. _ = F.nn.nms(boxes, scores=scores, iou_thresh=0.5)
  333. return results
  334. f(*make_inputs(10))
  335. f(*make_inputs(20))
  336. f(*make_inputs(30))
  337. def test_trace_valid_broadcast():
  338. x1 = tensor(np.random.randn(1, 1))
  339. x2 = tensor(np.random.randn(1, 2))
  340. shape = (tensor([2]), tensor([2]))
  341. @trace(symbolic=False)
  342. def f(x, shape):
  343. y = F.broadcast_to(x, shape)
  344. return y
  345. f(x1, shape)
  346. f(x2, shape)
  347. def test_clip():
  348. x = tensor(np.random.randn(10, 10))
  349. @trace(symbolic=True)
  350. def f(x, lower, upper):
  351. y = F.clip(x, lower, upper)
  352. return y
  353. for i in range(3):
  354. f(x, tensor([0]), tensor([1]))
  355. # test returning noncontiguous tensor from trace
  356. def test_slice():
  357. @trace
  358. def f(x):
  359. return x[:, 1::2]
  360. x = F.arange(8).reshape(2, 4)
  361. f(x)
  362. y = f(x)
  363. np.testing.assert_array_equal(y.numpy(), x.numpy()[:, 1::2])
  364. y + y
  365. @pytest.mark.parametrize("shape_mode", [False, True])
  366. def test_random(shape_mode):
  367. def run_test(op):
  368. @trace(symbolic=True, symbolic_shape=shape_mode)
  369. def f():
  370. out = op(size=[10, 10])
  371. out_shape = out.shape
  372. assert out_shape is not None
  373. if not isinstance(out_shape, tuple):
  374. assert out.shape.numpy() is not None
  375. return out
  376. for _ in range(3):
  377. f()
  378. run_test(uniform)
  379. run_test(normal)
  380. @pytest.mark.parametrize("shape_mode", [False, True])
  381. def test_trace_advance_indexing(shape_mode):
  382. funcs = [
  383. lambda x, i: x[i],
  384. # lambda x, i, j: x[i, j], # FIXME
  385. lambda x, i, j: x[i, :, j, ...],
  386. # lambda x, start, end: x[start:end], # FIXME
  387. lambda x, start, end: x[:, 0, start:end, ..., 1],
  388. lambda x, vec: x[vec],
  389. lambda x, vec: x[vec, ..., 0, 1:3],
  390. lambda x, vec: x[vec, vec[0], vec[1]],
  391. # lambda x, i, start, end, vec: x[i, ..., :, vec, start:end], # FIXME
  392. lambda x, mask: x[mask],
  393. ]
  394. inputs = {
  395. "x": np.random.randn(5, 5, 5, 5, 5).astype("float32"),
  396. "i": 0,
  397. "j": 2,
  398. "start": 1,
  399. "end": 3,
  400. "vec": [1, 2, 3],
  401. "mask": np.random.randn(5, 5, 5, 5, 5) >= 0,
  402. }
  403. for f in funcs:
  404. sig = inspect.signature(f)
  405. param_names = list(sig._parameters.keys())
  406. params = {}
  407. params_np = {}
  408. f_traced = trace(f, symbolic=False, symbolic_shape=shape_mode)
  409. for name in param_names:
  410. params[name] = tensor(inputs[name])
  411. params_np[name] = inputs[name]
  412. expected = f(**params_np)
  413. result_imperative = f(**params)
  414. np.testing.assert_equal(expected, result_imperative.numpy())
  415. for _ in range(3):
  416. result_trace = f_traced(**params)
  417. np.testing.assert_equal(expected, result_trace.numpy())

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