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.

graph_utils.h 32 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  1. /**
  2. * Copyright 2020 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #ifndef INC_GRAPH_UTILS_GRAPH_UTILS_H_
  17. #define INC_GRAPH_UTILS_GRAPH_UTILS_H_
  18. #include <fstream>
  19. #include <iostream>
  20. #include <list>
  21. #include <map>
  22. #include <string>
  23. #include <unordered_map>
  24. #include <vector>
  25. #include "graph/anchor.h"
  26. #include "graph/compute_graph.h"
  27. #include "graph/graph.h"
  28. #include "graph/model.h"
  29. #include "graph/node.h"
  30. #include "graph/utils/anchor_utils.h"
  31. #define GE_DUMP(compute_graph, name) \
  32. do { \
  33. GraphUtils::DumpGEGraph(compute_graph, name); \
  34. GraphUtils::DumpGEGraphToOnnx(*compute_graph, name); \
  35. uint64_t i = 0; \
  36. for (const auto &sub_graph_func : compute_graph->GetAllSubgraphs()) { \
  37. auto sub_graph_func_name = std::string(name) + std::string("_sub_graph_") + std::to_string(i++); \
  38. GraphUtils::DumpGEGraph(sub_graph_func, sub_graph_func_name); \
  39. GraphUtils::DumpGEGraphToOnnx(*sub_graph_func, sub_graph_func_name); \
  40. } \
  41. } while (0)
  42. #define REFER_ATTR_VALUE(VT_ENUM, DataType, attr, ret) \
  43. do { \
  44. DataType ret; \
  45. attr.GetValue<DataType>(ret); \
  46. } while (0)
  47. #define PRINT_ATTR_VALUE_IF(value_type, VT_ENUM, DataType, attr, stream) \
  48. do { \
  49. if (value_type == VT_ENUM) { \
  50. REFER_ATTR_VALUE(VT_ENUM, DataType, attr, ret) \
  51. stream << ret; \
  52. } \
  53. } while (0)
  54. #define PRINT_LIST_ATTR_VALUE_IF(value_type, VT_ENUM, DataType, attr, stream) \
  55. do { \
  56. if (value_type == VT_ENUM) { \
  57. REFER_ATTR_VALUE(VT_ENUM, DataType, attr, ret) \
  58. stream << "["; \
  59. for (int i = 0; i < ret.size(); i++) { \
  60. stream << ret[i]; \
  61. if (i + 1 != ret.size()) stream << ", "; \
  62. } \
  63. stream << "]"; \
  64. } \
  65. } while (0)
  66. #define PRINT_ATTR_VALUE_ELIF(value_type, VT_ENUM, DataType, attr, stream) \
  67. else PRINT_ATTR_VALUE_IF(value_type, VT_ENUM, DataType, attr, stream)
  68. #define PRINT_LIST_ATTR_VALUE_ELIF(value_type, VT_ENUM, DataType, attr, stream) \
  69. else PRINT_LIST_ATTR_VALUE_IF(value_type, VT_ENUM, DataType, attr, stream)
  70. #define PRINT_SHAPE(i_o, n, idx, stream) \
  71. do { \
  72. auto op = n->GetOpDesc(); \
  73. GeTensorDesc td = i_o == "input" ? op->GetInputDesc(idx) : op->GetOutputDesc(idx); \
  74. auto shape = td.GetShape().GetDims(); \
  75. stream << "["; \
  76. for (int i = 0; i < shape.size(); i++) { \
  77. stream << shape[i]; \
  78. if (i + 1 < shape.size()) stream << ", "; \
  79. } \
  80. stream << "]"; \
  81. } while (0)
  82. #define PRINT_ATTR_FUNC(stream) \
  83. [&](GeAttrValue attr) { \
  84. auto type = attr.GetValueType(); \
  85. PRINT_ATTR_VALUE_IF(type, GeAttrValue::ValueType::VT_STRING, GeAttrValue::STR, attr, stream) \
  86. PRINT_ATTR_VALUE_ELIF(type, GeAttrValue::ValueType::VT_FLOAT, GeAttrValue::FLOAT, attr, stream) \
  87. PRINT_ATTR_VALUE_ELIF(type, GeAttrValue::ValueType::VT_BOOL, GeAttrValue::BOOL, attr, stream) \
  88. PRINT_ATTR_VALUE_ELIF(type, GeAttrValue::ValueType::VT_INT, GeAttrValue::INT, attr, stream) \
  89. PRINT_LIST_ATTR_VALUE_ELIF(type, GeAttrValue::ValueType::VT_LIST_STRING, GeAttrValue::LIST_STR, attr, stream) \
  90. PRINT_LIST_ATTR_VALUE_ELIF(type, GeAttrValue::ValueType::VT_LIST_FLOAT, GeAttrValue::LIST_FLOAT, attr, stream) \
  91. PRINT_LIST_ATTR_VALUE_ELIF(type, GeAttrValue::ValueType::VT_LIST_BOOL, GeAttrValue::LIST_BOOL, attr, stream) \
  92. PRINT_LIST_ATTR_VALUE_ELIF(type, GeAttrValue::ValueType::VT_LIST_INT, GeAttrValue::LIST_INT, attr, stream) \
  93. else if (type == GeAttrValue::ValueType::VT_TENSOR_DESC) stream << "TENSOR_DESC"; \
  94. else if (type == GeAttrValue::ValueType::VT_TENSOR) stream << "TENSOR"; \
  95. else if (type == GeAttrValue::ValueType::VT_BYTES) stream << "BYTES"; \
  96. else if (type == GeAttrValue::ValueType::VT_LIST_TENSOR_DESC) stream << "LIST_TENSOR_DESC"; \
  97. else if (type == GeAttrValue::ValueType::VT_LIST_TENSOR) stream << "LIST_TENSOR"; \
  98. else if (type == GeAttrValue::ValueType::VT_LIST_BYTES) stream << "LIST_BYTES"; \
  99. };
  100. namespace ge {
  101. enum IOType { kIn, kOut };
  102. struct NodeIndexIO {
  103. NodeIndexIO(ge::NodePtr node, uint32_t index, IOType io_type)
  104. : node_(std::move(node)), index_(index), io_type_(io_type) {
  105. if (node_ != nullptr) {
  106. value_ = node_->GetName() + (io_type_ == kOut ? "_out_" : "_in_") + std::to_string(index_);
  107. }
  108. }
  109. NodeIndexIO(ge::NodePtr node, int index, IOType io_type)
  110. : node_(std::move(node)), index_(static_cast<uint32_t>(index)), io_type_(io_type) {
  111. if (node_ != nullptr) {
  112. value_ = node_->GetName() + (io_type_ == kOut ? "_out_" : "_in_") + std::to_string(index_);
  113. }
  114. }
  115. ~NodeIndexIO() {}
  116. NodePtr node_ = nullptr;
  117. uint32_t index_ = 0;
  118. IOType io_type_ = kOut;
  119. std::string value_;
  120. const std::string &ToString() const { return value_; }
  121. };
  122. class GraphUtils {
  123. public:
  124. static ComputeGraphPtr GetComputeGraph(const Graph &graph);
  125. static Graph CreateGraphFromComputeGraph(const ComputeGraphPtr compute_graph);
  126. static GraphPtr CreateGraphPtrFromComputeGraph(const ComputeGraphPtr compute_graph);
  127. static graphStatus RecoverGraphOperators(const Graph &graph);
  128. static ComputeGraphPtr CreateGraphFromOperator(const string &name, const std::vector<Operator> &inputs);
  129. static graphStatus AddEdge(const OutDataAnchorPtr &src, const InDataAnchorPtr &dst);
  130. static graphStatus AddEdge(const OutDataAnchorPtr &src, const Format &src_format, const InDataAnchorPtr &dst,
  131. const Format &dst_format);
  132. static graphStatus AddEdge(const AnchorPtr &src, const AnchorPtr &dst);
  133. static graphStatus AddEdge(const OutControlAnchorPtr &src, const InControlAnchorPtr &dst);
  134. static graphStatus AddEdge(const OutDataAnchorPtr &src, const InControlAnchorPtr &dst);
  135. // check whether src is link to dst and then remove
  136. static graphStatus RemoveEdge(const OutDataAnchorPtr &src, const InDataAnchorPtr &dst);
  137. static graphStatus RemoveEdge(const AnchorPtr &src, const AnchorPtr &dst);
  138. static graphStatus RemoveEdge(const OutControlAnchorPtr &src, const InControlAnchorPtr &dst);
  139. static graphStatus RemoveEdge(const OutDataAnchorPtr &src, const InControlAnchorPtr &dst);
  140. static graphStatus ReplaceEdgeDst(const OutDataAnchorPtr &src, const InDataAnchorPtr &dst,
  141. const InDataAnchorPtr &new_dst);
  142. static graphStatus ReplaceEdgeDst(const OutControlAnchorPtr &src, const InControlAnchorPtr &dst,
  143. const InControlAnchorPtr &new_dst);
  144. static graphStatus InsertNodeBetweenDataAnchors(const OutDataAnchorPtr &src, const InDataAnchorPtr &dst,
  145. const NodePtr &new_node);
  146. static graphStatus RemoveSubgraphRecursively(const ComputeGraphPtr &compute_graph, const NodePtr &remove_node);
  147. static graphStatus RemoveNodeWithoutRelink(const ComputeGraphPtr &compute_graph, const NodePtr &node);
  148. static graphStatus InsertTransNode(ComputeGraphPtr compute_graph, const InDataAnchorPtr &in_data_anchor,
  149. const std::vector<OpDescPtr> &vec_op_desc);
  150. ///
  151. /// @brief Insert node: src->insert_node:input_index, insert_node:output_index->dst
  152. /// @param [in] src
  153. /// @param [in] dsts
  154. /// @param [in] insert_node
  155. /// @param [in] input_index
  156. /// @param [in] output_index
  157. /// @return graphStatus
  158. ///
  159. static graphStatus InsertNodeAfter(const OutDataAnchorPtr &src, const std::vector<InDataAnchorPtr> &dsts,
  160. const NodePtr &insert_node, uint32_t input_index = 0, uint32_t output_index = 0);
  161. static graphStatus RemoveJustNode(ComputeGraphPtr compute_graph, const NodePtr &node);
  162. static graphStatus RemoveJustNode(ComputeGraph &compute_graph, const NodePtr &node);
  163. static void RecordOriginalNames(std::vector<ge::NodePtr> original_nodes, const ge::NodePtr &node);
  164. static void RecordOriginalNames(std::vector<std::string> names_tmp, const ge::NodePtr &node);
  165. static bool MatchDumpStr(const std::string &suffix);
  166. static void DumpGEGraph(const ge::ComputeGraphPtr &graph,
  167. const std::string &suffix,
  168. bool is_always_dump = false,
  169. const std::string &user_graph_name = "");
  170. static void DumpGEGrph(const ge::ComputeGraphPtr &graph,
  171. const std::string &path,
  172. const std::string &suffix);
  173. static bool LoadGEGraph(const char *file, ge::ComputeGraph &compute_graph);
  174. static bool LoadGEGraph(const char *file, ge::ComputeGraphPtr &compute_graph);
  175. static void BreakConnect(const std::map<OperatorImplPtr, NodePtr> &all_nodes_infos);
  176. static void DumpGEGraphToOnnx(const ge::ComputeGraph &compute_graph, const std::string &suffix);
  177. static void DumpGrphToOnnx(const ge::ComputeGraph &compute_graph,
  178. const std::string &path, const std::string &suffix);
  179. static bool LoadGEGraphFromOnnx(const char *file, ge::ComputeGraph &compute_graph);
  180. static bool ReadProtoFromTextFile(const char *file, google::protobuf::Message *message);
  181. static void WriteProtoToTextFile(const google::protobuf::Message &proto, const char *real_path);
  182. static graphStatus AppendInputNode(const ComputeGraphPtr &graph, const NodePtr &node);
  183. ///
  184. /// Isolating `node`, relinking data links from the in-anchor peer nodes to
  185. /// the out-anchor peer nodes according to `io_map`, relinking control links
  186. /// to ensure that input nodes of `node` are before out nodes
  187. ///
  188. /// Link the `io_map[i]` input anchor peer node to `i` output anchor peer
  189. /// nodes, then unlink all links connecting with `node`. If `io_map[i]` < 0,
  190. /// unlink all links from `i` output anchor without any relinking.
  191. ///
  192. /// @param node
  193. /// @param io_map
  194. /// @return
  195. ///
  196. static graphStatus IsolateNode(const NodePtr &node, const std::initializer_list<int> &io_map);
  197. static graphStatus IsolateNode(const NodePtr &node, const std::vector<int> &io_map);
  198. ///
  199. /// Isolate `node` which must be one input one output, equivalent to
  200. /// `IsolateNode(node, {0})`
  201. /// @param node
  202. /// @return
  203. ///
  204. static graphStatus IsolateNodeOneIO(const NodePtr &node);
  205. ///
  206. /// The data anchors replacing behavior is the same with
  207. /// `ReplaceNodeDataAnchors`. In addition, replace all `old_node` control
  208. /// anchors with `new_node`'s.
  209. /// @param new_node
  210. /// @param old_node
  211. /// @param inputs_map
  212. /// @param outputs_map
  213. /// @return
  214. ///
  215. static graphStatus ReplaceNodeAnchors(const NodePtr &new_node, const NodePtr &old_node,
  216. std::initializer_list<int> inputs_map, std::initializer_list<int> outputs_map);
  217. static graphStatus ReplaceNodeAnchors(const NodePtr &new_node, const NodePtr &old_node,
  218. const std::vector<int> &inputs_map, const std::vector<int> &outputs_map);
  219. ///
  220. /// Replace `old_node` data anchors with `new_node`'s according to `inputs_map` and `outputs_map`.
  221. /// Replace the `i` in/out data anchor on `old_node` with
  222. /// `inputs_map[i]`/`outputs_map[i]` data anchor on `new_node`.
  223. /// If `inputs_map[i]`/`outputs_map[i]` < 0 or the index not contained in
  224. /// `inputs_map[i]`/`outputs_map[i]`, the `i` data anchor will remain
  225. /// on `old_node`.
  226. /// @param new_node
  227. /// @param old_node
  228. /// @param inputs_map
  229. /// @param outputs_map
  230. /// @return
  231. ///
  232. static graphStatus ReplaceNodeDataAnchors(const NodePtr &new_node, const NodePtr &old_node,
  233. std::initializer_list<int> inputs_map,
  234. std::initializer_list<int> outputs_map);
  235. static graphStatus ReplaceNodeDataAnchors(const NodePtr &new_node, const NodePtr &old_node,
  236. const std::vector<int> &inputs_map, const std::vector<int> &outputs_map);
  237. ///
  238. /// Copy all in-control edges from `src_node` to `dst_node`
  239. /// @param src_node
  240. /// @param dst_node
  241. /// @return
  242. ///
  243. static graphStatus CopyInCtrlEdges(const NodePtr &src_node, NodePtr &dst_node);
  244. static graphStatus MoveInCtrlEdges(const NodePtr &src_node, NodePtr &dst_node);
  245. ///
  246. /// Copy all out-control edges from `src_node` to `dst_node`
  247. /// @param src_node
  248. /// @param dst_node
  249. /// @return success: GRAPH_SUCESS
  250. ///
  251. static graphStatus CopyOutCtrlEdges(const NodePtr &src_node, NodePtr &dst_node);
  252. ///
  253. /// Move all out-control edges from `src_node` to `dst_node`
  254. /// @param src_node
  255. /// @param dst_node
  256. /// @return success: GRAPH_SUCESS
  257. ///
  258. static graphStatus MoveOutCtrlEdges(NodePtr &src_node, NodePtr &dst_node);
  259. ///
  260. /// Copy all in-data edges from `src_node` to `dst_node`
  261. /// @param src_node
  262. /// @param dst_node
  263. /// @return
  264. ///
  265. static graphStatus CopyInDataEdges(const NodePtr &src_node, NodePtr &dst_node);
  266. static ComputeGraphPtr FindRootGraph(ComputeGraphPtr graph);
  267. ///
  268. /// Make a copy of ComputeGraph.
  269. /// @param graph: original graph.
  270. /// @param prefix: node name prefix of new graph.
  271. /// @return ComputeGraphPtr
  272. ///
  273. static ComputeGraphPtr CloneGraph(const ComputeGraphPtr &graph, const string &prefix,
  274. std::vector<NodePtr> &input_nodes, std::vector<NodePtr> &output_nodes);
  275. ///
  276. /// Copy tensor attribute to new node.
  277. /// @param [in] dst_desc: cloned node.
  278. /// @param [in] src_node: original node.
  279. /// @return success: GRAPH_SUCESS
  280. ///
  281. static graphStatus CopyTensorAttrs(const OpDescPtr &dst_desc, const NodePtr &src_node);
  282. static graphStatus TopologicalSortingByName(const ge::ComputeGraphPtr &compute_graph, vector<NodePtr> &node_vec);
  283. ///
  284. /// Get reference-mapping of all data_anchors in graph
  285. /// @param [in] graph
  286. /// @param [out] symbol_to_anchors
  287. /// @param [out] anchor_to_symbol
  288. /// @return success: GRAPH_SUCESS
  289. ///
  290. static graphStatus GetRefMapping(const ComputeGraphPtr &graph,
  291. std::map<std::string, std::list<NodeIndexIO>> &symbol_to_anchors,
  292. std::map<std::string, std::string> &anchor_to_symbol);
  293. ///
  294. /// Determine if the graph is a UNKNOWN_SHAPE graph based on whether the graph and all subgraphs
  295. /// of the graph have UNKNOWN_SHAPE operators or not.
  296. /// Note: This function will only look 'down' from the graph, not 'up'. For example, the following
  297. /// scenario (K for known shape, U for unknown shape), ROOT graph is UNKNOWN_SHAPE while SUB graph is KNOWN_SHAPE
  298. /// ROOT graph: A -----> B -----> C
  299. /// K subgraph U
  300. /// |
  301. /// V
  302. /// SUB graph: D --> E --> F
  303. /// K K K
  304. /// @param [in] graph
  305. /// @return bool
  306. ///
  307. static bool IsUnknownShapeGraph(const ComputeGraphPtr &graph);
  308. static NodePtr FindNodeFromAllNodes(ComputeGraphPtr &graph, const std::string &name);
  309. private:
  310. ///
  311. /// Get reference-mapping for in_data_anchors of node
  312. /// @param [in] node
  313. /// @param [out] symbol_to_anchors
  314. /// @param [out] anchor_to_symbol
  315. /// @return success: GRAPH_SUCESS
  316. ///
  317. static graphStatus HandleInAnchorMapping(const NodePtr &node,
  318. std::map<std::string, std::list<NodeIndexIO>> &symbol_to_anchors,
  319. std::map<std::string, std::string> &anchor_to_symbol);
  320. ///
  321. /// Get reference-mapping for out_data_anchors of node
  322. /// @param [in] node
  323. /// @param [out] symbol_to_anchors
  324. /// @param [out] anchor_to_symbol
  325. /// @return success: GRAPH_SUCESS
  326. ///
  327. static graphStatus HandleOutAnchorMapping(const NodePtr &node,
  328. std::map<std::string, std::list<NodeIndexIO>> &symbol_to_anchors,
  329. std::map<std::string, std::string> &anchor_to_symbol);
  330. ///
  331. /// Handle input of subgraph
  332. /// @param [in] node
  333. /// @param [out] symbol_to_anchors
  334. /// @param [out] anchor_to_symbol
  335. /// @return success: GRAPH_SUCESS
  336. ///
  337. static graphStatus HandleSubgraphInput(const NodePtr &node,
  338. std::map<std::string, std::list<NodeIndexIO>> &symbol_to_anchors,
  339. std::map<std::string, std::string> &anchor_to_symbol);
  340. ///
  341. /// Handle input of Merge op
  342. /// @param [in] node
  343. /// @param [out] symbol_to_anchors
  344. /// @param [out] anchor_to_symbol
  345. /// @return success: GRAPH_SUCESS
  346. ///
  347. static graphStatus HandleMergeInput(const NodePtr &node,
  348. std::map<std::string, std::list<NodeIndexIO>> &symbol_to_anchors,
  349. std::map<std::string, std::string> &anchor_to_symbol);
  350. ///
  351. /// Handle output of subgraph
  352. /// @param [in] node
  353. /// @param [out] symbol_to_anchors
  354. /// @param [out] anchor_to_symbol
  355. /// @return success: GRAPH_SUCESS
  356. ///
  357. static graphStatus HandleSubgraphOutput(const NodePtr &node,
  358. std::map<std::string, std::list<NodeIndexIO>> &symbol_to_anchors,
  359. std::map<std::string, std::string> &anchor_to_symbol);
  360. ///
  361. /// Relink all edges for cloned ComputeGraph.
  362. /// @param [in] node: original node.
  363. /// @param [in] prefix: node name prefix of new node.
  364. /// @param [in] all_nodes: all nodes in new graph.
  365. /// @return success: GRAPH_SUCESS
  366. ///
  367. static graphStatus RelinkGraphEdges(const NodePtr &node, const string &prefix,
  368. const std::unordered_map<string, NodePtr> &all_nodes);
  369. ///
  370. /// Union ref-mapping
  371. /// @param [in] exist_node_info1
  372. /// @param [in] exist_node_info2
  373. /// @param [out] symbol_to_anchors
  374. /// @param [out] anchor_to_symbol
  375. /// @param [out] symbol
  376. /// @return success: GRAPH_SUCESS
  377. ///
  378. static graphStatus UnionSymbolMapping(const NodeIndexIO &exist_node_info1, const NodeIndexIO &exist_node_info2,
  379. std::map<std::string, std::list<NodeIndexIO>> &symbol_to_anchors,
  380. std::map<std::string, std::string> &anchor_to_symbol, std::string &symbol);
  381. ///
  382. /// Update symbol mapping with a new reference pair
  383. /// @param [in] cur_node_info
  384. /// @param [in] exist_node_info
  385. /// @param [out] symbol_to_anchors
  386. /// @param [out] anchor_to_symbol
  387. /// @return success: GRAPH_SUCESS
  388. ///
  389. static graphStatus UpdateRefMapping(const NodeIndexIO &cur_node_info, const NodeIndexIO &exist_node_info,
  390. std::map<std::string, std::list<NodeIndexIO>> &symbol_to_anchors,
  391. std::map<std::string, std::string> &anchor_to_symbol);
  392. ///
  393. /// Check if out_data_anchor is reference of input
  394. /// @param [in] out_data_anchor
  395. /// @param [out] reuse_in_index
  396. /// @return bool
  397. ///
  398. static bool IsRefFromInput(const OutDataAnchorPtr &out_data_anchor, int32_t &reuse_in_index);
  399. };
  400. class ComputeGraphBuilder {
  401. public:
  402. ComputeGraphBuilder() : owner_graph_(nullptr) {}
  403. ComputeGraphBuilder(const ComputeGraphBuilder &) = delete;
  404. ComputeGraphBuilder &operator=(const ComputeGraphBuilder &) = delete;
  405. ComputeGraphBuilder(const ComputeGraphBuilder &&) = delete;
  406. ComputeGraphBuilder &operator=(const ComputeGraphBuilder &&) = delete;
  407. ~ComputeGraphBuilder() = default;
  408. ///
  409. /// @brief Add node to graph
  410. /// @param [in] op_desc
  411. /// @return ComputeGraphBuilder
  412. ///
  413. virtual ComputeGraphBuilder &AddNode(const OpDescPtr &op_desc);
  414. ///
  415. /// @brief Add data-link among nodes in graph
  416. /// @param [in] src_name
  417. /// @param [in] out_anchor_ind
  418. /// @param [in] dst_name
  419. /// @param [in] in_anchor_ind
  420. /// @return ComputeGraphBuilder
  421. ///
  422. virtual ComputeGraphBuilder &AddDataLink(const std::string &src_name, uint32_t out_anchor_ind,
  423. const std::string &dst_name, uint32_t in_anchor_ind);
  424. ///
  425. /// @brief Add ctrl-link among nodes in graph
  426. /// @param [in] src_name
  427. /// @param [in] dst_name
  428. /// @return ComputeGraphBuilder
  429. ///
  430. virtual ComputeGraphBuilder &AddControlLink(const std::string &src_name, const std::string &dst_name);
  431. ///
  432. /// @brief Build graph
  433. /// @param [out] error_code
  434. /// @param [out] error_msg
  435. /// @return ComputeGraphPtr
  436. ///
  437. virtual ComputeGraphPtr Build(graphStatus &error_code, std::string &error_msg) = 0;
  438. /// @brief Get node with name
  439. /// @param [in] name
  440. /// @return NodePtr
  441. ///
  442. NodePtr GetNode(const std::string &name);
  443. /// @brief Get all nodes
  444. /// @return std::vector<NodePtr>
  445. ///
  446. std::vector<NodePtr> GetAllNodes();
  447. protected:
  448. ///
  449. /// @brief Build nodes
  450. /// @param [out] error_code
  451. /// @param [out] error_msg
  452. /// @return void
  453. ///
  454. void BuildNodes(graphStatus &error_code, std::string &error_msg);
  455. ///
  456. /// @brief Build data-links
  457. /// @param [out] error_code
  458. /// @param [out] error_msg
  459. /// @return void
  460. ///
  461. void BuildDataLinks(graphStatus &error_code, std::string &error_msg);
  462. ///
  463. /// @brief Build ctrl-links
  464. /// @param [out] error_code
  465. /// @param [out] error_msg
  466. /// @return void
  467. ///
  468. void BuildCtrlLinks(graphStatus &error_code, std::string &error_msg);
  469. ComputeGraphPtr owner_graph_;
  470. // node_name -> node
  471. std::map<std::string, NodePtr> node_names_;
  472. std::vector<OpDescPtr> nodes_;
  473. // <src_node_name, out_anchor_ind> -> <dst_node_name, in_anchor_ind>
  474. std::vector<std::pair<std::pair<std::string, uint32_t>, std::pair<std::string, uint32_t>>> data_links_;
  475. // src_node_name -> dst_node_name
  476. std::vector<std::pair<std::string, std::string>> ctrl_links_;
  477. };
  478. class CompleteGraphBuilder : public ComputeGraphBuilder {
  479. public:
  480. explicit CompleteGraphBuilder(std::string name, bool retval_flag = true)
  481. : name_(std::move(name)), parent_node_(nullptr), retval_flag_(retval_flag) {}
  482. CompleteGraphBuilder(const CompleteGraphBuilder &) = delete;
  483. CompleteGraphBuilder &operator=(const CompleteGraphBuilder &) = delete;
  484. CompleteGraphBuilder(const CompleteGraphBuilder &&) = delete;
  485. CompleteGraphBuilder &operator=(const CompleteGraphBuilder &&) = delete;
  486. ~CompleteGraphBuilder() = default;
  487. ///
  488. /// @brief Add node to graph
  489. /// @param [in] op_desc
  490. /// @return CompleteGraphBuilder
  491. ///
  492. CompleteGraphBuilder &AddNode(const OpDescPtr &op_desc) override;
  493. ///
  494. /// @brief Add data-link among nodes in graph
  495. /// @param [in] src_name
  496. /// @param [in] out_anchor_ind
  497. /// @param [in] dst_name
  498. /// @param [in] in_anchor_ind
  499. /// @return CompleteGraphBuilder
  500. ///
  501. CompleteGraphBuilder &AddDataLink(const std::string &src_name, uint32_t out_anchor_ind,
  502. const std::string &dst_name, uint32_t in_anchor_ind) override;
  503. ///
  504. /// @brief Add ctrl-link among nodes in graph
  505. /// @param [in] src_name
  506. /// @param [in] dst_name
  507. /// @return CompleteGraphBuilder
  508. ///
  509. CompleteGraphBuilder &AddControlLink(const std::string &src_name, const std::string &dst_name) override;
  510. ///
  511. /// @brief Set index_th input anchor for graph
  512. /// @param [in] index
  513. /// @param [in] node_names
  514. /// @param [in] anchor_inds
  515. /// @return CompleteGraphBuilder
  516. ///
  517. CompleteGraphBuilder &SetInput(uint32_t index, const std::vector<std::string> &node_names,
  518. const std::vector<uint32_t> &anchor_inds);
  519. ///
  520. /// @brief Set index_th input of graph as useless
  521. /// @param [in] index
  522. /// @return CompleteGraphBuilder
  523. ///
  524. CompleteGraphBuilder &SetUselessInput(uint32_t index);
  525. ///
  526. /// @brief Add output anchor for graph
  527. /// @param [in] owner_node_name
  528. /// @param [in] anchor_ind
  529. /// @return CompleteGraphBuilder
  530. ///
  531. CompleteGraphBuilder &AddOutput(const std::string &owner_node_name, uint32_t anchor_ind);
  532. ///
  533. /// @brief Add target for graph
  534. /// @param [in] target_name
  535. /// @return CompleteGraphBuilder
  536. ///
  537. CompleteGraphBuilder &AddTarget(const std::string &target_name);
  538. ///
  539. /// @brief Set parent-node of graph
  540. /// @param [in] parent_node
  541. /// @return CompleteGraphBuilder
  542. ///
  543. CompleteGraphBuilder &SetParentNode(const NodePtr &parent_node);
  544. ///
  545. /// @brief Set mapping-relation of parent-node in_anchor_ind & Data-node
  546. /// @param [in] input_mapping: index_of_graph_input -> in_anchor_index_of_parent_node
  547. /// @return CompleteGraphBuilder
  548. ///
  549. CompleteGraphBuilder &SetInputMapping(const std::map<uint32_t, uint32_t> &input_mapping);
  550. ///
  551. /// @brief Set mapping-relation of parent-node out_anchor_ind & NetOutput-node out_anchor_ind
  552. /// @param [in] output_mapping: index_of_graph_output -> out_anchor_index_of_parent_node
  553. /// @return CompleteGraphBuilder
  554. ///
  555. CompleteGraphBuilder &SetOutputMapping(const std::map<uint32_t, uint32_t> &output_mapping);
  556. ///
  557. /// @brief Build graph
  558. /// @param [out] error_code
  559. /// @param [out] error_msg
  560. /// @return ComputeGraphPtr
  561. ///
  562. ComputeGraphPtr Build(graphStatus &error_code, std::string &error_msg) override;
  563. private:
  564. ///
  565. /// @brief Add data nodes
  566. /// @param [out] error_code
  567. /// @param [out] error_msg
  568. /// @return void
  569. ///
  570. void AddDataNodes(graphStatus &error_code, std::string &error_msg);
  571. ///
  572. /// @brief Add data node
  573. /// @param [in] index
  574. /// @param [out] error_code
  575. /// @param [out] error_msg
  576. /// @return void
  577. ///
  578. NodePtr AddDataNode(uint32_t index, graphStatus &error_code, std::string &error_msg);
  579. ///
  580. /// @brief Add RetVal nodes
  581. /// @param [out] error_code
  582. /// @param [out] error_msg
  583. /// @return void
  584. ///
  585. void AddRetValNodes(graphStatus &error_code, std::string &error_msg);
  586. ///
  587. /// @brief Build target-nodes for graph
  588. /// @param [out] error_code
  589. /// @param [out] error_msg
  590. /// @return void
  591. ///
  592. void BuildGraphTargets(graphStatus &error_code, std::string &error_msg);
  593. ///
  594. /// @brief Add NetOutput node
  595. /// @param [out] error_code
  596. /// @param [out] error_msg
  597. /// @return void
  598. ///
  599. void AddNetOutputNode(graphStatus &error_code, std::string &error_msg);
  600. ///
  601. /// @brief Build NetOutput nodes with data & ctrl edges
  602. /// @param [in] net_output_desc
  603. /// @param [in] peer_out_anchors
  604. /// @param [out] error_code
  605. /// @param [out] error_msg
  606. /// @return void
  607. ///
  608. void BuildNetOutputNodeWithLink(const OpDescPtr &net_output_desc,
  609. const std::vector<OutDataAnchorPtr> &peer_out_anchors,
  610. graphStatus &error_code, std::string &error_msg);
  611. ///
  612. /// @brief process after build
  613. /// @param [out] error_code
  614. /// @param [out] error_msg
  615. /// @return void
  616. ///
  617. void PostProcess(graphStatus &error_code, std::string &error_msg);
  618. std::string name_;
  619. NodePtr parent_node_;
  620. bool retval_flag_;
  621. std::map<uint32_t, std::pair<std::vector<std::string>, std::vector<uint32_t>>> graph_inputs_;
  622. std::vector<std::pair<std::string, uint32_t>> graph_outputs_;
  623. std::vector<std::string> graph_targets_;
  624. // index_of_graph_input -> in_anchor_index_of_parent_node
  625. std::map<uint32_t, uint32_t> input_mapping_;
  626. // index_of_graph_output -> out_anchor_index_of_parent_node
  627. std::map<uint32_t, uint32_t> output_mapping_;
  628. };
  629. class PartialGraphBuilder : public ComputeGraphBuilder {
  630. public:
  631. PartialGraphBuilder() = default;
  632. PartialGraphBuilder(const PartialGraphBuilder &) = delete;
  633. PartialGraphBuilder &operator=(const PartialGraphBuilder &) = delete;
  634. PartialGraphBuilder(const PartialGraphBuilder &&) = delete;
  635. PartialGraphBuilder &operator=(const PartialGraphBuilder &&) = delete;
  636. ~PartialGraphBuilder() = default;
  637. ///
  638. /// @brief Add node to graph
  639. /// @param [in] op_desc
  640. /// @return PartialGraphBuilder
  641. ///
  642. PartialGraphBuilder &AddNode(const OpDescPtr &op_desc) override;
  643. ///
  644. /// @brief Add data-link among nodes in graph
  645. /// @param [in] src_name
  646. /// @param [in] out_anchor_ind
  647. /// @param [in] dst_name
  648. /// @param [in] in_anchor_ind
  649. /// @return PartialGraphBuilder
  650. ///
  651. PartialGraphBuilder &AddDataLink(const std::string &src_name, uint32_t out_anchor_ind,
  652. const std::string &dst_name, uint32_t in_anchor_ind) override;
  653. ///
  654. /// @brief Add ctrl-link among nodes in graph
  655. /// @param [in] src_name
  656. /// @param [in] dst_name
  657. /// @return PartialGraphBuilder
  658. ///
  659. PartialGraphBuilder &AddControlLink(const std::string &src_name, const std::string &dst_name) override;
  660. ///
  661. /// @brief Set owner graph
  662. /// @param [in] graph
  663. /// @return PartialGraphBuilder
  664. ///
  665. PartialGraphBuilder &SetOwnerGraph(const ComputeGraphPtr &graph);
  666. ///
  667. /// @brief Add exist node
  668. /// @param [in] node
  669. /// @return PartialGraphBuilder
  670. ///
  671. PartialGraphBuilder &AddExistNode(const NodePtr &node);
  672. ///
  673. /// @brief Build multi nodes with links
  674. /// @param [out] error_code
  675. /// @param [out] error_msg
  676. /// @return ComputeGraphPtr
  677. ///
  678. ComputeGraphPtr Build(graphStatus &error_code, std::string &error_msg) override;
  679. private:
  680. ///
  681. /// @brief Build exist nodes
  682. /// @param [out] error_code
  683. /// @param [out] error_msg
  684. /// @return void
  685. ///
  686. void BuildExistNodes(graphStatus &error_code, std::string &error_msg);
  687. std::vector<NodePtr> exist_nodes_;
  688. };
  689. } // namespace ge
  690. #endif // INC_GRAPH_UTILS_GRAPH_UTILS_H_

图引擎模块(GE)是MindSpore的一个子模块,其代码由C++实现,位于前端模块ME和底层硬件之间,起到承接作用。图引擎模块以ME下发的图作为输入,然后进行一系列的深度图优化操作,最后输出一张可以在底层硬件上高效运行的图。GE针对昇腾AI处理器的硬件结构特点,做了特定的优化工作,以此来充分发挥出昇腾AI处理器的强大算力。在进行模型训练/推理时,GE会被自动调用而用户并不感知。GE主要由GE API和GE Core两部分组成,详细的架构图如下所示