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

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

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