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

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

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