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 116 kB

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

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