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 105 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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768
  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. GELOGE(GRAPH_FAILED, "Param dst node not valid");
  1335. return GRAPH_FAILED;
  1336. }
  1337. input_desc->CopyAttrsFrom(src_desc->GetInputDesc(i));
  1338. }
  1339. for (uint32_t i = 0; i < src_node->GetAllOutDataAnchorsSize(); ++i) {
  1340. auto output_desc = dst_desc->MutableOutputDesc(i);
  1341. if (output_desc == nullptr) {
  1342. GELOGE(GRAPH_FAILED, "Param dst node not valid");
  1343. return GRAPH_FAILED;
  1344. }
  1345. output_desc->CopyAttrsFrom(src_desc->GetOutputDesc(i));
  1346. }
  1347. return GRAPH_SUCCESS;
  1348. }
  1349. ///
  1350. /// Relink all edges for cloned ComputeGraph.
  1351. /// @param [in] node: original node.
  1352. /// @param [in] prefix: node name prefix of new node.
  1353. /// @param [in] all_nodes: all nodes in new graph.
  1354. /// @return success: GRAPH_SUCESS
  1355. ///
  1356. graphStatus GraphUtils::RelinkGraphEdges(const NodePtr &node, const string &prefix,
  1357. const std::unordered_map<string, NodePtr> &all_nodes) {
  1358. if (node == nullptr || node->GetOpDesc() == nullptr) {
  1359. GELOGE(GRAPH_FAILED, "Input node not valid");
  1360. return GRAPH_FAILED;
  1361. }
  1362. auto it = all_nodes.find(prefix + node->GetName());
  1363. if (it == all_nodes.end()) {
  1364. GELOGE(GRAPH_FAILED, "node[%s] not found", node->GetName().c_str());
  1365. return GRAPH_FAILED;
  1366. }
  1367. const auto &new_node = it->second;
  1368. for (const auto &in_anchor : node->GetAllInDataAnchors()) {
  1369. GE_CHK_BOOL_EXEC(in_anchor != nullptr, return GRAPH_FAILED, "In data anchor is null");
  1370. const auto &out_anchor = in_anchor->GetPeerOutAnchor();
  1371. if (out_anchor == nullptr) {
  1372. GELOGW("Peer out anchor is null: %s", node->GetName().c_str());
  1373. continue;
  1374. }
  1375. GE_CHK_BOOL_EXEC(out_anchor->GetOwnerNode() != nullptr, return GRAPH_FAILED, "Peer out node is null");
  1376. it = all_nodes.find(prefix + out_anchor->GetOwnerNode()->GetName());
  1377. if (it == all_nodes.end()) {
  1378. GELOGE(GRAPH_FAILED, "node[%s] not found", out_anchor->GetOwnerNode()->GetName().c_str());
  1379. return GRAPH_FAILED;
  1380. }
  1381. const auto &new_out_node = it->second;
  1382. auto rslt =
  1383. GraphUtils::AddEdge(new_out_node->GetOutAnchor(out_anchor->GetIdx()), new_node->GetInAnchor(in_anchor->GetIdx()));
  1384. GE_CHK_BOOL_EXEC(rslt == GRAPH_SUCCESS, return GRAPH_FAILED, "link failed[%s to %s]",
  1385. new_out_node->GetName().c_str(), new_node->GetName().c_str());
  1386. }
  1387. if (node->GetInControlAnchor() != nullptr) {
  1388. for (const auto &out_anchor : node->GetInControlAnchor()->GetPeerAnchors()) {
  1389. GE_CHK_BOOL_EXEC(out_anchor != nullptr, continue, "Peer out anchor is null: %s", node->GetName().c_str());
  1390. GE_CHK_BOOL_EXEC(out_anchor->GetOwnerNode() != nullptr, return GRAPH_FAILED, "Peer out node is null");
  1391. it = all_nodes.find(prefix + out_anchor->GetOwnerNode()->GetName());
  1392. if (it == all_nodes.end()) {
  1393. GELOGE(GRAPH_FAILED, "node[%s] not found", out_anchor->GetOwnerNode()->GetName().c_str());
  1394. return GRAPH_FAILED;
  1395. }
  1396. const auto &new_out_node = it->second;
  1397. auto rslt = GraphUtils::AddEdge(new_out_node->GetOutAnchor(out_anchor->GetIdx()), new_node->GetInControlAnchor());
  1398. GE_CHK_BOOL_EXEC(rslt == GRAPH_SUCCESS, return GRAPH_FAILED, "link failed[%s to %s]",
  1399. new_out_node->GetName().c_str(), new_node->GetName().c_str());
  1400. }
  1401. }
  1402. return GRAPH_SUCCESS;
  1403. }
  1404. ///
  1405. /// Get reference-mapping of all data_anchors in graph
  1406. /// @param [in] graph
  1407. /// @param [out] symbol_to_anchors
  1408. /// @param [out] anchor_to_symbol
  1409. /// @return success: GRAPH_SUCESS
  1410. ///
  1411. graphStatus GraphUtils::GetRefMapping(const ComputeGraphPtr &graph,
  1412. std::map<std::string, std::list<NodeIndexIO>> &symbol_to_anchors,
  1413. std::map<std::string, std::string> &anchor_to_symbol) {
  1414. GE_CHECK_NOTNULL(graph);
  1415. for (const auto &node : graph->GetAllNodes()) {
  1416. // in_data_anchor
  1417. if (HandleInAnchorMapping(node, symbol_to_anchors, anchor_to_symbol) != GRAPH_SUCCESS) {
  1418. GE_LOGE("Find ref_mapping for in_data_anchors of node %s failed.", node->GetName().c_str());
  1419. return GRAPH_FAILED;
  1420. }
  1421. // out_data_anchor
  1422. if (HandleOutAnchorMapping(node, symbol_to_anchors, anchor_to_symbol) != GRAPH_SUCCESS) {
  1423. GE_LOGE("Find ref_mapping for out_data_anchors of node %s failed.", node->GetName().c_str());
  1424. return GRAPH_FAILED;
  1425. }
  1426. }
  1427. return GRAPH_SUCCESS;
  1428. }
  1429. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY NodePtr GraphUtils::FindNodeFromAllNodes(ComputeGraphPtr &graph,
  1430. const std::string &name) {
  1431. auto root_graph = FindRootGraph(graph);
  1432. if (root_graph == nullptr) {
  1433. GE_LOGE("Failed find node %s, null root graph", name.c_str());
  1434. return nullptr;
  1435. }
  1436. for (const auto &node : root_graph->GetAllNodes()) {
  1437. if (node == nullptr) {
  1438. continue;
  1439. }
  1440. if (node->GetName() == name) {
  1441. return node;
  1442. }
  1443. }
  1444. return nullptr;
  1445. }
  1446. ///
  1447. /// Get reference-mapping for in_data_anchors of node
  1448. /// @param [in] node
  1449. /// @param [out] symbol_to_anchors
  1450. /// @param [out] anchor_to_symbol
  1451. /// @return success: GRAPH_SUCESS
  1452. ///
  1453. graphStatus GraphUtils::HandleInAnchorMapping(const NodePtr &node,
  1454. std::map<std::string, std::list<NodeIndexIO>> &symbol_to_anchors,
  1455. std::map<std::string, std::string> &anchor_to_symbol) {
  1456. GE_CHECK_NOTNULL(node);
  1457. if (NodeUtils::IsSubgraphOutput(node)) {
  1458. return HandleSubgraphOutput(node, symbol_to_anchors, anchor_to_symbol);
  1459. }
  1460. if (NodeUtils::IsSubgraphInput(node)) {
  1461. return HandleSubgraphInput(node, symbol_to_anchors, anchor_to_symbol);
  1462. }
  1463. const std::string &type = node->GetType();
  1464. if ((type == MERGE) || (type == STREAMMERGE)) {
  1465. return HandleMergeInput(node, symbol_to_anchors, anchor_to_symbol);
  1466. }
  1467. for (const auto &in_data_anchor : node->GetAllInDataAnchors()) {
  1468. NodeIndexIO cur_node_info(node, in_data_anchor->GetIdx(), kIn);
  1469. OutDataAnchorPtr peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  1470. if (peer_out_anchor == nullptr) {
  1471. const std::string &symbol = cur_node_info.ToString();
  1472. GELOGD("Add anchor %s, symbol %s.", cur_node_info.ToString().c_str(), symbol.c_str());
  1473. symbol_to_anchors[symbol] = {cur_node_info};
  1474. anchor_to_symbol[symbol] = symbol;
  1475. } else {
  1476. NodeIndexIO exist_node_info(peer_out_anchor->GetOwnerNode(), peer_out_anchor->GetIdx(), kOut);
  1477. if (UpdateRefMapping(cur_node_info, exist_node_info, symbol_to_anchors, anchor_to_symbol) != GRAPH_SUCCESS) {
  1478. GE_LOGE("Update symbol mapping failed.");
  1479. return GRAPH_FAILED;
  1480. }
  1481. }
  1482. }
  1483. return GRAPH_SUCCESS;
  1484. }
  1485. ///
  1486. /// Get reference-mapping for out_data_anchors of node
  1487. /// @param [in] node
  1488. /// @param [out] symbol_to_anchors
  1489. /// @param [out] anchor_to_symbol
  1490. /// @return success: GRAPH_SUCESS
  1491. ///
  1492. graphStatus GraphUtils::HandleOutAnchorMapping(const NodePtr &node,
  1493. std::map<std::string, std::list<NodeIndexIO>> &symbol_to_anchors,
  1494. std::map<std::string, std::string> &anchor_to_symbol) {
  1495. GE_CHECK_NOTNULL(node);
  1496. for (const auto &out_data_anchor : node->GetAllOutDataAnchors()) {
  1497. NodeIndexIO cur_node_info(node, out_data_anchor->GetIdx(), kOut);
  1498. if (anchor_to_symbol.find(cur_node_info.ToString()) != anchor_to_symbol.end()) {
  1499. continue;
  1500. }
  1501. int32_t reuse_in_index = -1;
  1502. if (IsRefFromInput(out_data_anchor, reuse_in_index)) {
  1503. NodeIndexIO exist_node_info(node, reuse_in_index, kIn);
  1504. if (UpdateRefMapping(cur_node_info, exist_node_info, symbol_to_anchors, anchor_to_symbol) != GRAPH_SUCCESS) {
  1505. GE_LOGE("Update symbol mapping failed.");
  1506. return GRAPH_FAILED;
  1507. }
  1508. } else {
  1509. const std::string &symbol = cur_node_info.ToString();
  1510. GELOGD("Add anchor %s, symbol %s.", cur_node_info.ToString().c_str(), symbol.c_str());
  1511. symbol_to_anchors.emplace(std::make_pair(symbol, std::list<NodeIndexIO>{cur_node_info}));
  1512. anchor_to_symbol.emplace(std::make_pair(symbol, symbol));
  1513. }
  1514. }
  1515. return GRAPH_SUCCESS;
  1516. }
  1517. ///
  1518. /// Handle input of subgraph
  1519. /// @param [in] node
  1520. /// @param [out] symbol_to_anchors
  1521. /// @param [out] anchor_to_symbol
  1522. /// @return success: GRAPH_SUCESS
  1523. ///
  1524. graphStatus GraphUtils::HandleSubgraphInput(const NodePtr &node,
  1525. std::map<std::string, std::list<NodeIndexIO>> &symbol_to_anchors,
  1526. std::map<std::string, std::string> &anchor_to_symbol) {
  1527. GE_CHECK_NOTNULL(node);
  1528. GE_CHECK_NOTNULL(node->GetOpDesc());
  1529. // Data in subgraph
  1530. uint32_t index = 0;
  1531. if (!ge::AttrUtils::GetInt(node->GetOpDesc(), ATTR_NAME_PARENT_NODE_INDEX, index)) {
  1532. GE_LOGE("Get attr ATTR_NAME_PARENT_NODE_INDEX failed, node:%s.", node->GetName().c_str());
  1533. return GRAPH_FAILED;
  1534. }
  1535. NodePtr parent_node = node->GetOwnerComputeGraph()->GetParentNode();
  1536. GE_CHECK_NOTNULL(parent_node);
  1537. InDataAnchorPtr parent_in_anchor = parent_node->GetInDataAnchor(index);
  1538. GE_CHECK_NOTNULL(parent_in_anchor);
  1539. OutDataAnchorPtr peer_out_anchor = parent_in_anchor->GetPeerOutAnchor();
  1540. if (peer_out_anchor != nullptr) {
  1541. // Data has and only has one input
  1542. NodeIndexIO cur_node_info(node, 0, kIn);
  1543. NodeIndexIO exist_node_info(peer_out_anchor->GetOwnerNode(), peer_out_anchor->GetIdx(), kOut);
  1544. if (UpdateRefMapping(cur_node_info, exist_node_info, symbol_to_anchors, anchor_to_symbol) != GRAPH_SUCCESS) {
  1545. GE_LOGE("Update symbol mapping failed.");
  1546. return GRAPH_FAILED;
  1547. }
  1548. }
  1549. return GRAPH_SUCCESS;
  1550. }
  1551. ///
  1552. /// Handle input of Merge op
  1553. /// @param [in] node
  1554. /// @param [out] symbol_to_anchors
  1555. /// @param [out] anchor_to_symbol
  1556. /// @return success: GRAPH_SUCESS
  1557. ///
  1558. graphStatus GraphUtils::HandleMergeInput(const NodePtr &node,
  1559. std::map<std::string, std::list<NodeIndexIO>> &symbol_to_anchors,
  1560. std::map<std::string, std::string> &anchor_to_symbol) {
  1561. GE_CHECK_NOTNULL(node);
  1562. std::vector<NodeIndexIO> exist_node_infos;
  1563. std::vector<NodeIndexIO> cur_node_infos;
  1564. for (const auto &in_data_anchor : node->GetAllInDataAnchors()) {
  1565. auto peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  1566. if (peer_out_anchor == nullptr) {
  1567. std::string next_name;
  1568. if (AttrUtils::GetStr(node->GetOpDesc(), ATTR_NAME_NEXT_ITERATION, next_name) && !next_name.empty()) {
  1569. ComputeGraphPtr graph = node->GetOwnerComputeGraph();
  1570. GE_CHECK_NOTNULL(graph);
  1571. ge::NodePtr next_node = graph->FindNode(next_name);
  1572. GE_CHECK_NOTNULL(next_node);
  1573. // NextIteration has and only has one output
  1574. peer_out_anchor = next_node->GetOutDataAnchor(0);
  1575. GE_CHECK_NOTNULL(peer_out_anchor);
  1576. cur_node_infos.emplace_back(NodeIndexIO(node, in_data_anchor->GetIdx(), kIn));
  1577. cur_node_infos.emplace_back(NodeIndexIO(next_node, peer_out_anchor->GetIdx(), kOut));
  1578. }
  1579. } else {
  1580. cur_node_infos.emplace_back(NodeIndexIO(node, in_data_anchor->GetIdx(), kIn));
  1581. exist_node_infos.emplace_back(NodeIndexIO(peer_out_anchor->GetOwnerNode(), peer_out_anchor->GetIdx(), kOut));
  1582. }
  1583. }
  1584. size_t anchor_nums = 0;
  1585. NodeIndexIO max_node_index_io(nullptr, 0, kOut);
  1586. for (const auto &temp_node_info : exist_node_infos) {
  1587. auto iter1 = anchor_to_symbol.find(temp_node_info.ToString());
  1588. if (iter1 != anchor_to_symbol.end()) {
  1589. const std::string &temp_symbol = iter1->second;
  1590. auto iter2 = symbol_to_anchors.find(temp_symbol);
  1591. if (iter2 != symbol_to_anchors.end()) {
  1592. if (iter2->second.size() > anchor_nums) {
  1593. max_node_index_io = temp_node_info;
  1594. anchor_nums = iter2->second.size();
  1595. }
  1596. }
  1597. }
  1598. }
  1599. std::string symbol;
  1600. for (const auto &temp_node_info : exist_node_infos) {
  1601. if ((UnionSymbolMapping(max_node_index_io, temp_node_info, symbol_to_anchors, anchor_to_symbol, symbol) !=
  1602. GRAPH_SUCCESS) ||
  1603. symbol.empty()) {
  1604. GE_LOGE("Union symbol map anchor1:%s & anchor2:%s.", max_node_index_io.ToString().c_str(),
  1605. temp_node_info.ToString().c_str());
  1606. return GRAPH_FAILED;
  1607. }
  1608. }
  1609. auto iter = symbol_to_anchors.find(symbol);
  1610. if (iter != symbol_to_anchors.end()) {
  1611. for (const auto &temp_node_info : cur_node_infos) {
  1612. GELOGD("Add anchor %s, symbol %s.", temp_node_info.ToString().c_str(), symbol.c_str());
  1613. iter->second.emplace_back(temp_node_info);
  1614. anchor_to_symbol.emplace(std::make_pair(temp_node_info.ToString(), symbol));
  1615. }
  1616. }
  1617. return GRAPH_SUCCESS;
  1618. }
  1619. ///
  1620. /// Handle output of subgraph
  1621. /// @param [in] node
  1622. /// @param [out] symbol_to_anchors
  1623. /// @param [out] anchor_to_symbol
  1624. /// @return success: GRAPH_SUCESS
  1625. ///
  1626. graphStatus GraphUtils::HandleSubgraphOutput(const NodePtr &node,
  1627. std::map<std::string, std::list<NodeIndexIO>> &symbol_to_anchors,
  1628. std::map<std::string, std::string> &anchor_to_symbol) {
  1629. GE_CHECK_NOTNULL(node);
  1630. ComputeGraphPtr owner_graph = node->GetOwnerComputeGraph();
  1631. GE_CHECK_NOTNULL(owner_graph);
  1632. NodePtr parent_node = owner_graph->GetParentNode();
  1633. GE_CHECK_NOTNULL(parent_node);
  1634. OpDescPtr op_desc = node->GetOpDesc();
  1635. GE_CHECK_NOTNULL(op_desc);
  1636. for (const auto &in_data_anchor : node->GetAllInDataAnchors()) {
  1637. OutDataAnchorPtr peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  1638. GE_CHECK_NOTNULL(peer_out_anchor);
  1639. GeTensorDesc in_tensor = op_desc->GetInputDesc(in_data_anchor->GetIdx());
  1640. uint32_t index = 0;
  1641. if (!ge::AttrUtils::GetInt(in_tensor, ATTR_NAME_PARENT_NODE_INDEX, index)) {
  1642. continue;
  1643. }
  1644. GE_CHECK_NOTNULL(parent_node->GetOutDataAnchor(index));
  1645. // Union symbol of peer_out_anchor & parent_out_anchor
  1646. NodeIndexIO peer_node_info(peer_out_anchor->GetOwnerNode(), peer_out_anchor->GetIdx(), kOut);
  1647. NodeIndexIO parent_node_info(parent_node, index, kOut);
  1648. std::string symbol;
  1649. if ((UnionSymbolMapping(peer_node_info, parent_node_info, symbol_to_anchors, anchor_to_symbol, symbol) !=
  1650. GRAPH_SUCCESS) ||
  1651. symbol.empty()) {
  1652. GE_LOGE("Union symbol map anchor1:%s, anchor2:%s.", peer_node_info.ToString().c_str(),
  1653. parent_node_info.ToString().c_str());
  1654. return GRAPH_FAILED;
  1655. }
  1656. NodeIndexIO cur_node_info(node, in_data_anchor->GetIdx(), kIn);
  1657. GELOGD("Add anchor %s, symbol %s.", cur_node_info.ToString().c_str(), symbol.c_str());
  1658. symbol_to_anchors[symbol].emplace_back(cur_node_info);
  1659. anchor_to_symbol.emplace(std::make_pair(cur_node_info.ToString(), symbol));
  1660. }
  1661. return GRAPH_SUCCESS;
  1662. }
  1663. ///
  1664. /// Union ref-mapping
  1665. /// @param [in] exist_node_info1
  1666. /// @param [in] exist_node_info2
  1667. /// @param [out] symbol_to_anchors
  1668. /// @param [out] anchor_to_symbol
  1669. /// @param [out] symbol
  1670. /// @return success: GRAPH_SUCESS
  1671. ///
  1672. graphStatus GraphUtils::UnionSymbolMapping(const NodeIndexIO &exist_node_info1, const NodeIndexIO &exist_node_info2,
  1673. std::map<std::string, std::list<NodeIndexIO>> &symbol_to_anchors,
  1674. std::map<std::string, std::string> &anchor_to_symbol, std::string &symbol) {
  1675. const std::string &symbol1 = anchor_to_symbol[exist_node_info1.ToString()];
  1676. const std::string &symbol2 = anchor_to_symbol[exist_node_info2.ToString()];
  1677. if (symbol1 == symbol2) {
  1678. symbol = symbol1;
  1679. GELOGI("no need to union.");
  1680. return GRAPH_SUCCESS;
  1681. }
  1682. auto iter1 = symbol_to_anchors.find(symbol1);
  1683. auto iter2 = symbol_to_anchors.find(symbol2);
  1684. if ((iter1 == symbol_to_anchors.end()) || (iter2 == symbol_to_anchors.end())) {
  1685. GE_LOGE("symbol %s or %s not exist.", symbol1.c_str(), symbol2.c_str());
  1686. return GRAPH_FAILED;
  1687. }
  1688. auto &max_iter = (iter1->second.size() > iter2->second.size() ? iter1 : iter2);
  1689. auto &min_iter = (iter1->second.size() > iter2->second.size() ? iter2 : iter1);
  1690. symbol = (iter1->second.size() > iter2->second.size() ? symbol1 : symbol2);
  1691. std::string min_symbol = (iter1->second.size() > iter2->second.size() ? symbol2 : symbol1);
  1692. for (auto &node_index_io : min_iter->second) {
  1693. GELOGD("Update anchor %s, symbol %s.", node_index_io.ToString().c_str(), symbol.c_str());
  1694. max_iter->second.emplace_back(node_index_io);
  1695. auto iter = anchor_to_symbol.find(node_index_io.ToString());
  1696. if (iter == anchor_to_symbol.end()) {
  1697. GE_LOGE("anchor %s not exist.", node_index_io.ToString().c_str());
  1698. return GRAPH_FAILED;
  1699. }
  1700. if (iter->second != min_symbol) {
  1701. GELOGW("not expected symbol of anchor %s, expect %s but %s exactly.", iter->first.c_str(), min_symbol.c_str(),
  1702. iter->second.c_str());
  1703. }
  1704. iter->second = symbol;
  1705. }
  1706. GELOGI("Union symbol %s and %s succ.", symbol.c_str(), min_symbol.c_str());
  1707. symbol_to_anchors.erase(min_iter);
  1708. return GRAPH_SUCCESS;
  1709. }
  1710. ///
  1711. /// Update symbol mapping with a new reference pair
  1712. /// @param [in] cur_node_info
  1713. /// @param [in] exist_node_info
  1714. /// @param [out] symbol_to_anchors
  1715. /// @param [out] anchor_to_symbol
  1716. /// @return success: GRAPH_SUCESS
  1717. ///
  1718. graphStatus GraphUtils::UpdateRefMapping(const NodeIndexIO &cur_node_info, const NodeIndexIO &exist_node_info,
  1719. std::map<std::string, std::list<NodeIndexIO>> &symbol_to_anchors,
  1720. std::map<std::string, std::string> &anchor_to_symbol) {
  1721. auto iter1 = anchor_to_symbol.find(exist_node_info.ToString());
  1722. if (iter1 == anchor_to_symbol.end()) {
  1723. GE_LOGE("data_anchor %s is not visible before data_anchor %s, maybe TopoSorting is missing.",
  1724. exist_node_info.ToString().c_str(), cur_node_info.ToString().c_str());
  1725. return GRAPH_FAILED;
  1726. }
  1727. const std::string &symbol = iter1->second;
  1728. auto iter2 = symbol_to_anchors.find(symbol);
  1729. if (iter2 == symbol_to_anchors.end()) {
  1730. GE_LOGE("symbol %s not found.", symbol.c_str());
  1731. return GRAPH_FAILED;
  1732. }
  1733. GELOGD("Add anchor %s, symbol %s.", cur_node_info.ToString().c_str(), symbol.c_str());
  1734. iter2->second.emplace_back(cur_node_info);
  1735. anchor_to_symbol.emplace(std::make_pair(cur_node_info.ToString(), symbol));
  1736. return GRAPH_SUCCESS;
  1737. }
  1738. ///
  1739. /// Check if out_data_anchor is reference of input
  1740. /// @param [in] out_data_anchor
  1741. /// @param [out] reuse_in_index
  1742. /// @return bool
  1743. ///
  1744. bool GraphUtils::IsRefFromInput(const OutDataAnchorPtr &out_data_anchor, int32_t &reuse_in_index) {
  1745. if (out_data_anchor == nullptr) {
  1746. GELOGW("out_data_anchor is NULL.");
  1747. return false;
  1748. }
  1749. int32_t output_index = out_data_anchor->GetIdx();
  1750. // pass-through op
  1751. NodePtr node = out_data_anchor->GetOwnerNode();
  1752. const std::string &type = node->GetType();
  1753. const std::set<std::string> pass_through_set = {NETOUTPUT, WHILE, _WHILE, STATELESSWHILE};
  1754. if ((pass_through_set.count(type) > 0) || (NodeUtils::IsSubgraphInput(node))) {
  1755. reuse_in_index = output_index;
  1756. GELOGI("Pass-Through node name[%s] index[%u].", node->GetName().c_str(), reuse_in_index);
  1757. return true;
  1758. }
  1759. // Merge op 0th output
  1760. if ((type == MERGE) && (output_index == 0)) {
  1761. reuse_in_index = 0;
  1762. GELOGI("Merge name[%s] output_index[0].", node->GetName().c_str());
  1763. return true;
  1764. }
  1765. // ref op
  1766. OpDescPtr op_desc = node->GetOpDesc();
  1767. if (op_desc == nullptr) {
  1768. GELOGW("op_desc is NULL.");
  1769. return false;
  1770. }
  1771. bool is_ref = false;
  1772. (void)ge::AttrUtils::GetBool(op_desc, ATTR_NAME_REFERENCE, is_ref);
  1773. if (is_ref) {
  1774. const string &output_name = op_desc->GetOutputNameByIndex(output_index);
  1775. for (const auto &input_name : op_desc->GetAllInputNames()) {
  1776. if (!input_name.empty() && (output_name == input_name)) {
  1777. reuse_in_index = op_desc->GetInputIndexByName(input_name);
  1778. GELOGI("Reference name[%s] output[%s][%d] ref to input[%s][%d].", op_desc->GetName().c_str(),
  1779. output_name.c_str(), output_index, input_name.c_str(), reuse_in_index);
  1780. return true;
  1781. }
  1782. }
  1783. }
  1784. // reuse input
  1785. auto output_op_desc = op_desc->GetOutputDescPtr(output_index);
  1786. bool reuse_input = false;
  1787. if (output_op_desc != nullptr) {
  1788. if ((TensorUtils::GetReuseInput(*output_op_desc, reuse_input) == GRAPH_SUCCESS) && reuse_input) {
  1789. uint32_t reuse_input_index = 0;
  1790. if (TensorUtils::GetReuseInputIndex(*output_op_desc, reuse_input_index) == GRAPH_SUCCESS) {
  1791. reuse_in_index = static_cast<int32_t>(reuse_input_index);
  1792. GELOGI("ReuseInput name[%s] output[%d] reuse input[%d].", op_desc->GetName().c_str(), output_index,
  1793. reuse_in_index);
  1794. return true;
  1795. }
  1796. }
  1797. }
  1798. return false;
  1799. }
  1800. ///
  1801. /// Determine if the graph is a UNKNOWN_SHAPE graph based on whether the graph and all subgraphs
  1802. /// of the graph have UNKNOWN_SHAPE operators or not.
  1803. /// Note: This function will only look 'down' from the graph, not 'up'. For example, the following
  1804. /// scenario (K for known shape, U for unknown shape), ROOT graph is UNKNOWN_SHAPE while SUB graph is KNOWN_SHAPE
  1805. /// ROOT graph: A -----> B -----> C
  1806. /// K subgraph U
  1807. /// |
  1808. /// V
  1809. /// SUB graph: D --> E --> F
  1810. /// K K K
  1811. /// @param [in] graph
  1812. /// @return bool
  1813. ///
  1814. bool GraphUtils::IsUnknownShapeGraph(const ComputeGraphPtr &graph) {
  1815. if (graph == nullptr) {
  1816. GELOGW("Input graph is nullptr.");
  1817. return false;
  1818. }
  1819. for (const auto &node : graph->GetDirectNode()) {
  1820. bool is_unknown = false;
  1821. auto ret = NodeUtils::GetNodeUnknownShapeStatus(*node, is_unknown);
  1822. if (ret != GRAPH_SUCCESS) {
  1823. GELOGW("Get node unknown status failed, node name:%s, type:%s.", node->GetName().c_str(),
  1824. node->GetType().c_str());
  1825. continue;
  1826. }
  1827. if (is_unknown) {
  1828. GELOGD("Node %s, type %s is unknown shape in graph %s.", node->GetName().c_str(), node->GetType().c_str(),
  1829. graph->GetName().c_str());
  1830. return true;
  1831. }
  1832. }
  1833. GELOGD("Graph %s does not have unknown shape node.", graph->GetName().c_str());
  1834. return false;
  1835. }
  1836. ///
  1837. /// @brief Add node to graph
  1838. /// @param [in] op_desc
  1839. /// @return ComputeGraphBuilder
  1840. ///
  1841. ComputeGraphBuilder &ComputeGraphBuilder::AddNode(const OpDescPtr &op_desc) {
  1842. nodes_.emplace_back(op_desc);
  1843. return *this;
  1844. }
  1845. ///
  1846. /// @brief Add data-link among nodes in graph
  1847. /// @param [in] src_name
  1848. /// @param [in] out_anchor_ind
  1849. /// @param [in] dst_name
  1850. /// @param [in] in_anchor_ind
  1851. /// @return ComputeGraphBuilder
  1852. ///
  1853. ComputeGraphBuilder &ComputeGraphBuilder::AddDataLink(const std::string &src_name, uint32_t out_anchor_ind,
  1854. const std::string &dst_name, uint32_t in_anchor_ind) {
  1855. data_links_.emplace_back(
  1856. std::make_pair(std::make_pair(src_name, out_anchor_ind), std::make_pair(dst_name, in_anchor_ind)));
  1857. return *this;
  1858. }
  1859. ///
  1860. /// @brief Add ctrl-link among nodes in graph
  1861. /// @param [in] src_name
  1862. /// @param [in] dst_name
  1863. /// @return ComputeGraphBuilder
  1864. ///
  1865. ComputeGraphBuilder &ComputeGraphBuilder::AddControlLink(const std::string &src_name, const std::string &dst_name) {
  1866. ctrl_links_.emplace_back(std::make_pair(src_name, dst_name));
  1867. return *this;
  1868. }
  1869. ///
  1870. /// @brief Build nodes
  1871. /// @param [out] error_code
  1872. /// @param [out] error_msg
  1873. /// @return void
  1874. ///
  1875. void ComputeGraphBuilder::BuildNodes(graphStatus &error_code, std::string &error_msg) {
  1876. if (owner_graph_ == nullptr) {
  1877. error_code = GRAPH_FAILED;
  1878. error_msg = "graph is NULL.";
  1879. return;
  1880. }
  1881. std::string node_name;
  1882. for (auto &op_desc : nodes_) {
  1883. if (op_desc == nullptr) {
  1884. error_code = GRAPH_FAILED;
  1885. error_msg = "op_desc is NULL.";
  1886. return;
  1887. }
  1888. node_name = op_desc->GetName();
  1889. NodePtr node = owner_graph_->AddNode(op_desc);
  1890. if (node == nullptr) {
  1891. error_code = GRAPH_FAILED;
  1892. error_msg = "Add node " + node_name + " failed.";
  1893. return;
  1894. }
  1895. GELOGD("Add node name:%s, type:%s.", node_name.c_str(), op_desc->GetType().c_str());
  1896. node_names_[node_name] = node;
  1897. }
  1898. GELOGD("BuildNodes succ.");
  1899. }
  1900. ///
  1901. /// @brief Build data-links
  1902. /// @param [out] error_code
  1903. /// @param [out] error_msg
  1904. /// @return void
  1905. ///
  1906. void ComputeGraphBuilder::BuildDataLinks(graphStatus &error_code, std::string &error_msg) {
  1907. for (auto &pair : data_links_) {
  1908. std::string src_name = pair.first.first;
  1909. uint32_t out_ind = pair.first.second;
  1910. std::string dst_name = pair.second.first;
  1911. uint32_t in_ind = pair.second.second;
  1912. std::string log_msg = "Add data-edge ";
  1913. log_msg.append(src_name)
  1914. .append(":")
  1915. .append(std::to_string(out_ind))
  1916. .append("->")
  1917. .append(dst_name)
  1918. .append(":")
  1919. .append(std::to_string(in_ind));
  1920. auto src_iter = node_names_.find(src_name);
  1921. auto dst_iter = node_names_.find(dst_name);
  1922. if ((src_iter == node_names_.end()) || (dst_iter == node_names_.end())) {
  1923. error_code = GRAPH_FAILED;
  1924. error_msg = log_msg + " failed: node not exist in graph.";
  1925. return;
  1926. }
  1927. NodePtr src_node = node_names_[src_name];
  1928. NodePtr dst_node = node_names_[dst_name];
  1929. if ((src_node == nullptr) || (dst_node == nullptr)) {
  1930. error_code = GRAPH_FAILED;
  1931. error_msg = log_msg + " failed: node is NULL.";
  1932. return;
  1933. }
  1934. if (GraphUtils::AddEdge(src_node->GetOutDataAnchor(out_ind), dst_node->GetInDataAnchor(in_ind)) != GRAPH_SUCCESS) {
  1935. error_code = GRAPH_FAILED;
  1936. error_msg = log_msg + " failed.";
  1937. return;
  1938. }
  1939. GELOGD("%s succ.", log_msg.c_str());
  1940. }
  1941. GELOGD("BuildDataLinks succ.");
  1942. }
  1943. ///
  1944. /// @brief Build ctrl-links
  1945. /// @param [out] error_code
  1946. /// @param [out] error_msg
  1947. /// @return void
  1948. ///
  1949. void ComputeGraphBuilder::BuildCtrlLinks(graphStatus &error_code, std::string &error_msg) {
  1950. for (auto &pair : ctrl_links_) {
  1951. std::string src_name = pair.first;
  1952. std::string dst_name = pair.second;
  1953. std::string log_msg = "Add ctrl-edge ";
  1954. log_msg.append(src_name).append("->").append(dst_name);
  1955. auto src_iter = node_names_.find(src_name);
  1956. auto dst_iter = node_names_.find(dst_name);
  1957. if ((src_iter == node_names_.end()) || (dst_iter == node_names_.end())) {
  1958. error_code = GRAPH_FAILED;
  1959. error_msg = log_msg + " failed: node not exist in graph.";
  1960. return;
  1961. }
  1962. NodePtr src_node = node_names_[src_name];
  1963. NodePtr dst_node = node_names_[dst_name];
  1964. if ((src_node == nullptr) || (dst_node == nullptr)) {
  1965. error_code = GRAPH_FAILED;
  1966. error_msg = log_msg + " failed: node is NULL.";
  1967. return;
  1968. }
  1969. if (GraphUtils::AddEdge(src_node->GetOutControlAnchor(), dst_node->GetInControlAnchor()) != GRAPH_SUCCESS) {
  1970. error_code = GRAPH_FAILED;
  1971. error_msg = log_msg + " failed.";
  1972. return;
  1973. }
  1974. GELOGD("%s succ.", log_msg.c_str());
  1975. }
  1976. GELOGD("BuildCtrlLinks succ.");
  1977. }
  1978. /// @brief Get node with name
  1979. /// @param [in] name
  1980. /// @return NodePtr
  1981. ///
  1982. NodePtr ComputeGraphBuilder::GetNode(const std::string &name) {
  1983. auto iter = node_names_.find(name);
  1984. if (iter == node_names_.end()) {
  1985. GE_LOGE("node %s not exist.", name.c_str());
  1986. return nullptr;
  1987. }
  1988. return iter->second;
  1989. }
  1990. /// @brief Get all nodes
  1991. /// @return std::vector<NodePtr>
  1992. ///
  1993. std::vector<NodePtr> ComputeGraphBuilder::GetAllNodes() {
  1994. std::vector<NodePtr> nodes;
  1995. for (const auto &iter : node_names_) {
  1996. nodes.emplace_back(iter.second);
  1997. }
  1998. return nodes;
  1999. }
  2000. ///
  2001. /// @brief Add node to graph
  2002. /// @param [in] op_desc
  2003. /// @return CompleteGraphBuilder
  2004. ///
  2005. CompleteGraphBuilder &CompleteGraphBuilder::AddNode(const OpDescPtr &op_desc) {
  2006. ComputeGraphBuilder::AddNode(op_desc);
  2007. return *this;
  2008. }
  2009. ///
  2010. /// @brief Add data-link among nodes in graph
  2011. /// @param [in] src_name
  2012. /// @param [in] out_anchor_ind
  2013. /// @param [in] dst_name
  2014. /// @param [in] in_anchor_ind
  2015. /// @return CompleteGraphBuilder
  2016. ///
  2017. CompleteGraphBuilder &CompleteGraphBuilder::AddDataLink(const std::string &src_name, uint32_t out_anchor_ind,
  2018. const std::string &dst_name, uint32_t in_anchor_ind) {
  2019. ComputeGraphBuilder::AddDataLink(src_name, out_anchor_ind, dst_name, in_anchor_ind);
  2020. return *this;
  2021. }
  2022. ///
  2023. /// @brief Add ctrl-link among nodes in graph
  2024. /// @param [in] src_name
  2025. /// @param [in] dst_name
  2026. /// @return CompleteGraphBuilder
  2027. ///
  2028. CompleteGraphBuilder &CompleteGraphBuilder::AddControlLink(const std::string &src_name, const std::string &dst_name) {
  2029. ComputeGraphBuilder::AddControlLink(src_name, dst_name);
  2030. return *this;
  2031. }
  2032. ///
  2033. /// @brief Set index_th input anchor for graph
  2034. /// @param [in] index
  2035. /// @param [in] node_names
  2036. /// @param [in] anchor_inds
  2037. /// @return CompleteGraphBuilder
  2038. ///
  2039. CompleteGraphBuilder &CompleteGraphBuilder::SetInput(uint32_t index, const std::vector<std::string> &node_names,
  2040. const std::vector<uint32_t> &anchor_inds) {
  2041. graph_inputs_[index] = std::make_pair(node_names, anchor_inds);
  2042. return *this;
  2043. }
  2044. ///
  2045. /// @brief Set index_th input of graph as useless
  2046. /// @param [in] index
  2047. /// @return CompleteGraphBuilder
  2048. ///
  2049. CompleteGraphBuilder &CompleteGraphBuilder::SetUselessInput(uint32_t index) {
  2050. graph_inputs_[index] = std::make_pair(std::vector<std::string>(), std::vector<uint32_t>());
  2051. return *this;
  2052. }
  2053. ///
  2054. /// @brief Add output anchor for graph
  2055. /// @param [in] owner_node_name
  2056. /// @param [in] anchor_ind
  2057. /// @return CompleteGraphBuilder
  2058. ///
  2059. CompleteGraphBuilder &CompleteGraphBuilder::AddOutput(const std::string &owner_node_name, uint32_t anchor_ind) {
  2060. graph_outputs_.emplace_back(std::make_pair(owner_node_name, anchor_ind));
  2061. return *this;
  2062. }
  2063. ///
  2064. /// @brief Add target for graph
  2065. /// @param [in] target_name
  2066. /// @return CompleteGraphBuilder
  2067. ///
  2068. CompleteGraphBuilder &CompleteGraphBuilder::AddTarget(const std::string &target_name) {
  2069. graph_targets_.emplace_back(target_name);
  2070. return *this;
  2071. }
  2072. ///
  2073. /// @brief Set parent-node of graph
  2074. /// @param [in] parent_node
  2075. /// @return CompleteGraphBuilder
  2076. ///
  2077. CompleteGraphBuilder &CompleteGraphBuilder::SetParentNode(const NodePtr &parent_node) {
  2078. parent_node_ = parent_node;
  2079. return *this;
  2080. }
  2081. ///
  2082. /// @brief Set mapping-relation of parent-node in_anchor_ind & Data-node
  2083. /// @param [in] input_mapping: index_of_graph_input -> in_anchor_index_of_parent_node
  2084. /// @return CompleteGraphBuilder
  2085. ///
  2086. CompleteGraphBuilder &CompleteGraphBuilder::SetInputMapping(const std::map<uint32_t, uint32_t> &input_mapping) {
  2087. for (auto &item : input_mapping) {
  2088. input_mapping_[item.first] = item.second;
  2089. }
  2090. return *this;
  2091. }
  2092. ///
  2093. /// @brief Set mapping-relation of parent-node out_anchor_ind & NetOutput-node out_anchor_ind
  2094. /// @param [in] output_mapping: index_of_graph_output -> out_anchor_index_of_parent_node
  2095. /// @return CompleteGraphBuilder
  2096. ///
  2097. CompleteGraphBuilder &CompleteGraphBuilder::SetOutputMapping(const std::map<uint32_t, uint32_t> &output_mapping) {
  2098. for (auto &item : output_mapping) {
  2099. output_mapping_[item.first] = item.second;
  2100. }
  2101. return *this;
  2102. }
  2103. ///
  2104. /// @brief Build graph
  2105. /// @param [out] error_code
  2106. /// @param [out] error_msg
  2107. /// @return ComputeGraphPtr
  2108. ///
  2109. ComputeGraphPtr CompleteGraphBuilder::Build(graphStatus &error_code, std::string &error_msg) {
  2110. owner_graph_ = shared_ptr<ComputeGraph>(new (std::nothrow) ComputeGraph(name_));
  2111. if ((owner_graph_ == nullptr) || (parent_node_ == nullptr)) {
  2112. error_code = GRAPH_FAILED;
  2113. error_msg = "graph / parent_node is NULL.";
  2114. return nullptr;
  2115. }
  2116. owner_graph_->SetParentNode(parent_node_);
  2117. owner_graph_->SetParentGraph(parent_node_->GetOwnerComputeGraph());
  2118. BuildNodes(error_code, error_msg);
  2119. if (error_code != GRAPH_SUCCESS) {
  2120. return nullptr;
  2121. }
  2122. BuildDataLinks(error_code, error_msg);
  2123. if (error_code != GRAPH_SUCCESS) {
  2124. return nullptr;
  2125. }
  2126. BuildCtrlLinks(error_code, error_msg);
  2127. if (error_code != GRAPH_SUCCESS) {
  2128. return nullptr;
  2129. }
  2130. AddDataNodes(error_code, error_msg);
  2131. if (error_code != GRAPH_SUCCESS) {
  2132. return nullptr;
  2133. }
  2134. AddRetValNodes(error_code, error_msg);
  2135. if (error_code != GRAPH_SUCCESS) {
  2136. return nullptr;
  2137. }
  2138. BuildGraphTargets(error_code, error_msg);
  2139. if (error_code != GRAPH_SUCCESS) {
  2140. return nullptr;
  2141. }
  2142. // ATTR_NAME_SESSION_GRAPH_ID
  2143. std::string graph_id;
  2144. if (!AttrUtils::GetStr(parent_node_->GetOwnerComputeGraph(), ATTR_NAME_SESSION_GRAPH_ID, graph_id)) {
  2145. error_code = GRAPH_FAILED;
  2146. error_msg = "Get attr session_graph_id failed.";
  2147. return nullptr;
  2148. }
  2149. if (!AttrUtils::SetStr(owner_graph_, ATTR_NAME_SESSION_GRAPH_ID, graph_id)) {
  2150. error_code = GRAPH_FAILED;
  2151. error_msg = "Set attr session_graph_id failed.";
  2152. return nullptr;
  2153. }
  2154. // refresh node name
  2155. for (const NodePtr &node : owner_graph_->GetDirectNode()) {
  2156. if ((node->GetOpDesc() == nullptr) || (node->GetType() == VARIABLE) || (node->GetType() == VARIABLEV2)) {
  2157. continue;
  2158. }
  2159. node->GetOpDesc()->SetName(owner_graph_->GetName() + "/" + node->GetName());
  2160. }
  2161. return owner_graph_;
  2162. }
  2163. ///
  2164. /// @brief Add data nodes
  2165. /// @param [out] error_code
  2166. /// @param [out] error_msg
  2167. /// @return void
  2168. ///
  2169. void CompleteGraphBuilder::AddDataNodes(graphStatus &error_code, std::string &error_msg) {
  2170. for (auto &input : graph_inputs_) {
  2171. NodePtr data_node = AddDataNode(input.first, error_code, error_msg);
  2172. if (data_node == nullptr) {
  2173. error_code = GRAPH_FAILED;
  2174. error_msg = "AddDataNodes failed: add node Data:" + std::to_string(input.first) + +" failed.";
  2175. return;
  2176. }
  2177. if (owner_graph_->AddInputNode(data_node) == nullptr) {
  2178. error_code = GRAPH_FAILED;
  2179. error_msg = "AddDataNodes failed: add input node Data:" + std::to_string(input.first) + +" failed.";
  2180. return;
  2181. }
  2182. // useless input
  2183. std::vector<std::string> input_names = input.second.first;
  2184. std::vector<uint32_t> anchor_indes = input.second.second;
  2185. if (input_names.size() != anchor_indes.size()) {
  2186. error_code = GRAPH_FAILED;
  2187. error_msg = "AddDataNodes failed: num of input_names and indexs not equal.";
  2188. return;
  2189. }
  2190. if (input_names.empty()) {
  2191. continue;
  2192. }
  2193. size_t input_num = input_names.size();
  2194. for (size_t i = 0; i < input_num; i++) {
  2195. std::string input_name = input_names[i];
  2196. uint32_t ind = anchor_indes[i];
  2197. auto iter = node_names_.find(input_name);
  2198. if (iter == node_names_.end()) {
  2199. error_code = GRAPH_FAILED;
  2200. error_msg = "AddDataNodes failed: node " + input_name + " not exist in graph.";
  2201. return;
  2202. }
  2203. NodePtr in_node = node_names_[input_name];
  2204. if (in_node == nullptr) {
  2205. error_code = GRAPH_FAILED;
  2206. error_msg = "AddDataNodes failed: node " + input_name + " is NULL.";
  2207. return;
  2208. }
  2209. if (GraphUtils::AddEdge(data_node->GetOutDataAnchor(0), in_node->GetInDataAnchor(ind)) != GRAPH_SUCCESS) {
  2210. error_code = GRAPH_FAILED;
  2211. error_msg = "AddDataNodes failed: add data-edge Data:" + std::to_string(input.first) + ":0->" + input_name +
  2212. ":" + std::to_string(ind) + " failed.";
  2213. return;
  2214. }
  2215. }
  2216. GELOGD("AddDataNodes : Add %u input succ.", input.first);
  2217. }
  2218. GELOGD("AddDataNodes succ.");
  2219. }
  2220. ///
  2221. /// @brief Add data node
  2222. /// @param [in] index
  2223. /// @param [out] error_code
  2224. /// @param [out] error_msg
  2225. /// @return void
  2226. ///
  2227. NodePtr CompleteGraphBuilder::AddDataNode(uint32_t index, graphStatus &error_code, std::string &error_msg) {
  2228. std::string data_name = "Data_" + std::to_string(index);
  2229. OpDescBuilder op_desc_builder(data_name, "Data");
  2230. OpDescPtr op_desc = op_desc_builder.AddInput("x").AddOutput("y").Build();
  2231. if (op_desc == nullptr) {
  2232. error_code = GRAPH_FAILED;
  2233. error_msg = "AddDataNode failed: create op_desc " + data_name + " failed.";
  2234. return nullptr;
  2235. }
  2236. auto index_iter = input_mapping_.find(index);
  2237. if (index_iter != input_mapping_.end()) {
  2238. if (!ge::AttrUtils::SetInt(op_desc, ATTR_NAME_PARENT_NODE_INDEX, index_iter->second)) {
  2239. error_code = GRAPH_FAILED;
  2240. error_msg = "AddDataNode failed: set attr ATTR_NAME_PARENT_NODE_INDEX for " + data_name + " failed.";
  2241. return nullptr;
  2242. }
  2243. }
  2244. NodePtr data_node = owner_graph_->AddNode(op_desc);
  2245. if (data_node == nullptr) {
  2246. error_code = GRAPH_FAILED;
  2247. error_msg = "AddDataNode failed: add node " + data_name + " failed.";
  2248. return nullptr;
  2249. }
  2250. node_names_[data_name] = data_node;
  2251. return data_node;
  2252. }
  2253. ///
  2254. /// @brief Add RetVal nodes
  2255. /// @param [out] error_code
  2256. /// @param [out] error_msg
  2257. /// @return void
  2258. ///
  2259. void CompleteGraphBuilder::AddRetValNodes(graphStatus &error_code, std::string &error_msg) {
  2260. size_t output_num = graph_outputs_.size();
  2261. for (size_t i = 0; i < output_num; i++) {
  2262. int32_t index = graph_outputs_[i].second;
  2263. auto out_iter = node_names_.find(graph_outputs_[i].first);
  2264. if (out_iter == node_names_.end()) {
  2265. error_code = GRAPH_FAILED;
  2266. error_msg = "AddRetValNode failed: node " + graph_outputs_[i].first + " not exist in graph.";
  2267. return;
  2268. }
  2269. NodePtr node = out_iter->second;
  2270. if ((node == nullptr) || (node->GetOpDesc() == nullptr)) {
  2271. error_code = GRAPH_FAILED;
  2272. error_msg = "AddRetValNode failed: node is NULL.";
  2273. return;
  2274. }
  2275. std::string name = node->GetName() + "_RetVal_" + std::to_string(index);
  2276. OpDescPtr ret_val_desc = shared_ptr<OpDesc>(new (std::nothrow) OpDesc(name, FRAMEWORKOP));
  2277. if (ret_val_desc == nullptr) {
  2278. error_code = GRAPH_FAILED;
  2279. error_msg = "AddRetValNode " + name + " failed: op_desc is NULL.";
  2280. return;
  2281. }
  2282. ge::GeTensorDesc tensor = node->GetOpDesc()->GetOutputDesc(index);
  2283. if ((ret_val_desc->AddInputDesc(tensor) != GRAPH_SUCCESS) ||
  2284. (ret_val_desc->AddOutputDesc(tensor) != GRAPH_SUCCESS)) {
  2285. error_code = GRAPH_FAILED;
  2286. error_msg = "AddRetValNode " + name + " failed: add input_desc / output_desc failed.";
  2287. return;
  2288. }
  2289. if (!(ge::AttrUtils::SetStr(ret_val_desc, ATTR_NAME_FRAMEWORK_ORIGINAL_TYPE, "_RetVal") &&
  2290. ge::AttrUtils::SetInt(ret_val_desc, RETVAL_ATTR_NAME_INDEX, i))) {
  2291. error_code = GRAPH_FAILED;
  2292. error_msg = "AddRetValNode " + name + " failed: set FRAMEWORK_ORIGINAL_TYPE / RETVAL_ATTR_NAME_INDEX failed.";
  2293. return;
  2294. }
  2295. auto iter = output_mapping_.find(i);
  2296. if (iter != output_mapping_.end()) {
  2297. if (!ge::AttrUtils::SetInt(ret_val_desc, ATTR_NAME_PARENT_NODE_INDEX, iter->second)) {
  2298. error_code = GRAPH_FAILED;
  2299. error_msg = "AddRetValNode " + name + " failed: set attr PARENT_NODE_INDEX failed.";
  2300. return;
  2301. }
  2302. }
  2303. NodePtr ret_val_node = owner_graph_->AddNode(ret_val_desc);
  2304. if (ret_val_node == nullptr) {
  2305. error_code = GRAPH_FAILED;
  2306. error_msg = "AddRetValNode " + name + " failed: add node failed.";
  2307. return;
  2308. }
  2309. if (GraphUtils::AddEdge(node->GetOutDataAnchor(index), ret_val_node->GetInDataAnchor(0)) != GRAPH_SUCCESS) {
  2310. error_code = GRAPH_FAILED;
  2311. error_msg = "AddRetValNode " + name + " failed: add data-edge " + node->GetName() + ":" + std::to_string(index) +
  2312. "->" + ret_val_node->GetName() + ":0 failed.";
  2313. return;
  2314. }
  2315. }
  2316. GELOGD("AddRetValNodes succ.");
  2317. }
  2318. ///
  2319. /// @brief Build target-nodes for graph
  2320. /// @param [out] error_code
  2321. /// @param [out] error_msg
  2322. /// @return void
  2323. ///
  2324. void CompleteGraphBuilder::BuildGraphTargets(graphStatus &error_code, std::string &error_msg) {
  2325. std::vector<NodePtr> target_nodes;
  2326. for (const std::string &target_name : graph_targets_) {
  2327. auto target_iter = node_names_.find(target_name);
  2328. if ((target_iter == node_names_.end()) || (target_iter->second == nullptr)) {
  2329. error_code = GRAPH_FAILED;
  2330. error_msg = "BuildGraphTargets failed: target_node " + target_name + " not exist in graph.";
  2331. return;
  2332. }
  2333. target_nodes.emplace_back(target_iter->second);
  2334. }
  2335. owner_graph_->SetGraphTargetNodesInfo(target_nodes);
  2336. return;
  2337. }
  2338. ///
  2339. /// @brief Add node to graph
  2340. /// @param [in] op_desc
  2341. /// @return PartialGraphBuilder
  2342. ///
  2343. PartialGraphBuilder &PartialGraphBuilder::AddNode(const OpDescPtr &op_desc) {
  2344. ComputeGraphBuilder::AddNode(op_desc);
  2345. return *this;
  2346. }
  2347. ///
  2348. /// @brief Add data-link among nodes in graph
  2349. /// @param [in] src_name
  2350. /// @param [in] out_anchor_ind
  2351. /// @param [in] dst_name
  2352. /// @param [in] in_anchor_ind
  2353. /// @return PartialGraphBuilder
  2354. ///
  2355. PartialGraphBuilder &PartialGraphBuilder::AddDataLink(const std::string &src_name, uint32_t out_anchor_ind,
  2356. const std::string &dst_name, uint32_t in_anchor_ind) {
  2357. ComputeGraphBuilder::AddDataLink(src_name, out_anchor_ind, dst_name, in_anchor_ind);
  2358. return *this;
  2359. }
  2360. ///
  2361. /// @brief Add ctrl-link among nodes in graph
  2362. /// @param [in] src_name
  2363. /// @param [in] dst_name
  2364. /// @return PartialGraphBuilder
  2365. ///
  2366. PartialGraphBuilder &PartialGraphBuilder::AddControlLink(const std::string &src_name, const std::string &dst_name) {
  2367. ComputeGraphBuilder::AddControlLink(src_name, dst_name);
  2368. return *this;
  2369. }
  2370. ///
  2371. /// @brief Set owner graph
  2372. /// @param [in] graph
  2373. /// @return PartialGraphBuilder
  2374. ///
  2375. PartialGraphBuilder &PartialGraphBuilder::SetOwnerGraph(const ComputeGraphPtr &graph) {
  2376. owner_graph_ = graph;
  2377. return *this;
  2378. }
  2379. ///
  2380. /// @brief Add exist node
  2381. /// @param [in] node
  2382. /// @return PartialGraphBuilder
  2383. ///
  2384. PartialGraphBuilder &PartialGraphBuilder::AddExistNode(const NodePtr &node) {
  2385. exist_nodes_.emplace_back(node);
  2386. return *this;
  2387. }
  2388. ///
  2389. /// @brief Build partial graph
  2390. /// @param [out] error_code
  2391. /// @param [out] error_msg
  2392. /// @return ComputeGraphPtr
  2393. ///
  2394. ComputeGraphPtr PartialGraphBuilder::Build(graphStatus &error_code, std::string &error_msg) {
  2395. if (owner_graph_ == nullptr) {
  2396. error_code = GRAPH_FAILED;
  2397. error_msg = "graph is NULL.";
  2398. return nullptr;
  2399. }
  2400. BuildNodes(error_code, error_msg);
  2401. if (error_code != GRAPH_SUCCESS) {
  2402. return nullptr;
  2403. }
  2404. BuildExistNodes(error_code, error_msg);
  2405. if (error_code != GRAPH_SUCCESS) {
  2406. return nullptr;
  2407. }
  2408. BuildDataLinks(error_code, error_msg);
  2409. if (error_code != GRAPH_SUCCESS) {
  2410. return nullptr;
  2411. }
  2412. BuildCtrlLinks(error_code, error_msg);
  2413. if (error_code != GRAPH_SUCCESS) {
  2414. return nullptr;
  2415. }
  2416. return owner_graph_;
  2417. }
  2418. ///
  2419. /// @brief Build exist nodes
  2420. /// @param [out] error_code
  2421. /// @param [out] error_msg
  2422. /// @return void
  2423. ///
  2424. void PartialGraphBuilder::BuildExistNodes(graphStatus &error_code, std::string &error_msg) {
  2425. std::string node_name;
  2426. for (auto &node : exist_nodes_) {
  2427. if (node == nullptr) {
  2428. error_code = GRAPH_FAILED;
  2429. error_msg = "Build exist nodes failed: node is NULL.";
  2430. return;
  2431. }
  2432. node_name = node->GetName();
  2433. if (node->GetOwnerComputeGraph() != owner_graph_) {
  2434. error_code = GRAPH_FAILED;
  2435. error_msg = "Build exist nodes failed: node " + node_name + " not belongs to this graph.";
  2436. return;
  2437. }
  2438. GELOGD("Add exist_node name:%s.", node_name.c_str());
  2439. node_names_[node_name] = node;
  2440. }
  2441. GELOGD("Build exist nodes succ.");
  2442. }
  2443. GE_FUNC_DEV_VISIBILITY GE_FUNC_HOST_VISIBILITY graphStatus
  2444. GraphUtils::TopologicalSortingByName(const ge::ComputeGraphPtr &compute_graph, vector<NodePtr> &node_vec) {
  2445. std::vector<NodePtr> stack_input;
  2446. std::map<NodePtr, uint32_t> map_in_edge_num;
  2447. graphStatus ret = compute_graph->SortNodes(stack_input, map_in_edge_num);
  2448. if (ret != GRAPH_SUCCESS) {
  2449. GELOGE(GRAPH_FAILED, "Sort nodes failed.");
  2450. return GRAPH_FAILED;
  2451. }
  2452. const size_t non_user_input_index = stack_input.size() - compute_graph->inputs_order_.size() - 1;
  2453. std::sort(stack_input.begin(), stack_input.begin() + non_user_input_index,
  2454. [](const NodePtr &a, const NodePtr &b) -> bool { return (a->GetName() > b->GetName()); });
  2455. std::queue<NodePtr> stack;
  2456. NodePtr cur_node = nullptr;
  2457. std::map<string, NodePtr> name_node_map;
  2458. vector<string> nodes_name;
  2459. while (!stack_input.empty() || !stack.empty()) {
  2460. if (!stack.empty()) {
  2461. cur_node = stack.front();
  2462. stack.pop();
  2463. } else {
  2464. cur_node = stack_input.back();
  2465. stack_input.pop_back();
  2466. }
  2467. node_vec.emplace_back(cur_node);
  2468. compute_graph->CollectBreadthOutNode(cur_node, map_in_edge_num, name_node_map);
  2469. for (const auto &iter : name_node_map) {
  2470. nodes_name.emplace_back(iter.first);
  2471. }
  2472. std::sort(nodes_name.begin(), nodes_name.end());
  2473. for (const auto &iter : nodes_name) {
  2474. stack.push(name_node_map[iter]);
  2475. }
  2476. name_node_map.clear();
  2477. nodes_name.clear();
  2478. }
  2479. // If they are not equal, there is a closed loop
  2480. if (node_vec.size() != compute_graph->nodes_.size()) {
  2481. std::set<Node *> itered_nodes_set;
  2482. for (auto &node : node_vec) {
  2483. itered_nodes_set.insert(node.get());
  2484. }
  2485. GE_LOGE("Failed to do topo sorting total %zu, itered %zu, exist closed loop in graph.",
  2486. compute_graph->nodes_.size(), node_vec.size());
  2487. for (auto &node : compute_graph->nodes_) {
  2488. if (itered_nodes_set.count(node.get()) == 0) {
  2489. GE_LOGE("The node %s does not itered when topological sorting", node->GetName().c_str());
  2490. }
  2491. }
  2492. return GRAPH_FAILED;
  2493. }
  2494. return GRAPH_SUCCESS;
  2495. }
  2496. } // namespace ge

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