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

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

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