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.

hybrid_model_builder.cc 118 kB

5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681
  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 "hybrid/model/hybrid_model_builder.h"
  17. #include <algorithm>
  18. #include "common/math/math_util.h"
  19. #include "common/op/ge_op_utils.h"
  20. #include "graph/ge_context.h"
  21. #include "graph/build/memory/var_mem_assign_util.h"
  22. #include "graph/debug/ge_attr_define.h"
  23. #include "graph/common/omg_util.h"
  24. #include "graph/load/model_manager/model_utils.h"
  25. #include "graph/load/model_manager/model_manager.h"
  26. #include "graph/manager/graph_var_manager.h"
  27. #include "graph/manager/host_mem_manager.h"
  28. #include "graph/manager/trans_var_data_utils.h"
  29. #include "graph/manager/graph_mem_manager.h"
  30. #include "graph/utils/graph_utils.h"
  31. #include "hybrid/common/npu_memory_allocator.h"
  32. #include "hybrid/node_executor/node_executor.h"
  33. namespace ge {
  34. namespace hybrid {
  35. using domi::LogTimeStampDef;
  36. using domi::TaskDef;
  37. namespace {
  38. const uint32_t kSubgraphIndex = 0U;
  39. const uint32_t kVarOutputIndex = 0U;
  40. const uint64_t kProfilingFpStartLogid = 1U;
  41. const uint64_t kProfilingBpEndLogid = 2U;
  42. const uint64_t kProfilingIterEndLogid = 65535U;
  43. const int kBytes = 8;
  44. const int kDecimal = 10;
  45. const uint8_t kLoopEnterIdx = 0;
  46. const uint8_t kLoopIterationIdx = 1;
  47. const uint8_t kLoopMergeSize = 2;
  48. const uint8_t kStreamSwitchIdx = 1;
  49. const uint8_t kStreamSwitchNum = 2;
  50. const uint32_t kStringHeadElems = 2;
  51. const char *const kOwnerGraphIsUnknown = "OwnerGraphIsUnknown";
  52. const char *const kProfilingGraph = "ProfilingGraph";
  53. const char *const kProfilingFpNode = "ProfilingFpNode";
  54. const char *const kProfilingBpNode = "ProfilingBpNode";
  55. const char *const kProfilingEndNode = "ProfilingEndNode";
  56. const char *const kProfilingArNode = "ProfilingAllReduceNode";
  57. const char *const kEngineNameRts = "DNN_VM_RTS_OP_STORE";
  58. const char *const kForceInfershape = "_force_infershape_when_running";
  59. const std::set<std::string> kExecutionDependentTypes{ IF, STATELESSIF, CASE, STREAMSWITCH };
  60. const std::set<std::string> kMergeInputSkipTypes{ STREAMACTIVE, STREAMSWITCH, CONSTANT, CONSTANTOP };
  61. const std::set<std::string> kStreamActiveTypes{ ENTER, REFENTER, NEXTITERATION, REFNEXTITERATION };
  62. Status SetOutputNameAttr(ComputeGraph &graph) {
  63. vector<string> output_names;
  64. for (const auto &node : graph.GetDirectNode()) {
  65. auto op_desc = node->GetOpDesc();
  66. if (op_desc == nullptr) {
  67. continue;
  68. }
  69. auto op_type = op_desc->GetType();
  70. if (op_type == NETOUTPUT) {
  71. for (InDataAnchorPtr &in_data_anchor : node->GetAllInDataAnchors()) {
  72. const OutDataAnchorPtr &peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  73. GE_IF_BOOL_EXEC(peer_out_anchor == nullptr, continue);
  74. NodePtr in_node = peer_out_anchor->GetOwnerNode();
  75. GE_CHECK_NOTNULL(in_node);
  76. output_names.push_back(in_node->GetName());
  77. }
  78. }
  79. }
  80. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetListStr(&graph, ATTR_MODEL_OUT_NODES_NAME, output_names),
  81. GELOGE(FAILED, "[Invoke][SetListStr] failed, graph:%s name:%s.", graph.GetName().c_str(),
  82. ATTR_MODEL_OUT_NODES_NAME.c_str());
  83. REPORT_CALL_ERROR("E19999", "SetListStr failed, graph:%s name:%s.", graph.GetName().c_str(),
  84. ATTR_MODEL_OUT_NODES_NAME.c_str());
  85. return FAILED);
  86. return SUCCESS;
  87. }
  88. int64_t CalcVarSizeInBytes(const GeTensorDesc &desc) {
  89. int64_t var_size = 0;
  90. auto data_type = desc.GetDataType();
  91. if (data_type == DT_STRING) {
  92. (void) TensorUtils::GetSize(desc, var_size);
  93. return var_size;
  94. }
  95. if (TensorUtils::GetTensorMemorySizeInBytes(desc, var_size) != GRAPH_SUCCESS) {
  96. GELOGW("Failed to calc var data size");
  97. return -1;
  98. }
  99. return var_size;
  100. }
  101. Status CollectDependenciesForFusedGraph(NodeItem &node_item, std::set<OpDesc *> &data_ops) {
  102. for (const auto &node : node_item.fused_subgraph->nodes) {
  103. auto op_desc = node->GetOpDesc();
  104. GE_CHECK_NOTNULL(op_desc);
  105. const auto &depends = op_desc->GetOpInferDepends();
  106. if (depends.empty()) {
  107. continue;
  108. }
  109. for (auto &input_name : depends) {
  110. auto input_index = op_desc->GetInputIndexByName(input_name);
  111. auto src_node = NodeUtils::GetInDataNodeByIndex(*node, input_index);
  112. GE_CHECK_NOTNULL(src_node);
  113. auto src_op_desc = src_node->GetOpDesc();
  114. GE_CHECK_NOTNULL(src_op_desc);
  115. if (src_node->GetType() != DATA_TYPE) {
  116. GELOGE(UNSUPPORTED, "[Check][NodeType][%s::%s] Node in fused subgraph can only depend on Data nodes,"
  117. "but depend on %s actually", node_item.NodeName().c_str(), node->GetName().c_str(),
  118. src_node->GetType().c_str());
  119. REPORT_INNER_ERROR("E19999", "[%s::%s] Node in fused subgraph can only depend on Data nodes,"
  120. "but depend on %s actually.", node_item.NodeName().c_str(), node->GetName().c_str(),
  121. src_node->GetType().c_str());
  122. return UNSUPPORTED;
  123. }
  124. data_ops.emplace(src_op_desc.get());
  125. }
  126. }
  127. return SUCCESS;
  128. }
  129. } // namespace
  130. HybridModelBuilder::HybridModelBuilder(HybridModel &hybrid_model)
  131. : hybrid_model_(hybrid_model), runtime_param_(hybrid_model.root_runtime_param_) {
  132. ge_root_model_ = hybrid_model_.ge_root_model_;
  133. }
  134. Status HybridModelBuilder::Build() {
  135. GE_CHK_STATUS_RET(ValidateParams(), "[Invoke][ValidateParams] failed, model_name_:[%s]", GetGraphName());
  136. hybrid_model_.model_name_ = ge_root_model_->GetModelName();
  137. GELOGI("[%s] Start to build hybrid model.", GetGraphName());
  138. GE_CHK_STATUS_RET(CopyGraph(), "[Invoke][CopyGraph] failed, model_name_:[%s]", GetGraphName());
  139. GE_CHK_STATUS_RET(InitRuntimeParams(), "[Invoke][InitRuntimeParams] failed, model_name_:[%s]", GetGraphName());
  140. GE_CHK_STATUS_RET(RecoverGraphUnknownFlag(),
  141. "[Invoke][RecoverGraphUnknownFlag] failed, model_name_:[%s]", GetGraphName());
  142. GE_CHK_STATUS_RET(IndexSpecialNodes(), "[Invoke][IndexSpecialNodes] failed, model_name_:[%s]", GetGraphName());
  143. GE_CHK_STATUS_RET(IndexTaskDefs(), "[Invoke][IndexTaskDefs] failed, model_name_:[%s]", GetGraphName());
  144. GE_CHK_STATUS_RET(InitWeights(), "[Invoke][InitWeights] failed, model_name_:[%s]", GetGraphName());
  145. GE_CHK_STATUS_RET(LoadGraph(), "[Invoke][LoadGraph] failed, model_name_:[%s]", GetGraphName());
  146. GE_CHK_STATUS_RET(AssignUninitializedConstantOps(),
  147. "[Invoke][AssignUninitializedConstantOps] failed, model_name_:[%s]", GetGraphName());
  148. GE_CHK_STATUS_RET(TransAllVarData(), "[Invoke][TransAllVarData] failed, model_name_:[%s]", GetGraphName());
  149. GE_CHK_STATUS_RET(CopyVarData(), "[Invoke][CopyVarData] failed, model_name_:[%s]", GetGraphName());
  150. GE_CHK_STATUS_RET(InitModelMem(), "[Invoke][InitModelMem] failed, model_name_:[%s]", GetGraphName());
  151. GE_CHK_STATUS_RET(InitConstantOps(), "[Invoke][InitConstantOps] failed, model_name_:[%s]", GetGraphName());
  152. GE_CHK_STATUS_RET(InitVariableTensors(), "[Invoke][InitVariableTensors], model_name_:[%s]", GetGraphName());
  153. GE_CHK_STATUS_RET(LoadTasks(), "[Invoke][LoadTasks] failed, model_name_:[%s]", GetGraphName());
  154. GE_CHK_STATUS_RET(OptimizeDependenciesForConstantInputs(),
  155. "[Invoke][OptimizeDependenciesForConstantInputs] failed, model_name_:[%s]",
  156. GetGraphName());
  157. GELOGI("[%s] Done building hybrid model successfully.", GetGraphName());
  158. return SUCCESS;
  159. }
  160. Status HybridModelBuilder::BuildForSingleOp() {
  161. GE_CHK_STATUS_RET(ValidateParams(), "[Invoke][ValidateParams] failed, model_name_:[%s]", GetGraphName());
  162. hybrid_model_.root_graph_ = ge_root_model_->GetRootGraph();
  163. hybrid_model_.model_name_ = ge_root_model_->GetRootGraph()->GetName();
  164. GELOGI("[%s] Start to build hybrid model.", GetGraphName());
  165. auto ret = ge_root_model_->GetSubgraphInstanceNameToModel();
  166. const GeModelPtr ge_model = ret[hybrid_model_.root_graph_->GetName()];
  167. GE_CHK_STATUS_RET(IndexTaskDefs(hybrid_model_.root_graph_, ge_model),
  168. "[Invoke][IndexTaskDefs] failed, model_name_:[%s]", GetGraphName());
  169. GE_CHK_STATUS_RET(LoadGraph(), "[Invoke][LoadGraph] failed, model_name_:[%s]", GetGraphName());
  170. GE_CHK_STATUS_RET(InitWeights(), "[Invoke][InitWeights] failed, model_name_:[%s]", GetGraphName());
  171. GE_CHK_STATUS_RET(LoadTasks(), "[Invoke][LoadTasks] failed, model_name_:[%s]", GetGraphName());
  172. GELOGI("[%s] Done building hybrid model for single op successfully.", GetGraphName());
  173. return SUCCESS;
  174. }
  175. Status HybridModelBuilder::ValidateParams() {
  176. GE_CHECK_NOTNULL(ge_root_model_);
  177. GE_CHECK_NOTNULL(ge_root_model_->GetRootGraph());
  178. return SUCCESS;
  179. }
  180. Status HybridModelBuilder::CopyGraph() {
  181. GELOGD("Copy compute graph begin.");
  182. auto root_graph = ge_root_model_->GetRootGraph();
  183. std::string new_graph_name = ge_root_model_->GetRootGraph()->GetName();
  184. ComputeGraphPtr new_root_graph = MakeShared<ComputeGraph>(new_graph_name);
  185. GE_CHECK_NOTNULL(new_root_graph);
  186. int32_t depth = 0;
  187. std::map<ConstNodePtr, NodePtr> node_old_2_new;
  188. std::map<ConstOpDescPtr, OpDescPtr> op_desc_old_2_new;
  189. graphStatus ret = GraphUtils::CopyComputeGraph(root_graph, new_root_graph, node_old_2_new, op_desc_old_2_new, depth);
  190. if (ret != GRAPH_SUCCESS) {
  191. GELOGE(GRAPH_FAILED, "Copy compute graph failed.");
  192. return GRAPH_FAILED;
  193. }
  194. hybrid_model_.root_graph_ = new_root_graph;
  195. GELOGD("Copy compute graph[%s] success.", new_graph_name.c_str());
  196. return SUCCESS;
  197. }
  198. Status HybridModelBuilder::BuildNodeItem(const NodePtr &node, NodeItem &node_item) {
  199. auto op_desc = node->GetOpDesc();
  200. GE_CHK_STATUS_RET(ParseForceInfershapeNodes(node, node_item),
  201. "[Invoke][ParseForceInfershapeNodes]failed, node:[%s].",
  202. node_item.NodeName().c_str());
  203. vector<string> dependencies = node->GetOpDesc()->GetOpInferDepends();
  204. GE_CHK_STATUS_RET(ParseDependentInputNodes(node_item, dependencies),
  205. "[Invoke][ParseDependentInputNodes]failed, node:[%s].",
  206. node_item.NodeName().c_str());
  207. node_item.outputs.resize(node_item.num_outputs);
  208. for (int i = 0; i < node_item.num_outputs; ++i) {
  209. auto out_data_anchor = node->GetOutDataAnchor(i);
  210. if (out_data_anchor == nullptr) {
  211. GELOGE(INTERNAL_ERROR, "[Get][OutDataAnchor]out anchor[%d] of node %s is nullptr", i, node->GetName().c_str());
  212. REPORT_CALL_ERROR("E19999", "out anchor[%d] of node %s is nullptr.", i, node->GetName().c_str());
  213. return INTERNAL_ERROR;
  214. }
  215. for (auto &dst_in_anchor: out_data_anchor->GetPeerInDataAnchors()) {
  216. auto dst_node = dst_in_anchor->GetOwnerNode();
  217. if (dst_node == nullptr) {
  218. GELOGW("dst node is nullptr. out anchor = %d", out_data_anchor->GetIdx());
  219. continue;
  220. }
  221. NodeItem *dst_node_item = nullptr;
  222. GE_CHK_STATUS_RET(GetOrCreateNodeItem(dst_node, &dst_node_item),
  223. "[GetOrCreate][NodeItem] failed, dst_node:[%s].", dst_node->GetName().c_str());
  224. int canonical_index;
  225. GE_CHK_STATUS_RET(dst_node_item->GetCanonicalInputIndex(dst_in_anchor->GetIdx(), canonical_index),
  226. "[Invoke][GetCanonicalInputIndex] failed, dst_node:[%s].", dst_node->GetName().c_str());
  227. node_item.outputs[i].emplace_back(canonical_index, dst_node_item);
  228. node_item.SetDataSend(dst_node_item, dst_in_anchor->GetIdx());
  229. }
  230. }
  231. GE_CHK_STATUS_RET_NOLOG(ResolveRefIo(node_item));
  232. return SUCCESS;
  233. }
  234. Status HybridModelBuilder::ResolveRefIo(NodeItem &node_item) {
  235. bool is_ref = false;
  236. auto &op_desc = *node_item.op_desc;
  237. (void) AttrUtils::GetBool(op_desc, ATTR_NAME_REFERENCE, is_ref);
  238. if (!is_ref) {
  239. return SUCCESS;
  240. }
  241. auto inputs = op_desc.GetAllInputName();
  242. auto outputs = op_desc.GetAllOutputName();
  243. for (auto &output : outputs) {
  244. for (auto &input : inputs) {
  245. if (input.first == output.first) {
  246. int input_idx;
  247. GE_CHK_STATUS_RET_NOLOG(node_item.GetCanonicalInputIndex(input.second, input_idx));
  248. auto output_idx = static_cast<int>(output.second);
  249. node_item.reuse_inputs[output_idx] = input_idx;
  250. GELOGD("[%s] Output[%d] reuse input[%d]", node_item.NodeName().c_str(), output_idx, input_idx);
  251. }
  252. }
  253. }
  254. return SUCCESS;
  255. }
  256. Status HybridModelBuilder::GetOrCreateNodeItem(const NodePtr &node, NodeItem **node_item) {
  257. auto &node_items = hybrid_model_.node_items_;
  258. auto it = node_items.find(node);
  259. if (it != node_items.end()) {
  260. *node_item = it->second.get();
  261. return SUCCESS;
  262. }
  263. if (node->GetType() == MEMCPYASYNC) { // Convert MemcpyAsync to Identity.
  264. node->GetOpDesc()->SetType(IDENTITY);
  265. }
  266. std::unique_ptr<NodeItem> new_node;
  267. GE_CHK_STATUS_RET(NodeItem::Create(node, new_node), "[Invoke][Create] failed, model_name_:[%s]", GetGraphName());
  268. GE_CHK_STATUS_RET_NOLOG(NodeExecutorManager::GetInstance().GetExecutor(*node, &new_node->node_executor));
  269. // we do not need L2 Buffer
  270. const char *const kIsFirstNode = "is_first_node";
  271. const char *const kIsLastNode = "is_last_node";
  272. (void) AttrUtils::SetBool(new_node->op_desc, kIsFirstNode, false);
  273. (void) AttrUtils::SetBool(new_node->op_desc, kIsLastNode, false);
  274. new_node->node_id = static_cast<int>(new_node->op_desc->GetId());
  275. NodeExecutorManager::ExecutorType executor_type = NodeExecutorManager::GetInstance().ResolveExecutorType(*node);
  276. new_node->is_profiling_report = (executor_type == NodeExecutorManager::ExecutorType::AICORE) ||
  277. (executor_type == NodeExecutorManager::ExecutorType::AICPU_TF) ||
  278. (executor_type == NodeExecutorManager::ExecutorType::AICPU_CUSTOM);
  279. *node_item = new_node.get();
  280. node_items[node] = std::move(new_node);
  281. return SUCCESS;
  282. }
  283. Status HybridModelBuilder::ParseForceInfershapeNodes(const NodePtr &node, NodeItem &node_item) {
  284. auto op_desc = node->GetOpDesc();
  285. GE_CHECK_NOTNULL(op_desc);
  286. // not care result, if no this attr, stand for the op does not need force infershape
  287. (void) AttrUtils::GetBool(op_desc, kForceInfershape, node_item.is_need_force_infershape);
  288. GELOGD("node [%s] is need do infershape, flag is %d",
  289. op_desc->GetName().c_str(),
  290. node_item.is_need_force_infershape);
  291. return SUCCESS;
  292. }
  293. Status HybridModelBuilder::ParseDependencies(NodeItem &node_item, const std::vector<string> &dependencies,
  294. std::set<NodePtr> &dependent_for_shape_inference) {
  295. for (const auto &input_name : dependencies) {
  296. int input_index = node_item.op_desc->GetInputIndexByName(input_name);
  297. if (input_index < 0) {
  298. GELOGE(INTERNAL_ERROR, "[Get][InputIndex]failed, node:[%s] inputname: %s.",
  299. node_item.NodeName().c_str(), input_name.c_str());
  300. REPORT_CALL_ERROR("E19999", "GetInputIndexByName failed, node:[%s] inputname: %s.",
  301. node_item.NodeName().c_str(), input_name.c_str());
  302. return INTERNAL_ERROR;
  303. }
  304. const auto &in_anchor = node_item.node->GetInDataAnchor(input_index);
  305. GE_CHECK_NOTNULL(in_anchor);
  306. const auto &peer_out_anchor = in_anchor->GetPeerOutAnchor();
  307. GE_CHECK_NOTNULL(peer_out_anchor);
  308. const auto &src_node = peer_out_anchor->GetOwnerNode();
  309. GE_CHECK_NOTNULL(src_node);
  310. auto src_node_item = MutableNodeItem(src_node);
  311. GE_CHECK_NOTNULL(src_node_item);
  312. if (src_node_item->NodeType() == DATA) {
  313. auto op_desc = src_node_item->GetOpDesc();
  314. GE_CHECK_NOTNULL(op_desc);
  315. auto tensor = op_desc->MutableInputDesc(0);
  316. if (AttrUtils::HasAttr(tensor, ATTR_NAME_VALUE)) {
  317. GELOGD("Skip d2h memcpy, get hostmem from node %s.", src_node_item->NodeName().c_str());
  318. continue;
  319. }
  320. }
  321. src_node_item->to_const_output_id_list.emplace(peer_out_anchor->GetIdx());
  322. dependent_for_shape_inference.emplace(src_node);
  323. host_input_value_dependencies_[&node_item].emplace_back(peer_out_anchor->GetIdx(), src_node_item);
  324. GELOGD("[%s] Dependent added from output of [%s:%d]",
  325. node_item.NodeName().c_str(),
  326. src_node_item->NodeName().c_str(),
  327. peer_out_anchor->GetIdx());
  328. }
  329. return SUCCESS;
  330. }
  331. Status HybridModelBuilder::ParseDependentInputNodes(NodeItem &node_item, const std::vector<string> &dependencies) {
  332. std::set<NodePtr> dependent_for_shape_inference;
  333. std::set<NodePtr> dependent_for_execution;
  334. auto &ge_node = node_item.node;
  335. bool is_hccl_op = node_item.IsHcclOp();
  336. // The input tensors become valid after computation is done for parent nodes of type DEPEND_COMPUTE.
  337. // Wait for these parent nodes before execution.
  338. for (const auto &in_anchor : ge_node->GetAllInDataAnchors()) {
  339. const auto &peer_anchor = in_anchor->GetPeerOutAnchor();
  340. if (peer_anchor == nullptr) {
  341. GELOGD("[%s] Input[%d] do not have peer anchor", node_item.NodeName().c_str(), in_anchor->GetIdx());
  342. continue;
  343. }
  344. auto src_node = peer_anchor->GetOwnerNode();
  345. GE_CHECK_NOTNULL(src_node);
  346. NodeItem *src_node_item = nullptr;
  347. GE_CHK_STATUS_RET(GetOrCreateNodeItem(src_node, &src_node_item),
  348. "[%s] failed to get or create node item", src_node->GetName().c_str());
  349. if (src_node_item->shape_inference_type == DEPEND_COMPUTE || is_hccl_op || src_node_item->IsHcclOp()) {
  350. GELOGD("[%s](%s) Add input data dependent node [%s](%s), shape inference type = %d",
  351. ge_node->GetName().c_str(),
  352. ge_node->GetType().c_str(),
  353. src_node->GetName().c_str(),
  354. src_node->GetType().c_str(),
  355. static_cast<int>(src_node_item->shape_inference_type));
  356. src_node_item->has_observer = true;
  357. dependent_for_execution.emplace(src_node);
  358. }
  359. if (src_node_item->shape_inference_type == DEPEND_SHAPE_RANGE) {
  360. GELOGD("[%s] Add input shape dependent node [%s] due to inference type = DEPEND_SHAPE_RANGE",
  361. node_item.NodeName().c_str(),
  362. src_node_item->NodeName().c_str());
  363. src_node_item->has_observer = true;
  364. dependent_for_shape_inference.emplace(src_node);
  365. }
  366. }
  367. if (node_item.node_type == NETOUTPUT) {
  368. for (const auto &src_node : ge_node->GetInControlNodes()) {
  369. auto src_node_item = MutableNodeItem(src_node);
  370. if ((src_node_item != nullptr) && src_node_item->IsHcclOp()) {
  371. GELOGD("[%s](%s) Add input control dependent node [%s](%s)",
  372. ge_node->GetName().c_str(),
  373. ge_node->GetType().c_str(),
  374. src_node->GetName().c_str(),
  375. src_node->GetType().c_str());
  376. dependent_for_execution.emplace(src_node);
  377. }
  378. }
  379. }
  380. // cond or branch need to be prepared before the execution of IF or CASE
  381. if (kExecutionDependentTypes.count(node_item.node_type) > 0) {
  382. auto src_node = NodeUtils::GetInDataNodeByIndex(*ge_node, 0); // cond input
  383. GE_CHECK_NOTNULL(src_node);
  384. auto src_node_item = MutableNodeItem(src_node);
  385. GE_CHECK_NOTNULL(src_node_item);
  386. dependent_for_execution.emplace(src_node);
  387. GELOGD("[%s] Dependent added from %s for control op's cond/branch",
  388. node_item.NodeName().c_str(),
  389. src_node_item->NodeName().c_str());
  390. }
  391. GE_CHK_STATUS_RET(ParseDependencies(node_item, dependencies, dependent_for_shape_inference));
  392. GE_CHK_STATUS_RET(ParseDependentForFusedSubgraph(node_item, dependent_for_shape_inference));
  393. for (const auto &dep_node : dependent_for_shape_inference) {
  394. auto src_node_item = MutableNodeItem(dep_node);
  395. GE_CHECK_NOTNULL(src_node_item);
  396. src_node_item->has_observer = true;
  397. node_item.dependents_for_shape_inference.emplace_back(dep_node);
  398. }
  399. for (const auto &dep_node : dependent_for_execution) {
  400. auto src_node_item = MutableNodeItem(dep_node);
  401. GE_CHECK_NOTNULL(src_node_item);
  402. src_node_item->has_observer = true;
  403. node_item.dependents_for_execution.emplace_back(dep_node);
  404. }
  405. return SUCCESS;
  406. }
  407. Status HybridModelBuilder::ParseDependentForFusedSubgraph(NodeItem &node_item, std::set<ge::NodePtr> &dependencies) {
  408. if (node_item.fused_subgraph == nullptr) {
  409. return SUCCESS;
  410. }
  411. std::set<OpDesc *> data_ops;
  412. GE_CHK_STATUS_RET_NOLOG(CollectDependenciesForFusedGraph(node_item, data_ops));
  413. for (auto &op_desc : data_ops) {
  414. uint32_t parent_index = 0;
  415. if (!AttrUtils::GetInt(*op_desc, ATTR_NAME_PARENT_NODE_INDEX, parent_index)) {
  416. GELOGE(INTERNAL_ERROR, "[Invoke][GetInt] failed, node:[%s] attr:[%s]",
  417. op_desc->GetName().c_str(), ATTR_NAME_PARENT_NODE_INDEX.c_str());
  418. REPORT_CALL_ERROR("E19999", "invoke GetInt failed, node:[%s] attr:[%s]",
  419. op_desc->GetName().c_str(), ATTR_NAME_PARENT_NODE_INDEX.c_str());
  420. return INTERNAL_ERROR;
  421. }
  422. const auto &in_anchor = node_item.node->GetInDataAnchor(parent_index);
  423. GE_CHECK_NOTNULL(in_anchor);
  424. const auto &peer_out_anchor = in_anchor->GetPeerOutAnchor();
  425. GE_CHECK_NOTNULL(peer_out_anchor);
  426. const auto &src_node = peer_out_anchor->GetOwnerNode();
  427. GE_CHECK_NOTNULL(src_node);
  428. NodeItem *src_node_item = nullptr;
  429. GE_CHK_STATUS_RET_NOLOG(GetOrCreateNodeItem(src_node, &src_node_item));
  430. op_desc->SetId(src_node_item->op_desc->GetId());
  431. GELOGD("[%s::%s] Node id was set to that of outer src node's, src_node = %s",
  432. node_item.NodeName().c_str(),
  433. op_desc->GetName().c_str(),
  434. src_node_item->NodeName().c_str());
  435. src_node_item->to_const_output_id_list.emplace(peer_out_anchor->GetIdx());
  436. dependencies.emplace(src_node);
  437. GELOGD("[%s] Dependent added from output of [%s:%d]",
  438. node_item.NodeName().c_str(),
  439. src_node_item->NodeName().c_str(),
  440. peer_out_anchor->GetIdx());
  441. }
  442. return SUCCESS;
  443. }
  444. Status HybridModelBuilder::UpdateAnchorStatus(const NodePtr &node) {
  445. if (NodeUtils::SetAllAnchorStatus(node) != GRAPH_SUCCESS) {
  446. GELOGE(INTERNAL_ERROR, "[Invoke][SetAllAnchorStatus] failed, node:[%s].", node->GetName().c_str());
  447. REPORT_CALL_ERROR("E19999", "[%s] NodeUtils::SetAllAnchorStatus failed.", node->GetName().c_str());
  448. return INTERNAL_ERROR;
  449. }
  450. for (auto &anchor : node->GetAllInDataAnchors()) {
  451. auto peer_anchor = anchor->GetPeerOutAnchor();
  452. if (peer_anchor == nullptr) {
  453. if (AnchorUtils::SetStatus(anchor, ANCHOR_SUSPEND) != GRAPH_SUCCESS) {
  454. GELOGE(INTERNAL_ERROR, "[Invoke][SetStatus] failed to set ANCHOR_SUSPEND, node:[%s].",
  455. node->GetName().c_str());
  456. REPORT_CALL_ERROR("E19999", "SetStatus failed to set ANCHOR_SUSPEND, node:[%s].", node->GetName().c_str());
  457. return INTERNAL_ERROR;
  458. }
  459. } else if (peer_anchor->GetOwnerNode()->GetType() == CONSTANT) {
  460. if (AnchorUtils::SetStatus(anchor, ANCHOR_CONST) != GRAPH_SUCCESS) {
  461. GELOGE(INTERNAL_ERROR, "[Invoke][SetStatus] failed to set ANCHOR_CONST, node:[%s].", node->GetName().c_str());
  462. REPORT_CALL_ERROR("E19999", "SetStatus failed to set ANCHOR_CONST, node:[%s].", node->GetName().c_str());
  463. return INTERNAL_ERROR;
  464. }
  465. } else {
  466. if (AnchorUtils::SetStatus(anchor, ANCHOR_DATA) != GRAPH_SUCCESS) {
  467. GELOGE(INTERNAL_ERROR, "[Invoke][SetStatus] failed to set ANCHOR_DATA, node:[%s].", node->GetName().c_str());
  468. REPORT_CALL_ERROR("E19999", "SetStatus failed to set ANCHOR_DATA, node:[%s].", node->GetName().c_str());
  469. return INTERNAL_ERROR;
  470. }
  471. }
  472. }
  473. return SUCCESS;
  474. }
  475. Status HybridModelBuilder::DoUnlinkDataAnchors(const OutDataAnchorPtr &out_data_anchor,
  476. const InDataAnchorPtr &in_data_anchor) {
  477. GE_CHK_GRAPH_STATUS_RET(out_data_anchor->Unlink(in_data_anchor),
  478. "[Invoke][Unlink] failed to unlink %s:%d from %s:%d",
  479. out_data_anchor->GetOwnerNode()->GetName().c_str(), out_data_anchor->GetIdx(),
  480. in_data_anchor->GetOwnerNode()->GetName().c_str(), in_data_anchor->GetIdx());
  481. GELOGD("Succeeded in unlinking %s:%d from %s:%d",
  482. out_data_anchor->GetOwnerNode()->GetName().c_str(),
  483. out_data_anchor->GetIdx(),
  484. in_data_anchor->GetOwnerNode()->GetName().c_str(),
  485. in_data_anchor->GetIdx());
  486. return SUCCESS;
  487. }
  488. Status HybridModelBuilder::DoLinkDataAnchors(OutDataAnchorPtr &out_data_anchor, InDataAnchorPtr &in_data_anchor) {
  489. GE_CHK_GRAPH_STATUS_RET(out_data_anchor->LinkTo(in_data_anchor), "[Invoke][LinkTo]Failed to link %s:%d to %s:%d",
  490. out_data_anchor->GetOwnerNode()->GetName().c_str(),
  491. out_data_anchor->GetIdx(),
  492. in_data_anchor->GetOwnerNode()->GetName().c_str(),
  493. in_data_anchor->GetIdx());
  494. GELOGD("Succeeded in linking %s:%d to %s:%d",
  495. out_data_anchor->GetOwnerNode()->GetName().c_str(),
  496. out_data_anchor->GetIdx(),
  497. in_data_anchor->GetOwnerNode()->GetName().c_str(),
  498. in_data_anchor->GetIdx());
  499. return SUCCESS;
  500. }
  501. Status HybridModelBuilder::MergeInputNodes(ComputeGraph &graph) {
  502. const auto &wrapped_node = graph.GetParentNode();
  503. std::set<NodePtr> root_nodes;
  504. for (const auto &node : graph.GetDirectNode()) {
  505. GE_CHECK_NOTNULL(node);
  506. if (node->GetType() != DATA_TYPE) {
  507. if (node->GetInDataNodes().empty()) {
  508. root_nodes.emplace(node);
  509. }
  510. continue;
  511. }
  512. auto data_op_desc = node->GetOpDesc();
  513. GE_CHECK_NOTNULL(data_op_desc);
  514. uint32_t parent_index = 0;
  515. if (!AttrUtils::GetInt(data_op_desc, ATTR_NAME_PARENT_NODE_INDEX, parent_index)) {
  516. GELOGE(FAILED, "[Invoke][GetInt] failed, node:[%s] attr:[%s]",
  517. data_op_desc->GetName().c_str(), ATTR_NAME_PARENT_NODE_INDEX.c_str());
  518. REPORT_CALL_ERROR("E19999", "GetInt failed, node:[%s] attr:[%s]",
  519. data_op_desc->GetName().c_str(), ATTR_NAME_PARENT_NODE_INDEX.c_str());
  520. return FAILED;
  521. }
  522. auto wrapped_node_in_anchor = wrapped_node->GetInDataAnchor(parent_index);
  523. GE_CHECK_NOTNULL(wrapped_node_in_anchor);
  524. auto src_out_anchor = wrapped_node_in_anchor->GetPeerOutAnchor();
  525. if (src_out_anchor == nullptr || src_out_anchor->GetOwnerNode() == nullptr) {
  526. continue;
  527. }
  528. wrapped_node_in_anchor->UnlinkAll();
  529. // link src to outputs of DataNode
  530. for (auto &out_data_anchor : node->GetAllOutDataAnchors()) {
  531. GE_CHECK_NOTNULL(out_data_anchor);
  532. for (auto &peer_in_data_anchor : out_data_anchor->GetPeerInDataAnchors()) {
  533. auto dst_node = peer_in_data_anchor->GetOwnerNode();
  534. GE_CHECK_NOTNULL(dst_node);
  535. root_nodes.emplace(dst_node);
  536. GE_CHK_STATUS_RET_NOLOG(DoUnlinkDataAnchors(out_data_anchor, peer_in_data_anchor));
  537. GE_CHK_STATUS_RET_NOLOG(DoLinkDataAnchors(src_out_anchor, peer_in_data_anchor));
  538. }
  539. }
  540. }
  541. // transfer in control edges to all root nodes
  542. for (auto &root_node : root_nodes) {
  543. auto in_nodes = root_node->GetInAllNodes();
  544. std::set<NodePtr> in_node_set(in_nodes.begin(), in_nodes.end());
  545. for (auto &in_control_node : wrapped_node->GetInControlNodes()) {
  546. if (in_node_set.count(in_control_node) == 0 && kMergeInputSkipTypes.count(root_node->GetType()) == 0) {
  547. GELOGD("[%s] Restore control edge to [%s]", in_control_node->GetName().c_str(), root_node->GetName().c_str());
  548. GE_CHECK_NOTNULL(in_control_node->GetOutControlAnchor());
  549. (void) in_control_node->GetOutControlAnchor()->LinkTo(root_node->GetInControlAnchor());
  550. }
  551. }
  552. }
  553. wrapped_node->GetInControlAnchor()->UnlinkAll();
  554. return SUCCESS;
  555. }
  556. Status HybridModelBuilder::MergeNetOutputNode(ComputeGraph &graph) {
  557. const auto &parent_node = graph.GetParentNode();
  558. const NodePtr &net_output_node = graph.FindFirstNodeMatchType(NETOUTPUT);
  559. if (net_output_node == nullptr) {
  560. GELOGD("Graph has no netoutput no need to merge");
  561. return SUCCESS;
  562. }
  563. const auto &net_output_desc = net_output_node->GetOpDesc();
  564. GE_CHECK_NOTNULL(net_output_desc);
  565. auto all_in_nodes = net_output_node->GetInAllNodes();
  566. auto all_out_nodes = parent_node->GetOutAllNodes();
  567. net_output_node->GetInControlAnchor()->UnlinkAll();
  568. parent_node->GetOutControlAnchor()->UnlinkAll();
  569. for (const auto &in_data_anchor : net_output_node->GetAllInDataAnchors()) {
  570. auto src_out_anchor = in_data_anchor->GetPeerOutAnchor();
  571. GE_CHECK_NOTNULL(src_out_anchor);
  572. GE_CHECK_NOTNULL(src_out_anchor->GetOwnerNode());
  573. GE_CHK_STATUS_RET_NOLOG(DoUnlinkDataAnchors(src_out_anchor, in_data_anchor));
  574. auto index = in_data_anchor->GetIdx();
  575. auto input_desc = net_output_desc->MutableInputDesc(index);
  576. if (input_desc == nullptr) {
  577. GELOGE(INTERNAL_ERROR, "[Invoke][MutableInputDesc][%s] Failed to get input desc[%d]",
  578. net_output_desc->GetName().c_str(), index);
  579. REPORT_CALL_ERROR("E19999", "[%s] Failed to get input desc[%d].", net_output_desc->GetName().c_str(), index);
  580. return INTERNAL_ERROR;
  581. }
  582. uint32_t parent_index = 0;
  583. if (!AttrUtils::GetInt(input_desc, ATTR_NAME_PARENT_NODE_INDEX, parent_index)) {
  584. GELOGW("SubGraph: %s NetOutput input tensor %d, attr %s not found.",
  585. graph.GetName().c_str(), index, ATTR_NAME_PARENT_NODE_INDEX.c_str());
  586. continue;
  587. }
  588. const OutDataAnchorPtr &parent_out_anchor = parent_node->GetOutDataAnchor(parent_index);
  589. GE_CHECK_NOTNULL(parent_out_anchor);
  590. for (InDataAnchorPtr &dst_in_anchor : parent_out_anchor->GetPeerInDataAnchors()) {
  591. if (dst_in_anchor == nullptr) {
  592. continue;
  593. }
  594. GE_CHECK_NOTNULL(dst_in_anchor->GetOwnerNode());
  595. GE_CHK_STATUS_RET_NOLOG(DoUnlinkDataAnchors(parent_out_anchor, dst_in_anchor));
  596. GE_CHK_STATUS_RET_NOLOG(DoLinkDataAnchors(src_out_anchor, dst_in_anchor));
  597. }
  598. }
  599. // transfer out control edges
  600. std::set<NodePtr> in_node_set(all_in_nodes.begin(), all_in_nodes.end());
  601. std::set<NodePtr> out_node_set(all_out_nodes.begin(), all_out_nodes.end());
  602. for (auto &src_node : in_node_set) {
  603. GELOGD("[%s] process in node.", src_node->GetName().c_str());
  604. auto out_nodes = src_node->GetOutAllNodes();
  605. std::set<NodePtr> node_set(out_nodes.begin(), out_nodes.end());
  606. for (auto &dst_node : out_node_set) {
  607. if (node_set.count(dst_node) == 0) {
  608. src_node->GetOutControlAnchor()->LinkTo(dst_node->GetInControlAnchor());
  609. GELOGD("[%s] Restore control edge to [%s]", src_node->GetName().c_str(), dst_node->GetName().c_str());
  610. }
  611. }
  612. }
  613. return SUCCESS;
  614. }
  615. Status HybridModelBuilder::UnfoldSubgraphs(ComputeGraphPtr &root_graph, ComputeGraphPtr &merged_graph) {
  616. merged_graph = MakeShared<ComputeGraph>("MergedGraph");
  617. merged_graph->SetGraphUnknownFlag(root_graph->GetGraphUnknownFlag());
  618. for (const auto &node : root_graph->GetDirectNode()) {
  619. GE_CHECK_NOTNULL(node);
  620. auto op_desc = node->GetOpDesc();
  621. GE_CHECK_NOTNULL(op_desc);
  622. const auto &op_type = node->GetType();
  623. if (op_type != PARTITIONEDCALL) {
  624. merged_graph->AddNode(node);
  625. GELOGD("[%s] Node added to merged graph.", op_desc->GetName().c_str());
  626. continue;
  627. }
  628. auto subgraph = NodeUtils::GetSubgraph(*node, kSubgraphIndex);
  629. GE_CHECK_NOTNULL(subgraph);
  630. bool is_unknown_shape = subgraph->GetGraphUnknownFlag();
  631. if (!is_unknown_shape) {
  632. merged_graph->AddNode(node);
  633. GELOGD("[%s] Known shape partitioned call added to merged graph.", op_desc->GetName().c_str());
  634. continue;
  635. }
  636. if (op_desc->HasAttr(ATTR_STAGE_LEVEL)) {
  637. uint32_t stage_level = UINT32_MAX;
  638. if (AttrUtils::GetInt(node->GetOpDesc(), ATTR_STAGE_LEVEL, stage_level)) {
  639. for (const auto &stage_node : subgraph->GetAllNodes()) {
  640. GELOGD("Set ATTR_STAGE_LEVEL on node %s, stage_level=%u", stage_node->GetName().c_str(), stage_level);
  641. (void)AttrUtils::SetInt(stage_node->GetOpDesc(), ATTR_STAGE_LEVEL, stage_level);
  642. }
  643. }
  644. }
  645. GE_CHK_GRAPH_STATUS_RET(UnfoldSubgraph(root_graph, merged_graph, *subgraph),
  646. "[Invoke][UnfoldSubgraph][%s] Failed to merge subgraph.",
  647. subgraph->GetName().c_str());
  648. }
  649. // invoke before adding subgraphs. in case modify node id in known-shaped subgraphs.
  650. GE_CHK_GRAPH_STATUS_RET(merged_graph->TopologicalSorting(),
  651. "[Invoke][TopologicalSorting]Failed to invoke TopologicalSorting on merged graph.");
  652. GE_DUMP(merged_graph, "hybrid_merged_graph_BeforeStageSort");
  653. merged_graph->TopologicalSorting([](const NodePtr &a, const NodePtr &b) -> bool {
  654. uint32_t a_level = UINT32_MAX;
  655. (void)AttrUtils::GetInt(a->GetOpDesc(), ATTR_STAGE_LEVEL, a_level);
  656. uint32_t b_level = UINT32_MAX;
  657. (void)AttrUtils::GetInt(b->GetOpDesc(), ATTR_STAGE_LEVEL, b_level);
  658. return a_level < b_level;
  659. });
  660. for (auto &remained_subgraph : root_graph->GetAllSubgraphs()) {
  661. GELOGD("Adding subgraph [%s] to merged-graph.", remained_subgraph->GetName().c_str());
  662. GE_CHK_GRAPH_STATUS_RET(merged_graph->AddSubgraph(remained_subgraph),
  663. "[Invoke][AddSubgraph]Failed to add subgraph [%s]",
  664. remained_subgraph->GetName().c_str());
  665. remained_subgraph->SetParentGraph(merged_graph);
  666. }
  667. return SUCCESS;
  668. }
  669. Status HybridModelBuilder::UnfoldSubgraph(ComputeGraphPtr &root_graph,
  670. ComputeGraphPtr &parent_graph,
  671. ComputeGraph &sub_graph) {
  672. auto parent_node = sub_graph.GetParentNode();
  673. GE_CHECK_NOTNULL(parent_node);
  674. GE_CHK_STATUS_RET(MergeInputNodes(sub_graph),
  675. "[Invoke][MergeInputNodes][%s] Failed to merge data nodes for subgraph",
  676. sub_graph.GetName().c_str());
  677. GE_CHK_STATUS_RET(MergeNetOutputNode(sub_graph),
  678. "[Invoke][MergeNetOutputNode][%s] Failed to merge net output nodes for subgraph",
  679. sub_graph.GetName().c_str());
  680. GELOGD("[%s] Done merging subgraph inputs and outputs successfully", sub_graph.GetName().c_str());
  681. for (auto &sub_node : sub_graph.GetDirectNode()) {
  682. auto sub_op_type = sub_node->GetType();
  683. if (sub_op_type == DATA_TYPE || sub_op_type == NETOUTPUT) {
  684. continue;
  685. }
  686. if (sub_op_type == PARTITIONEDCALL) {
  687. auto sub_sub_graph = NodeUtils::GetSubgraph(*sub_node, kSubgraphIndex);
  688. GE_CHECK_NOTNULL(sub_sub_graph);
  689. if (sub_sub_graph->GetGraphUnknownFlag()) {
  690. GE_CHK_STATUS_RET(UnfoldSubgraph(root_graph, parent_graph, *sub_sub_graph),
  691. "[Invoke][UnfoldSubgraph][%s] Failed to merge subgraph",
  692. sub_sub_graph->GetName().c_str());
  693. continue;
  694. }
  695. }
  696. if (!sub_node->GetOpDesc()->GetSubgraphInstanceNames().empty()) {
  697. for (size_t i = 0; i < sub_node->GetOpDesc()->GetSubgraphInstanceNames().size(); ++i) {
  698. auto sub_sub_graph = NodeUtils::GetSubgraph(*sub_node, i);
  699. GE_CHECK_NOTNULL(sub_sub_graph);
  700. sub_sub_graph->SetParentGraph(parent_graph);
  701. }
  702. }
  703. parent_graph->AddNode(sub_node);
  704. GELOGD("[%s::%s] added to parent graph: [%s].",
  705. sub_graph.GetName().c_str(),
  706. sub_node->GetName().c_str(),
  707. parent_graph->GetName().c_str());
  708. sub_node->SetOwnerComputeGraph(parent_graph);
  709. }
  710. GELOGD("[%s] Done merging subgraph. remove it from root graph", sub_graph.GetName().c_str());
  711. root_graph->RemoveSubgraph(sub_graph.GetName());
  712. return SUCCESS;
  713. }
  714. Status HybridModelBuilder::BuildOutputMapping(GraphItem &graph_item,
  715. const NodeItem &node_item,
  716. bool is_root_graph) {
  717. auto output_size = node_item.num_inputs;
  718. graph_item.output_edges_.resize(output_size);
  719. for (auto &in_data_anchor : node_item.node->GetAllInDataAnchors()) {
  720. auto peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  721. GE_CHECK_NOTNULL(peer_out_anchor);
  722. auto src_node = peer_out_anchor->GetOwnerNode();
  723. GE_CHECK_NOTNULL(src_node);
  724. auto src_node_item = GetNodeItem(src_node);
  725. GE_CHECK_NOTNULL(src_node_item);
  726. auto output_idx = in_data_anchor->GetIdx();
  727. auto output_offset = src_node_item->output_start + peer_out_anchor->GetIdx();
  728. GELOGI("Output[%d], node = %s, output_index = %d, output_offset = %d ",
  729. output_idx,
  730. src_node_item->NodeName().c_str(),
  731. peer_out_anchor->GetIdx(),
  732. output_offset);
  733. GE_CHECK_LE(output_idx, output_size - 1);
  734. graph_item.output_edges_[output_idx] = {src_node_item, peer_out_anchor->GetIdx()};
  735. }
  736. if (!is_root_graph) {
  737. for (uint32_t i = 0; i < static_cast<uint32_t>(output_size); ++i) {
  738. uint32_t p_index = i;
  739. // Net output of Subgraph of while do not have parent index
  740. if (AttrUtils::GetInt(node_item.op_desc->GetInputDesc(i), ATTR_NAME_PARENT_NODE_INDEX, p_index)) {
  741. GELOGD("[%s] Parent index not set for input[%u].", node_item.NodeName().c_str(), i);
  742. }
  743. graph_item.output_index_mapping_.emplace_back(p_index);
  744. }
  745. }
  746. return SUCCESS;
  747. }
  748. Status HybridModelBuilder::LoadGraph() {
  749. auto root_graph = hybrid_model_.root_graph_;
  750. if (!GetContext().GetHostExecFlag()) {
  751. std::shared_ptr<ComputeGraph> merged_graph;
  752. GELOGI("Before merging subgraphs DirectNodesSize = %zu, GetAllNodesSize = %zu",
  753. root_graph->GetDirectNodesSize(),
  754. root_graph->GetAllNodesSize());
  755. hybrid_model_.orig_root_graph_ = root_graph;
  756. GE_CHK_GRAPH_STATUS_RET(UnfoldSubgraphs(root_graph, merged_graph),
  757. "[Invoke][UnfoldSubgraphs]Failed to unfold subgraphs, model_name_:%s.", GetGraphName());
  758. root_graph = std::move(merged_graph);
  759. GELOGI("After merging subgraphs DirectNodesSize = %zu, GetAllNodesSize = %zu",
  760. root_graph->GetDirectNodesSize(),
  761. root_graph->GetAllNodesSize());
  762. }
  763. hybrid_model_.root_graph_ = root_graph;
  764. GE_CHK_STATUS_RET(RelinkNextIteration(), "[%s] Relink NextIteration failed", GetGraphName());
  765. // Reset node id by topological order across all subgraphs
  766. int64_t index = 0;
  767. for (const auto &node : root_graph->GetAllNodes()) {
  768. GE_CHECK_NOTNULL(node);
  769. auto parent_graph = node->GetOwnerComputeGraph();
  770. // No need to update nodes in known subgraph
  771. if (parent_graph != nullptr && !parent_graph->GetGraphUnknownFlag()) {
  772. continue;
  773. }
  774. auto op_desc = node->GetOpDesc();
  775. GE_CHECK_NOTNULL(op_desc);
  776. op_desc->SetId(index++);
  777. }
  778. GE_DUMP(root_graph, "hybrid_merged_graph");
  779. GE_CHK_STATUS_RET(LoadDynamicSubgraph(*root_graph, true),
  780. "[Invoke][LoadDynamicSubgraph]Failed to load root graph, model_name_:%s.", GetGraphName());
  781. GELOGD("Done loading root graph successfully.");
  782. GE_CHK_STATUS_RET(hybrid_model_.root_graph_item_->GroupNodes(),
  783. "[Invoke][GroupNodes]Failed to group nodes for root graph, model_name_:%s.", GetGraphName());
  784. for (auto &sub_graph : root_graph->GetAllSubgraphs()) {
  785. GE_CHECK_NOTNULL(sub_graph);
  786. GELOGD("Start to load subgraph [%s]", sub_graph->GetName().c_str());
  787. auto parent_node = sub_graph->GetParentNode();
  788. GE_CHECK_NOTNULL(parent_node);
  789. auto parent_node_item = MutableNodeItem(parent_node);
  790. // parent node is in another known subgraph
  791. if (parent_node_item == nullptr) {
  792. GELOGD("[%s] Subgraph is in another known shaped subgraph, skip it.", sub_graph->GetName().c_str());
  793. continue;
  794. }
  795. if (sub_graph->GetGraphUnknownFlag()) {
  796. GE_CHK_STATUS_RET(LoadDynamicSubgraph(*sub_graph, false),
  797. "[Invoke][LoadDynamicSubgraph]Failed to load subgraph: [%s]",
  798. sub_graph->GetName().c_str());
  799. } else {
  800. // if parent is function control op. need add a virtual partitioned call
  801. if (parent_node_item->IsControlFlowV2Op()) {
  802. GE_CHK_STATUS_RET(LoadKnownShapedSubgraph(*sub_graph, parent_node_item),
  803. "[Invoke][LoadKnownShapedSubgraph]Failed to load function control op subgraph [%s]",
  804. sub_graph->GetName().c_str());
  805. }
  806. }
  807. }
  808. for (auto &it : hybrid_model_.known_shape_sub_models_) {
  809. auto node_item = MutableNodeItem(it.first);
  810. GE_CHECK_NOTNULL(node_item);
  811. AscendString graph_name;
  812. GE_CHK_GRAPH_STATUS_RET(it.second->GetGraph().GetName(graph_name), "Failed to get subgraph name");
  813. auto subgraph = hybrid_model_.GetRootGraph()->GetSubgraph(graph_name.GetString());
  814. GE_CHECK_NOTNULL(subgraph);
  815. GE_CHK_STATUS_RET(IdentifyVariableOutputs(*node_item, subgraph),
  816. "[Invoke][IdentifyVariableOutputs][%s] Failed to identify ref outputs.",
  817. node_item->NodeName().c_str());
  818. }
  819. GE_CHK_STATUS_RET(ParseDependentByParallelGroup(),
  820. "[Invoke][ParseDependentByParallelGroup]Failed to establish dependencies for hccl ops,"
  821. "model_name_:%s.", GetGraphName());
  822. GELOGI("Done loading all subgraphs successfully.");
  823. return SUCCESS;
  824. }
  825. const NodeItem *HybridModelBuilder::GetNodeItem(const NodePtr &node) const {
  826. return hybrid_model_.GetNodeItem(node);
  827. }
  828. NodeItem *HybridModelBuilder::MutableNodeItem(const NodePtr &node) {
  829. return hybrid_model_.MutableNodeItem(node);
  830. }
  831. Status HybridModelBuilder::VarNodeToTensor(const NodePtr &var_node, std::unique_ptr<TensorValue> &tensor) {
  832. string var_name = var_node->GetName();
  833. auto tensor_desc = var_node->GetOpDesc()->MutableOutputDesc(0);
  834. uint8_t *var_logic = nullptr;
  835. GE_CHK_STATUS_RET(var_manager_->GetVarAddr(var_name, *tensor_desc, &var_logic),
  836. "[Invoke][GetVarAddr]Failed to get var addr. var_name = %s, session_id = %ld",
  837. var_name.c_str(),
  838. hybrid_model_.GetSessionId());
  839. rtMemType_t memory_type = RT_MEMORY_HBM;
  840. uint32_t mem_type = 0;
  841. if (AttrUtils::GetInt(var_node->GetOpDesc(), ATTR_OUTPUT_MEMORY_TYPE, mem_type) && (mem_type == 1)) {
  842. memory_type = RT_MEMORY_RDMA_HBM;
  843. }
  844. uint8_t *dev_mem = var_manager_->GetVarMemoryAddr(var_logic, memory_type);
  845. if (dev_mem == nullptr) {
  846. GELOGE(INTERNAL_ERROR, "[Invoke][GetVarMemoryAddr]Failed to copy var %s from device,"
  847. "cant not get var addr from logic addr %p", var_node->GetName().c_str(), var_logic);
  848. REPORT_CALL_ERROR("E19999", "GetVarMemoryAddr failed, Failed to copy var %s from device,"
  849. "cant not get var addr from logic addr %p", var_node->GetName().c_str(), var_logic);
  850. return INTERNAL_ERROR;
  851. }
  852. int64_t var_size = CalcVarSizeInBytes(*tensor_desc);
  853. // var size is only for checking, will not allocate any memory by it
  854. tensor.reset(new(std::nothrow)TensorValue(dev_mem, static_cast<size_t>(var_size)));
  855. GE_CHECK_NOTNULL(tensor);
  856. GELOGI("Get var memory addr %p for node %s, size = %ld, mem_type=%u", dev_mem, var_name.c_str(), var_size, mem_type);
  857. return SUCCESS;
  858. }
  859. Status HybridModelBuilder::HandleDtString(const GeTensor &tensor, void *var_addr) {
  860. auto desc = tensor.GetTensorDesc();
  861. if (desc.GetDataType() == DT_STRING) {
  862. GeShape tensor_shape = desc.GetShape();
  863. /// if tensor is a scaler, it's shape size if zero, according ge_tensor.cc.
  864. /// the logic of GetShapeSize is wrong, the scaler tensor's GetShapeSize is zero
  865. /// and that of unknown shape is zero too.
  866. /// unknown shape will not appear here, so we can use zero judge a tensor is scalar or not
  867. int64_t elem_num = tensor_shape.GetShapeSize();
  868. if (elem_num == 0 && tensor_shape.GetDims().empty()) {
  869. elem_num = 1;
  870. }
  871. auto &mutable_tensor = const_cast<GeTensor &>(tensor);
  872. uint64_t *buff = reinterpret_cast<uint64_t *>(mutable_tensor.MutableData().data());
  873. GE_CHK_BOOL_RET_STATUS(ge::CheckInt64Uint32MulOverflow(elem_num, kBytes * kStringHeadElems) == SUCCESS, FAILED,
  874. "[Invoke][CheckInt64Uint32MulOverflow] failed because Shape size is invalid.");
  875. auto offset = static_cast<uint64_t>(elem_num * kBytes * kStringHeadElems);
  876. auto hbm_raw_data_base_addr =
  877. static_cast<uint64_t>(reinterpret_cast<uintptr_t>(var_addr) + offset);
  878. for (int64_t i = elem_num - 1; i >= 0; --i) {
  879. buff[i * kStringHeadElems] = hbm_raw_data_base_addr + (buff[i * kStringHeadElems] - buff[0]);
  880. }
  881. }
  882. return SUCCESS;
  883. }
  884. Status HybridModelBuilder::AssignUninitializedConstantOps() {
  885. if (GetContext().GetHostExecFlag()) {
  886. GELOGI("no need to assign when exec on host.");
  887. return SUCCESS;
  888. }
  889. for (auto &it : constant_op_nodes_) {
  890. const string &var_name = it.first;
  891. const NodePtr &var_node = it.second;
  892. auto tensor_desc = var_node->GetOpDesc()->MutableOutputDesc(0);
  893. if (!var_manager_->IsVarExist(var_name, *tensor_desc)) {
  894. // allocate constant
  895. GELOGD("[%s] Constant not allocated during graph building. now allocate it.", var_name.c_str());
  896. GE_CHK_STATUS_RET(var_manager_->AssignVarMem(var_name, *tensor_desc, RT_MEMORY_HBM));
  897. GE_CHK_STATUS_RET(var_manager_->SetAllocatedGraphId(var_name, runtime_param_.graph_id));
  898. }
  899. }
  900. for (auto &it : hybrid_model_.device_variable_nodes_) {
  901. const string &var_name = it.first;
  902. const NodePtr &var_node = it.second;
  903. auto tensor_desc = var_node->GetOpDesc()->MutableOutputDesc(0);
  904. if (!var_manager_->IsVarExist(var_name, *tensor_desc)) {
  905. // allocate constant
  906. GELOGD("[%s] Constant not allocated during graph building. now allocate it.", var_name.c_str());
  907. GE_CHK_STATUS_RET(var_manager_->AssignVarMem(var_name, *tensor_desc, RT_MEMORY_HBM));
  908. GE_CHK_STATUS_RET(VarMemAssignUtil::AssignData2Fp32Var(var_node, runtime_param_.session_id))
  909. GE_CHK_STATUS_RET(var_manager_->SetAllocatedGraphId(var_name, runtime_param_.graph_id));
  910. }
  911. }
  912. return SUCCESS;
  913. }
  914. Status HybridModelBuilder::InitConstantOps() {
  915. for (auto &it : constant_op_nodes_) {
  916. const string &var_name = it.first;
  917. const NodePtr &var_node = it.second;
  918. auto op_desc = var_node->GetOpDesc();
  919. auto v_weights = ModelUtils::GetWeights(op_desc);
  920. if (v_weights.empty()) {
  921. GELOGE(INTERNAL_ERROR, "[Check][Size][%s] Constant op has no weight", var_node->GetName().c_str());
  922. return INTERNAL_ERROR;
  923. }
  924. auto *ge_tensor = const_cast<GeTensor *>(v_weights[0].get());
  925. std::unique_ptr<TensorValue> var_tensor;
  926. if (GetContext().GetHostExecFlag()) {
  927. GE_CHECK_NOTNULL(ge_tensor);
  928. // Address for eigen kernel should be aligned with 16 bytes
  929. // Tensors return by api GetWeights share data with proto, whose addr is not confirmed to be aligned
  930. GeTensor aligned_tensor = ge_tensor->Clone();
  931. GELOGD("Init tensor with host constant %s size = %zu", var_name.c_str(), aligned_tensor.MutableData().GetSize());
  932. if (aligned_tensor.GetData().size() > 0) {
  933. if (MemManager::Instance().HostMemInstance(RT_MEMORY_HBM).Malloc(aligned_tensor.GetAlignedPtr(),
  934. aligned_tensor.GetData().size()) == nullptr) {
  935. GELOGE(MEMALLOC_FAILED, "[Malloc][HostMemory] for an existed GeTensor failed, model_name_:%s.",
  936. GetGraphName());
  937. return MEMALLOC_FAILED;
  938. }
  939. var_tensor.reset(new(std::nothrow)TensorValue(aligned_tensor.MutableData().data(),
  940. aligned_tensor.GetData().size()));
  941. } else {
  942. var_tensor.reset(new(std::nothrow)TensorValue(nullptr, 0));
  943. }
  944. GE_CHECK_NOTNULL(var_tensor);
  945. } else {
  946. GE_CHK_STATUS_RET_NOLOG(VarNodeToTensor(var_node, var_tensor));
  947. GELOGD("Init const op tensor. name = %s, size = %ld", var_name.c_str(), var_tensor->GetSize());
  948. var_tensor->SetName("ConstOp_" + var_name);
  949. auto v_output_size = var_tensor->GetSize();
  950. auto v_output_addr = var_tensor->MutableData();
  951. if (ge_tensor->GetData().size() > 0) {
  952. GE_CHK_STATUS_RET_NOLOG(HandleDtString(*ge_tensor, v_output_addr));
  953. GELOGI("[IMAS]InitConstant memcpy graph_%u type[V] name[%s] output[%d] memaddr[%p]"
  954. "mem_size[%zu] datasize[%zu]",
  955. runtime_param_.graph_id, op_desc->GetName().c_str(), 0, v_output_addr, v_output_size,
  956. ge_tensor->GetData().size());
  957. GE_CHK_RT_RET(rtMemcpy(v_output_addr, v_output_size, ge_tensor->GetData().data(), ge_tensor->GetData().size(),
  958. RT_MEMCPY_HOST_TO_DEVICE));
  959. } else {
  960. GELOGI("[%s] Const op has no weight data.", op_desc->GetName().c_str());
  961. }
  962. }
  963. hybrid_model_.variable_tensors_.emplace(var_name, std::move(var_tensor));
  964. }
  965. return SUCCESS;
  966. }
  967. Status HybridModelBuilder::InitVariableTensors() {
  968. for (auto &it : hybrid_model_.device_variable_nodes_) {
  969. string var_name = it.first;
  970. NodePtr &var_node = it.second;
  971. std::unique_ptr<TensorValue> tensor;
  972. GE_CHK_STATUS_RET_NOLOG(VarNodeToTensor(var_node, tensor));
  973. GELOGD("Init variable tensor. name = %s, size = %ld, addr = %p",
  974. var_name.c_str(),
  975. tensor->GetSize(),
  976. tensor->GetData());
  977. tensor->SetName("Var_" + var_name);
  978. hybrid_model_.variable_tensors_.emplace(var_name, std::move(tensor));
  979. }
  980. for (const auto &it : hybrid_model_.host_variable_nodes_) {
  981. auto op_desc = it.second->GetOpDesc();
  982. GE_CHECK_NOTNULL(op_desc);
  983. GeTensorDesc output_tensor = op_desc->GetOutputDesc(0);
  984. int64_t tensor_size = 0;
  985. if (TensorUtils::CalcTensorMemSize(output_tensor.GetShape(), output_tensor.GetFormat(),
  986. output_tensor.GetDataType(), tensor_size) != SUCCESS) {
  987. REPORT_CALL_ERROR("E19999", "CalcTensorMemSize failed, node name:%s", it.first.c_str());
  988. GELOGE(INTERNAL_ERROR, "[Calculate][TensorMemSize] failed, node name:%s", it.first.c_str());
  989. return INTERNAL_ERROR;
  990. }
  991. // Host variable will be assigned to allocated shared memory first.
  992. SharedMemInfo mem_info;
  993. void *mem_addr = nullptr;
  994. if (HostMemManager::Instance().QueryVarMemInfo(it.first, mem_info)) {
  995. mem_addr = const_cast<void *>(MemManager::Instance().HostMemInstance(RT_MEMORY_HBM)
  996. .Malloc(mem_info.host_aligned_ptr, tensor_size));
  997. } else {
  998. mem_addr = MemManager::Instance().HostMemInstance(RT_MEMORY_HBM).Malloc(tensor_size);
  999. }
  1000. if (mem_addr == nullptr) {
  1001. REPORT_INNER_ERROR("E19999", "[Malloc][HostMem] for variable [%s] failed.", it.first.c_str());
  1002. GELOGE(MEMALLOC_FAILED, "[Malloc][HostMem] for variable [%s] failed.", it.first.c_str());
  1003. return MEMALLOC_FAILED;
  1004. }
  1005. GELOGD("Host variable [%s] malloc success, size=%ld.", it.first.c_str(), tensor_size);
  1006. std::unique_ptr<TensorValue> tensor(new (std::nothrow) TensorValue(mem_addr, tensor_size));
  1007. GE_CHECK_NOTNULL(tensor);
  1008. hybrid_model_.variable_tensors_.emplace(it.first, std::move(tensor));
  1009. }
  1010. return SUCCESS;
  1011. }
  1012. Status HybridModelBuilder::InitWeights() {
  1013. // For constant in root graph
  1014. for (const auto &subgraph_model : ge_root_model_->GetSubgraphInstanceNameToModel()) {
  1015. const auto &weight_buffer = subgraph_model.second->GetWeight();
  1016. if (weight_buffer.GetSize() == 0) {
  1017. GELOGD("weight is empty");
  1018. return SUCCESS;
  1019. }
  1020. auto allocator = NpuMemoryAllocator::GetAllocator();
  1021. GE_CHECK_NOTNULL(allocator);
  1022. auto sub_weight_buffer = TensorBuffer::Create(allocator, weight_buffer.size());
  1023. GE_CHECK_NOTNULL(sub_weight_buffer);
  1024. auto weight_base = reinterpret_cast<uint8_t *>(sub_weight_buffer->GetData());
  1025. GE_CHK_RT_RET(rtMemcpy(weight_base,
  1026. sub_weight_buffer->GetSize(),
  1027. weight_buffer.GetData(),
  1028. weight_buffer.GetSize(),
  1029. RT_MEMCPY_HOST_TO_DEVICE));
  1030. GELOGI("Init weight mem successfully, weight base %p, weight size = %zu",
  1031. weight_base,
  1032. sub_weight_buffer->GetSize());
  1033. auto subgraph = GraphUtils::GetComputeGraph(subgraph_model.second->GetGraph());
  1034. if (subgraph != ge_root_model_->GetRootGraph()) {
  1035. subgraph = hybrid_model_.root_graph_->GetSubgraph(subgraph_model.first);
  1036. } else {
  1037. subgraph = hybrid_model_.root_graph_;
  1038. }
  1039. GE_CHECK_NOTNULL(subgraph);
  1040. hybrid_model_.weight_buffer_map_.emplace(subgraph->GetName(), std::move(sub_weight_buffer));
  1041. for (auto &node : subgraph->GetDirectNode()) {
  1042. if (node->GetType() != CONSTANT) {
  1043. continue;
  1044. }
  1045. auto op_desc = node->GetOpDesc();
  1046. auto v_weights = ModelUtils::GetWeights(op_desc);
  1047. if (v_weights.empty()) {
  1048. GELOGE(INTERNAL_ERROR, "[Invoke][GetWeights][%s] Constant has no value", node->GetName().c_str());
  1049. REPORT_CALL_ERROR("E19999", "[%s] Constant has no value.", node->GetName().c_str());
  1050. return INTERNAL_ERROR;
  1051. }
  1052. auto *ge_tensor = const_cast<GeTensor *>(v_weights[0].get());
  1053. GE_CHECK_NOTNULL(ge_tensor);
  1054. const GeTensorDesc &tensor_desc = ge_tensor->GetTensorDesc();
  1055. int64_t tensor_size = 0;
  1056. GE_CHK_GRAPH_STATUS_RET(TensorUtils::GetSize(*op_desc->MutableOutputDesc(0), tensor_size),
  1057. "[Invoke][GetSize][%s] Failed to get output tensor size",
  1058. node->GetName().c_str());
  1059. int64_t data_offset = 0;
  1060. GE_CHK_GRAPH_STATUS_RET(TensorUtils::GetDataOffset(tensor_desc, data_offset),
  1061. "[Invoke][GetDataOffset][%s] Failed to get data offset",
  1062. node->GetName().c_str());
  1063. GELOGD("[%s] Start to init Constant node [%s], size = %ld, offset = %ld",
  1064. GetGraphName(),
  1065. node->GetName().c_str(),
  1066. tensor_size,
  1067. data_offset);
  1068. auto tensor_buffer = TensorBuffer::Create(weight_base + data_offset, tensor_size);
  1069. GE_CHECK_NOTNULL(tensor_buffer);
  1070. std::unique_ptr<TensorValue> constant_tensor(new (std::nothrow)TensorValue(std::move(tensor_buffer)));
  1071. GE_CHECK_NOTNULL(constant_tensor);
  1072. constant_tensor->SetName("Constant_" + op_desc->GetName());
  1073. hybrid_model_.constant_tensors_.emplace(node, std::move(constant_tensor));
  1074. GELOGD("[%s] Constant node [%s] added, size = %ld", GetGraphName(), node->GetName().c_str(), tensor_size);
  1075. }
  1076. }
  1077. return SUCCESS;
  1078. }
  1079. Status HybridModelBuilder::LoadTask(NodeItem &node_item) {
  1080. auto &node_ptr = node_item.node;
  1081. GELOGD("[%s] Start to build kernel task", node_ptr->GetName().c_str());
  1082. auto load_ret = node_item.node_executor->LoadTask(hybrid_model_,
  1083. node_ptr,
  1084. node_item.kernel_task);
  1085. if (load_ret != UNSUPPORTED && load_ret != SUCCESS) {
  1086. GELOGE(load_ret, "[Invoke][LoadTask][%s] Failed to load task", node_ptr->GetName().c_str());
  1087. REPORT_CALL_ERROR("E19999", "[%s] Failed to load task", node_ptr->GetName().c_str());
  1088. return load_ret;
  1089. }
  1090. GELOGD("[%s] Done loading task successfully.", node_ptr->GetName().c_str());
  1091. return SUCCESS;
  1092. }
  1093. Status HybridModelBuilder::LoadTasks() {
  1094. GE_CHK_STATUS_RET(CheckAicpuOpList(), "[Check][AicpuOpList] failed.");
  1095. std::map<int, std::map<std::string, NodeItem *>> ordered_partitioned_calls;
  1096. for (auto &it : hybrid_model_.node_items_) {
  1097. auto &node_item = it.second;
  1098. if (node_item->node_type == NETOUTPUT) {
  1099. continue;
  1100. }
  1101. if (node_item->node_type == PARTITIONEDCALL) {
  1102. ordered_partitioned_calls[node_item->node_id][node_item->node_name] = node_item.get();
  1103. continue;
  1104. }
  1105. GE_CHK_STATUS_RET_NOLOG(LoadTask(*node_item));
  1106. }
  1107. // HCCL operators need to be loaded in the same order across different processes
  1108. for (auto &it : ordered_partitioned_calls) {
  1109. for (auto &it2 : it.second) {
  1110. GE_CHK_STATUS_RET_NOLOG(LoadTask(*it2.second));
  1111. }
  1112. }
  1113. return SUCCESS;
  1114. }
  1115. Status HybridModelBuilder::LoadGeModel(ComputeGraph &sub_graph, const GeModelPtr &ge_model) {
  1116. auto parent_node = sub_graph.GetParentNode();
  1117. GE_CHECK_NOTNULL(parent_node);
  1118. auto op_type = parent_node->GetType();
  1119. if (IsControlFlowV2Op(op_type)) {
  1120. GELOGD("Set ge_model for control op subgraph: [%s], task_size = %d",
  1121. sub_graph.GetName().c_str(),
  1122. ge_model->GetModelTaskDefPtr()->task_size());
  1123. subgraph_models_.emplace(sub_graph.GetName(), ge_model);
  1124. } else {
  1125. GELOGD("Set ge_model for subgraph: [%s], task_size = %d",
  1126. sub_graph.GetName().c_str(),
  1127. ge_model->GetModelTaskDefPtr()->task_size());
  1128. hybrid_model_.known_shape_sub_models_.emplace(parent_node, ge_model);
  1129. }
  1130. GE_CHK_STATUS_RET_NOLOG(InitHcclExecutorOnDemand(ge_model));
  1131. return SUCCESS;
  1132. }
  1133. Status HybridModelBuilder::InitHcclExecutorOnDemand(const GeModelPtr &ge_model) {
  1134. if (NodeExecutorManager::GetInstance().IsExecutorInitialized(NodeExecutorManager::ExecutorType::HCCL)) {
  1135. return SUCCESS;
  1136. }
  1137. // HCCL tasks in known-shaped subgraph which resides in a dynamic root graph
  1138. // still depends on the initialization of the HcclExecutor
  1139. auto tasks = ge_model->GetModelTaskDefPtr()->task();
  1140. for (int i = 0; i < tasks.size(); ++i) {
  1141. const domi::TaskDef &task_def = tasks[i];
  1142. auto task_type = static_cast<rtModelTaskType_t>(task_def.type());
  1143. if (task_type == RT_MODEL_TASK_HCCL) {
  1144. const NodeExecutor *unused = nullptr;
  1145. GE_CHK_STATUS_RET_NOLOG(NodeExecutorManager::GetInstance()
  1146. .GetOrCreateExecutor(NodeExecutorManager::ExecutorType::HCCL, &unused));
  1147. return SUCCESS;
  1148. }
  1149. }
  1150. return SUCCESS;
  1151. }
  1152. Status HybridModelBuilder::IndexTaskDefs(const ComputeGraphPtr &sub_graph, const GeModelPtr &ge_model) {
  1153. // index task defs
  1154. GELOGD("To index tasks for subgraph: %s", sub_graph->GetName().c_str());
  1155. std::unordered_map<int64_t, NodePtr> node_map;
  1156. for (const auto &node : sub_graph->GetDirectNode()) {
  1157. GE_CHECK_NOTNULL(node);
  1158. GE_CHECK_NOTNULL(node->GetOpDesc());
  1159. auto node_id = node->GetOpDesc()->GetId();
  1160. GELOGD("op_index = %ld, node_name = %s", node_id, node->GetName().c_str());
  1161. node_map.emplace(node_id, node);
  1162. }
  1163. auto tasks = ge_model->GetModelTaskDefPtr()->task();
  1164. for (int i = 0; i < tasks.size(); ++i) {
  1165. const domi::TaskDef &task_def = tasks[i];
  1166. GELOGI("Task id = %d, task type = %d", i, task_def.type());
  1167. auto task_type = static_cast<rtModelTaskType_t>(task_def.type());
  1168. uint32_t op_index = -1;
  1169. if (task_type == RT_MODEL_TASK_KERNEL) {
  1170. op_index = task_def.kernel().context().op_index();
  1171. } else if (task_type == RT_MODEL_TASK_KERNEL_EX) {
  1172. op_index = task_def.kernel_ex().op_index();
  1173. } else if (task_type == RT_MODEL_TASK_HCCL) {
  1174. op_index = task_def.kernel_hccl().op_index();
  1175. } else if (task_type == RT_MODEL_TASK_ALL_KERNEL) {
  1176. op_index = task_def.kernel_with_handle().context().op_index();
  1177. } else {
  1178. GELOGD("Skip task type: %d", static_cast<int>(task_type));
  1179. continue;
  1180. }
  1181. GELOGD("op_index = %u, task_type = %d", op_index, task_type);
  1182. auto iter = node_map.find(op_index);
  1183. if (iter == node_map.end()) {
  1184. GELOGE(INTERNAL_ERROR, "[Find][Node]Failed to get node by op_index = %u", op_index);
  1185. REPORT_INNER_ERROR("E19999", "Failed to get node by op_index = %u.", op_index);
  1186. return INTERNAL_ERROR;
  1187. }
  1188. auto &node = iter->second;
  1189. if (task_type == RT_MODEL_TASK_KERNEL || task_type == RT_MODEL_TASK_ALL_KERNEL) {
  1190. ge_model->GetTBEKernelStore().LoadTBEKernelBinToOpDesc(node->GetOpDesc());
  1191. }
  1192. GELOGD("Task loaded for node: %s, task type = %d, op_index = %u", node->GetName().c_str(), task_type, op_index);
  1193. hybrid_model_.task_defs_[node].emplace_back(task_def);
  1194. }
  1195. return SUCCESS;
  1196. }
  1197. Status HybridModelBuilder::IndexTaskDefs() {
  1198. const auto &root_graph = hybrid_model_.root_graph_;
  1199. const auto &root_graph_name = root_graph->GetName();
  1200. if (SetOutputNameAttr(*root_graph) != SUCCESS) {
  1201. GELOGW("Set output name attr failed.");
  1202. }
  1203. for (auto &it : ge_root_model_->GetSubgraphInstanceNameToModel()) {
  1204. auto &name = it.first;
  1205. auto &ge_model = it.second;
  1206. GE_CHECK_NOTNULL(ge_model);
  1207. auto sub_graph = root_graph->GetSubgraph(name);
  1208. if (name != root_graph_name) {
  1209. if (sub_graph == nullptr) {
  1210. continue;
  1211. }
  1212. bool is_unknown_shape = sub_graph->GetGraphUnknownFlag();
  1213. if (!is_unknown_shape) {
  1214. GE_CHK_STATUS_RET_NOLOG(LoadGeModel(*sub_graph, ge_model));
  1215. continue;
  1216. }
  1217. } else {
  1218. sub_graph = root_graph;
  1219. }
  1220. GE_CHK_STATUS_RET_NOLOG(IndexTaskDefs(sub_graph, ge_model));
  1221. }
  1222. return SUCCESS;
  1223. }
  1224. Status HybridModelBuilder::IndexSpecialNodes() {
  1225. GELOGD("Start to index special nodes");
  1226. const auto &root_graph = hybrid_model_.root_graph_;
  1227. for (auto &node : root_graph->GetAllNodes()) {
  1228. GE_CHECK_NOTNULL(node);
  1229. GE_CHECK_NOTNULL(node->GetOpDesc());
  1230. auto op_type = node->GetType();
  1231. GELOGD("node name = %s, node type = %s", node->GetName().c_str(), node->GetType().c_str());
  1232. if (op_type == VARIABLE) {
  1233. string placement;
  1234. (void) AttrUtils::GetStr(node->GetOpDesc(), ATTR_VARIABLE_PLACEMENT, placement);
  1235. if (placement == "host") {
  1236. hybrid_model_.host_variable_nodes_.emplace(node->GetName(), node);
  1237. } else {
  1238. hybrid_model_.device_variable_nodes_.emplace(node->GetName(), node);
  1239. }
  1240. } else if (op_type == CONSTANTOP) {
  1241. constant_op_nodes_.emplace(node->GetName(), node);
  1242. } else if (op_type == STREAMMERGE) {
  1243. stream_merge_op_nodes_.emplace(node->GetName(), node);
  1244. } else if (op_type == NEXTITERATION || op_type == REFNEXTITERATION) {
  1245. next_iteration_op_nodes_.emplace(node->GetName(), node);
  1246. } else if (op_type == DATA && node->GetOwnerComputeGraph() != root_graph) {
  1247. NodePtr src_node;
  1248. int peer_out_index = -1;
  1249. GE_CHK_STATUS_RET_NOLOG(GetPeerNodeAcrossSubGraphs(node, src_node, peer_out_index));
  1250. GELOGD("Got peer node for data node %s, peer node = %s(%s)",
  1251. node->GetName().c_str(),
  1252. src_node->GetName().c_str(),
  1253. src_node->GetType().c_str());
  1254. auto src_op_type = src_node->GetType();
  1255. if (src_op_type == CONSTANTOP || src_op_type == VARIABLE) {
  1256. for (auto &dst_node_and_in_anchor : node->GetOutDataNodesAndAnchors()) {
  1257. auto &dst_node = dst_node_and_in_anchor.first;
  1258. auto &in_anchor = dst_node_and_in_anchor.second;
  1259. node_ref_inputs_[dst_node].emplace_back(std::make_pair(in_anchor->GetIdx(), src_node));
  1260. }
  1261. }
  1262. }
  1263. }
  1264. return SUCCESS;
  1265. }
  1266. Status HybridModelBuilder::GetPeerNodeAcrossSubGraphs(const NodePtr &data_node,
  1267. NodePtr &peer_node,
  1268. int &peer_out_index) {
  1269. auto sub_graph = data_node->GetOwnerComputeGraph();
  1270. GE_CHECK_NOTNULL(sub_graph);
  1271. GELOGD("To get peer node of %s::%s", sub_graph->GetName().c_str(), data_node->GetName().c_str());
  1272. auto wrapped_node = data_node->GetOwnerComputeGraph()->GetParentNode();
  1273. if (wrapped_node == nullptr) {
  1274. REPORT_INNER_ERROR("E19999", "[%s] Node is in root graph.", data_node->GetName().c_str());
  1275. GELOGE(INTERNAL_ERROR, "[Invoke][GetParentNode][%s] Node is in root graph.", data_node->GetName().c_str());
  1276. return INTERNAL_ERROR;
  1277. }
  1278. auto data_op_desc = data_node->GetOpDesc();
  1279. uint32_t parent_index = 0;
  1280. if (!AttrUtils::GetInt(data_op_desc, ATTR_NAME_PARENT_NODE_INDEX, parent_index)) {
  1281. REPORT_CALL_ERROR("E19999", "[%s] Failed to get attr [%s].", data_op_desc->GetName().c_str(),
  1282. ATTR_NAME_PARENT_NODE_INDEX.c_str());
  1283. GELOGE(INTERNAL_ERROR, "[Invoke][GetInt][%s] Failed to get attr [%s]",
  1284. data_op_desc->GetName().c_str(), ATTR_NAME_PARENT_NODE_INDEX.c_str());
  1285. return INTERNAL_ERROR;
  1286. }
  1287. auto wrapped_node_in_anchor = wrapped_node->GetInDataAnchor(parent_index);
  1288. GE_CHECK_NOTNULL(wrapped_node_in_anchor);
  1289. auto src_out_anchor = wrapped_node_in_anchor->GetPeerOutAnchor();
  1290. if (src_out_anchor == nullptr || src_out_anchor->GetOwnerNode() == nullptr) {
  1291. REPORT_INNER_ERROR("E19999", "[%s] Parent node do not have peer anchor.", data_node->GetName().c_str());
  1292. GELOGE(INTERNAL_ERROR,
  1293. "[Check][ParentNode][%s] Parent node do not have peer anchor.", data_node->GetName().c_str());
  1294. return INTERNAL_ERROR;
  1295. }
  1296. auto src_wrapped_node_out_anchor = wrapped_node_in_anchor->GetPeerOutAnchor();
  1297. GE_CHECK_NOTNULL(src_wrapped_node_out_anchor);
  1298. auto src_wrapped_node = src_wrapped_node_out_anchor->GetOwnerNode();
  1299. GE_CHECK_NOTNULL(src_wrapped_node);
  1300. // connected to root-graph's DATA
  1301. auto src_node_type = src_wrapped_node->GetType();
  1302. if (src_node_type != PARTITIONEDCALL) {
  1303. peer_node = src_wrapped_node;
  1304. peer_out_index = kVarOutputIndex;
  1305. GELOGD("[%s] Node is connected to root graph's node: %s",
  1306. data_node->GetName().c_str(),
  1307. peer_node->GetName().c_str());
  1308. return SUCCESS;
  1309. }
  1310. auto src_graph = NodeUtils::GetSubgraph(*src_wrapped_node, kSubgraphIndex);
  1311. GE_CHECK_NOTNULL(src_graph);
  1312. auto src_net_output_node = src_graph->FindFirstNodeMatchType(NETOUTPUT);
  1313. if (src_net_output_node == nullptr) {
  1314. REPORT_INNER_ERROR("E19999", "Failed to find NetOutput in subgraph: %s", src_graph->GetName().c_str());
  1315. GELOGE(INTERNAL_ERROR, "[Invoke][FindFirstNodeMatchType]Failed to find NetOutput in subgraph: %s",
  1316. src_graph->GetName().c_str());
  1317. return INTERNAL_ERROR;
  1318. }
  1319. auto net_output_desc = src_net_output_node->GetOpDesc();
  1320. GE_CHECK_NOTNULL(net_output_desc);
  1321. auto out_index = static_cast<uint32_t>(src_wrapped_node_out_anchor->GetIdx());
  1322. GELOGD("src graph = %s, src parent output index = %u", src_graph->GetName().c_str(), out_index);
  1323. // link src to outputs of DataNode
  1324. auto input_size = net_output_desc->GetAllInputsSize();
  1325. GE_CHECK_LE(input_size, UINT32_MAX);
  1326. for (uint32_t i = 0; i < static_cast<uint32_t>(input_size); ++i) {
  1327. uint32_t p_index = 0;
  1328. if (!AttrUtils::GetInt(net_output_desc->GetInputDesc(i), ATTR_NAME_PARENT_NODE_INDEX, p_index)) {
  1329. GELOGW("SubGraph: %s input tensor %u attr %s not found.",
  1330. src_graph->GetName().c_str(), i, ATTR_NAME_PARENT_NODE_INDEX.c_str());
  1331. continue;
  1332. }
  1333. GELOGD("NetOutput's input[%u], parent_node_index = %u", i, p_index);
  1334. if (p_index == out_index) {
  1335. auto in_anchor = src_net_output_node->GetInDataAnchor(i);
  1336. GE_CHECK_NOTNULL(in_anchor);
  1337. auto peer_out_anchor = in_anchor->GetPeerOutAnchor();
  1338. GE_CHECK_NOTNULL(peer_out_anchor);
  1339. peer_node = peer_out_anchor->GetOwnerNode();
  1340. GE_CHECK_NOTNULL(peer_node);
  1341. peer_out_index = peer_out_anchor->GetIdx();
  1342. GELOGD("Found peer node of Data node: %s::%s is %s::%s",
  1343. sub_graph->GetName().c_str(),
  1344. data_node->GetName().c_str(),
  1345. src_graph->GetName().c_str(),
  1346. peer_node->GetName().c_str());
  1347. return SUCCESS;
  1348. }
  1349. }
  1350. GELOGE(FAILED, "[Get][PeerNode]Failed to find peer node for %s::%s", sub_graph->GetName().c_str(),
  1351. data_node->GetName().c_str());
  1352. REPORT_INNER_ERROR("E19999", "Failed to find peer node for %s::%s.",
  1353. sub_graph->GetName().c_str(), data_node->GetName().c_str());
  1354. return FAILED;
  1355. }
  1356. Status HybridModelBuilder::InitRuntimeParams() {
  1357. int64_t value = 0;
  1358. bool ret = false;
  1359. if (ge_root_model_->GetSubgraphInstanceNameToModel().empty()) {
  1360. GELOGE(INTERNAL_ERROR, "[Get][SubModel]Root model has no sub model, model:%s.", GetGraphName());
  1361. REPORT_INNER_ERROR("E19999", "Root model has no sub model, model:%s.", GetGraphName());
  1362. return INTERNAL_ERROR;
  1363. }
  1364. // session id and var size is same for every model
  1365. auto first_model = ge_root_model_->GetSubgraphInstanceNameToModel().begin()->second;
  1366. ret = ge::AttrUtils::GetInt(first_model, ge::MODEL_ATTR_SESSION_ID, value);
  1367. runtime_param_.session_id = ret ? static_cast<uint64_t>(value) : 0;
  1368. ret = ge::AttrUtils::GetInt(first_model, ATTR_MODEL_TASK_GEN_VAR_ADDR, value);
  1369. runtime_param_.logic_var_base = ret ? static_cast<uint64_t>(value) : 0;
  1370. runtime_param_.graph_id = hybrid_model_.root_graph_->GetGraphID();
  1371. value = 0;
  1372. for (auto &it : ge_root_model_->GetSubgraphInstanceNameToModel()) {
  1373. (void) ge::AttrUtils::GetInt(it.second, ATTR_MODEL_VAR_SIZE, value);
  1374. if (value > 0) {
  1375. runtime_param_.var_size = static_cast<uint64_t>(value);
  1376. break;
  1377. }
  1378. }
  1379. GELOGI("InitRuntimeParams(), session_id:%lu, var_size:%lu. graph_id = %u",
  1380. runtime_param_.session_id, runtime_param_.var_size, runtime_param_.graph_id);
  1381. var_manager_ = VarManager::Instance(runtime_param_.session_id);
  1382. GE_CHECK_NOTNULL(var_manager_);
  1383. return SUCCESS;
  1384. }
  1385. Status HybridModelBuilder::IdentifyVariableOutputs(NodeItem &node_item, const ComputeGraphPtr &subgraph) {
  1386. GELOGD("Start to parse outputs of node: %s", node_item.NodeName().c_str());
  1387. auto net_output_node = subgraph->FindFirstNodeMatchType(NETOUTPUT);
  1388. if (net_output_node == nullptr) {
  1389. GELOGD("[%s] Subgraph do not got net output", subgraph->GetName().c_str());
  1390. return SUCCESS;
  1391. }
  1392. auto net_output_desc = net_output_node->GetOpDesc();
  1393. GE_CHECK_NOTNULL(net_output_desc);
  1394. // constants connected to net output
  1395. for (const auto &in_data_anchor : net_output_node->GetAllInDataAnchors()) {
  1396. auto src_node = GetPeerNode(in_data_anchor);
  1397. GE_CHECK_NOTNULL(src_node);
  1398. auto src_op_type = src_node->GetType();
  1399. if (src_op_type == CONSTANTOP || src_op_type == CONSTANT) {
  1400. known_subgraph_constant_output_refs_[&node_item].emplace(in_data_anchor->GetIdx(), src_node);
  1401. }
  1402. }
  1403. // Data nodes marked with REF_VAR_SRC_VAR_NAME
  1404. // Using variable tensor as data's output
  1405. for (auto &node : subgraph->GetDirectNode()) {
  1406. if (node->GetType() != DATA) {
  1407. continue;
  1408. }
  1409. string ref_var_name;
  1410. (void) AttrUtils::GetStr(node->GetOpDesc(), REF_VAR_SRC_VAR_NAME, ref_var_name);
  1411. if (ref_var_name.empty()) {
  1412. continue;
  1413. }
  1414. GELOGD("Data node ref to variable: %s", ref_var_name.c_str());
  1415. NodePtr src_node;
  1416. auto var_node = hybrid_model_.GetVariableNode(ref_var_name);
  1417. GE_CHECK_NOTNULL(var_node);
  1418. GELOGD("Found var node [%s] by ref_var_name [%s]", var_node->GetName().c_str(), ref_var_name.c_str());
  1419. int peer_output_index = -1;
  1420. GE_CHK_STATUS_RET_NOLOG(GetPeerNodeAcrossSubGraphs(node, src_node, peer_output_index));
  1421. auto src_node_item = MutableNodeItem(src_node);
  1422. GE_CHECK_NOTNULL(src_node_item);
  1423. src_node_item->ref_outputs.emplace(peer_output_index, var_node);
  1424. }
  1425. return SUCCESS;
  1426. }
  1427. NodePtr HybridModelBuilder::GetPeerNode(const InDataAnchorPtr &in_data_anchor) {
  1428. auto peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  1429. if (peer_out_anchor != nullptr) {
  1430. return peer_out_anchor->GetOwnerNode();
  1431. }
  1432. return nullptr;
  1433. }
  1434. Status HybridModelBuilder::GetParentNodeOutputIndex(const OpDesc &op_desc, int index, uint32_t &out_index) {
  1435. auto input_desc = op_desc.MutableInputDesc(index);
  1436. GE_CHECK_NOTNULL(input_desc);
  1437. if (!AttrUtils::GetInt(input_desc, ATTR_NAME_PARENT_NODE_INDEX, out_index)) {
  1438. GELOGE(INTERNAL_ERROR, "[Invoke][GetInt]NetOutput %s input tensor %d, attr %s not found.",
  1439. op_desc.GetName().c_str(), index, ATTR_NAME_PARENT_NODE_INDEX.c_str());
  1440. REPORT_CALL_ERROR("E19999", "NetOutput %s input tensor %d, attr %s not found.",
  1441. op_desc.GetName().c_str(), index, ATTR_NAME_PARENT_NODE_INDEX.c_str());
  1442. return INTERNAL_ERROR;
  1443. }
  1444. return SUCCESS;
  1445. }
  1446. Status HybridModelBuilder::InitModelMem() {
  1447. hybrid_model_.var_mem_base_ = var_manager_->GetVarMemoryBase(RT_MEMORY_HBM);
  1448. auto total_var_size = hybrid_model_.TotalVarMemSize();
  1449. if (total_var_size == 0 && !constant_op_nodes_.empty()) {
  1450. total_var_size = var_manager_->GetVarMemSize(RT_MEMORY_HBM) > 0 ? var_manager_->GetVarMemMaxSize() : 0;
  1451. GELOGD("Model var size = 0. but got uninitialized constant. set var size to %zu.", total_var_size);
  1452. }
  1453. if (total_var_size > 0 && hybrid_model_.var_mem_base_ == nullptr) {
  1454. GE_CHK_STATUS_RET(var_manager_->MallocVarMemory(total_var_size),
  1455. "[Malloc][VarMemory] failed, size:%zu.", total_var_size);
  1456. hybrid_model_.var_mem_base_ = var_manager_->GetVarMemoryBase(RT_MEMORY_HBM);
  1457. }
  1458. runtime_param_.var_base = hybrid_model_.var_mem_base_;
  1459. auto allocator = NpuMemoryAllocator::GetAllocator();
  1460. GE_CHECK_NOTNULL(allocator);
  1461. hybrid_model_.global_step_ = TensorBuffer::Create(allocator, sizeof(int64_t));
  1462. GE_CHECK_NOTNULL(hybrid_model_.global_step_);
  1463. return SUCCESS;
  1464. }
  1465. Status HybridModelBuilder::TransAllVarData() {
  1466. GELOGI("TransAllVarData start: session_id:%lu, graph_id: %u.", runtime_param_.session_id, runtime_param_.graph_id);
  1467. rtContext_t ctx = nullptr;
  1468. rtError_t rt_ret = rtCtxGetCurrent(&ctx);
  1469. if (rt_ret != RT_ERROR_NONE) {
  1470. GELOGE(RT_FAILED, "[Invoke][rtCtxGetCurrent]Failed to get current context, error_code is: 0x%X.", rt_ret);
  1471. REPORT_CALL_ERROR("E19999", "rtCtxGetCurrent failed, error_code: 0x%X.", rt_ret);
  1472. return RT_FAILED;
  1473. }
  1474. std::vector<NodePtr> variable_node_list;
  1475. for (auto &it : hybrid_model_.device_variable_nodes_) {
  1476. variable_node_list.emplace_back(it.second);
  1477. GELOGD("[%s] added for trans var data", it.first.c_str());
  1478. }
  1479. GE_CHK_STATUS_RET(TransVarDataUtils::TransAllVarData(variable_node_list,
  1480. runtime_param_.session_id,
  1481. ctx,
  1482. runtime_param_.graph_id),
  1483. "[Invoke][TransAllVarData] failed.");
  1484. GELOGI("TransAllVarData success.");
  1485. return SUCCESS;
  1486. }
  1487. Status HybridModelBuilder::CopyVarData() {
  1488. GE_CHK_STATUS_RET(TransVarDataUtils::CopyVarData(hybrid_model_.root_graph_,
  1489. runtime_param_.session_id,
  1490. hybrid_model_.device_id_),
  1491. "[Invoke][CopyVarData] failed.");
  1492. GELOGI("CopyVarData success.");
  1493. return SUCCESS;
  1494. }
  1495. Status HybridModelBuilder::LoadKnownShapedSubgraph(ComputeGraph &graph, NodeItem *parent_node_item) {
  1496. GELOGD("Start to load known shaped subgraph [%s]", graph.GetName().c_str());
  1497. auto graph_item = std::unique_ptr<GraphItem>(new(std::nothrow)GraphItem());
  1498. GE_CHECK_NOTNULL(graph_item);
  1499. graph_item->is_dynamic_ = false;
  1500. auto subgraph_name = graph.GetName();
  1501. auto wrapper_op_desc = MakeShared<OpDesc>(subgraph_name + "_partitioned_call", PARTITIONEDCALL);
  1502. GE_CHECK_NOTNULL(wrapper_op_desc);
  1503. for (auto &node : graph.GetDirectNode()) {
  1504. GE_CHECK_NOTNULL(node);
  1505. auto op_desc = node->GetOpDesc();
  1506. GE_CHECK_NOTNULL(op_desc);
  1507. const auto &op_type = node->GetType();
  1508. if (op_type == DATA) {
  1509. int32_t data_index = 0;
  1510. if (!AttrUtils::GetInt(node->GetOpDesc(), ATTR_NAME_PARENT_NODE_INDEX, data_index)) {
  1511. GELOGE(FAILED,
  1512. "[Invoke][GetInt][%s] Failed to get attr [%s]",
  1513. node->GetName().c_str(),
  1514. ATTR_NAME_PARENT_NODE_INDEX.c_str());
  1515. return FAILED;
  1516. }
  1517. (void) wrapper_op_desc->AddInputDesc(op_desc->GetInputDesc(0));
  1518. graph_item->input_index_mapping_.emplace_back(data_index);
  1519. } else if (op_type == NETOUTPUT) {
  1520. int output_index = 0;
  1521. for (const auto &output_desc : op_desc->GetAllInputsDescPtr()) {
  1522. int32_t data_index = output_index++;
  1523. if (!AttrUtils::GetInt(output_desc, ATTR_NAME_PARENT_NODE_INDEX, data_index)) {
  1524. GELOGI("[%s] Failed to get attr [%s]", node->GetName().c_str(), ATTR_NAME_PARENT_NODE_INDEX.c_str());
  1525. }
  1526. GE_CHK_GRAPH_STATUS_RET(wrapper_op_desc->AddOutputDesc(*output_desc),
  1527. "[Invoke][AddOutputDesc][%s] Failed to add output desc. output index = %d",
  1528. graph.GetName().c_str(),
  1529. output_index);
  1530. graph_item->output_index_mapping_.emplace_back(data_index);
  1531. }
  1532. }
  1533. }
  1534. auto temp_graph = MakeShared<ComputeGraph>("temp");
  1535. GE_CHECK_NOTNULL(temp_graph);
  1536. auto wrapper_node = temp_graph->AddNode(wrapper_op_desc);
  1537. wrapper_op_desc->SetId(parent_node_item->node_id);
  1538. GeModelPtr ge_model = subgraph_models_[subgraph_name];
  1539. GE_CHECK_NOTNULL(ge_model);
  1540. hybrid_model_.known_shape_sub_models_.emplace(wrapper_node, ge_model);
  1541. NodeItem *node_item = nullptr;
  1542. GE_CHK_STATUS_RET_NOLOG(GetOrCreateNodeItem(wrapper_node, &node_item));
  1543. node_item->input_start = 0;
  1544. node_item->output_start = 0;
  1545. node_item->outputs.resize(node_item->num_outputs);
  1546. graph_item->node_items_.emplace_back(node_item);
  1547. graph_item->output_node_ = node_item;
  1548. graph_item->total_inputs_ = node_item->num_inputs;
  1549. graph_item->total_outputs_ = node_item->num_outputs;
  1550. GELOGD("NodeItem create for known shape subgraph [%s], NodeItem = %s",
  1551. graph.GetName().c_str(),
  1552. node_item->DebugString().c_str());
  1553. GELOGD("Done parse known shape subgraph successfully. graph = [%s]", graph.GetName().c_str());
  1554. graph_item->SetName(graph.GetName());
  1555. GELOGD("Done loading known shape subgraph: [%s]", graph_item->GetName().c_str());
  1556. hybrid_model_.subgraph_items_.emplace(graph.GetName(), std::move(graph_item));
  1557. return SUCCESS;
  1558. }
  1559. Status HybridModelBuilder::RecoverGraphUnknownFlag() {
  1560. const auto &root_graph = hybrid_model_.root_graph_;
  1561. for (auto &sub_graph : root_graph->GetAllSubgraphs()) {
  1562. GE_CHECK_NOTNULL(sub_graph);
  1563. for (const auto &node : sub_graph->GetDirectNode()) {
  1564. bool is_unknown_shape = false;
  1565. (void)AttrUtils::GetBool(node->GetOpDesc(), kOwnerGraphIsUnknown, is_unknown_shape);
  1566. sub_graph->SetGraphUnknownFlag(is_unknown_shape);
  1567. break;
  1568. }
  1569. }
  1570. return SUCCESS;
  1571. }
  1572. Status HybridModelBuilder::GenerateFpProfilingTask(const OpDescPtr &op_desc, vector<domi::TaskDef> &task_def_list) {
  1573. uint64_t jobid_log_id = ge::GetContext().TraceId();
  1574. GELOGD("The first FP operator is %s,, job_id %lu", op_desc->GetName().c_str(), jobid_log_id);
  1575. TaskDef job_task_def;
  1576. job_task_def.set_type(RT_MODEL_TASK_PROFILER_TRACE);
  1577. job_task_def.set_stream_id(op_desc->GetStreamId());
  1578. LogTimeStampDef *job_log_def = job_task_def.mutable_log_timestamp();
  1579. if (job_log_def != nullptr) {
  1580. job_log_def->set_logid(jobid_log_id);
  1581. job_log_def->set_notify(false);
  1582. }
  1583. task_def_list.emplace_back(job_task_def);
  1584. TaskDef fp_task_def;
  1585. fp_task_def.set_type(RT_MODEL_TASK_PROFILER_TRACE);
  1586. fp_task_def.set_stream_id(op_desc->GetStreamId());
  1587. LogTimeStampDef *fp_log_def = fp_task_def.mutable_log_timestamp();
  1588. if (fp_log_def != nullptr) {
  1589. fp_log_def->set_logid(kProfilingFpStartLogid);
  1590. fp_log_def->set_notify(false);
  1591. }
  1592. task_def_list.emplace_back(fp_task_def);
  1593. return SUCCESS;
  1594. }
  1595. Status HybridModelBuilder::GenerateArProfilingTask(const OpDescPtr &op_desc, int64_t log_id,
  1596. vector<domi::TaskDef> &task_def_list) {
  1597. TaskDef ar_task_def;
  1598. ar_task_def.set_type(RT_MODEL_TASK_PROFILER_TRACE);
  1599. ar_task_def.set_stream_id(op_desc->GetStreamId());
  1600. LogTimeStampDef *ar_log_def = ar_task_def.mutable_log_timestamp();
  1601. if (ar_log_def != nullptr) {
  1602. ar_log_def->set_logid(log_id);
  1603. ar_log_def->set_notify(false);
  1604. }
  1605. task_def_list.emplace_back(ar_task_def);
  1606. return SUCCESS;
  1607. }
  1608. Status HybridModelBuilder::GenerateBpProfilingTask(const OpDescPtr &op_desc, vector<domi::TaskDef> &task_def_list) {
  1609. TaskDef bp_task_def;
  1610. bp_task_def.set_type(RT_MODEL_TASK_PROFILER_TRACE);
  1611. bp_task_def.set_stream_id(op_desc->GetStreamId());
  1612. LogTimeStampDef *bp_log_def = bp_task_def.mutable_log_timestamp();
  1613. GE_CHECK_NOTNULL(bp_log_def);
  1614. bp_log_def->set_logid(kProfilingBpEndLogid);
  1615. bp_log_def->set_notify(false);
  1616. task_def_list.emplace_back(bp_task_def);
  1617. return SUCCESS;
  1618. }
  1619. Status HybridModelBuilder::GenerateEndProfilingTask(const OpDescPtr &op_desc, vector<domi::TaskDef> &task_def_list) {
  1620. TaskDef end_task_def;
  1621. end_task_def.set_type(RT_MODEL_TASK_PROFILER_TRACE);
  1622. end_task_def.set_stream_id(op_desc->GetStreamId());
  1623. LogTimeStampDef *end_log_def = end_task_def.mutable_log_timestamp();
  1624. GE_CHECK_NOTNULL(end_log_def);
  1625. end_log_def->set_logid(kProfilingIterEndLogid);
  1626. end_log_def->set_notify(true);
  1627. task_def_list.emplace_back(end_task_def);
  1628. return SUCCESS;
  1629. }
  1630. Status HybridModelBuilder::CreateProfilingNodeBefore(GraphItem &graph_item, const NodePtr &node, uint32_t &prev_num) {
  1631. GE_CHECK_NOTNULL(node);
  1632. const OpDescPtr &op_desc = node->GetOpDesc();
  1633. GE_CHECK_NOTNULL(op_desc);
  1634. const auto &compute_graph = MakeShared<ComputeGraph>(kProfilingGraph);
  1635. GE_CHECK_NOTNULL(compute_graph);
  1636. NodePtr node_ptr = nullptr;
  1637. map<NodePtr, vector<domi::TaskDef>> node_task_map;
  1638. // create fp node
  1639. bool is_insert_fp_profiling_task = false;
  1640. (void)ge::AttrUtils::GetBool(op_desc, ATTR_NAME_INSERT_FP_PROFILILNG_TASK, is_insert_fp_profiling_task);
  1641. if (is_insert_fp_profiling_task) {
  1642. vector<domi::TaskDef> task_def_list;
  1643. (void)GenerateFpProfilingTask(op_desc, task_def_list);
  1644. auto fp_desc = MakeShared<OpDesc>(kProfilingFpNode, PROFILINGTRAININGTRACE);
  1645. GE_CHECK_NOTNULL(fp_desc);
  1646. fp_desc->SetOpKernelLibName(kEngineNameRts);
  1647. node_ptr = compute_graph->AddNode(fp_desc);
  1648. GE_CHECK_NOTNULL(node_ptr);
  1649. node_task_map[node_ptr] = task_def_list;
  1650. GELOGD("Create fp profiling node success before.");
  1651. }
  1652. // creat all reduce start node
  1653. bool is_insert_bp_profiling_task = false;
  1654. (void)ge::AttrUtils::GetBool(op_desc, ATTR_NAME_INSERT_BP_PROFILILNG_TASK, is_insert_bp_profiling_task);
  1655. bool is_all_reduce = (op_desc->GetType() == HCOMALLREDUCE || op_desc->GetType() == HVDCALLBACKALLREDUCE);
  1656. if (is_all_reduce && is_insert_bp_profiling_task) {
  1657. vector<domi::TaskDef> task_def_list;
  1658. int64_t log_id = 0;
  1659. (void)ge::AttrUtils::GetInt(op_desc, ATTR_NAME_INSERT_PROFILILNG_TASK_LOG_ID, log_id);
  1660. GELOGD("All reduce node profiling task log id: %ld before", log_id);
  1661. (void) GenerateArProfilingTask(op_desc, log_id, task_def_list);
  1662. string op_name = string(kProfilingArNode) + std::to_string(log_id);
  1663. auto ar_desc_start = MakeShared<OpDesc>(op_name, PROFILINGTRAININGTRACE);
  1664. GE_CHECK_NOTNULL(ar_desc_start);
  1665. ar_desc_start->SetOpKernelLibName(kEngineNameRts);
  1666. node_ptr = compute_graph->AddNode(ar_desc_start);
  1667. GE_CHECK_NOTNULL(node_ptr);
  1668. node_task_map[node_ptr] = task_def_list;
  1669. GELOGD("Create all reduce start profiling node success before.");
  1670. }
  1671. if (!node_task_map.empty()) {
  1672. for (const auto &node_task : node_task_map) {
  1673. NodePtr profiling_node = node_task.first;
  1674. const vector<domi::TaskDef> &task_def_lists = node_task.second;
  1675. for (const auto &task_def : task_def_lists) {
  1676. hybrid_model_.task_defs_[profiling_node].emplace_back(task_def);
  1677. }
  1678. if (op_desc->HasAttr(ATTR_STAGE_LEVEL)) {
  1679. uint32_t stage_level = UINT32_MAX;
  1680. (void)ge::AttrUtils::GetInt(op_desc, ATTR_STAGE_LEVEL, stage_level);
  1681. (void)ge::AttrUtils::SetInt(node_ptr->GetOpDesc(), ATTR_STAGE_LEVEL, stage_level);
  1682. }
  1683. NodeItem *node_item = nullptr;
  1684. GE_CHK_STATUS_RET_NOLOG(GetOrCreateNodeItem(profiling_node, &node_item));
  1685. GE_CHECK_NOTNULL(node_item);
  1686. node_item->input_start = 0;
  1687. node_item->output_start = 0;
  1688. graph_item.node_items_.emplace_back(node_item);
  1689. ++prev_num;
  1690. }
  1691. } else {
  1692. GELOGD("No need to create profiling node before.");
  1693. }
  1694. return SUCCESS;
  1695. }
  1696. Status HybridModelBuilder::CreateProfilingNodeAfter(GraphItem &graph_item, const NodePtr &node, uint32_t &post_num) {
  1697. GE_CHECK_NOTNULL(node);
  1698. const OpDescPtr &op_desc = node->GetOpDesc();
  1699. GE_CHECK_NOTNULL(op_desc);
  1700. const auto &compute_graph = MakeShared<ComputeGraph>(kProfilingGraph);
  1701. GE_CHECK_NOTNULL(compute_graph);
  1702. NodePtr node_ptr = nullptr;
  1703. map<NodePtr, vector<domi::TaskDef>> node_task_map;
  1704. // Create all reduce end node
  1705. bool is_insert_bp_profiling_task = false;
  1706. (void)ge::AttrUtils::GetBool(op_desc, ATTR_NAME_INSERT_BP_PROFILILNG_TASK, is_insert_bp_profiling_task);
  1707. bool is_all_reduce = (op_desc->GetType() == HCOMALLREDUCE || op_desc->GetType() == HVDCALLBACKALLREDUCE);
  1708. if (is_all_reduce && is_insert_bp_profiling_task) {
  1709. vector<domi::TaskDef> task_def_list;
  1710. int64_t log_id = 0;
  1711. (void)ge::AttrUtils::GetInt(op_desc, ATTR_NAME_INSERT_PROFILILNG_TASK_LOG_ID, log_id);
  1712. GELOGD("All reduce node profiling task log id: %ld after", log_id);
  1713. (void) GenerateArProfilingTask(op_desc, log_id + 1, task_def_list);
  1714. string op_name = string(kProfilingArNode) + std::to_string(log_id + 1);
  1715. auto ar_desc_end = MakeShared<OpDesc>(op_name, PROFILINGTRAININGTRACE);
  1716. GE_CHECK_NOTNULL(ar_desc_end);
  1717. ar_desc_end->SetOpKernelLibName(kEngineNameRts);
  1718. node_ptr = compute_graph->AddNode(ar_desc_end);
  1719. GE_CHECK_NOTNULL(node_ptr);
  1720. node_task_map[node_ptr] = task_def_list;
  1721. GELOGD("Create all reduce end profiling node success after.");
  1722. }
  1723. // create bp node
  1724. if (!is_all_reduce && is_insert_bp_profiling_task) {
  1725. vector<domi::TaskDef> task_def_list;
  1726. (void) GenerateBpProfilingTask(op_desc, task_def_list);
  1727. auto bp_op_desc = MakeShared<OpDesc>(kProfilingBpNode, PROFILINGTRAININGTRACE);
  1728. GE_CHECK_NOTNULL(bp_op_desc);
  1729. bp_op_desc->SetOpKernelLibName(kEngineNameRts);
  1730. node_ptr = compute_graph->AddNode(bp_op_desc);
  1731. GE_CHECK_NOTNULL(node_ptr);
  1732. node_task_map[node_ptr] = task_def_list;
  1733. GELOGD("Create bp profiling node success after.");
  1734. }
  1735. // create end node
  1736. bool is_insert_end_profiling_task = false;
  1737. (void)ge::AttrUtils::GetBool(op_desc, ATTR_NAME_INSERT_END_PROFILILNG_TASK, is_insert_end_profiling_task);
  1738. if (is_insert_end_profiling_task) {
  1739. vector<domi::TaskDef> task_def_list;
  1740. (void)GenerateEndProfilingTask(op_desc, task_def_list);
  1741. auto end_desc = MakeShared<OpDesc>(kProfilingEndNode, PROFILINGTRAININGTRACE);
  1742. GE_CHECK_NOTNULL(end_desc);
  1743. end_desc->SetOpKernelLibName(kEngineNameRts);
  1744. node_ptr = compute_graph->AddNode(end_desc);
  1745. GE_CHECK_NOTNULL(node_ptr);
  1746. node_task_map[node_ptr] = task_def_list;
  1747. GELOGD("Create end profiling node success after.");
  1748. }
  1749. if (!node_task_map.empty()) {
  1750. for (const auto &node_task : node_task_map) {
  1751. NodePtr profiling_node = node_task.first;
  1752. const vector<domi::TaskDef> &task_def_lists = node_task.second;
  1753. for (const auto &task_def : task_def_lists) {
  1754. hybrid_model_.task_defs_[profiling_node].emplace_back(task_def);
  1755. }
  1756. if (op_desc->HasAttr(ATTR_STAGE_LEVEL)) {
  1757. uint32_t stage_level = UINT32_MAX;
  1758. (void)ge::AttrUtils::GetInt(op_desc, ATTR_STAGE_LEVEL, stage_level);
  1759. (void)ge::AttrUtils::SetInt(profiling_node->GetOpDesc(), ATTR_STAGE_LEVEL, stage_level);
  1760. }
  1761. NodeItem *node_item = nullptr;
  1762. GE_CHK_STATUS_RET_NOLOG(GetOrCreateNodeItem(profiling_node, &node_item));
  1763. GE_CHECK_NOTNULL(node_item);
  1764. node_item->input_start = 0;
  1765. node_item->output_start = 0;
  1766. graph_item.node_items_.emplace_back(node_item);
  1767. ++post_num;
  1768. }
  1769. } else {
  1770. GELOGD("No need to create profiling node after.");
  1771. }
  1772. return SUCCESS;
  1773. }
  1774. Status HybridModelBuilder::LoadDynamicSubgraph(ComputeGraph &graph, bool is_root_graph) {
  1775. GELOGD("Start to load subgraph [%s]", graph.GetName().c_str());
  1776. // for known partitioned call, load all nodes
  1777. auto graph_item = std::unique_ptr<GraphItem>(new(std::nothrow)GraphItem());
  1778. GE_CHECK_NOTNULL(graph_item);
  1779. graph_item->is_dynamic_ = true;
  1780. graph_item->node_items_.reserve(graph.GetDirectNodesSize());
  1781. int input_start = 0;
  1782. int output_start = 0;
  1783. std::vector<NodeItem *> data_nodes;
  1784. std::map<size_t, std::pair<uint32_t, uint32_t>> profiling_nodes;
  1785. for (auto &node : graph.GetDirectNode()) {
  1786. GE_CHECK_NOTNULL(node);
  1787. GE_CHECK_NOTNULL(node->GetOpDesc());
  1788. const auto &op_type = node->GetType();
  1789. NodeItem *node_item = nullptr;
  1790. GE_CHK_STATUS_RET_NOLOG(GetOrCreateNodeItem(node, &node_item));
  1791. GE_CHK_STATUS_RET_NOLOG(BuildNodeItem(node, *node_item));
  1792. GE_CHK_STATUS_RET_NOLOG(UpdateAnchorStatus(node)); // needed by FE generate task
  1793. GE_CHK_STATUS_RET_NOLOG(BuildFrameGroupIndex(*node_item));
  1794. GE_CHK_STATUS_RET_NOLOG(BuildControlFlowGroup(*graph_item, node, node_item));
  1795. if (node->GetInAllNodes().empty()) {
  1796. graph_item->root_items_.emplace_back(node_item);
  1797. GELOGD("[%s] add to root node list", node->GetName().c_str());
  1798. }
  1799. node_item->input_start = input_start;
  1800. node_item->output_start = output_start;
  1801. input_start += node_item->num_inputs;
  1802. output_start += node_item->num_outputs;
  1803. if (op_type == DATA_TYPE || op_type == AIPP_DATA_TYPE) {
  1804. data_nodes.emplace_back(node_item);
  1805. } else if (op_type == NETOUTPUT) {
  1806. graph_item->output_node_ = node_item;
  1807. GE_CHK_STATUS_RET_NOLOG(BuildOutputMapping(*graph_item, *node_item, is_root_graph));
  1808. }
  1809. uint32_t prev_num = 0;
  1810. uint32_t post_num = 0;
  1811. GE_CHK_STATUS_RET_NOLOG(CreateProfilingNodeBefore(*graph_item, node, prev_num));
  1812. size_t node_index = graph_item->node_items_.size();
  1813. graph_item->node_items_.emplace_back(node_item);
  1814. GE_CHK_STATUS_RET_NOLOG(CreateProfilingNodeAfter(*graph_item, node, post_num));
  1815. if (prev_num > 0 || post_num > 0) {
  1816. profiling_nodes[node_index] = { prev_num, post_num };
  1817. }
  1818. // parse var outputs
  1819. GE_CHK_STATUS_RET_NOLOG(ParseVarOutputs(*node_item));
  1820. GELOGD("NodeItem created: %s", node_item->DebugString().c_str());
  1821. }
  1822. graph_item->total_inputs_ = input_start;
  1823. graph_item->total_outputs_ = output_start;
  1824. GE_CHK_STATUS_RET_NOLOG(BuildInputMapping(*graph_item, data_nodes, is_root_graph));
  1825. GE_CHK_STATUS_RET_NOLOG(BuildProfilingControl(*graph_item, profiling_nodes));
  1826. if (is_root_graph) {
  1827. graph_item->SetName("Root-Graph");
  1828. GELOGD("Done loading dynamic subgraph: [%s]", graph_item->GetName().c_str());
  1829. hybrid_model_.root_graph_item_ = std::move(graph_item);
  1830. } else {
  1831. graph_item->SetName(graph.GetName());
  1832. GELOGD("Done loading dynamic subgraph: [%s]", graph_item->GetName().c_str());
  1833. hybrid_model_.subgraph_items_.emplace(graph.GetName(), std::move(graph_item));
  1834. }
  1835. return SUCCESS;
  1836. }
  1837. Status HybridModelBuilder::ParseVarOutputs(NodeItem &node_item) {
  1838. for (int i = 0; i < node_item.num_outputs; ++i) {
  1839. auto output_tensor_desc = node_item.op_desc->GetOutputDesc(i);
  1840. std::string var_name;
  1841. (void) AttrUtils::GetStr(output_tensor_desc, ASSIGN_VAR_NAME, var_name);
  1842. if (!var_name.empty()) {
  1843. auto var_node = hybrid_model_.GetVariableNode(var_name);
  1844. GE_CHECK_NOTNULL(var_node);
  1845. node_item.ref_outputs.emplace(i, var_node);
  1846. }
  1847. }
  1848. return SUCCESS;
  1849. }
  1850. Status HybridModelBuilder::BuildInputMapping(GraphItem &graph_item,
  1851. vector<NodeItem *> &data_nodes,
  1852. bool is_root_graph) {
  1853. uint32_t data_op_index = 0;
  1854. for (auto &node_item : data_nodes) {
  1855. auto node = node_item->node;
  1856. int data_index = data_op_index;
  1857. if (is_root_graph) {
  1858. if (AttrUtils::GetInt(node->GetOpDesc(), ATTR_NAME_INDEX, data_index)) {
  1859. GELOGI("ge_train: get new index %u, old %u", data_index, data_op_index);
  1860. }
  1861. data_op_index++;
  1862. } else {
  1863. if (!AttrUtils::GetInt(node->GetOpDesc(), ATTR_NAME_PARENT_NODE_INDEX, data_index)) {
  1864. GELOGE(FAILED, "[Invoke][GetInt][%s] Failed to get attr [%s]",
  1865. node->GetName().c_str(), ATTR_NAME_PARENT_NODE_INDEX.c_str());
  1866. REPORT_CALL_ERROR("E19999", "call GetInt failed, [%s] Failed to get attr [%s]",
  1867. node->GetName().c_str(), ATTR_NAME_PARENT_NODE_INDEX.c_str());
  1868. return FAILED;
  1869. }
  1870. }
  1871. if (graph_item.input_nodes_.size() <= static_cast<size_t>(data_index)) {
  1872. graph_item.input_nodes_.resize(data_index + 1);
  1873. }
  1874. graph_item.input_nodes_[data_index] = node_item;
  1875. }
  1876. return SUCCESS;
  1877. }
  1878. Status HybridModelBuilder::CheckAicpuOpList() {
  1879. std::vector<std::string> aicpu_optype_list;
  1880. std::vector<std::string> aicpu_tf_optype_list;
  1881. std::set<std::string> aicpu_optype_set;
  1882. std::set<std::string> aicpu_tf_optype_set;
  1883. for (auto &it : ge_root_model_->GetSubgraphInstanceNameToModel()) {
  1884. auto &ge_model = it.second;
  1885. GE_CHECK_NOTNULL(ge_model);
  1886. if (ge::AttrUtils::GetListStr(*ge_model, "needCheckCpu", aicpu_optype_list)) {
  1887. aicpu_optype_set.insert(aicpu_optype_list.begin(), aicpu_optype_list.end());
  1888. }
  1889. if (ge::AttrUtils::GetListStr(*ge_model, "needCheckTf", aicpu_tf_optype_list)) {
  1890. aicpu_tf_optype_set.insert(aicpu_tf_optype_list.begin(), aicpu_tf_optype_list.end());
  1891. }
  1892. }
  1893. // reset list with set
  1894. aicpu_optype_list.assign(aicpu_optype_set.begin(), aicpu_optype_set.end());
  1895. aicpu_tf_optype_list.assign(aicpu_tf_optype_set.begin(), aicpu_tf_optype_set.end());
  1896. GE_CHK_STATUS_RET(ModelManager::GetInstance()->LaunchKernelCheckAicpuOp(aicpu_optype_list, aicpu_tf_optype_list),
  1897. "[Launch][KernelCheckAicpuOp] failed.");
  1898. return SUCCESS;
  1899. }
  1900. Status HybridModelBuilder::CollectParallelGroups(NodeItem *node_item) {
  1901. const auto &node = node_item->node;
  1902. auto executor_type = NodeExecutorManager::GetInstance().ResolveExecutorType(*node);
  1903. if (executor_type == NodeExecutorManager::ExecutorType::HCCL) {
  1904. std::string parallel_group;
  1905. if (AttrUtils::GetStr(node->GetOpDesc(), ATTR_NAME_PARALLEL_GROUP, parallel_group)) {
  1906. GELOGD("[%s] Got parallel group = [%s]", node_item->NodeName().c_str(), parallel_group.c_str());
  1907. parallel_group_to_nodes_[parallel_group].emplace(node_item);
  1908. std::set<std::string> group{parallel_group};
  1909. node_to_parallel_groups_[node_item].emplace(parallel_group);
  1910. }
  1911. } else if (executor_type == NodeExecutorManager::ExecutorType::COMPILED_SUBGRAPH) {
  1912. std::set<std::string> parallel_groups;
  1913. GELOGD("[%s] To collect parallel group for known-shaped subgraph", node_item->NodeName().c_str());
  1914. for (const auto &subgraph_name : node->GetOpDesc()->GetSubgraphInstanceNames()) {
  1915. GELOGD("[%s] Start to get parallel group from subgraph: %s",
  1916. node_item->NodeName().c_str(),
  1917. subgraph_name.c_str());
  1918. auto subgraph = hybrid_model_.root_graph_->GetSubgraph(subgraph_name);
  1919. GE_CHECK_NOTNULL(subgraph);
  1920. for (const auto &sub_node : subgraph->GetAllNodes()) {
  1921. std::string parallel_group;
  1922. if (AttrUtils::GetStr(sub_node->GetOpDesc(), ATTR_NAME_PARALLEL_GROUP, parallel_group)) {
  1923. GELOGD("[%s::%s] Got parallel group = %s",
  1924. subgraph_name.c_str(),
  1925. sub_node->GetName().c_str(),
  1926. parallel_group.c_str());
  1927. parallel_groups.emplace(parallel_group);
  1928. }
  1929. }
  1930. }
  1931. if (!parallel_groups.empty()) {
  1932. for (const auto &parallel_group : parallel_groups) {
  1933. parallel_group_to_nodes_[parallel_group].emplace(node_item);
  1934. GELOGD("[%s] has parallel group: %s", node_item->NodeName().c_str(), parallel_group.c_str());
  1935. }
  1936. node_to_parallel_groups_.emplace(node_item, std::move(parallel_groups));
  1937. }
  1938. }
  1939. return SUCCESS;
  1940. }
  1941. Status HybridModelBuilder::ParseDependentByParallelGroup() {
  1942. for (auto &it : hybrid_model_.node_items_) {
  1943. GE_CHK_STATUS_RET_NOLOG(CollectParallelGroups(it.second.get()));
  1944. }
  1945. for (const auto &it : node_to_parallel_groups_) {
  1946. auto node_item = it.first;
  1947. auto dst_executor_type = NodeExecutorManager::GetInstance().ResolveExecutorType(*node_item->node);
  1948. for (const auto &parallel_group : it.second) {
  1949. auto &dependent_nodes = parallel_group_to_nodes_[parallel_group];
  1950. NodeItem *nearest_dep_node = nullptr;
  1951. int max_id = -1;
  1952. for (auto &dep_node : dependent_nodes) {
  1953. if (dep_node->node_id < node_item->node_id && dep_node->node_id > max_id) {
  1954. nearest_dep_node = dep_node;
  1955. max_id = dep_node->node_id;
  1956. }
  1957. }
  1958. if (nearest_dep_node != nullptr) {
  1959. GELOGD("[%s] Nearest node = [%s]", node_item->NodeName().c_str(), nearest_dep_node->NodeName().c_str());
  1960. auto src_engine_type = NodeExecutorManager::GetInstance().ResolveExecutorType(*nearest_dep_node->node);
  1961. if (src_engine_type == dst_executor_type) {
  1962. GELOGD("No need to add dependency for nodes with same executor type");
  1963. continue;
  1964. }
  1965. auto &deps = node_item->dependents_for_execution;
  1966. if (std::find(deps.begin(), deps.end(), nearest_dep_node->node) != deps.end()) {
  1967. GELOGD("%s->%s Already has dependency, skip it",
  1968. nearest_dep_node->node->GetName().c_str(),
  1969. node_item->NodeName().c_str());
  1970. continue;
  1971. }
  1972. nearest_dep_node->has_observer = true;
  1973. deps.emplace_back(nearest_dep_node->node);
  1974. GELOGD("Add dependency for nodes with the same parallel group[%s], src = [%s], dst = [%s]",
  1975. parallel_group.c_str(),
  1976. nearest_dep_node->NodeName().c_str(),
  1977. node_item->NodeName().c_str());
  1978. }
  1979. }
  1980. }
  1981. return SUCCESS;
  1982. }
  1983. Status HybridModelBuilder::OptimizeDependenciesForConstantInputs() {
  1984. std::map<NodePtr, std::set<uint32_t>> converted;
  1985. for (auto &it : host_input_value_dependencies_) {
  1986. auto node_item = it.first;
  1987. std::map<NodeItem *, int> ref_counts;
  1988. bool changed = false;
  1989. for (auto output_idx_and_node : it.second) {
  1990. auto output_idx = output_idx_and_node.first;
  1991. auto src_node_item = output_idx_and_node.second;
  1992. ++ref_counts[src_node_item];
  1993. NodePtr constant_node;
  1994. if (src_node_item->node_type == CONSTANT || src_node_item->node_type == CONSTANTOP) {
  1995. constant_node = src_node_item->node;
  1996. GELOGD("src node [%s] is a constant", src_node_item->NodeName().c_str());
  1997. } else {
  1998. auto iter = known_subgraph_constant_output_refs_.find(src_node_item);
  1999. if (iter != known_subgraph_constant_output_refs_.end()) {
  2000. constant_node = iter->second[output_idx];
  2001. if (constant_node != nullptr) {
  2002. GELOGD("Output[%u] of subgraph [%s] is a constant", output_idx, src_node_item->NodeName().c_str());
  2003. }
  2004. }
  2005. }
  2006. if (constant_node == nullptr) {
  2007. GELOGD("Output[%u] of [%s] is not a constant", output_idx, src_node_item->NodeName().c_str());
  2008. continue;
  2009. }
  2010. if (converted[constant_node].count(output_idx) == 0) {
  2011. GE_CHK_STATUS_RET(Convert2HostTensor(constant_node, src_node_item->node_id, output_idx),
  2012. "[%s] Failed to convert constant to host tensor", constant_node->GetName().c_str());
  2013. converted[constant_node].emplace(output_idx);
  2014. }
  2015. src_node_item->to_const_output_id_list.erase(output_idx);
  2016. --ref_counts[src_node_item];
  2017. changed = true;
  2018. }
  2019. if (changed) {
  2020. std::vector<NodePtr> depends_to_keep;
  2021. for (auto &ref_count_it : ref_counts) {
  2022. if (ref_count_it.second == 0) {
  2023. GELOGD("[%s] no longer depends on [%s] for shape inference",
  2024. node_item->NodeName().c_str(),
  2025. ref_count_it.first->NodeName().c_str());
  2026. } else {
  2027. depends_to_keep.emplace_back(ref_count_it.first->node);
  2028. }
  2029. }
  2030. node_item->dependents_for_shape_inference.swap(depends_to_keep);
  2031. }
  2032. }
  2033. return SUCCESS;
  2034. }
  2035. Status HybridModelBuilder::Convert2HostTensor(const NodePtr &node, int node_id, uint32_t output_idx) {
  2036. auto tensor_value = hybrid_model_.GetTensor(node);
  2037. GE_CHECK_NOTNULL(tensor_value);
  2038. auto tensor_desc = node->GetOpDesc()->MutableOutputDesc(0);
  2039. GE_CHECK_NOTNULL(tensor_desc);
  2040. Tensor tensor(TensorAdapter::GeTensorDesc2TensorDesc(*tensor_desc));
  2041. int64_t tensor_size = -1;
  2042. GE_CHK_GRAPH_STATUS_RET(TensorUtils::GetTensorSizeInBytes(*tensor_desc, tensor_size),
  2043. "[%s] Failed to get tensor size", node->GetName().c_str());
  2044. if (tensor_size > 0) {
  2045. auto copy_size = static_cast<size_t>(tensor_size);
  2046. GE_CHECK_GE(tensor_value->GetSize(), copy_size);
  2047. std::vector<uint8_t> buffer(copy_size);
  2048. GE_CHK_RT_RET(rtMemcpy(buffer.data(),
  2049. copy_size,
  2050. tensor_value->GetData(),
  2051. copy_size,
  2052. RT_MEMCPY_DEVICE_TO_HOST));
  2053. tensor.SetData(std::move(buffer));
  2054. GELOGD("[%s] Copy constant tensor to host successfully, size = %zu", node->GetName().c_str(), copy_size);
  2055. }
  2056. hybrid_model_.host_tensors_[node_id].emplace_back(output_idx, std::move(tensor));
  2057. return SUCCESS;
  2058. }
  2059. Status HybridModelBuilder::RelinkNextIteration() {
  2060. for (const auto &item : stream_merge_op_nodes_) {
  2061. const auto &merge = item.second;
  2062. std::string node_name;
  2063. if (!AttrUtils::GetStr(merge->GetOpDesc(), ATTR_NAME_NEXT_ITERATION, node_name)) {
  2064. GELOGD("[%s] no attribute[%s], not in while loop", merge->GetName().c_str(), ATTR_NAME_NEXT_ITERATION.c_str());
  2065. continue;
  2066. }
  2067. const auto it = next_iteration_op_nodes_.find(node_name);
  2068. if (it == next_iteration_op_nodes_.end()) {
  2069. GELOGE(INTERNAL_ERROR, "[%s] expect NextIteration[%s] not found", merge->GetName().c_str(), node_name.c_str());
  2070. return INTERNAL_ERROR;
  2071. }
  2072. const auto &iteration = it->second;
  2073. if (GraphUtils::AddEdge(iteration->GetOutDataAnchor(0), merge->GetInDataAnchor(1)) != GRAPH_SUCCESS) {
  2074. GELOGE(INTERNAL_ERROR, "[%s] -> [%s] Add edge failed", node_name.c_str(), merge->GetName().c_str());
  2075. return INTERNAL_ERROR;
  2076. }
  2077. }
  2078. return SUCCESS;
  2079. }
  2080. Status HybridModelBuilder::BuildProfilingControl(GraphItem &graph_item,
  2081. const std::map<size_t, std::pair<uint32_t, uint32_t>> &nodes) {
  2082. const auto node_size = graph_item.node_items_.size();
  2083. for (const auto &item : nodes) {
  2084. const auto node_index = item.first;
  2085. GE_CHK_BOOL_RET_STATUS(node_index < node_size, FAILED, "node index invalid");
  2086. const auto &node_item = graph_item.node_items_[node_index];
  2087. if (item.second.first > 0) {
  2088. const auto prev_num = item.second.first;
  2089. if (node_index == prev_num) {
  2090. // Profiling Before root node.
  2091. for (uint32_t i = 1; i <= prev_num; ++i) {
  2092. GE_CHK_BOOL_RET_STATUS(node_index - i < node_size, FAILED, "prev index invalid");
  2093. const auto &curr_item = graph_item.node_items_[node_index - i];
  2094. graph_item.root_items_.emplace(graph_item.root_items_.begin(), curr_item);
  2095. }
  2096. } else {
  2097. GE_CHK_BOOL_RET_STATUS((node_index - prev_num) - 1 < node_size, FAILED, "prev index invalid");
  2098. const auto &prev_item = graph_item.node_items_[(node_index - prev_num) - 1];
  2099. for (uint32_t i = 1; i <= prev_num; ++i) {
  2100. GE_CHK_BOOL_RET_STATUS(node_index - i < node_size, FAILED, "prev index invalid");
  2101. const auto &curr_item = graph_item.node_items_[node_index - i];
  2102. prev_item->SetCtrlSend(curr_item, UINT32_MAX);
  2103. curr_item->SetCtrlSend(node_item, UINT32_MAX);
  2104. }
  2105. }
  2106. }
  2107. if (item.second.second > 0) {
  2108. const auto post_num = item.second.second;
  2109. if (node_size == node_index + post_num + 1) {
  2110. // Profiling After last node.
  2111. for (uint32_t i = 1; i <= post_num; ++i) {
  2112. GE_CHK_BOOL_RET_STATUS(node_index + i < node_size, FAILED, "post index invalid");
  2113. const auto &curr_item = graph_item.node_items_[node_index + i];
  2114. node_item->SetCtrlSend(curr_item, UINT32_MAX);
  2115. }
  2116. } else {
  2117. GE_CHK_BOOL_RET_STATUS((node_index + post_num) + 1 < node_size, FAILED, "post index invalid");
  2118. const auto &post_item = graph_item.node_items_[(node_index + post_num) + 1];
  2119. for (uint32_t i = 1; i <= post_num; ++i) {
  2120. GE_CHK_BOOL_RET_STATUS(node_index + i < node_size, FAILED, "post index invalid");
  2121. const auto &curr_item = graph_item.node_items_[node_index + i];
  2122. node_item->SetCtrlSend(curr_item, UINT32_MAX);
  2123. curr_item->SetCtrlSend(post_item, UINT32_MAX);
  2124. }
  2125. }
  2126. }
  2127. }
  2128. return SUCCESS;
  2129. }
  2130. Status HybridModelBuilder::BuildFrameGroupIndex(NodeItem &node_item) {
  2131. if (node_item.is_root_node_) {
  2132. GELOGD("[%s] control flow frame group: %ld, parent frame: %ld",
  2133. node_item.node_name.c_str(), node_item.frame_index_, node_item.parent_frame_);
  2134. return SUCCESS;
  2135. }
  2136. int64_t ctrl_flow_group = -1;
  2137. if (node_item.IsEnterOp() && AttrUtils::GetInt(node_item.op_desc, ATTR_NAME_CONTROL_FLOW_GROUP, ctrl_flow_group)) {
  2138. node_item.frame_index_ = ctrl_flow_group;
  2139. for (const auto src_node : node_item.node->GetInAllNodes()) {
  2140. NodeItem *src_node_item = nullptr;
  2141. GE_CHK_STATUS_RET(GetOrCreateNodeItem(src_node, &src_node_item),
  2142. "[%s] failed to get or create node item", src_node->GetName().c_str());
  2143. if (!src_node_item->is_root_node_) {
  2144. GELOGD("[%s] frame index: %ld, [%s] parent frame index: %ld", node_item.node_name.c_str(),
  2145. node_item.frame_index_, src_node_item->node_name.c_str(), src_node_item->frame_index_);
  2146. parent_frame_group_[node_item.frame_index_] = src_node_item->frame_index_;
  2147. break;
  2148. }
  2149. }
  2150. const auto it = parent_frame_group_.find(node_item.frame_index_);
  2151. node_item.parent_frame_ = (it != parent_frame_group_.end()) ? it->second : -1;
  2152. GELOGD("[%s] control flow frame group: %ld, parent frame: %ld",
  2153. node_item.node_name.c_str(), node_item.frame_index_, node_item.parent_frame_);
  2154. return SUCCESS;
  2155. }
  2156. for (const auto src_node : node_item.node->GetInAllNodes()) {
  2157. NodeItem *src_node_item = nullptr;
  2158. GE_CHK_STATUS_RET(GetOrCreateNodeItem(src_node, &src_node_item),
  2159. "[%s] failed to get or create node item", src_node->GetName().c_str());
  2160. if (src_node_item->is_root_node_) {
  2161. continue;
  2162. }
  2163. if (src_node_item->IsExitOp()) {
  2164. const auto it = parent_frame_group_.find(src_node_item->frame_index_);
  2165. node_item.frame_index_ = (it != parent_frame_group_.end()) ? it->second : -1;
  2166. } else {
  2167. node_item.frame_index_ = src_node_item->frame_index_;
  2168. }
  2169. const auto it = parent_frame_group_.find(node_item.frame_index_);
  2170. node_item.parent_frame_ = (it != parent_frame_group_.end()) ? it->second : -1;
  2171. GELOGD("[%s] control flow frame group: %ld, parent frame: %ld",
  2172. node_item.node_name.c_str(), node_item.frame_index_, node_item.parent_frame_);
  2173. return SUCCESS;
  2174. }
  2175. GELOGD("[%s] control flow frame group: %ld, parent frame: %ld",
  2176. node_item.node_name.c_str(), node_item.frame_index_, node_item.parent_frame_);
  2177. return SUCCESS;
  2178. }
  2179. Status HybridModelBuilder::BuildControlFlowGroup(GraphItem &graph_item, const NodePtr &node, NodeItem *node_item) {
  2180. GELOGD("Build control flow for node %s", node->GetName().c_str());
  2181. using GroupBuilder = std::function<Status(HybridModelBuilder *, const NodePtr &, NodeItem *)>;
  2182. static const std::map<std::string, GroupBuilder> control_flow{
  2183. { STREAMACTIVE, &HybridModelBuilder::CreateStreamActiveGroup },
  2184. { STREAMSWITCH, &HybridModelBuilder::CreateStreamSwitchGroup },
  2185. { STREAMSWITCHN, &HybridModelBuilder::CreateStreamSwitchNGroup },
  2186. { NEXTITERATION, &HybridModelBuilder::CreateNextIterationGroup },
  2187. { REFNEXTITERATION, &HybridModelBuilder::CreateNextIterationGroup },
  2188. { SWITCH, &HybridModelBuilder::CreateSwitchGroup },
  2189. { REFSWITCH, &HybridModelBuilder::CreateSwitchGroup },
  2190. { LABELSET, &HybridModelBuilder::CreateLabelSetGroup },
  2191. { LABELGOTO, &HybridModelBuilder::CreateLabelGotoGroup },
  2192. { LABELGOTOEX, &HybridModelBuilder::CreateLabelGotoGroup },
  2193. { LABELSWITCH, &HybridModelBuilder::CreateLabelSwitchGroup },
  2194. { LABELSWITCHBYINDEX, &HybridModelBuilder::CreateLabelSwitchGroup }
  2195. };
  2196. Status ret = SUCCESS;
  2197. auto it = control_flow.find(node_item->node_type);
  2198. if (it == control_flow.end()) {
  2199. ret = CreateNormalNodeGroup(node, node_item);
  2200. } else {
  2201. graph_item.has_ctrl_flow_op_ = true;
  2202. ret = it->second(this, node, node_item);
  2203. }
  2204. GELOGD("Node: %s, control by: %zu, control for: %zu, switch group: %zu", node->GetName().c_str(),
  2205. node_item->ctrl_recv_.size(), node_item->ctrl_send_.size(), node_item->switch_groups_.size());
  2206. return ret;
  2207. }
  2208. Status HybridModelBuilder::CreateNormalNodeGroup(const NodePtr &node, NodeItem *node_item) {
  2209. for (const auto &dst_node : node->GetOutControlNodes()) {
  2210. GE_CHECK_NOTNULL(dst_node);
  2211. if ((dst_node->GetType() == STREAMACTIVE) && (kStreamActiveTypes.count(node->GetType()) == 0)) {
  2212. GELOGI("[%s] ignore control to [%s]", node->GetName().c_str(), dst_node->GetName().c_str());
  2213. continue;
  2214. }
  2215. NodeItem *dst_node_item = nullptr;
  2216. GE_CHK_STATUS_RET(GetOrCreateNodeItem(dst_node, &dst_node_item),
  2217. "[%s] failed to get or create node item", dst_node->GetName().c_str());
  2218. node_item->SetCtrlSend(dst_node_item, UINT32_MAX);
  2219. }
  2220. return SUCCESS;
  2221. }
  2222. Status HybridModelBuilder::CreateMergeEnterGroup(const NodePtr &node, NodeItem *node_item) {
  2223. // Enter --> StreamActive --> StreamMerge
  2224. for (const auto &dst_node : node->GetOutControlNodes()) {
  2225. GE_CHECK_NOTNULL(dst_node);
  2226. if (dst_node->GetType() != STREAMMERGE) {
  2227. GELOGI("[%s] Skip Not StreamMerge node [%s]", node->GetName().c_str(), dst_node->GetName().c_str());
  2228. continue;
  2229. }
  2230. NodeItem *dst_node_item = nullptr;
  2231. GE_CHK_STATUS_RET(GetOrCreateNodeItem(dst_node, &dst_node_item),
  2232. "[%s] failed to get or create node item", dst_node->GetName().c_str());
  2233. // Set Enter Control to StreamMerge as Group 0.
  2234. dst_node_item->switch_groups_.resize(kLoopMergeSize);
  2235. dst_node_item->SetMergeCtrl(node_item, kLoopEnterIdx);
  2236. }
  2237. return SUCCESS;
  2238. }
  2239. Status HybridModelBuilder::CreateMergeIterationGroup(const NodePtr &node, NodeItem *node_item) {
  2240. // NextIteration --> StreamActive {-->} StreamMerge
  2241. std::string node_name;
  2242. for (const auto &src_node : node->GetInControlNodes()) {
  2243. GE_CHECK_NOTNULL(src_node);
  2244. if (kNextIterationOpTypes.count(src_node->GetType()) == 0) {
  2245. GELOGI("[%s] Skip Not NextIteration node [%s]", node->GetName().c_str(), src_node->GetName().c_str());
  2246. continue;
  2247. }
  2248. if (!AttrUtils::GetStr(src_node->GetOpDesc(), ATTR_NAME_NEXT_ITERATION, node_name)) {
  2249. GELOGE(INTERNAL_ERROR, "[%s] input node [%s] expect attribute[%s] not found",
  2250. node->GetName().c_str(), src_node->GetName().c_str(), ATTR_NAME_NEXT_ITERATION.c_str());
  2251. return INTERNAL_ERROR;
  2252. }
  2253. const auto it = stream_merge_op_nodes_.find(node_name);
  2254. if (it == stream_merge_op_nodes_.end()) {
  2255. GELOGE(INTERNAL_ERROR, "[%s] expect StreamMerge[%s] not found", node->GetName().c_str(), node_name.c_str());
  2256. return INTERNAL_ERROR;
  2257. }
  2258. const auto &dst_node = it->second;
  2259. GE_CHECK_NOTNULL(dst_node);
  2260. NodeItem *dst_node_item = nullptr;
  2261. GE_CHK_STATUS_RET(GetOrCreateNodeItem(dst_node, &dst_node_item), "[%s] failed to get or create node item",
  2262. dst_node->GetName().c_str());
  2263. // Set NextIteration Control to StreamMerge as Group 1.
  2264. dst_node_item->SetMergeCtrl(node_item, kLoopIterationIdx);
  2265. }
  2266. return SUCCESS;
  2267. }
  2268. Status HybridModelBuilder::CreateStreamActiveGroup(const NodePtr &node, NodeItem *node_item) {
  2269. if (node_item->node_type != STREAMACTIVE) {
  2270. GELOGE(INTERNAL_ERROR, "Called by %s is invalid", node_item->node_type.c_str());
  2271. return INTERNAL_ERROR;
  2272. }
  2273. const auto ctrl_nodes = node->GetInControlNodes();
  2274. if (ctrl_nodes.empty()) {
  2275. GELOGW("Skip no in control node: %s", node->GetName().c_str());
  2276. return SUCCESS;
  2277. }
  2278. const auto IsEnterNode = [](const NodePtr &n) {
  2279. return kEnterOpTypes.count(n->GetType()) > 0;
  2280. };
  2281. const auto IsIterationNode = [](const NodePtr &n) {
  2282. return kNextIterationOpTypes.count(n->GetType()) > 0;
  2283. };
  2284. if (std::any_of(ctrl_nodes.begin(), ctrl_nodes.end(), IsEnterNode)) {
  2285. // Enter --> StreamActive --> StreamMerge
  2286. node_item->is_enter_active_ = true;
  2287. return CreateMergeEnterGroup(node, node_item);
  2288. } else if (std::any_of(ctrl_nodes.begin(), ctrl_nodes.end(), IsIterationNode)) {
  2289. // NextIteration --> StreamActive {-->} StreamMerge
  2290. return CreateMergeIterationGroup(node, node_item);
  2291. }
  2292. return SUCCESS;
  2293. }
  2294. Status HybridModelBuilder::CreateStreamSwitchGroup(const NodePtr &node, NodeItem *node_item) {
  2295. if (node_item->node_type != STREAMSWITCH) {
  2296. GELOGE(INTERNAL_ERROR, "Called by %s is invalid", node_item->node_type.c_str());
  2297. return INTERNAL_ERROR;
  2298. }
  2299. // Consider as two groups, group[0] set empty for false, group[1] for true.
  2300. node_item->switch_groups_.resize(kStreamSwitchNum);
  2301. for (const auto &dst_node : node->GetOutControlNodes()) {
  2302. GE_CHECK_NOTNULL(dst_node);
  2303. NodeItem *dst_node_item = nullptr;
  2304. GE_CHK_STATUS_RET(GetOrCreateNodeItem(dst_node, &dst_node_item),
  2305. "[%s] failed to get or create node item", dst_node->GetName().c_str());
  2306. node_item->SetCtrlSend(dst_node_item, kStreamSwitchIdx);
  2307. }
  2308. return SUCCESS;
  2309. }
  2310. Status HybridModelBuilder::CreateStreamSwitchNGroup(const NodePtr &node, NodeItem *node_item) {
  2311. if (node_item->node_type != STREAMSWITCHN) {
  2312. GELOGE(INTERNAL_ERROR, "Called by %s is invalid", node->GetName().c_str());
  2313. return INTERNAL_ERROR;
  2314. }
  2315. uint32_t batch_num = 0;
  2316. if (!AttrUtils::GetInt(node->GetOpDesc(), ATTR_NAME_BATCH_NUM, batch_num)) {
  2317. GELOGE(INTERNAL_ERROR, "[%s] Get ATTR_NAME_BATCH_NUM failed", node->GetName().c_str());
  2318. return INTERNAL_ERROR;
  2319. }
  2320. if (batch_num == 0) {
  2321. GELOGW("[%s] Got empty branch for SwitchN, Please check.", node->GetName().c_str());
  2322. return SUCCESS;
  2323. }
  2324. node_item->switch_groups_.resize(batch_num);
  2325. for (const auto &dst_node : node->GetOutControlNodes()) {
  2326. GE_CHECK_NOTNULL(dst_node);
  2327. std::string batch_label;
  2328. if (!AttrUtils::GetStr(dst_node->GetOpDesc(), ATTR_NAME_BATCH_LABEL, batch_label)) {
  2329. GELOGE(INTERNAL_ERROR, "[%s] Get ATTR_NAME_BATCH_LABEL failed", dst_node->GetName().c_str());
  2330. return INTERNAL_ERROR;
  2331. }
  2332. std::string::size_type pos = batch_label.rfind("_");
  2333. if (pos == std::string::npos) {
  2334. GELOGW("[%s] Separator not found in batch label: %s.", dst_node->GetName().c_str(), batch_label.c_str());
  2335. continue;
  2336. }
  2337. ++pos; // Skip Separator
  2338. uint64_t batch_index = std::strtoul(batch_label.data() + pos, nullptr, kDecimal);
  2339. if (batch_index >= batch_num) {
  2340. GELOGW("batch label: %s, batch index: %lu great than batch num: %u", batch_label.c_str(), batch_index, batch_num);
  2341. continue;
  2342. }
  2343. NodeItem *dst_node_item = nullptr;
  2344. GE_CHK_STATUS_RET(GetOrCreateNodeItem(dst_node, &dst_node_item),
  2345. "[%s] failed to get or create node item", dst_node->GetName().c_str());
  2346. node_item->SetCtrlSend(dst_node_item, batch_index);
  2347. }
  2348. return SUCCESS;
  2349. }
  2350. Status HybridModelBuilder::CreateNextIterationGroup(const NodePtr &node, NodeItem *node_item) {
  2351. if (node_item->node_type != NEXTITERATION && node_item->node_type != REFNEXTITERATION) {
  2352. GELOGE(INTERNAL_ERROR, "Called by %s is invalid", node->GetName().c_str());
  2353. return INTERNAL_ERROR;
  2354. }
  2355. return CreateNormalNodeGroup(node, node_item);
  2356. }
  2357. Status HybridModelBuilder::CreateSwitchGroup(const NodePtr &node, NodeItem *node_item) {
  2358. if (node_item->node_type != SWITCH && node_item->node_type != REFSWITCH) {
  2359. GELOGE(INTERNAL_ERROR, "Called by %s is invalid", node->GetName().c_str());
  2360. return INTERNAL_ERROR;
  2361. }
  2362. for (const auto &dst_node : node->GetOutControlNodes()) {
  2363. GE_CHECK_NOTNULL(dst_node);
  2364. NodeItem *dst_node_item = nullptr;
  2365. GE_CHK_STATUS_RET(GetOrCreateNodeItem(dst_node, &dst_node_item),
  2366. "[%s] failed to get or create node item", dst_node->GetName().c_str());
  2367. node_item->SetCtrlSend(dst_node_item, UINT32_MAX);
  2368. }
  2369. // Group switch flow by out put data.
  2370. node_item->switch_groups_.resize(SWITCH_OUTPUT_NUM);
  2371. for (uint32_t i = 0; i < SWITCH_OUTPUT_NUM; ++i) {
  2372. for (const auto &dst_node : node->GetOutDataNodes()) {
  2373. GE_CHECK_NOTNULL(dst_node);
  2374. NodeItem *dst_node_item = nullptr;
  2375. GE_CHK_STATUS_RET(GetOrCreateNodeItem(dst_node, &dst_node_item),
  2376. "[%s] failed to get or create node item", dst_node->GetName().c_str());
  2377. node_item->SetCtrlSend(dst_node_item, i); // take switch data as ctrl.
  2378. }
  2379. }
  2380. return SUCCESS;
  2381. }
  2382. Status HybridModelBuilder::CreateLabelSetGroup(const NodePtr &node, NodeItem *node_item) {
  2383. if (node_item->node_type != LABELSET) {
  2384. GELOGE(INTERNAL_ERROR, "Called by %s is invalid", node->GetName().c_str());
  2385. return INTERNAL_ERROR;
  2386. }
  2387. GELOGE(UNSUPPORTED, "[%s] Not implemented.", node->GetName().c_str());
  2388. return UNSUPPORTED;
  2389. }
  2390. Status HybridModelBuilder::CreateLabelGotoGroup(const NodePtr &node, NodeItem *node_item) {
  2391. if (node_item->node_type != LABELGOTO && node_item->node_type != LABELGOTOEX) {
  2392. GELOGE(INTERNAL_ERROR, "Called by %s is invalid", node->GetName().c_str());
  2393. return INTERNAL_ERROR;
  2394. }
  2395. GELOGE(UNSUPPORTED, "[%s] Not implemented.", node->GetName().c_str());
  2396. return UNSUPPORTED;
  2397. }
  2398. Status HybridModelBuilder::CreateLabelSwitchGroup(const NodePtr &node, NodeItem *node_item) {
  2399. if (node_item->node_type != LABELSWITCH && node_item->node_type != LABELSWITCHBYINDEX) {
  2400. GELOGE(INTERNAL_ERROR, "Called by %s is invalid", node->GetName().c_str());
  2401. return INTERNAL_ERROR;
  2402. }
  2403. GELOGE(UNSUPPORTED, "[%s] Not implemented.", node->GetName().c_str());
  2404. return UNSUPPORTED;
  2405. }
  2406. } // namespace hybrid
  2407. } // namespace ge

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