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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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, Optional, Union
  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. def get_suffix_name(prefix: str, name: str):
  30. if prefix == name:
  31. return ""
  32. matchd = re.compile("^%s\.(.*)" % prefix).match(name)
  33. if matchd is None:
  34. return None
  35. return matchd.group(1)
  36. def is_call_module(expr):
  37. return (
  38. isinstance(expr, CallMethod)
  39. and isinstance(expr.inputs[0], ModuleNode)
  40. and expr.method == "__call__"
  41. )
  42. def is_call_tensor_method(expr):
  43. return isinstance(expr, CallMethod) and not is_call_module(expr)
  44. def is_call_function(expr):
  45. return isinstance(expr, CallFunction)
  46. def is_constant(expr):
  47. return isinstance(expr, Constant)
  48. def is_getattr(expr):
  49. return isinstance(expr, GetAttr)
  50. def is_apply_def(expr):
  51. return isinstance(expr, Apply)
  52. class Expr:
  53. r"""``Expr`` represents the operations (i.e. ``CallMethod``, ``CallFunction``, ``Apply``,
  54. ``GetAttr``, ``Input``, ``Constant``) on ``Node``.
  55. """
  56. inputs = None # type: List[Node]
  57. r"""The input Nodes of this Expr."""
  58. outputs = None # type: List[Node]
  59. r"""The output Nodes of this Expr."""
  60. const_val = None # type: List[Any]
  61. r"""The non-tensor object in the input of the operation."""
  62. arg_def = None # type: TreeDef
  63. r"""The :class:`TreeDef` used to reconstruct the input of the operation."""
  64. out_def = None # type: TreeDef
  65. r"""The :class:`TreeDef` used to reconstruct the output of the operation."""
  66. _top_graph = None # type: weakref.ReferenceType
  67. __total_id = 0
  68. def __init__(self) -> None:
  69. self._id = Expr.__total_id
  70. Expr.__total_id += 1
  71. self._disable_remove = False
  72. def enable_remove(self):
  73. self._disable_remove = False
  74. def disable_remove(self):
  75. self._disable_remove = True
  76. def add_inputs(self, vals):
  77. if not isinstance(vals, collections.abc.Sequence):
  78. vals = (vals,)
  79. for val in vals:
  80. node = NodeMixin.get(val, None)
  81. if isinstance(node, (TensorNode, ModuleNode)):
  82. self.inputs.append(node)
  83. node.users.append(self)
  84. else:
  85. assert node is None
  86. assert _is_leaf(val) and _is_const_leaf(val)
  87. idx = len(self.inputs) + len(self.const_val)
  88. self.const_val.append((idx, val))
  89. def add_outputs(self, outputs):
  90. assert active_module_tracer() is not None
  91. self.outputs = []
  92. if outputs is None:
  93. return
  94. current_graph = active_module_tracer().current_scope()
  95. if not isinstance(outputs, collections.Sequence):
  96. outputs = (outputs,)
  97. for i in outputs:
  98. assert isinstance(i, RawTensor), "The output must be a Tensor"
  99. node = NodeMixin.get_wrapped_type(i)(expr=self, name="", qualname="",)
  100. NodeMixin.wrap_safe(i, node)
  101. self.outputs.append(node)
  102. current_graph._namespace.auto_naming_for_outputs(self)
  103. def unflatten_args(self, inputs):
  104. if self.arg_def is not None:
  105. inputs = list(inputs)
  106. for idx, val in self.const_val:
  107. inputs.insert(idx, val)
  108. args, kwargs = self.arg_def.unflatten(inputs)
  109. return args, kwargs
  110. else:
  111. return inputs, {}
  112. def replace_inputs(self, repl_dict: Dict[Node, Node]):
  113. r"""Replace the input Nodes of this Expr.
  114. Args:
  115. repl_dict: the map {old_Node: new_Node} that specifies how to replace the input Nodes.
  116. """
  117. while repl_dict:
  118. node, repl_node = repl_dict.popitem()
  119. assert type(node) == type(repl_node)
  120. assert node in self.inputs, "({}) is not in the ({})".format(node, self)
  121. assert (
  122. repl_node.top_graph == node.top_graph
  123. ), "({}) and ({}) are not in the same graph".format(node, repl_node)
  124. graph = self.top_graph
  125. repl_expr_idx = graph._exprs.index(repl_node.expr)
  126. self_idx = graph._exprs.index(self)
  127. assert (
  128. repl_expr_idx < self_idx
  129. ), "({}) must be generated before ({})".format(repl_node, self)
  130. idx = self.inputs.index(node)
  131. self.inputs[idx] = repl_node
  132. node.users.remove(self)
  133. repl_node.users.append(self)
  134. @property
  135. def kwargs(self):
  136. r"""Get the keyword arguments of the operation corresponding to this Expr."""
  137. _, kwargs = self.unflatten_args(self.inputs)
  138. return kwargs
  139. @property
  140. def args(self):
  141. r"""Get the positional arguments of the operation corresponding to this Expr."""
  142. args, _ = self.unflatten_args(self.inputs)
  143. return args
  144. @property
  145. def top_graph(self):
  146. r"""Get the parent graph of this Expr."""
  147. if self._top_graph:
  148. return self._top_graph()
  149. return None
  150. def __getstate__(self):
  151. state = self.__dict__.copy()
  152. if "_top_graph" in state:
  153. state.pop("_top_graph")
  154. return state
  155. @classmethod
  156. def _get_next_id(cls):
  157. return cls.__total_id
  158. @classmethod
  159. def _set_next_id(cls, id: int = 0):
  160. assert isinstance(id, int)
  161. cls.__total_id = id
  162. # expr: None (i.e. fake expression which is used to mark input)
  163. class Input(Expr):
  164. r"""A fake Expr which is used to mark the input of graph."""
  165. name = None
  166. def __init__(self, type: List[Node], name: str = "args", qualname: str = ""):
  167. super().__init__()
  168. assert type in [ModuleNode, TensorNode]
  169. assert name and qualname
  170. self.inputs = []
  171. node_cls = type if type else Node
  172. self.outputs = [
  173. node_cls(self, name=name, qualname=qualname),
  174. ]
  175. self.name = name
  176. @classmethod
  177. def make(cls, *args, **kwargs):
  178. assert active_module_tracer() is not None
  179. expr = cls(*args, **kwargs)
  180. out_node = expr.outputs[0]
  181. active_module_tracer().current_scope()._add_input(out_node)
  182. return expr.outputs[0]
  183. def __repr__(self):
  184. return "%{}:\t{} = Input()".format(self._id, self.outputs[0])
  185. # expr: outputs = getattr(inputs[0], self.name)
  186. class GetAttr(Expr):
  187. r"""``Getattr`` represents the fetch of an attribute from the ``Module`` hierarchy."""
  188. name = None
  189. r"""name: the qualified name of the attribute to be retrieved."""
  190. def __init__(
  191. self, module: ModuleNode, type: Union[Node], attr_name: str, name: str = "",
  192. ):
  193. super().__init__()
  194. assert isinstance(module, ModuleNode)
  195. assert type in [TensorNode, ModuleNode]
  196. self.inputs = [
  197. module,
  198. ]
  199. module.users.append(self)
  200. self.name = attr_name
  201. self.outputs = [
  202. type(self, name=name, qualname="{}.{}".format(module.qualname, attr_name)),
  203. ]
  204. @classmethod
  205. def make(cls, *args, **kwargs):
  206. assert active_module_tracer() is not None
  207. current_graph = active_module_tracer().current_scope()
  208. expr = cls(*args, **kwargs)
  209. current_graph._namespace.auto_naming_for_outputs(expr)
  210. current_graph._insert(expr)
  211. return expr.outputs[0]
  212. def interpret(self, *inputs):
  213. mod = inputs[0]
  214. module_path, _, name = self.name.rpartition(".")
  215. if module_path == "":
  216. return (getattr(mod, name),)
  217. module_names = module_path.split(".")
  218. for item in module_names:
  219. mod = getattr(mod, item)
  220. if not isinstance(mod, Module):
  221. raise AttributeError("`{}` is not an Module".format(item))
  222. return (getattr(mod, name),)
  223. def __repr__(self):
  224. out_type = "Tensor"
  225. if isinstance(self.outputs[0], ModuleNode):
  226. out_type = self.outputs[0].module_type.__name__
  227. return '%{}:\t{} = getattr({}, "{}") -> ({})'.format(
  228. self._id, self.outputs[0], self.inputs[0], self.name, out_type
  229. )
  230. # expr: outputs = inputs[0].__call__(*inputs[1:])
  231. class CallMethod(Expr):
  232. r"""``CallMethod`` represents a call to the ``__call__`` method of ``Module`` or a method of ``Tensor``.
  233. Args:
  234. node: the Node to be called.
  235. method: the method name.
  236. Default: "__call__"
  237. """
  238. def __init__(self, node, method="__call__"):
  239. super().__init__()
  240. if isinstance(node, type):
  241. assert issubclass(node, Tensor)
  242. cls = Parameter if issubclass(node, Parameter) else Tensor
  243. self.inputs = []
  244. self.const_val = [(0, cls)]
  245. else:
  246. assert isinstance(node, (TensorNode, ModuleNode))
  247. node.users.append(self)
  248. self.inputs = [
  249. node,
  250. ]
  251. self.const_val = []
  252. self.method = method
  253. @classmethod
  254. def make(cls, *args, **kwargs):
  255. assert active_module_tracer() is not None
  256. expr = cls(*args, **kwargs)
  257. active_module_tracer().current_scope()._insert(expr)
  258. return expr
  259. @property
  260. def graph(self):
  261. if isinstance(self.inputs[0], ModuleNode):
  262. m_node = self.inputs[0]
  263. if (
  264. hasattr(m_node.owner, "argdef_graph_map")
  265. and m_node.owner.argdef_graph_map
  266. ):
  267. assert self.arg_def in m_node.owner.argdef_graph_map
  268. return m_node.owner.argdef_graph_map[self.arg_def]
  269. return None
  270. def interpret(self, *inputs):
  271. args, kwargs = self.unflatten_args(inputs)
  272. obj = args[0]
  273. meth = getattr(obj, self.method)
  274. if inspect.ismethod(meth):
  275. args = args[1:]
  276. outputs = getattr(obj, self.method)(*args, **kwargs)
  277. if self.method == "__setitem__":
  278. outputs = obj
  279. if outputs is None:
  280. return outputs
  281. outputs, _ = tree_flatten(outputs, is_leaf=lambda x: isinstance(x, RawTensor))
  282. return outputs
  283. def __repr__(self):
  284. args = ", ".join(str(i) for i in self.args[1:])
  285. kwargs = ", ".join("{}={}".format(k, v) for k, v in self.kwargs.items())
  286. outputs = self.outputs
  287. if self.out_def:
  288. outputs = self.out_def.unflatten(outputs)
  289. method = ".%s" % self.method
  290. if method == ".__call__":
  291. method = ""
  292. return "%{}:\t{}{}{}({})".format(
  293. self._id,
  294. str(outputs) + " = " if outputs else "",
  295. self.args[0],
  296. method,
  297. ", ".join([args, kwargs]),
  298. )
  299. # expr: outputs = apply(self.opdef, *inputs)
  300. class Apply(Expr):
  301. r"""``Apply`` represents a call to :func:`apply`.
  302. Args:
  303. opdef: the applied :class:`OpDef`.
  304. """
  305. opdef = None
  306. def __init__(self, opdef):
  307. super().__init__()
  308. assert isinstance(opdef, OpDef)
  309. self.opdef = opdef
  310. self.inputs = []
  311. @classmethod
  312. def make(cls, *args, **kwargs):
  313. assert active_module_tracer() is not None
  314. expr = cls(*args, **kwargs)
  315. active_module_tracer().current_scope()._insert(expr)
  316. return expr
  317. def interpret(self, *inputs):
  318. return apply(self.opdef, *inputs)
  319. def __repr__(self):
  320. return "%{}:\t{} = {}({})".format(
  321. self._id,
  322. ", ".join(str(i) for i in self.outputs),
  323. self.opdef,
  324. ", ".join(str(i) for i in self.inputs),
  325. )
  326. def __getstate__(self):
  327. state = super().__getstate__()
  328. state["opdef"] = get_opdef_state(state["opdef"])
  329. return state
  330. def __setstate__(self, state):
  331. state["opdef"] = load_opdef_from_state(state["opdef"])
  332. for k, v in state.items():
  333. setattr(self, k, v)
  334. @classmethod
  335. def apply_module_trace_hook(cls, opdef, *inputs):
  336. for i in inputs:
  337. node = NodeMixin.get(i, None)
  338. if node is None: # capture as constant
  339. NodeMixin.wrap_safe(i, Constant.make(i))
  340. if isinstance(opdef, FakeQuant):
  341. inp_nodes = [NodeMixin.get(inputs[0])]
  342. for i in inputs[1:]:
  343. node = Constant.make(i)
  344. inp_nodes.append(node)
  345. apply_node = cls.make(opdef)
  346. for n in inp_nodes:
  347. n.users.append(apply_node)
  348. apply_node.inputs = inp_nodes
  349. else:
  350. apply_node = cls.make(opdef)
  351. apply_node.add_inputs(inputs)
  352. assert not apply_node.const_val
  353. unset_module_tracing()
  354. outputs = apply(opdef, *inputs)
  355. set_module_tracing()
  356. apply_node.add_outputs(outputs)
  357. for n, v in zip(apply_node.outputs, outputs):
  358. NodeMixin.wrap_safe(v, n)
  359. return list(outputs)
  360. class CallFunction(Expr):
  361. r"""``CallFunction`` represents a call to a built-in function.
  362. Args:
  363. func: a built-in function.
  364. """
  365. def __init__(self, func):
  366. super().__init__()
  367. assert isinstance(func, Callable)
  368. self.func = func
  369. self.const_val = []
  370. self.inputs = []
  371. @classmethod
  372. def make(cls, *args, **kwargs):
  373. assert active_module_tracer() is not None
  374. expr = cls(*args, **kwargs)
  375. active_module_tracer().current_scope()._insert(expr)
  376. return expr
  377. def interpret(self, *inputs):
  378. args, kwargs = self.unflatten_args(inputs)
  379. outputs = self.func(*args, **kwargs)
  380. if outputs is None:
  381. return outputs
  382. outputs, _ = tree_flatten(outputs, is_leaf=lambda x: isinstance(x, RawTensor))
  383. return outputs
  384. def __repr__(self):
  385. args = ", ".join(str(i) for i in self.args)
  386. kwargs = ", ".join("{}={}".format(k, v) for k, v in self.kwargs.items())
  387. outputs = self.outputs
  388. if self.out_def:
  389. outputs = self.out_def.unflatten(outputs)
  390. return "%{}:\t{}{}({})".format(
  391. self._id,
  392. str(outputs) + " = " if outputs else "",
  393. self.func.__module__.rsplit(".")[-1] + "." + self.func.__name__,
  394. ", ".join([args, kwargs]),
  395. )
  396. # expr outputs = self.value
  397. class Constant(Expr):
  398. r"""``Constant`` represents a ``Tensor`` or "Module" which is not the attribute of a Module.
  399. Args:
  400. c: a const Tensor or Module.
  401. name: the name of output Node.
  402. """
  403. value = None
  404. r"""The const Tensor or Module"""
  405. # TODO: constant cache to reduce the size of dumped model
  406. _constant_cache = {}
  407. def __init__(self, c, name: str = "", qualname: str = ""):
  408. super().__init__()
  409. assert isinstance(c, (RawTensor, Module))
  410. if isinstance(c, Module):
  411. assert module_tracer.is_builtin(c) or c.is_qat
  412. self.value = c
  413. self.name = name
  414. self.inputs = []
  415. node_cls = NodeMixin.get_wrapped_type(c)
  416. self.outputs = [
  417. node_cls(self, name=name, qualname=qualname),
  418. ]
  419. @classmethod
  420. def make(cls, *args, **kwargs):
  421. assert active_module_tracer() is not None
  422. expr = cls(*args, **kwargs)
  423. current_graph = active_module_tracer().current_scope()
  424. current_graph._namespace.auto_naming_for_outputs(expr)
  425. current_graph._insert(expr)
  426. return expr.outputs[0]
  427. def interpret(self, *inputs):
  428. if isinstance(self.value, RawTensor):
  429. return Const(self.value.numpy())()
  430. return (self.value,)
  431. def __repr__(self):
  432. name = self.name
  433. if name is None:
  434. name = type(self.value)
  435. node_type = "Module"
  436. if isinstance(self.outputs[0], TensorNode):
  437. node_type = "Tensor"
  438. return "%{}:\t{} = Constant({}) -> ({})".format(
  439. self._id, self.outputs[0], name, node_type
  440. )
  441. def __getstate__(self):
  442. state = self.__dict__.copy()
  443. if "_top_graph" in state:
  444. state.pop("_top_graph")
  445. if isinstance(self.value, RawTensor):
  446. state["value"] = Tensor(self.value)
  447. return state

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