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 95 kB

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

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