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

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