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.cc 74 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002
  1. /**
  2. * Copyright 2019-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. #include "utils/graph_utils.h"
  17. #include <google/protobuf/io/coded_stream.h>
  18. #include <google/protobuf/io/zero_copy_stream_impl.h>
  19. #include <google/protobuf/text_format.h>
  20. #include <fcntl.h>
  21. #include <sys/stat.h>
  22. #include <sys/types.h>
  23. #include <unistd.h>
  24. #include <algorithm>
  25. #include <cstring>
  26. #include <fstream>
  27. #include <iomanip>
  28. #include "./ge_context.h"
  29. #include "debug/ge_util.h"
  30. #include "framework/common/debug/ge_log.h"
  31. #include "proto/ge_ir.pb.h"
  32. #include "utils/attr_utils.h"
  33. #include "utils/ge_ir_utils.h"
  34. #include "utils/node_utils.h"
  35. #include "debug/ge_op_types.h"
  36. #include "graph/debug/ge_attr_define.h"
  37. #include "graph/utils/op_desc_utils.h"
  38. #include "graph/utils/tensor_utils.h"
  39. using google::protobuf::io::FileOutputStream;
  40. namespace ge {
  41. enum DumpGraphLevel {
  42. kDumpLevel1 = 1,
  43. kDumpLevel2 = 2,
  44. kDumpLevel3 = 3,
  45. kDumpLevelOther,
  46. };
  47. namespace {
  48. const int32_t kBaseOfIntegerValue = 10;
  49. #ifdef FMK_SUPPORT_DUMP
  50. const char *const kDumpGeGraph = "DUMP_GE_GRAPH";
  51. #endif
  52. const char *const kDumpGraphLevel = "DUMP_GRAPH_LEVEL";
  53. const char *const kDumpStrBuild = "Build";
  54. const char *const kDumpStrPartition = "partition";
  55. const char *const kDumpStrOptimizeSubgraph = "OptimizeSubGraph";
  56. const char *const kDumpStrAicpu = "Aicpu";
  57. }; // namespace
  58. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::AddEdge(const OutDataAnchorPtr &src,
  59. const InDataAnchorPtr &dst) {
  60. if ((src != nullptr) && (src->LinkTo(dst) == GRAPH_SUCCESS)) {
  61. return GRAPH_SUCCESS;
  62. }
  63. GELOGE(GRAPH_FAILED, "Add edge Failed.");
  64. return GRAPH_FAILED;
  65. }
  66. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::AddEdge(const AnchorPtr &src,
  67. const AnchorPtr &dst) {
  68. OutDataAnchorPtr src_data = Anchor::DynamicAnchorCast<OutDataAnchor>(src);
  69. InDataAnchorPtr dst_data = Anchor::DynamicAnchorCast<InDataAnchor>(dst);
  70. OutControlAnchorPtr src_control = Anchor::DynamicAnchorCast<OutControlAnchor>(src);
  71. InControlAnchorPtr dst_control = Anchor::DynamicAnchorCast<InControlAnchor>(dst);
  72. if ((src_data != nullptr) && (dst_data != nullptr) && (src_data->LinkTo(dst_data) == GRAPH_SUCCESS)) {
  73. return GRAPH_SUCCESS;
  74. }
  75. if ((src_data != nullptr) && (dst_control != nullptr) && (src_data->LinkTo(dst_control) == GRAPH_SUCCESS)) {
  76. return GRAPH_SUCCESS;
  77. }
  78. if ((src_control != nullptr) && (dst_control != nullptr) && (src_control->LinkTo(dst_control) == GRAPH_SUCCESS)) {
  79. return GRAPH_SUCCESS;
  80. }
  81. if ((src_control != nullptr) && (dst_data != nullptr) && (src_control->LinkTo(dst_data) == GRAPH_SUCCESS)) {
  82. return GRAPH_SUCCESS;
  83. }
  84. GELOGE(GRAPH_FAILED, "Add edge Failed.");
  85. return GRAPH_FAILED;
  86. }
  87. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::AddEdge(const OutDataAnchorPtr &src,
  88. const Format &src_format,
  89. const InDataAnchorPtr &dst,
  90. const Format &dst_format) {
  91. if ((src != nullptr) && (src->LinkTo(dst) == GRAPH_SUCCESS)) {
  92. auto ret = AnchorUtils::SetFormat(src, src_format);
  93. if (ret != GRAPH_SUCCESS) {
  94. GELOGE(GRAPH_FAILED, "Set format failed, format is %d", static_cast<int>(src_format));
  95. return ret;
  96. }
  97. ret = AnchorUtils::SetFormat(dst, dst_format);
  98. if (ret != GRAPH_SUCCESS) {
  99. GELOGE(GRAPH_FAILED, "Set format failed,format is %d", static_cast<int>(dst_format));
  100. return ret;
  101. }
  102. return GRAPH_SUCCESS;
  103. }
  104. GELOGE(GRAPH_FAILED, "Add edge Failed.");
  105. return GRAPH_FAILED;
  106. }
  107. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::AddEdge(const OutControlAnchorPtr &src,
  108. const InControlAnchorPtr &dst) {
  109. if ((src != nullptr) && (src->LinkTo(dst) == GRAPH_SUCCESS)) {
  110. return GRAPH_SUCCESS;
  111. }
  112. GELOGE(GRAPH_FAILED, "Add edge Failed.");
  113. return GRAPH_FAILED;
  114. }
  115. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::AddEdge(const OutDataAnchorPtr &src,
  116. const InControlAnchorPtr &dst) {
  117. if ((src != nullptr) && (src->LinkTo(dst) == GRAPH_SUCCESS)) {
  118. return GRAPH_SUCCESS;
  119. }
  120. GELOGE(GRAPH_FAILED, "Add edge Failed.");
  121. return GRAPH_FAILED;
  122. }
  123. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::RemoveEdge(const OutDataAnchorPtr &src,
  124. const InDataAnchorPtr &dst) {
  125. if ((src != nullptr) && (src->Unlink(dst) == GRAPH_SUCCESS)) {
  126. return GRAPH_SUCCESS;
  127. }
  128. GELOGE(GRAPH_FAILED, "Remove edge Failed.");
  129. return GRAPH_FAILED;
  130. }
  131. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::RemoveEdge(const AnchorPtr &src,
  132. const AnchorPtr &dst) {
  133. if ((src != nullptr) && (src->Unlink(dst) == GRAPH_SUCCESS)) {
  134. return GRAPH_SUCCESS;
  135. }
  136. GELOGE(GRAPH_FAILED, "Remove edge Failed.");
  137. return GRAPH_FAILED;
  138. }
  139. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::RemoveEdge(const OutControlAnchorPtr &src,
  140. const InControlAnchorPtr &dst) {
  141. if ((src != nullptr) && (src->Unlink(dst) == GRAPH_SUCCESS)) {
  142. return GRAPH_SUCCESS;
  143. }
  144. GELOGE(GRAPH_FAILED, "Remove edge Failed.");
  145. return GRAPH_FAILED;
  146. }
  147. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::RemoveEdge(const OutDataAnchorPtr &src,
  148. const InControlAnchorPtr &dst) {
  149. if ((src != nullptr) && (src->Unlink(dst) == GRAPH_SUCCESS)) {
  150. return GRAPH_SUCCESS;
  151. }
  152. GELOGE(GRAPH_FAILED, "Remove edge Failed.");
  153. return GRAPH_FAILED;
  154. }
  155. graphStatus GraphUtils::ReplaceEdgeDst(const OutDataAnchorPtr &src, const InDataAnchorPtr &dst,
  156. const InDataAnchorPtr &new_dst) {
  157. if (RemoveEdge(src, dst) == GRAPH_SUCCESS && AddEdge(src, new_dst) == GRAPH_SUCCESS) {
  158. return GRAPH_SUCCESS;
  159. }
  160. GELOGE(GRAPH_FAILED, "Replace edge dst Failed.");
  161. return GRAPH_FAILED;
  162. }
  163. graphStatus GraphUtils::ReplaceEdgeDst(const OutControlAnchorPtr &src, const InControlAnchorPtr &dst,
  164. const InControlAnchorPtr &new_dst) {
  165. if (RemoveEdge(src, dst) == GRAPH_SUCCESS && AddEdge(src, new_dst) == GRAPH_SUCCESS) {
  166. return GRAPH_SUCCESS;
  167. }
  168. GELOGE(GRAPH_FAILED, "Replace edge dst Failed.");
  169. return GRAPH_FAILED;
  170. }
  171. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::InsertNodeBetweenDataAnchors(
  172. const OutDataAnchorPtr &src, const InDataAnchorPtr &dst, const NodePtr &new_node) {
  173. GE_CHECK_NOTNULL(src);
  174. GE_CHECK_NOTNULL(dst);
  175. GE_CHECK_NOTNULL(new_node);
  176. InDataAnchorPtr node_in_anchor = new_node->GetInDataAnchor(0);
  177. GE_CHK_BOOL_RET_STATUS(node_in_anchor != nullptr, GRAPH_FAILED, "this node has not inDataAnchor");
  178. OutDataAnchorPtr node_out_anchor = new_node->GetOutDataAnchor(0);
  179. GE_CHK_BOOL_RET_STATUS(node_out_anchor != nullptr, GRAPH_FAILED, "this node has not outDataAnchor");
  180. GE_CHK_STATUS_RET(src->ReplacePeer(dst, node_in_anchor, node_out_anchor), "ReplacePeer Failed");
  181. return GRAPH_SUCCESS;
  182. }
  183. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus
  184. GraphUtils::RemoveNodeWithoutRelink(const ComputeGraphPtr &compute_graph, const NodePtr &node) {
  185. GE_CHECK_NOTNULL(compute_graph);
  186. if (node == nullptr) {
  187. GELOGE(GRAPH_FAILED, "The node ptr should not be null.");
  188. return GRAPH_FAILED;
  189. }
  190. // If the node save as input node, delete it
  191. (void)compute_graph->RemoveInputNode(node);
  192. // If the node save as output node, delete it
  193. (void)compute_graph->RemoveOutputNode(node);
  194. // If the node has sub-graphs, delete them
  195. auto sub_graph_names = node->GetOpDesc()->GetSubgraphInstanceNames();
  196. if (!sub_graph_names.empty()) {
  197. auto root_graph = FindRootGraph(compute_graph);
  198. for (const auto &name : sub_graph_names) {
  199. root_graph->RemoveSubgraph(name);
  200. }
  201. }
  202. auto iter = find(compute_graph->nodes_.begin(), compute_graph->nodes_.end(), node);
  203. if (iter != compute_graph->nodes_.end()) {
  204. compute_graph->nodes_.erase(iter);
  205. return GRAPH_SUCCESS;
  206. }
  207. return GRAPH_FAILED;
  208. }
  209. /// Add two edges to the new node, respectively connecting the SRC and DST
  210. /// associated with the original edge
  211. /// A ---> B transfered to A ---> N ---> B
  212. graphStatus InsertTransNode(ComputeGraph &compute_graph, const InDataAnchorPtr &in_data_anchor,
  213. const std::vector<OpDescPtr> &vec_op_desc) {
  214. GE_CHECK_NOTNULL(in_data_anchor);
  215. for (const auto &op_desc : vec_op_desc) {
  216. GE_CHECK_NOTNULL(op_desc);
  217. auto ret = op_desc->AddInputDesc(GeTensorDesc());
  218. GE_CHK_BOOL_EXEC(ret == GRAPH_SUCCESS, return GRAPH_FAILED, "Add input desc failed");
  219. ret = op_desc->AddOutputDesc(GeTensorDesc());
  220. GE_CHK_BOOL_EXEC(ret == GRAPH_SUCCESS, return GRAPH_FAILED, "Add input desc failed");
  221. auto node_to_insert = compute_graph.AddNode(op_desc);
  222. GE_CHECK_NOTNULL(node_to_insert);
  223. GE_CHECK_NOTNULL(in_data_anchor->GetPeerOutAnchor());
  224. auto src = in_data_anchor->GetPeerOutAnchor()->GetOwnerNode();
  225. if (!src) {
  226. GELOGE(GRAPH_FAILED, "src nullptr error.");
  227. return GRAPH_FAILED;
  228. }
  229. auto src_out_index = in_data_anchor->GetPeerOutAnchor()->GetIdx();
  230. auto dst = in_data_anchor->GetOwnerNode();
  231. if (!dst) {
  232. GELOGE(GRAPH_FAILED, "dst nullptr error.");
  233. return GRAPH_FAILED;
  234. }
  235. auto dst_in_index = in_data_anchor->GetIdx();
  236. auto in_data_anchor_src_format = AnchorUtils::GetFormat(in_data_anchor->GetPeerOutAnchor());
  237. auto in_data_anchor_dst_format = AnchorUtils::GetFormat(in_data_anchor);
  238. GE_CHECK_NOTNULL(src->GetOutDataAnchor(src_out_index));
  239. GE_CHECK_NOTNULL(dst->GetInDataAnchor(dst_in_index));
  240. ret = GraphUtils::RemoveEdge(src->GetOutDataAnchor(src_out_index), dst->GetInDataAnchor(dst_in_index));
  241. if (ret != GRAPH_SUCCESS) {
  242. GELOGE(GRAPH_FAILED, "Remove edge failed");
  243. return GRAPH_FAILED;
  244. }
  245. GE_CHECK_NOTNULL(node_to_insert->GetInDataAnchor(0));
  246. GE_CHECK_NOTNULL(node_to_insert->GetOutDataAnchor(0));
  247. ret = GraphUtils::AddEdge(src->GetOutDataAnchor(src_out_index), node_to_insert->GetInDataAnchor(0));
  248. if (ret != GRAPH_SUCCESS) {
  249. GELOGE(GRAPH_FAILED, "Add edge failed");
  250. return ret;
  251. }
  252. ret = GraphUtils::AddEdge(node_to_insert->GetOutDataAnchor(0), dst->GetInDataAnchor(dst_in_index));
  253. if (ret != GRAPH_SUCCESS) {
  254. GELOGE(GRAPH_FAILED, "Add edge failed");
  255. return ret;
  256. }
  257. if (op_desc->HasAttr("input_format")) {
  258. int64_t input_format = 0;
  259. int64_t output_format = 0;
  260. if (!AttrUtils::GetInt(op_desc, "input_format", input_format)) {
  261. GELOGW("get attr input_format failed");
  262. continue;
  263. }
  264. if (!AttrUtils::GetInt(op_desc, "output_format", output_format)) {
  265. GELOGW("get attr output_format failed");
  266. continue;
  267. }
  268. GE_CHECK_NOTNULL(node_to_insert->GetInDataAnchor(0)->GetPeerOutAnchor());
  269. GE_CHK_BOOL_RET_STATUS(node_to_insert->GetOutDataAnchor(0)->GetPeerInDataAnchors().empty(), GRAPH_FAILED,
  270. "Vistor<InDataAnchorPtr> is empty");
  271. GE_CHECK_NOTNULL(node_to_insert->GetOutDataAnchor(0)->GetPeerInDataAnchors().at(0));
  272. auto status =
  273. AnchorUtils::SetFormat(node_to_insert->GetInDataAnchor(0)->GetPeerOutAnchor(), in_data_anchor_src_format);
  274. if (status != GRAPH_SUCCESS) {
  275. GELOGE(GRAPH_FAILED, "Set format failed,format is %d", static_cast<int>(in_data_anchor_src_format));
  276. return status;
  277. }
  278. status = AnchorUtils::SetFormat(node_to_insert->GetInDataAnchor(0), static_cast<Format>(input_format));
  279. if (status != GRAPH_SUCCESS) {
  280. GELOGE(GRAPH_FAILED, "Set format failed,format is %ld", input_format);
  281. return status;
  282. }
  283. status = AnchorUtils::SetFormat(node_to_insert->GetOutDataAnchor(0), static_cast<Format>(output_format));
  284. if (status != GRAPH_SUCCESS) {
  285. GELOGE(GRAPH_FAILED, "Set format failed,format is %ld", output_format);
  286. return status;
  287. }
  288. status = AnchorUtils::SetFormat(node_to_insert->GetOutDataAnchor(0)->GetPeerInDataAnchors().at(0),
  289. in_data_anchor_dst_format);
  290. if (status != GRAPH_SUCCESS) {
  291. GELOGE(GRAPH_FAILED, "Set format failed,format is %d", static_cast<int>(in_data_anchor_dst_format));
  292. return status;
  293. }
  294. }
  295. std::vector<ge::NodePtr> original_nodes;
  296. GraphUtils::RecordOriginalNames(original_nodes, node_to_insert);
  297. }
  298. return GRAPH_SUCCESS;
  299. }
  300. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::InsertTransNode(
  301. ComputeGraphPtr compute_graph, const InDataAnchorPtr &in_data_anchor, const std::vector<OpDescPtr> &vec_op_desc) {
  302. GE_CHECK_NOTNULL(compute_graph);
  303. GE_CHECK_NOTNULL(in_data_anchor);
  304. graphStatus ret =
  305. ge::InsertTransNode(*compute_graph, in_data_anchor, vec_op_desc) == GRAPH_SUCCESS ? GRAPH_SUCCESS : GRAPH_FAILED;
  306. return ret;
  307. }
  308. ///
  309. /// @brief Insert node: src->insert_node:input_index, insert_node:output_index->dst
  310. /// @param [in] src
  311. /// @param [in] dsts
  312. /// @param [in] insert_node
  313. /// @param [in] input_index
  314. /// @param [in] output_index
  315. /// @return graphStatus
  316. ///
  317. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus
  318. GraphUtils::InsertNodeBefore(const OutDataAnchorPtr &src, const std::vector<InDataAnchorPtr> &dsts,
  319. const NodePtr &insert_node, uint32_t input_index, uint32_t output_index) {
  320. GE_CHECK_NOTNULL(src);
  321. GE_CHECK_NOTNULL(insert_node);
  322. NodePtr src_node = src->GetOwnerNode();
  323. if (src_node->GetOwnerComputeGraph() != insert_node->GetOwnerComputeGraph()) {
  324. GELOGE(GRAPH_FAILED, "src:%s and insert_node:%s not exist in the same graph.", src_node->GetName().c_str(),
  325. insert_node->GetName().c_str());
  326. return GRAPH_FAILED;
  327. }
  328. if (AddEdge(src, insert_node->GetInDataAnchor(input_index)) != GRAPH_SUCCESS) {
  329. GELOGE(GRAPH_FAILED, "AddEdge %s->%s failed.", src_node->GetName().c_str(), insert_node->GetName().c_str());
  330. return GRAPH_FAILED;
  331. }
  332. OutControlAnchorPtr src_out_ctrl_anchor = src_node->GetOutControlAnchor();
  333. GE_CHECK_NOTNULL(src_out_ctrl_anchor);
  334. for (auto &dst : dsts) {
  335. GE_CHECK_NOTNULL(dst);
  336. NodePtr dst_node = dst->GetOwnerNode();
  337. GE_CHECK_NOTNULL(dst_node);
  338. GELOGI("Insert node %s between %s->%s.", insert_node->GetName().c_str(), src_node->GetName().c_str(),
  339. dst_node->GetName().c_str());
  340. if (src_node->GetOwnerComputeGraph() != dst_node->GetOwnerComputeGraph()) {
  341. GELOGE(GRAPH_FAILED, "src:%s and dst:%s not exist in the same graph.", src_node->GetName().c_str(),
  342. dst_node->GetName().c_str());
  343. return GRAPH_FAILED;
  344. }
  345. if ((RemoveEdge(src, dst) != GRAPH_SUCCESS) ||
  346. (AddEdge(insert_node->GetOutDataAnchor(output_index), dst) != GRAPH_SUCCESS)) {
  347. GELOGE(GRAPH_FAILED, "ReplaceEdge from %s->%s to %s->%s failed.", src_node->GetName().c_str(),
  348. dst_node->GetName().c_str(), insert_node->GetName().c_str(), dst_node->GetName().c_str());
  349. return GRAPH_FAILED;
  350. }
  351. OutControlAnchorPtr new_out_ctrl_anchor = insert_node->GetOutControlAnchor();
  352. GE_CHECK_NOTNULL(new_out_ctrl_anchor);
  353. for (InControlAnchorPtr peer_in_ctrl_anchor : src_out_ctrl_anchor->GetPeerInControlAnchors()) {
  354. if ((RemoveEdge(src_out_ctrl_anchor, peer_in_ctrl_anchor) != GRAPH_SUCCESS) ||
  355. (AddEdge(new_out_ctrl_anchor, peer_in_ctrl_anchor) != GRAPH_SUCCESS)) {
  356. GELOGE(GRAPH_FAILED, "ReplaceEdge from %s->%s to %s->%s failed.", src_node->GetName().c_str(),
  357. peer_in_ctrl_anchor->GetOwnerNode()->GetName().c_str(), insert_node->GetName().c_str(),
  358. peer_in_ctrl_anchor->GetOwnerNode()->GetName().c_str());
  359. return GRAPH_FAILED;
  360. }
  361. }
  362. }
  363. return GRAPH_SUCCESS;
  364. }
  365. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::RemoveJustNode(ComputeGraph &compute_graph,
  366. const NodePtr &node) {
  367. if (node == nullptr) {
  368. GELOGE(GRAPH_FAILED, "The node ptr should be not null.");
  369. return GRAPH_FAILED;
  370. }
  371. auto iter = find(compute_graph.nodes_.begin(), compute_graph.nodes_.end(), node);
  372. if (iter != compute_graph.nodes_.end()) {
  373. compute_graph.nodes_.erase(iter);
  374. return GRAPH_SUCCESS;
  375. }
  376. return GRAPH_FAILED;
  377. }
  378. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::RemoveJustNode(ComputeGraphPtr compute_graph,
  379. const NodePtr &node) {
  380. GE_CHECK_NOTNULL(compute_graph);
  381. GE_CHECK_NOTNULL(node);
  382. graphStatus ret = (RemoveJustNode(*compute_graph, node) == GRAPH_SUCCESS ? GRAPH_SUCCESS : GRAPH_FAILED);
  383. return ret;
  384. }
  385. void GraphUtils::RecordOriginalNames(std::vector<ge::NodePtr> original_nodes, const ge::NodePtr &node) {
  386. GE_CHK_BOOL_EXEC(node != nullptr, return, "node is null.");
  387. std::vector<std::string> original_names;
  388. for (const auto &node_tmp : original_nodes) {
  389. std::vector<std::string> names_tmp;
  390. ge::OpDescPtr opdesc_tmp = node_tmp->GetOpDesc();
  391. if (opdesc_tmp == nullptr) {
  392. GELOGE(GRAPH_FAILED, "Node %s get opdesc is nullptr", node_tmp->GetName().c_str());
  393. continue;
  394. }
  395. auto ret = ge::AttrUtils::GetListStr(opdesc_tmp, ATTR_NAME_DATA_DUMP_ORIGIN_OP_NAMES, names_tmp);
  396. if (!ret) {
  397. GELOGW("Get list str failed");
  398. continue;
  399. }
  400. if (names_tmp.size() != 0) {
  401. original_names.insert(original_names.end(), names_tmp.begin(), names_tmp.end());
  402. } else {
  403. original_names.push_back(opdesc_tmp->GetName());
  404. }
  405. }
  406. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetListStr(node->GetOpDesc(), ATTR_NAME_DATA_DUMP_ORIGIN_OP_NAMES, original_names),
  407. return, "Set original_op_names fail.");
  408. }
  409. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY void GraphUtils::RecordOriginalNames(std::vector<std::string> names_tmp,
  410. const ge::NodePtr &node) {
  411. GE_CHK_BOOL_EXEC(node != nullptr, return, "node is null.");
  412. std::vector<std::string> original_names;
  413. if (names_tmp.size() != 0) {
  414. original_names.insert(original_names.end(), names_tmp.begin(), names_tmp.end());
  415. } else {
  416. std::string tmp;
  417. original_names.push_back(tmp);
  418. }
  419. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetListStr(node->GetOpDesc(), ATTR_NAME_DATA_DUMP_ORIGIN_OP_NAMES, original_names),
  420. return, "Set original_op_names fail.");
  421. }
  422. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY bool GraphUtils::MatchDumpStr(const std::string &suffix) {
  423. char *dump_level = std::getenv(kDumpGraphLevel);
  424. int64_t dump_graph_level =
  425. (dump_level != nullptr) ? std::strtol(dump_level, nullptr, kBaseOfIntegerValue) : kDumpLevel2;
  426. if (dump_graph_level == kDumpLevel1) {
  427. return false;
  428. }
  429. if (dump_graph_level == kDumpLevel2 && ((suffix.find(kDumpStrPartition) != std::string::npos) ||
  430. (suffix.find(kDumpStrOptimizeSubgraph) != std::string::npos) ||
  431. (suffix.find(kDumpStrAicpu) != std::string::npos))) {
  432. return true;
  433. }
  434. if (dump_graph_level == kDumpLevel3 && suffix.compare(kDumpStrBuild) != 0) {
  435. return true;
  436. }
  437. return false;
  438. }
  439. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY void GraphUtils::DumpGEGraph(const ge::ComputeGraphPtr &graph,
  440. const std::string &suffix,
  441. bool is_always_dump) {
  442. #ifdef FMK_SUPPORT_DUMP
  443. char *dump_ge_graph = std::getenv(kDumpGeGraph);
  444. GE_IF_BOOL_EXEC(dump_ge_graph == nullptr && !is_always_dump, return;);
  445. // dump the graph according to different graph level
  446. if (GraphUtils::MatchDumpStr(suffix)) {
  447. return;
  448. }
  449. // file name
  450. static int file_idx = 0;
  451. const int dump_graph_index_width = 5;
  452. file_idx++;
  453. GELOGD("Start to dump om txt: %d", file_idx);
  454. static int max_dumpfile_num = 0;
  455. if (max_dumpfile_num == 0) {
  456. string opt = "0";
  457. (void)GetContext().GetOption("ge.maxDumpFileNum", opt);
  458. max_dumpfile_num = std::strtol(opt.c_str(), nullptr, kBaseOfIntegerValue);
  459. }
  460. if (max_dumpfile_num != 0 && file_idx > max_dumpfile_num) {
  461. GELOGW("dump graph file cnt > maxDumpFileNum, maxDumpFileCnt=%d.", max_dumpfile_num);
  462. return;
  463. }
  464. std::stringstream stream_file_name;
  465. stream_file_name << "ge_proto_" << std::setw(dump_graph_index_width) << std::setfill('0') << file_idx;
  466. stream_file_name << "_" << suffix << ".txt";
  467. std::string proto_file = stream_file_name.str();
  468. // Create buffer
  469. ge::Model model("", "");
  470. model.SetGraph(GraphUtils::CreateGraphFromComputeGraph(std::const_pointer_cast<ComputeGraph>(graph)));
  471. Buffer buffer;
  472. model.Save(buffer, true);
  473. // Write file
  474. ge::proto::ModelDef ge_proto;
  475. if (buffer.GetData() != nullptr) {
  476. std::string str(reinterpret_cast<const char *>(buffer.GetData()), buffer.GetSize());
  477. if (!ge_proto.ParseFromString(str)) {
  478. GELOGE(GRAPH_FAILED, "parse from string failed.");
  479. return;
  480. }
  481. char real_path[PATH_MAX] = {0x00};
  482. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(strlen(proto_file.c_str()) >= PATH_MAX, return, "file path is too longer!");
  483. GE_IF_BOOL_EXEC(realpath(proto_file.c_str(), real_path) == nullptr,
  484. GELOGI("file %s does not exist, it will be created.", proto_file.c_str()));
  485. GraphUtils::WriteProtoToTextFile(ge_proto, real_path);
  486. }
  487. #else
  488. GELOGW("need to define FMK_SUPPORT_DUMP for dump graph.");
  489. #endif
  490. }
  491. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY bool GraphUtils::LoadGEGraph(const char *file,
  492. ge::ComputeGraph &compute_graph) {
  493. ge::proto::ModelDef model_def;
  494. // Get ModelDef object from file generated by DumpGEGraph()
  495. if (!ReadProtoFromTextFile(file, &model_def)) {
  496. GELOGE(GRAPH_FAILED, "Get ModelDef failed from file");
  497. return false;
  498. }
  499. ge::Model model;
  500. // Get Model object from ModelDef by deserialize ModelDef
  501. if (model.Load(model_def) == GRAPH_SUCCESS) {
  502. GE_CHK_BOOL_EXEC(GraphUtils::GetComputeGraph(model.GetGraph()) != nullptr, return false,
  503. "Get computer graph is nullptr");
  504. compute_graph = *(GraphUtils::GetComputeGraph(model.GetGraph()));
  505. return true;
  506. } else {
  507. GELOGE(GRAPH_FAILED, "Get Model failed from ModelDef");
  508. return false;
  509. }
  510. }
  511. // Printing protocol messages in text format is useful for debugging and human editing of messages.
  512. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY void GraphUtils::WriteProtoToTextFile(
  513. const google::protobuf::Message &proto, const char *real_path) {
  514. #ifdef FMK_SUPPORT_DUMP
  515. const int FILE_AUTHORITY = 0600;
  516. int fd = open(real_path, O_WRONLY | O_CREAT | O_TRUNC, FILE_AUTHORITY);
  517. if (fd < 0) {
  518. GELOGE(GRAPH_FAILED, "fail to open the file: %s, %s", real_path, strerror(errno));
  519. return;
  520. }
  521. google::protobuf::io::FileOutputStream *output = new (std::nothrow) FileOutputStream(fd);
  522. if (output == nullptr) {
  523. GELOGE(GRAPH_FAILED, "Output is nullptr");
  524. if (close(fd) != 0) {
  525. GELOGE(GRAPH_FAILED, "Close fileoutputstream failed");
  526. }
  527. return;
  528. }
  529. bool ret = google::protobuf::TextFormat::Print(proto, output);
  530. if (!ret) {
  531. GELOGE(GRAPH_FAILED, "Fail to write the file: %s", real_path);
  532. delete output;
  533. output = nullptr;
  534. GE_CHK_BOOL_EXEC(close(fd) == 0, return, "Close fileoutputstream failed");
  535. return;
  536. }
  537. delete output;
  538. output = nullptr;
  539. GE_CHK_BOOL_EXEC(close(fd) == 0, return, "Close fileoutputstream failed");
  540. FILE *file = fopen(real_path, "rb");
  541. if (file == nullptr) {
  542. return;
  543. }
  544. if (fseek(file, 0L, SEEK_END) == 0) {
  545. int64_t fileSize = ftell(file);
  546. static int64_t maxDumpFileSize = 0;
  547. if (maxDumpFileSize == 0) {
  548. string opt = "0";
  549. // Can not check return value
  550. (void)GetContext().GetOption("ge.maxDumpFileSize", opt);
  551. maxDumpFileSize = atol(opt.c_str());
  552. }
  553. if (maxDumpFileSize != 0 && fileSize != -1 && fileSize > maxDumpFileSize) {
  554. GELOGW("dump graph file size > maxDumpFileSize, maxDumpFileSize=%ld.", maxDumpFileSize);
  555. GE_IF_BOOL_EXEC(std::remove(real_path) != 0, GELOGW("remove %s failed", real_path));
  556. GE_CHK_BOOL_EXEC(fclose(file) == 0, return, "Fclose %s failed", real_path);
  557. return;
  558. }
  559. }
  560. GE_CHK_BOOL_EXEC(fclose(file) == 0, return, "Fclose fileoutputstream failed");
  561. #else
  562. GELOGW("need to define FMK_SUPPORT_DUMP for dump graph.");
  563. #endif
  564. }
  565. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY bool GraphUtils::ReadProtoFromTextFile(
  566. const char *file, google::protobuf::Message *proto) {
  567. if (file == nullptr || proto == nullptr) {
  568. GELOGE(GRAPH_FAILED, "incorrect parameter. file path or message is invalid");
  569. return false;
  570. }
  571. std::ifstream fs(file, std::ifstream::in);
  572. if (!fs.is_open()) {
  573. GELOGE(GRAPH_FAILED, "proto file '%s' open fail.", file);
  574. return false;
  575. }
  576. google::protobuf::io::IstreamInputStream input(&fs);
  577. bool ret = google::protobuf::TextFormat::Parse(&input, proto);
  578. if (!ret) {
  579. GELOGE(GRAPH_FAILED, "parse proto from text ret fail, please check your text file '%s'.", file);
  580. }
  581. fs.close();
  582. return ret;
  583. }
  584. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY void GraphUtils::DumpGEGraphToOnnx(const ge::ComputeGraph &compute_graph,
  585. const std::string &suffix) {
  586. #ifdef FMK_SUPPORT_DUMP
  587. char *dump_ge_graph = std::getenv(kDumpGeGraph);
  588. int64_t dump_ge_graph_level =
  589. (dump_ge_graph != nullptr) ? std::strtol(dump_ge_graph, nullptr, kBaseOfIntegerValue) : OnnxUtils::NO_DUMP;
  590. if ((dump_ge_graph_level == OnnxUtils::NO_DUMP) || (dump_ge_graph_level >= OnnxUtils::DUMP_LEVEL_END)) {
  591. GELOGD("Skip DumpGEGraphToOnnx with dump_ge_graph_level %ld.", dump_ge_graph_level);
  592. return;
  593. }
  594. // dump the graph according to different graph level
  595. if (GraphUtils::MatchDumpStr(suffix)) {
  596. return;
  597. }
  598. // 1.Get ge::onnx::ModelProto from ge::Model
  599. ge::Model model("GE", "");
  600. std::shared_ptr<ge::ComputeGraph> compute_graph_ptr = ComGraphMakeShared<ge::ComputeGraph>(compute_graph);
  601. model.SetGraph(GraphUtils::CreateGraphFromComputeGraph(std::const_pointer_cast<ComputeGraph>(compute_graph_ptr)));
  602. onnx::ModelProto model_proto;
  603. if (!OnnxUtils::ConvertGeModelToModelProto(model, model_proto)) {
  604. GELOGE(GRAPH_FAILED, "DumpGEGraphToOnnx failed.");
  605. return;
  606. }
  607. // 2.Set file name
  608. static int file_index = 0;
  609. file_index++;
  610. GELOGD("Start to dump ge onnx file: %d", file_index);
  611. static int max_dumpfile_num = 0;
  612. if (max_dumpfile_num == 0) {
  613. string opt = "0";
  614. (void)GetContext().GetOption("ge.maxDumpFileNum", opt);
  615. max_dumpfile_num = std::strtol(opt.c_str(), nullptr, kBaseOfIntegerValue);
  616. }
  617. if (max_dumpfile_num != 0 && file_index > max_dumpfile_num) {
  618. GELOGW("dump graph file cnt > maxDumpFileNum, maxDumpFileNum=%d.", max_dumpfile_num);
  619. return;
  620. }
  621. /// 99999 graphs can be dumped at most at one time
  622. /// setw(5) is for formatted sort
  623. std::stringstream stream_file_name;
  624. stream_file_name << "ge_onnx_" << std::setw(5) << std::setfill('0') << file_index;
  625. stream_file_name << "_graph_" << compute_graph.GetGraphID();
  626. stream_file_name << "_" << suffix << ".pbtxt";
  627. std::string proto_file = stream_file_name.str();
  628. if ((proto_file.length()) >= NAME_MAX) {
  629. GELOGE(GRAPH_FAILED, "File name is too longer!");
  630. return;
  631. }
  632. std::unique_ptr<char> real_path(new (std::nothrow) char[PATH_MAX]{0});
  633. if (real_path == nullptr) {
  634. GELOGE(GRAPH_FAILED, "New real_path failed.");
  635. return;
  636. }
  637. /// Returning nullptr means 3 case as follows:
  638. /// a.path is PATH_MAX chars or more
  639. /// b.the file does not exist
  640. /// c.the path has no permissions
  641. /// Distinguish between last the two cases in the function WriteProtoToTextFile call open()
  642. if (realpath(proto_file.c_str(), real_path.get()) == nullptr) {
  643. // For case a
  644. if (errno == ENAMETOOLONG) {
  645. GELOGE(GRAPH_FAILED, "Call realpath failed: path is PATH_MAX chars or more.");
  646. return;
  647. }
  648. }
  649. // 3. Serialize to file in current path
  650. GraphUtils::WriteProtoToTextFile(model_proto, real_path.get());
  651. #else
  652. GELOGW("need to define FMK_SUPPORT_DUMP for dump graph.");
  653. #endif
  654. }
  655. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY bool GraphUtils::LoadGEGraphFromOnnx(const char *file,
  656. ge::ComputeGraph &compute_graph) {
  657. if (file == nullptr) {
  658. GELOGE(GRAPH_FAILED, "incorrect parameter. file path is invalid");
  659. return false;
  660. }
  661. onnx::ModelProto model_proto;
  662. // 1. Get ModelDef object from file generated by DumpGEGraphToOnnx()
  663. if (!ReadProtoFromTextFile(file, &model_proto)) {
  664. GELOGE(GRAPH_FAILED, "Get ModelDef from file failed");
  665. return false;
  666. }
  667. // 2.Convert onnx::ModelProto To ge::Model
  668. ge::Model model;
  669. if (!OnnxUtils::ConvertModelProtoToGeModel(model_proto, model)) {
  670. GELOGE(GRAPH_FAILED, "Convert ModelDef to Model failed");
  671. return false;
  672. }
  673. auto compute_graph_ptr = GraphUtils::GetComputeGraph(model.GetGraph());
  674. if (compute_graph_ptr == nullptr) {
  675. GELOGE(GRAPH_FAILED, "Get compute graph from Model failed");
  676. return false;
  677. }
  678. compute_graph = *(compute_graph_ptr);
  679. return true;
  680. }
  681. namespace {
  682. using InNodesToOut = std::unordered_map<NodePtr, std::unordered_set<NodePtr>>;
  683. inline std::string GetNodeNameByAnchor(const Anchor *anchor) {
  684. if (anchor == nullptr) {
  685. GELOGE(GRAPH_FAILED, "Anchor is nullptr");
  686. return "Null";
  687. }
  688. auto node = anchor->GetOwnerNode();
  689. return node == nullptr ? "Null" : node->GetName();
  690. }
  691. graphStatus ReplaceOutDataAnchor(const OutDataAnchorPtr &new_anchor, const OutDataAnchorPtr &old_anchor,
  692. InNodesToOut *in_nodes_to_out = nullptr) {
  693. if (new_anchor == nullptr || old_anchor == nullptr) {
  694. GELOGE(GRAPH_FAILED, "new_anchor or old_anchor is nullptr");
  695. return GRAPH_PARAM_INVALID;
  696. }
  697. auto new_node = new_anchor->GetOwnerNode();
  698. for (const auto &peer_in_anchor : old_anchor->GetPeerInDataAnchors()) {
  699. auto ret = peer_in_anchor->Unlink(old_anchor);
  700. if (ret != GRAPH_SUCCESS) {
  701. GELOGE(GRAPH_FAILED, "Failed to unlink old anchor link from %s(%d) to %s(%d)",
  702. GetNodeNameByAnchor(old_anchor.get()).c_str(), old_anchor->GetIdx(),
  703. GetNodeNameByAnchor(peer_in_anchor.get()).c_str(), peer_in_anchor->GetIdx());
  704. return GRAPH_FAILED;
  705. }
  706. ret = peer_in_anchor->LinkFrom(new_anchor);
  707. if (ret != GRAPH_SUCCESS) {
  708. GELOGE(GRAPH_FAILED, "Failed to relink new anchors from %s(%d) to %s(%d)",
  709. GetNodeNameByAnchor(new_anchor.get()).c_str(), new_anchor->GetIdx(),
  710. GetNodeNameByAnchor(peer_in_anchor.get()).c_str(), peer_in_anchor->GetIdx());
  711. return GRAPH_FAILED;
  712. }
  713. if (in_nodes_to_out != nullptr) {
  714. (*in_nodes_to_out)[new_node].insert(peer_in_anchor->GetOwnerNode());
  715. }
  716. }
  717. return GRAPH_SUCCESS;
  718. }
  719. graphStatus RelinkDataIO(const NodePtr &node, const std::vector<int> &io_map, InNodesToOut &in_nodes_to_out) {
  720. GE_CHECK_NOTNULL(node);
  721. auto in_data_anchors = node->GetAllInDataAnchors();
  722. auto out_data_anchors = node->GetAllOutDataAnchors();
  723. if (out_data_anchors.size() < io_map.size()) {
  724. GELOGE(GRAPH_FAILED, "The io_map specified for node %s type %s is larger %zu than the actual size %zu",
  725. node->GetName().c_str(), node->GetType().c_str(), io_map.size(), out_data_anchors.size());
  726. return GRAPH_PARAM_INVALID;
  727. }
  728. for (size_t i = 0; i < out_data_anchors.size(); ++i) {
  729. auto out_data_anchor = out_data_anchors.at(i);
  730. if (out_data_anchor == nullptr) {
  731. GELOGE(GRAPH_FAILED, "Failed to relink for node %s type %s, the out data anchor at index %zu is null",
  732. node->GetName().c_str(), node->GetType().c_str(), i);
  733. return GRAPH_FAILED;
  734. }
  735. int in_index = -1;
  736. if (i < io_map.size()) {
  737. in_index = io_map.at(i);
  738. }
  739. if (in_index < 0) {
  740. out_data_anchor->UnlinkAll();
  741. continue;
  742. }
  743. if (in_index >= static_cast<int>(in_data_anchors.size())) {
  744. GELOGE(GRAPH_PARAM_INVALID, "Failed to relink for node %s type %s, invalid index %d specified for input(%zu)",
  745. node->GetName().c_str(), node->GetType().c_str(), in_index, in_data_anchors.size());
  746. return GRAPH_PARAM_INVALID;
  747. }
  748. auto in_anchor = in_data_anchors.at(in_index);
  749. if (in_anchor == nullptr) {
  750. GELOGW("Invalid in data anchors(null) found at node %s type %s index %d, ignore it.", node->GetName().c_str(),
  751. node->GetType().c_str(), in_index);
  752. continue;
  753. }
  754. auto peer_out_anchor = in_anchor->GetPeerOutAnchor();
  755. if (peer_out_anchor == nullptr) {
  756. continue;
  757. }
  758. if (peer_out_anchor->Unlink(in_anchor) != GRAPH_SUCCESS) {
  759. GELOGE(GRAPH_FAILED,
  760. "Failed relink node %s type %s, failed to unlink the data link"
  761. " from %s(%d) to it at input-index %d",
  762. node->GetName().c_str(), node->GetType().c_str(), GetNodeNameByAnchor(peer_out_anchor.get()).c_str(),
  763. peer_out_anchor->GetIdx(), in_index);
  764. return GRAPH_FAILED;
  765. }
  766. auto ret = ReplaceOutDataAnchor(peer_out_anchor, out_data_anchor, &in_nodes_to_out);
  767. if (ret != GRAPH_SUCCESS) {
  768. GELOGE(GRAPH_FAILED, "Failed to relink node %s type %s for relinking data anchors", node->GetName().c_str(),
  769. node->GetType().c_str());
  770. return GRAPH_FAILED;
  771. }
  772. }
  773. for (const auto &in_anchor : node->GetAllInDataAnchors()) {
  774. in_anchor->UnlinkAll();
  775. }
  776. return GRAPH_SUCCESS;
  777. }
  778. InNodesToOut GetFullConnectIONodes(const NodePtr &node) {
  779. InNodesToOut in_nodes_to_out;
  780. if (node == nullptr) {
  781. GELOGE(GRAPH_FAILED, "Node is nullptr,node is %s", node->GetName().c_str());
  782. return in_nodes_to_out;
  783. }
  784. auto in_nodes_list = node->GetInNodes();
  785. auto out_nodes_list = node->GetOutNodes();
  786. auto out_nodes = std::unordered_set<NodePtr>(out_nodes_list.begin(), out_nodes_list.end());
  787. for (const auto &in_node : in_nodes_list) {
  788. in_nodes_to_out.insert(std::make_pair(in_node, out_nodes));
  789. }
  790. return in_nodes_to_out;
  791. }
  792. graphStatus RelinkControlNodeIfNeed(const NodePtr &node, InNodesToOut &in_nodes_to_out,
  793. InNodesToOut &connected_data_in_to_out) {
  794. GE_CHECK_NOTNULL(node);
  795. for (const auto &in_node_to_out : in_nodes_to_out) {
  796. auto &in_node = in_node_to_out.first;
  797. GE_CHECK_NOTNULL(in_node);
  798. auto &connected_data_out = connected_data_in_to_out[in_node];
  799. for (const auto &out_node : in_node_to_out.second) {
  800. GE_CHECK_NOTNULL(out_node);
  801. if (connected_data_out.count(out_node) == 0) {
  802. GE_CHECK_NOTNULL(in_node->GetOutControlAnchor());
  803. if (in_node->GetOutControlAnchor()->IsLinkedWith(out_node->GetInControlAnchor())) {
  804. continue;
  805. }
  806. auto ret = GraphUtils::AddEdge(in_node->GetOutControlAnchor(), out_node->GetInControlAnchor());
  807. if (ret != GRAPH_SUCCESS) {
  808. GELOGE(GRAPH_FAILED, "Failed to add control edge from %s to %s when isolating node %s type %s",
  809. in_node->GetName().c_str(), out_node->GetName().c_str(), node->GetName().c_str(),
  810. node->GetType().c_str());
  811. return GRAPH_FAILED;
  812. }
  813. }
  814. }
  815. }
  816. return GRAPH_SUCCESS;
  817. }
  818. graphStatus ReplaceOutDataAnchors(const Node::Vistor<OutDataAnchorPtr> &new_outs,
  819. const Node::Vistor<OutDataAnchorPtr> &old_outs, const std::vector<int> &outputs_map) {
  820. auto new_out_size = new_outs.size();
  821. if (new_out_size < outputs_map.size()) {
  822. GELOGE(GRAPH_PARAM_INVALID,
  823. "Failed to replace out data anchors, the actual size %zu is less than the mapping size %zu", new_out_size,
  824. outputs_map.size());
  825. return GRAPH_PARAM_INVALID;
  826. }
  827. for (size_t i = 0; i < new_out_size; ++i) {
  828. auto &new_out_anchor = new_outs.at(i);
  829. if (new_out_anchor == nullptr) {
  830. GELOGE(GRAPH_FAILED, "Failed to replace out data anchors, the out data anchor on new node is null, index %zu", i);
  831. return GRAPH_FAILED;
  832. }
  833. if (i >= outputs_map.size()) {
  834. continue;
  835. }
  836. auto old_index = outputs_map.at(i);
  837. if (old_index < 0) {
  838. continue;
  839. }
  840. const OutDataAnchorPtr &old_out_anchor = old_outs.at(old_index);
  841. if (old_out_anchor == nullptr) {
  842. GELOGE(GRAPH_FAILED, "Failed to replace out data anchors, the out data anchor on old node is null, index %d",
  843. old_index);
  844. return GRAPH_FAILED;
  845. }
  846. auto ret = ReplaceOutDataAnchor(new_out_anchor, old_out_anchor);
  847. if (ret != GRAPH_SUCCESS) {
  848. return ret;
  849. }
  850. }
  851. return GRAPH_SUCCESS;
  852. }
  853. graphStatus ReplaceInDataAnchors(const Node::Vistor<InDataAnchorPtr> &new_ins,
  854. const Node::Vistor<InDataAnchorPtr> &old_ins, const std::vector<int> &inputs_map) {
  855. auto new_in_size = new_ins.size();
  856. if (new_in_size < inputs_map.size()) {
  857. GELOGE(GRAPH_FAILED, "Failed to replace in data anchors, the actual size %zu is less than the mapping size %zu",
  858. new_in_size, inputs_map.size());
  859. return GRAPH_PARAM_INVALID;
  860. }
  861. for (size_t i = 0; i < new_in_size; ++i) {
  862. auto &new_in_anchor = new_ins.at(i);
  863. if (new_in_anchor == nullptr) {
  864. GELOGE(GRAPH_FAILED, "Failed to replace in data anchors, the out data anchor on new node is null, index %zu", i);
  865. return GRAPH_FAILED;
  866. }
  867. if (i >= inputs_map.size()) {
  868. continue;
  869. }
  870. auto old_index = inputs_map.at(i);
  871. if (old_index < 0) {
  872. continue;
  873. }
  874. const InDataAnchorPtr &old_in_anchor = old_ins.at(old_index);
  875. if (old_in_anchor == nullptr) {
  876. GELOGE(GRAPH_FAILED, "Failed to replace in data anchors, the out data anchor on old node is null, index %d",
  877. old_index);
  878. return GRAPH_FAILED;
  879. }
  880. auto peer_out_anchor = old_in_anchor->GetPeerOutAnchor();
  881. if (peer_out_anchor == nullptr) {
  882. GELOGW("Peer out anchor is nullptr");
  883. continue;
  884. }
  885. auto ret = peer_out_anchor->Unlink(old_in_anchor);
  886. if (ret != GRAPH_SUCCESS) {
  887. GELOGE(GRAPH_FAILED, "Failed to unlink old anchors, unlink from %s(%d) to %s(%d)",
  888. GetNodeNameByAnchor(peer_out_anchor.get()).c_str(), peer_out_anchor->GetIdx(),
  889. GetNodeNameByAnchor(old_in_anchor.get()).c_str(), old_in_anchor->GetIdx());
  890. return GRAPH_FAILED;
  891. }
  892. ret = peer_out_anchor->LinkTo(new_in_anchor);
  893. if (ret != GRAPH_SUCCESS) {
  894. GELOGE(GRAPH_FAILED, "Failed to link new anchors, link from %s(%d) to %s(%d)",
  895. GetNodeNameByAnchor(peer_out_anchor.get()).c_str(), peer_out_anchor->GetIdx(),
  896. GetNodeNameByAnchor(old_in_anchor.get()).c_str(), old_in_anchor->GetIdx());
  897. return GRAPH_FAILED;
  898. }
  899. }
  900. return GRAPH_SUCCESS;
  901. }
  902. graphStatus ReplaceControlAnchors(const NodePtr &new_node, const NodePtr &old_node) {
  903. GE_CHECK_NOTNULL(new_node);
  904. GE_CHECK_NOTNULL(new_node->GetInControlAnchor());
  905. GE_CHECK_NOTNULL(old_node);
  906. GE_CHECK_NOTNULL(old_node->GetInControlAnchor());
  907. auto peer_out_anchors = old_node->GetInControlAnchor()->GetPeerAnchors();
  908. auto new_in_control_anchor = new_node->GetInControlAnchor();
  909. auto exists_out_anchors = new_in_control_anchor->GetPeerAnchors();
  910. auto exists_out_anchors_set = std::set<AnchorPtr>(exists_out_anchors.begin(), exists_out_anchors.end());
  911. for (const auto &peer_out_anchor : peer_out_anchors) {
  912. if (peer_out_anchor != nullptr) {
  913. if (exists_out_anchors_set.count(peer_out_anchor) > 0) {
  914. continue;
  915. }
  916. auto ret = GraphUtils::AddEdge(peer_out_anchor, new_in_control_anchor);
  917. if (ret != GRAPH_SUCCESS) {
  918. GELOGE(GRAPH_FAILED, "Add edge failed");
  919. return GRAPH_FAILED;
  920. }
  921. } else {
  922. GELOGW("peer outanchor is nullptr");
  923. continue;
  924. }
  925. }
  926. auto old_out_control_anchor = old_node->GetOutControlAnchor();
  927. GE_CHECK_NOTNULL(old_out_control_anchor);
  928. auto peer_in_anchors = old_out_control_anchor->GetPeerAnchors();
  929. auto new_out_control_anchor = new_node->GetOutControlAnchor();
  930. auto exists_in_anchors = new_out_control_anchor->GetPeerAnchors();
  931. auto exists_in_anchors_set = std::set<AnchorPtr>(exists_in_anchors.begin(), exists_in_anchors.end());
  932. GE_CHECK_NOTNULL(new_out_control_anchor);
  933. for (const auto &peer_in_anchor : peer_in_anchors) {
  934. if (peer_in_anchor != nullptr) {
  935. if (exists_in_anchors_set.count(peer_in_anchor) > 0) {
  936. continue;
  937. }
  938. auto ret = GraphUtils::AddEdge(new_out_control_anchor, peer_in_anchor);
  939. if (ret != GRAPH_SUCCESS) {
  940. GELOGE(GRAPH_FAILED, "Add edge failed");
  941. return GRAPH_FAILED;
  942. }
  943. } else {
  944. GELOGW("Peer inanchor is nullptr");
  945. continue;
  946. }
  947. }
  948. return GRAPH_SUCCESS;
  949. }
  950. } // namespace
  951. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::IsolateNode(const NodePtr &node,
  952. const std::vector<int> &io_map) {
  953. if (node == nullptr) {
  954. GELOGE(GRAPH_PARAM_INVALID, "Failed to isolate node(null)");
  955. return GRAPH_PARAM_INVALID;
  956. }
  957. /// We must get full connections info before re-link data io, because the data
  958. /// edges may be unlinked when relink data io
  959. auto in_nodes_to_out = GetFullConnectIONodes(node);
  960. InNodesToOut data_in_to_out;
  961. auto ret = RelinkDataIO(node, io_map, data_in_to_out);
  962. if (ret != GRAPH_SUCCESS) {
  963. GELOGE(GRAPH_FAILED, "Failed to isolate node %s type %s when relink data IO", node->GetName().c_str(),
  964. node->GetType().c_str());
  965. return ret;
  966. }
  967. ret = RelinkControlNodeIfNeed(node, in_nodes_to_out, data_in_to_out);
  968. if (ret != GRAPH_SUCCESS) {
  969. return ret;
  970. }
  971. NodeUtils::UnlinkAll(*node);
  972. return GRAPH_SUCCESS;
  973. }
  974. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus
  975. GraphUtils::IsolateNode(const NodePtr &node, const std::initializer_list<int> &io_map) {
  976. return IsolateNode(node, std::vector<int>(io_map));
  977. }
  978. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::IsolateNodeOneIO(const NodePtr &node) {
  979. if (node == nullptr) {
  980. GELOGE(GRAPH_PARAM_INVALID, "incorrect parameter. node is invalid");
  981. return GRAPH_PARAM_INVALID;
  982. }
  983. if (node->GetAllInDataAnchorsSize() != 1) {
  984. return GRAPH_PARAM_INVALID;
  985. }
  986. if (node->GetAllOutDataAnchorsSize() != 1) {
  987. return GRAPH_PARAM_INVALID;
  988. }
  989. return IsolateNode(node, {0});
  990. }
  991. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus
  992. GraphUtils::ReplaceNodeAnchors(const NodePtr &new_node, const NodePtr &old_node, const std::vector<int> &inputs_map,
  993. const std::vector<int> &outputs_map) {
  994. if ((new_node == nullptr) || (old_node == nullptr)) {
  995. GELOGE(GRAPH_FAILED, "Parameter is nullptr");
  996. return GRAPH_PARAM_INVALID;
  997. }
  998. auto ret = ReplaceNodeDataAnchors(new_node, old_node, inputs_map, outputs_map);
  999. if (ret != GRAPH_SUCCESS) {
  1000. // The error log was printed in `ReplaceNodeDataAnchors`
  1001. return GRAPH_FAILED;
  1002. }
  1003. ret = ReplaceControlAnchors(new_node, old_node);
  1004. if (ret != GRAPH_SUCCESS) {
  1005. GELOGE(GRAPH_FAILED,
  1006. "Failed to replace control anchors when replace node from old node %s type %s to new node %s type %s",
  1007. old_node->GetName().c_str(), old_node->GetType().c_str(), new_node->GetName().c_str(),
  1008. new_node->GetType().c_str());
  1009. return GRAPH_FAILED;
  1010. }
  1011. return GRAPH_SUCCESS;
  1012. }
  1013. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::ReplaceNodeAnchors(
  1014. const NodePtr &new_node, const NodePtr &old_node, const std::initializer_list<int> inputs_map,
  1015. const std::initializer_list<int> outputs_map) {
  1016. return ReplaceNodeAnchors(new_node, old_node, std::vector<int>(inputs_map), std::vector<int>(outputs_map));
  1017. }
  1018. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus
  1019. GraphUtils::ReplaceNodeDataAnchors(const NodePtr &new_node, const NodePtr &old_node,
  1020. std::initializer_list<int> inputs_map, std::initializer_list<int> outputs_map) {
  1021. return ReplaceNodeDataAnchors(new_node, old_node, std::vector<int>(inputs_map), std::vector<int>(outputs_map));
  1022. }
  1023. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus
  1024. GraphUtils::ReplaceNodeDataAnchors(const NodePtr &new_node, const NodePtr &old_node, const std::vector<int> &inputs_map,
  1025. const std::vector<int> &outputs_map) {
  1026. if (new_node == nullptr || old_node == nullptr) {
  1027. GELOGE(GRAPH_FAILED, "Parameter is nullptr");
  1028. return GRAPH_PARAM_INVALID;
  1029. }
  1030. auto ret = ReplaceOutDataAnchors(new_node->GetAllOutDataAnchors(), old_node->GetAllOutDataAnchors(), outputs_map);
  1031. if (ret != GRAPH_SUCCESS) {
  1032. GELOGE(GRAPH_FAILED,
  1033. "Failed to replace out data anchors when replace node from old node %s type %s to new node %s type %s",
  1034. old_node->GetName().c_str(), old_node->GetType().c_str(), new_node->GetName().c_str(),
  1035. new_node->GetType().c_str());
  1036. return GRAPH_FAILED;
  1037. }
  1038. ret = ReplaceInDataAnchors(new_node->GetAllInDataAnchors(), old_node->GetAllInDataAnchors(), inputs_map);
  1039. if (ret != GRAPH_SUCCESS) {
  1040. GELOGE(GRAPH_FAILED,
  1041. "Failed to replace in data anchors when replace node from old node %s type %s to new node %s type %s",
  1042. old_node->GetName().c_str(), old_node->GetType().c_str(), new_node->GetName().c_str(),
  1043. new_node->GetType().c_str());
  1044. return GRAPH_FAILED;
  1045. }
  1046. return GRAPH_SUCCESS;
  1047. }
  1048. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::CopyInCtrlEdges(const NodePtr &src_node,
  1049. NodePtr &dst_node) {
  1050. if ((src_node == nullptr) || (dst_node == nullptr)) {
  1051. GELOGE(GRAPH_FAILED, "Parameter is nullptr");
  1052. return GRAPH_PARAM_INVALID;
  1053. }
  1054. auto src_ctrl_in_nodes = src_node->GetInControlNodes();
  1055. if (src_ctrl_in_nodes.empty()) {
  1056. return GRAPH_SUCCESS;
  1057. }
  1058. std::unordered_set<NodePtr> exist_in_ctrl_nodes_set;
  1059. auto exist_in_ctrl_nodes = dst_node->GetInControlNodes();
  1060. if (!exist_in_ctrl_nodes.empty()) {
  1061. exist_in_ctrl_nodes_set.insert(exist_in_ctrl_nodes.begin(), exist_in_ctrl_nodes.end());
  1062. }
  1063. auto dst_ctrl = dst_node->GetInControlAnchor();
  1064. for (const auto &in_node : src_ctrl_in_nodes) {
  1065. if (exist_in_ctrl_nodes_set.count(in_node) > 0) {
  1066. continue;
  1067. }
  1068. auto ret = GraphUtils::AddEdge(in_node->GetOutControlAnchor(), dst_ctrl);
  1069. if (ret != GRAPH_SUCCESS) {
  1070. GELOGE(GRAPH_FAILED, "Failed to add control edge from %s to %s when copy control dependencies from %s to %s",
  1071. in_node->GetName().c_str(), dst_node->GetName().c_str(), src_node->GetName().c_str(),
  1072. dst_node->GetName().c_str());
  1073. return ret;
  1074. }
  1075. }
  1076. return GRAPH_SUCCESS;
  1077. }
  1078. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::MoveInCtrlEdges(const NodePtr &src_node,
  1079. NodePtr &dst_node) {
  1080. if (src_node == nullptr || dst_node == nullptr) {
  1081. GELOGE(GRAPH_FAILED, "Parameter is nullptr");
  1082. return GRAPH_FAILED;
  1083. }
  1084. auto ret = CopyInCtrlEdges(src_node, dst_node);
  1085. if (ret != GRAPH_SUCCESS) {
  1086. GELOGE(GRAPH_FAILED, "Copy in ctrl edges failed");
  1087. return ret;
  1088. }
  1089. GE_CHECK_NOTNULL(src_node->GetInControlAnchor());
  1090. src_node->GetInControlAnchor()->UnlinkAll();
  1091. return GRAPH_SUCCESS;
  1092. }
  1093. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::CopyOutCtrlEdges(const NodePtr &src_node,
  1094. NodePtr &dst_node) {
  1095. if (src_node == nullptr || dst_node == nullptr) {
  1096. GELOGE(GRAPH_FAILED, "Parameter is nullptr");
  1097. return GRAPH_FAILED;
  1098. }
  1099. auto out_ctrl_nodes = src_node->GetOutControlNodes();
  1100. if (out_ctrl_nodes.empty()) {
  1101. return GRAPH_SUCCESS;
  1102. }
  1103. std::unordered_set<Node *> exists_out_ctrl_nodes_set;
  1104. for (const auto &node : dst_node->GetOutControlNodes()) {
  1105. exists_out_ctrl_nodes_set.insert(node.get());
  1106. }
  1107. auto dst_out_ctrl = dst_node->GetOutControlAnchor();
  1108. for (const auto &node : out_ctrl_nodes) {
  1109. if (exists_out_ctrl_nodes_set.count(node.get()) > 0) {
  1110. continue;
  1111. }
  1112. auto ret = GraphUtils::AddEdge(dst_out_ctrl, node->GetInControlAnchor());
  1113. if (ret != GRAPH_SUCCESS) {
  1114. GELOGE(GRAPH_FAILED, "Failed to add control edge from %s to %s when copy control dependencies from %s to %s",
  1115. dst_node->GetName().c_str(), node->GetName().c_str(), src_node->GetName().c_str(),
  1116. dst_node->GetName().c_str());
  1117. return ret;
  1118. }
  1119. }
  1120. return GRAPH_SUCCESS;
  1121. }
  1122. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::MoveOutCtrlEdges(NodePtr &src_node,
  1123. NodePtr &dst_node) {
  1124. if (src_node == nullptr || dst_node == nullptr) {
  1125. GELOGE(GRAPH_FAILED, "Parameter is nullptr");
  1126. return GRAPH_FAILED;
  1127. }
  1128. auto ret = CopyOutCtrlEdges(src_node, dst_node);
  1129. if (ret != GRAPH_SUCCESS) {
  1130. GELOGE(GRAPH_FAILED, "Copyout ctrl edges failed");
  1131. return ret;
  1132. }
  1133. GE_CHECK_NOTNULL(src_node->GetOutControlAnchor());
  1134. src_node->GetOutControlAnchor()->UnlinkAll();
  1135. return GRAPH_SUCCESS;
  1136. }
  1137. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::AppendInputNode(const ComputeGraphPtr &graph,
  1138. const NodePtr &node) {
  1139. if (graph->AddInputNode(node) == nullptr) {
  1140. GELOGE(GRAPH_FAILED, "Copyout ctrl edges failed");
  1141. return GRAPH_FAILED;
  1142. }
  1143. graph->SetInputSize(graph->GetInputSize() + 1);
  1144. graph->inputs_order_.emplace_back(node->GetName());
  1145. return GRAPH_SUCCESS;
  1146. }
  1147. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY ComputeGraphPtr GraphUtils::FindRootGraph(ComputeGraphPtr graph) {
  1148. ComputeGraphPtr result = nullptr;
  1149. while (graph != nullptr) {
  1150. result = std::move(graph);
  1151. graph = result->GetParentGraph();
  1152. }
  1153. return result;
  1154. }
  1155. ///
  1156. /// @brief Add node to graph
  1157. /// @param [in] op_desc
  1158. /// @return ComputeGraphBuilder
  1159. ///
  1160. ComputeGraphBuilder &ComputeGraphBuilder::AddNode(const OpDescPtr &op_desc) {
  1161. nodes_.emplace_back(op_desc);
  1162. return *this;
  1163. }
  1164. ///
  1165. /// @brief Add data-link among nodes in graph
  1166. /// @param [in] src_name
  1167. /// @param [in] out_anchor_ind
  1168. /// @param [in] dst_name
  1169. /// @param [in] in_anchor_ind
  1170. /// @return ComputeGraphBuilder
  1171. ///
  1172. ComputeGraphBuilder &ComputeGraphBuilder::AddDataLink(const std::string &src_name, uint32_t out_anchor_ind,
  1173. const std::string &dst_name, uint32_t in_anchor_ind) {
  1174. data_links_.emplace_back(
  1175. std::make_pair(std::make_pair(src_name, out_anchor_ind), std::make_pair(dst_name, in_anchor_ind)));
  1176. return *this;
  1177. }
  1178. ///
  1179. /// @brief Add ctrl-link among nodes in graph
  1180. /// @param [in] src_name
  1181. /// @param [in] dst_name
  1182. /// @return ComputeGraphBuilder
  1183. ///
  1184. ComputeGraphBuilder &ComputeGraphBuilder::AddControlLink(const std::string &src_name, const std::string &dst_name) {
  1185. ctrl_links_.emplace_back(std::make_pair(src_name, dst_name));
  1186. return *this;
  1187. }
  1188. ///
  1189. /// @brief Build nodes
  1190. /// @param [out] error_code
  1191. /// @param [out] error_msg
  1192. /// @return void
  1193. ///
  1194. void ComputeGraphBuilder::BuildNodes(graphStatus &error_code, std::string &error_msg) {
  1195. if (owner_graph_ == nullptr) {
  1196. error_code = GRAPH_FAILED;
  1197. error_msg = "graph is NULL.";
  1198. return;
  1199. }
  1200. std::string node_name;
  1201. for (auto &op_desc : nodes_) {
  1202. if (op_desc == nullptr) {
  1203. error_code = GRAPH_FAILED;
  1204. error_msg = "op_desc is NULL.";
  1205. return;
  1206. }
  1207. node_name = op_desc->GetName();
  1208. NodePtr node = owner_graph_->AddNode(op_desc);
  1209. if (node == nullptr) {
  1210. error_code = GRAPH_FAILED;
  1211. error_msg = "Add node " + node_name + " failed.";
  1212. return;
  1213. }
  1214. GELOGD("Add node name:%s, type:%s.", node_name.c_str(), op_desc->GetType().c_str());
  1215. node_names_[node_name] = node;
  1216. }
  1217. GELOGD("BuildNodes succ.");
  1218. }
  1219. ///
  1220. /// @brief Build data-links
  1221. /// @param [out] error_code
  1222. /// @param [out] error_msg
  1223. /// @return void
  1224. ///
  1225. void ComputeGraphBuilder::BuildDataLinks(graphStatus &error_code, std::string &error_msg) {
  1226. for (auto &pair : data_links_) {
  1227. std::string src_name = pair.first.first;
  1228. uint32_t out_ind = pair.first.second;
  1229. std::string dst_name = pair.second.first;
  1230. uint32_t in_ind = pair.second.second;
  1231. std::string log_msg = "Add data-edge ";
  1232. log_msg.append(src_name)
  1233. .append(":")
  1234. .append(std::to_string(out_ind))
  1235. .append("->")
  1236. .append(dst_name)
  1237. .append(":")
  1238. .append(std::to_string(in_ind));
  1239. auto src_iter = node_names_.find(src_name);
  1240. auto dst_iter = node_names_.find(dst_name);
  1241. if ((src_iter == node_names_.end()) || (dst_iter == node_names_.end())) {
  1242. error_code = GRAPH_FAILED;
  1243. error_msg = log_msg + " failed: node not exist in graph.";
  1244. return;
  1245. }
  1246. NodePtr src_node = node_names_[src_name];
  1247. NodePtr dst_node = node_names_[dst_name];
  1248. if ((src_node == nullptr) || (dst_node == nullptr)) {
  1249. error_code = GRAPH_FAILED;
  1250. error_msg = log_msg + " failed: node is NULL.";
  1251. return;
  1252. }
  1253. if (GraphUtils::AddEdge(src_node->GetOutDataAnchor(out_ind), dst_node->GetInDataAnchor(in_ind)) != GRAPH_SUCCESS) {
  1254. error_code = GRAPH_FAILED;
  1255. error_msg = log_msg + " failed.";
  1256. return;
  1257. }
  1258. GELOGD("%s succ.", log_msg.c_str());
  1259. }
  1260. GELOGD("BuildDataLinks succ.");
  1261. }
  1262. ///
  1263. /// @brief Build ctrl-links
  1264. /// @param [out] error_code
  1265. /// @param [out] error_msg
  1266. /// @return void
  1267. ///
  1268. void ComputeGraphBuilder::BuildCtrlLinks(graphStatus &error_code, std::string &error_msg) {
  1269. for (auto &pair : ctrl_links_) {
  1270. std::string src_name = pair.first;
  1271. std::string dst_name = pair.second;
  1272. std::string log_msg = "Add ctrl-edge ";
  1273. log_msg.append(src_name).append("->").append(dst_name);
  1274. auto src_iter = node_names_.find(src_name);
  1275. auto dst_iter = node_names_.find(dst_name);
  1276. if ((src_iter == node_names_.end()) || (dst_iter == node_names_.end())) {
  1277. error_code = GRAPH_FAILED;
  1278. error_msg = log_msg + " failed: node not exist in graph.";
  1279. return;
  1280. }
  1281. NodePtr src_node = node_names_[src_name];
  1282. NodePtr dst_node = node_names_[dst_name];
  1283. if ((src_node == nullptr) || (dst_node == nullptr)) {
  1284. error_code = GRAPH_FAILED;
  1285. error_msg = log_msg + " failed: node is NULL.";
  1286. return;
  1287. }
  1288. if (GraphUtils::AddEdge(src_node->GetOutControlAnchor(), dst_node->GetInControlAnchor()) != GRAPH_SUCCESS) {
  1289. error_code = GRAPH_FAILED;
  1290. error_msg = log_msg + " failed.";
  1291. return;
  1292. }
  1293. GELOGD("%s succ.", log_msg.c_str());
  1294. }
  1295. GELOGD("BuildCtrlLinks succ.");
  1296. }
  1297. /// @brief Get node with name
  1298. /// @param [in] name
  1299. /// @return NodePtr
  1300. ///
  1301. NodePtr ComputeGraphBuilder::GetNode(const std::string &name) {
  1302. auto iter = node_names_.find(name);
  1303. if (iter == node_names_.end()) {
  1304. GE_LOGE("node %s not exist.", name.c_str());
  1305. return nullptr;
  1306. }
  1307. return iter->second;
  1308. }
  1309. ///
  1310. /// @brief Add node to graph
  1311. /// @param [in] op_desc
  1312. /// @return CompleteGraphBuilder
  1313. ///
  1314. CompleteGraphBuilder &CompleteGraphBuilder::AddNode(const OpDescPtr &op_desc) {
  1315. ComputeGraphBuilder::AddNode(op_desc);
  1316. return *this;
  1317. }
  1318. ///
  1319. /// @brief Add data-link among nodes in graph
  1320. /// @param [in] src_name
  1321. /// @param [in] out_anchor_ind
  1322. /// @param [in] dst_name
  1323. /// @param [in] in_anchor_ind
  1324. /// @return CompleteGraphBuilder
  1325. ///
  1326. CompleteGraphBuilder &CompleteGraphBuilder::AddDataLink(const std::string &src_name, uint32_t out_anchor_ind,
  1327. const std::string &dst_name, uint32_t in_anchor_ind) {
  1328. ComputeGraphBuilder::AddDataLink(src_name, out_anchor_ind, dst_name, in_anchor_ind);
  1329. return *this;
  1330. }
  1331. ///
  1332. /// @brief Add ctrl-link among nodes in graph
  1333. /// @param [in] src_name
  1334. /// @param [in] dst_name
  1335. /// @return CompleteGraphBuilder
  1336. ///
  1337. CompleteGraphBuilder &CompleteGraphBuilder::AddControlLink(const std::string &src_name, const std::string &dst_name) {
  1338. ComputeGraphBuilder::AddControlLink(src_name, dst_name);
  1339. return *this;
  1340. }
  1341. ///
  1342. /// @brief Set index_th input anchor for graph
  1343. /// @param [in] index
  1344. /// @param [in] node_names
  1345. /// @param [in] anchor_inds
  1346. /// @return CompleteGraphBuilder
  1347. ///
  1348. CompleteGraphBuilder &CompleteGraphBuilder::SetInput(uint32_t index, const std::vector<std::string> &node_names,
  1349. const std::vector<uint32_t> &anchor_inds) {
  1350. graph_inputs_[index] = std::make_pair(node_names, anchor_inds);
  1351. return *this;
  1352. }
  1353. ///
  1354. /// @brief Set index_th input of graph as useless
  1355. /// @param [in] index
  1356. /// @return CompleteGraphBuilder
  1357. ///
  1358. CompleteGraphBuilder &CompleteGraphBuilder::SetUselessInput(uint32_t index) {
  1359. graph_inputs_[index] = std::make_pair(std::vector<std::string>(), std::vector<uint32_t>());
  1360. return *this;
  1361. }
  1362. ///
  1363. /// @brief Add output anchor for graph
  1364. /// @param [in] owner_node_name
  1365. /// @param [in] anchor_ind
  1366. /// @return CompleteGraphBuilder
  1367. ///
  1368. CompleteGraphBuilder &CompleteGraphBuilder::AddOutput(const std::string &owner_node_name, uint32_t anchor_ind) {
  1369. graph_outputs_.emplace_back(std::make_pair(owner_node_name, anchor_ind));
  1370. return *this;
  1371. }
  1372. ///
  1373. /// @brief Set parent-node of graph
  1374. /// @param [in] parent_node
  1375. /// @return CompleteGraphBuilder
  1376. ///
  1377. CompleteGraphBuilder &CompleteGraphBuilder::SetParentNode(const NodePtr &parent_node) {
  1378. parent_node_ = parent_node;
  1379. return *this;
  1380. }
  1381. ///
  1382. /// @brief Set mapping-relation of parent-node in_anchor_ind & Data-node
  1383. /// @param [in] input_mapping: index_of_graph_input -> in_anchor_index_of_parent_node
  1384. /// @return CompleteGraphBuilder
  1385. ///
  1386. CompleteGraphBuilder &CompleteGraphBuilder::SetInputMapping(const std::map<uint32_t, uint32_t> &input_mapping) {
  1387. for (auto &item : input_mapping) {
  1388. input_mapping_[item.first] = item.second;
  1389. }
  1390. return *this;
  1391. }
  1392. ///
  1393. /// @brief Set mapping-relation of parent-node out_anchor_ind & NetOutput-node out_anchor_ind
  1394. /// @param [in] output_mapping: index_of_graph_output -> out_anchor_index_of_parent_node
  1395. /// @return CompleteGraphBuilder
  1396. ///
  1397. CompleteGraphBuilder &CompleteGraphBuilder::SetOutputMapping(const std::map<uint32_t, uint32_t> &output_mapping) {
  1398. for (auto &item : output_mapping) {
  1399. output_mapping_[item.first] = item.second;
  1400. }
  1401. return *this;
  1402. }
  1403. ///
  1404. /// @brief Build graph
  1405. /// @param [out] error_code
  1406. /// @param [out] error_msg
  1407. /// @return ComputeGraphPtr
  1408. ///
  1409. ComputeGraphPtr CompleteGraphBuilder::Build(graphStatus &error_code, std::string &error_msg) {
  1410. owner_graph_ = shared_ptr<ComputeGraph>(new (std::nothrow) ComputeGraph(name_));
  1411. if (owner_graph_ == nullptr) {
  1412. error_code = GRAPH_FAILED;
  1413. error_msg = "graph is NULL.";
  1414. return nullptr;
  1415. }
  1416. owner_graph_->SetParentNode(parent_node_);
  1417. BuildNodes(error_code, error_msg);
  1418. if (error_code != GRAPH_SUCCESS) {
  1419. return nullptr;
  1420. }
  1421. BuildDataLinks(error_code, error_msg);
  1422. if (error_code != GRAPH_SUCCESS) {
  1423. return nullptr;
  1424. }
  1425. BuildCtrlLinks(error_code, error_msg);
  1426. if (error_code != GRAPH_SUCCESS) {
  1427. return nullptr;
  1428. }
  1429. BuildInputs(error_code, error_msg);
  1430. if (error_code != GRAPH_SUCCESS) {
  1431. return nullptr;
  1432. }
  1433. BuildOutputs(error_code, error_msg);
  1434. if (error_code != GRAPH_SUCCESS) {
  1435. return nullptr;
  1436. }
  1437. if (AddNetOutputNode(error_code, error_msg) == nullptr) {
  1438. return nullptr;
  1439. }
  1440. return owner_graph_;
  1441. }
  1442. ///
  1443. /// @brief Build inputs
  1444. /// @param [out] error_code
  1445. /// @param [out] error_msg
  1446. /// @return void
  1447. ///
  1448. void CompleteGraphBuilder::BuildInputs(graphStatus &error_code, std::string &error_msg) {
  1449. for (auto &input : graph_inputs_) {
  1450. NodePtr data_node = AddDateNode(input.first, error_code, error_msg);
  1451. if (data_node == nullptr) {
  1452. error_code = GRAPH_FAILED;
  1453. error_msg = "BuildInputs failed: add node Data:" + std::to_string(input.first) + +" failed.";
  1454. return;
  1455. }
  1456. if (owner_graph_->AddInputNode(data_node) == nullptr) {
  1457. error_code = GRAPH_FAILED;
  1458. error_msg = "BuildInputs failed: add input node Data:" + std::to_string(input.first) + +" failed.";
  1459. return;
  1460. }
  1461. // useless input
  1462. std::vector<std::string> input_names = input.second.first;
  1463. std::vector<uint32_t> anchor_indes = input.second.second;
  1464. if (input_names.size() != anchor_indes.size()) {
  1465. error_code = GRAPH_FAILED;
  1466. error_msg = "BuildInputs failed: num of input_names and indexs not equal.";
  1467. return;
  1468. }
  1469. if (input_names.empty()) {
  1470. continue;
  1471. }
  1472. size_t input_num = input_names.size();
  1473. for (size_t i = 0; i < input_num; i++) {
  1474. std::string input_name = input_names[i];
  1475. uint32_t ind = anchor_indes[i];
  1476. auto iter = node_names_.find(input_name);
  1477. if (iter == node_names_.end()) {
  1478. error_code = GRAPH_FAILED;
  1479. error_msg = "BuildInputs failed: node " + input_name + " not exist in graph.";
  1480. return;
  1481. }
  1482. NodePtr in_node = node_names_[input_name];
  1483. if (in_node == nullptr) {
  1484. error_code = GRAPH_FAILED;
  1485. error_msg = "BuildInputs failed: node " + input_name + " is NULL.";
  1486. return;
  1487. }
  1488. if (GraphUtils::AddEdge(data_node->GetOutDataAnchor(0), in_node->GetInDataAnchor(ind)) != GRAPH_SUCCESS) {
  1489. error_code = GRAPH_FAILED;
  1490. error_msg = "BuildInputs failed: add data-edge Data:" + std::to_string(input.first) + ":0->" + input_name +
  1491. ":" + std::to_string(ind) + " failed.";
  1492. return;
  1493. }
  1494. }
  1495. GELOGD("BuildInputs : Add %u input succ.", input.first);
  1496. }
  1497. GELOGD("BuildInputs succ.");
  1498. }
  1499. ///
  1500. /// @brief Add data node
  1501. /// @param [in] index
  1502. /// @param [out] error_code
  1503. /// @param [out] error_msg
  1504. /// @return void
  1505. ///
  1506. NodePtr CompleteGraphBuilder::AddDateNode(uint32_t index, graphStatus &error_code, std::string &error_msg) {
  1507. std::string data_name = "Data_" + std::to_string(index);
  1508. OpDescBuilder op_desc_builder(data_name, "Data");
  1509. OpDescPtr op_desc = op_desc_builder.AddInput("x").AddOutput("y").Build();
  1510. if (op_desc == nullptr) {
  1511. error_code = GRAPH_FAILED;
  1512. error_msg = "BuildInputs failed: create op_desc " + data_name + " failed.";
  1513. return nullptr;
  1514. }
  1515. auto index_iter = input_mapping_.find(index);
  1516. if (index_iter != input_mapping_.end()) {
  1517. if (!ge::AttrUtils::SetInt(op_desc, ATTR_NAME_PARENT_NODE_INDEX, index_iter->second)) {
  1518. error_code = GRAPH_FAILED;
  1519. error_msg = "BuildInputs failed: set attr ATTR_NAME_PARENT_NODE_INDEX for " + data_name + " failed.";
  1520. return nullptr;
  1521. }
  1522. }
  1523. NodePtr data_node = owner_graph_->AddNode(op_desc);
  1524. if (data_node == nullptr) {
  1525. error_code = GRAPH_FAILED;
  1526. error_msg = "BuildInputs failed: add node " + data_name + " failed.";
  1527. return nullptr;
  1528. }
  1529. return data_node;
  1530. }
  1531. ///
  1532. /// @brief Build outputs
  1533. /// @param [out] error_code
  1534. /// @param [out] error_msg
  1535. /// @return void
  1536. ///
  1537. void CompleteGraphBuilder::BuildOutputs(graphStatus &error_code, std::string &error_msg) {
  1538. std::map<std::string, std::vector<int32_t>> out_nodes_map;
  1539. std::vector<std::pair<NodePtr, int32_t>> out_nodes_info;
  1540. for (auto &pair : graph_outputs_) {
  1541. std::string output = pair.first;
  1542. int32_t ind = pair.second;
  1543. auto out_iter = node_names_.find(output);
  1544. if (out_iter == node_names_.end()) {
  1545. error_code = GRAPH_FAILED;
  1546. error_msg = "BuildOutputs failed: node " + output + " not exist in graph.";
  1547. return;
  1548. }
  1549. NodePtr out_node = node_names_[output];
  1550. if (out_node == nullptr) {
  1551. error_code = GRAPH_FAILED;
  1552. error_msg = "BuildOutputs failed: node " + output + " is NULL.";
  1553. return;
  1554. }
  1555. OutDataAnchorPtr out_anchor = out_node->GetOutDataAnchor(ind);
  1556. if (out_anchor == nullptr) {
  1557. error_code = GRAPH_FAILED;
  1558. error_msg = "BuildOutputs failed: anchor " + output + ":" + std::to_string(ind) + " is NULL.";
  1559. return;
  1560. }
  1561. auto iter = out_nodes_map.find(output);
  1562. if (iter == out_nodes_map.end()) {
  1563. std::vector<int32_t> vec = {ind};
  1564. out_nodes_map[output] = vec;
  1565. } else {
  1566. out_nodes_map[output].emplace_back(ind);
  1567. }
  1568. out_nodes_info.emplace_back(std::make_pair(out_node, ind));
  1569. GELOGD("BuildOutputs : AddOutputAnchor %s:%u succ.", output.c_str(), ind);
  1570. }
  1571. owner_graph_->SetGraphOutNodes(out_nodes_map);
  1572. owner_graph_->SetGraphOutNodesInfo(out_nodes_info);
  1573. GELOGD("BuildOutputs succ.");
  1574. }
  1575. ///
  1576. /// @brief Add NetOutput node
  1577. /// @param [out] error_code
  1578. /// @param [out] error_msg
  1579. /// @return NodePtr
  1580. ///
  1581. NodePtr CompleteGraphBuilder::AddNetOutputNode(graphStatus &error_code, std::string &error_msg) {
  1582. std::string log_msg = "AddNetOutputNode name:" + std::string(kNodeNameNetOutput) + ", type:" + NETOUTPUT;
  1583. OpDescPtr net_output_desc = shared_ptr<OpDesc>(new (std::nothrow) OpDesc(kNodeNameNetOutput, NETOUTPUT));
  1584. if (net_output_desc == nullptr) {
  1585. error_code = GRAPH_FAILED;
  1586. error_msg = log_msg + " failed: op_desc is NULL.";
  1587. return nullptr;
  1588. }
  1589. std::vector<std::pair<NodePtr, int32_t>> out_nodes_info = owner_graph_->GetGraphOutNodesInfo();
  1590. error_code = BuildInOutForNetOutput(out_nodes_info, net_output_desc);
  1591. if (error_code != GRAPH_SUCCESS) {
  1592. error_msg = log_msg + " failed: add input/output tensor failed.";
  1593. return nullptr;
  1594. }
  1595. NodePtr net_output_node = owner_graph_->AddNode(net_output_desc);
  1596. if (net_output_node == nullptr) {
  1597. error_code = GRAPH_FAILED;
  1598. error_msg = log_msg + " failed: add node failed.";
  1599. return nullptr;
  1600. }
  1601. error_code = AddEdgeForNetOutput(out_nodes_info, net_output_node);
  1602. if (error_code != GRAPH_SUCCESS) {
  1603. error_msg = log_msg + " failed: link edge failed.";
  1604. return nullptr;
  1605. }
  1606. GELOGD("%s succ.", log_msg.c_str());
  1607. return net_output_node;
  1608. }
  1609. ///
  1610. /// @brief Add input/output tensor for NetOutput node
  1611. /// @param [in] out_nodes_info
  1612. /// @param [out] net_output_desc
  1613. /// @return graphStatus
  1614. ///
  1615. graphStatus CompleteGraphBuilder::BuildInOutForNetOutput(const std::vector<std::pair<NodePtr, int32_t>> &out_nodes_info,
  1616. OpDescPtr &net_output_desc) {
  1617. size_t output_num = out_nodes_info.size();
  1618. for (size_t i = 0; i < output_num; i++) {
  1619. NodePtr src_node = out_nodes_info[i].first;
  1620. uint32_t src_index = out_nodes_info[i].second;
  1621. if ((src_node == nullptr) || (src_node->GetOpDesc() == nullptr)) {
  1622. GE_LOGE("AddInOutForNetOutputOp failed: src_node is NULL.");
  1623. return GRAPH_FAILED;
  1624. }
  1625. ge::GeTensorDesc in_desc = src_node->GetOpDesc()->GetOutputDesc(src_index);
  1626. auto iter = output_mapping_.find(i);
  1627. if (iter != output_mapping_.end()) {
  1628. if (!ge::AttrUtils::SetInt(in_desc, ATTR_NAME_PARENT_NODE_INDEX, iter->second)) {
  1629. GE_LOGE("AddInOutForNetOutputOp failed: set attr ATTR_NAME_PARENT_NODE_INDEX failed.");
  1630. return GRAPH_FAILED;
  1631. }
  1632. }
  1633. if (net_output_desc->AddInputDesc(in_desc) != SUCCESS) {
  1634. GE_LOGE("AddInOutForNetOutputOp failed: add input_desc failed.");
  1635. return GRAPH_FAILED;
  1636. }
  1637. ge::GeTensorDesc out_desc = src_node->GetOpDesc()->GetOutputDesc(src_index);
  1638. TensorUtils::SetOutputTensor(out_desc, true);
  1639. if (net_output_desc->AddOutputDesc(out_desc) != SUCCESS) {
  1640. GE_LOGE("AddInOutForNetOutputOp failed: add output_desc failed.");
  1641. return GRAPH_FAILED;
  1642. }
  1643. }
  1644. GELOGD("Add input/output tensor for NetOutput node succ.");
  1645. return GRAPH_SUCCESS;
  1646. }
  1647. ///
  1648. /// @brief Add edge for NetOutput node
  1649. /// @param [in] out_nodes_info
  1650. /// @param [out] net_output_node
  1651. /// @return graphStatus
  1652. ///
  1653. graphStatus CompleteGraphBuilder::AddEdgeForNetOutput(const std::vector<std::pair<NodePtr, int32_t>> &out_nodes_info,
  1654. const NodePtr &net_output_node) {
  1655. if (net_output_node == nullptr) {
  1656. GE_LOGE("AddEdgeForNetOutputOp failed: NetOutput is NULL.");
  1657. return GRAPH_FAILED;
  1658. }
  1659. size_t out_num = out_nodes_info.size();
  1660. for (size_t i = 0; i < out_num; i++) {
  1661. NodePtr src_node = out_nodes_info[i].first;
  1662. uint32_t ind = out_nodes_info[i].second;
  1663. if (src_node == nullptr) {
  1664. GE_LOGE("AddEdgeForNetOutputOp failed: src_node is NULL.");
  1665. return GRAPH_FAILED;
  1666. }
  1667. if (GraphUtils::AddEdge(src_node->GetOutDataAnchor(ind), net_output_node->GetInDataAnchor(i)) != GRAPH_SUCCESS) {
  1668. GE_LOGE("Add data-edge %s:%u->%s:%zu failed.", src_node->GetName().c_str(), ind,
  1669. net_output_node->GetName().c_str(), i);
  1670. return GRAPH_FAILED;
  1671. }
  1672. }
  1673. std::vector<NodePtr> leaf_nodes;
  1674. for (auto &node : owner_graph_->GetDirectNode()) {
  1675. if (node->GetOutNodes().empty()) {
  1676. leaf_nodes.emplace_back(node);
  1677. }
  1678. }
  1679. for (auto &node : leaf_nodes) {
  1680. if (GraphUtils::AddEdge(node->GetOutControlAnchor(), net_output_node->GetInControlAnchor()) != GRAPH_SUCCESS) {
  1681. GE_LOGE("Add ctrl-edge %s->%s failed.", node->GetName().c_str(), net_output_node->GetName().c_str());
  1682. return GRAPH_FAILED;
  1683. }
  1684. }
  1685. GELOGD("Add edge for NetOutput node succ.");
  1686. return GRAPH_SUCCESS;
  1687. }
  1688. ///
  1689. /// @brief Add node to graph
  1690. /// @param [in] op_desc
  1691. /// @return PartialGraphBuilder
  1692. ///
  1693. PartialGraphBuilder &PartialGraphBuilder::AddNode(const OpDescPtr &op_desc) {
  1694. ComputeGraphBuilder::AddNode(op_desc);
  1695. return *this;
  1696. }
  1697. ///
  1698. /// @brief Add data-link among nodes in graph
  1699. /// @param [in] src_name
  1700. /// @param [in] out_anchor_ind
  1701. /// @param [in] dst_name
  1702. /// @param [in] in_anchor_ind
  1703. /// @return PartialGraphBuilder
  1704. ///
  1705. PartialGraphBuilder &PartialGraphBuilder::AddDataLink(const std::string &src_name, uint32_t out_anchor_ind,
  1706. const std::string &dst_name, uint32_t in_anchor_ind) {
  1707. ComputeGraphBuilder::AddDataLink(src_name, out_anchor_ind, dst_name, in_anchor_ind);
  1708. return *this;
  1709. }
  1710. ///
  1711. /// @brief Add ctrl-link among nodes in graph
  1712. /// @param [in] src_name
  1713. /// @param [in] dst_name
  1714. /// @return PartialGraphBuilder
  1715. ///
  1716. PartialGraphBuilder &PartialGraphBuilder::AddControlLink(const std::string &src_name, const std::string &dst_name) {
  1717. ComputeGraphBuilder::AddControlLink(src_name, dst_name);
  1718. return *this;
  1719. }
  1720. ///
  1721. /// @brief Set owner graph
  1722. /// @param [in] graph
  1723. /// @return PartialGraphBuilder
  1724. ///
  1725. PartialGraphBuilder &PartialGraphBuilder::SetOwnerGraph(const ComputeGraphPtr &graph) {
  1726. owner_graph_ = graph;
  1727. return *this;
  1728. }
  1729. ///
  1730. /// @brief Add exist node
  1731. /// @param [in] node
  1732. /// @return PartialGraphBuilder
  1733. ///
  1734. PartialGraphBuilder &PartialGraphBuilder::AddExistNode(const NodePtr &node) {
  1735. exist_nodes_.emplace_back(node);
  1736. return *this;
  1737. }
  1738. ///
  1739. /// @brief Build partial graph
  1740. /// @param [out] error_code
  1741. /// @param [out] error_msg
  1742. /// @return ComputeGraphPtr
  1743. ///
  1744. ComputeGraphPtr PartialGraphBuilder::Build(graphStatus &error_code, std::string &error_msg) {
  1745. if (owner_graph_ == nullptr) {
  1746. error_code = GRAPH_FAILED;
  1747. error_msg = "graph is NULL.";
  1748. return nullptr;
  1749. }
  1750. BuildNodes(error_code, error_msg);
  1751. if (error_code != GRAPH_SUCCESS) {
  1752. return nullptr;
  1753. }
  1754. BuildExistNodes(error_code, error_msg);
  1755. if (error_code != GRAPH_SUCCESS) {
  1756. return nullptr;
  1757. }
  1758. BuildDataLinks(error_code, error_msg);
  1759. if (error_code != GRAPH_SUCCESS) {
  1760. return nullptr;
  1761. }
  1762. BuildCtrlLinks(error_code, error_msg);
  1763. if (error_code != GRAPH_SUCCESS) {
  1764. return nullptr;
  1765. }
  1766. return owner_graph_;
  1767. }
  1768. ///
  1769. /// @brief Build exist nodes
  1770. /// @param [out] error_code
  1771. /// @param [out] error_msg
  1772. /// @return void
  1773. ///
  1774. void PartialGraphBuilder::BuildExistNodes(graphStatus &error_code, std::string &error_msg) {
  1775. std::string node_name;
  1776. for (auto &node : exist_nodes_) {
  1777. if (node == nullptr) {
  1778. error_code = GRAPH_FAILED;
  1779. error_msg = "Build exist nodes failed: node is NULL.";
  1780. return;
  1781. }
  1782. node_name = node->GetName();
  1783. if (node->GetOwnerComputeGraph() != owner_graph_) {
  1784. error_code = GRAPH_FAILED;
  1785. error_msg = "Build exist nodes failed: node " + node_name + " not belongs to this graph.";
  1786. return;
  1787. }
  1788. GELOGD("Add exist_node name:%s.", node_name.c_str());
  1789. node_names_[node_name] = node;
  1790. }
  1791. GELOGD("Build exist nodes succ.");
  1792. }
  1793. } // namespace ge

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