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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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 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. def test_insert_qat_module():
  159. class concat(qat.Concat):
  160. pass
  161. traced_module, x, expect = _init_block()
  162. graph = traced_module.graph
  163. self = graph.inputs[0]
  164. out = graph.outputs[0]
  165. setattr(traced_module, "cat_0", qat.Concat())
  166. setattr(traced_module, "cat_1", concat())
  167. with graph.insert_exprs():
  168. x_0 = self.cat_0([out, out])
  169. x_1 = self.cat_1([out, x_0])
  170. graph.replace_node({out: x_1})
  171. graph.compile()
  172. x = F.copy(x)
  173. np.testing.assert_allclose(
  174. F.concat([expect, expect, expect]), traced_module(x), atol=1e-6
  175. )
  176. assert not hasattr(traced_module.cat_0, "graph")
  177. assert traced_module.cat_1.graph is not None
  178. def test_add_input_and_output():
  179. traced_module, x, y = _init_module()
  180. data_node = traced_module.graph.add_input_node(shape=(1, 3, 224, 224), name="data")
  181. traced_module.graph.add_output_node(data_node)
  182. assert data_node.name == "data"
  183. assert traced_module.graph.inputs[-1] == data_node
  184. assert len(traced_module.graph.inputs) == 3
  185. assert len(traced_module.graph.outputs) == 2
  186. y1, y2 = traced_module(x, x)
  187. np.testing.assert_equal(y1.numpy(), y.numpy())
  188. np.testing.assert_equal(y2.numpy(), x.numpy())
  189. y1, y2 = traced_module(x, y)
  190. np.testing.assert_equal(y2.numpy(), y.numpy())
  191. traced_module.graph.reset_outputs(
  192. ({"orig_out": traced_module.graph.outputs[0]}, traced_module.graph.outputs[1])
  193. )
  194. out = traced_module(x, x)
  195. assert isinstance(out, tuple)
  196. assert isinstance(out[0], dict)
  197. np.testing.assert_equal(out[0]["orig_out"].numpy(), y.numpy())
  198. np.testing.assert_equal(out[1].numpy(), x.numpy())
  199. def test_delete():
  200. traced_module, x, expect = _init_block()
  201. graph = traced_module.graph
  202. relu_expr = graph.get_function_by_type(F.relu).as_unique()
  203. node = relu_expr.outputs
  204. repl_node = relu_expr.inputs
  205. graph.replace_node({node[0]: repl_node[0]})
  206. graph.compile()
  207. np.testing.assert_allclose(expect - 1, F.relu(traced_module(x) - 1), atol=1e-6)
  208. # clear graph
  209. graph.replace_node({graph.outputs[0]: graph.inputs[1]})
  210. graph.compile()
  211. np.testing.assert_equal(len(list(graph._exprs)), 0)
  212. np.testing.assert_equal(traced_module(x).numpy(), x.numpy())
  213. def test_flatten():
  214. traced_module, x, expect = _init_module()
  215. traced_module = traced_module.flatten()
  216. assert len(traced_module.graph._exprs) == 12
  217. np.testing.assert_equal(expect.numpy(), traced_module(x).numpy())
  218. traced_module = traced_module.flatten()
  219. assert len(traced_module.graph._exprs) == 12
  220. np.testing.assert_equal(expect.numpy(), traced_module(x).numpy())
  221. traced_module, x, expect = _init_cls(MyModule1)
  222. traced_module = traced_module.flatten()
  223. _check_expr_users(traced_module)
  224. def test_id_and_name():
  225. def _check_id(traced_module):
  226. _total_ids = traced_module.graph._total_ids
  227. node_ids = [n._id for n in traced_module.graph.nodes().as_list()]
  228. assert len(set(node_ids)) == len(node_ids)
  229. assert max(node_ids) + 1 == _total_ids[0]
  230. expr_ids = [n._id for n in traced_module.graph.exprs().as_list()]
  231. assert len(set(expr_ids)) == len(expr_ids)
  232. assert max(expr_ids) + 1 == _total_ids[1]
  233. def _check_name(flatened_module):
  234. node_names = [n._name for n in flatened_module.graph.nodes().as_list()]
  235. assert len(set(node_names)) == len(node_names)
  236. traced_module, x, expect = _init_module()
  237. _check_id(traced_module)
  238. flattened_module = traced_module.flatten()
  239. _check_id(flattened_module)
  240. _check_name(flattened_module)
  241. # pickle check
  242. obj = pickle.dumps(traced_module)
  243. traced_module = pickle.loads(obj)
  244. Node._set_next_id(159)
  245. Expr._set_next_id(1024)
  246. graph = traced_module.graph
  247. for expr in graph.get_function_by_type(F.relu).as_list():
  248. relu_out = expr.outputs[0]
  249. cur_graph = expr.top_graph
  250. with cur_graph.insert_exprs():
  251. neg_out = F.neg(relu_out)
  252. cur_graph.replace_node({relu_out: neg_out})
  253. cur_graph.compile()
  254. _check_id(traced_module)
  255. flattened_module = traced_module.flatten()
  256. _check_id(flattened_module)
  257. _check_name(flattened_module)
  258. # check trace TracedModule
  259. obj = pickle.dumps(traced_module)
  260. traced_module = pickle.loads(obj)
  261. module = NewModule(traced_module)
  262. traced_module = trace_module(module, x)
  263. _check_id(traced_module)
  264. flattened_module = traced_module.flatten()
  265. _check_id(flattened_module)
  266. _check_name(flattened_module)
  267. def test_set_node_name():
  268. traced_module, x, expect = _init_module()
  269. graph = traced_module.graph
  270. output_node = graph.outputs[0]
  271. def rename(name):
  272. output_node.name = name
  273. np.testing.assert_raises(AssertionError, rename, "block1_out")
  274. rename("output")
  275. np.testing.assert_equal(str(graph.outputs[0]), "output")
  276. def test_set_graph_name():
  277. traced_module, x, expect = _init_module()
  278. graph = traced_module.graph
  279. output_node = graph.outputs[0]
  280. node_name = output_node.name
  281. graph.name = "Top"
  282. node = graph.get_node_by_name("{}_{}".format("Top", node_name)).as_unique()
  283. assert node is output_node
  284. def test_extra_block():
  285. class PostProcess(M.Module):
  286. def forward(self, x):
  287. return x * 2
  288. class Net(M.Module):
  289. def __init__(self, traced_module):
  290. super().__init__()
  291. self.post_process = PostProcess()
  292. self.traced_module = traced_module
  293. def forward(self, x):
  294. x = self.traced_module(x)
  295. x = self.post_process(x)
  296. return x
  297. traced_module, x, expect = _init_block()
  298. module = Net(traced_module)
  299. np.testing.assert_allclose(2 * expect, module(x), atol=1e-6)
  300. traced_module = trace_module(module, x)
  301. np.testing.assert_allclose(2 * expect, traced_module(x), atol=1e-6)

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