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_network.py 12 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. import io
  2. import numpy as np
  3. import megengine.core.tensor.megbrain_graph as G
  4. import megengine.functional as F
  5. import megengine.module as M
  6. import megengine.utils.network_node as N
  7. from megengine.jit.tracing import trace
  8. from megengine.tensor import Tensor
  9. from megengine.utils.comp_graph_tools import GraphInference
  10. from megengine.utils.network import Network as Net
  11. from megengine.utils.network import as_oprnode, set_symbolic_shape
  12. from megengine.utils.network_node import Host2DeviceCopy, VarNode
  13. def test_metadata():
  14. x = Tensor(0)
  15. @trace(symbolic=True, capture_as_const=True)
  16. def fwd(x):
  17. return x * 2
  18. fwd(x)
  19. orig_model = io.BytesIO()
  20. fwd.dump(orig_model, user_info="test", optimize_for_inference=False)
  21. orig_model.seek(0)
  22. graph = Net.load(orig_model)
  23. assert graph.metadata == {
  24. "user_info": "test",
  25. "graph_modified": False, # False: tracing.dump
  26. "optimized_for_inference": False,
  27. }
  28. orig_model.seek(0)
  29. graph.dump(
  30. orig_model,
  31. user_info={"str": "x", "tensor": x, "module": M.Module, "none": None},
  32. optimize_for_inference=True,
  33. enable_nchw4=True,
  34. enable_ioc16=True,
  35. )
  36. orig_model.seek(0)
  37. graph = Net.load(orig_model)
  38. assert graph.metadata == {
  39. "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None},
  40. "graph_modified": True, # True: Network.dump
  41. "optimized_for_inference": True,
  42. "enable_nchw4": True,
  43. "enable_ioc16": True,
  44. }
  45. orig_model.seek(0)
  46. fwd.dump(orig_model, enable_metadata=False)
  47. orig_model.seek(0)
  48. graph = Net.load(orig_model)
  49. assert graph.metadata is None
  50. def test_replace_var():
  51. a = Tensor([1, 2])
  52. b = Tensor([3, 4])
  53. @trace(symbolic=True, capture_as_const=True)
  54. def fwd(a, b):
  55. return (a + b) * 2
  56. fwd(a, b)
  57. orig_model = io.BytesIO()
  58. fwd.dump(
  59. orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False
  60. )
  61. orig_model.seek(0)
  62. graph = Net.load(orig_model)
  63. vara = graph.var_filter.name("a").as_unique()
  64. varb = graph.var_filter.name("b").as_unique()
  65. out = F.mul(vara, varb)
  66. out = F.relu(out)
  67. opnode = list(graph.opr_filter.has_input(vara))
  68. repl_dict = {opnode[0].outputs[0]: out}
  69. graph.replace_vars(repl_dict)
  70. modified_model = io.BytesIO()
  71. graph.dump(modified_model)
  72. modified_model.seek(0)
  73. load_graph = GraphInference(modified_model)
  74. out = load_graph.run(a, b)
  75. np.testing.assert_equal(out["o"], [6, 16])
  76. def test_replace_opr():
  77. a = Tensor([1, 2])
  78. b = Tensor([3, 4])
  79. @trace(symbolic=True, capture_as_const=True)
  80. def fwd(a, b):
  81. return (a + b) * 2
  82. fwd(a, b)
  83. orig_model = io.BytesIO()
  84. fwd.dump(
  85. orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False
  86. )
  87. orig_model.seek(0)
  88. graph = Net.load(orig_model)
  89. vara = graph.var_filter.name("a").as_unique()
  90. varb = graph.var_filter.name("b").as_unique()
  91. out1 = F.sub(vara, varb)
  92. out1 = F.relu(out1)
  93. out1 = graph.add_dep_oprs(out1)
  94. orig_opr = graph.opr_filter.has_input(vara).as_unique()
  95. repl_dict = {orig_opr: out1[0].owner}
  96. graph.replace_oprs(repl_dict)
  97. modified_model1 = io.BytesIO()
  98. graph.dump(modified_model1)
  99. modified_model1.seek(0)
  100. load_graph = GraphInference(modified_model1)
  101. out = load_graph.run(a, b)
  102. np.testing.assert_equal(out["o"], [0, 0])
  103. def test_modify_params():
  104. a = Tensor([1, 2])
  105. b = Tensor([3, 4])
  106. @trace(symbolic=True, capture_as_const=True)
  107. def fwd(a, b):
  108. return (a + b) * 2
  109. fwd(a, b)
  110. orig_model = io.BytesIO()
  111. fwd.dump(
  112. orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False
  113. )
  114. orig_model.seek(0)
  115. graph = Net.load(orig_model)
  116. param_const = graph.params_filter.as_unique()
  117. param_const.set_value(3)
  118. modified_model = io.BytesIO()
  119. graph.dump(modified_model)
  120. modified_model.seek(0)
  121. load_graph = GraphInference(modified_model)
  122. out = load_graph.run(a, b)
  123. np.testing.assert_equal(out["o"], [12, 18])
  124. def test_make_const():
  125. a = Tensor([1, 2])
  126. b = Tensor([3, 4])
  127. @trace(symbolic=True, capture_as_const=True)
  128. def fwd(a, b):
  129. return (a + b) * 2
  130. fwd(a, b)
  131. orig_model = io.BytesIO()
  132. fwd.dump(
  133. orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False
  134. )
  135. orig_model.seek(0)
  136. graph = Net.load(orig_model)
  137. const_b = graph.make_const(np.array([0.0, 0.0]), name="b")
  138. varb = graph.var_filter.name("b").as_unique()
  139. repl_dict = {varb: const_b}
  140. graph.replace_vars(repl_dict)
  141. modified_model = io.BytesIO()
  142. graph.dump(modified_model)
  143. modified_model.seek(0)
  144. load_graph = GraphInference(modified_model)
  145. out = load_graph.run(a)
  146. np.testing.assert_equal(out["o"], [2, 4])
  147. def test_add_input():
  148. a = Tensor([1, 2])
  149. b = Tensor([3, 4])
  150. @trace(symbolic=True, capture_as_const=True)
  151. def fwd(a, b):
  152. return (a + b) * 2
  153. fwd(a, b)
  154. orig_model = io.BytesIO()
  155. fwd.dump(
  156. orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False
  157. )
  158. orig_model.seek(0)
  159. graph = Net.load(orig_model)
  160. inp_c = graph.make_input_node((2,), np.int32, name="c")
  161. varo = graph.var_filter.name("o").as_unique()
  162. out = F.add(varo, inp_c)
  163. out.name = "o1"
  164. graph.remove_output(varo)
  165. graph.add_output(out)
  166. modified_model = io.BytesIO()
  167. graph.dump(modified_model)
  168. modified_model.seek(0)
  169. load_graph = GraphInference(modified_model)
  170. out = load_graph.run(a, b, a)
  171. np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy())
  172. def test_add_remove_output():
  173. a = Tensor([1.0, 2.0])
  174. b = Tensor([3.0, 4.0])
  175. @trace(symbolic=True, capture_as_const=True)
  176. def fwd(a, b):
  177. return (a + b) * 2, (a - b)
  178. fwd(a, b)
  179. orig_model = io.BytesIO()
  180. fwd.dump(
  181. orig_model,
  182. arg_names=["a", "b"],
  183. output_names=["o1", "o2"],
  184. optimize_for_inference=False,
  185. )
  186. orig_model.seek(0)
  187. net = Net.load(orig_model)
  188. var_a = net.var_filter.name("a").as_unique()
  189. var_b = net.var_filter.name("b").as_unique()
  190. y1 = (var_a + var_b) * 3
  191. y2 = F.sigmoid(var_a + var_b)
  192. net.remove_output(*net.output_vars)
  193. y1.name = "new_o1"
  194. y2.name = "new_o2"
  195. net.add_output(y1, y2)
  196. modified_model = io.BytesIO()
  197. net.dump(modified_model)
  198. modified_model.seek(0)
  199. g = GraphInference(modified_model)
  200. out = g.run(a.numpy(), b.numpy())
  201. np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy())
  202. np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy())
  203. def test_query():
  204. class Model(M.Module):
  205. def __init__(self):
  206. super().__init__()
  207. self.conv1 = M.Conv2d(3, 32, 3)
  208. self.conv2 = M.Conv2d(32, 32, 3)
  209. self.conv3 = M.Conv2d(32, 32, 3)
  210. def forward(self, data):
  211. x = self.conv1(data)
  212. x = self.conv2(x)
  213. x = self.conv3(x)
  214. return x
  215. n = Model()
  216. @trace(symbolic=True, capture_as_const=True)
  217. def fwd(data):
  218. return n(data)
  219. fwd(Tensor(np.random.random((1, 3, 224, 224))))
  220. orig_model = io.BytesIO()
  221. fwd.dump(
  222. orig_model,
  223. arg_names=["data"],
  224. output_names="o",
  225. keep_opr_name=True,
  226. keep_var_name=True,
  227. optimize_for_inference=False,
  228. )
  229. orig_model.seek(0)
  230. graph = Net.load(orig_model)
  231. r = graph.data_providers_filter.as_count()
  232. assert r == 1
  233. opr = graph.get_opr_by_type(Host2DeviceCopy)
  234. assert isinstance(opr, Host2DeviceCopy)
  235. r1 = graph.params_filter.as_count()
  236. assert r1 == 6
  237. r2 = graph.opr_filter.type(N.ConvolutionForward).as_count()
  238. assert r2 == 3
  239. r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count()
  240. assert r3 == len(graph.all_oprs) - r2
  241. var = graph.var_filter.name("data").as_unique()
  242. r4 = graph.opr_filter.has_input(var).as_count()
  243. assert r4 == 1
  244. r5 = graph.opr_filter.name("data").as_count()
  245. assert r5 == 1
  246. opr = graph.get_opr_by_name("data")
  247. assert isinstance(opr, Host2DeviceCopy)
  248. var = graph.get_var_by_name("data")
  249. assert isinstance(var, VarNode)
  250. r6 = graph.var_filter.name("*bias").as_count()
  251. assert r6 == 3
  252. def test_optimize_for_inference():
  253. @trace(symbolic=True, capture_as_const=True)
  254. def f(x):
  255. return F.exp(x)
  256. orig_model = io.BytesIO()
  257. f(Tensor(5.0))
  258. f.dump(orig_model, optimize_for_inference=False)
  259. orig_model.seek(0)
  260. optimize_model = io.BytesIO()
  261. net = Net.load(orig_model)
  262. net.dump(optimize_model, enable_io16xc32=True)
  263. optimize_model.seek(0)
  264. res = G.load_graph(optimize_model)
  265. computing_input = res.output_vars_list[0].owner.inputs[0]
  266. assert computing_input.dtype == np.float16
  267. def test_reset_batchsize():
  268. @trace(symbolic=True, capture_as_const=True)
  269. def f(x):
  270. return F.exp(x)
  271. orig_model = io.BytesIO()
  272. f(Tensor(np.random.random((3, 3, 224, 224))))
  273. f.dump(orig_model, optimize_for_inference=False)
  274. orig_model.seek(0)
  275. modified_model = io.BytesIO()
  276. net = Net.load(orig_model)
  277. net.reset_batch_size(1)
  278. net.dump(modified_model, optimize_for_inference=False)
  279. modified_model.seek(0)
  280. net1 = Net.load(modified_model)
  281. assert net1.data_providers_filter.as_unique().shape[0] == 1
  282. def test_modify_opr_name():
  283. @trace(symbolic=True, capture_as_const=True)
  284. def f(x):
  285. return F.exp(x)
  286. orig_model = io.BytesIO()
  287. f(Tensor(np.random.random((3, 3, 224, 224))))
  288. f.dump(orig_model, arg_names=["a"], optimize_for_inference=False)
  289. orig_model.seek(0)
  290. modified_model = io.BytesIO()
  291. net = Net.load(orig_model)
  292. net.modify_opr_names("net")
  293. net.modify_opr_names(lambda x: "net1." + x)
  294. net.dump(modified_model, optimize_for_inference=False)
  295. modified_model.seek(0)
  296. net1 = Net.load(modified_model)
  297. assert net1.data_providers_filter.as_unique().name == "net1.net.a"
  298. def test_dump_cond_take():
  299. a = Tensor([1.0, 2.0])
  300. @trace(symbolic=True, capture_as_const=True)
  301. def fwd(a):
  302. return F.cond_take(a > 1, a)
  303. fwd(a)
  304. orig_model = io.BytesIO()
  305. fwd.dump(
  306. orig_model,
  307. arg_names=["a"],
  308. output_names=["o1", "o2"],
  309. optimize_for_inference=False,
  310. )
  311. orig_model.seek(0)
  312. net = Net.load(orig_model)
  313. var_a = net.input_vars[0]
  314. val, idx = F.cond_take(var_a > 1, var_a)
  315. net.remove_output(*net.output_vars)
  316. val.name = "value"
  317. idx.name = "index"
  318. net.add_output(val, idx)
  319. modified_model = io.BytesIO()
  320. net.dump(modified_model)
  321. modified_model.seek(0)
  322. g = GraphInference(modified_model)
  323. out = g.run(a.numpy())
  324. data = a.numpy()
  325. mask = a.numpy() > 1
  326. np.testing.assert_equal(out["index"], np.where(mask.reshape(-1))[0])
  327. np.testing.assert_equal(out["value"], data[mask])
  328. def test_set_symbolic_shape():
  329. a = Tensor([1.0, 2.0])
  330. @trace(symbolic=True, capture_as_const=True)
  331. def fwd(a):
  332. return F.relu(a * 2)
  333. fwd(a)
  334. orig_model = io.BytesIO()
  335. fwd.dump(
  336. orig_model, arg_names=["a"], output_names=["o"], optimize_for_inference=False,
  337. )
  338. orig_model.seek(0)
  339. net = Net.load(orig_model)
  340. var_a = net.input_vars[0]
  341. saved_symbolic_shape = set_symbolic_shape(True)
  342. assert isinstance(var_a.shape, VarNode)
  343. set_symbolic_shape(False)
  344. assert var_a.shape == var_a.partial_shape
  345. set_symbolic_shape(saved_symbolic_shape)

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