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

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