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

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