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

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

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