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

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