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.

comp_graph_tools.py 15 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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 collections
  9. from collections import OrderedDict
  10. from typing import Dict, List, Tuple, Union
  11. import numpy as np
  12. from ..core import _imperative_rt
  13. from ..core._imperative_rt import GraphProfiler
  14. from ..core._imperative_rt import OperatorNode as _OpNode
  15. from ..core._imperative_rt import VarNode as _VarNode
  16. from ..core.tensor import megbrain_graph as G
  17. from ..core.tensor.megbrain_graph import set_priority_to_id
  18. from ..tensor import Tensor
  19. __all__ = [
  20. "get_dep_vars",
  21. "get_owner_opr_inputs",
  22. "get_owner_opr_type",
  23. "get_opr_type",
  24. "graph_traversal",
  25. "get_oprs_seq",
  26. "replace_vars",
  27. "replace_oprs",
  28. "set_priority_to_id",
  29. "GraphInference",
  30. ]
  31. def get_dep_vars(
  32. var: Union[_VarNode, List[_VarNode]], var_type: Union[str, List[str]] = None
  33. ) -> List[_VarNode]:
  34. """
  35. Returns :class:`.tensor.core.megbrain_graph.VarNode` of type ``var_type`` that input ``var``
  36. depands on. If ``var_type`` is None, returns all types.
  37. """
  38. outputs = []
  39. memo = set()
  40. if isinstance(var, _VarNode):
  41. var = [var]
  42. if isinstance(var_type, str):
  43. var_type = [var_type]
  44. q = list(var)
  45. while q:
  46. v = q.pop(0)
  47. if v in memo:
  48. continue
  49. memo.add(v)
  50. q.extend(get_owner_opr_inputs(v))
  51. if var_type is not None:
  52. if get_owner_opr_type(v) in var_type:
  53. outputs.append(v)
  54. else:
  55. outputs.append(v)
  56. return outputs
  57. def get_owner_opr_inputs(var: _VarNode) -> List[_VarNode]:
  58. """
  59. Gets the inputs of owner opr of a variable.
  60. """
  61. return var.owner.inputs
  62. def get_owner_opr_type(var: _VarNode) -> str:
  63. """
  64. Gets the type of owner opr of a variable.
  65. """
  66. return var.owner.type
  67. def get_opr_type(opr: _OpNode) -> str:
  68. """
  69. Gets the type of an opr.
  70. """
  71. assert isinstance(opr, _OpNode)
  72. return opr.type
  73. def graph_traversal(outputs: _VarNode):
  74. """
  75. Helper function to traverse the computing graph and return enough useful information.
  76. :param outputs: model outputs.
  77. :return: tuple (map_oprs, map_vars, var2oprs, opr2receivers, indegree2opr, opr2indegree)
  78. WHERE
  79. map_oprs is dict from opr_id to actual opr
  80. map_vars is dict from var_id to actual var
  81. var2oprs is dict from var to dest oprs along with index
  82. opr2receivers is dict from current opr to next opr
  83. indegree2opr is dict from in_degree to opr in computing graph
  84. opr2indegree is dict from opr in computing graph to in_degree
  85. (indegree2opr, opr2indegree) are only used in topological sort in get_oprs_seq function
  86. """
  87. # meta information for comp graph
  88. map_oprs = collections.defaultdict(set)
  89. map_vars = collections.defaultdict(set)
  90. var2oprs = collections.defaultdict(list)
  91. opr2receivers = collections.defaultdict(list)
  92. queue = list(set(map(lambda x: x.owner, outputs)))
  93. visited = set(map(lambda x: x.id, queue))
  94. # iterate through whole comp_graph, fill in meta information
  95. indegree2opr = collections.defaultdict(set)
  96. opr2indegree = {}
  97. idx = 0
  98. while idx < len(queue):
  99. cur_opr = queue[idx]
  100. map_oprs[cur_opr.id] = cur_opr
  101. idx += 1
  102. indegree = 0
  103. for var_idx, var in enumerate(cur_opr.inputs):
  104. map_vars[var.id] = var
  105. var2oprs[var.id].append((cur_opr.id, var_idx))
  106. pre_opr = var.owner
  107. if pre_opr.id not in visited:
  108. visited.add(pre_opr.id)
  109. queue.append(pre_opr)
  110. indegree += 1
  111. opr2receivers[pre_opr.id].append(cur_opr.id)
  112. indegree2opr[indegree].add(cur_opr.id)
  113. opr2indegree[cur_opr.id] = indegree
  114. return map_oprs, map_vars, var2oprs, opr2receivers, indegree2opr, opr2indegree
  115. def get_oprs_seq(
  116. outputs: List[_VarNode], prune_reshape=False, prune_immtensor=True
  117. ) -> List[_OpNode]:
  118. """
  119. Gets oprs in some topological order for a dumped model.
  120. :param outputs: model outputs.
  121. :param prune_reshape: whether to prune the useless operators used by Reshape opr during inference.
  122. :param prune_immtensor: whether to prune the ImmutableTensor opr.
  123. :return: opr list with some correct execution order.
  124. """
  125. def topological_sort(map_oprs, opr2receivers, indegree2opr, opr2indegree):
  126. # generate an execution order with topological sort algorithm
  127. oprs_seq = []
  128. nr_remain = len(map_oprs)
  129. while indegree2opr[0]:
  130. opr_id = indegree2opr[0].pop()
  131. opr = map_oprs[opr_id]
  132. nr_remain -= 1
  133. if opr.type != "ImmutableTensor" or not prune_immtensor:
  134. oprs_seq.append(opr)
  135. for post_id in opr2receivers[opr_id]:
  136. indegree = opr2indegree[post_id]
  137. indegree2opr[indegree].remove(post_id)
  138. indegree -= 1
  139. indegree2opr[indegree].add(post_id)
  140. opr2indegree[post_id] = indegree
  141. assert nr_remain == 0, "there are {} remaining nodes; cyclic graph?".format(
  142. nr_remain
  143. )
  144. return oprs_seq
  145. # reshape op definition: reshape(input_tensor, dest_shape) -> output_tensor
  146. # when inferencing, shape of output_tensor is already known, so one can prune some operators related to dest_shape in the loaded graph
  147. def prune_reshape_oprs(outputs, oprs_seq, var2oprs):
  148. def iterative_pruning(cur_opr, post_opr, marked_opr_ids, visited):
  149. useless = True
  150. for oup in cur_opr.outputs:
  151. if "workspace" not in oup.name:
  152. var_idx = post_opr.inputs.index(oup)
  153. var2oprs[oup.id].remove((post_opr.id, var_idx))
  154. useless = useless and (len(var2oprs[oup.id]) == 0)
  155. if useless:
  156. marked_opr_ids.append(cur_opr.id)
  157. for opr in set([var.owner for var in cur_opr.inputs]):
  158. if (opr.id, cur_opr.id) not in visited:
  159. visited.add((opr.id, cur_opr.id))
  160. iterative_pruning(opr, cur_opr, marked_opr_ids, visited)
  161. reshape_vars = get_dep_vars(outputs, "Reshape")
  162. reshape_oprs = [var.owner for var in reshape_vars]
  163. marked_opr_ids = []
  164. visited = set()
  165. for reshape_opr in reshape_oprs:
  166. iterative_pruning(
  167. reshape_opr.inputs[1].owner, reshape_opr, marked_opr_ids, visited
  168. )
  169. # filter out all marked oprs
  170. return list(filter(lambda x: x.id not in marked_opr_ids, oprs_seq))
  171. map_oprs, _, var2oprs, opr2receivers, indegree2opr, opr2indegree = graph_traversal(
  172. outputs
  173. )
  174. oprs_seq = topological_sort(map_oprs, opr2receivers, indegree2opr, opr2indegree)
  175. if prune_reshape is True:
  176. oprs_seq = prune_reshape_oprs(outputs, oprs_seq, var2oprs.copy())
  177. return oprs_seq
  178. def replace_vars(
  179. dst: List[_VarNode], varmap: Dict[_VarNode, _VarNode]
  180. ) -> List[_VarNode]:
  181. """
  182. Replaces vars in the graph.
  183. :param dst: target vars representing the graph.
  184. :param varmap: the map that specifies how to replace the vars.
  185. :return: new vars that correspond to ``dst`` with all the dependencies
  186. replaced.
  187. """
  188. dst_vec = []
  189. repl_src_vec = []
  190. repl_dst_vec = []
  191. for i in dst:
  192. assert isinstance(i, _VarNode)
  193. dst_vec.append(i)
  194. for i, j in getattr(varmap, "items", lambda: varmap)():
  195. assert isinstance(i, _VarNode)
  196. assert isinstance(j, _VarNode)
  197. repl_src_vec.append(i)
  198. repl_dst_vec.append(j)
  199. return _imperative_rt.graph._replace_vars(repl_src_vec, repl_dst_vec, dst_vec)
  200. def replace_oprs(dst: List[_VarNode], oprmap: Dict[_OpNode, _OpNode]) -> List[_VarNode]:
  201. """
  202. Replaces operators in the graph.
  203. :param dst: target vars representing the graph.
  204. :param oprmap: the map that specifies how to replace the operators.
  205. :return: new vars that correspond to ``dst`` with all the dependencies
  206. replaced.
  207. """
  208. dst_vec = []
  209. repl_src_vec = []
  210. repl_dst_vec = []
  211. for i in dst:
  212. assert isinstance(i, _VarNode)
  213. dst_vec.append(i)
  214. for i, j in getattr(oprmap, "items", lambda: oprmap)():
  215. assert isinstance(i, _OpNode)
  216. assert isinstance(j, _OpNode)
  217. repl_src_vec.append(i)
  218. repl_dst_vec.append(j)
  219. return _imperative_rt.graph._replace_oprs(repl_src_vec, repl_dst_vec, dst_vec)
  220. def find_vars_by_name(dst: List[_VarNode], names: List[str]) -> List[_VarNode]:
  221. """
  222. Gets VarNode list by names in the graph.
  223. :param dst: target vars representing the graph.
  224. :param names: name list for target VarNode.
  225. :return: results found by names.
  226. """
  227. output_names = names.copy()
  228. all_vars = get_dep_vars(dst) + dst
  229. # use dict to keep outputs order the same as names.
  230. output_dict = {}
  231. for i in all_vars:
  232. if i.name in output_names:
  233. output_dict[i.name] = i
  234. output_names.remove(i.name)
  235. assert len(output_names) == 0, "Can not find varnode {} in this model".format(
  236. output_names
  237. )
  238. return [output_dict[i] for i in names]
  239. def convert_inputs(
  240. dst: List[_VarNode], inputs: List[_VarNode] = None
  241. ) -> Tuple[List[_VarNode], Dict[str, _VarNode]]:
  242. """
  243. Replaces ``Host2DeviceCopy`` with :class:`~.InputNode` in the graph
  244. to :meth:`~.InputNode.set_value` and run.
  245. :param dst: target vars representing the graph.
  246. :param inputs: indicates which inputs to be replaced. All
  247. inputs(``Host2DeiceCopy``) will be replaced if not specified.
  248. :return: new vars that correspond to ``dst`` with all inputs
  249. replaced, and new inputs dict.
  250. """
  251. if inputs is None:
  252. inputs = get_dep_vars(dst, "Host2DeviceCopy")
  253. input_dict = OrderedDict()
  254. replace_dict = {}
  255. for inp in inputs:
  256. inp_node = G.InputNode(
  257. device=inp.comp_node, dtype=inp.dtype, shape=inp.shape, graph=inp.graph,
  258. )
  259. inp_node.name = inp.name
  260. input_dict[inp.name] = inp_node
  261. replace_dict[inp] = inp_node.outputs[0]
  262. new_output_nodes = replace_vars(dst, replace_dict)
  263. for old, new in zip(dst, new_output_nodes):
  264. new.name = old.name
  265. return new_output_nodes, input_dict
  266. def convert_outputs(dst: List[_VarNode]) -> Tuple[List[_VarNode], Dict[str, _VarNode]]:
  267. """
  268. Wraps ``dst`` with :class:`~.OutputNode` in the graph to get outputs
  269. with :meth:`~.OutputNode.get_value`.
  270. :param dst: target vars representing the graph.
  271. :return: new vars that correspond to ``dst`` with all inputs
  272. replaced, and outputs dict.
  273. """
  274. output_dict = OrderedDict([(i.name, G.OutputNode(i)) for i in dst])
  275. new_output_nodes = [i.outputs[0] for i in output_dict.values()]
  276. return new_output_nodes, output_dict
  277. def embed_inputs(
  278. dst: List[_VarNode], data: List[np.ndarray], inputs: List[_VarNode] = None
  279. ) -> Tuple[List[_VarNode], Dict[str, _VarNode]]:
  280. """
  281. Embeds ``data`` to the graph's inputs of ``dst``.
  282. :param dst: target vars representing the graph.
  283. :param data: data to be embeded.
  284. :param inputs: indicates which inputs to be replaced. All
  285. inputs(``Host2DeiceCopy``) will be replaced if not specified.
  286. :return: new vars that correspond to ``dst`` with all inputs
  287. replaced, and new inputs dict.
  288. """
  289. if inputs is None:
  290. inputs = get_dep_vars(dst, "Host2DeviceCopy")
  291. assert len(data) == len(inputs)
  292. input_dict = OrderedDict()
  293. replace_dict = {}
  294. for inp, d in zip(inputs, data):
  295. new_inp = _imperative_rt.make_shared(inp.graph, Tensor(d)._dev_tensor())
  296. new_inp.name = inp.name
  297. input_dict[inp.name] = new_inp
  298. replace_dict[inp] = new_inp
  299. new_output_nodes = replace_vars(dst, replace_dict)
  300. for old, new in zip(dst, new_output_nodes):
  301. new.name = old.name
  302. return new_output_nodes, input_dict
  303. class GraphInference:
  304. """
  305. Loads a serialized computing graph as a GraphInference object which can be used
  306. to execute the computing graph.
  307. :param file: could be file object or filename.
  308. :param outputs: only compile the subgraph with outputs as its endpoints.
  309. """
  310. def __init__(
  311. self,
  312. file,
  313. outputs: List[str] = None,
  314. profiling: bool = False,
  315. optimize_for_inference: bool = False,
  316. **kwargs
  317. ):
  318. self._graph, _, output_nodes = G.load_graph(file)
  319. if outputs is not None:
  320. output_nodes = find_vars_by_name(output_nodes, outputs)
  321. self._origin_outputs = output_nodes
  322. # replace inputs with `InputNode`
  323. output_nodes, self._inp_dict = convert_inputs(output_nodes)
  324. # replace outputs with `OutputNode`
  325. output_nodes, self._oup_dict = convert_outputs(output_nodes)
  326. self._func = self._graph.compile(output_nodes)
  327. def run(
  328. self, *inp_args: np.ndarray, inp_dict: Dict[str, np.ndarray] = None
  329. ) -> Dict[str, np.ndarray]:
  330. """
  331. :param inp_args: list of input datas.
  332. :param inp_dict: dict of named input datas.
  333. :return: a dict {output_name: output_value}.
  334. """
  335. assert len(inp_args) <= len(
  336. self._inp_dict
  337. ), "This model expects {} inputs".format(len(self._inp_dict))
  338. inputs = {}
  339. inp_keys = list(self._inp_dict.keys())
  340. for ind, data in enumerate(inp_args):
  341. inputs[inp_keys[ind]] = data
  342. if inp_dict is not None:
  343. inputs.update(inp_dict)
  344. assert (
  345. inputs.keys() == self._inp_dict.keys()
  346. ), "This model expects inputs {}, but gets inputs {}".format(
  347. list(self._inp_dict.keys()), list(inputs.keys())
  348. )
  349. for key in self._inp_dict:
  350. self._inp_dict[key].set_value(
  351. Tensor(inputs[key], device=self._inp_dict[key].device)._dev_tensor()
  352. )
  353. self._func.execute()
  354. self._func.wait()
  355. result = OrderedDict()
  356. for key in self._oup_dict:
  357. result[key] = self._oup_dict[key].get_value().numpy()
  358. return result

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