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

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

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