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

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