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

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