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

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

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