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.

expr.py 15 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. import builtins
  10. import collections
  11. import copy
  12. import inspect
  13. import re
  14. from typing import Callable, Dict, List
  15. from ...core._imperative_rt import OpDef
  16. from ...core._imperative_rt.core2 import Tensor as RawTensor
  17. from ...core._imperative_rt.core2 import apply, set_module_tracing, unset_module_tracing
  18. from ...core.ops.builtin import FakeQuant
  19. from ...core.ops.special import Const
  20. from ...module import Module
  21. from ...tensor import Parameter, Tensor
  22. from .module_tracer import active_module_tracer, module_tracer
  23. from .node import ModuleNode, Node, NodeMixin, TensorNode
  24. from .pytree import ArgsIndex, TreeDef, _is_const_leaf, _is_leaf, tree_flatten
  25. from .serialization import get_opdef_state, load_opdef_from_state
  26. def rstrip(s: str, __chars: str):
  27. __chars = re.escape(__chars)
  28. s = re.sub(r"^(?P<left>.*?)(?:%s)+$" % __chars, "\g<left>", s)
  29. return s
  30. def lstrip(s: str, __chars: str):
  31. __chars = re.escape(__chars)
  32. s = re.sub(r"^(?:%s)+(?P<right>.*)$" % __chars, "\g<right>", s)
  33. return s
  34. def strip(s: str, __chars: str):
  35. s = lstrip(rstrip(s, __chars), __chars)
  36. return s
  37. class Expr:
  38. """
  39. ``Expr`` represents the operations(i.e. CallMethod, CallFunction, Apply, GetAttr, Input, Constant) on ``Node``.
  40. """
  41. __total_id = 0
  42. inputs = None # type: List[Node]
  43. outputs = None # type: List[Node]
  44. const_val = None # type: List[Any]
  45. arg_def = None # type: TreeDef
  46. out_def = None # type: TreeDef
  47. _top_graph = None # type: weakref.ReferenceType
  48. def __init__(self) -> None:
  49. self._id = Expr.__total_id
  50. Expr.__total_id += 1
  51. self._disable_remove = False
  52. def enable_remove(self):
  53. self._disable_remove = False
  54. def disable_remove(self):
  55. self._disable_remove = True
  56. def add_inputs(self, vals):
  57. if not isinstance(vals, collections.abc.Sequence):
  58. vals = (vals,)
  59. for val in vals:
  60. node = NodeMixin.get(val, None)
  61. if isinstance(node, (TensorNode, ModuleNode)):
  62. self.inputs.append(node)
  63. node.users.append(self)
  64. else:
  65. assert node is None
  66. assert _is_leaf(val) and _is_const_leaf(val)
  67. idx = len(self.inputs) + len(self.const_val)
  68. self.const_val.append((idx, val))
  69. def add_outputs(self, outputs):
  70. self.outputs = []
  71. if outputs is not None:
  72. if not isinstance(outputs, collections.Sequence):
  73. outputs = (outputs,)
  74. name = None
  75. if isinstance(self, CallMethod):
  76. name = self.inputs[0]._name
  77. assert name is not None
  78. name = rstrip(name, "_out")
  79. if self.method == "__call__":
  80. name += "_out"
  81. else:
  82. strip_method = strip(self.method, "_")
  83. name = "%s_out" % strip_method
  84. elif isinstance(self, CallFunction):
  85. name = self.func.__name__ + "_out"
  86. elif isinstance(self, Apply):
  87. name = str(self.opdef).lower() + "_out"
  88. for i in outputs:
  89. assert isinstance(i, RawTensor)
  90. o_name = (
  91. active_module_tracer().current_scope()._create_unique_name(name)
  92. )
  93. self.outputs.append(
  94. NodeMixin.get_wrapped_type(i)(expr=self, name=o_name)
  95. )
  96. for i, node in zip(outputs, self.outputs,):
  97. NodeMixin.wrap_safe(i, node)
  98. def unflatten_args(self, inputs):
  99. if self.arg_def is not None:
  100. inputs = list(inputs)
  101. for idx, val in self.const_val:
  102. inputs.insert(idx, val)
  103. args, kwargs = self.arg_def.unflatten(inputs)
  104. return args, kwargs
  105. else:
  106. return inputs, {}
  107. def _replace_nodes(self, repl_dict: Dict[Node, Node], nodes: List[Node]):
  108. while repl_dict:
  109. node, repl_node = repl_dict.popitem()
  110. assert type(node) == type(repl_node)
  111. assert node in nodes
  112. index = nodes.index(node)
  113. nodes[index] = repl_node
  114. repl_node.users.append(self)
  115. node.users.pop(self)
  116. def replace_inputs(self, repl_dict: Dict[Node, Node]):
  117. self._replace_nodes(repl_dict, self.inputs)
  118. def replace_outputs(self, repl_dict: Dict[Node, Node]):
  119. self._replace_nodes(repl_dict, self.outputs)
  120. @property
  121. def kwargs(self):
  122. _, kwargs = self.unflatten_args(self.inputs)
  123. return kwargs
  124. @property
  125. def args(self):
  126. args, _ = self.unflatten_args(self.inputs)
  127. return args
  128. @property
  129. def top_graph(self):
  130. if self._top_graph:
  131. return self._top_graph()
  132. return None
  133. def __getstate__(self):
  134. state = self.__dict__.copy()
  135. state.pop("_top_graph", None)
  136. return state
  137. # expr: None (i.e. fake expression which is used to mark input)
  138. class Input(Expr):
  139. name = None
  140. def __init__(self, name=None, type=None):
  141. super().__init__()
  142. self.inputs = []
  143. node_cls = type if type else Node
  144. self.outputs = [
  145. node_cls(self, name=name),
  146. ]
  147. self.name = name
  148. @classmethod
  149. def make(cls, *args, **kwargs):
  150. expr = cls(*args, **kwargs)
  151. oup_node = expr.outputs[0]
  152. name = (
  153. active_module_tracer().current_scope()._create_unique_name(oup_node._name)
  154. )
  155. oup_node._name = name
  156. active_module_tracer().current_scope().add_input(oup_node)
  157. return expr.outputs[0]
  158. def __repr__(self):
  159. return "%{}:\t{} = Input({})".format(self._id, self.outputs[0], self.name)
  160. # expr: outputs = getattr(inputs[0], self.name)
  161. class GetAttr(Expr):
  162. name = None
  163. def __init__(self, module, name, type=None):
  164. super().__init__()
  165. assert isinstance(module, ModuleNode)
  166. self.inputs = [
  167. module,
  168. ]
  169. module.users.append(self)
  170. self.name = name
  171. node_cls = type if type else Node
  172. self.outputs = [
  173. node_cls(self, name=name),
  174. ]
  175. @classmethod
  176. def make(cls, *args, **kwargs):
  177. expr = cls(*args, **kwargs)
  178. module = expr.inputs[0]
  179. oup_name = expr.name
  180. while module._name != "self":
  181. oup_name = module._name + "_" + oup_name
  182. module = module.expr.inputs[0]
  183. oup_name = active_module_tracer().current_scope()._create_unique_name(oup_name)
  184. expr.outputs[0]._name = oup_name
  185. active_module_tracer().current_scope().insert(expr)
  186. return expr.outputs[0]
  187. def interpret(self, *inputs):
  188. return (getattr(inputs[0], self.name),)
  189. def __repr__(self):
  190. out_type = "Tensor"
  191. if isinstance(self.outputs[0], ModuleNode):
  192. out_type = self.outputs[0].module_type.__name__
  193. return '%{}:\t{} = getattr({}, "{}") -> ({})'.format(
  194. self._id, self.outputs[0], self.inputs[0], self.name, out_type
  195. )
  196. # expr: outputs = inputs[0].__call__(*inputs[1:])
  197. class CallMethod(Expr):
  198. def __init__(self, node, method="__call__"):
  199. super().__init__()
  200. if isinstance(node, type):
  201. assert issubclass(node, Tensor)
  202. cls = Parameter if issubclass(node, Parameter) else Tensor
  203. self.inputs = []
  204. self.const_val = [(0, cls)]
  205. else:
  206. assert isinstance(node, (TensorNode, ModuleNode))
  207. node.users.append(self)
  208. self.inputs = [
  209. node,
  210. ]
  211. self.const_val = []
  212. self.method = method
  213. @classmethod
  214. def make(cls, *args, **kwargs):
  215. expr = cls(*args, **kwargs)
  216. active_module_tracer().current_scope().insert(expr)
  217. return expr
  218. @property
  219. def graph(self):
  220. if isinstance(self.inputs[0], ModuleNode):
  221. m_node = self.inputs[0]
  222. if (
  223. hasattr(m_node.owner, "argdef_graph_map")
  224. and m_node.owner.argdef_graph_map
  225. ):
  226. assert self.arg_def in m_node.owner.argdef_graph_map
  227. return m_node.owner.argdef_graph_map[self.arg_def]
  228. return None
  229. def interpret(self, *inputs):
  230. args, kwargs = self.unflatten_args(inputs)
  231. obj = args[0]
  232. meth = getattr(obj, self.method)
  233. if inspect.ismethod(meth):
  234. args = args[1:]
  235. outputs = getattr(obj, self.method)(*args, **kwargs)
  236. if self.method == "__setitem__":
  237. outputs = obj
  238. if outputs is None:
  239. return outputs
  240. outputs, _ = tree_flatten(outputs, is_leaf=lambda x: isinstance(x, RawTensor))
  241. return outputs
  242. def __repr__(self):
  243. args = ", ".join(str(i) for i in self.args[1:])
  244. kwargs = ", ".join("{}={}".format(k, v) for k, v in self.kwargs.items())
  245. outputs = self.outputs
  246. if self.out_def:
  247. outputs = self.out_def.unflatten(outputs)
  248. method = ".%s" % self.method
  249. if method == ".__call__":
  250. method = ""
  251. return "%{}:\t{}{}{}({})".format(
  252. self._id,
  253. str(outputs) + " = " if outputs else "",
  254. self.args[0],
  255. method,
  256. ", ".join([args, kwargs]),
  257. )
  258. # expr: outputs = apply(self.opdef, *inputs)
  259. class Apply(Expr):
  260. opdef = None
  261. def __init__(self, opdef):
  262. super().__init__()
  263. assert isinstance(opdef, OpDef)
  264. self.opdef = opdef
  265. self.inputs = []
  266. @classmethod
  267. def make(cls, *args, **kwargs):
  268. expr = cls(*args, **kwargs)
  269. active_module_tracer().current_scope().insert(expr)
  270. return expr
  271. def interpret(self, *inputs):
  272. return apply(self.opdef, *inputs)
  273. def __repr__(self):
  274. return "%{}:\t{} = {}({})".format(
  275. self._id,
  276. ", ".join(str(i) for i in self.outputs),
  277. self.opdef,
  278. ", ".join(str(i) for i in self.inputs),
  279. )
  280. def __getstate__(self):
  281. state = super().__getstate__()
  282. state["opdef"] = get_opdef_state(state["opdef"])
  283. return state
  284. def __setstate__(self, state):
  285. state["opdef"] = load_opdef_from_state(state["opdef"])
  286. for k, v in state.items():
  287. setattr(self, k, v)
  288. @classmethod
  289. def apply_module_trace_hook(cls, opdef, *inputs):
  290. for i in inputs:
  291. node = NodeMixin.get(i, None)
  292. if node is None: # capture as constant
  293. NodeMixin.wrap_safe(i, Constant.make(i))
  294. if isinstance(opdef, FakeQuant):
  295. inp_nodes = [NodeMixin.get(inputs[0])]
  296. for i in inputs[1:]:
  297. node = Constant.make(i)
  298. inp_nodes.append(node)
  299. apply_node = cls.make(opdef)
  300. for n in inp_nodes:
  301. n.users.append(apply_node)
  302. apply_node.inputs = inp_nodes
  303. else:
  304. apply_node = cls.make(opdef)
  305. apply_node.add_inputs(inputs)
  306. assert not apply_node.const_val
  307. unset_module_tracing()
  308. outputs = apply(opdef, *inputs)
  309. set_module_tracing()
  310. apply_node.add_outputs(outputs)
  311. for n, v in zip(apply_node.outputs, outputs):
  312. NodeMixin.wrap_safe(v, n)
  313. return list(outputs)
  314. class CallFunction(Expr):
  315. def __init__(self, func):
  316. super().__init__()
  317. assert isinstance(func, Callable)
  318. self.func = func
  319. self.const_val = []
  320. self.inputs = []
  321. @classmethod
  322. def make(cls, *args, **kwargs):
  323. expr = cls(*args, **kwargs)
  324. active_module_tracer().current_scope().insert(expr)
  325. return expr
  326. def interpret(self, *inputs):
  327. args, kwargs = self.unflatten_args(inputs)
  328. outputs = self.func(*args, **kwargs)
  329. if outputs is None:
  330. return outputs
  331. outputs, _ = tree_flatten(outputs, is_leaf=lambda x: isinstance(x, RawTensor))
  332. return outputs
  333. def __repr__(self):
  334. args = ", ".join(str(i) for i in self.args)
  335. kwargs = ", ".join("{}={}".format(k, v) for k, v in self.kwargs.items())
  336. outputs = self.outputs
  337. if self.out_def:
  338. outputs = self.out_def.unflatten(outputs)
  339. return "%{}:\t{}{}({})".format(
  340. self._id,
  341. str(outputs) + " = " if outputs else "",
  342. self.func.__module__.rsplit(".")[-1] + "." + self.func.__name__,
  343. ", ".join([args, kwargs]),
  344. )
  345. # expr outputs = self.value
  346. class Constant(Expr):
  347. value = None
  348. # TODO: constant cache to reduce the size of dumped model
  349. _constant_cache = {}
  350. def __init__(self, c, name=None):
  351. super().__init__()
  352. assert isinstance(c, (RawTensor, Module))
  353. if isinstance(c, Module):
  354. assert module_tracer.is_builtin(c) or c.is_qat
  355. self.value = c
  356. self.name = name
  357. self.inputs = []
  358. node_cls = NodeMixin.get_wrapped_type(c)
  359. self.outputs = [
  360. node_cls(self, name=name),
  361. ]
  362. self.outputs[0]._name = name if name else "const_" + str(self._id)
  363. @classmethod
  364. def make(cls, *args, **kwargs):
  365. expr = cls(*args, **kwargs)
  366. name = "const_module" if isinstance(expr.value, Module) else "const_tensor"
  367. name = active_module_tracer().current_scope()._create_unique_name(name)
  368. expr.outputs[0]._name = name
  369. active_module_tracer().current_scope().insert(expr)
  370. return expr.outputs[0]
  371. def interpret(self, *inputs):
  372. if isinstance(self.value, RawTensor):
  373. return Const(self.value.numpy())()
  374. return (self.value,)
  375. def __repr__(self):
  376. name = self.name
  377. if name is None:
  378. name = type(self.value)
  379. node_type = "Module"
  380. if isinstance(self.outputs[0], TensorNode):
  381. node_type = "Tensor"
  382. return "%{}:\t{} = Constant({}) -> ({})".format(
  383. self._id, self.outputs[0], name, node_type
  384. )
  385. def __getstate__(self):
  386. state = super().__getstate__()
  387. if isinstance(self.value, RawTensor):
  388. state["value"] = Tensor(self.value)
  389. return state

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