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

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

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