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

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