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

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

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