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 104 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
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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767
  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 <atomic>
  30. #include "./ge_context.h"
  31. #include "debug/ge_util.h"
  32. #include "framework/common/debug/ge_log.h"
  33. #include "proto/ge_ir.pb.h"
  34. #include "utils/attr_utils.h"
  35. #include "utils/ge_ir_utils.h"
  36. #include "utils/node_utils.h"
  37. #include "debug/ge_op_types.h"
  38. #include "external/ge/ge_api_types.h"
  39. #include "graph/debug/ge_attr_define.h"
  40. #include "graph/utils/op_desc_utils.h"
  41. #include "graph/utils/tensor_utils.h"
  42. using google::protobuf::io::FileOutputStream;
  43. namespace ge {
  44. enum DumpGraphLevel {
  45. kDumpLevel1 = 1,
  46. kDumpLevel2 = 2,
  47. kDumpLevel3 = 3,
  48. kDumpLevelOther,
  49. };
  50. namespace {
  51. const int32_t kBaseOfIntegerValue = 10;
  52. #ifdef FMK_SUPPORT_DUMP
  53. const char *const kDumpGeGraph = "DUMP_GE_GRAPH";
  54. const int kDumpGraphIndexWidth = 5;
  55. #endif
  56. const char *const kDumpGraphLevel = "DUMP_GRAPH_LEVEL";
  57. const char *const kDumpStrBuild = "Build";
  58. const char *const kDumpStrPartition = "partition";
  59. const char *const kDumpStrOptimizeSubgraph = "OptimizeSubGraph";
  60. const char *const kDumpStrSubgraphFunc = "sub_graph";
  61. const char *const kDumpStrAicpu = "Aicpu";
  62. }; // namespace
  63. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::AddEdge(const OutDataAnchorPtr &src,
  64. const InDataAnchorPtr &dst) {
  65. if ((src != nullptr) && (src->LinkTo(dst) == GRAPH_SUCCESS)) {
  66. return GRAPH_SUCCESS;
  67. }
  68. GELOGE(GRAPH_FAILED, "Add edge Failed.");
  69. return GRAPH_FAILED;
  70. }
  71. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::AddEdge(const AnchorPtr &src,
  72. const AnchorPtr &dst) {
  73. OutDataAnchorPtr src_data = Anchor::DynamicAnchorCast<OutDataAnchor>(src);
  74. InDataAnchorPtr dst_data = Anchor::DynamicAnchorCast<InDataAnchor>(dst);
  75. OutControlAnchorPtr src_control = Anchor::DynamicAnchorCast<OutControlAnchor>(src);
  76. InControlAnchorPtr dst_control = Anchor::DynamicAnchorCast<InControlAnchor>(dst);
  77. if ((src_data != nullptr) && (dst_data != nullptr) && (src_data->LinkTo(dst_data) == GRAPH_SUCCESS)) {
  78. return GRAPH_SUCCESS;
  79. }
  80. if ((src_data != nullptr) && (dst_control != nullptr) && (src_data->LinkTo(dst_control) == GRAPH_SUCCESS)) {
  81. return GRAPH_SUCCESS;
  82. }
  83. if ((src_control != nullptr) && (dst_control != nullptr) && (src_control->LinkTo(dst_control) == GRAPH_SUCCESS)) {
  84. return GRAPH_SUCCESS;
  85. }
  86. if ((src_control != nullptr) && (dst_data != nullptr) && (src_control->LinkTo(dst_data) == GRAPH_SUCCESS)) {
  87. return GRAPH_SUCCESS;
  88. }
  89. GELOGE(GRAPH_FAILED, "Add edge Failed.");
  90. return GRAPH_FAILED;
  91. }
  92. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::AddEdge(const OutDataAnchorPtr &src,
  93. const Format &src_format,
  94. const InDataAnchorPtr &dst,
  95. const Format &dst_format) {
  96. if ((src != nullptr) && (src->LinkTo(dst) == GRAPH_SUCCESS)) {
  97. auto ret = AnchorUtils::SetFormat(src, src_format);
  98. if (ret != GRAPH_SUCCESS) {
  99. GELOGE(GRAPH_FAILED, "Set format failed, format is %d", static_cast<int>(src_format));
  100. return ret;
  101. }
  102. ret = AnchorUtils::SetFormat(dst, dst_format);
  103. if (ret != GRAPH_SUCCESS) {
  104. GELOGE(GRAPH_FAILED, "Set format failed,format is %d", static_cast<int>(dst_format));
  105. return ret;
  106. }
  107. return GRAPH_SUCCESS;
  108. }
  109. GELOGE(GRAPH_FAILED, "Add edge Failed.");
  110. return GRAPH_FAILED;
  111. }
  112. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::AddEdge(const OutControlAnchorPtr &src,
  113. const InControlAnchorPtr &dst) {
  114. if ((src != nullptr) && (src->LinkTo(dst) == GRAPH_SUCCESS)) {
  115. return GRAPH_SUCCESS;
  116. }
  117. GELOGE(GRAPH_FAILED, "Add edge Failed.");
  118. return GRAPH_FAILED;
  119. }
  120. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::AddEdge(const OutDataAnchorPtr &src,
  121. const InControlAnchorPtr &dst) {
  122. if ((src != nullptr) && (src->LinkTo(dst) == GRAPH_SUCCESS)) {
  123. return GRAPH_SUCCESS;
  124. }
  125. GELOGE(GRAPH_FAILED, "Add edge Failed.");
  126. return GRAPH_FAILED;
  127. }
  128. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::RemoveEdge(const OutDataAnchorPtr &src,
  129. const InDataAnchorPtr &dst) {
  130. if ((src != nullptr) && (src->Unlink(dst) == GRAPH_SUCCESS)) {
  131. return GRAPH_SUCCESS;
  132. }
  133. GELOGE(GRAPH_FAILED, "Remove edge Failed.");
  134. return GRAPH_FAILED;
  135. }
  136. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::RemoveEdge(const AnchorPtr &src,
  137. const AnchorPtr &dst) {
  138. if ((src != nullptr) && (src->Unlink(dst) == GRAPH_SUCCESS)) {
  139. return GRAPH_SUCCESS;
  140. }
  141. GELOGE(GRAPH_FAILED, "Remove edge Failed.");
  142. return GRAPH_FAILED;
  143. }
  144. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::RemoveEdge(const OutControlAnchorPtr &src,
  145. const InControlAnchorPtr &dst) {
  146. if ((src != nullptr) && (src->Unlink(dst) == GRAPH_SUCCESS)) {
  147. return GRAPH_SUCCESS;
  148. }
  149. GELOGE(GRAPH_FAILED, "Remove edge Failed.");
  150. return GRAPH_FAILED;
  151. }
  152. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::RemoveEdge(const OutDataAnchorPtr &src,
  153. const InControlAnchorPtr &dst) {
  154. if ((src != nullptr) && (src->Unlink(dst) == GRAPH_SUCCESS)) {
  155. return GRAPH_SUCCESS;
  156. }
  157. GELOGE(GRAPH_FAILED, "Remove edge Failed.");
  158. return GRAPH_FAILED;
  159. }
  160. graphStatus GraphUtils::ReplaceEdgeDst(const OutDataAnchorPtr &src, const InDataAnchorPtr &dst,
  161. const InDataAnchorPtr &new_dst) {
  162. if (RemoveEdge(src, dst) == GRAPH_SUCCESS && AddEdge(src, new_dst) == GRAPH_SUCCESS) {
  163. return GRAPH_SUCCESS;
  164. }
  165. GELOGE(GRAPH_FAILED, "Replace edge dst Failed.");
  166. return GRAPH_FAILED;
  167. }
  168. graphStatus GraphUtils::ReplaceEdgeDst(const OutControlAnchorPtr &src, const InControlAnchorPtr &dst,
  169. const InControlAnchorPtr &new_dst) {
  170. if (RemoveEdge(src, dst) == GRAPH_SUCCESS && AddEdge(src, new_dst) == GRAPH_SUCCESS) {
  171. return GRAPH_SUCCESS;
  172. }
  173. GELOGE(GRAPH_FAILED, "Replace edge dst Failed.");
  174. return GRAPH_FAILED;
  175. }
  176. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::InsertNodeBetweenDataAnchors(
  177. const OutDataAnchorPtr &src, const InDataAnchorPtr &dst, const NodePtr &new_node) {
  178. GE_CHECK_NOTNULL(src);
  179. GE_CHECK_NOTNULL(dst);
  180. GE_CHECK_NOTNULL(new_node);
  181. InDataAnchorPtr node_in_anchor = new_node->GetInDataAnchor(0);
  182. GE_CHK_BOOL_RET_STATUS(node_in_anchor != nullptr, GRAPH_FAILED, "this node has not inDataAnchor");
  183. OutDataAnchorPtr node_out_anchor = new_node->GetOutDataAnchor(0);
  184. GE_CHK_BOOL_RET_STATUS(node_out_anchor != nullptr, GRAPH_FAILED, "this node has not outDataAnchor");
  185. GE_CHK_STATUS_RET(src->ReplacePeer(dst, node_in_anchor, node_out_anchor), "ReplacePeer Failed");
  186. return GRAPH_SUCCESS;
  187. }
  188. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus
  189. GraphUtils::RemoveSubgraphRecursively(const ComputeGraphPtr &compute_graph, const NodePtr &remove_node) {
  190. GE_CHECK_NOTNULL(compute_graph);
  191. if (remove_node == nullptr) {
  192. GELOGE(GRAPH_FAILED, "The node ptr should not be null.");
  193. return GRAPH_FAILED;
  194. }
  195. // Check if this node is belong to this compute graph, maybe a little slow
  196. const auto &all_nodes_in_graph = compute_graph->GetDirectNode();
  197. if (std::find(all_nodes_in_graph.begin(), all_nodes_in_graph.end(), remove_node) == all_nodes_in_graph.end()) {
  198. GELOGE(GRAPH_FAILED, "Can not find node %s in graph %s.", remove_node->GetName().c_str(),
  199. compute_graph->GetName().c_str());
  200. return GRAPH_FAILED;
  201. }
  202. // Find all subgraph of this node
  203. const auto &root_graph = GraphUtils::FindRootGraph(compute_graph);
  204. std::vector<ComputeGraphPtr> subgraphs;
  205. std::vector<NodePtr> all_nodes;
  206. std::deque<NodePtr> candidates;
  207. NodePtr remove_node_new = remove_node;
  208. candidates.emplace_back(remove_node_new);
  209. while (!candidates.empty()) {
  210. const NodePtr node = candidates.front();
  211. all_nodes.emplace_back(node);
  212. candidates.pop_front();
  213. OpDescPtr op_desc = node->GetOpDesc();
  214. if (op_desc == nullptr) {
  215. continue;
  216. }
  217. const auto &subgraph_names = op_desc->GetSubgraphInstanceNames();
  218. for (auto name_iter = subgraph_names.rbegin(); name_iter != subgraph_names.rend(); ++name_iter) {
  219. auto subgraph = root_graph->GetSubgraph(*name_iter);
  220. if (subgraph != nullptr) {
  221. subgraphs.emplace_back(subgraph);
  222. candidates.insert(candidates.begin(), subgraph->nodes_.begin(), subgraph->nodes_.end());
  223. }
  224. }
  225. }
  226. // Remove all subgraph
  227. for (const auto &remove_graph : subgraphs) {
  228. if (root_graph->RemoveSubGraph(remove_graph) != GRAPH_SUCCESS) {
  229. GELOGE(GRAPH_FAILED, "Remove subgraph failed, sub graph name is %s, compute graph is %s.",
  230. remove_node->GetName().c_str(), compute_graph->GetName().c_str());
  231. return GRAPH_FAILED;
  232. }
  233. }
  234. return GRAPH_SUCCESS;
  235. }
  236. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus
  237. GraphUtils::RemoveNodeWithoutRelink(const ComputeGraphPtr &compute_graph, const NodePtr &node) {
  238. GE_CHECK_NOTNULL(compute_graph);
  239. if (node == nullptr) {
  240. GELOGE(GRAPH_FAILED, "The node ptr should not be null.");
  241. return GRAPH_FAILED;
  242. }
  243. // If the node save as input node, delete it
  244. (void)compute_graph->RemoveInputNode(node);
  245. // If the node save as output node, delete it
  246. (void)compute_graph->RemoveOutputNode(node);
  247. // If the node has sub-graphs, delete them
  248. auto ret = RemoveSubgraphRecursively(compute_graph, node);
  249. if (ret != GRAPH_SUCCESS) {
  250. GELOGE(GRAPH_FAILED, "Remove subgraph recursively failed.");
  251. return GRAPH_FAILED;
  252. }
  253. auto iter = find(compute_graph->nodes_.begin(), compute_graph->nodes_.end(), node);
  254. if (iter != compute_graph->nodes_.end()) {
  255. compute_graph->nodes_.erase(iter);
  256. return GRAPH_SUCCESS;
  257. }
  258. return GRAPH_FAILED;
  259. }
  260. /// Add two edges to the new node, respectively connecting the SRC and DST
  261. /// associated with the original edge
  262. /// A ---> B transfered to A ---> N ---> B
  263. graphStatus InsertTransNode(ComputeGraph &compute_graph, const InDataAnchorPtr &in_data_anchor,
  264. const std::vector<OpDescPtr> &vec_op_desc) {
  265. GE_CHECK_NOTNULL(in_data_anchor);
  266. for (const auto &op_desc : vec_op_desc) {
  267. GE_CHECK_NOTNULL(op_desc);
  268. auto ret = op_desc->AddInputDesc(GeTensorDesc());
  269. GE_CHK_BOOL_EXEC(ret == GRAPH_SUCCESS, return GRAPH_FAILED, "Add input desc failed");
  270. ret = op_desc->AddOutputDesc(GeTensorDesc());
  271. GE_CHK_BOOL_EXEC(ret == GRAPH_SUCCESS, return GRAPH_FAILED, "Add input desc failed");
  272. auto node_to_insert = compute_graph.AddNode(op_desc);
  273. GE_CHECK_NOTNULL(node_to_insert);
  274. GE_CHECK_NOTNULL(in_data_anchor->GetPeerOutAnchor());
  275. auto src = in_data_anchor->GetPeerOutAnchor()->GetOwnerNode();
  276. if (!src) {
  277. GELOGE(GRAPH_FAILED, "src nullptr error.");
  278. return GRAPH_FAILED;
  279. }
  280. auto src_out_index = in_data_anchor->GetPeerOutAnchor()->GetIdx();
  281. auto dst = in_data_anchor->GetOwnerNode();
  282. if (!dst) {
  283. GELOGE(GRAPH_FAILED, "dst nullptr error.");
  284. return GRAPH_FAILED;
  285. }
  286. auto dst_in_index = in_data_anchor->GetIdx();
  287. auto in_data_anchor_src_format = AnchorUtils::GetFormat(in_data_anchor->GetPeerOutAnchor());
  288. auto in_data_anchor_dst_format = AnchorUtils::GetFormat(in_data_anchor);
  289. GE_CHECK_NOTNULL(src->GetOutDataAnchor(src_out_index));
  290. GE_CHECK_NOTNULL(dst->GetInDataAnchor(dst_in_index));
  291. ret = GraphUtils::RemoveEdge(src->GetOutDataAnchor(src_out_index), dst->GetInDataAnchor(dst_in_index));
  292. if (ret != GRAPH_SUCCESS) {
  293. GELOGE(GRAPH_FAILED, "Remove edge failed");
  294. return GRAPH_FAILED;
  295. }
  296. GE_CHECK_NOTNULL(node_to_insert->GetInDataAnchor(0));
  297. GE_CHECK_NOTNULL(node_to_insert->GetOutDataAnchor(0));
  298. ret = GraphUtils::AddEdge(src->GetOutDataAnchor(src_out_index), node_to_insert->GetInDataAnchor(0));
  299. if (ret != GRAPH_SUCCESS) {
  300. GELOGE(GRAPH_FAILED, "Add edge failed");
  301. return ret;
  302. }
  303. ret = GraphUtils::AddEdge(node_to_insert->GetOutDataAnchor(0), dst->GetInDataAnchor(dst_in_index));
  304. if (ret != GRAPH_SUCCESS) {
  305. GELOGE(GRAPH_FAILED, "Add edge failed");
  306. return ret;
  307. }
  308. if (op_desc->HasAttr("input_format")) {
  309. int64_t input_format = 0;
  310. int64_t output_format = 0;
  311. if (!AttrUtils::GetInt(op_desc, "input_format", input_format)) {
  312. GELOGW("get attr input_format failed");
  313. continue;
  314. }
  315. if (!AttrUtils::GetInt(op_desc, "output_format", output_format)) {
  316. GELOGW("get attr output_format failed");
  317. continue;
  318. }
  319. GE_CHECK_NOTNULL(node_to_insert->GetInDataAnchor(0)->GetPeerOutAnchor());
  320. GE_CHK_BOOL_RET_STATUS(node_to_insert->GetOutDataAnchor(0)->GetPeerInDataAnchors().empty(), GRAPH_FAILED,
  321. "Vistor<InDataAnchorPtr> is empty");
  322. GE_CHECK_NOTNULL(node_to_insert->GetOutDataAnchor(0)->GetPeerInDataAnchors().at(0));
  323. auto status =
  324. AnchorUtils::SetFormat(node_to_insert->GetInDataAnchor(0)->GetPeerOutAnchor(), in_data_anchor_src_format);
  325. if (status != GRAPH_SUCCESS) {
  326. GELOGE(GRAPH_FAILED, "Set format failed,format is %d", static_cast<int>(in_data_anchor_src_format));
  327. return status;
  328. }
  329. status = AnchorUtils::SetFormat(node_to_insert->GetInDataAnchor(0), static_cast<Format>(input_format));
  330. if (status != GRAPH_SUCCESS) {
  331. GELOGE(GRAPH_FAILED, "Set format failed,format is %ld", input_format);
  332. return status;
  333. }
  334. status = AnchorUtils::SetFormat(node_to_insert->GetOutDataAnchor(0), static_cast<Format>(output_format));
  335. if (status != GRAPH_SUCCESS) {
  336. GELOGE(GRAPH_FAILED, "Set format failed,format is %ld", output_format);
  337. return status;
  338. }
  339. status = AnchorUtils::SetFormat(node_to_insert->GetOutDataAnchor(0)->GetPeerInDataAnchors().at(0),
  340. in_data_anchor_dst_format);
  341. if (status != GRAPH_SUCCESS) {
  342. GELOGE(GRAPH_FAILED, "Set format failed,format is %d", static_cast<int>(in_data_anchor_dst_format));
  343. return status;
  344. }
  345. }
  346. std::vector<ge::NodePtr> original_nodes;
  347. GraphUtils::RecordOriginalNames(original_nodes, node_to_insert);
  348. }
  349. return GRAPH_SUCCESS;
  350. }
  351. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::InsertTransNode(
  352. ComputeGraphPtr compute_graph, const InDataAnchorPtr &in_data_anchor, const std::vector<OpDescPtr> &vec_op_desc) {
  353. GE_CHECK_NOTNULL(compute_graph);
  354. GE_CHECK_NOTNULL(in_data_anchor);
  355. graphStatus ret =
  356. ge::InsertTransNode(*compute_graph, in_data_anchor, vec_op_desc) == GRAPH_SUCCESS ? GRAPH_SUCCESS : GRAPH_FAILED;
  357. return ret;
  358. }
  359. ///
  360. /// @brief Insert node: src->insert_node:input_index, insert_node:output_index->dst
  361. /// @param [in] src
  362. /// @param [in] dsts
  363. /// @param [in] insert_node
  364. /// @param [in] input_index
  365. /// @param [in] output_index
  366. /// @return graphStatus
  367. ///
  368. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus
  369. GraphUtils::InsertNodeAfter(const OutDataAnchorPtr &src, const std::vector<InDataAnchorPtr> &dsts,
  370. const NodePtr &insert_node, uint32_t input_index, uint32_t output_index) {
  371. GE_CHECK_NOTNULL(src);
  372. GE_CHECK_NOTNULL(insert_node);
  373. NodePtr src_node = src->GetOwnerNode();
  374. if (src_node->GetOwnerComputeGraph() != insert_node->GetOwnerComputeGraph()) {
  375. GELOGE(GRAPH_FAILED, "src:%s and insert_node:%s not exist in the same graph.", src_node->GetName().c_str(),
  376. insert_node->GetName().c_str());
  377. return GRAPH_FAILED;
  378. }
  379. if (AddEdge(src, insert_node->GetInDataAnchor(input_index)) != GRAPH_SUCCESS) {
  380. GELOGE(GRAPH_FAILED, "AddEdge %s->%s failed.", src_node->GetName().c_str(), insert_node->GetName().c_str());
  381. return GRAPH_FAILED;
  382. }
  383. OutControlAnchorPtr src_out_ctrl_anchor = src_node->GetOutControlAnchor();
  384. GE_CHECK_NOTNULL(src_out_ctrl_anchor);
  385. bool ctrl_edge_flag = true;
  386. std::string type = NodeUtils::GetNodeType(src->GetOwnerNode());
  387. if ((type == SWITCH) || (type == REFSWITCH) || (type == SWITCHN)) {
  388. ctrl_edge_flag = false;
  389. }
  390. for (auto &dst : dsts) {
  391. GE_CHECK_NOTNULL(dst);
  392. NodePtr dst_node = dst->GetOwnerNode();
  393. GELOGI("Insert node %s between %s->%s.", insert_node->GetName().c_str(), src_node->GetName().c_str(),
  394. dst_node->GetName().c_str());
  395. if (src_node->GetOwnerComputeGraph() != dst_node->GetOwnerComputeGraph()) {
  396. GELOGE(GRAPH_FAILED, "src:%s and dst:%s not exist in the same graph.", src_node->GetName().c_str(),
  397. dst_node->GetName().c_str());
  398. return GRAPH_FAILED;
  399. }
  400. (void)RemoveEdge(src, dst);
  401. if (AddEdge(insert_node->GetOutDataAnchor(output_index), dst) != GRAPH_SUCCESS) {
  402. GELOGE(GRAPH_FAILED, "ReplaceEdge from %s->%s to %s->%s failed.", src_node->GetName().c_str(),
  403. dst_node->GetName().c_str(), insert_node->GetName().c_str(), dst_node->GetName().c_str());
  404. return GRAPH_FAILED;
  405. }
  406. if (!ctrl_edge_flag) {
  407. continue;
  408. }
  409. for (const InControlAnchorPtr &peer_in_ctrl_anchor : src_out_ctrl_anchor->GetPeerInControlAnchors()) {
  410. if ((RemoveEdge(src_out_ctrl_anchor, peer_in_ctrl_anchor) != GRAPH_SUCCESS) ||
  411. (AddEdge(insert_node->GetOutControlAnchor(), peer_in_ctrl_anchor) != GRAPH_SUCCESS)) {
  412. GELOGE(GRAPH_FAILED, "ReplaceEdge from %s->%s to %s->%s failed.", src_node->GetName().c_str(),
  413. peer_in_ctrl_anchor->GetOwnerNode()->GetName().c_str(), insert_node->GetName().c_str(),
  414. peer_in_ctrl_anchor->GetOwnerNode()->GetName().c_str());
  415. return GRAPH_FAILED;
  416. }
  417. }
  418. }
  419. return GRAPH_SUCCESS;
  420. }
  421. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::RemoveJustNode(ComputeGraph &compute_graph,
  422. const NodePtr &node) {
  423. if (node == nullptr) {
  424. GELOGE(GRAPH_FAILED, "The node ptr should be not null.");
  425. return GRAPH_FAILED;
  426. }
  427. auto iter = find(compute_graph.nodes_.begin(), compute_graph.nodes_.end(), node);
  428. if (iter != compute_graph.nodes_.end()) {
  429. compute_graph.nodes_.erase(iter);
  430. return GRAPH_SUCCESS;
  431. }
  432. return GRAPH_FAILED;
  433. }
  434. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::RemoveJustNode(ComputeGraphPtr compute_graph,
  435. const NodePtr &node) {
  436. GE_CHECK_NOTNULL(compute_graph);
  437. GE_CHECK_NOTNULL(node);
  438. graphStatus ret = (RemoveJustNode(*compute_graph, node) == GRAPH_SUCCESS ? GRAPH_SUCCESS : GRAPH_FAILED);
  439. return ret;
  440. }
  441. void GraphUtils::RecordOriginalNames(std::vector<ge::NodePtr> original_nodes, const ge::NodePtr &node) {
  442. GE_CHK_BOOL_EXEC(node != nullptr, return, "node is null.");
  443. std::vector<std::string> original_names;
  444. for (const auto &node_tmp : original_nodes) {
  445. std::vector<std::string> names_tmp;
  446. ge::OpDescPtr opdesc_tmp = node_tmp->GetOpDesc();
  447. if (opdesc_tmp == nullptr) {
  448. GELOGE(GRAPH_FAILED, "Node %s get opdesc is nullptr", node_tmp->GetName().c_str());
  449. continue;
  450. }
  451. auto ret = ge::AttrUtils::GetListStr(opdesc_tmp, ATTR_NAME_DATA_DUMP_ORIGIN_OP_NAMES, names_tmp);
  452. if (!ret) {
  453. GELOGW("Get list str failed");
  454. continue;
  455. }
  456. if (names_tmp.size() != 0) {
  457. original_names.insert(original_names.end(), names_tmp.begin(), names_tmp.end());
  458. } else {
  459. original_names.push_back(opdesc_tmp->GetName());
  460. }
  461. }
  462. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetListStr(node->GetOpDesc(), ATTR_NAME_DATA_DUMP_ORIGIN_OP_NAMES, original_names),
  463. return, "Set original_op_names fail.");
  464. }
  465. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY void GraphUtils::RecordOriginalNames(std::vector<std::string> names_tmp,
  466. const ge::NodePtr &node) {
  467. GE_CHK_BOOL_EXEC(node != nullptr, return, "node is null.");
  468. std::vector<std::string> original_names;
  469. if (names_tmp.size() != 0) {
  470. original_names.insert(original_names.end(), names_tmp.begin(), names_tmp.end());
  471. } else {
  472. std::string tmp;
  473. original_names.push_back(tmp);
  474. }
  475. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetListStr(node->GetOpDesc(), ATTR_NAME_DATA_DUMP_ORIGIN_OP_NAMES, original_names),
  476. return, "Set original_op_names fail.");
  477. }
  478. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY bool GraphUtils::MatchDumpStr(const std::string &suffix) {
  479. char *dump_level = std::getenv(kDumpGraphLevel);
  480. int64_t dump_graph_level =
  481. (dump_level != nullptr) ? std::strtol(dump_level, nullptr, kBaseOfIntegerValue) : kDumpLevel2;
  482. if (dump_graph_level == kDumpLevel1) {
  483. return false;
  484. }
  485. if (dump_graph_level == kDumpLevel2 &&
  486. ((suffix.find(kDumpStrPartition) != std::string::npos) ||
  487. (suffix.find(kDumpStrOptimizeSubgraph) != std::string::npos) ||
  488. (suffix.find(kDumpStrAicpu) != std::string::npos) || (suffix.find(kDumpStrSubgraphFunc) != std::string::npos))) {
  489. return true;
  490. }
  491. if (dump_graph_level == kDumpLevel3 && suffix.compare(kDumpStrBuild) != 0) {
  492. return true;
  493. }
  494. return false;
  495. }
  496. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY void GraphUtils::DumpGEGraph(const ge::ComputeGraphPtr &graph,
  497. const std::string &suffix,
  498. bool is_always_dump,
  499. const std::string &user_graph_name) {
  500. #ifdef FMK_SUPPORT_DUMP
  501. char *dump_ge_graph = std::getenv(kDumpGeGraph);
  502. GE_IF_BOOL_EXEC(dump_ge_graph == nullptr && !is_always_dump, return;);
  503. // dump the graph according to different graph level
  504. if (GraphUtils::MatchDumpStr(suffix)) {
  505. return;
  506. }
  507. // file name
  508. static std::atomic_long atomic_file_index(0);
  509. auto file_index = atomic_file_index.fetch_add(1);
  510. GELOGD("Start to dump om txt: %ld", file_index);
  511. thread_local long max_dump_file_num = 0;
  512. if (max_dump_file_num == 0) {
  513. string opt = "0";
  514. (void)GetContext().GetOption(OPTION_GE_MAX_DUMP_FILE_NUM, opt);
  515. max_dump_file_num = std::strtol(opt.c_str(), nullptr, kBaseOfIntegerValue);
  516. }
  517. if (max_dump_file_num != 0 && file_index > max_dump_file_num) {
  518. GELOGW("dump graph file cnt > maxDumpFileNum, maxDumpFileCnt=%ld.", max_dump_file_num);
  519. return;
  520. }
  521. std::stringstream stream_file_name;
  522. stream_file_name << "ge_proto_" << std::setw(kDumpGraphIndexWidth) << std::setfill('0') << file_index;
  523. stream_file_name << "_" << suffix << ".txt";
  524. std::string proto_file = user_graph_name.empty() ? stream_file_name.str() : user_graph_name;
  525. // Create buffer
  526. ge::Model model("", "");
  527. model.SetGraph(GraphUtils::CreateGraphFromComputeGraph(std::const_pointer_cast<ComputeGraph>(graph)));
  528. Buffer buffer;
  529. const int64_t kDumpLevel =
  530. (dump_ge_graph != nullptr) ? std::strtol(dump_ge_graph, nullptr, kBaseOfIntegerValue) : ge::OnnxUtils::NO_DUMP;
  531. model.Save(buffer, kDumpLevel != ge::OnnxUtils::DUMP_ALL);
  532. // Write file
  533. ge::proto::ModelDef ge_proto;
  534. if (buffer.GetData() != nullptr) {
  535. std::string str(reinterpret_cast<const char *>(buffer.GetData()), buffer.GetSize());
  536. if (!ge_proto.ParseFromString(str)) {
  537. GELOGE(GRAPH_FAILED, "parse from string failed.");
  538. return;
  539. }
  540. char real_path[PATH_MAX] = {0x00};
  541. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(strlen(proto_file.c_str()) >= PATH_MAX, return, "file path is too longer!");
  542. GE_IF_BOOL_EXEC(realpath(proto_file.c_str(), real_path) == nullptr,
  543. GELOGI("file %s does not exist, it will be created.", proto_file.c_str()));
  544. GraphUtils::WriteProtoToTextFile(ge_proto, real_path);
  545. }
  546. #else
  547. GELOGW("need to define FMK_SUPPORT_DUMP for dump graph.");
  548. #endif
  549. }
  550. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY bool GraphUtils::LoadGEGraph(const char *file,
  551. ge::ComputeGraph &compute_graph) {
  552. ge::proto::ModelDef model_def;
  553. // Get ModelDef object from file generated by DumpGEGraph()
  554. if (!ReadProtoFromTextFile(file, &model_def)) {
  555. GELOGE(GRAPH_FAILED, "Get ModelDef failed from file");
  556. return false;
  557. }
  558. ge::Model model;
  559. // Get Model object from ModelDef by deserialize ModelDef
  560. if (model.Load(model_def) == GRAPH_SUCCESS) {
  561. GE_CHK_BOOL_EXEC(GraphUtils::GetComputeGraph(model.GetGraph()) != nullptr, return false,
  562. "Get computer graph is nullptr");
  563. compute_graph = *(GraphUtils::GetComputeGraph(model.GetGraph()));
  564. return true;
  565. } else {
  566. GELOGE(GRAPH_FAILED, "Get Model failed from ModelDef");
  567. return false;
  568. }
  569. }
  570. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY bool GraphUtils::LoadGEGraph(const char *file,
  571. ge::ComputeGraphPtr &compute_graph) {
  572. ge::proto::ModelDef model_def;
  573. // Get ModelDef object from file generated by DumpGEGraph()
  574. if (!ReadProtoFromTextFile(file, &model_def)) {
  575. GELOGE(GRAPH_FAILED, "Get ModelDef failed from file");
  576. return false;
  577. }
  578. ge::Model model;
  579. // Get Model object from ModelDef by deserialize ModelDef
  580. if (model.Load(model_def) == GRAPH_SUCCESS) {
  581. GE_CHK_BOOL_EXEC(GraphUtils::GetComputeGraph(model.GetGraph()) != nullptr, return false,
  582. "Get computer graph is nullptr");
  583. compute_graph = GraphUtils::GetComputeGraph(model.GetGraph());
  584. for (const auto &node : compute_graph->GetDirectNode()) {
  585. GELOGI("Node %s set owner graph", node->GetName().c_str());
  586. GE_CHECK_NOTNULL(node);
  587. if (node->SetOwnerComputeGraph(compute_graph) != GRAPH_SUCCESS) {
  588. GELOGE(GRAPH_FAILED, "Node %s set owner graph failed", node->GetName().c_str());
  589. return false;
  590. }
  591. }
  592. return true;
  593. } else {
  594. GELOGE(GRAPH_FAILED, "Get Model failed from ModelDef");
  595. return false;
  596. }
  597. }
  598. // Printing protocol messages in text format is useful for debugging and human editing of messages.
  599. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY void GraphUtils::WriteProtoToTextFile(
  600. const google::protobuf::Message &proto, const char *real_path) {
  601. #ifdef FMK_SUPPORT_DUMP
  602. const int FILE_AUTHORITY = 0600;
  603. int fd = open(real_path, O_WRONLY | O_CREAT | O_TRUNC, FILE_AUTHORITY);
  604. if (fd < 0) {
  605. GELOGE(GRAPH_FAILED, "fail to open the file: %s, %s", real_path, strerror(errno));
  606. return;
  607. }
  608. google::protobuf::io::FileOutputStream *output = new (std::nothrow) FileOutputStream(fd);
  609. if (output == nullptr) {
  610. GELOGE(GRAPH_FAILED, "Output is nullptr");
  611. if (close(fd) != 0) {
  612. GELOGE(GRAPH_FAILED, "Close fileoutputstream failed");
  613. }
  614. return;
  615. }
  616. bool ret = google::protobuf::TextFormat::Print(proto, output);
  617. if (!ret) {
  618. GELOGE(GRAPH_FAILED, "Fail to write the file: %s", real_path);
  619. delete output;
  620. output = nullptr;
  621. GE_CHK_BOOL_EXEC(close(fd) == 0, return, "Close fileoutputstream failed");
  622. return;
  623. }
  624. delete output;
  625. output = nullptr;
  626. GE_CHK_BOOL_EXEC(close(fd) == 0, return, "Close fileoutputstream failed");
  627. FILE *file = fopen(real_path, "rb");
  628. if (file == nullptr) {
  629. return;
  630. }
  631. if (fseek(file, 0L, SEEK_END) == 0) {
  632. long fileSize = ftell(file);
  633. thread_local long max_dump_file_size = 0;
  634. if (max_dump_file_size == 0) {
  635. string opt = "0";
  636. // Can not check return value
  637. (void)GetContext().GetOption(OPTION_GE_MAX_DUMP_FILE_SIZE, opt);
  638. max_dump_file_size = std::strtol(opt.c_str(), nullptr, kBaseOfIntegerValue);
  639. }
  640. if (max_dump_file_size != 0 && fileSize != -1 && fileSize > max_dump_file_size) {
  641. GELOGW("dump graph file size > maxDumpFileSize, maxDumpFileSize=%ld.", max_dump_file_size);
  642. GE_IF_BOOL_EXEC(std::remove(real_path) != 0, GELOGW("remove %s failed", real_path));
  643. GE_CHK_BOOL_EXEC(fclose(file) == 0, return, "Fclose %s failed", real_path);
  644. return;
  645. }
  646. }
  647. GE_CHK_BOOL_EXEC(fclose(file) == 0, return, "Fclose fileoutputstream failed");
  648. #else
  649. GELOGW("need to define FMK_SUPPORT_DUMP for dump graph.");
  650. #endif
  651. }
  652. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY bool GraphUtils::ReadProtoFromTextFile(
  653. const char *file, google::protobuf::Message *proto) {
  654. if (file == nullptr || proto == nullptr) {
  655. GELOGE(GRAPH_FAILED, "incorrect parameter. file path or message is invalid");
  656. return false;
  657. }
  658. std::ifstream fs(file, std::ifstream::in);
  659. if (!fs.is_open()) {
  660. GELOGE(GRAPH_FAILED, "proto file '%s' open fail.", file);
  661. return false;
  662. }
  663. google::protobuf::io::IstreamInputStream input(&fs);
  664. bool ret = google::protobuf::TextFormat::Parse(&input, proto);
  665. if (!ret) {
  666. GELOGE(GRAPH_FAILED, "parse proto from text ret fail, please check your text file '%s'.", file);
  667. }
  668. fs.close();
  669. return ret;
  670. }
  671. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY void GraphUtils::DumpGEGraphToOnnx(const ge::ComputeGraph &compute_graph,
  672. const std::string &suffix) {
  673. #ifdef FMK_SUPPORT_DUMP
  674. char *dump_ge_graph = std::getenv(kDumpGeGraph);
  675. int64_t dump_ge_graph_level =
  676. (dump_ge_graph != nullptr) ? std::strtol(dump_ge_graph, nullptr, kBaseOfIntegerValue) : OnnxUtils::NO_DUMP;
  677. if ((dump_ge_graph_level == OnnxUtils::NO_DUMP) || (dump_ge_graph_level >= OnnxUtils::DUMP_LEVEL_END)) {
  678. GELOGD("Skip DumpGEGraphToOnnx with dump_ge_graph_level %ld.", dump_ge_graph_level);
  679. return;
  680. }
  681. // dump the graph according to different graph level
  682. if (GraphUtils::MatchDumpStr(suffix)) {
  683. return;
  684. }
  685. // 1.Get ge::onnx::ModelProto from ge::Model
  686. ge::Model model("GE", "");
  687. std::shared_ptr<ge::ComputeGraph> compute_graph_ptr = ComGraphMakeShared<ge::ComputeGraph>(compute_graph);
  688. model.SetGraph(GraphUtils::CreateGraphFromComputeGraph(std::const_pointer_cast<ComputeGraph>(compute_graph_ptr)));
  689. onnx::ModelProto model_proto;
  690. if (!OnnxUtils::ConvertGeModelToModelProto(model, model_proto)) {
  691. GELOGE(GRAPH_FAILED, "DumpGEGraphToOnnx failed.");
  692. return;
  693. }
  694. // 2.Set file name
  695. static std::atomic_long atomic_file_index(0);
  696. auto file_index = atomic_file_index.fetch_add(1);
  697. GELOGD("Start to dump ge onnx file: %ld", file_index);
  698. thread_local long max_dump_file_num = 0;
  699. if (max_dump_file_num == 0) {
  700. string opt = "0";
  701. (void)GetContext().GetOption(OPTION_GE_MAX_DUMP_FILE_NUM, opt);
  702. max_dump_file_num = std::strtol(opt.c_str(), nullptr, kBaseOfIntegerValue);
  703. }
  704. if (max_dump_file_num != 0 && file_index > max_dump_file_num) {
  705. GELOGW("dump graph file cnt > maxDumpFileNum, maxDumpFileNum=%ld.", max_dump_file_num);
  706. return;
  707. }
  708. std::stringstream stream_file_name;
  709. stream_file_name << "ge_onnx_" << std::setw(kDumpGraphIndexWidth) << std::setfill('0') << file_index;
  710. stream_file_name << "_graph_" << compute_graph.GetGraphID();
  711. stream_file_name << "_" << suffix << ".pbtxt";
  712. std::string proto_file = stream_file_name.str();
  713. if ((proto_file.length()) >= NAME_MAX) {
  714. GELOGE(GRAPH_FAILED, "File name is too longer!");
  715. return;
  716. }
  717. std::unique_ptr<char[]> real_path(new (std::nothrow) char[PATH_MAX]{0});
  718. if (real_path == nullptr) {
  719. GELOGE(GRAPH_FAILED, "New real_path failed.");
  720. return;
  721. }
  722. /// Returning nullptr means 3 case as follows:
  723. /// a.path is PATH_MAX chars or more
  724. /// b.the file does not exist
  725. /// c.the path has no permissions
  726. /// Distinguish between last the two cases in the function WriteProtoToTextFile call open()
  727. if (realpath(proto_file.c_str(), real_path.get()) == nullptr) {
  728. // For case a
  729. if (errno == ENAMETOOLONG) {
  730. GELOGE(GRAPH_FAILED, "Call realpath failed: path is PATH_MAX chars or more.");
  731. return;
  732. }
  733. }
  734. // 3. Serialize to file in current path
  735. GraphUtils::WriteProtoToTextFile(model_proto, real_path.get());
  736. #else
  737. GELOGW("need to define FMK_SUPPORT_DUMP for dump graph.");
  738. #endif
  739. }
  740. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY bool GraphUtils::LoadGEGraphFromOnnx(const char *file,
  741. ge::ComputeGraph &compute_graph) {
  742. if (file == nullptr) {
  743. GELOGE(GRAPH_FAILED, "incorrect parameter. file path is invalid");
  744. return false;
  745. }
  746. onnx::ModelProto model_proto;
  747. // 1. Get ModelDef object from file generated by DumpGEGraphToOnnx()
  748. if (!ReadProtoFromTextFile(file, &model_proto)) {
  749. GELOGE(GRAPH_FAILED, "Get ModelDef from file failed");
  750. return false;
  751. }
  752. // 2.Convert onnx::ModelProto To ge::Model
  753. ge::Model model;
  754. if (!OnnxUtils::ConvertModelProtoToGeModel(model_proto, model)) {
  755. GELOGE(GRAPH_FAILED, "Convert ModelDef to Model failed");
  756. return false;
  757. }
  758. auto compute_graph_ptr = GraphUtils::GetComputeGraph(model.GetGraph());
  759. if (compute_graph_ptr == nullptr) {
  760. GELOGE(GRAPH_FAILED, "Get compute graph from Model failed");
  761. return false;
  762. }
  763. compute_graph = *(compute_graph_ptr);
  764. return true;
  765. }
  766. namespace {
  767. using InNodesToOut = std::unordered_map<NodePtr, std::unordered_set<NodePtr>>;
  768. inline std::string GetNodeNameByAnchor(const Anchor *anchor) {
  769. if (anchor == nullptr) {
  770. GELOGE(GRAPH_FAILED, "Anchor is nullptr");
  771. return "Null";
  772. }
  773. auto node = anchor->GetOwnerNode();
  774. return node == nullptr ? "Null" : node->GetName();
  775. }
  776. graphStatus ReplaceOutDataAnchor(const OutDataAnchorPtr &new_anchor, const OutDataAnchorPtr &old_anchor,
  777. InNodesToOut *in_nodes_to_out = nullptr) {
  778. if (new_anchor == nullptr || old_anchor == nullptr) {
  779. GELOGE(GRAPH_FAILED, "new_anchor or old_anchor is nullptr");
  780. return GRAPH_PARAM_INVALID;
  781. }
  782. auto new_node = new_anchor->GetOwnerNode();
  783. for (const auto &peer_in_anchor : old_anchor->GetPeerInDataAnchors()) {
  784. auto ret = peer_in_anchor->Unlink(old_anchor);
  785. if (ret != GRAPH_SUCCESS) {
  786. GELOGE(GRAPH_FAILED, "Failed to unlink old anchor link from %s(%d) to %s(%d)",
  787. GetNodeNameByAnchor(old_anchor.get()).c_str(), old_anchor->GetIdx(),
  788. GetNodeNameByAnchor(peer_in_anchor.get()).c_str(), peer_in_anchor->GetIdx());
  789. return GRAPH_FAILED;
  790. }
  791. ret = peer_in_anchor->LinkFrom(new_anchor);
  792. if (ret != GRAPH_SUCCESS) {
  793. GELOGE(GRAPH_FAILED, "Failed to relink new anchors from %s(%d) to %s(%d)",
  794. GetNodeNameByAnchor(new_anchor.get()).c_str(), new_anchor->GetIdx(),
  795. GetNodeNameByAnchor(peer_in_anchor.get()).c_str(), peer_in_anchor->GetIdx());
  796. return GRAPH_FAILED;
  797. }
  798. if (in_nodes_to_out != nullptr) {
  799. (*in_nodes_to_out)[new_node].insert(peer_in_anchor->GetOwnerNode());
  800. }
  801. }
  802. return GRAPH_SUCCESS;
  803. }
  804. graphStatus RelinkDataIO(const NodePtr &node, const std::vector<int> &io_map, InNodesToOut &in_nodes_to_out) {
  805. GE_CHECK_NOTNULL(node);
  806. auto in_data_anchors = node->GetAllInDataAnchors();
  807. auto out_data_anchors = node->GetAllOutDataAnchors();
  808. if (out_data_anchors.size() < io_map.size()) {
  809. GELOGE(GRAPH_FAILED, "The io_map specified for node %s type %s is larger %zu than the actual size %zu",
  810. node->GetName().c_str(), node->GetType().c_str(), io_map.size(), out_data_anchors.size());
  811. return GRAPH_PARAM_INVALID;
  812. }
  813. for (size_t i = 0; i < out_data_anchors.size(); ++i) {
  814. auto out_data_anchor = out_data_anchors.at(i);
  815. if (out_data_anchor == nullptr) {
  816. GELOGE(GRAPH_FAILED, "Failed to relink for node %s type %s, the out data anchor at index %zu is null",
  817. node->GetName().c_str(), node->GetType().c_str(), i);
  818. return GRAPH_FAILED;
  819. }
  820. int in_index = -1;
  821. if (i < io_map.size()) {
  822. in_index = io_map.at(i);
  823. }
  824. if (in_index < 0) {
  825. out_data_anchor->UnlinkAll();
  826. continue;
  827. }
  828. if (in_index >= static_cast<int>(in_data_anchors.size())) {
  829. GELOGE(GRAPH_PARAM_INVALID, "Failed to relink for node %s type %s, invalid index %d specified for input(%zu)",
  830. node->GetName().c_str(), node->GetType().c_str(), in_index, in_data_anchors.size());
  831. return GRAPH_PARAM_INVALID;
  832. }
  833. auto in_anchor = in_data_anchors.at(in_index);
  834. if (in_anchor == nullptr) {
  835. GELOGW("Invalid in data anchors(null) found at node %s type %s index %d, ignore it.", node->GetName().c_str(),
  836. node->GetType().c_str(), in_index);
  837. continue;
  838. }
  839. auto peer_out_anchor = in_anchor->GetPeerOutAnchor();
  840. if (peer_out_anchor == nullptr) {
  841. continue;
  842. }
  843. if (peer_out_anchor->Unlink(in_anchor) != GRAPH_SUCCESS) {
  844. GELOGE(GRAPH_FAILED,
  845. "Failed relink node %s type %s, failed to unlink the data link"
  846. " from %s(%d) to it at input-index %d",
  847. node->GetName().c_str(), node->GetType().c_str(), GetNodeNameByAnchor(peer_out_anchor.get()).c_str(),
  848. peer_out_anchor->GetIdx(), in_index);
  849. return GRAPH_FAILED;
  850. }
  851. auto ret = ReplaceOutDataAnchor(peer_out_anchor, out_data_anchor, &in_nodes_to_out);
  852. if (ret != GRAPH_SUCCESS) {
  853. GELOGE(GRAPH_FAILED, "Failed to relink node %s type %s for relinking data anchors", node->GetName().c_str(),
  854. node->GetType().c_str());
  855. return GRAPH_FAILED;
  856. }
  857. }
  858. for (const auto &in_anchor : node->GetAllInDataAnchors()) {
  859. in_anchor->UnlinkAll();
  860. }
  861. return GRAPH_SUCCESS;
  862. }
  863. InNodesToOut GetFullConnectIONodes(const NodePtr &node) {
  864. InNodesToOut in_nodes_to_out;
  865. if (node == nullptr) {
  866. GELOGE(GRAPH_FAILED, "Node is nullptr");
  867. return in_nodes_to_out;
  868. }
  869. auto in_nodes_list = node->GetInNodes();
  870. auto out_nodes_list = node->GetOutNodes();
  871. auto out_nodes = std::unordered_set<NodePtr>(out_nodes_list.begin(), out_nodes_list.end());
  872. for (const auto &in_node : in_nodes_list) {
  873. in_nodes_to_out.insert(std::make_pair(in_node, out_nodes));
  874. }
  875. return in_nodes_to_out;
  876. }
  877. graphStatus RelinkControlNodeIfNeed(const NodePtr &node, InNodesToOut &in_nodes_to_out,
  878. InNodesToOut &connected_data_in_to_out) {
  879. GE_CHECK_NOTNULL(node);
  880. for (const auto &in_node_to_out : in_nodes_to_out) {
  881. auto &in_node = in_node_to_out.first;
  882. GE_CHECK_NOTNULL(in_node);
  883. auto &connected_data_out = connected_data_in_to_out[in_node];
  884. for (const auto &out_node : in_node_to_out.second) {
  885. GE_CHECK_NOTNULL(out_node);
  886. if (connected_data_out.count(out_node) == 0) {
  887. GE_CHECK_NOTNULL(in_node->GetOutControlAnchor());
  888. if (in_node->GetOutControlAnchor()->IsLinkedWith(out_node->GetInControlAnchor())) {
  889. continue;
  890. }
  891. auto ret = GraphUtils::AddEdge(in_node->GetOutControlAnchor(), out_node->GetInControlAnchor());
  892. if (ret != GRAPH_SUCCESS) {
  893. GELOGE(GRAPH_FAILED, "Failed to add control edge from %s to %s when isolating node %s type %s",
  894. in_node->GetName().c_str(), out_node->GetName().c_str(), node->GetName().c_str(),
  895. node->GetType().c_str());
  896. return GRAPH_FAILED;
  897. }
  898. }
  899. }
  900. }
  901. return GRAPH_SUCCESS;
  902. }
  903. graphStatus ReplaceOutDataAnchors(const Node::Vistor<OutDataAnchorPtr> &new_outs,
  904. const Node::Vistor<OutDataAnchorPtr> &old_outs, const std::vector<int> &outputs_map) {
  905. auto new_out_size = new_outs.size();
  906. if (new_out_size < outputs_map.size()) {
  907. GELOGE(GRAPH_PARAM_INVALID,
  908. "Failed to replace out data anchors, the actual size %zu is less than the mapping size %zu", new_out_size,
  909. outputs_map.size());
  910. return GRAPH_PARAM_INVALID;
  911. }
  912. for (size_t i = 0; i < new_out_size; ++i) {
  913. auto &new_out_anchor = new_outs.at(i);
  914. if (new_out_anchor == nullptr) {
  915. GELOGE(GRAPH_FAILED, "Failed to replace out data anchors, the out data anchor on new node is null, index %zu", i);
  916. return GRAPH_FAILED;
  917. }
  918. if (i >= outputs_map.size()) {
  919. continue;
  920. }
  921. auto old_index = outputs_map.at(i);
  922. if (old_index < 0) {
  923. continue;
  924. }
  925. const OutDataAnchorPtr &old_out_anchor = old_outs.at(old_index);
  926. if (old_out_anchor == nullptr) {
  927. GELOGE(GRAPH_FAILED, "Failed to replace out data anchors, the out data anchor on old node is null, index %d",
  928. old_index);
  929. return GRAPH_FAILED;
  930. }
  931. auto ret = ReplaceOutDataAnchor(new_out_anchor, old_out_anchor);
  932. if (ret != GRAPH_SUCCESS) {
  933. return ret;
  934. }
  935. }
  936. return GRAPH_SUCCESS;
  937. }
  938. graphStatus ReplaceInDataAnchors(const Node::Vistor<InDataAnchorPtr> &new_ins,
  939. const Node::Vistor<InDataAnchorPtr> &old_ins, const std::vector<int> &inputs_map) {
  940. auto new_in_size = new_ins.size();
  941. if (new_in_size < inputs_map.size()) {
  942. GELOGE(GRAPH_FAILED, "Failed to replace in data anchors, the actual size %zu is less than the mapping size %zu",
  943. new_in_size, inputs_map.size());
  944. return GRAPH_PARAM_INVALID;
  945. }
  946. for (size_t i = 0; i < new_in_size; ++i) {
  947. auto &new_in_anchor = new_ins.at(i);
  948. if (new_in_anchor == nullptr) {
  949. GELOGE(GRAPH_FAILED, "Failed to replace in data anchors, the out data anchor on new node is null, index %zu", i);
  950. return GRAPH_FAILED;
  951. }
  952. if (i >= inputs_map.size()) {
  953. continue;
  954. }
  955. auto old_index = inputs_map.at(i);
  956. if (old_index < 0) {
  957. continue;
  958. }
  959. const InDataAnchorPtr &old_in_anchor = old_ins.at(old_index);
  960. if (old_in_anchor == nullptr) {
  961. GELOGE(GRAPH_FAILED, "Failed to replace in data anchors, the out data anchor on old node is null, index %d",
  962. old_index);
  963. return GRAPH_FAILED;
  964. }
  965. auto peer_out_anchor = old_in_anchor->GetPeerOutAnchor();
  966. if (peer_out_anchor == nullptr) {
  967. GELOGW("Peer out anchor is nullptr");
  968. continue;
  969. }
  970. auto ret = peer_out_anchor->Unlink(old_in_anchor);
  971. if (ret != GRAPH_SUCCESS) {
  972. GELOGE(GRAPH_FAILED, "Failed to unlink old anchors, unlink from %s(%d) to %s(%d)",
  973. GetNodeNameByAnchor(peer_out_anchor.get()).c_str(), peer_out_anchor->GetIdx(),
  974. GetNodeNameByAnchor(old_in_anchor.get()).c_str(), old_in_anchor->GetIdx());
  975. return GRAPH_FAILED;
  976. }
  977. ret = peer_out_anchor->LinkTo(new_in_anchor);
  978. if (ret != GRAPH_SUCCESS) {
  979. GELOGE(GRAPH_FAILED, "Failed to link new anchors, link from %s(%d) to %s(%d)",
  980. GetNodeNameByAnchor(peer_out_anchor.get()).c_str(), peer_out_anchor->GetIdx(),
  981. GetNodeNameByAnchor(old_in_anchor.get()).c_str(), old_in_anchor->GetIdx());
  982. return GRAPH_FAILED;
  983. }
  984. }
  985. return GRAPH_SUCCESS;
  986. }
  987. graphStatus ReplaceControlAnchors(const NodePtr &new_node, const NodePtr &old_node) {
  988. GE_CHECK_NOTNULL(new_node);
  989. GE_CHECK_NOTNULL(new_node->GetInControlAnchor());
  990. GE_CHECK_NOTNULL(old_node);
  991. GE_CHECK_NOTNULL(old_node->GetInControlAnchor());
  992. auto peer_out_anchors = old_node->GetInControlAnchor()->GetPeerAnchors();
  993. auto new_in_control_anchor = new_node->GetInControlAnchor();
  994. auto exists_out_anchors = new_in_control_anchor->GetPeerAnchors();
  995. auto exists_out_anchors_set = std::set<AnchorPtr>(exists_out_anchors.begin(), exists_out_anchors.end());
  996. for (const auto &peer_out_anchor : peer_out_anchors) {
  997. if (peer_out_anchor != nullptr) {
  998. if (exists_out_anchors_set.count(peer_out_anchor) > 0) {
  999. continue;
  1000. }
  1001. auto ret = GraphUtils::AddEdge(peer_out_anchor, new_in_control_anchor);
  1002. if (ret != GRAPH_SUCCESS) {
  1003. GELOGE(GRAPH_FAILED, "Add edge failed");
  1004. return GRAPH_FAILED;
  1005. }
  1006. } else {
  1007. GELOGW("peer outanchor is nullptr");
  1008. continue;
  1009. }
  1010. }
  1011. auto old_out_control_anchor = old_node->GetOutControlAnchor();
  1012. GE_CHECK_NOTNULL(old_out_control_anchor);
  1013. auto peer_in_anchors = old_out_control_anchor->GetPeerAnchors();
  1014. auto new_out_control_anchor = new_node->GetOutControlAnchor();
  1015. GE_CHECK_NOTNULL(new_out_control_anchor);
  1016. auto exists_in_anchors = new_out_control_anchor->GetPeerAnchors();
  1017. auto exists_in_anchors_set = std::set<AnchorPtr>(exists_in_anchors.begin(), exists_in_anchors.end());
  1018. for (const auto &peer_in_anchor : peer_in_anchors) {
  1019. if (peer_in_anchor != nullptr) {
  1020. if (exists_in_anchors_set.count(peer_in_anchor) > 0) {
  1021. continue;
  1022. }
  1023. auto ret = GraphUtils::AddEdge(new_out_control_anchor, peer_in_anchor);
  1024. if (ret != GRAPH_SUCCESS) {
  1025. GELOGE(GRAPH_FAILED, "Add edge failed");
  1026. return GRAPH_FAILED;
  1027. }
  1028. } else {
  1029. GELOGW("Peer inanchor is nullptr");
  1030. continue;
  1031. }
  1032. }
  1033. return GRAPH_SUCCESS;
  1034. }
  1035. } // namespace
  1036. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::IsolateNode(const NodePtr &node,
  1037. const std::vector<int> &io_map) {
  1038. if (node == nullptr) {
  1039. GELOGE(GRAPH_PARAM_INVALID, "Failed to isolate node(null)");
  1040. return GRAPH_PARAM_INVALID;
  1041. }
  1042. /// We must get full connections info before re-link data io, because the data
  1043. /// edges may be unlinked when relink data io
  1044. auto in_nodes_to_out = GetFullConnectIONodes(node);
  1045. InNodesToOut data_in_to_out;
  1046. auto ret = RelinkDataIO(node, io_map, data_in_to_out);
  1047. if (ret != GRAPH_SUCCESS) {
  1048. GELOGE(GRAPH_FAILED, "Failed to isolate node %s type %s when relink data IO", node->GetName().c_str(),
  1049. node->GetType().c_str());
  1050. return ret;
  1051. }
  1052. ret = RelinkControlNodeIfNeed(node, in_nodes_to_out, data_in_to_out);
  1053. if (ret != GRAPH_SUCCESS) {
  1054. return ret;
  1055. }
  1056. NodeUtils::UnlinkAll(*node);
  1057. return GRAPH_SUCCESS;
  1058. }
  1059. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus
  1060. GraphUtils::IsolateNode(const NodePtr &node, const std::initializer_list<int> &io_map) {
  1061. return IsolateNode(node, std::vector<int>(io_map));
  1062. }
  1063. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::IsolateNodeOneIO(const NodePtr &node) {
  1064. if (node == nullptr) {
  1065. GELOGE(GRAPH_PARAM_INVALID, "incorrect parameter. node is invalid");
  1066. return GRAPH_PARAM_INVALID;
  1067. }
  1068. if (node->GetAllInDataAnchorsSize() != 1) {
  1069. return GRAPH_PARAM_INVALID;
  1070. }
  1071. if (node->GetAllOutDataAnchorsSize() != 1) {
  1072. return GRAPH_PARAM_INVALID;
  1073. }
  1074. return IsolateNode(node, {0});
  1075. }
  1076. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus
  1077. GraphUtils::ReplaceNodeAnchors(const NodePtr &new_node, const NodePtr &old_node, const std::vector<int> &inputs_map,
  1078. const std::vector<int> &outputs_map) {
  1079. if ((new_node == nullptr) || (old_node == nullptr)) {
  1080. GELOGE(GRAPH_FAILED, "Parameter is nullptr");
  1081. return GRAPH_PARAM_INVALID;
  1082. }
  1083. auto ret = ReplaceNodeDataAnchors(new_node, old_node, inputs_map, outputs_map);
  1084. if (ret != GRAPH_SUCCESS) {
  1085. // The error log was printed in `ReplaceNodeDataAnchors`
  1086. return GRAPH_FAILED;
  1087. }
  1088. ret = ReplaceControlAnchors(new_node, old_node);
  1089. if (ret != GRAPH_SUCCESS) {
  1090. GELOGE(GRAPH_FAILED,
  1091. "Failed to replace control anchors when replace node from old node %s type %s to new node %s type %s",
  1092. old_node->GetName().c_str(), old_node->GetType().c_str(), new_node->GetName().c_str(),
  1093. new_node->GetType().c_str());
  1094. return GRAPH_FAILED;
  1095. }
  1096. return GRAPH_SUCCESS;
  1097. }
  1098. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::ReplaceNodeAnchors(
  1099. const NodePtr &new_node, const NodePtr &old_node, const std::initializer_list<int> inputs_map,
  1100. const std::initializer_list<int> outputs_map) {
  1101. return ReplaceNodeAnchors(new_node, old_node, std::vector<int>(inputs_map), std::vector<int>(outputs_map));
  1102. }
  1103. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus
  1104. GraphUtils::ReplaceNodeDataAnchors(const NodePtr &new_node, const NodePtr &old_node,
  1105. std::initializer_list<int> inputs_map, std::initializer_list<int> outputs_map) {
  1106. return ReplaceNodeDataAnchors(new_node, old_node, std::vector<int>(inputs_map), std::vector<int>(outputs_map));
  1107. }
  1108. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus
  1109. GraphUtils::ReplaceNodeDataAnchors(const NodePtr &new_node, const NodePtr &old_node, const std::vector<int> &inputs_map,
  1110. const std::vector<int> &outputs_map) {
  1111. if (new_node == nullptr || old_node == nullptr) {
  1112. GELOGE(GRAPH_FAILED, "Parameter is nullptr");
  1113. return GRAPH_PARAM_INVALID;
  1114. }
  1115. auto ret = ReplaceOutDataAnchors(new_node->GetAllOutDataAnchors(), old_node->GetAllOutDataAnchors(), outputs_map);
  1116. if (ret != GRAPH_SUCCESS) {
  1117. GELOGE(GRAPH_FAILED,
  1118. "Failed to replace out data anchors when replace node from old node %s type %s to new node %s type %s",
  1119. old_node->GetName().c_str(), old_node->GetType().c_str(), new_node->GetName().c_str(),
  1120. new_node->GetType().c_str());
  1121. return GRAPH_FAILED;
  1122. }
  1123. ret = ReplaceInDataAnchors(new_node->GetAllInDataAnchors(), old_node->GetAllInDataAnchors(), inputs_map);
  1124. if (ret != GRAPH_SUCCESS) {
  1125. GELOGE(GRAPH_FAILED,
  1126. "Failed to replace in data anchors when replace node from old node %s type %s to new node %s type %s",
  1127. old_node->GetName().c_str(), old_node->GetType().c_str(), new_node->GetName().c_str(),
  1128. new_node->GetType().c_str());
  1129. return GRAPH_FAILED;
  1130. }
  1131. return GRAPH_SUCCESS;
  1132. }
  1133. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::CopyInCtrlEdges(const NodePtr &src_node,
  1134. NodePtr &dst_node) {
  1135. if ((src_node == nullptr) || (dst_node == nullptr)) {
  1136. GELOGE(GRAPH_FAILED, "Parameter is nullptr");
  1137. return GRAPH_PARAM_INVALID;
  1138. }
  1139. auto src_ctrl_in_nodes = src_node->GetInControlNodes();
  1140. if (src_ctrl_in_nodes.empty()) {
  1141. return GRAPH_SUCCESS;
  1142. }
  1143. std::unordered_set<NodePtr> exist_in_ctrl_nodes_set;
  1144. auto exist_in_ctrl_nodes = dst_node->GetInControlNodes();
  1145. if (!exist_in_ctrl_nodes.empty()) {
  1146. exist_in_ctrl_nodes_set.insert(exist_in_ctrl_nodes.begin(), exist_in_ctrl_nodes.end());
  1147. }
  1148. auto dst_ctrl = dst_node->GetInControlAnchor();
  1149. for (const auto &in_node : src_ctrl_in_nodes) {
  1150. if (exist_in_ctrl_nodes_set.count(in_node) > 0) {
  1151. continue;
  1152. }
  1153. auto ret = GraphUtils::AddEdge(in_node->GetOutControlAnchor(), dst_ctrl);
  1154. if (ret != GRAPH_SUCCESS) {
  1155. GELOGE(GRAPH_FAILED, "Failed to add control edge from %s to %s when copy control dependencies from %s to %s",
  1156. in_node->GetName().c_str(), dst_node->GetName().c_str(), src_node->GetName().c_str(),
  1157. dst_node->GetName().c_str());
  1158. return ret;
  1159. }
  1160. }
  1161. return GRAPH_SUCCESS;
  1162. }
  1163. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::MoveInCtrlEdges(const NodePtr &src_node,
  1164. NodePtr &dst_node) {
  1165. if (src_node == nullptr || dst_node == nullptr) {
  1166. GELOGE(GRAPH_FAILED, "Parameter is nullptr");
  1167. return GRAPH_FAILED;
  1168. }
  1169. auto ret = CopyInCtrlEdges(src_node, dst_node);
  1170. if (ret != GRAPH_SUCCESS) {
  1171. GELOGE(GRAPH_FAILED, "Copy in ctrl edges failed");
  1172. return ret;
  1173. }
  1174. GE_CHECK_NOTNULL(src_node->GetInControlAnchor());
  1175. src_node->GetInControlAnchor()->UnlinkAll();
  1176. return GRAPH_SUCCESS;
  1177. }
  1178. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::CopyOutCtrlEdges(const NodePtr &src_node,
  1179. NodePtr &dst_node) {
  1180. if (src_node == nullptr || dst_node == nullptr) {
  1181. GELOGE(GRAPH_FAILED, "Parameter is nullptr");
  1182. return GRAPH_FAILED;
  1183. }
  1184. auto out_ctrl_nodes = src_node->GetOutControlNodes();
  1185. if (out_ctrl_nodes.empty()) {
  1186. return GRAPH_SUCCESS;
  1187. }
  1188. std::unordered_set<Node *> exists_out_ctrl_nodes_set;
  1189. for (const auto &node : dst_node->GetOutControlNodes()) {
  1190. exists_out_ctrl_nodes_set.insert(node.get());
  1191. }
  1192. auto dst_out_ctrl = dst_node->GetOutControlAnchor();
  1193. for (const auto &node : out_ctrl_nodes) {
  1194. if (exists_out_ctrl_nodes_set.count(node.get()) > 0) {
  1195. continue;
  1196. }
  1197. auto ret = GraphUtils::AddEdge(dst_out_ctrl, node->GetInControlAnchor());
  1198. if (ret != GRAPH_SUCCESS) {
  1199. GELOGE(GRAPH_FAILED, "Failed to add control edge from %s to %s when copy control dependencies from %s to %s",
  1200. dst_node->GetName().c_str(), node->GetName().c_str(), src_node->GetName().c_str(),
  1201. dst_node->GetName().c_str());
  1202. return ret;
  1203. }
  1204. }
  1205. return GRAPH_SUCCESS;
  1206. }
  1207. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::MoveOutCtrlEdges(NodePtr &src_node,
  1208. NodePtr &dst_node) {
  1209. if (src_node == nullptr || dst_node == nullptr) {
  1210. GELOGE(GRAPH_FAILED, "Parameter is nullptr");
  1211. return GRAPH_FAILED;
  1212. }
  1213. auto ret = CopyOutCtrlEdges(src_node, dst_node);
  1214. if (ret != GRAPH_SUCCESS) {
  1215. GELOGE(GRAPH_FAILED, "Copyout ctrl edges failed");
  1216. return ret;
  1217. }
  1218. GE_CHECK_NOTNULL(src_node->GetOutControlAnchor());
  1219. src_node->GetOutControlAnchor()->UnlinkAll();
  1220. return GRAPH_SUCCESS;
  1221. }
  1222. ///
  1223. /// Copy all in-data edges from `src_node` to `dst_node`.
  1224. /// @param src_node
  1225. /// @param dst_node
  1226. /// @return
  1227. ///
  1228. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::CopyInDataEdges(const NodePtr &src_node,
  1229. NodePtr &dst_node) {
  1230. if ((src_node == nullptr) || (dst_node == nullptr)) {
  1231. GELOGE(GRAPH_FAILED, "Parameter is nullptr");
  1232. return GRAPH_PARAM_INVALID;
  1233. }
  1234. auto src_data_in_nodes = src_node->GetInDataNodes();
  1235. if (src_data_in_nodes.empty()) {
  1236. return GRAPH_SUCCESS;
  1237. }
  1238. for (const auto &in_data_anchor : src_node->GetAllInDataAnchors()) {
  1239. auto input_desc = src_node->GetOpDesc()->GetInputDesc(in_data_anchor->GetIdx());
  1240. auto ret =
  1241. GraphUtils::AddEdge(in_data_anchor->GetPeerOutAnchor(), dst_node->GetInDataAnchor(in_data_anchor->GetIdx()));
  1242. if (ret != GRAPH_SUCCESS) {
  1243. GELOGE(GRAPH_FAILED, "Failed to add data edge from %s to %s when copy in data edge from %s to %s",
  1244. in_data_anchor->GetPeerOutAnchor()->GetOwnerNode()->GetName().c_str(), dst_node->GetName().c_str(),
  1245. src_node->GetName().c_str(), dst_node->GetName().c_str());
  1246. return ret;
  1247. }
  1248. }
  1249. return GRAPH_SUCCESS;
  1250. }
  1251. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus GraphUtils::AppendInputNode(const ComputeGraphPtr &graph,
  1252. const NodePtr &node) {
  1253. if (graph->AddInputNode(node) == nullptr) {
  1254. GELOGE(GRAPH_FAILED, "Copyout ctrl edges failed");
  1255. return GRAPH_FAILED;
  1256. }
  1257. graph->SetInputSize(graph->GetInputSize() + 1);
  1258. graph->inputs_order_.emplace_back(node->GetName());
  1259. return GRAPH_SUCCESS;
  1260. }
  1261. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY ComputeGraphPtr GraphUtils::FindRootGraph(ComputeGraphPtr graph) {
  1262. ComputeGraphPtr result = nullptr;
  1263. while (graph != nullptr) {
  1264. result = std::move(graph);
  1265. graph = result->GetParentGraph();
  1266. }
  1267. return result;
  1268. }
  1269. ///
  1270. /// Make a copy of ComputeGraph.
  1271. /// @param graph: original graph.
  1272. /// @param prefix: node name prefix of new graph.
  1273. /// @param output_nodes: output nodes of new graph.
  1274. /// @return ComputeGraphPtr
  1275. ///
  1276. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY ComputeGraphPtr
  1277. GraphUtils::CloneGraph(const ComputeGraphPtr &graph, const std::string &prefix, std::vector<NodePtr> &input_nodes,
  1278. std::vector<NodePtr> &output_nodes) {
  1279. GE_CHK_BOOL_EXEC(graph != nullptr, return nullptr, "Original graph is null");
  1280. ComputeGraphPtr new_graph = ComGraphMakeShared<ComputeGraph>(graph->GetName());
  1281. GE_CHK_BOOL_EXEC(new_graph != nullptr, return nullptr, "Create new graph failed");
  1282. std::unordered_map<std::string, NodePtr> all_new_nodes;
  1283. for (const auto &n : graph->GetDirectNode()) {
  1284. OpDescPtr op_desc = AttrUtils::CopyOpDesc(n->GetOpDesc());
  1285. GE_CHK_BOOL_EXEC(op_desc != nullptr, return nullptr, "Create new node failed");
  1286. if (CopyTensorAttrs(op_desc, n) != GRAPH_SUCCESS) {
  1287. return nullptr;
  1288. }
  1289. op_desc->SetName(prefix + n->GetName());
  1290. NodePtr node = new_graph->AddNode(op_desc);
  1291. GE_CHK_BOOL_EXEC(node != nullptr, return nullptr, "Add node[%s] to graph failed", op_desc->GetName().c_str());
  1292. all_new_nodes[node->GetName()] = node;
  1293. if (node->GetType() == DATA) {
  1294. input_nodes.emplace_back(node);
  1295. } else if (node->GetType() == NETOUTPUT) {
  1296. output_nodes.emplace_back(node);
  1297. }
  1298. }
  1299. for (const auto &n : graph->GetDirectNode()) {
  1300. if (RelinkGraphEdges(n, prefix, all_new_nodes) != GRAPH_SUCCESS) {
  1301. return nullptr;
  1302. }
  1303. }
  1304. std::string session_graph_id;
  1305. if (AttrUtils::GetStr(*graph, ATTR_NAME_SESSION_GRAPH_ID, session_graph_id)) {
  1306. bool ret = AttrUtils::SetStr(*new_graph, ATTR_NAME_SESSION_GRAPH_ID, session_graph_id);
  1307. if (!ret) {
  1308. GELOGE(GRAPH_FAILED, "Set attr ATTR_NAME_SESSION_GRAPH_ID failed.");
  1309. return nullptr;
  1310. }
  1311. }
  1312. return new_graph;
  1313. }
  1314. ///
  1315. /// Copy tensor attribute to new node.
  1316. /// @param [in] dst_node: cloned node.
  1317. /// @param [in] src_node: original node.
  1318. /// @return success: GRAPH_SUCESS
  1319. ///
  1320. graphStatus GraphUtils::CopyTensorAttrs(const OpDescPtr &dst_desc, const NodePtr &src_node) {
  1321. if (dst_desc == nullptr) {
  1322. GELOGE(GRAPH_FAILED, "Input param dst node not valid");
  1323. return GRAPH_FAILED;
  1324. }
  1325. if (src_node == nullptr || src_node->GetOpDesc() == nullptr) {
  1326. GELOGE(GRAPH_FAILED, "Input param src node not valid");
  1327. return GRAPH_FAILED;
  1328. }
  1329. const auto &src_desc = src_node->GetOpDesc();
  1330. dst_desc->CopyAttrsFrom(*src_desc);
  1331. for (uint32_t i = 0; i < src_node->GetAllInDataAnchorsSize(); ++i) {
  1332. auto input_desc = dst_desc->MutableInputDesc(i);
  1333. if (input_desc == nullptr) {
  1334. continue;
  1335. }
  1336. input_desc->CopyAttrsFrom(src_desc->GetInputDesc(i));
  1337. }
  1338. for (uint32_t i = 0; i < src_node->GetAllOutDataAnchorsSize(); ++i) {
  1339. auto output_desc = dst_desc->MutableOutputDesc(i);
  1340. if (output_desc == nullptr) {
  1341. GELOGE(GRAPH_FAILED, "Param dst node not valid");
  1342. return GRAPH_FAILED;
  1343. }
  1344. output_desc->CopyAttrsFrom(src_desc->GetOutputDesc(i));
  1345. }
  1346. return GRAPH_SUCCESS;
  1347. }
  1348. ///
  1349. /// Relink all edges for cloned ComputeGraph.
  1350. /// @param [in] node: original node.
  1351. /// @param [in] prefix: node name prefix of new node.
  1352. /// @param [in] all_nodes: all nodes in new graph.
  1353. /// @return success: GRAPH_SUCESS
  1354. ///
  1355. graphStatus GraphUtils::RelinkGraphEdges(const NodePtr &node, const string &prefix,
  1356. const std::unordered_map<string, NodePtr> &all_nodes) {
  1357. if (node == nullptr || node->GetOpDesc() == nullptr) {
  1358. GELOGE(GRAPH_FAILED, "Input node not valid");
  1359. return GRAPH_FAILED;
  1360. }
  1361. auto it = all_nodes.find(prefix + node->GetName());
  1362. if (it == all_nodes.end()) {
  1363. GELOGE(GRAPH_FAILED, "node[%s] not found", node->GetName().c_str());
  1364. return GRAPH_FAILED;
  1365. }
  1366. const auto &new_node = it->second;
  1367. for (const auto &in_anchor : node->GetAllInDataAnchors()) {
  1368. GE_CHK_BOOL_EXEC(in_anchor != nullptr, return GRAPH_FAILED, "In data anchor is null");
  1369. const auto &out_anchor = in_anchor->GetPeerOutAnchor();
  1370. if (out_anchor == nullptr) {
  1371. GELOGW("Peer out anchor is null: %s", node->GetName().c_str());
  1372. continue;
  1373. }
  1374. GE_CHK_BOOL_EXEC(out_anchor->GetOwnerNode() != nullptr, return GRAPH_FAILED, "Peer out node is null");
  1375. it = all_nodes.find(prefix + out_anchor->GetOwnerNode()->GetName());
  1376. if (it == all_nodes.end()) {
  1377. GELOGE(GRAPH_FAILED, "node[%s] not found", out_anchor->GetOwnerNode()->GetName().c_str());
  1378. return GRAPH_FAILED;
  1379. }
  1380. const auto &new_out_node = it->second;
  1381. auto rslt =
  1382. GraphUtils::AddEdge(new_out_node->GetOutAnchor(out_anchor->GetIdx()), new_node->GetInAnchor(in_anchor->GetIdx()));
  1383. GE_CHK_BOOL_EXEC(rslt == GRAPH_SUCCESS, return GRAPH_FAILED, "link failed[%s to %s]",
  1384. new_out_node->GetName().c_str(), new_node->GetName().c_str());
  1385. }
  1386. if (node->GetInControlAnchor() != nullptr) {
  1387. for (const auto &out_anchor : node->GetInControlAnchor()->GetPeerAnchors()) {
  1388. GE_CHK_BOOL_EXEC(out_anchor != nullptr, continue, "Peer out anchor is null: %s", node->GetName().c_str());
  1389. GE_CHK_BOOL_EXEC(out_anchor->GetOwnerNode() != nullptr, return GRAPH_FAILED, "Peer out node is null");
  1390. it = all_nodes.find(prefix + out_anchor->GetOwnerNode()->GetName());
  1391. if (it == all_nodes.end()) {
  1392. GELOGE(GRAPH_FAILED, "node[%s] not found", out_anchor->GetOwnerNode()->GetName().c_str());
  1393. return GRAPH_FAILED;
  1394. }
  1395. const auto &new_out_node = it->second;
  1396. auto rslt = GraphUtils::AddEdge(new_out_node->GetOutAnchor(out_anchor->GetIdx()), new_node->GetInControlAnchor());
  1397. GE_CHK_BOOL_EXEC(rslt == GRAPH_SUCCESS, return GRAPH_FAILED, "link failed[%s to %s]",
  1398. new_out_node->GetName().c_str(), new_node->GetName().c_str());
  1399. }
  1400. }
  1401. return GRAPH_SUCCESS;
  1402. }
  1403. ///
  1404. /// Get reference-mapping of all data_anchors in graph
  1405. /// @param [in] graph
  1406. /// @param [out] symbol_to_anchors
  1407. /// @param [out] anchor_to_symbol
  1408. /// @return success: GRAPH_SUCESS
  1409. ///
  1410. graphStatus GraphUtils::GetRefMapping(const ComputeGraphPtr &graph,
  1411. std::map<std::string, std::list<NodeIndexIO>> &symbol_to_anchors,
  1412. std::map<std::string, std::string> &anchor_to_symbol) {
  1413. GE_CHECK_NOTNULL(graph);
  1414. for (const auto &node : graph->GetAllNodes()) {
  1415. // in_data_anchor
  1416. if (HandleInAnchorMapping(node, symbol_to_anchors, anchor_to_symbol) != GRAPH_SUCCESS) {
  1417. GE_LOGE("Find ref_mapping for in_data_anchors of node %s failed.", node->GetName().c_str());
  1418. return GRAPH_FAILED;
  1419. }
  1420. // out_data_anchor
  1421. if (HandleOutAnchorMapping(node, symbol_to_anchors, anchor_to_symbol) != GRAPH_SUCCESS) {
  1422. GE_LOGE("Find ref_mapping for out_data_anchors of node %s failed.", node->GetName().c_str());
  1423. return GRAPH_FAILED;
  1424. }
  1425. }
  1426. return GRAPH_SUCCESS;
  1427. }
  1428. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY NodePtr GraphUtils::FindNodeFromAllNodes(ComputeGraphPtr &graph,
  1429. const std::string &name) {
  1430. auto root_graph = FindRootGraph(graph);
  1431. if (root_graph == nullptr) {
  1432. GE_LOGE("Failed find node %s, null root graph", name.c_str());
  1433. return nullptr;
  1434. }
  1435. for (const auto &node : root_graph->GetAllNodes()) {
  1436. if (node == nullptr) {
  1437. continue;
  1438. }
  1439. if (node->GetName() == name) {
  1440. return node;
  1441. }
  1442. }
  1443. return nullptr;
  1444. }
  1445. ///
  1446. /// Get reference-mapping for in_data_anchors of node
  1447. /// @param [in] node
  1448. /// @param [out] symbol_to_anchors
  1449. /// @param [out] anchor_to_symbol
  1450. /// @return success: GRAPH_SUCESS
  1451. ///
  1452. graphStatus GraphUtils::HandleInAnchorMapping(const NodePtr &node,
  1453. std::map<std::string, std::list<NodeIndexIO>> &symbol_to_anchors,
  1454. std::map<std::string, std::string> &anchor_to_symbol) {
  1455. GE_CHECK_NOTNULL(node);
  1456. if (NodeUtils::IsSubgraphOutput(node)) {
  1457. return HandleSubgraphOutput(node, symbol_to_anchors, anchor_to_symbol);
  1458. }
  1459. if (NodeUtils::IsSubgraphInput(node)) {
  1460. return HandleSubgraphInput(node, symbol_to_anchors, anchor_to_symbol);
  1461. }
  1462. const std::string &type = node->GetType();
  1463. if ((type == MERGE) || (type == STREAMMERGE)) {
  1464. return HandleMergeInput(node, symbol_to_anchors, anchor_to_symbol);
  1465. }
  1466. for (const auto &in_data_anchor : node->GetAllInDataAnchors()) {
  1467. NodeIndexIO cur_node_info(node, in_data_anchor->GetIdx(), kIn);
  1468. OutDataAnchorPtr peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  1469. if (peer_out_anchor == nullptr) {
  1470. const std::string &symbol = cur_node_info.ToString();
  1471. GELOGD("Add anchor %s, symbol %s.", cur_node_info.ToString().c_str(), symbol.c_str());
  1472. symbol_to_anchors[symbol] = {cur_node_info};
  1473. anchor_to_symbol[symbol] = symbol;
  1474. } else {
  1475. NodeIndexIO exist_node_info(peer_out_anchor->GetOwnerNode(), peer_out_anchor->GetIdx(), kOut);
  1476. if (UpdateRefMapping(cur_node_info, exist_node_info, symbol_to_anchors, anchor_to_symbol) != GRAPH_SUCCESS) {
  1477. GE_LOGE("Update symbol mapping failed.");
  1478. return GRAPH_FAILED;
  1479. }
  1480. }
  1481. }
  1482. return GRAPH_SUCCESS;
  1483. }
  1484. ///
  1485. /// Get reference-mapping for out_data_anchors of node
  1486. /// @param [in] node
  1487. /// @param [out] symbol_to_anchors
  1488. /// @param [out] anchor_to_symbol
  1489. /// @return success: GRAPH_SUCESS
  1490. ///
  1491. graphStatus GraphUtils::HandleOutAnchorMapping(const NodePtr &node,
  1492. std::map<std::string, std::list<NodeIndexIO>> &symbol_to_anchors,
  1493. std::map<std::string, std::string> &anchor_to_symbol) {
  1494. GE_CHECK_NOTNULL(node);
  1495. for (const auto &out_data_anchor : node->GetAllOutDataAnchors()) {
  1496. NodeIndexIO cur_node_info(node, out_data_anchor->GetIdx(), kOut);
  1497. if (anchor_to_symbol.find(cur_node_info.ToString()) != anchor_to_symbol.end()) {
  1498. continue;
  1499. }
  1500. int32_t reuse_in_index = -1;
  1501. if (IsRefFromInput(out_data_anchor, reuse_in_index)) {
  1502. NodeIndexIO exist_node_info(node, reuse_in_index, kIn);
  1503. if (UpdateRefMapping(cur_node_info, exist_node_info, symbol_to_anchors, anchor_to_symbol) != GRAPH_SUCCESS) {
  1504. GE_LOGE("Update symbol mapping failed.");
  1505. return GRAPH_FAILED;
  1506. }
  1507. } else {
  1508. const std::string &symbol = cur_node_info.ToString();
  1509. GELOGD("Add anchor %s, symbol %s.", cur_node_info.ToString().c_str(), symbol.c_str());
  1510. symbol_to_anchors.emplace(std::make_pair(symbol, std::list<NodeIndexIO>{cur_node_info}));
  1511. anchor_to_symbol.emplace(std::make_pair(symbol, symbol));
  1512. }
  1513. }
  1514. return GRAPH_SUCCESS;
  1515. }
  1516. ///
  1517. /// Handle input of subgraph
  1518. /// @param [in] node
  1519. /// @param [out] symbol_to_anchors
  1520. /// @param [out] anchor_to_symbol
  1521. /// @return success: GRAPH_SUCESS
  1522. ///
  1523. graphStatus GraphUtils::HandleSubgraphInput(const NodePtr &node,
  1524. std::map<std::string, std::list<NodeIndexIO>> &symbol_to_anchors,
  1525. std::map<std::string, std::string> &anchor_to_symbol) {
  1526. GE_CHECK_NOTNULL(node);
  1527. GE_CHECK_NOTNULL(node->GetOpDesc());
  1528. // Data in subgraph
  1529. uint32_t index = 0;
  1530. if (!ge::AttrUtils::GetInt(node->GetOpDesc(), ATTR_NAME_PARENT_NODE_INDEX, index)) {
  1531. GE_LOGE("Get attr ATTR_NAME_PARENT_NODE_INDEX failed, node:%s.", node->GetName().c_str());
  1532. return GRAPH_FAILED;
  1533. }
  1534. NodePtr parent_node = node->GetOwnerComputeGraph()->GetParentNode();
  1535. GE_CHECK_NOTNULL(parent_node);
  1536. InDataAnchorPtr parent_in_anchor = parent_node->GetInDataAnchor(index);
  1537. GE_CHECK_NOTNULL(parent_in_anchor);
  1538. OutDataAnchorPtr peer_out_anchor = parent_in_anchor->GetPeerOutAnchor();
  1539. if (peer_out_anchor != nullptr) {
  1540. // Data has and only has one input
  1541. NodeIndexIO cur_node_info(node, 0, kIn);
  1542. NodeIndexIO exist_node_info(peer_out_anchor->GetOwnerNode(), peer_out_anchor->GetIdx(), kOut);
  1543. if (UpdateRefMapping(cur_node_info, exist_node_info, symbol_to_anchors, anchor_to_symbol) != GRAPH_SUCCESS) {
  1544. GE_LOGE("Update symbol mapping failed.");
  1545. return GRAPH_FAILED;
  1546. }
  1547. }
  1548. return GRAPH_SUCCESS;
  1549. }
  1550. ///
  1551. /// Handle input of Merge op
  1552. /// @param [in] node
  1553. /// @param [out] symbol_to_anchors
  1554. /// @param [out] anchor_to_symbol
  1555. /// @return success: GRAPH_SUCESS
  1556. ///
  1557. graphStatus GraphUtils::HandleMergeInput(const NodePtr &node,
  1558. std::map<std::string, std::list<NodeIndexIO>> &symbol_to_anchors,
  1559. std::map<std::string, std::string> &anchor_to_symbol) {
  1560. GE_CHECK_NOTNULL(node);
  1561. std::vector<NodeIndexIO> exist_node_infos;
  1562. std::vector<NodeIndexIO> cur_node_infos;
  1563. for (const auto &in_data_anchor : node->GetAllInDataAnchors()) {
  1564. auto peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  1565. if (peer_out_anchor == nullptr) {
  1566. std::string next_name;
  1567. if (AttrUtils::GetStr(node->GetOpDesc(), ATTR_NAME_NEXT_ITERATION, next_name) && !next_name.empty()) {
  1568. ComputeGraphPtr graph = node->GetOwnerComputeGraph();
  1569. GE_CHECK_NOTNULL(graph);
  1570. ge::NodePtr next_node = graph->FindNode(next_name);
  1571. GE_CHECK_NOTNULL(next_node);
  1572. // NextIteration has and only has one output
  1573. peer_out_anchor = next_node->GetOutDataAnchor(0);
  1574. GE_CHECK_NOTNULL(peer_out_anchor);
  1575. cur_node_infos.emplace_back(NodeIndexIO(node, in_data_anchor->GetIdx(), kIn));
  1576. cur_node_infos.emplace_back(NodeIndexIO(next_node, peer_out_anchor->GetIdx(), kOut));
  1577. }
  1578. } else {
  1579. cur_node_infos.emplace_back(NodeIndexIO(node, in_data_anchor->GetIdx(), kIn));
  1580. exist_node_infos.emplace_back(NodeIndexIO(peer_out_anchor->GetOwnerNode(), peer_out_anchor->GetIdx(), kOut));
  1581. }
  1582. }
  1583. size_t anchor_nums = 0;
  1584. NodeIndexIO max_node_index_io(nullptr, 0, kOut);
  1585. for (const auto &temp_node_info : exist_node_infos) {
  1586. auto iter1 = anchor_to_symbol.find(temp_node_info.ToString());
  1587. if (iter1 != anchor_to_symbol.end()) {
  1588. const std::string &temp_symbol = iter1->second;
  1589. auto iter2 = symbol_to_anchors.find(temp_symbol);
  1590. if (iter2 != symbol_to_anchors.end()) {
  1591. if (iter2->second.size() > anchor_nums) {
  1592. max_node_index_io = temp_node_info;
  1593. anchor_nums = iter2->second.size();
  1594. }
  1595. }
  1596. }
  1597. }
  1598. std::string symbol;
  1599. for (const auto &temp_node_info : exist_node_infos) {
  1600. if ((UnionSymbolMapping(max_node_index_io, temp_node_info, symbol_to_anchors, anchor_to_symbol, symbol) !=
  1601. GRAPH_SUCCESS) ||
  1602. symbol.empty()) {
  1603. GE_LOGE("Union symbol map anchor1:%s & anchor2:%s.", max_node_index_io.ToString().c_str(),
  1604. temp_node_info.ToString().c_str());
  1605. return GRAPH_FAILED;
  1606. }
  1607. }
  1608. auto iter = symbol_to_anchors.find(symbol);
  1609. if (iter != symbol_to_anchors.end()) {
  1610. for (const auto &temp_node_info : cur_node_infos) {
  1611. GELOGD("Add anchor %s, symbol %s.", temp_node_info.ToString().c_str(), symbol.c_str());
  1612. iter->second.emplace_back(temp_node_info);
  1613. anchor_to_symbol.emplace(std::make_pair(temp_node_info.ToString(), symbol));
  1614. }
  1615. }
  1616. return GRAPH_SUCCESS;
  1617. }
  1618. ///
  1619. /// Handle output of subgraph
  1620. /// @param [in] node
  1621. /// @param [out] symbol_to_anchors
  1622. /// @param [out] anchor_to_symbol
  1623. /// @return success: GRAPH_SUCESS
  1624. ///
  1625. graphStatus GraphUtils::HandleSubgraphOutput(const NodePtr &node,
  1626. std::map<std::string, std::list<NodeIndexIO>> &symbol_to_anchors,
  1627. std::map<std::string, std::string> &anchor_to_symbol) {
  1628. GE_CHECK_NOTNULL(node);
  1629. ComputeGraphPtr owner_graph = node->GetOwnerComputeGraph();
  1630. GE_CHECK_NOTNULL(owner_graph);
  1631. NodePtr parent_node = owner_graph->GetParentNode();
  1632. GE_CHECK_NOTNULL(parent_node);
  1633. OpDescPtr op_desc = node->GetOpDesc();
  1634. GE_CHECK_NOTNULL(op_desc);
  1635. for (const auto &in_data_anchor : node->GetAllInDataAnchors()) {
  1636. OutDataAnchorPtr peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  1637. GE_CHECK_NOTNULL(peer_out_anchor);
  1638. GeTensorDesc in_tensor = op_desc->GetInputDesc(in_data_anchor->GetIdx());
  1639. uint32_t index = 0;
  1640. if (!ge::AttrUtils::GetInt(in_tensor, ATTR_NAME_PARENT_NODE_INDEX, index)) {
  1641. continue;
  1642. }
  1643. GE_CHECK_NOTNULL(parent_node->GetOutDataAnchor(index));
  1644. // Union symbol of peer_out_anchor & parent_out_anchor
  1645. NodeIndexIO peer_node_info(peer_out_anchor->GetOwnerNode(), peer_out_anchor->GetIdx(), kOut);
  1646. NodeIndexIO parent_node_info(parent_node, index, kOut);
  1647. std::string symbol;
  1648. if ((UnionSymbolMapping(peer_node_info, parent_node_info, symbol_to_anchors, anchor_to_symbol, symbol) !=
  1649. GRAPH_SUCCESS) ||
  1650. symbol.empty()) {
  1651. GE_LOGE("Union symbol map anchor1:%s, anchor2:%s.", peer_node_info.ToString().c_str(),
  1652. parent_node_info.ToString().c_str());
  1653. return GRAPH_FAILED;
  1654. }
  1655. NodeIndexIO cur_node_info(node, in_data_anchor->GetIdx(), kIn);
  1656. GELOGD("Add anchor %s, symbol %s.", cur_node_info.ToString().c_str(), symbol.c_str());
  1657. symbol_to_anchors[symbol].emplace_back(cur_node_info);
  1658. anchor_to_symbol.emplace(std::make_pair(cur_node_info.ToString(), symbol));
  1659. }
  1660. return GRAPH_SUCCESS;
  1661. }
  1662. ///
  1663. /// Union ref-mapping
  1664. /// @param [in] exist_node_info1
  1665. /// @param [in] exist_node_info2
  1666. /// @param [out] symbol_to_anchors
  1667. /// @param [out] anchor_to_symbol
  1668. /// @param [out] symbol
  1669. /// @return success: GRAPH_SUCESS
  1670. ///
  1671. graphStatus GraphUtils::UnionSymbolMapping(const NodeIndexIO &exist_node_info1, const NodeIndexIO &exist_node_info2,
  1672. std::map<std::string, std::list<NodeIndexIO>> &symbol_to_anchors,
  1673. std::map<std::string, std::string> &anchor_to_symbol, std::string &symbol) {
  1674. const std::string &symbol1 = anchor_to_symbol[exist_node_info1.ToString()];
  1675. const std::string &symbol2 = anchor_to_symbol[exist_node_info2.ToString()];
  1676. if (symbol1 == symbol2) {
  1677. symbol = symbol1;
  1678. GELOGI("no need to union.");
  1679. return GRAPH_SUCCESS;
  1680. }
  1681. auto iter1 = symbol_to_anchors.find(symbol1);
  1682. auto iter2 = symbol_to_anchors.find(symbol2);
  1683. if ((iter1 == symbol_to_anchors.end()) || (iter2 == symbol_to_anchors.end())) {
  1684. GE_LOGE("symbol %s or %s not exist.", symbol1.c_str(), symbol2.c_str());
  1685. return GRAPH_FAILED;
  1686. }
  1687. auto &max_iter = (iter1->second.size() > iter2->second.size() ? iter1 : iter2);
  1688. auto &min_iter = (iter1->second.size() > iter2->second.size() ? iter2 : iter1);
  1689. symbol = (iter1->second.size() > iter2->second.size() ? symbol1 : symbol2);
  1690. std::string min_symbol = (iter1->second.size() > iter2->second.size() ? symbol2 : symbol1);
  1691. for (auto &node_index_io : min_iter->second) {
  1692. GELOGD("Update anchor %s, symbol %s.", node_index_io.ToString().c_str(), symbol.c_str());
  1693. max_iter->second.emplace_back(node_index_io);
  1694. auto iter = anchor_to_symbol.find(node_index_io.ToString());
  1695. if (iter == anchor_to_symbol.end()) {
  1696. GE_LOGE("anchor %s not exist.", node_index_io.ToString().c_str());
  1697. return GRAPH_FAILED;
  1698. }
  1699. if (iter->second != min_symbol) {
  1700. GELOGW("not expected symbol of anchor %s, expect %s but %s exactly.", iter->first.c_str(), min_symbol.c_str(),
  1701. iter->second.c_str());
  1702. }
  1703. iter->second = symbol;
  1704. }
  1705. GELOGI("Union symbol %s and %s succ.", symbol.c_str(), min_symbol.c_str());
  1706. symbol_to_anchors.erase(min_iter);
  1707. return GRAPH_SUCCESS;
  1708. }
  1709. ///
  1710. /// Update symbol mapping with a new reference pair
  1711. /// @param [in] cur_node_info
  1712. /// @param [in] exist_node_info
  1713. /// @param [out] symbol_to_anchors
  1714. /// @param [out] anchor_to_symbol
  1715. /// @return success: GRAPH_SUCESS
  1716. ///
  1717. graphStatus GraphUtils::UpdateRefMapping(const NodeIndexIO &cur_node_info, const NodeIndexIO &exist_node_info,
  1718. std::map<std::string, std::list<NodeIndexIO>> &symbol_to_anchors,
  1719. std::map<std::string, std::string> &anchor_to_symbol) {
  1720. auto iter1 = anchor_to_symbol.find(exist_node_info.ToString());
  1721. if (iter1 == anchor_to_symbol.end()) {
  1722. GE_LOGE("data_anchor %s is not visible before data_anchor %s, maybe TopoSorting is missing.",
  1723. exist_node_info.ToString().c_str(), cur_node_info.ToString().c_str());
  1724. return GRAPH_FAILED;
  1725. }
  1726. const std::string &symbol = iter1->second;
  1727. auto iter2 = symbol_to_anchors.find(symbol);
  1728. if (iter2 == symbol_to_anchors.end()) {
  1729. GE_LOGE("symbol %s not found.", symbol.c_str());
  1730. return GRAPH_FAILED;
  1731. }
  1732. GELOGD("Add anchor %s, symbol %s.", cur_node_info.ToString().c_str(), symbol.c_str());
  1733. iter2->second.emplace_back(cur_node_info);
  1734. anchor_to_symbol.emplace(std::make_pair(cur_node_info.ToString(), symbol));
  1735. return GRAPH_SUCCESS;
  1736. }
  1737. ///
  1738. /// Check if out_data_anchor is reference of input
  1739. /// @param [in] out_data_anchor
  1740. /// @param [out] reuse_in_index
  1741. /// @return bool
  1742. ///
  1743. bool GraphUtils::IsRefFromInput(const OutDataAnchorPtr &out_data_anchor, int32_t &reuse_in_index) {
  1744. if (out_data_anchor == nullptr) {
  1745. GELOGW("out_data_anchor is NULL.");
  1746. return false;
  1747. }
  1748. int32_t output_index = out_data_anchor->GetIdx();
  1749. // pass-through op
  1750. NodePtr node = out_data_anchor->GetOwnerNode();
  1751. const std::string &type = node->GetType();
  1752. const std::set<std::string> pass_through_set = {NETOUTPUT, WHILE, _WHILE, STATELESSWHILE};
  1753. if ((pass_through_set.count(type) > 0) || (NodeUtils::IsSubgraphInput(node))) {
  1754. reuse_in_index = output_index;
  1755. GELOGI("Pass-Through node name[%s] index[%u].", node->GetName().c_str(), reuse_in_index);
  1756. return true;
  1757. }
  1758. // Merge op 0th output
  1759. if ((type == MERGE) && (output_index == 0)) {
  1760. reuse_in_index = 0;
  1761. GELOGI("Merge name[%s] output_index[0].", node->GetName().c_str());
  1762. return true;
  1763. }
  1764. // ref op
  1765. OpDescPtr op_desc = node->GetOpDesc();
  1766. if (op_desc == nullptr) {
  1767. GELOGW("op_desc is NULL.");
  1768. return false;
  1769. }
  1770. bool is_ref = false;
  1771. (void)ge::AttrUtils::GetBool(op_desc, ATTR_NAME_REFERENCE, is_ref);
  1772. if (is_ref) {
  1773. const string &output_name = op_desc->GetOutputNameByIndex(output_index);
  1774. for (const auto &input_name : op_desc->GetAllInputNames()) {
  1775. if (!input_name.empty() && (output_name == input_name)) {
  1776. reuse_in_index = op_desc->GetInputIndexByName(input_name);
  1777. GELOGI("Reference name[%s] output[%s][%d] ref to input[%s][%d].", op_desc->GetName().c_str(),
  1778. output_name.c_str(), output_index, input_name.c_str(), reuse_in_index);
  1779. return true;
  1780. }
  1781. }
  1782. }
  1783. // reuse input
  1784. auto output_op_desc = op_desc->GetOutputDescPtr(output_index);
  1785. bool reuse_input = false;
  1786. if (output_op_desc != nullptr) {
  1787. if ((TensorUtils::GetReuseInput(*output_op_desc, reuse_input) == GRAPH_SUCCESS) && reuse_input) {
  1788. uint32_t reuse_input_index = 0;
  1789. if (TensorUtils::GetReuseInputIndex(*output_op_desc, reuse_input_index) == GRAPH_SUCCESS) {
  1790. reuse_in_index = static_cast<int32_t>(reuse_input_index);
  1791. GELOGI("ReuseInput name[%s] output[%d] reuse input[%d].", op_desc->GetName().c_str(), output_index,
  1792. reuse_in_index);
  1793. return true;
  1794. }
  1795. }
  1796. }
  1797. return false;
  1798. }
  1799. ///
  1800. /// Determine if the graph is a UNKNOWN_SHAPE graph based on whether the graph and all subgraphs
  1801. /// of the graph have UNKNOWN_SHAPE operators or not.
  1802. /// Note: This function will only look 'down' from the graph, not 'up'. For example, the following
  1803. /// scenario (K for known shape, U for unknown shape), ROOT graph is UNKNOWN_SHAPE while SUB graph is KNOWN_SHAPE
  1804. /// ROOT graph: A -----> B -----> C
  1805. /// K subgraph U
  1806. /// |
  1807. /// V
  1808. /// SUB graph: D --> E --> F
  1809. /// K K K
  1810. /// @param [in] graph
  1811. /// @return bool
  1812. ///
  1813. bool GraphUtils::IsUnknownShapeGraph(const ComputeGraphPtr &graph) {
  1814. if (graph == nullptr) {
  1815. GELOGW("Input graph is nullptr.");
  1816. return false;
  1817. }
  1818. for (const auto &node : graph->GetDirectNode()) {
  1819. bool is_unknown = false;
  1820. auto ret = NodeUtils::GetNodeUnknownShapeStatus(*node, is_unknown);
  1821. if (ret != GRAPH_SUCCESS) {
  1822. GELOGW("Get node unknown status failed, node name:%s, type:%s.", node->GetName().c_str(),
  1823. node->GetType().c_str());
  1824. continue;
  1825. }
  1826. if (is_unknown) {
  1827. GELOGD("Node %s, type %s is unknown shape in graph %s.", node->GetName().c_str(), node->GetType().c_str(),
  1828. graph->GetName().c_str());
  1829. return true;
  1830. }
  1831. }
  1832. GELOGD("Graph %s does not have unknown shape node.", graph->GetName().c_str());
  1833. return false;
  1834. }
  1835. ///
  1836. /// @brief Add node to graph
  1837. /// @param [in] op_desc
  1838. /// @return ComputeGraphBuilder
  1839. ///
  1840. ComputeGraphBuilder &ComputeGraphBuilder::AddNode(const OpDescPtr &op_desc) {
  1841. nodes_.emplace_back(op_desc);
  1842. return *this;
  1843. }
  1844. ///
  1845. /// @brief Add data-link among nodes in graph
  1846. /// @param [in] src_name
  1847. /// @param [in] out_anchor_ind
  1848. /// @param [in] dst_name
  1849. /// @param [in] in_anchor_ind
  1850. /// @return ComputeGraphBuilder
  1851. ///
  1852. ComputeGraphBuilder &ComputeGraphBuilder::AddDataLink(const std::string &src_name, uint32_t out_anchor_ind,
  1853. const std::string &dst_name, uint32_t in_anchor_ind) {
  1854. data_links_.emplace_back(
  1855. std::make_pair(std::make_pair(src_name, out_anchor_ind), std::make_pair(dst_name, in_anchor_ind)));
  1856. return *this;
  1857. }
  1858. ///
  1859. /// @brief Add ctrl-link among nodes in graph
  1860. /// @param [in] src_name
  1861. /// @param [in] dst_name
  1862. /// @return ComputeGraphBuilder
  1863. ///
  1864. ComputeGraphBuilder &ComputeGraphBuilder::AddControlLink(const std::string &src_name, const std::string &dst_name) {
  1865. ctrl_links_.emplace_back(std::make_pair(src_name, dst_name));
  1866. return *this;
  1867. }
  1868. ///
  1869. /// @brief Build nodes
  1870. /// @param [out] error_code
  1871. /// @param [out] error_msg
  1872. /// @return void
  1873. ///
  1874. void ComputeGraphBuilder::BuildNodes(graphStatus &error_code, std::string &error_msg) {
  1875. if (owner_graph_ == nullptr) {
  1876. error_code = GRAPH_FAILED;
  1877. error_msg = "graph is NULL.";
  1878. return;
  1879. }
  1880. std::string node_name;
  1881. for (auto &op_desc : nodes_) {
  1882. if (op_desc == nullptr) {
  1883. error_code = GRAPH_FAILED;
  1884. error_msg = "op_desc is NULL.";
  1885. return;
  1886. }
  1887. node_name = op_desc->GetName();
  1888. NodePtr node = owner_graph_->AddNode(op_desc);
  1889. if (node == nullptr) {
  1890. error_code = GRAPH_FAILED;
  1891. error_msg = "Add node " + node_name + " failed.";
  1892. return;
  1893. }
  1894. GELOGD("Add node name:%s, type:%s.", node_name.c_str(), op_desc->GetType().c_str());
  1895. node_names_[node_name] = node;
  1896. }
  1897. GELOGD("BuildNodes succ.");
  1898. }
  1899. ///
  1900. /// @brief Build data-links
  1901. /// @param [out] error_code
  1902. /// @param [out] error_msg
  1903. /// @return void
  1904. ///
  1905. void ComputeGraphBuilder::BuildDataLinks(graphStatus &error_code, std::string &error_msg) {
  1906. for (auto &pair : data_links_) {
  1907. std::string src_name = pair.first.first;
  1908. uint32_t out_ind = pair.first.second;
  1909. std::string dst_name = pair.second.first;
  1910. uint32_t in_ind = pair.second.second;
  1911. std::string log_msg = "Add data-edge ";
  1912. log_msg.append(src_name)
  1913. .append(":")
  1914. .append(std::to_string(out_ind))
  1915. .append("->")
  1916. .append(dst_name)
  1917. .append(":")
  1918. .append(std::to_string(in_ind));
  1919. auto src_iter = node_names_.find(src_name);
  1920. auto dst_iter = node_names_.find(dst_name);
  1921. if ((src_iter == node_names_.end()) || (dst_iter == node_names_.end())) {
  1922. error_code = GRAPH_FAILED;
  1923. error_msg = log_msg + " failed: node not exist in graph.";
  1924. return;
  1925. }
  1926. NodePtr src_node = node_names_[src_name];
  1927. NodePtr dst_node = node_names_[dst_name];
  1928. if ((src_node == nullptr) || (dst_node == nullptr)) {
  1929. error_code = GRAPH_FAILED;
  1930. error_msg = log_msg + " failed: node is NULL.";
  1931. return;
  1932. }
  1933. if (GraphUtils::AddEdge(src_node->GetOutDataAnchor(out_ind), dst_node->GetInDataAnchor(in_ind)) != GRAPH_SUCCESS) {
  1934. error_code = GRAPH_FAILED;
  1935. error_msg = log_msg + " failed.";
  1936. return;
  1937. }
  1938. GELOGD("%s succ.", log_msg.c_str());
  1939. }
  1940. GELOGD("BuildDataLinks succ.");
  1941. }
  1942. ///
  1943. /// @brief Build ctrl-links
  1944. /// @param [out] error_code
  1945. /// @param [out] error_msg
  1946. /// @return void
  1947. ///
  1948. void ComputeGraphBuilder::BuildCtrlLinks(graphStatus &error_code, std::string &error_msg) {
  1949. for (auto &pair : ctrl_links_) {
  1950. std::string src_name = pair.first;
  1951. std::string dst_name = pair.second;
  1952. std::string log_msg = "Add ctrl-edge ";
  1953. log_msg.append(src_name).append("->").append(dst_name);
  1954. auto src_iter = node_names_.find(src_name);
  1955. auto dst_iter = node_names_.find(dst_name);
  1956. if ((src_iter == node_names_.end()) || (dst_iter == node_names_.end())) {
  1957. error_code = GRAPH_FAILED;
  1958. error_msg = log_msg + " failed: node not exist in graph.";
  1959. return;
  1960. }
  1961. NodePtr src_node = node_names_[src_name];
  1962. NodePtr dst_node = node_names_[dst_name];
  1963. if ((src_node == nullptr) || (dst_node == nullptr)) {
  1964. error_code = GRAPH_FAILED;
  1965. error_msg = log_msg + " failed: node is NULL.";
  1966. return;
  1967. }
  1968. if (GraphUtils::AddEdge(src_node->GetOutControlAnchor(), dst_node->GetInControlAnchor()) != GRAPH_SUCCESS) {
  1969. error_code = GRAPH_FAILED;
  1970. error_msg = log_msg + " failed.";
  1971. return;
  1972. }
  1973. GELOGD("%s succ.", log_msg.c_str());
  1974. }
  1975. GELOGD("BuildCtrlLinks succ.");
  1976. }
  1977. /// @brief Get node with name
  1978. /// @param [in] name
  1979. /// @return NodePtr
  1980. ///
  1981. NodePtr ComputeGraphBuilder::GetNode(const std::string &name) {
  1982. auto iter = node_names_.find(name);
  1983. if (iter == node_names_.end()) {
  1984. GE_LOGE("node %s not exist.", name.c_str());
  1985. return nullptr;
  1986. }
  1987. return iter->second;
  1988. }
  1989. /// @brief Get all nodes
  1990. /// @return std::vector<NodePtr>
  1991. ///
  1992. std::vector<NodePtr> ComputeGraphBuilder::GetAllNodes() {
  1993. std::vector<NodePtr> nodes;
  1994. for (const auto &iter : node_names_) {
  1995. nodes.emplace_back(iter.second);
  1996. }
  1997. return nodes;
  1998. }
  1999. ///
  2000. /// @brief Add node to graph
  2001. /// @param [in] op_desc
  2002. /// @return CompleteGraphBuilder
  2003. ///
  2004. CompleteGraphBuilder &CompleteGraphBuilder::AddNode(const OpDescPtr &op_desc) {
  2005. ComputeGraphBuilder::AddNode(op_desc);
  2006. return *this;
  2007. }
  2008. ///
  2009. /// @brief Add data-link among nodes in graph
  2010. /// @param [in] src_name
  2011. /// @param [in] out_anchor_ind
  2012. /// @param [in] dst_name
  2013. /// @param [in] in_anchor_ind
  2014. /// @return CompleteGraphBuilder
  2015. ///
  2016. CompleteGraphBuilder &CompleteGraphBuilder::AddDataLink(const std::string &src_name, uint32_t out_anchor_ind,
  2017. const std::string &dst_name, uint32_t in_anchor_ind) {
  2018. ComputeGraphBuilder::AddDataLink(src_name, out_anchor_ind, dst_name, in_anchor_ind);
  2019. return *this;
  2020. }
  2021. ///
  2022. /// @brief Add ctrl-link among nodes in graph
  2023. /// @param [in] src_name
  2024. /// @param [in] dst_name
  2025. /// @return CompleteGraphBuilder
  2026. ///
  2027. CompleteGraphBuilder &CompleteGraphBuilder::AddControlLink(const std::string &src_name, const std::string &dst_name) {
  2028. ComputeGraphBuilder::AddControlLink(src_name, dst_name);
  2029. return *this;
  2030. }
  2031. ///
  2032. /// @brief Set index_th input anchor for graph
  2033. /// @param [in] index
  2034. /// @param [in] node_names
  2035. /// @param [in] anchor_inds
  2036. /// @return CompleteGraphBuilder
  2037. ///
  2038. CompleteGraphBuilder &CompleteGraphBuilder::SetInput(uint32_t index, const std::vector<std::string> &node_names,
  2039. const std::vector<uint32_t> &anchor_inds) {
  2040. graph_inputs_[index] = std::make_pair(node_names, anchor_inds);
  2041. return *this;
  2042. }
  2043. ///
  2044. /// @brief Set index_th input of graph as useless
  2045. /// @param [in] index
  2046. /// @return CompleteGraphBuilder
  2047. ///
  2048. CompleteGraphBuilder &CompleteGraphBuilder::SetUselessInput(uint32_t index) {
  2049. graph_inputs_[index] = std::make_pair(std::vector<std::string>(), std::vector<uint32_t>());
  2050. return *this;
  2051. }
  2052. ///
  2053. /// @brief Add output anchor for graph
  2054. /// @param [in] owner_node_name
  2055. /// @param [in] anchor_ind
  2056. /// @return CompleteGraphBuilder
  2057. ///
  2058. CompleteGraphBuilder &CompleteGraphBuilder::AddOutput(const std::string &owner_node_name, uint32_t anchor_ind) {
  2059. graph_outputs_.emplace_back(std::make_pair(owner_node_name, anchor_ind));
  2060. return *this;
  2061. }
  2062. ///
  2063. /// @brief Add target for graph
  2064. /// @param [in] target_name
  2065. /// @return CompleteGraphBuilder
  2066. ///
  2067. CompleteGraphBuilder &CompleteGraphBuilder::AddTarget(const std::string &target_name) {
  2068. graph_targets_.emplace_back(target_name);
  2069. return *this;
  2070. }
  2071. ///
  2072. /// @brief Set parent-node of graph
  2073. /// @param [in] parent_node
  2074. /// @return CompleteGraphBuilder
  2075. ///
  2076. CompleteGraphBuilder &CompleteGraphBuilder::SetParentNode(const NodePtr &parent_node) {
  2077. parent_node_ = parent_node;
  2078. return *this;
  2079. }
  2080. ///
  2081. /// @brief Set mapping-relation of parent-node in_anchor_ind & Data-node
  2082. /// @param [in] input_mapping: index_of_graph_input -> in_anchor_index_of_parent_node
  2083. /// @return CompleteGraphBuilder
  2084. ///
  2085. CompleteGraphBuilder &CompleteGraphBuilder::SetInputMapping(const std::map<uint32_t, uint32_t> &input_mapping) {
  2086. for (auto &item : input_mapping) {
  2087. input_mapping_[item.first] = item.second;
  2088. }
  2089. return *this;
  2090. }
  2091. ///
  2092. /// @brief Set mapping-relation of parent-node out_anchor_ind & NetOutput-node out_anchor_ind
  2093. /// @param [in] output_mapping: index_of_graph_output -> out_anchor_index_of_parent_node
  2094. /// @return CompleteGraphBuilder
  2095. ///
  2096. CompleteGraphBuilder &CompleteGraphBuilder::SetOutputMapping(const std::map<uint32_t, uint32_t> &output_mapping) {
  2097. for (auto &item : output_mapping) {
  2098. output_mapping_[item.first] = item.second;
  2099. }
  2100. return *this;
  2101. }
  2102. ///
  2103. /// @brief Build graph
  2104. /// @param [out] error_code
  2105. /// @param [out] error_msg
  2106. /// @return ComputeGraphPtr
  2107. ///
  2108. ComputeGraphPtr CompleteGraphBuilder::Build(graphStatus &error_code, std::string &error_msg) {
  2109. owner_graph_ = shared_ptr<ComputeGraph>(new (std::nothrow) ComputeGraph(name_));
  2110. if ((owner_graph_ == nullptr) || (parent_node_ == nullptr)) {
  2111. error_code = GRAPH_FAILED;
  2112. error_msg = "graph / parent_node is NULL.";
  2113. return nullptr;
  2114. }
  2115. owner_graph_->SetParentNode(parent_node_);
  2116. owner_graph_->SetParentGraph(parent_node_->GetOwnerComputeGraph());
  2117. BuildNodes(error_code, error_msg);
  2118. if (error_code != GRAPH_SUCCESS) {
  2119. return nullptr;
  2120. }
  2121. BuildDataLinks(error_code, error_msg);
  2122. if (error_code != GRAPH_SUCCESS) {
  2123. return nullptr;
  2124. }
  2125. BuildCtrlLinks(error_code, error_msg);
  2126. if (error_code != GRAPH_SUCCESS) {
  2127. return nullptr;
  2128. }
  2129. AddDataNodes(error_code, error_msg);
  2130. if (error_code != GRAPH_SUCCESS) {
  2131. return nullptr;
  2132. }
  2133. AddRetValNodes(error_code, error_msg);
  2134. if (error_code != GRAPH_SUCCESS) {
  2135. return nullptr;
  2136. }
  2137. BuildGraphTargets(error_code, error_msg);
  2138. if (error_code != GRAPH_SUCCESS) {
  2139. return nullptr;
  2140. }
  2141. // ATTR_NAME_SESSION_GRAPH_ID
  2142. std::string graph_id;
  2143. if (!AttrUtils::GetStr(parent_node_->GetOwnerComputeGraph(), ATTR_NAME_SESSION_GRAPH_ID, graph_id)) {
  2144. error_code = GRAPH_FAILED;
  2145. error_msg = "Get attr session_graph_id failed.";
  2146. return nullptr;
  2147. }
  2148. if (!AttrUtils::SetStr(owner_graph_, ATTR_NAME_SESSION_GRAPH_ID, graph_id)) {
  2149. error_code = GRAPH_FAILED;
  2150. error_msg = "Set attr session_graph_id failed.";
  2151. return nullptr;
  2152. }
  2153. // refresh node name
  2154. for (const NodePtr &node : owner_graph_->GetDirectNode()) {
  2155. if ((node->GetOpDesc() == nullptr) || (node->GetType() == VARIABLE) || (node->GetType() == VARIABLEV2)) {
  2156. continue;
  2157. }
  2158. node->GetOpDesc()->SetName(owner_graph_->GetName() + "/" + node->GetName());
  2159. }
  2160. return owner_graph_;
  2161. }
  2162. ///
  2163. /// @brief Add data nodes
  2164. /// @param [out] error_code
  2165. /// @param [out] error_msg
  2166. /// @return void
  2167. ///
  2168. void CompleteGraphBuilder::AddDataNodes(graphStatus &error_code, std::string &error_msg) {
  2169. for (auto &input : graph_inputs_) {
  2170. NodePtr data_node = AddDataNode(input.first, error_code, error_msg);
  2171. if (data_node == nullptr) {
  2172. error_code = GRAPH_FAILED;
  2173. error_msg = "AddDataNodes failed: add node Data:" + std::to_string(input.first) + +" failed.";
  2174. return;
  2175. }
  2176. if (owner_graph_->AddInputNode(data_node) == nullptr) {
  2177. error_code = GRAPH_FAILED;
  2178. error_msg = "AddDataNodes failed: add input node Data:" + std::to_string(input.first) + +" failed.";
  2179. return;
  2180. }
  2181. // useless input
  2182. std::vector<std::string> input_names = input.second.first;
  2183. std::vector<uint32_t> anchor_indes = input.second.second;
  2184. if (input_names.size() != anchor_indes.size()) {
  2185. error_code = GRAPH_FAILED;
  2186. error_msg = "AddDataNodes failed: num of input_names and indexs not equal.";
  2187. return;
  2188. }
  2189. if (input_names.empty()) {
  2190. continue;
  2191. }
  2192. size_t input_num = input_names.size();
  2193. for (size_t i = 0; i < input_num; i++) {
  2194. std::string input_name = input_names[i];
  2195. uint32_t ind = anchor_indes[i];
  2196. auto iter = node_names_.find(input_name);
  2197. if (iter == node_names_.end()) {
  2198. error_code = GRAPH_FAILED;
  2199. error_msg = "AddDataNodes failed: node " + input_name + " not exist in graph.";
  2200. return;
  2201. }
  2202. NodePtr in_node = node_names_[input_name];
  2203. if (in_node == nullptr) {
  2204. error_code = GRAPH_FAILED;
  2205. error_msg = "AddDataNodes failed: node " + input_name + " is NULL.";
  2206. return;
  2207. }
  2208. if (GraphUtils::AddEdge(data_node->GetOutDataAnchor(0), in_node->GetInDataAnchor(ind)) != GRAPH_SUCCESS) {
  2209. error_code = GRAPH_FAILED;
  2210. error_msg = "AddDataNodes failed: add data-edge Data:" + std::to_string(input.first) + ":0->" + input_name +
  2211. ":" + std::to_string(ind) + " failed.";
  2212. return;
  2213. }
  2214. }
  2215. GELOGD("AddDataNodes : Add %u input succ.", input.first);
  2216. }
  2217. GELOGD("AddDataNodes succ.");
  2218. }
  2219. ///
  2220. /// @brief Add data node
  2221. /// @param [in] index
  2222. /// @param [out] error_code
  2223. /// @param [out] error_msg
  2224. /// @return void
  2225. ///
  2226. NodePtr CompleteGraphBuilder::AddDataNode(uint32_t index, graphStatus &error_code, std::string &error_msg) {
  2227. std::string data_name = "Data_" + std::to_string(index);
  2228. OpDescBuilder op_desc_builder(data_name, "Data");
  2229. OpDescPtr op_desc = op_desc_builder.AddInput("x").AddOutput("y").Build();
  2230. if (op_desc == nullptr) {
  2231. error_code = GRAPH_FAILED;
  2232. error_msg = "AddDataNode failed: create op_desc " + data_name + " failed.";
  2233. return nullptr;
  2234. }
  2235. auto index_iter = input_mapping_.find(index);
  2236. if (index_iter != input_mapping_.end()) {
  2237. if (!ge::AttrUtils::SetInt(op_desc, ATTR_NAME_PARENT_NODE_INDEX, index_iter->second)) {
  2238. error_code = GRAPH_FAILED;
  2239. error_msg = "AddDataNode failed: set attr ATTR_NAME_PARENT_NODE_INDEX for " + data_name + " failed.";
  2240. return nullptr;
  2241. }
  2242. }
  2243. NodePtr data_node = owner_graph_->AddNode(op_desc);
  2244. if (data_node == nullptr) {
  2245. error_code = GRAPH_FAILED;
  2246. error_msg = "AddDataNode failed: add node " + data_name + " failed.";
  2247. return nullptr;
  2248. }
  2249. node_names_[data_name] = data_node;
  2250. return data_node;
  2251. }
  2252. ///
  2253. /// @brief Add RetVal nodes
  2254. /// @param [out] error_code
  2255. /// @param [out] error_msg
  2256. /// @return void
  2257. ///
  2258. void CompleteGraphBuilder::AddRetValNodes(graphStatus &error_code, std::string &error_msg) {
  2259. size_t output_num = graph_outputs_.size();
  2260. for (size_t i = 0; i < output_num; i++) {
  2261. int32_t index = graph_outputs_[i].second;
  2262. auto out_iter = node_names_.find(graph_outputs_[i].first);
  2263. if (out_iter == node_names_.end()) {
  2264. error_code = GRAPH_FAILED;
  2265. error_msg = "AddRetValNode failed: node " + graph_outputs_[i].first + " not exist in graph.";
  2266. return;
  2267. }
  2268. NodePtr node = out_iter->second;
  2269. if ((node == nullptr) || (node->GetOpDesc() == nullptr)) {
  2270. error_code = GRAPH_FAILED;
  2271. error_msg = "AddRetValNode failed: node is NULL.";
  2272. return;
  2273. }
  2274. std::string name = node->GetName() + "_RetVal_" + std::to_string(index);
  2275. OpDescPtr ret_val_desc = shared_ptr<OpDesc>(new (std::nothrow) OpDesc(name, FRAMEWORKOP));
  2276. if (ret_val_desc == nullptr) {
  2277. error_code = GRAPH_FAILED;
  2278. error_msg = "AddRetValNode " + name + " failed: op_desc is NULL.";
  2279. return;
  2280. }
  2281. ge::GeTensorDesc tensor = node->GetOpDesc()->GetOutputDesc(index);
  2282. if ((ret_val_desc->AddInputDesc(tensor) != GRAPH_SUCCESS) ||
  2283. (ret_val_desc->AddOutputDesc(tensor) != GRAPH_SUCCESS)) {
  2284. error_code = GRAPH_FAILED;
  2285. error_msg = "AddRetValNode " + name + " failed: add input_desc / output_desc failed.";
  2286. return;
  2287. }
  2288. if (!(ge::AttrUtils::SetStr(ret_val_desc, ATTR_NAME_FRAMEWORK_ORIGINAL_TYPE, "_RetVal") &&
  2289. ge::AttrUtils::SetInt(ret_val_desc, RETVAL_ATTR_NAME_INDEX, i))) {
  2290. error_code = GRAPH_FAILED;
  2291. error_msg = "AddRetValNode " + name + " failed: set FRAMEWORK_ORIGINAL_TYPE / RETVAL_ATTR_NAME_INDEX failed.";
  2292. return;
  2293. }
  2294. auto iter = output_mapping_.find(i);
  2295. if (iter != output_mapping_.end()) {
  2296. if (!ge::AttrUtils::SetInt(ret_val_desc, ATTR_NAME_PARENT_NODE_INDEX, iter->second)) {
  2297. error_code = GRAPH_FAILED;
  2298. error_msg = "AddRetValNode " + name + " failed: set attr PARENT_NODE_INDEX failed.";
  2299. return;
  2300. }
  2301. }
  2302. NodePtr ret_val_node = owner_graph_->AddNode(ret_val_desc);
  2303. if (ret_val_node == nullptr) {
  2304. error_code = GRAPH_FAILED;
  2305. error_msg = "AddRetValNode " + name + " failed: add node failed.";
  2306. return;
  2307. }
  2308. if (GraphUtils::AddEdge(node->GetOutDataAnchor(index), ret_val_node->GetInDataAnchor(0)) != GRAPH_SUCCESS) {
  2309. error_code = GRAPH_FAILED;
  2310. error_msg = "AddRetValNode " + name + " failed: add data-edge " + node->GetName() + ":" + std::to_string(index) +
  2311. "->" + ret_val_node->GetName() + ":0 failed.";
  2312. return;
  2313. }
  2314. }
  2315. GELOGD("AddRetValNodes succ.");
  2316. }
  2317. ///
  2318. /// @brief Build target-nodes for graph
  2319. /// @param [out] error_code
  2320. /// @param [out] error_msg
  2321. /// @return void
  2322. ///
  2323. void CompleteGraphBuilder::BuildGraphTargets(graphStatus &error_code, std::string &error_msg) {
  2324. std::vector<NodePtr> target_nodes;
  2325. for (const std::string &target_name : graph_targets_) {
  2326. auto target_iter = node_names_.find(target_name);
  2327. if ((target_iter == node_names_.end()) || (target_iter->second == nullptr)) {
  2328. error_code = GRAPH_FAILED;
  2329. error_msg = "BuildGraphTargets failed: target_node " + target_name + " not exist in graph.";
  2330. return;
  2331. }
  2332. target_nodes.emplace_back(target_iter->second);
  2333. }
  2334. owner_graph_->SetGraphTargetNodesInfo(target_nodes);
  2335. return;
  2336. }
  2337. ///
  2338. /// @brief Add node to graph
  2339. /// @param [in] op_desc
  2340. /// @return PartialGraphBuilder
  2341. ///
  2342. PartialGraphBuilder &PartialGraphBuilder::AddNode(const OpDescPtr &op_desc) {
  2343. ComputeGraphBuilder::AddNode(op_desc);
  2344. return *this;
  2345. }
  2346. ///
  2347. /// @brief Add data-link among nodes in graph
  2348. /// @param [in] src_name
  2349. /// @param [in] out_anchor_ind
  2350. /// @param [in] dst_name
  2351. /// @param [in] in_anchor_ind
  2352. /// @return PartialGraphBuilder
  2353. ///
  2354. PartialGraphBuilder &PartialGraphBuilder::AddDataLink(const std::string &src_name, uint32_t out_anchor_ind,
  2355. const std::string &dst_name, uint32_t in_anchor_ind) {
  2356. ComputeGraphBuilder::AddDataLink(src_name, out_anchor_ind, dst_name, in_anchor_ind);
  2357. return *this;
  2358. }
  2359. ///
  2360. /// @brief Add ctrl-link among nodes in graph
  2361. /// @param [in] src_name
  2362. /// @param [in] dst_name
  2363. /// @return PartialGraphBuilder
  2364. ///
  2365. PartialGraphBuilder &PartialGraphBuilder::AddControlLink(const std::string &src_name, const std::string &dst_name) {
  2366. ComputeGraphBuilder::AddControlLink(src_name, dst_name);
  2367. return *this;
  2368. }
  2369. ///
  2370. /// @brief Set owner graph
  2371. /// @param [in] graph
  2372. /// @return PartialGraphBuilder
  2373. ///
  2374. PartialGraphBuilder &PartialGraphBuilder::SetOwnerGraph(const ComputeGraphPtr &graph) {
  2375. owner_graph_ = graph;
  2376. return *this;
  2377. }
  2378. ///
  2379. /// @brief Add exist node
  2380. /// @param [in] node
  2381. /// @return PartialGraphBuilder
  2382. ///
  2383. PartialGraphBuilder &PartialGraphBuilder::AddExistNode(const NodePtr &node) {
  2384. exist_nodes_.emplace_back(node);
  2385. return *this;
  2386. }
  2387. ///
  2388. /// @brief Build partial graph
  2389. /// @param [out] error_code
  2390. /// @param [out] error_msg
  2391. /// @return ComputeGraphPtr
  2392. ///
  2393. ComputeGraphPtr PartialGraphBuilder::Build(graphStatus &error_code, std::string &error_msg) {
  2394. if (owner_graph_ == nullptr) {
  2395. error_code = GRAPH_FAILED;
  2396. error_msg = "graph is NULL.";
  2397. return nullptr;
  2398. }
  2399. BuildNodes(error_code, error_msg);
  2400. if (error_code != GRAPH_SUCCESS) {
  2401. return nullptr;
  2402. }
  2403. BuildExistNodes(error_code, error_msg);
  2404. if (error_code != GRAPH_SUCCESS) {
  2405. return nullptr;
  2406. }
  2407. BuildDataLinks(error_code, error_msg);
  2408. if (error_code != GRAPH_SUCCESS) {
  2409. return nullptr;
  2410. }
  2411. BuildCtrlLinks(error_code, error_msg);
  2412. if (error_code != GRAPH_SUCCESS) {
  2413. return nullptr;
  2414. }
  2415. return owner_graph_;
  2416. }
  2417. ///
  2418. /// @brief Build exist nodes
  2419. /// @param [out] error_code
  2420. /// @param [out] error_msg
  2421. /// @return void
  2422. ///
  2423. void PartialGraphBuilder::BuildExistNodes(graphStatus &error_code, std::string &error_msg) {
  2424. std::string node_name;
  2425. for (auto &node : exist_nodes_) {
  2426. if (node == nullptr) {
  2427. error_code = GRAPH_FAILED;
  2428. error_msg = "Build exist nodes failed: node is NULL.";
  2429. return;
  2430. }
  2431. node_name = node->GetName();
  2432. if (node->GetOwnerComputeGraph() != owner_graph_) {
  2433. error_code = GRAPH_FAILED;
  2434. error_msg = "Build exist nodes failed: node " + node_name + " not belongs to this graph.";
  2435. return;
  2436. }
  2437. GELOGD("Add exist_node name:%s.", node_name.c_str());
  2438. node_names_[node_name] = node;
  2439. }
  2440. GELOGD("Build exist nodes succ.");
  2441. }
  2442. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus
  2443. GraphUtils::TopologicalSortingByName(const ge::ComputeGraphPtr &compute_graph, vector<NodePtr> &node_vec) {
  2444. std::vector<NodePtr> stack_input;
  2445. std::map<NodePtr, uint32_t> map_in_edge_num;
  2446. graphStatus ret = compute_graph->SortNodes(stack_input, map_in_edge_num);
  2447. if (ret != GRAPH_SUCCESS) {
  2448. GELOGE(GRAPH_FAILED, "Sort nodes failed.");
  2449. return GRAPH_FAILED;
  2450. }
  2451. const size_t non_user_input_index = stack_input.size() - compute_graph->inputs_order_.size() - 1;
  2452. std::sort(stack_input.begin(), stack_input.begin() + non_user_input_index,
  2453. [](const NodePtr &a, const NodePtr &b) -> bool { return (a->GetName() > b->GetName()); });
  2454. std::queue<NodePtr> stack;
  2455. NodePtr cur_node = nullptr;
  2456. std::map<string, NodePtr> name_node_map;
  2457. vector<string> nodes_name;
  2458. while (!stack_input.empty() || !stack.empty()) {
  2459. if (!stack.empty()) {
  2460. cur_node = stack.front();
  2461. stack.pop();
  2462. } else {
  2463. cur_node = stack_input.back();
  2464. stack_input.pop_back();
  2465. }
  2466. node_vec.emplace_back(cur_node);
  2467. compute_graph->CollectBreadthOutNode(cur_node, map_in_edge_num, name_node_map);
  2468. for (const auto &iter : name_node_map) {
  2469. nodes_name.emplace_back(iter.first);
  2470. }
  2471. std::sort(nodes_name.begin(), nodes_name.end());
  2472. for (const auto &iter : nodes_name) {
  2473. stack.push(name_node_map[iter]);
  2474. }
  2475. name_node_map.clear();
  2476. nodes_name.clear();
  2477. }
  2478. // If they are not equal, there is a closed loop
  2479. if (node_vec.size() != compute_graph->nodes_.size()) {
  2480. std::set<Node *> itered_nodes_set;
  2481. for (auto &node : node_vec) {
  2482. itered_nodes_set.insert(node.get());
  2483. }
  2484. GE_LOGE("Failed to do topo sorting total %zu, itered %zu, exist closed loop in graph.",
  2485. compute_graph->nodes_.size(), node_vec.size());
  2486. for (auto &node : compute_graph->nodes_) {
  2487. if (itered_nodes_set.count(node.get()) == 0) {
  2488. GE_LOGE("The node %s does not itered when topological sorting", node->GetName().c_str());
  2489. }
  2490. }
  2491. return GRAPH_FAILED;
  2492. }
  2493. return GRAPH_SUCCESS;
  2494. }
  2495. } // namespace ge

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