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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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. def test_goptions():
  125. @trace(symbolic=True, opt_level=0, capture_as_const=True)
  126. def f(x):
  127. # directly return x / x will not trigger gopt
  128. # since there's no way to tell the two x are the same
  129. y = 2.0 * x
  130. return y / y
  131. @trace(symbolic=True, opt_level=1, capture_as_const=True)
  132. def g(x):
  133. y = 2.0 * x
  134. return y / y
  135. d = tensor(0.0)
  136. assert not np.isfinite(f(d).numpy())
  137. np.testing.assert_equal(g(d).numpy().item(), 1.0)
  138. def test_goptions_log_sum_exp():
  139. @trace(symbolic=True, opt_level=0, capture_as_const=True)
  140. def f(x, y):
  141. return log(exp(x) + exp(y))
  142. @trace(symbolic=True, opt_level=1, capture_as_const=True)
  143. def g(x, y):
  144. return log(exp(x) + exp(y))
  145. val = 1.0e4
  146. d = tensor(val)
  147. o = tensor(0.0)
  148. assert not np.isfinite(f(d, o).numpy())
  149. np.testing.assert_almost_equal(g(d, o), val)
  150. @pytest.mark.skip(reason="could not use opt_level=0 with dump")
  151. def test_goptions_log_exp():
  152. @trace(symbolic=True, opt_level=0, capture_as_const=True)
  153. def f(x):
  154. return log(exp(x))
  155. @trace(symbolic=True, opt_level=1, capture_as_const=True)
  156. def g(x):
  157. return log(exp(x))
  158. f(tensor(1.0))
  159. _, out = mkstemp()
  160. f.dump(out, optimize_for_inference=False)
  161. *_, outputs = G.load_graph(out)
  162. oprs_1 = cgtools.get_oprs_seq(outputs)
  163. g(tensor(1.0))
  164. g.dump(out, optimize_for_inference=False)
  165. *_, outputs = G.load_graph(out)
  166. oprs_2 = cgtools.get_oprs_seq(outputs)
  167. assert len(oprs_1) - len(oprs_2) == 2
  168. def test_optimize_for_inference():
  169. @trace(symbolic=True, capture_as_const=True)
  170. def f(x):
  171. return exp(x)
  172. _, out = mkstemp()
  173. f(tensor(5.0))
  174. f.dump(out, enable_io16xc32=True)
  175. res = G.load_graph(out)
  176. computing_input = res.output_vars_list[0].owner.inputs[0]
  177. assert computing_input.dtype == np.float16
  178. def test_optimize_for_inference_broadcast():
  179. a = tensor(np.ones(1, dtype=np.float32))
  180. @trace(capture_as_const=True, symbolic_shape=True)
  181. def f():
  182. return a._broadcast(tensor([1, 10], dtype=np.int32))
  183. f()
  184. f.dump(io.BytesIO())
  185. def test_trace_cvt_bool():
  186. x = tensor([0], dtype=np.int32)
  187. @trace(symbolic=True)
  188. def f(x):
  189. a = x.shape
  190. b = a[0]
  191. assert isscalar(b)
  192. return b == 0
  193. for i in range(3):
  194. np.testing.assert_equal(f(x).numpy(), False)
  195. def test_trace_reshape():
  196. for symbolic in [False, True]:
  197. x1 = tensor(np.random.randn(2, 10, 10))
  198. x2 = tensor(np.random.randn(4, 10, 10))
  199. x3 = tensor(np.random.randn(8, 10, 10))
  200. @trace(symbolic=symbolic, capture_as_const=True)
  201. def f(x):
  202. y = x.reshape(x.shape[0], 100)
  203. return y
  204. f(x1)
  205. f(x2)
  206. f(x3)
  207. def test_trace_topk():
  208. x = tensor([5, 2, 7, 1, 0, 3, 2])
  209. @trace(symbolic=True)
  210. def f(x):
  211. y = F.topk(x, 3)
  212. np.testing.assert_equal(y[0].shape.numpy(), np.array([3,]))
  213. return y
  214. for i in range(3):
  215. f(x)
  216. def test_trace_warp_perspective():
  217. inp_shape = (1, 1, 4, 4)
  218. x = tensor(np.arange(16, dtype=np.float32).reshape(inp_shape))
  219. M_shape = (1, 3, 3)
  220. M = tensor(
  221. np.array(
  222. [[1.0, 0.0, 1.0], [0.0, 1.0, 1.0], [0.0, 0.0, 1.0]], dtype=np.float32
  223. ).reshape(M_shape)
  224. )
  225. @trace(symbolic=True)
  226. def f(x, M):
  227. out = F.warp_perspective(x, M, (2, 2))
  228. np.testing.assert_equal(out.shape.numpy(), np.array([1, 1, 2, 2]))
  229. return out
  230. for i in range(1):
  231. f(x, M)
  232. def test_raise_on_trace():
  233. step_count = 0
  234. catch_count = 0
  235. bad_step = 10
  236. class CatchMe(Exception):
  237. pass
  238. a = tensor([1, 2, 3, 4])
  239. b = tensor([5, 6, 7, 8])
  240. c = tensor([9, 0, 1, 2])
  241. @trace
  242. def add_abc(a, b, c):
  243. print("Hello")
  244. ps = a + b
  245. result = ps + c
  246. if step_count == bad_step:
  247. raise CatchMe("catch me")
  248. return result
  249. for i in range(100):
  250. try:
  251. d = add_abc(a, b, c)
  252. except CatchMe as e:
  253. catch_count += 1
  254. else:
  255. np.testing.assert_equal(d.numpy(), (a + b + c).numpy())
  256. step_count += 1
  257. assert catch_count == 1
  258. def test_trace_broadcast():
  259. for symbolic in [False, True]:
  260. x1 = tensor(np.random.randn(3, 1, 1))
  261. x2 = tensor(np.random.randn(1, 4, 1))
  262. x3 = tensor(np.random.randn(1, 1, 5))
  263. @trace(symbolic=symbolic, capture_as_const=True)
  264. def f(x):
  265. y = F.broadcast_to(x, (3, 4, 5))
  266. return y
  267. f(x1)
  268. f(x2)
  269. f(x3)
  270. def test_trace_nms():
  271. def make_inputs(n):
  272. boxes = np.zeros((n, 4))
  273. boxes[:, :2] = np.random.rand(n, 2) * 100
  274. boxes[:, 2:] = np.random.rand(n, 2) * 100 + 100
  275. scores = np.random.rand(n)
  276. return tensor(boxes), tensor(scores)
  277. @trace(symbolic=False)
  278. def f(boxes, scores):
  279. # with tracing, max_output must be specified
  280. results = F.nn.nms(boxes, scores=scores, iou_thresh=0.5, max_output=20)
  281. # without tracing, max output can be inferred inside nms
  282. with exclude_from_trace():
  283. _ = F.nn.nms(boxes, scores=scores, iou_thresh=0.5)
  284. return results
  285. f(*make_inputs(10))
  286. f(*make_inputs(20))
  287. f(*make_inputs(30))
  288. def test_trace_valid_broadcast():
  289. x1 = tensor(np.random.randn(1, 1))
  290. x2 = tensor(np.random.randn(1, 2))
  291. shape = (tensor([2]), tensor([2]))
  292. @trace(symbolic=False)
  293. def f(x, shape):
  294. y = F.broadcast_to(x, shape)
  295. return y
  296. f(x1, shape)
  297. f(x2, shape)
  298. def test_clip():
  299. x = tensor(np.random.randn(10, 10))
  300. @trace(symbolic=True)
  301. def f(x, lower, upper):
  302. y = F.clip(x, lower, upper)
  303. return y
  304. for i in range(3):
  305. f(x, tensor([0]), tensor([1]))
  306. # test returning noncontiguous tensor from trace
  307. def test_slice():
  308. @trace
  309. def f(x):
  310. return x[:, 1::2]
  311. x = F.arange(8).reshape(2, 4)
  312. f(x)
  313. y = f(x)
  314. np.testing.assert_array_equal(y.numpy(), x.numpy()[:, 1::2])
  315. y + y
  316. def test_random():
  317. def run_test(op):
  318. for symbolic_shape in [True, False]:
  319. @trace(symbolic=True, symbolic_shape=symbolic_shape)
  320. def f():
  321. out = op(size=[10, 10])
  322. out_shape = out.shape
  323. assert out_shape is not None
  324. if not isinstance(out_shape, tuple):
  325. assert out.shape.numpy() is not None
  326. return out
  327. for _ in range(3):
  328. f()
  329. run_test(uniform)
  330. run_test(normal)

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