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

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