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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. from megengine.module.identity import Identity
  15. from megengine.traced_module import trace_module
  16. from megengine.traced_module.expr import CallFunction, CallMethod, Expr, GetAttr, Input
  17. from megengine.traced_module.node import ModuleNode, Node
  18. class IdentityMod(M.Module):
  19. def forward(self, x):
  20. return x
  21. class MyBlock(M.Module):
  22. def __init__(self, in_channels=3, channels=3):
  23. super(MyBlock, self).__init__()
  24. self.conv1 = M.Conv2d(in_channels, channels, 3, 1, padding=1, bias=False)
  25. self.bn1 = M.BatchNorm2d(channels)
  26. self.nothing = IdentityMod()
  27. def forward(self, x):
  28. x = self.conv1(x)
  29. x = self.bn1(x)
  30. x = F.relu(x) + 1
  31. x = self.nothing(x)
  32. return x
  33. class MyModule(M.Module):
  34. def __init__(self):
  35. super(MyModule, self).__init__()
  36. self.block0 = MyBlock()
  37. self.block1 = MyBlock()
  38. self.nothing = IdentityMod()
  39. def forward(self, x):
  40. x = self.block0(x)
  41. x = self.block1(x)
  42. x = self.nothing(x)
  43. return x
  44. class MyBlock1(M.Module):
  45. def forward(self, a):
  46. y = F.concat([a, a])
  47. return a, y
  48. class MyModule1(M.Module):
  49. def __init__(self):
  50. super().__init__()
  51. self.block0 = MyBlock1()
  52. self.block1 = MyBlock1()
  53. def forward(self, a):
  54. a, y1 = self.block0(a)
  55. a = a + 1
  56. a, y2 = self.block1(a)
  57. return a, y1 + y2
  58. class NewModule(M.Module):
  59. def __init__(self, traced_module):
  60. super(NewModule, self).__init__()
  61. self.module = traced_module
  62. def forward(self, x):
  63. x = x - 1
  64. x = self.module(x)
  65. x = x + 1
  66. return x
  67. def _check_expr_users(traced_module):
  68. node_user = defaultdict(list)
  69. for expr in traced_module.graph._exprs:
  70. for node in expr.inputs:
  71. node_user[node].append(expr)
  72. for node in traced_module.graph.nodes():
  73. node.users.sort(key=lambda m: m._id)
  74. node_user[node].sort(key=lambda m: m._id)
  75. assert node.users == node_user[node]
  76. def _init_cls(cls):
  77. module = cls()
  78. x = F.ones((1, 3, 3, 3))
  79. y = module(x)
  80. traced_module = trace_module(module, x)
  81. return traced_module, x, y
  82. def _init_block():
  83. return _init_cls(MyBlock)
  84. def _init_module():
  85. return _init_cls(MyModule)
  86. def test_search():
  87. traced_module, *_ = _init_block()
  88. graph = traced_module.graph
  89. relu_expr = graph.get_function_by_type(F.relu).as_unique()
  90. assert isinstance(relu_expr, CallFunction) and relu_expr.func == F.relu
  91. conv_node = graph.get_module_by_type(M.Conv2d).as_unique()
  92. assert isinstance(conv_node, ModuleNode) and conv_node.module_type == M.Conv2d
  93. add_expr = graph.get_method_by_type("__add__").as_unique()
  94. assert isinstance(add_expr, CallMethod) and add_expr.method == "__add__"
  95. conv_node = graph.get_node_by_name("MyBlock_conv1").as_unique()
  96. assert isinstance(conv_node, ModuleNode) and conv_node.module_type == M.Conv2d
  97. def test_producer_and_users():
  98. traced_module, *_ = _init_module()
  99. def _check(exprs):
  100. for expr in exprs:
  101. for n in chain(expr.inputs, expr.outputs):
  102. if not isinstance(n.expr, Input):
  103. assert n.expr in exprs
  104. for e in n.users:
  105. assert e in exprs
  106. assert n in e.inputs
  107. for mod in traced_module.modules():
  108. if not hasattr(mod, "argdef_graph_map"):
  109. continue
  110. for g in mod.argdef_graph_map.values():
  111. _check(g._exprs)
  112. def test_insert():
  113. traced_module, x, expect = _init_block()
  114. graph = traced_module.graph
  115. relu_out = graph.get_function_by_type(F.relu).as_unique().outputs[0]
  116. with graph.insert_exprs():
  117. neg_out = F.neg(relu_out)
  118. graph.replace_node({relu_out: neg_out})
  119. graph.compile()
  120. np.testing.assert_allclose(expect - 1, 1 - traced_module(x), atol=1e-6)
  121. def test_insert_module():
  122. class Neg(M.Module):
  123. def forward(self, x):
  124. return F.neg(x)
  125. traced_module, x, expect = _init_block()
  126. graph = traced_module.graph
  127. relu_out = graph.get_function_by_type(F.relu).as_unique().outputs[0]
  128. self = graph.inputs[0]
  129. setattr(traced_module, "neg", Neg())
  130. with graph.insert_exprs():
  131. neg_out = self.neg(relu_out)
  132. graph.replace_node({relu_out: neg_out})
  133. graph.compile()
  134. np.testing.assert_allclose(expect - 1, 1 - traced_module(x), atol=1e-6)
  135. assert traced_module.neg.graph is not None
  136. assert len(traced_module.neg.graph._exprs) == 1
  137. def test_add_input_and_output():
  138. traced_module, x, y = _init_module()
  139. data_node = traced_module.graph.add_input_node(shape=(1, 3, 224, 224), name="data")
  140. traced_module.graph.add_output_node(data_node)
  141. assert data_node.name == "data"
  142. assert traced_module.graph.inputs[-1] == data_node
  143. assert len(traced_module.graph.inputs) == 3
  144. assert len(traced_module.graph.outputs) == 2
  145. y1, y2 = traced_module(x, x)
  146. np.testing.assert_equal(y1.numpy(), y.numpy())
  147. np.testing.assert_equal(y2.numpy(), x.numpy())
  148. y1, y2 = traced_module(x, y)
  149. np.testing.assert_equal(y2.numpy(), y.numpy())
  150. traced_module.graph.reset_outputs(
  151. ({"orig_out": traced_module.graph.outputs[0]}, traced_module.graph.outputs[1])
  152. )
  153. out = traced_module(x, x)
  154. assert isinstance(out, tuple)
  155. assert isinstance(out[0], dict)
  156. np.testing.assert_equal(out[0]["orig_out"].numpy(), y.numpy())
  157. np.testing.assert_equal(out[1].numpy(), x.numpy())
  158. def test_delete():
  159. traced_module, x, expect = _init_block()
  160. graph = traced_module.graph
  161. relu_expr = graph.get_function_by_type(F.relu).as_unique()
  162. node = relu_expr.outputs
  163. repl_node = relu_expr.inputs
  164. graph.replace_node({node[0]: repl_node[0]})
  165. graph.compile()
  166. np.testing.assert_allclose(expect - 1, F.relu(traced_module(x) - 1), atol=1e-6)
  167. # clear graph
  168. graph.replace_node({graph.outputs[0]: graph.inputs[1]})
  169. graph.compile()
  170. np.testing.assert_equal(len(list(graph._exprs)), 0)
  171. np.testing.assert_equal(traced_module(x).numpy(), x.numpy())
  172. def test_flatten():
  173. traced_module, x, expect = _init_module()
  174. traced_module = traced_module.flatten()
  175. assert len(traced_module.graph._exprs) == 12
  176. np.testing.assert_equal(expect.numpy(), traced_module(x).numpy())
  177. traced_module = traced_module.flatten()
  178. assert len(traced_module.graph._exprs) == 12
  179. np.testing.assert_equal(expect.numpy(), traced_module(x).numpy())
  180. traced_module, x, expect = _init_cls(MyModule1)
  181. traced_module = traced_module.flatten()
  182. _check_expr_users(traced_module)
  183. def test_id_and_name():
  184. def _check_id(traced_module):
  185. _total_ids = traced_module.graph._total_ids
  186. node_ids = [n._id for n in traced_module.graph.nodes().as_list()]
  187. assert len(set(node_ids)) == len(node_ids)
  188. assert max(node_ids) + 1 == _total_ids[0]
  189. expr_ids = [n._id for n in traced_module.graph.exprs().as_list()]
  190. assert len(set(expr_ids)) == len(expr_ids)
  191. assert max(expr_ids) + 1 == _total_ids[1]
  192. def _check_name(flatened_module):
  193. node_names = [n._name for n in flatened_module.graph.nodes().as_list()]
  194. assert len(set(node_names)) == len(node_names)
  195. traced_module, x, expect = _init_module()
  196. _check_id(traced_module)
  197. flattened_module = traced_module.flatten()
  198. _check_id(flattened_module)
  199. _check_name(flattened_module)
  200. # pickle check
  201. obj = pickle.dumps(traced_module)
  202. traced_module = pickle.loads(obj)
  203. Node._set_next_id(159)
  204. Expr._set_next_id(1024)
  205. graph = traced_module.graph
  206. for expr in graph.get_function_by_type(F.relu).as_list():
  207. relu_out = expr.outputs[0]
  208. cur_graph = expr.top_graph
  209. with cur_graph.insert_exprs():
  210. neg_out = F.neg(relu_out)
  211. cur_graph.replace_node({relu_out: neg_out})
  212. cur_graph.compile()
  213. _check_id(traced_module)
  214. flattened_module = traced_module.flatten()
  215. _check_id(flattened_module)
  216. _check_name(flattened_module)
  217. # check trace TracedModule
  218. obj = pickle.dumps(traced_module)
  219. traced_module = pickle.loads(obj)
  220. module = NewModule(traced_module)
  221. traced_module = trace_module(module, x)
  222. _check_id(traced_module)
  223. flattened_module = traced_module.flatten()
  224. _check_id(flattened_module)
  225. _check_name(flattened_module)
  226. def test_set_node_name():
  227. traced_module, x, expect = _init_module()
  228. graph = traced_module.graph
  229. output_node = graph.outputs[0]
  230. def rename(name):
  231. output_node.name = name
  232. np.testing.assert_raises(AssertionError, rename, "block1_out")
  233. rename("output")
  234. np.testing.assert_equal(str(graph.outputs[0]), "output")
  235. def test_set_graph_name():
  236. traced_module, x, expect = _init_module()
  237. graph = traced_module.graph
  238. output_node = graph.outputs[0]
  239. node_name = output_node.name
  240. graph.name = "Top"
  241. node = graph.get_node_by_name("{}_{}".format("Top", node_name)).as_unique()
  242. assert node is output_node
  243. def test_extra_block():
  244. class PostProcess(M.Module):
  245. def forward(self, x):
  246. return x * 2
  247. class Net(M.Module):
  248. def __init__(self, traced_module):
  249. super().__init__()
  250. self.post_process = PostProcess()
  251. self.traced_module = traced_module
  252. def forward(self, x):
  253. x = self.traced_module(x)
  254. x = self.post_process(x)
  255. return x
  256. traced_module, x, expect = _init_block()
  257. module = Net(traced_module)
  258. np.testing.assert_allclose(2 * expect, module(x), atol=1e-6)
  259. traced_module = trace_module(module, x)
  260. np.testing.assert_allclose(2 * expect, traced_module(x), atol=1e-6)

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