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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  2. #
  3. # Copyright (c) 2014-2020 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 typing import Dict, List
  10. import numpy
  11. from ..core import _imperative_rt
  12. from ..core._imperative_rt import OperatorNode, VarNode
  13. from ..core.tensor import megbrain_graph as G
  14. from ..core.tensor.raw_tensor import as_raw_tensor
  15. __all__ = [
  16. "get_dep_vars",
  17. "get_owner_opr_inputs",
  18. "get_owner_opr_type",
  19. "get_opr_type",
  20. "graph_traversal",
  21. "get_oprs_seq",
  22. "replace_vars",
  23. "replace_oprs",
  24. "set_priority_to_id",
  25. "load_and_inference",
  26. ]
  27. def get_dep_vars(var: VarNode, var_type: str = None) -> List[VarNode]:
  28. """
  29. Returns :class:`.tensor.core.megbrain_graph.VarNode` of type ``var_type`` that input ``var``
  30. depands on. If ``var_type`` is None, returns all types.
  31. """
  32. outputs = []
  33. memo = set()
  34. if isinstance(var, VarNode):
  35. var = [var]
  36. if isinstance(var_type, str):
  37. var_type = [var_type]
  38. q = list(var)
  39. while q:
  40. v = q.pop()
  41. if v in memo:
  42. continue
  43. memo.add(v)
  44. q.extend(get_owner_opr_inputs(v))
  45. if var_type is not None:
  46. if get_owner_opr_type(v) in var_type:
  47. outputs.append(v)
  48. else:
  49. outputs.append(v)
  50. return outputs
  51. def get_owner_opr_inputs(var: VarNode) -> List[VarNode]:
  52. """
  53. Gets the inputs of owner opr of a variable.
  54. """
  55. assert isinstance(var, VarNode)
  56. return var.owner.inputs
  57. def get_owner_opr_type(var: VarNode) -> str:
  58. """
  59. Gets the type of owner opr of a variable.
  60. """
  61. assert isinstance(var, VarNode)
  62. return var.owner.type
  63. def get_opr_type(opr: OperatorNode) -> str:
  64. """
  65. Gets the type of an opr.
  66. """
  67. assert isinstance(opr, OperatorNode)
  68. return opr.type
  69. def graph_traversal(outputs: VarNode):
  70. """
  71. Helper function to traverse the computing graph and return enough useful information.
  72. :param outputs: model outputs.
  73. :return: tuple (map_oprs, map_vars, var2oprs, opr2receivers, indegree2opr, opr2indegree)
  74. WHERE
  75. map_oprs is dict from opr_id to actual opr
  76. map_vars is dict from var_id to actual var
  77. var2oprs is dict from var to dest oprs along with index
  78. opr2receivers is dict from current opr to next opr
  79. indegree2opr is dict from in_degree to opr in computing graph
  80. opr2indegree is dict from opr in computing graph to in_degree
  81. (indegree2opr, opr2indegree) are only used in topological sort in get_oprs_seq function
  82. """
  83. # meta information for comp graph
  84. map_oprs = collections.defaultdict(set)
  85. map_vars = collections.defaultdict(set)
  86. var2oprs = collections.defaultdict(list)
  87. opr2receivers = collections.defaultdict(list)
  88. queue = list(map(lambda x: x.owner, outputs))
  89. visited = set(map(lambda x: x.id, queue))
  90. # iterate through whole comp_graph, fill in meta information
  91. indegree2opr = collections.defaultdict(set)
  92. opr2indegree = {}
  93. idx = 0
  94. while idx < len(queue):
  95. cur_opr = queue[idx]
  96. map_oprs[cur_opr.id] = cur_opr
  97. idx += 1
  98. indegree = 0
  99. for var_idx, var in enumerate(cur_opr.inputs):
  100. map_vars[var.id] = var
  101. var2oprs[var.id].append((cur_opr.id, var_idx))
  102. pre_opr = var.owner
  103. if pre_opr.id not in visited:
  104. visited.add(pre_opr.id)
  105. queue.append(pre_opr)
  106. indegree += 1
  107. opr2receivers[pre_opr.id].append(cur_opr.id)
  108. indegree2opr[indegree].add(cur_opr.id)
  109. opr2indegree[cur_opr.id] = indegree
  110. return map_oprs, map_vars, var2oprs, opr2receivers, indegree2opr, opr2indegree
  111. def get_oprs_seq(outputs: List[VarNode], prune_reshape=False) -> List[OperatorNode]:
  112. """
  113. Gets oprs in some topological order for a dumped model.
  114. :param outputs: model outputs.
  115. :param prune_reshape: whether to prune the useless operators during inference.
  116. :return: opr list with some correct execution order.
  117. """
  118. def topological_sort(map_oprs, opr2receivers, indegree2opr, opr2indegree):
  119. # generate an execution order with topological sort algorithm
  120. oprs_seq = []
  121. nr_remain = len(map_oprs)
  122. while indegree2opr[0]:
  123. opr_id = indegree2opr[0].pop()
  124. opr = map_oprs[opr_id]
  125. nr_remain -= 1
  126. # skip const value generation operator
  127. if get_opr_type(opr) != "ImmutableTensor":
  128. oprs_seq.append(opr)
  129. for post_id in opr2receivers[opr_id]:
  130. indegree = opr2indegree[post_id]
  131. indegree2opr[indegree].remove(post_id)
  132. indegree -= 1
  133. indegree2opr[indegree].add(post_id)
  134. opr2indegree[post_id] = indegree
  135. assert nr_remain == 0, "there are {} remaining nodes; cyclic graph?".format(
  136. nr_remain
  137. )
  138. return oprs_seq
  139. # reshape op definition: reshape(input_tensor, dest_shape) -> output_tensor
  140. # when inferencing, shape of output_tensor is already known, so one can prune some operators related to dest_shape in the loaded graph
  141. def prune_reshape_oprs(outputs, oprs_seq, var2oprs):
  142. def iterative_pruning(cur_opr, post_opr, marked_opr_ids, visited):
  143. useless = True
  144. for oup in cur_opr.outputs:
  145. if "workspace" not in oup.name:
  146. var_idx = post_opr.inputs.index(oup)
  147. var2oprs[oup.id].remove((post_opr.id, var_idx))
  148. useless = useless and (len(var2oprs[oup.id]) == 0)
  149. if useless:
  150. marked_opr_ids.append(cur_opr.id)
  151. for opr in set([var.owner for var in cur_opr.inputs]):
  152. if (opr.id, cur_opr.id) not in visited:
  153. visited.add((opr.id, cur_opr.id))
  154. iterative_pruning(opr, cur_opr, marked_opr_ids, visited)
  155. reshape_vars = get_dep_vars(outputs, "Reshape")
  156. reshape_oprs = [var.owner for var in reshape_vars]
  157. marked_opr_ids = []
  158. visited = set()
  159. for reshape_opr in reshape_oprs:
  160. iterative_pruning(
  161. reshape_opr.inputs[1].owner, reshape_opr, marked_opr_ids, visited
  162. )
  163. # filter out all marked oprs
  164. return list(filter(lambda x: x.id not in marked_opr_ids, oprs_seq))
  165. map_oprs, _, var2oprs, opr2receivers, indegree2opr, opr2indegree = graph_traversal(
  166. outputs
  167. )
  168. oprs_seq = topological_sort(map_oprs, opr2receivers, indegree2opr, opr2indegree)
  169. if prune_reshape is True:
  170. oprs_seq = prune_reshape_oprs(outputs, oprs_seq, var2oprs.copy())
  171. return oprs_seq
  172. def replace_vars(dst: VarNode, varmap: Dict[VarNode, VarNode]) -> List[VarNode]:
  173. """
  174. Replaces vars in the graph.
  175. :param dst: target vars representing the graph.
  176. :param varmap: the map that specifies how to replace the vars.
  177. :return: new vars that correspond to ``dst`` with all the dependencies
  178. replaced.
  179. """
  180. dst_vec = []
  181. repl_src_vec = []
  182. repl_dst_vec = []
  183. for i in dst:
  184. assert isinstance(i, VarNode)
  185. dst_vec.append(i)
  186. for i, j in getattr(varmap, "items", lambda: varmap)():
  187. assert isinstance(i, VarNode)
  188. assert isinstance(j, VarNode)
  189. repl_src_vec.append(i)
  190. repl_dst_vec.append(j)
  191. return _imperative_rt.graph._replace_vars(repl_src_vec, repl_dst_vec, dst_vec)
  192. def replace_oprs(
  193. dst: List[VarNode], oprmap: Dict[OperatorNode, OperatorNode]
  194. ) -> List[VarNode]:
  195. """
  196. Replaces operators in the graph.
  197. :param dst: target vars representing the graph.
  198. :param oprmap: the map that specifies how to replace the operators.
  199. :return: new vars that correspond to ``dst`` with all the dependencies
  200. replaced.
  201. """
  202. dst_vec = []
  203. repl_src_vec = []
  204. repl_dst_vec = []
  205. for i in dst:
  206. assert isinstance(i, VarNode)
  207. dst_vec.append(i)
  208. for i, j in getattr(oprmap, "items", lambda: oprmap)():
  209. assert isinstance(i, OperatorNode)
  210. assert isinstance(j, OperatorNode)
  211. repl_src_vec.append(i)
  212. repl_dst_vec.append(j)
  213. return _imperative_rt.graph._replace_oprs(repl_src_vec, repl_dst_vec, dst_vec)
  214. def set_priority_to_id(dest_vars):
  215. """
  216. For all oprs in the subgraph constructed by dest_vars,
  217. sets its priority to id if its original priority is zero.
  218. :param dest_vars: target vars representing the graph.
  219. """
  220. dest_vec = []
  221. for i in dest_vars:
  222. assert isinstance(i, VarNode)
  223. dest_vec.append(i)
  224. _imperative_rt.graph._set_priority_to_id(dest_vec)
  225. def load_and_inference(file, inp_data_list: List[numpy.ndarray]) -> List[numpy.ndarray]:
  226. """
  227. Loads a serialized computing graph and run inference with input data.
  228. :param file: path or handle of the input file.
  229. :param inp_data_list: list of input data.
  230. :return: list of inference results.
  231. """
  232. *_, out_list = G.load_graph(file)
  233. inputs = get_dep_vars(out_list, "Host2DeviceCopy")
  234. replace_dict = {}
  235. inp_node_list = []
  236. for i in inputs:
  237. inp_node = G.InputNode(
  238. device="xpux", dtype=inputs[0].dtype, graph=inputs[0].graph
  239. )
  240. replace_dict[i] = inp_node.outputs[0]
  241. inp_node_list.append(inp_node)
  242. new_out = replace_vars(out_list, replace_dict)
  243. out_node_list = [G.OutputNode(i) for i in new_out]
  244. new_out_list = [i.outputs[0] for i in out_node_list]
  245. cg = new_out_list[0].graph
  246. func = cg.compile(new_out_list)
  247. for node, value in zip(inp_node_list, inp_data_list):
  248. node.set_value(as_raw_tensor(value)._dev_tensor())
  249. func.execute()
  250. out_data_list = [o.get_value().numpy() for o in out_node_list]
  251. return out_data_list

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