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

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

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