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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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.mul(vara, varb)
  92. out1 = F.relu(out1)
  93. out1 += 2
  94. out1 *= 3
  95. out1 = graph.add_dep_oprs(out1)
  96. orig_opr = graph.opr_filter.has_input(vara).as_unique()
  97. new_opr = out1[0].owner
  98. repl_dict = {orig_opr: new_opr}
  99. graph.replace_oprs(repl_dict)
  100. var_out = orig_opr.outputs
  101. for idx, node in enumerate(var_out):
  102. assert node.owner is new_opr
  103. assert node.owner.outputs[idx] is node
  104. modified_model1 = io.BytesIO()
  105. graph.dump(modified_model1)
  106. modified_model1.seek(0)
  107. load_graph = GraphInference(modified_model1)
  108. out = load_graph.run(a, b)
  109. np.testing.assert_equal(out["o"], [30, 60])
  110. def test_splice_network():
  111. x = F.ones((2,))
  112. y = F.ones((2,))
  113. @trace(symbolic=True, capture_as_const=True)
  114. def fun1(a, b):
  115. return (a + b) * 2
  116. @trace(symbolic=True, capture_as_const=True)
  117. def fun2(a):
  118. return a * 2 - 1
  119. model = io.BytesIO()
  120. fun1(x, y)
  121. fun2(x)
  122. fun1.dump(
  123. model,
  124. arg_names=["net1_i0", "net1_i1"],
  125. output_names=["net1_o0"],
  126. optimize_for_inference=False,
  127. )
  128. model.seek(0)
  129. net1 = Net.load(model)
  130. model.seek(0)
  131. fun2.dump(
  132. model,
  133. arg_names=["net2_i0"],
  134. output_names=["net2_o0"],
  135. optimize_for_inference=False,
  136. )
  137. model.seek(0)
  138. net2 = Net.load(model)
  139. net1.add_output(*net2.output_vars)
  140. var = net1.var_filter.name("net1_i0").as_unique()
  141. repl_var = net2.var_filter.name("net2_o0").as_unique()
  142. net1.replace_vars({var: repl_var})
  143. assert "net1_i0" not in [var.name for var in net1.all_vars]
  144. assert "net2_i0" in [var.name for var in net1.all_vars]
  145. model.seek(0)
  146. net1.dump(model, keep_var_name=2, optimize_for_inference=False)
  147. model.seek(0)
  148. net = Net.load(model)
  149. assert "net1_i0" not in [var.name for var in net.all_vars]
  150. assert "net2_i0" in [var.name for var in net.all_vars]
  151. def test_modify_params():
  152. a = Tensor([1, 2])
  153. b = Tensor([3, 4])
  154. @trace(symbolic=True, capture_as_const=True)
  155. def fwd(a, b):
  156. return (a + b) * 2
  157. fwd(a, b)
  158. orig_model = io.BytesIO()
  159. fwd.dump(
  160. orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False
  161. )
  162. orig_model.seek(0)
  163. graph = Net.load(orig_model)
  164. param_const = graph.params_filter.as_unique()
  165. param_const.set_value(3)
  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)
  171. np.testing.assert_equal(out["o"], [12, 18])
  172. def test_make_const():
  173. a = Tensor([1, 2])
  174. b = Tensor([3, 4])
  175. @trace(symbolic=True, capture_as_const=True)
  176. def fwd(a, b):
  177. return (a + b) * 2
  178. fwd(a, b)
  179. orig_model = io.BytesIO()
  180. fwd.dump(
  181. orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False
  182. )
  183. orig_model.seek(0)
  184. graph = Net.load(orig_model)
  185. const_b = graph.make_const(np.array([0.0, 0.0]), name="b")
  186. varb = graph.var_filter.name("b").as_unique()
  187. repl_dict = {varb: const_b}
  188. graph.replace_vars(repl_dict)
  189. modified_model = io.BytesIO()
  190. graph.dump(modified_model)
  191. modified_model.seek(0)
  192. load_graph = GraphInference(modified_model)
  193. out = load_graph.run(a)
  194. np.testing.assert_equal(out["o"], [2, 4])
  195. def test_add_input():
  196. a = Tensor([1, 2])
  197. b = Tensor([3, 4])
  198. @trace(symbolic=True, capture_as_const=True)
  199. def fwd(a, b):
  200. return (a + b) * 2
  201. fwd(a, b)
  202. orig_model = io.BytesIO()
  203. fwd.dump(
  204. orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False
  205. )
  206. orig_model.seek(0)
  207. graph = Net.load(orig_model)
  208. inp_c = graph.make_input_node((2,), np.int32, name="c")
  209. varo = graph.var_filter.name("o").as_unique()
  210. out = F.add(varo, inp_c)
  211. out.name = "o1"
  212. graph.remove_output(varo)
  213. graph.add_output(out)
  214. modified_model = io.BytesIO()
  215. graph.dump(modified_model)
  216. modified_model.seek(0)
  217. load_graph = GraphInference(modified_model)
  218. out = load_graph.run(a, b, a)
  219. np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy())
  220. def test_add_remove_output():
  221. a = Tensor([1.0, 2.0])
  222. b = Tensor([3.0, 4.0])
  223. @trace(symbolic=True, capture_as_const=True)
  224. def fwd(a, b):
  225. return (a + b) * 2, (a - b)
  226. fwd(a, b)
  227. orig_model = io.BytesIO()
  228. fwd.dump(
  229. orig_model,
  230. arg_names=["a", "b"],
  231. output_names=["o1", "o2"],
  232. optimize_for_inference=False,
  233. )
  234. orig_model.seek(0)
  235. net = Net.load(orig_model)
  236. var_a = net.var_filter.name("a").as_unique()
  237. var_b = net.var_filter.name("b").as_unique()
  238. y1 = (var_a + var_b) * 3
  239. y2 = F.sigmoid(var_a + var_b)
  240. net.remove_output(*net.output_vars)
  241. y1.name = "new_o1"
  242. y2.name = "new_o2"
  243. net.add_output(y1, y2)
  244. modified_model = io.BytesIO()
  245. net.dump(modified_model)
  246. modified_model.seek(0)
  247. g = GraphInference(modified_model)
  248. out = g.run(a.numpy(), b.numpy())
  249. np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy())
  250. np.testing.assert_almost_equal(out["new_o2"], (F.sigmoid((a + b))).numpy())
  251. def test_query():
  252. class Model(M.Module):
  253. def __init__(self):
  254. super().__init__()
  255. self.conv1 = M.Conv2d(3, 32, 3)
  256. self.conv2 = M.Conv2d(32, 32, 3)
  257. self.conv3 = M.Conv2d(32, 32, 3)
  258. def forward(self, data):
  259. x = self.conv1(data)
  260. x = self.conv2(x)
  261. x = self.conv3(x)
  262. return x
  263. n = Model()
  264. @trace(symbolic=True, capture_as_const=True)
  265. def fwd(data):
  266. return n(data)
  267. fwd(Tensor(np.random.random((1, 3, 224, 224))))
  268. orig_model = io.BytesIO()
  269. fwd.dump(
  270. orig_model,
  271. arg_names=["data"],
  272. output_names="o",
  273. keep_opr_name=True,
  274. keep_var_name=True,
  275. optimize_for_inference=False,
  276. )
  277. orig_model.seek(0)
  278. graph = Net.load(orig_model)
  279. r = graph.data_providers_filter.as_count()
  280. assert r == 1
  281. opr = graph.get_opr_by_type(Host2DeviceCopy)
  282. assert isinstance(opr, Host2DeviceCopy)
  283. r1 = graph.params_filter.as_count()
  284. assert r1 == 6
  285. r2 = graph.opr_filter.type(N.ConvolutionForward).as_count()
  286. assert r2 == 3
  287. r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count()
  288. assert r3 == len(graph.all_oprs) - r2
  289. var = graph.var_filter.name("data").as_unique()
  290. r4 = graph.opr_filter.has_input(var).as_count()
  291. assert r4 == 1
  292. r5 = graph.opr_filter.name("data").as_count()
  293. assert r5 == 1
  294. opr = graph.get_opr_by_name("data")
  295. assert isinstance(opr, Host2DeviceCopy)
  296. var = graph.get_var_by_name("data")
  297. assert isinstance(var, VarNode)
  298. r6 = graph.var_filter.name("*bias").as_count()
  299. assert r6 == 3
  300. def test_optimize_for_inference():
  301. @trace(symbolic=True, capture_as_const=True)
  302. def f(x):
  303. return F.exp(x)
  304. orig_model = io.BytesIO()
  305. f(Tensor(5.0))
  306. f.dump(orig_model, optimize_for_inference=False)
  307. orig_model.seek(0)
  308. optimize_model = io.BytesIO()
  309. net = Net.load(orig_model)
  310. net.dump(optimize_model, enable_io16xc32=True)
  311. optimize_model.seek(0)
  312. res = G.load_graph(optimize_model)
  313. computing_input = res.output_vars_list[0].owner.inputs[0]
  314. assert computing_input.dtype == np.float16
  315. def test_reset_batchsize():
  316. @trace(symbolic=True, capture_as_const=True)
  317. def f(x):
  318. return F.exp(x)
  319. orig_model = io.BytesIO()
  320. f(Tensor(np.random.random((3, 3, 224, 224))))
  321. f.dump(orig_model, optimize_for_inference=False)
  322. orig_model.seek(0)
  323. modified_model = io.BytesIO()
  324. net = Net.load(orig_model)
  325. net.reset_batch_size(1)
  326. net.dump(modified_model, optimize_for_inference=False)
  327. modified_model.seek(0)
  328. net1 = Net.load(modified_model)
  329. assert net1.data_providers_filter.as_unique().shape[0] == 1
  330. def test_modify_opr_name():
  331. @trace(symbolic=True, capture_as_const=True)
  332. def f(x):
  333. return F.exp(x)
  334. orig_model = io.BytesIO()
  335. f(Tensor(np.random.random((3, 3, 224, 224))))
  336. f.dump(orig_model, arg_names=["a"], optimize_for_inference=False)
  337. orig_model.seek(0)
  338. modified_model = io.BytesIO()
  339. net = Net.load(orig_model)
  340. net.modify_opr_names("net")
  341. net.modify_opr_names(lambda x: "net1." + x)
  342. net.dump(modified_model, optimize_for_inference=False)
  343. modified_model.seek(0)
  344. net1 = Net.load(modified_model)
  345. assert net1.data_providers_filter.as_unique().name == "net1.net.a"
  346. def test_dump_cond_take():
  347. a = Tensor([1.0, 2.0])
  348. @trace(symbolic=True, capture_as_const=True)
  349. def fwd(a):
  350. return F.cond_take(a > 1, a)
  351. fwd(a)
  352. orig_model = io.BytesIO()
  353. fwd.dump(
  354. orig_model,
  355. arg_names=["a"],
  356. output_names=["o1", "o2"],
  357. optimize_for_inference=False,
  358. )
  359. orig_model.seek(0)
  360. net = Net.load(orig_model)
  361. var_a = net.input_vars[0]
  362. val, idx = F.cond_take(var_a > 1, var_a)
  363. net.remove_output(*net.output_vars)
  364. val.name = "value"
  365. idx.name = "index"
  366. net.add_output(val, idx)
  367. modified_model = io.BytesIO()
  368. net.dump(modified_model)
  369. modified_model.seek(0)
  370. g = GraphInference(modified_model)
  371. out = g.run(a.numpy())
  372. data = a.numpy()
  373. mask = a.numpy() > 1
  374. np.testing.assert_equal(out["index"], np.where(mask.reshape(-1))[0])
  375. np.testing.assert_equal(out["value"], data[mask])
  376. def test_set_symbolic_shape():
  377. a = Tensor([1.0, 2.0])
  378. @trace(symbolic=True, capture_as_const=True)
  379. def fwd(a):
  380. return F.relu(a * 2)
  381. fwd(a)
  382. orig_model = io.BytesIO()
  383. fwd.dump(
  384. orig_model, arg_names=["a"], output_names=["o"], optimize_for_inference=False,
  385. )
  386. orig_model.seek(0)
  387. net = Net.load(orig_model)
  388. var_a = net.input_vars[0]
  389. saved_symbolic_shape = set_symbolic_shape(True)
  390. assert isinstance(var_a.shape, VarNode)
  391. set_symbolic_shape(False)
  392. assert var_a.shape == var_a.partial_shape
  393. set_symbolic_shape(saved_symbolic_shape)
  394. def test_replace_var_in_different_network():
  395. a = Tensor([1, 2])
  396. b = Tensor([3, 4])
  397. @trace(symbolic=True, capture_as_const=True)
  398. def fwd(a, b):
  399. return (a + b) * 2
  400. @trace(symbolic=True, capture_as_const=True)
  401. def fwd1(c, d):
  402. return c + d
  403. fwd(a, b)
  404. orig_model = io.BytesIO()
  405. fwd.dump(
  406. orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False
  407. )
  408. orig_model.seek(0)
  409. fwd1(a, b)
  410. orig_model1 = io.BytesIO()
  411. fwd1.dump(
  412. orig_model1,
  413. arg_names=["c", "d"],
  414. output_names="o",
  415. optimize_for_inference=False,
  416. )
  417. orig_model1.seek(0)
  418. graph = Net.load(orig_model)
  419. graph1 = Net.load(orig_model1)
  420. vara = graph.var_filter.name("a").as_unique()
  421. varb = graph.var_filter.name("b").as_unique()
  422. varo = graph1.var_filter.name("o").as_unique()
  423. graph.replace_vars({vara: varo, varb: varo})
  424. modified_model = io.BytesIO()
  425. graph.dump(modified_model)
  426. modified_model.seek(0)
  427. load_graph = GraphInference(modified_model)
  428. out = load_graph.run(a, b)
  429. np.testing.assert_equal(out["o"], [16, 24])