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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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
  14. import megengine.module as M
  15. from megengine import cgtools, tensor
  16. from megengine.core._trace_option import set_tensor_shape
  17. from megengine.core.ops import builtin as ops
  18. from megengine.core.tensor import megbrain_graph as G
  19. from megengine.core.tensor.core import apply
  20. from megengine.core.tensor.raw_tensor import as_raw_tensor
  21. from megengine.functional import exp, log
  22. from megengine.jit import exclude_from_trace, trace
  23. def load_and_inference(file, inp_data):
  24. cg, _, out_list = G.load_graph(file)
  25. inputs = cgtools.get_dep_vars(out_list, "Host2DeviceCopy")
  26. replace_dict = {}
  27. inp_node_list = []
  28. for i in inputs:
  29. inp_node = G.InputNode(
  30. device="xpux", dtype=inputs[0].dtype, graph=inputs[0].graph
  31. )
  32. replace_dict[i] = inp_node.outputs[0]
  33. inp_node_list.append(inp_node)
  34. new_out = cgtools.replace_vars(out_list, replace_dict)
  35. out_node_list = [G.OutputNode(i) for i in new_out]
  36. new_out_list = [i.outputs[0] for i in out_node_list]
  37. new_cg = new_out_list[0].graph
  38. func = new_cg.compile(new_out_list)
  39. for node, value in zip(inp_node_list, inp_data):
  40. node.set_value(as_raw_tensor(value)._dev_tensor())
  41. func.execute()
  42. out_data_list = [o.get_value().numpy() for o in out_node_list]
  43. return out_data_list
  44. def test_trace():
  45. for symbolic in [False, True]:
  46. @trace(symbolic=symbolic)
  47. def f(x):
  48. op = ops.Elemwise(mode="negate")
  49. (y,) = apply(op, x)
  50. return y
  51. x = as_raw_tensor([1]).numpy()
  52. y = f.__wrapped__(as_raw_tensor(x)).numpy()
  53. for i in range(3):
  54. np.testing.assert_equal(f(as_raw_tensor(x)).numpy(), y)
  55. def test_exclude_from_trace():
  56. for symbolic in [False, True]:
  57. @trace(symbolic=symbolic)
  58. def f(x):
  59. neg = ops.Elemwise(mode="negate")
  60. (x,) = apply(neg, x)
  61. with exclude_from_trace():
  62. if i % 2:
  63. (x,) = apply(neg, x)
  64. (x,) = apply(neg, x)
  65. return x
  66. x = as_raw_tensor([1]).numpy()
  67. for i in range(3):
  68. y = f.__wrapped__(as_raw_tensor(x)).numpy()
  69. np.testing.assert_equal(f(as_raw_tensor(x)).numpy(), y)
  70. def test_print_in_trace():
  71. for symbolic in [False]: # cannot read value in symbolic mode
  72. @trace(symbolic=symbolic)
  73. def f(x):
  74. nonlocal buf
  75. neg = ops.Elemwise(mode="negate")
  76. (x,) = apply(neg, x)
  77. buf = x.numpy()
  78. (x,) = apply(neg, x)
  79. return x
  80. buf = None
  81. x = as_raw_tensor([1]).numpy()
  82. for i in range(3):
  83. y = f.__wrapped__(as_raw_tensor(x)).numpy()
  84. z = buf
  85. buf = None
  86. np.testing.assert_equal(f(as_raw_tensor(x)).numpy(), y)
  87. np.testing.assert_equal(z, buf)
  88. def test_dump():
  89. @trace(symbolic=True, capture_as_const=True)
  90. def f(a, b):
  91. op = ops.Elemwise(mode="add")
  92. (y,) = apply(op, a, b)
  93. return y
  94. a = as_raw_tensor([2]).numpy()
  95. b = as_raw_tensor([4]).numpy()
  96. y = f.__wrapped__(as_raw_tensor(a), as_raw_tensor(b)).numpy()
  97. for i in range(3):
  98. np.testing.assert_equal(f(as_raw_tensor(a), as_raw_tensor(b)).numpy(), y)
  99. file = io.BytesIO()
  100. f.dump(file)
  101. file.seek(0)
  102. result = load_and_inference(file, [a, b])
  103. np.testing.assert_equal(result[0], y)
  104. def test_capture_dump():
  105. a = as_raw_tensor([2])
  106. @trace(symbolic=True, capture_as_const=True)
  107. def f(x):
  108. op = ops.Elemwise(mode="mul")
  109. (y,) = apply(op, x, a)
  110. return y
  111. x = as_raw_tensor([3]).numpy()
  112. y = f.__wrapped__(as_raw_tensor(x)).numpy()
  113. for i in range(3):
  114. np.testing.assert_equal(f(as_raw_tensor(x)).numpy(), y)
  115. file = io.BytesIO()
  116. f.dump(file)
  117. file.seek(0)
  118. result = load_and_inference(file, [x])
  119. np.testing.assert_equal(result[0], y)
  120. def test_dump_volatile():
  121. p = as_raw_tensor([2])
  122. @trace(symbolic=True, capture_as_const=True)
  123. def f(x):
  124. op = ops.Elemwise(mode="mul")
  125. (y,) = apply(op, x, p)
  126. return y
  127. x = as_raw_tensor([3]).numpy()
  128. y = f.__wrapped__(as_raw_tensor(x)).numpy()
  129. for i in range(3):
  130. np.testing.assert_equal(f(as_raw_tensor(x)).numpy(), y)
  131. file = io.BytesIO()
  132. f.dump(file, optimize_for_inference=False)
  133. file.seek(0)
  134. cg, _, outputs = G.load_graph(file)
  135. (out,) = outputs
  136. assert (
  137. cgtools.get_owner_opr_type(cgtools.get_owner_opr_inputs(out)[1])
  138. == "SharedDeviceTensor"
  139. )
  140. def test_trace_profiler():
  141. for symbolic in [False, True]:
  142. @trace(symbolic=symbolic, profiling=True)
  143. def f(x):
  144. op = ops.Elemwise(mode="negate")
  145. (y,) = apply(op, x)
  146. return y
  147. x = as_raw_tensor([1]).numpy()
  148. y = f.__wrapped__(as_raw_tensor(x)).numpy()
  149. f(as_raw_tensor(x))
  150. f(as_raw_tensor(x)) # XXX: has to run twice
  151. out = f.get_profile()
  152. assert out.get("profiler")
  153. @pytest.mark.skip(reason="could not disable opt_level")
  154. def test_goptions_log_exp():
  155. @trace(symbolic=True, opt_level=0, capture_as_const=True)
  156. def f(x):
  157. return log(exp(x))
  158. @trace(symbolic=True, opt_level=1, capture_as_const=True)
  159. def g(x):
  160. return log(exp(x))
  161. f(tensor(1.0))
  162. _, out = mkstemp()
  163. f.dump(out, optimize_for_inference=False)
  164. *_, outputs = G.load_graph(out)
  165. oprs_1 = cgtools.get_oprs_seq(outputs)
  166. g(tensor(1.0))
  167. g.dump(out, optimize_for_inference=False)
  168. *_, outputs = G.load_graph(out)
  169. oprs_2 = cgtools.get_oprs_seq(outputs)
  170. assert len(oprs_1) - len(oprs_2) == 2
  171. @pytest.mark.skip(reason="could not disable opt_level")
  172. def test_goptions_log_sum_exp():
  173. @trace(symbolic=True, opt_level=0, capture_as_const=True)
  174. def f(x, y):
  175. return log(exp(x) + exp(y))
  176. @trace(symbolic=True, opt_level=1, capture_as_const=True)
  177. def g(x, y):
  178. return log(exp(x) + exp(y))
  179. f(tensor(1.0), tensor(2.0))
  180. _, out = mkstemp()
  181. f.dump(out, optimize_for_inference=False)
  182. *_, outputs = G.load_graph(out)
  183. oprs_1 = cgtools.get_oprs_seq(outputs)
  184. g(tensor(1.0), tensor(2.0))
  185. g.dump(out, optimize_for_inference=False)
  186. *_, outputs = G.load_graph(out)
  187. oprs_2 = cgtools.get_oprs_seq(outputs)
  188. assert len(oprs_1) - len(oprs_2) == 2
  189. def test_optimize_for_inference():
  190. @trace(symbolic=True, capture_as_const=True)
  191. def f(x):
  192. return exp(x)
  193. _, out = mkstemp()
  194. f(tensor(5.0))
  195. f.dump(out, enable_io16xc32=True)
  196. res = G.load_graph(out)
  197. computing_input = res.output_vars_list[0].owner.inputs[0]
  198. assert computing_input.dtype == np.float16
  199. def test_trace_cvt_bool():
  200. set_tensor_shape(True)
  201. x = tensor([0], dtype=np.int32)
  202. @trace(symbolic=True)
  203. def f(x):
  204. return x.shape[0] == 0
  205. for i in range(3):
  206. np.testing.assert_equal(f(x).numpy()[0], False)

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