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

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

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