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_modification.py 14 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  2. #
  3. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  4. #
  5. # Unless required by applicable law or agreed to in writing,
  6. # software distributed under the License is distributed on an
  7. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8. import pickle
  9. from collections import defaultdict
  10. from itertools import chain
  11. import numpy as np
  12. import megengine.functional as F
  13. import megengine.module as M
  14. import megengine.module.qat as qat
  15. from megengine.module.identity import Identity
  16. from megengine.traced_module import TracedModule, trace_module
  17. from megengine.traced_module.expr import CallFunction, CallMethod, Expr, GetAttr, Input
  18. from megengine.traced_module.node import ModuleNode, Node, TensorNode
  19. class IdentityMod(M.Module):
  20. def forward(self, x):
  21. return x
  22. class MyBlock(M.Module):
  23. def __init__(self, in_channels=3, channels=3):
  24. super(MyBlock, self).__init__()
  25. self.conv1 = M.Conv2d(in_channels, channels, 3, 1, padding=1, bias=False)
  26. self.bn1 = M.BatchNorm2d(channels)
  27. self.nothing = IdentityMod()
  28. def forward(self, x):
  29. x = self.conv1(x)
  30. x = self.bn1(x)
  31. x = F.relu(x) + 1
  32. x = self.nothing(x)
  33. return x
  34. class MyModule(M.Module):
  35. def __init__(self):
  36. super(MyModule, self).__init__()
  37. self.block0 = MyBlock()
  38. self.block1 = MyBlock()
  39. self.nothing = IdentityMod()
  40. def forward(self, x):
  41. x = self.block0(x)
  42. x = self.block1(x)
  43. x = self.nothing(x)
  44. return x
  45. class MyBlock1(M.Module):
  46. def forward(self, a):
  47. y = F.concat([a, a])
  48. return a, y
  49. class MyModule1(M.Module):
  50. def __init__(self):
  51. super().__init__()
  52. self.block0 = MyBlock1()
  53. self.block1 = MyBlock1()
  54. def forward(self, a):
  55. a, y1 = self.block0(a)
  56. a = a + 1
  57. a, y2 = self.block1(a)
  58. return a, y1 + y2
  59. class NewModule(M.Module):
  60. def __init__(self, traced_module):
  61. super(NewModule, self).__init__()
  62. self.module = traced_module
  63. def forward(self, x):
  64. x = x - 1
  65. x = self.module(x)
  66. x = x + 1
  67. return x
  68. def _check_expr_users(flattened_module):
  69. node_user = defaultdict(list)
  70. for expr in flattened_module.graph._exprs:
  71. for node in expr.inputs:
  72. node_user[node].append(expr)
  73. for node in flattened_module.graph.nodes():
  74. node.users.sort(key=lambda m: m._id)
  75. node_user[node].sort(key=lambda m: m._id)
  76. assert node.users == node_user[node]
  77. def _init_cls(cls):
  78. module = cls()
  79. x = F.ones((1, 3, 3, 3))
  80. y = module(x)
  81. traced_module = trace_module(module, x)
  82. return traced_module, x, y
  83. def _init_block():
  84. return _init_cls(MyBlock)
  85. def _init_module():
  86. return _init_cls(MyModule)
  87. def test_search():
  88. traced_module, *_ = _init_block()
  89. graph = traced_module.graph
  90. relu_expr = graph.get_function_by_type(F.relu).as_unique()
  91. assert isinstance(relu_expr, CallFunction) and relu_expr.func == F.relu
  92. conv_node = graph.get_module_by_type(M.Conv2d).as_unique()
  93. assert isinstance(conv_node, ModuleNode) and conv_node.module_type == M.Conv2d
  94. add_expr = graph.get_method_by_type("__add__").as_unique()
  95. assert isinstance(add_expr, CallMethod) and add_expr.method == "__add__"
  96. conv_node = graph.get_node_by_name("MyBlock_conv1").as_unique()
  97. assert isinstance(conv_node, ModuleNode) and conv_node.module_type == M.Conv2d
  98. def test_producer_and_users():
  99. traced_module, *_ = _init_module()
  100. def _check(exprs):
  101. for expr in exprs:
  102. for n in chain(expr.inputs, expr.outputs):
  103. if not isinstance(n.expr, Input):
  104. assert n.expr in exprs
  105. for e in n.users:
  106. assert e in exprs
  107. assert n in e.inputs
  108. for mod in traced_module.modules():
  109. if not hasattr(mod, "argdef_graph_map"):
  110. continue
  111. for g in mod.argdef_graph_map.values():
  112. _check(g._exprs)
  113. def test_insert():
  114. traced_module, x, expect = _init_block()
  115. graph = traced_module.graph
  116. relu_out = graph.get_function_by_type(F.relu).as_unique().outputs[0]
  117. with graph.insert_exprs():
  118. neg_out = F.neg(relu_out)
  119. graph.replace_node({relu_out: neg_out})
  120. graph.compile()
  121. np.testing.assert_allclose(expect - 1, 1 - traced_module(x), atol=1e-6)
  122. def test_insert_module():
  123. class Neg(M.Module):
  124. def __init__(self, name):
  125. super().__init__(name)
  126. self.identity = M.Identity()
  127. self.identity_list = [M.Identity(), M.Identity()]
  128. self.identity_dict = {"0": M.Identity(), "1": M.Identity()}
  129. self.param = F.zeros((1,))
  130. def forward(self, x):
  131. x = self.identity(x)
  132. for m in self.identity_dict:
  133. x = self.identity_dict[m](x)
  134. for m in self.identity_list:
  135. x = m(x)
  136. return F.neg(x) + self.param
  137. traced_module, x, expect = _init_block()
  138. graph = traced_module.graph
  139. relu_out = graph.get_function_by_type(F.relu).as_unique().outputs[0]
  140. self = graph.inputs[0]
  141. setattr(traced_module, "neg", Neg(name="neg"))
  142. setattr(traced_module, "neg2", Neg(name="neg"))
  143. setattr(traced_module, "param", F.zeros((1,)))
  144. with graph.insert_exprs():
  145. neg_out = self.neg(relu_out)
  146. neg_out = self.neg2(relu_out)
  147. neg_out = neg_out + self.param
  148. graph.replace_node({relu_out: neg_out})
  149. graph.compile()
  150. np.testing.assert_allclose(expect - 1, 1 - traced_module(x), atol=1e-6)
  151. assert traced_module.neg.graph is not None
  152. assert traced_module.neg2.graph is not None
  153. assert traced_module.neg2.param is not None
  154. assert len(traced_module.neg.graph._exprs) == 13
  155. for n in traced_module.graph.nodes():
  156. if isinstance(n, TensorNode):
  157. assert n.value is None
  158. traced_module, x, expect = _init_module()
  159. setattr(traced_module.block0, "neg", Neg(name=None))
  160. graph = traced_module.graph
  161. self = graph.inputs[0]
  162. out_node = graph.outputs[0]
  163. with graph.insert_exprs():
  164. neg_out = self.block0.neg(out_node)
  165. graph.replace_node({out_node: neg_out})
  166. graph.compile()
  167. np.testing.assert_allclose(expect, -traced_module(x), atol=1e-6)
  168. assert isinstance(traced_module.block0.neg, TracedModule)
  169. assert traced_module.block0.neg.graph is not None
  170. setattr(traced_module.block0.neg, "neg", Neg(name=None))
  171. setattr(traced_module.block0.neg.neg, "relu", M.ReLU())
  172. out_node = graph.outputs[0]
  173. with graph.insert_exprs():
  174. neg_out = self.block0.neg.neg(out_node)
  175. neg_out = self.block0.neg.neg(neg_out)
  176. relu_out = self.block0.neg.neg.relu(neg_out)
  177. graph.replace_node({out_node: relu_out})
  178. graph.compile()
  179. np.testing.assert_allclose(F.relu(-expect), traced_module(x), atol=1e-6)
  180. assert isinstance(traced_module.block0.neg.neg, TracedModule)
  181. assert traced_module.block0.neg.neg.graph is not None
  182. def test_insert_qat_module():
  183. class concat(qat.Concat):
  184. pass
  185. traced_module, x, expect = _init_block()
  186. graph = traced_module.graph
  187. self = graph.inputs[0]
  188. out = graph.outputs[0]
  189. setattr(traced_module, "cat_0", qat.Concat())
  190. setattr(traced_module, "cat_1", concat())
  191. with graph.insert_exprs():
  192. x_0 = self.cat_0([out, out])
  193. x_1 = self.cat_1([out, x_0])
  194. graph.replace_node({out: x_1})
  195. graph.compile()
  196. x = F.copy(x)
  197. np.testing.assert_allclose(
  198. F.concat([expect, expect, expect]), traced_module(x), atol=1e-6
  199. )
  200. assert not hasattr(traced_module.cat_0, "graph")
  201. assert traced_module.cat_1.graph is not None
  202. def test_add_input_and_output():
  203. traced_module, x, y = _init_module()
  204. data_node = traced_module.graph.add_input_node(shape=(1, 3, 224, 224), name="data")
  205. traced_module.graph.add_output_node(data_node)
  206. assert data_node.name == "data"
  207. assert traced_module.graph.inputs[-1] == data_node
  208. assert len(traced_module.graph.inputs) == 3
  209. assert len(traced_module.graph.outputs) == 2
  210. y1, y2 = traced_module(x, x)
  211. np.testing.assert_equal(y1.numpy(), y.numpy())
  212. np.testing.assert_equal(y2.numpy(), x.numpy())
  213. y1, y2 = traced_module(x, y)
  214. np.testing.assert_equal(y2.numpy(), y.numpy())
  215. traced_module.graph.reset_outputs(
  216. ({"orig_out": traced_module.graph.outputs[0]}, traced_module.graph.outputs[1])
  217. )
  218. out = traced_module(x, x)
  219. assert isinstance(out, tuple)
  220. assert isinstance(out[0], dict)
  221. np.testing.assert_equal(out[0]["orig_out"].numpy(), y.numpy())
  222. np.testing.assert_equal(out[1].numpy(), x.numpy())
  223. def test_delete():
  224. traced_module, x, expect = _init_block()
  225. graph = traced_module.graph
  226. relu_expr = graph.get_function_by_type(F.relu).as_unique()
  227. node = relu_expr.outputs
  228. repl_node = relu_expr.inputs
  229. graph.replace_node({node[0]: repl_node[0]})
  230. graph.compile()
  231. np.testing.assert_allclose(expect - 1, F.relu(traced_module(x) - 1), atol=1e-6)
  232. # clear graph
  233. graph.replace_node({graph.outputs[0]: graph.inputs[1]})
  234. graph.compile()
  235. np.testing.assert_equal(len(list(graph._exprs)), 0)
  236. np.testing.assert_equal(traced_module(x).numpy(), x.numpy())
  237. def test_flatten():
  238. traced_module, x, expect = _init_module()
  239. traced_module = traced_module.flatten()
  240. assert len(traced_module.graph._exprs) == 12
  241. np.testing.assert_equal(expect.numpy(), traced_module(x).numpy())
  242. traced_module = traced_module.flatten()
  243. assert len(traced_module.graph._exprs) == 12
  244. np.testing.assert_equal(expect.numpy(), traced_module(x).numpy())
  245. traced_module, x, expect = _init_cls(MyModule1)
  246. traced_module = traced_module.flatten()
  247. _check_expr_users(traced_module)
  248. def test_id_and_name():
  249. def _check_id(traced_module):
  250. _total_ids = traced_module.graph._total_ids
  251. node_ids = [n._id for n in traced_module.graph.nodes().as_list()]
  252. assert len(set(node_ids)) == len(node_ids)
  253. assert max(node_ids) + 1 == _total_ids[0]
  254. expr_ids = [n._id for n in traced_module.graph.exprs().as_list()]
  255. assert len(set(expr_ids)) == len(expr_ids)
  256. assert max(expr_ids) + 1 == _total_ids[1]
  257. def _check_name(flatened_module):
  258. node_names = [n._name for n in flatened_module.graph.nodes().as_list()]
  259. assert len(set(node_names)) == len(node_names)
  260. traced_module, x, expect = _init_module()
  261. _check_id(traced_module)
  262. flattened_module = traced_module.flatten()
  263. _check_id(flattened_module)
  264. _check_name(flattened_module)
  265. # pickle check
  266. obj = pickle.dumps(traced_module)
  267. traced_module = pickle.loads(obj)
  268. Node._set_next_id(159)
  269. Expr._set_next_id(1024)
  270. graph = traced_module.graph
  271. for expr in graph.get_function_by_type(F.relu).as_list():
  272. relu_out = expr.outputs[0]
  273. cur_graph = expr.top_graph
  274. with cur_graph.insert_exprs():
  275. neg_out = F.neg(relu_out)
  276. cur_graph.replace_node({relu_out: neg_out})
  277. cur_graph.compile()
  278. _check_id(traced_module)
  279. flattened_module = traced_module.flatten()
  280. _check_id(flattened_module)
  281. _check_name(flattened_module)
  282. # check trace TracedModule
  283. obj = pickle.dumps(traced_module)
  284. traced_module = pickle.loads(obj)
  285. module = NewModule(traced_module)
  286. traced_module = trace_module(module, x)
  287. _check_id(traced_module)
  288. flattened_module = traced_module.flatten()
  289. _check_id(flattened_module)
  290. _check_name(flattened_module)
  291. def test_set_node_name():
  292. traced_module, x, expect = _init_module()
  293. graph = traced_module.graph
  294. output_node = graph.outputs[0]
  295. def rename(name):
  296. output_node.name = name
  297. np.testing.assert_raises(AssertionError, rename, "block1_out")
  298. rename("output")
  299. np.testing.assert_equal(str(graph.outputs[0]), "output")
  300. def add_1(x):
  301. x = x + 1
  302. x.name = "func_add_1"
  303. return x
  304. class ModuleAdd_3(M.Module):
  305. def forward(self, x):
  306. x = x + 1
  307. x.name = "module_add_1"
  308. x = x + 2
  309. return x
  310. setattr(traced_module, "add_3", ModuleAdd_3())
  311. self = graph.inputs[0]
  312. with graph.insert_exprs():
  313. x = output_node + 1
  314. x.name = "_add_1"
  315. x = add_1(x)
  316. x = self.add_3(x)
  317. graph.replace_node({output_node: x})
  318. graph.compile()
  319. assert "_add_1" in graph._namespace.used_names
  320. assert "func_add_1" in graph._namespace.used_names
  321. assert "module_add_1" in traced_module.add_3.graph._namespace.used_names
  322. def test_set_graph_name():
  323. traced_module, x, expect = _init_module()
  324. graph = traced_module.graph
  325. output_node = graph.outputs[0]
  326. node_name = output_node.name
  327. graph.name = "Top"
  328. node = graph.get_node_by_name("{}_{}".format("Top", node_name)).as_unique()
  329. assert node is output_node
  330. def test_extra_block():
  331. class PostProcess(M.Module):
  332. def forward(self, x):
  333. return x * 2
  334. class Net(M.Module):
  335. def __init__(self, traced_module):
  336. super().__init__()
  337. self.post_process = PostProcess()
  338. self.traced_module = traced_module
  339. def forward(self, x):
  340. x = self.traced_module(x)
  341. x = self.post_process(x)
  342. return x
  343. traced_module, x, expect = _init_block()
  344. module = Net(traced_module)
  345. np.testing.assert_allclose(2 * expect, module(x), atol=1e-6)
  346. traced_module = trace_module(module, x)
  347. np.testing.assert_allclose(2 * expect, traced_module(x), atol=1e-6)