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

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

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