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

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