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

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

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