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

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

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