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

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

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