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 64 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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564
  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/new_model_manager/model_utils.h"
  23. #include "graph/manager/graph_var_manager.h"
  24. #include "graph/manager/host_mem_manager.h"
  25. #include "graph/manager/trans_var_data_utils.h"
  26. #include "graph/utils/graph_utils.h"
  27. #include "hybrid/common/npu_memory_allocator.h"
  28. #include "hybrid/node_executor/node_executor.h"
  29. #include "framework/common/debug/ge_log.h"
  30. #include "graph/utils/attr_utils.h"
  31. namespace ge {
  32. namespace hybrid {
  33. namespace {
  34. const uint32_t kSubgraphIndex = 0U;
  35. const uint32_t kVarOutputIndex = 0U;
  36. const int kBytes = 8;
  37. const char *const kOwnerGraphIsUnknown = "OwnerGraphIsUnknown";
  38. Status SetOutputNameAttr(ComputeGraph &graph) {
  39. vector<string> output_names;
  40. for (const auto &node : graph.GetDirectNode()) {
  41. auto op_desc = node->GetOpDesc();
  42. if (op_desc == nullptr) {
  43. continue;
  44. }
  45. auto op_type = op_desc->GetType();
  46. if (op_type == NETOUTPUT) {
  47. for (InDataAnchorPtr &in_data_anchor : node->GetAllInDataAnchors()) {
  48. const OutDataAnchorPtr &peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  49. GE_IF_BOOL_EXEC(peer_out_anchor == nullptr, continue);
  50. NodePtr in_node = peer_out_anchor->GetOwnerNode();
  51. GE_CHECK_NOTNULL(in_node);
  52. output_names.push_back(in_node->GetName());
  53. }
  54. }
  55. }
  56. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetListStr(&graph, ATTR_MODEL_OUT_NODES_NAME, output_names),
  57. GELOGE(FAILED, "SetListStr of ATTR_MODEL_OUT_NODES_NAME failed.");
  58. return FAILED);
  59. return SUCCESS;
  60. }
  61. int64_t CalcVarSizeInBytes(const GeTensorDesc &desc) {
  62. int64_t var_size = 0;
  63. auto data_type = desc.GetDataType();
  64. if (data_type == DT_STRING) {
  65. (void) TensorUtils::GetSize(desc, var_size);
  66. return var_size;
  67. }
  68. if (TensorUtils::GetTensorMemorySizeInBytes(desc, var_size) != GRAPH_SUCCESS) {
  69. GELOGW("Failed to calc var data size");
  70. return -1;
  71. }
  72. return var_size;
  73. }
  74. Status CollectDependenciesForFusedGraph(NodeItem &node_item, std::set<OpDesc *> &data_ops) {
  75. for (const auto &node : node_item.fused_subgraph->nodes) {
  76. auto op_desc = node->GetOpDesc();
  77. GE_CHECK_NOTNULL(op_desc);
  78. const auto &depends = op_desc->GetOpInferDepends();
  79. if (depends.empty()) {
  80. continue;
  81. }
  82. for (auto &input_name : depends) {
  83. auto input_index = op_desc->GetInputIndexByName(input_name);
  84. auto src_node = NodeUtils::GetInDataNodeByIndex(*node, input_index);
  85. GE_CHECK_NOTNULL(src_node);
  86. auto src_op_desc = src_node->GetOpDesc();
  87. GE_CHECK_NOTNULL(src_op_desc);
  88. if (src_node->GetType() != DATA_TYPE) {
  89. GELOGE(UNSUPPORTED,
  90. "[%s::%s] Node in fused subgraph can only depend on Data nodes, but depend on %s",
  91. node_item.NodeName().c_str(),
  92. node->GetName().c_str(),
  93. src_node->GetType().c_str());
  94. return UNSUPPORTED;
  95. }
  96. data_ops.emplace(src_op_desc.get());
  97. }
  98. }
  99. return SUCCESS;
  100. }
  101. } // namespace
  102. HybridModelBuilder::HybridModelBuilder(HybridModel &hybrid_model)
  103. : hybrid_model_(hybrid_model), runtime_param_(hybrid_model.root_runtime_param_) {
  104. ge_root_model_ = hybrid_model_.ge_root_model_;
  105. }
  106. Status HybridModelBuilder::Build() {
  107. GE_CHK_STATUS_RET(ValidateParams(), "Failed to validate GeRootModel");
  108. hybrid_model_.model_name_ = ge_root_model_->GetRootGraph()->GetName();
  109. GELOGI("[%s] Start to build hybrid model.", GetGraphName());
  110. GE_CHK_STATUS_RET(InitRuntimeParams(), "[%s] Failed to InitRuntimeParams", GetGraphName());
  111. GE_CHK_STATUS_RET(RecoverGraphUnknownFlag(), "[%s] Failed to RecoverGraphUnknownFlag", GetGraphName());
  112. GE_CHK_STATUS_RET(IndexSpecialNodes(), "[%s] Failed to index nodes", GetGraphName());
  113. GE_CHK_STATUS_RET(IndexTaskDefs(), "[%s] Failed to index task defs", GetGraphName());
  114. GE_CHK_STATUS_RET(LoadGraph(), "[%s] Failed to load graph", GetGraphName());
  115. GE_CHK_STATUS_RET(AssignUninitializedConstantOps(), "[%s] Failed to assign uninitialized constants", GetGraphName());
  116. GE_CHK_STATUS_RET(TransAllVarData(), "[%s] Failed to trans all var data", GetGraphName());
  117. GE_CHK_STATUS_RET(CopyVarData(), "[%s] Failed to copy var data", GetGraphName());
  118. GE_CHK_STATUS_RET(InitModelMem(), "[%s] Failed to init memory", GetGraphName());
  119. GE_CHK_STATUS_RET(InitWeights(), "[%s] Failed to init weights", GetGraphName());
  120. GE_CHK_STATUS_RET(InitConstantOps(), "[%s] Failed to init constant op", GetGraphName());
  121. GE_CHK_STATUS_RET(InitVariableTensors(), "[%s] Failed to init variables", GetGraphName());
  122. GE_CHK_STATUS_RET(LoadTasks(), "[%s] Failed to load tasks", GetGraphName());
  123. GELOGI("[%s] Done building hybrid model successfully.", GetGraphName());
  124. return SUCCESS;
  125. }
  126. Status HybridModelBuilder::ValidateParams() {
  127. GE_CHECK_NOTNULL(ge_root_model_);
  128. GE_CHECK_NOTNULL(ge_root_model_->GetRootGraph());
  129. return SUCCESS;
  130. }
  131. Status HybridModelBuilder::BuildNodeItem(const NodePtr &node, NodeItem &node_item) {
  132. auto op_desc = node->GetOpDesc();
  133. vector<string> dependencies = node->GetOpDesc()->GetOpInferDepends();
  134. GE_CHK_STATUS_RET(ParseDependentInputNodes(node_item, dependencies),
  135. "[%s] Failed to parse node dependencies.",
  136. node_item.NodeName().c_str());
  137. node_item.outputs.resize(node_item.num_outputs);
  138. for (int i = 0; i < node_item.num_outputs; ++i) {
  139. auto out_data_anchor = node->GetOutDataAnchor(i);
  140. if (out_data_anchor == nullptr) {
  141. GELOGE(INTERNAL_ERROR, "out anchor[%d] of node %s is nullptr", i, node->GetName().c_str());
  142. return INTERNAL_ERROR;
  143. }
  144. for (auto &dst_in_anchor: out_data_anchor->GetPeerInDataAnchors()) {
  145. auto dst_node = dst_in_anchor->GetOwnerNode();
  146. if (dst_node == nullptr) {
  147. GELOGW("dst node is nullptr. out anchor = %d", out_data_anchor->GetIdx());
  148. continue;
  149. }
  150. NodeItem *dst_node_item = nullptr;
  151. GE_CHK_STATUS_RET(GetOrCreateNodeItem(dst_node, &dst_node_item),
  152. "[%s] Failed to get or create node item.",
  153. dst_node->GetName().c_str());
  154. int canonical_index;
  155. GE_CHK_STATUS_RET(dst_node_item->GetCanonicalInputIndex(dst_in_anchor->GetIdx(), canonical_index),
  156. "[%s] Failed to canonical input index",
  157. dst_node->GetName().c_str());
  158. node_item.outputs[i].emplace_back(canonical_index, dst_node_item);
  159. }
  160. }
  161. GE_CHK_STATUS_RET_NOLOG(ResolveRefIo(node_item));
  162. return SUCCESS;
  163. }
  164. Status HybridModelBuilder::ResolveRefIo(NodeItem &node_item) {
  165. bool is_ref = false;
  166. auto &op_desc = *node_item.op_desc;
  167. (void) AttrUtils::GetBool(op_desc, ATTR_NAME_REFERENCE, is_ref);
  168. if (!is_ref) {
  169. return SUCCESS;
  170. }
  171. auto inputs = op_desc.GetAllInputName();
  172. auto outputs = op_desc.GetAllOutputName();
  173. for (auto &output : outputs) {
  174. for (auto &input : inputs) {
  175. if (input.first == output.first) {
  176. int input_idx;
  177. GE_CHK_STATUS_RET_NOLOG(node_item.GetCanonicalInputIndex(input.second, input_idx));
  178. auto output_idx = static_cast<int>(output.second);
  179. node_item.reuse_inputs[output_idx] = input_idx;
  180. GELOGD("[%s] Output[%d] reuse input[%d]", node_item.NodeName().c_str(), output_idx, input_idx);
  181. }
  182. }
  183. }
  184. return SUCCESS;
  185. }
  186. Status HybridModelBuilder::GetOrCreateNodeItem(const NodePtr &node, NodeItem **node_item) {
  187. auto &node_items = hybrid_model_.node_items_;
  188. auto it = node_items.find(node);
  189. if (it != node_items.end()) {
  190. *node_item = it->second.get();
  191. return SUCCESS;
  192. }
  193. std::unique_ptr<NodeItem> new_node;
  194. GE_CHK_STATUS_RET(NodeItem::Create(node, new_node), "Failed to create node item");
  195. GE_CHK_STATUS_RET_NOLOG(NodeExecutorManager::GetInstance().GetExecutor(*node, &new_node->node_executor));
  196. // we do not need L2 Buffer
  197. const char *const kIsFirstNode = "is_first_node";
  198. const char *const kIsLastNode = "is_last_node";
  199. (void) AttrUtils::SetBool(new_node->op_desc, kIsFirstNode, false);
  200. (void) AttrUtils::SetBool(new_node->op_desc, kIsLastNode, false);
  201. new_node->node_id = node_index;
  202. new_node->op_desc->SetId(node_index);
  203. node_index += 1;
  204. NodeExecutorManager::ExecutorType executor_type = NodeExecutorManager::GetInstance().ResolveExecutorType(*node);
  205. new_node->is_profiling_report = (executor_type == NodeExecutorManager::ExecutorType::AICORE) ||
  206. (executor_type == NodeExecutorManager::ExecutorType::AICPU_TF) ||
  207. (executor_type == NodeExecutorManager::ExecutorType::AICPU_CUSTOM);
  208. *node_item = new_node.get();
  209. node_items[node] = std::move(new_node);
  210. return SUCCESS;
  211. }
  212. Status HybridModelBuilder::ParseDependentInputNodes(NodeItem &node_item, const std::vector<string> &dependencies) {
  213. std::set<NodePtr> dependent_input_nodes;
  214. auto &ge_node = node_item.node;
  215. bool is_hccl_op =
  216. NodeExecutorManager::GetInstance().ResolveExecutorType(*ge_node) == NodeExecutorManager::ExecutorType::HCCL;
  217. // The input tensors become valid after computation is done for parent nodes of type DEPEND_COMPUTE.
  218. // Wait for these parent nodes before execution.
  219. for (const auto &in_anchor : ge_node->GetAllInDataAnchors()) {
  220. const auto &peer_anchor = in_anchor->GetPeerOutAnchor();
  221. if (peer_anchor == nullptr) {
  222. GELOGD("[%s] Input[%d] do not have peer anchor", node_item.NodeName().c_str(), in_anchor->GetIdx());
  223. continue;
  224. }
  225. auto src_node = peer_anchor->GetOwnerNode();
  226. GE_CHECK_NOTNULL(src_node);
  227. auto src_node_item = MutableNodeItem(src_node);
  228. GE_CHECK_NOTNULL(src_node_item);
  229. if (is_hccl_op) {
  230. GELOGD("[%s] Add input data dependent node [%s] due to engine type is HCCL",
  231. node_item.NodeName().c_str(),
  232. src_node_item->NodeName().c_str());
  233. src_node_item->has_observer = true;
  234. node_item.dependents_for_execution.emplace_back(src_node);
  235. } else if (src_node_item->shape_inference_type == DEPEND_COMPUTE) {
  236. GELOGD("[%s] Add input data dependent node [%s] due to inference type = DEPEND_COMPUTE",
  237. node_item.NodeName().c_str(),
  238. src_node_item->NodeName().c_str());
  239. src_node_item->has_observer = true;
  240. node_item.dependents_for_execution.emplace_back(src_node);
  241. }
  242. if (src_node_item->shape_inference_type == DEPEND_SHAPE_RANGE) {
  243. GELOGD("[%s] Add input shape dependent node [%s] due to inference type = DEPEND_SHAPE_RANGE",
  244. node_item.NodeName().c_str(),
  245. src_node_item->NodeName().c_str());
  246. src_node_item->has_observer = true;
  247. dependent_input_nodes.emplace(src_node);
  248. }
  249. }
  250. // cond or branch need to be prepared before the execution of IF or CASE
  251. if (node_item.node_type == IF || node_item.node_type == STATELESSIF || node_item.node_type == CASE) {
  252. const auto &in_anchor = ge_node->GetInDataAnchor(0);
  253. GE_CHECK_NOTNULL(in_anchor);
  254. const auto &peer_anchor = in_anchor->GetPeerOutAnchor();
  255. GE_CHECK_NOTNULL(peer_anchor);
  256. auto src_node = peer_anchor->GetOwnerNode();
  257. GE_CHECK_NOTNULL(src_node);
  258. auto src_node_item = MutableNodeItem(src_node);
  259. GE_CHECK_NOTNULL(src_node_item);
  260. src_node_item->has_observer = true;
  261. node_item.dependents_for_execution.emplace_back(src_node);
  262. GELOGD("[%s] Dependent added from %s for control op's cond/branch",
  263. node_item.NodeName().c_str(),
  264. src_node_item->NodeName().c_str());
  265. }
  266. for (const auto &input_name : dependencies) {
  267. int input_index = node_item.op_desc->GetInputIndexByName(input_name);
  268. if (input_index < 0) {
  269. GELOGE(INTERNAL_ERROR,
  270. "[%s] Failed to get input index by name: %s",
  271. node_item.NodeName().c_str(),
  272. input_name.c_str());
  273. return INTERNAL_ERROR;
  274. }
  275. const auto &in_anchor = ge_node->GetInDataAnchor(input_index);
  276. GE_CHECK_NOTNULL(in_anchor);
  277. const auto &peer_out_anchor = in_anchor->GetPeerOutAnchor();
  278. GE_CHECK_NOTNULL(peer_out_anchor);
  279. const auto &src_node = peer_out_anchor->GetOwnerNode();
  280. GE_CHECK_NOTNULL(src_node);
  281. auto src_node_item = MutableNodeItem(src_node);
  282. src_node_item->to_const_output_id_list.emplace(peer_out_anchor->GetIdx());
  283. src_node_item->has_observer = true;
  284. dependent_input_nodes.emplace(src_node);
  285. GELOGD("[%s] Dependent added from output of [%s:%d]",
  286. node_item.NodeName().c_str(),
  287. src_node_item->NodeName().c_str(),
  288. peer_out_anchor->GetIdx());
  289. }
  290. for (const auto &dep_node : dependent_input_nodes) {
  291. node_item.dependents_for_shape_inference.emplace_back(dep_node);
  292. }
  293. GE_CHK_STATUS_RET(ParseDependentForFusedSubgraph(node_item));
  294. return SUCCESS;
  295. }
  296. Status HybridModelBuilder::ParseDependentForFusedSubgraph(NodeItem &node_item) {
  297. if (node_item.fused_subgraph == nullptr) {
  298. return SUCCESS;
  299. }
  300. std::set<OpDesc *> data_ops;
  301. GE_CHK_STATUS_RET_NOLOG(CollectDependenciesForFusedGraph(node_item, data_ops));
  302. for (auto &op_desc : data_ops) {
  303. uint32_t parent_index = 0;
  304. if (!AttrUtils::GetInt(*op_desc, ATTR_NAME_PARENT_NODE_INDEX, parent_index)) {
  305. GELOGE(INTERNAL_ERROR,
  306. "[%s] Failed to get attr [%s]",
  307. op_desc->GetName().c_str(),
  308. ATTR_NAME_PARENT_NODE_INDEX.c_str());
  309. return INTERNAL_ERROR;
  310. }
  311. const auto &in_anchor = node_item.node->GetInDataAnchor(parent_index);
  312. GE_CHECK_NOTNULL(in_anchor);
  313. const auto &peer_out_anchor = in_anchor->GetPeerOutAnchor();
  314. GE_CHECK_NOTNULL(peer_out_anchor);
  315. const auto &src_node = peer_out_anchor->GetOwnerNode();
  316. GE_CHECK_NOTNULL(src_node);
  317. NodeItem *src_node_item = nullptr;
  318. GE_CHK_STATUS_RET_NOLOG(GetOrCreateNodeItem(src_node, &src_node_item));
  319. op_desc->SetId(src_node_item->op_desc->GetId());
  320. GELOGD("[%s::%s] Node id was set to that of outer src node's, src_node = %s",
  321. node_item.NodeName().c_str(),
  322. op_desc->GetName().c_str(),
  323. src_node_item->NodeName().c_str());
  324. src_node_item->has_observer = true;
  325. src_node_item->to_const_output_id_list.emplace(peer_out_anchor->GetIdx());
  326. auto &depends = node_item.dependents_for_shape_inference;
  327. if (std::find(depends.begin(), depends.end(), src_node) == depends.end()) {
  328. depends.emplace_back(src_node);
  329. GELOGD("[%s] Dependent added from output of [%s:%d]",
  330. node_item.NodeName().c_str(),
  331. src_node_item->NodeName().c_str(),
  332. peer_out_anchor->GetIdx());
  333. }
  334. }
  335. return SUCCESS;
  336. }
  337. Status HybridModelBuilder::UpdateAnchorStatus(const NodePtr &node) {
  338. if (NodeUtils::SetAllAnchorStatus(node) != GRAPH_SUCCESS) {
  339. GELOGE(INTERNAL_ERROR, "[%s] NodeUtils::SetAllAnchorStatus failed.", node->GetName().c_str());
  340. return INTERNAL_ERROR;
  341. }
  342. for (auto &anchor : node->GetAllInDataAnchors()) {
  343. auto peer_anchor = anchor->GetPeerOutAnchor();
  344. if (peer_anchor == nullptr) {
  345. if (AnchorUtils::SetStatus(anchor, ANCHOR_SUSPEND) != GRAPH_SUCCESS) {
  346. GELOGE(INTERNAL_ERROR, "[%s] AnchorUtils::SetStatus failed.", node->GetName().c_str());
  347. return INTERNAL_ERROR;
  348. }
  349. } else if (peer_anchor->GetOwnerNode()->GetType() == CONSTANT) {
  350. if (AnchorUtils::SetStatus(anchor, ANCHOR_CONST) != GRAPH_SUCCESS) {
  351. GELOGE(INTERNAL_ERROR, "[%s] AnchorUtils::SetStatus failed.", node->GetName().c_str());
  352. return INTERNAL_ERROR;
  353. }
  354. } else {
  355. if (AnchorUtils::SetStatus(anchor, ANCHOR_DATA) != GRAPH_SUCCESS) {
  356. GELOGE(INTERNAL_ERROR, "[%s] AnchorUtils::SetStatus failed.", node->GetName().c_str());
  357. return INTERNAL_ERROR;
  358. }
  359. }
  360. }
  361. return SUCCESS;
  362. }
  363. Status HybridModelBuilder::DoUnlinkDataAnchors(const OutDataAnchorPtr &out_data_anchor,
  364. const InDataAnchorPtr &in_data_anchor) {
  365. GE_CHK_GRAPH_STATUS_RET(out_data_anchor->Unlink(in_data_anchor), "Failed to unlink %s:%d from %s:%d",
  366. out_data_anchor->GetOwnerNode()->GetName().c_str(),
  367. out_data_anchor->GetIdx(),
  368. in_data_anchor->GetOwnerNode()->GetName().c_str(),
  369. in_data_anchor->GetIdx());
  370. GELOGD("Succeeded in unlinking %s:%d from %s:%d",
  371. out_data_anchor->GetOwnerNode()->GetName().c_str(),
  372. out_data_anchor->GetIdx(),
  373. in_data_anchor->GetOwnerNode()->GetName().c_str(),
  374. in_data_anchor->GetIdx());
  375. return SUCCESS;
  376. }
  377. Status HybridModelBuilder::DoLinkDataAnchors(OutDataAnchorPtr &out_data_anchor, InDataAnchorPtr &in_data_anchor) {
  378. GE_CHK_GRAPH_STATUS_RET(out_data_anchor->LinkTo(in_data_anchor), "Failed to link %s:%d to %s:%d",
  379. out_data_anchor->GetOwnerNode()->GetName().c_str(),
  380. out_data_anchor->GetIdx(),
  381. in_data_anchor->GetOwnerNode()->GetName().c_str(),
  382. in_data_anchor->GetIdx());
  383. GELOGD("Succeeded in linking %s:%d to %s:%d",
  384. out_data_anchor->GetOwnerNode()->GetName().c_str(),
  385. out_data_anchor->GetIdx(),
  386. in_data_anchor->GetOwnerNode()->GetName().c_str(),
  387. in_data_anchor->GetIdx());
  388. return SUCCESS;
  389. }
  390. Status HybridModelBuilder::MergeInputNodes(ComputeGraph &graph) {
  391. const auto &wrapped_node = graph.GetParentNode();
  392. std::set<NodePtr> root_nodes;
  393. for (const auto &node : graph.GetDirectNode()) {
  394. GE_CHECK_NOTNULL(node);
  395. if (node->GetType() != DATA_TYPE) {
  396. if (node->GetInDataNodes().empty()) {
  397. root_nodes.emplace(node);
  398. }
  399. continue;
  400. }
  401. auto data_op_desc = node->GetOpDesc();
  402. GE_CHECK_NOTNULL(data_op_desc);
  403. uint32_t parent_index = 0;
  404. if (!AttrUtils::GetInt(data_op_desc, ATTR_NAME_PARENT_NODE_INDEX, parent_index)) {
  405. GELOGE(FAILED,
  406. "[%s] Failed to get attr [%s]",
  407. data_op_desc->GetName().c_str(),
  408. ATTR_NAME_PARENT_NODE_INDEX.c_str());
  409. return FAILED;
  410. }
  411. auto wrapped_node_in_anchor = wrapped_node->GetInDataAnchor(parent_index);
  412. GE_CHECK_NOTNULL(wrapped_node_in_anchor);
  413. auto src_out_anchor = wrapped_node_in_anchor->GetPeerOutAnchor();
  414. if (src_out_anchor == nullptr || src_out_anchor->GetOwnerNode() == nullptr) {
  415. continue;
  416. }
  417. wrapped_node_in_anchor->UnlinkAll();
  418. // link src to outputs of DataNode
  419. for (auto &out_data_anchor : node->GetAllOutDataAnchors()) {
  420. GE_CHECK_NOTNULL(out_data_anchor);
  421. for (auto &peer_in_data_anchor : out_data_anchor->GetPeerInDataAnchors()) {
  422. auto dst_node = peer_in_data_anchor->GetOwnerNode();
  423. GE_CHECK_NOTNULL(dst_node);
  424. root_nodes.emplace(dst_node);
  425. GE_CHK_STATUS_RET_NOLOG(DoUnlinkDataAnchors(out_data_anchor, peer_in_data_anchor));
  426. GE_CHK_STATUS_RET_NOLOG(DoLinkDataAnchors(src_out_anchor, peer_in_data_anchor));
  427. }
  428. }
  429. }
  430. // transfer in control edges to all root nodes
  431. for (auto &root_node : root_nodes) {
  432. auto in_nodes = root_node->GetInAllNodes();
  433. std::set<NodePtr> in_node_set(in_nodes.begin(), in_nodes.end());
  434. for (auto &in_control_node : wrapped_node->GetInControlNodes()) {
  435. if (in_node_set.count(in_control_node) == 0) {
  436. GELOGD("[%s] Restore control edge to [%s]", in_control_node->GetName().c_str(), root_node->GetName().c_str());
  437. GE_CHECK_NOTNULL(in_control_node->GetOutControlAnchor());
  438. (void) in_control_node->GetOutControlAnchor()->LinkTo(root_node->GetInControlAnchor());
  439. }
  440. }
  441. }
  442. wrapped_node->GetInControlAnchor()->UnlinkAll();
  443. return SUCCESS;
  444. }
  445. Status HybridModelBuilder::MergeNetOutputNode(ComputeGraph &graph) {
  446. const auto &parent_node = graph.GetParentNode();
  447. const NodePtr &net_output_node = graph.FindFirstNodeMatchType(NETOUTPUT);
  448. if (net_output_node == nullptr) {
  449. GELOGD("Graph has no netoutput no need to merge.");
  450. return SUCCESS;
  451. }
  452. const auto &net_output_desc = net_output_node->GetOpDesc();
  453. GE_CHECK_NOTNULL(net_output_desc);
  454. auto all_in_nodes = net_output_node->GetInAllNodes();
  455. auto all_out_nodes = parent_node->GetOutAllNodes();
  456. net_output_node->GetInControlAnchor()->UnlinkAll();
  457. parent_node->GetOutControlAnchor()->UnlinkAll();
  458. for (const auto &in_data_anchor : net_output_node->GetAllInDataAnchors()) {
  459. auto src_out_anchor = in_data_anchor->GetPeerOutAnchor();
  460. GE_CHECK_NOTNULL(src_out_anchor);
  461. GE_CHECK_NOTNULL(src_out_anchor->GetOwnerNode());
  462. GE_CHK_STATUS_RET_NOLOG(DoUnlinkDataAnchors(src_out_anchor, in_data_anchor));
  463. auto index = in_data_anchor->GetIdx();
  464. auto input_desc = net_output_desc->MutableInputDesc(index);
  465. if (input_desc == nullptr) {
  466. GELOGE(INTERNAL_ERROR, "[%s] Failed to get input desc[%d]", net_output_desc->GetName().c_str(), index);
  467. return INTERNAL_ERROR;
  468. }
  469. uint32_t parent_index = 0;
  470. if (!AttrUtils::GetInt(input_desc, ATTR_NAME_PARENT_NODE_INDEX, parent_index)) {
  471. GELOGW("SubGraph: %s NetOutput input tensor %d, attr %s not found.",
  472. graph.GetName().c_str(), index, ATTR_NAME_PARENT_NODE_INDEX.c_str());
  473. continue;
  474. }
  475. const OutDataAnchorPtr &parent_out_anchor = parent_node->GetOutDataAnchor(parent_index);
  476. GE_CHECK_NOTNULL(parent_out_anchor);
  477. for (InDataAnchorPtr &dst_in_anchor : parent_out_anchor->GetPeerInDataAnchors()) {
  478. if (dst_in_anchor == nullptr) {
  479. continue;
  480. }
  481. GE_CHECK_NOTNULL(dst_in_anchor->GetOwnerNode());
  482. GE_CHK_STATUS_RET_NOLOG(DoUnlinkDataAnchors(parent_out_anchor, dst_in_anchor));
  483. GE_CHK_STATUS_RET_NOLOG(DoLinkDataAnchors(src_out_anchor, dst_in_anchor));
  484. }
  485. }
  486. // transfer out control edges
  487. std::set<NodePtr> in_node_set(all_in_nodes.begin(), all_in_nodes.end());
  488. std::set<NodePtr> out_node_set(all_out_nodes.begin(), all_out_nodes.end());
  489. for (auto &src_node : in_node_set) {
  490. GELOGD("[%s] process in node.", src_node->GetName().c_str());
  491. auto out_nodes = src_node->GetOutAllNodes();
  492. std::set<NodePtr> node_set(out_nodes.begin(), out_nodes.end());
  493. for (auto &dst_node : out_node_set) {
  494. if (node_set.count(dst_node) == 0) {
  495. src_node->GetOutControlAnchor()->LinkTo(dst_node->GetInControlAnchor());
  496. GELOGD("[%s] Restore control edge to [%s]", src_node->GetName().c_str(), dst_node->GetName().c_str());
  497. }
  498. }
  499. }
  500. return SUCCESS;
  501. }
  502. Status HybridModelBuilder::UnfoldSubgraphs(ComputeGraph &root_graph, ComputeGraphPtr &merged_graph) {
  503. merged_graph = MakeShared<ComputeGraph>("MergedGraph");
  504. for (const auto &node : root_graph.GetDirectNode()) {
  505. GE_CHECK_NOTNULL(node);
  506. auto op_desc = node->GetOpDesc();
  507. GE_CHECK_NOTNULL(op_desc);
  508. const auto &op_type = node->GetType();
  509. if (op_type != PARTITIONEDCALL) {
  510. merged_graph->AddNode(node);
  511. GELOGD("[%s] Node added to merged graph.", op_desc->GetName().c_str());
  512. continue;
  513. }
  514. auto subgraph = NodeUtils::GetSubgraph(*node, kSubgraphIndex);
  515. GE_CHECK_NOTNULL(subgraph);
  516. bool is_unknown_shape = subgraph->GetGraphUnknownFlag();
  517. if (!is_unknown_shape) {
  518. merged_graph->AddNode(node);
  519. GELOGD("[%s] Known shape partitioned call added to merged graph.", op_desc->GetName().c_str());
  520. continue;
  521. }
  522. GE_CHK_GRAPH_STATUS_RET(UnfoldSubgraph(root_graph, *merged_graph, *subgraph),
  523. "[%s] Failed to merge subgraph.",
  524. subgraph->GetName().c_str());
  525. }
  526. // invoke before adding subgraphs. in case modify node id in known-shaped subgraphs.
  527. GE_CHK_GRAPH_STATUS_RET(merged_graph->TopologicalSorting(), "Failed to invoke TopologicalSorting on merged graph.");
  528. for (auto &remained_subgraph : root_graph.GetAllSubgraphs()) {
  529. GELOGD("Adding subgraph [%s] to merged-graph.", remained_subgraph->GetName().c_str());
  530. GE_CHK_GRAPH_STATUS_RET(merged_graph->AddSubgraph(remained_subgraph),
  531. "Failed to add subgraph [%s]",
  532. remained_subgraph->GetName().c_str());
  533. }
  534. return SUCCESS;
  535. }
  536. Status HybridModelBuilder::UnfoldSubgraph(ComputeGraph &root_graph,
  537. ComputeGraph &parent_graph,
  538. ComputeGraph &sub_graph) {
  539. auto parent_node = sub_graph.GetParentNode();
  540. GE_CHECK_NOTNULL(parent_node);
  541. GE_CHK_STATUS_RET(MergeInputNodes(sub_graph),
  542. "[%s] Failed to merge data nodes for subgraph",
  543. sub_graph.GetName().c_str());
  544. GE_CHK_STATUS_RET(MergeNetOutputNode(sub_graph),
  545. "[%s] Failed to merge net output nodes for subgraph",
  546. sub_graph.GetName().c_str());
  547. GELOGD("[%s] Done merging subgraph inputs and outputs successfully.", sub_graph.GetName().c_str());
  548. for (auto &sub_node : sub_graph.GetDirectNode()) {
  549. auto sub_op_type = sub_node->GetType();
  550. if (sub_op_type == DATA_TYPE || sub_op_type == NETOUTPUT) {
  551. continue;
  552. }
  553. if (sub_op_type == PARTITIONEDCALL) {
  554. auto sub_sub_graph = NodeUtils::GetSubgraph(*sub_node, kSubgraphIndex);
  555. GE_CHECK_NOTNULL(sub_sub_graph);
  556. if (sub_sub_graph->GetGraphUnknownFlag()) {
  557. GE_CHK_STATUS_RET(UnfoldSubgraph(root_graph, parent_graph, *sub_sub_graph),
  558. "[%s] Failed to merge subgraph",
  559. sub_sub_graph->GetName().c_str());
  560. continue;
  561. }
  562. }
  563. parent_graph.AddNode(sub_node);
  564. GELOGD("[%s::%s] added to parent graph: [%s].",
  565. sub_graph.GetName().c_str(),
  566. sub_node->GetName().c_str(),
  567. parent_graph.GetName().c_str());
  568. }
  569. GELOGD("[%s] Done merging subgraph. remove it from root graph.", sub_graph.GetName().c_str());
  570. root_graph.RemoveSubgraph(sub_graph.GetName());
  571. return SUCCESS;
  572. }
  573. Status HybridModelBuilder::BuildOutputMapping(GraphItem &graph_item,
  574. const NodeItem &node_item,
  575. bool is_root_graph) {
  576. auto output_size = node_item.num_inputs;
  577. graph_item.output_edges_.resize(output_size);
  578. for (auto &in_data_anchor : node_item.node->GetAllInDataAnchors()) {
  579. auto peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  580. GE_CHECK_NOTNULL(peer_out_anchor);
  581. auto src_node = peer_out_anchor->GetOwnerNode();
  582. GE_CHECK_NOTNULL(src_node);
  583. auto src_node_item = GetNodeItem(src_node);
  584. GE_CHECK_NOTNULL(src_node_item);
  585. auto output_idx = in_data_anchor->GetIdx();
  586. auto output_offset = src_node_item->output_start + peer_out_anchor->GetIdx();
  587. GELOGI("Output[%d], node = %s, output_index = %d, output_offset = %d ",
  588. output_idx,
  589. src_node_item->NodeName().c_str(),
  590. peer_out_anchor->GetIdx(),
  591. output_offset);
  592. GE_CHECK_LE(output_idx, output_size - 1);
  593. graph_item.output_edges_[output_idx] = {src_node_item, peer_out_anchor->GetIdx()};
  594. }
  595. if (!is_root_graph) {
  596. for (uint32_t i = 0; i < static_cast<uint32_t>(output_size); ++i) {
  597. uint32_t p_index = i;
  598. // Net output of Subgraph of while do not have parent index
  599. if (AttrUtils::GetInt(node_item.op_desc->GetInputDesc(i), ATTR_NAME_PARENT_NODE_INDEX, p_index)) {
  600. GELOGD("[%s] Parent index not set for input[%u].", node_item.NodeName().c_str(), i);
  601. }
  602. graph_item.output_index_mapping_.emplace_back(p_index);
  603. }
  604. }
  605. return SUCCESS;
  606. }
  607. Status HybridModelBuilder::LoadGraph() {
  608. auto root_graph = ge_root_model_->GetRootGraph();
  609. if (!GetContext().GetHostExecFlag()) {
  610. std::shared_ptr<ComputeGraph> merged_graph;
  611. GELOGI("Before merging subgraphs DirectNodesSize = %zu, GetAllNodesSize = %zu",
  612. root_graph->GetDirectNodesSize(),
  613. root_graph->GetAllNodesSize());
  614. GE_CHK_GRAPH_STATUS_RET(UnfoldSubgraphs(*root_graph, merged_graph), "Failed to unfold subgraphs.");
  615. root_graph = std::move(merged_graph);
  616. GELOGI("After merging subgraphs DirectNodesSize = %zu, GetAllNodesSize = %zu",
  617. root_graph->GetDirectNodesSize(),
  618. root_graph->GetAllNodesSize());
  619. GE_DUMP(root_graph, "hybrid_merged_graph");
  620. }
  621. GE_CHK_STATUS_RET(LoadDynamicSubgraph(*root_graph, true), "Failed to load root graph.");
  622. GELOGD("Done loading root graph successfully.");
  623. for (auto &sub_graph : root_graph->GetAllSubgraphs()) {
  624. GE_CHECK_NOTNULL(sub_graph);
  625. GELOGD("Start to load subgraph [%s]", sub_graph->GetName().c_str());
  626. auto parent_node = sub_graph->GetParentNode();
  627. GE_CHECK_NOTNULL(parent_node);
  628. auto parent_node_item = MutableNodeItem(parent_node);
  629. // parent node is in another known subgraph
  630. if (parent_node_item == nullptr) {
  631. GELOGD("[%s] Subgraph is in another known shaped subgraph, skip it.", sub_graph->GetName().c_str());
  632. continue;
  633. }
  634. if (sub_graph->GetGraphUnknownFlag()) {
  635. GE_CHK_STATUS_RET(LoadDynamicSubgraph(*sub_graph, false),
  636. "Failed to load subgraph: [%s]",
  637. sub_graph->GetName().c_str());
  638. } else {
  639. GE_CHK_STATUS_RET(IdentifyVariableOutputs(*parent_node_item),
  640. "[%s] Failed to identify ref outputs.",
  641. parent_node_item->NodeName().c_str());
  642. GE_CHK_STATUS_RET(IdentifySameInputs(*parent_node_item),
  643. "[%s] Failed to identify same outputs.",
  644. parent_node_item->NodeName().c_str());
  645. // if parent is function control op. need add a virtual partitioned call
  646. if (parent_node_item->IsControlOp()) {
  647. GE_CHK_STATUS_RET(LoadKnownShapedSubgraph(*sub_graph, parent_node_item),
  648. "Failed to load function control op subgraph [%s]",
  649. sub_graph->GetName().c_str());
  650. }
  651. }
  652. }
  653. GELOGI("Done loading all subgraphs successfully.");
  654. return SUCCESS;
  655. }
  656. const NodeItem *HybridModelBuilder::GetNodeItem(const NodePtr &node) const {
  657. return hybrid_model_.GetNodeItem(node);
  658. }
  659. NodeItem *HybridModelBuilder::MutableNodeItem(const NodePtr &node) {
  660. return hybrid_model_.MutableNodeItem(node);
  661. }
  662. Status HybridModelBuilder::VarNodeToTensor(const NodePtr &var_node, std::unique_ptr<TensorValue> &tensor) {
  663. string var_name = var_node->GetName();
  664. auto tensor_desc = var_node->GetOpDesc()->MutableOutputDesc(0);
  665. uint8_t *var_logic = nullptr;
  666. GE_CHK_STATUS_RET(var_manager_->GetVarAddr(var_name, *tensor_desc, &var_logic),
  667. "Failed to get var addr. var_name = %s, session_id = %ld",
  668. var_name.c_str(),
  669. hybrid_model_.GetSessionId());
  670. uint8_t *dev_mem = var_manager_->GetVarMemoryAddr(var_logic, RT_MEMORY_HBM);
  671. if (dev_mem == nullptr) {
  672. GELOGE(INTERNAL_ERROR,
  673. "Failed to copy var %s from device, cant not get "
  674. "var addr from logic addr %p",
  675. var_node->GetName().c_str(), var_logic);
  676. return INTERNAL_ERROR;
  677. }
  678. int64_t var_size = CalcVarSizeInBytes(*tensor_desc);
  679. // var size is only for checking, will not allocate any memory by it
  680. tensor.reset(new(std::nothrow)TensorValue(dev_mem, static_cast<size_t>(var_size)));
  681. GE_CHECK_NOTNULL(tensor);
  682. return SUCCESS;
  683. }
  684. Status HybridModelBuilder::HandleDtString(const GeTensor &tensor, void *var_addr) {
  685. auto desc = tensor.GetTensorDesc();
  686. if (desc.GetDataType() == DT_STRING) {
  687. GeShape tensor_shape = desc.GetShape();
  688. /// if tensor is a scaler, it's shape size if zero, according ge_tensor.cc.
  689. /// the logic of GetShapeSize is wrong, the scaler tensor's GetShapeSize is zero
  690. /// and that of unknown shape is zero too.
  691. /// unknown shape will not appear here, so we can use zero judge a tensor is scalar or not
  692. int64_t elem_num = tensor_shape.GetShapeSize();
  693. if (elem_num == 0 && tensor_shape.GetDims().empty()) {
  694. elem_num = 1;
  695. }
  696. auto &mutable_tensor = const_cast<GeTensor &>(tensor);
  697. uint64_t *buff = reinterpret_cast<uint64_t *>(mutable_tensor.MutableData().data());
  698. GE_CHK_BOOL_RET_STATUS(ge::CheckInt64Uint32MulOverflow(elem_num, kBytes) == SUCCESS, FAILED,
  699. "Shape size is invalid");
  700. auto offset = static_cast<uint64_t>(elem_num * kBytes);
  701. auto hbm_raw_data_base_addr =
  702. static_cast<uint64_t>(reinterpret_cast<uintptr_t>(var_addr) + offset);
  703. for (int64_t i = elem_num - 1; i >= 0; --i) {
  704. buff[i] = hbm_raw_data_base_addr + (buff[i] - buff[0]);
  705. }
  706. }
  707. return SUCCESS;
  708. }
  709. Status HybridModelBuilder::AssignUninitializedConstantOps() {
  710. if (GetContext().GetHostExecFlag()) {
  711. GELOGI("no need to assign when exec on host.");
  712. return SUCCESS;
  713. }
  714. for (auto &it : hybrid_model_.constant_op_nodes_) {
  715. const string &var_name = it.first;
  716. const NodePtr &var_node = it.second;
  717. auto tensor_desc = var_node->GetOpDesc()->MutableOutputDesc(0);
  718. if (!var_manager_->IsVarExist(var_name, *tensor_desc)) {
  719. // allocate constant
  720. GELOGD("[%s] Constant not allocated during graph building. now allocate it.", var_name.c_str());
  721. GE_CHK_STATUS_RET(var_manager_->AssignVarMem(var_name, *tensor_desc, RT_MEMORY_HBM));
  722. GE_CHK_STATUS_RET(var_manager_->SetAllocatedGraphId(var_name, runtime_param_.graph_id));
  723. }
  724. }
  725. for (auto &it : hybrid_model_.device_variable_nodes_) {
  726. const string &var_name = it.first;
  727. const NodePtr &var_node = it.second;
  728. auto tensor_desc = var_node->GetOpDesc()->MutableOutputDesc(0);
  729. if (!var_manager_->IsVarExist(var_name, *tensor_desc)) {
  730. // allocate constant
  731. GELOGD("[%s] Constant not allocated during graph building. now allocate it.", var_name.c_str());
  732. GE_CHK_STATUS_RET(var_manager_->AssignVarMem(var_name, *tensor_desc, RT_MEMORY_HBM));
  733. GE_CHK_STATUS_RET(VarMemAssignUtil::AssignData2Fp32Var(var_node, runtime_param_.session_id))
  734. GE_CHK_STATUS_RET(var_manager_->SetAllocatedGraphId(var_name, runtime_param_.graph_id));
  735. }
  736. }
  737. return SUCCESS;
  738. }
  739. Status HybridModelBuilder::InitConstantOps() {
  740. for (auto &it : hybrid_model_.constant_op_nodes_) {
  741. const string &var_name = it.first;
  742. const NodePtr &var_node = it.second;
  743. auto op_desc = var_node->GetOpDesc();
  744. auto v_weights = ModelUtils::GetWeights(op_desc);
  745. if (v_weights.empty()) {
  746. GELOGE(INTERNAL_ERROR, "[%s] Constant no not have value", var_node->GetName().c_str());
  747. return INTERNAL_ERROR;
  748. }
  749. auto *ge_tensor = const_cast<GeTensor *>(v_weights[0].get());
  750. std::unique_ptr<TensorValue> var_tensor;
  751. if (GetContext().GetHostExecFlag()) {
  752. auto buffer = ge_tensor->MutableData();
  753. GELOGD("Init tensor with host constant. size = %zu", buffer.GetSize());
  754. var_tensor.reset(new(std::nothrow)TensorValue(buffer.GetData(), buffer.GetSize()));
  755. } else {
  756. GE_CHK_STATUS_RET_NOLOG(VarNodeToTensor(var_node, var_tensor));
  757. GELOGD("Init const op tensor. name = %s, size = %ld", var_name.c_str(), var_tensor->GetSize());
  758. var_tensor->SetName("ConstOp_" + var_name);
  759. auto v_output_size = var_tensor->GetSize();
  760. auto v_output_addr = var_tensor->MutableData();
  761. if (ge_tensor->GetData().size() > 0) {
  762. GE_CHK_STATUS_RET_NOLOG(HandleDtString(*ge_tensor, v_output_addr));
  763. GELOGI("[IMAS]InitConstant memcpy graph_%u type[V] name[%s] output[%d] memaddr[%p] mem_size[%zu] datasize[%zu]",
  764. runtime_param_.graph_id, op_desc->GetName().c_str(), 0, v_output_addr, v_output_size,
  765. ge_tensor->GetData().size());
  766. GE_CHK_RT_RET(rtMemcpy(v_output_addr, v_output_size, ge_tensor->GetData().data(), ge_tensor->GetData().size(),
  767. RT_MEMCPY_HOST_TO_DEVICE));
  768. } else {
  769. GELOGI("[%s] Const op has no weight data.", op_desc->GetName().c_str());
  770. }
  771. }
  772. hybrid_model_.variable_tensors_.emplace(var_name, std::move(var_tensor));
  773. }
  774. return SUCCESS;
  775. }
  776. Status HybridModelBuilder::InitVariableTensors() {
  777. for (auto &it : hybrid_model_.device_variable_nodes_) {
  778. string var_name = it.first;
  779. NodePtr &var_node = it.second;
  780. std::unique_ptr<TensorValue> tensor;
  781. GE_CHK_STATUS_RET_NOLOG(VarNodeToTensor(var_node, tensor));
  782. GELOGD("Init variable tensor. name = %s, size = %ld, addr = %p",
  783. var_name.c_str(),
  784. tensor->GetSize(),
  785. tensor->GetData());
  786. tensor->SetName("Var_" + var_name);
  787. hybrid_model_.variable_tensors_.emplace(var_name, std::move(tensor));
  788. }
  789. for (const auto &it : hybrid_model_.host_variable_nodes_) {
  790. auto op_desc = it.second->GetOpDesc();
  791. GE_CHECK_NOTNULL(op_desc);
  792. GeTensorDesc output_tensor = op_desc->GetOutputDesc(0);
  793. int64_t tensor_size = 0;
  794. if (TensorUtils::CalcTensorMemSize(output_tensor.GetShape(), output_tensor.GetFormat(), output_tensor.GetDataType(),
  795. tensor_size) != SUCCESS) {
  796. GELOGE(INTERNAL_ERROR, "Calculate variable size failed, node name:%s", it.first.c_str());
  797. return INTERNAL_ERROR;
  798. }
  799. SharedMemInfo mem_info(it.first, tensor_size);
  800. if (HostMemManager::Instance().MallocSharedMemory(mem_info) != SUCCESS) {
  801. GELOGE(GE_GRAPH_MALLOC_FAILED, "Host variable [%s] malloc failed.", it.first.c_str());
  802. return GE_GRAPH_MALLOC_FAILED;
  803. }
  804. GELOGD("Host variable [%s] malloc success.", it.first.c_str());
  805. std::unique_ptr<TensorValue> tensor(new (std::nothrow) TensorValue(mem_info.host_address, tensor_size));
  806. GE_CHECK_NOTNULL(tensor);
  807. hybrid_model_.variable_tensors_.emplace(it.first, std::move(tensor));
  808. }
  809. return SUCCESS;
  810. }
  811. Status HybridModelBuilder::InitWeights() {
  812. // Train do not have weight. (only got ConstOp)
  813. return SUCCESS;
  814. }
  815. Status HybridModelBuilder::LoadTasks() {
  816. for (auto &it : hybrid_model_.node_items_) {
  817. auto &node_item = it.second;
  818. auto &node_ptr = node_item->node;
  819. if (node_item->node_type == NETOUTPUT) {
  820. continue;
  821. }
  822. GELOGD("[%s] Start to build kernel task", node_ptr->GetName().c_str());
  823. auto load_ret = node_item->node_executor->LoadTask(hybrid_model_,
  824. node_ptr,
  825. node_item->kernel_task);
  826. if (load_ret != UNSUPPORTED && load_ret != SUCCESS) {
  827. GELOGE(load_ret, "[%s] Failed to load task", node_ptr->GetName().c_str());
  828. return load_ret;
  829. }
  830. GELOGD("[%s] Done loading task successfully.", node_ptr->GetName().c_str());
  831. }
  832. return SUCCESS;
  833. }
  834. Status HybridModelBuilder::LoadGeModel(ComputeGraph &sub_graph, const GeModelPtr &ge_model) {
  835. auto parent_node = sub_graph.GetParentNode();
  836. GE_CHECK_NOTNULL(parent_node);
  837. auto op_type = parent_node->GetType();
  838. if (IsControlOp(op_type)) {
  839. GELOGD("Set ge_model for control op subgraph: [%s], task_size = %d",
  840. sub_graph.GetName().c_str(),
  841. ge_model->GetModelTaskDefPtr()->task_size());
  842. subgraph_models_.emplace(sub_graph.GetName(), ge_model);
  843. } else {
  844. GELOGD("Set ge_model for subgraph: [%s], task_size = %d",
  845. sub_graph.GetName().c_str(),
  846. ge_model->GetModelTaskDefPtr()->task_size());
  847. hybrid_model_.known_shape_sub_models_.emplace(parent_node, ge_model);
  848. }
  849. return SUCCESS;
  850. }
  851. Status HybridModelBuilder::IndexTaskDefs() {
  852. const auto &root_graph = ge_root_model_->GetRootGraph();
  853. if (SetOutputNameAttr(*root_graph) != SUCCESS) {
  854. GELOGW("Set output name attr failed.");
  855. }
  856. for (auto &it : ge_root_model_->GetSubgraphInstanceNameToModel()) {
  857. auto &name = it.first;
  858. auto &ge_model = it.second;
  859. GE_CHECK_NOTNULL(ge_model);
  860. const auto &sub_graph = root_graph->GetSubgraph(name);
  861. if (sub_graph == nullptr) {
  862. continue;
  863. }
  864. bool is_unknown_shape = sub_graph->GetGraphUnknownFlag();
  865. if (!is_unknown_shape) {
  866. GE_CHK_STATUS_RET_NOLOG(LoadGeModel(*sub_graph, ge_model));
  867. continue;
  868. }
  869. // index task defs
  870. GELOGD("To index tasks for subgraph: %s", name.c_str());
  871. std::unordered_map<int64_t, NodePtr> node_map;
  872. for (const auto &node : sub_graph->GetDirectNode()) {
  873. GE_CHECK_NOTNULL(node);
  874. GE_CHECK_NOTNULL(node->GetOpDesc());
  875. auto node_id = node->GetOpDesc()->GetId();
  876. GELOGD("op_index = %ld, node_name = %s", node_id, node->GetName().c_str());
  877. node_map.emplace(node_id, node);
  878. }
  879. auto tasks = ge_model->GetModelTaskDefPtr()->task();
  880. for (int i = 0; i < tasks.size(); ++i) {
  881. const domi::TaskDef &task_def = tasks[i];
  882. GELOGI("Task id = %d, task type = %d", i, task_def.type());
  883. auto task_type = static_cast<rtModelTaskType_t>(task_def.type());
  884. uint32_t op_index = -1;
  885. if (task_type == RT_MODEL_TASK_KERNEL) {
  886. op_index = task_def.kernel().context().op_index();
  887. } else if (task_type == RT_MODEL_TASK_KERNEL_EX) {
  888. op_index = task_def.kernel_ex().op_index();
  889. } else if (task_type == RT_MODEL_TASK_HCCL) {
  890. op_index = task_def.kernel_hccl().op_index();
  891. } else {
  892. GELOGD("Skip task type: %d", static_cast<int>(task_type));
  893. continue;
  894. }
  895. auto iter = node_map.find(op_index);
  896. if (iter == node_map.end()) {
  897. GELOGE(INTERNAL_ERROR, "Failed to get node by index = %u", op_index);
  898. return INTERNAL_ERROR;
  899. }
  900. auto &node = iter->second;
  901. if (task_type == RT_MODEL_TASK_KERNEL) {
  902. ge_model->GetTBEKernelStore().LoadTBEKernelBinToOpDesc(node->GetOpDesc());
  903. }
  904. GELOGD("Task loaded for node: %s, task type = %d, op_index = %u", node->GetName().c_str(), task_type, op_index);
  905. hybrid_model_.task_defs_[node].emplace_back(task_def);
  906. }
  907. }
  908. return SUCCESS;
  909. }
  910. Status HybridModelBuilder::IndexSpecialNodes() {
  911. GELOGD("Start to index special nodes");
  912. const auto &root_graph = ge_root_model_->GetRootGraph();
  913. for (auto &node : root_graph->GetAllNodes()) {
  914. GE_CHECK_NOTNULL(node);
  915. GE_CHECK_NOTNULL(node->GetOpDesc());
  916. auto op_type = node->GetType();
  917. GELOGD("node name = %s, node type = %s", node->GetName().c_str(), node->GetType().c_str());
  918. if (op_type == VARIABLE) {
  919. string placement;
  920. (void) AttrUtils::GetStr(node->GetOpDesc(), ATTR_VARIABLE_PLACEMENT, placement);
  921. if (placement == "host") {
  922. hybrid_model_.host_variable_nodes_.emplace(node->GetName(), node);
  923. } else {
  924. hybrid_model_.device_variable_nodes_.emplace(node->GetName(), node);
  925. }
  926. } else if (op_type == CONSTANTOP) {
  927. hybrid_model_.constant_op_nodes_.emplace(node->GetName(), node);
  928. } else if (op_type == DATA && node->GetOwnerComputeGraph() != root_graph) {
  929. NodePtr src_node;
  930. int peer_out_index = -1;
  931. GE_CHK_STATUS_RET_NOLOG(GetPeerNodeAcrossSubGraphs(node, src_node, peer_out_index));
  932. GELOGD("Got peer node for data node %s, peer node = %s(%s)",
  933. node->GetName().c_str(),
  934. src_node->GetName().c_str(),
  935. src_node->GetType().c_str());
  936. auto src_op_type = src_node->GetType();
  937. if (src_op_type == CONSTANTOP || src_op_type == VARIABLE) {
  938. for (auto &dst_node_and_in_anchor : node->GetOutDataNodesAndAnchors()) {
  939. auto &dst_node = dst_node_and_in_anchor.first;
  940. auto &in_anchor = dst_node_and_in_anchor.second;
  941. node_ref_inputs_[dst_node].emplace_back(std::make_pair(in_anchor->GetIdx(), src_node));
  942. }
  943. }
  944. }
  945. }
  946. return SUCCESS;
  947. }
  948. Status HybridModelBuilder::GetPeerNodeAcrossSubGraphs(const NodePtr &data_node,
  949. NodePtr &peer_node,
  950. int &peer_out_index) {
  951. auto sub_graph = data_node->GetOwnerComputeGraph();
  952. GE_CHECK_NOTNULL(sub_graph);
  953. GELOGD("To get peer node of %s::%s", sub_graph->GetName().c_str(), data_node->GetName().c_str());
  954. auto wrapped_node = data_node->GetOwnerComputeGraph()->GetParentNode();
  955. if (wrapped_node == nullptr) {
  956. GELOGE(INTERNAL_ERROR, "[%s] Node is in root graph.", data_node->GetName().c_str());
  957. return INTERNAL_ERROR;
  958. }
  959. auto data_op_desc = data_node->GetOpDesc();
  960. uint32_t parent_index = 0;
  961. if (!AttrUtils::GetInt(data_op_desc, ATTR_NAME_PARENT_NODE_INDEX, parent_index)) {
  962. GELOGE(INTERNAL_ERROR,
  963. "[%s] Failed to get attr [%s]",
  964. data_op_desc->GetName().c_str(),
  965. ATTR_NAME_PARENT_NODE_INDEX.c_str());
  966. return INTERNAL_ERROR;
  967. }
  968. auto wrapped_node_in_anchor = wrapped_node->GetInDataAnchor(parent_index);
  969. GE_CHECK_NOTNULL(wrapped_node_in_anchor);
  970. auto src_out_anchor = wrapped_node_in_anchor->GetPeerOutAnchor();
  971. if (src_out_anchor == nullptr || src_out_anchor->GetOwnerNode() == nullptr) {
  972. GELOGE(INTERNAL_ERROR, "[%s] Parent node do not have peer anchor.", data_node->GetName().c_str());
  973. return INTERNAL_ERROR;
  974. }
  975. auto src_wrapped_node_out_anchor = wrapped_node_in_anchor->GetPeerOutAnchor();
  976. GE_CHECK_NOTNULL(src_wrapped_node_out_anchor);
  977. auto src_wrapped_node = src_wrapped_node_out_anchor->GetOwnerNode();
  978. GE_CHECK_NOTNULL(src_wrapped_node);
  979. // connected to root-graph's DATA
  980. auto src_node_type = src_wrapped_node->GetType();
  981. if (src_node_type != PARTITIONEDCALL) {
  982. peer_node = src_wrapped_node;
  983. peer_out_index = kVarOutputIndex;
  984. GELOGD("[%s] Node is connected to root graph's node: %s",
  985. data_node->GetName().c_str(),
  986. peer_node->GetName().c_str());
  987. return SUCCESS;
  988. }
  989. auto src_graph = NodeUtils::GetSubgraph(*src_wrapped_node, kSubgraphIndex);
  990. GE_CHECK_NOTNULL(src_graph);
  991. auto src_net_output_node = src_graph->FindFirstNodeMatchType(NETOUTPUT);
  992. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(src_net_output_node == nullptr,
  993. return INTERNAL_ERROR,
  994. "Failed to find NetOutput in subgraph: %s",
  995. src_graph->GetName().c_str());
  996. auto net_output_desc = src_net_output_node->GetOpDesc();
  997. GE_CHECK_NOTNULL(net_output_desc);
  998. auto out_index = static_cast<uint32_t>(src_wrapped_node_out_anchor->GetIdx());
  999. GELOGD("src graph = %s, src parent output index = %u", src_graph->GetName().c_str(), out_index);
  1000. // link src to outputs of DataNode
  1001. auto input_size = net_output_desc->GetAllInputsSize();
  1002. GE_CHECK_LE(input_size, UINT32_MAX);
  1003. for (uint32_t i = 0; i < static_cast<uint32_t>(input_size); ++i) {
  1004. uint32_t p_index = 0;
  1005. if (!AttrUtils::GetInt(net_output_desc->GetInputDesc(i), ATTR_NAME_PARENT_NODE_INDEX, p_index)) {
  1006. GELOGW("SubGraph: %s input tensor %u attr %s not found.",
  1007. src_graph->GetName().c_str(), i, ATTR_NAME_PARENT_NODE_INDEX.c_str());
  1008. continue;
  1009. }
  1010. GELOGD("NetOutput's input[%u], parent_node_index = %u", i, p_index);
  1011. if (p_index == out_index) {
  1012. auto in_anchor = src_net_output_node->GetInDataAnchor(i);
  1013. GE_CHECK_NOTNULL(in_anchor);
  1014. auto peer_out_anchor = in_anchor->GetPeerOutAnchor();
  1015. GE_CHECK_NOTNULL(peer_out_anchor);
  1016. peer_node = peer_out_anchor->GetOwnerNode();
  1017. GE_CHECK_NOTNULL(peer_node);
  1018. peer_out_index = peer_out_anchor->GetIdx();
  1019. GELOGD("Found peer node of Data node: %s::%s is %s::%s",
  1020. sub_graph->GetName().c_str(),
  1021. data_node->GetName().c_str(),
  1022. src_graph->GetName().c_str(),
  1023. peer_node->GetName().c_str());
  1024. return SUCCESS;
  1025. }
  1026. }
  1027. GELOGE(FAILED,
  1028. "Failed to find peer node for %s::%s",
  1029. sub_graph->GetName().c_str(),
  1030. data_node->GetName().c_str());
  1031. return FAILED;
  1032. }
  1033. Status HybridModelBuilder::InitRuntimeParams() {
  1034. int64_t value = 0;
  1035. bool ret = false;
  1036. if (ge_root_model_->GetSubgraphInstanceNameToModel().empty()) {
  1037. GELOGE(INTERNAL_ERROR, "Root model has no sub model");
  1038. return INTERNAL_ERROR;
  1039. }
  1040. // session id and var size is same for every model
  1041. auto first_model = ge_root_model_->GetSubgraphInstanceNameToModel().begin()->second;
  1042. ret = ge::AttrUtils::GetInt(first_model, ge::MODEL_ATTR_SESSION_ID, value);
  1043. runtime_param_.session_id = ret ? static_cast<uint64_t>(value) : 0;
  1044. ret = ge::AttrUtils::GetInt(first_model, ATTR_MODEL_TASK_GEN_VAR_ADDR, value);
  1045. runtime_param_.logic_var_base = ret ? static_cast<uint64_t>(value) : 0;
  1046. runtime_param_.graph_id = ge_root_model_->GetRootGraph()->GetGraphID();
  1047. value = 0;
  1048. for (auto &it : ge_root_model_->GetSubgraphInstanceNameToModel()) {
  1049. (void) ge::AttrUtils::GetInt(it.second, ATTR_MODEL_VAR_SIZE, value);
  1050. if (value > 0) {
  1051. runtime_param_.var_size = static_cast<uint64_t>(value);
  1052. break;
  1053. }
  1054. }
  1055. GELOGI("InitRuntimeParams(), session_id:%lu, var_size:%lu. graph_id = %u",
  1056. runtime_param_.session_id, runtime_param_.var_size, runtime_param_.graph_id);
  1057. var_manager_ = VarManager::Instance(runtime_param_.session_id);
  1058. GE_CHECK_NOTNULL(var_manager_);
  1059. return SUCCESS;
  1060. }
  1061. Status HybridModelBuilder::IdentifySameInputs(NodeItem &node_item) {
  1062. GELOGD("Start to parse same inputs on net output: %s", node_item.NodeName().c_str());
  1063. auto subgraph = NodeUtils::GetSubgraph(*node_item.node, kSubgraphIndex);
  1064. GE_CHECK_NOTNULL(subgraph);
  1065. auto net_output_node = subgraph->FindFirstNodeMatchType(NETOUTPUT);
  1066. if (net_output_node == nullptr) {
  1067. GELOGD("Subgraph [%s] does not have net output", subgraph->GetName().c_str());
  1068. return SUCCESS;
  1069. }
  1070. auto net_output_desc = net_output_node->GetOpDesc();
  1071. GE_CHECK_NOTNULL(net_output_desc);
  1072. std::map<std::string, int> connected_inputs;
  1073. for (const auto &in_data_anchor : net_output_node->GetAllInDataAnchors()) {
  1074. auto out_data_anchor = in_data_anchor->GetPeerOutAnchor();
  1075. if (out_data_anchor == nullptr) {
  1076. continue;
  1077. }
  1078. auto src_node = out_data_anchor->GetOwnerNode();
  1079. GE_CHECK_NOTNULL(src_node);
  1080. auto op_desc = src_node->GetOpDesc();
  1081. GE_CHECK_NOTNULL(op_desc);
  1082. std::string input_key = std::to_string(op_desc->GetId()) + "_" + std::to_string(out_data_anchor->GetIdx());
  1083. auto it = connected_inputs.find(input_key);
  1084. if (it == connected_inputs.end()) {
  1085. connected_inputs.emplace(input_key, in_data_anchor->GetIdx());
  1086. } else {
  1087. GELOGD("[%s] output [%d] reuse output [%d] input node = %s, idx = %d.", node_item.NodeName().c_str(),
  1088. in_data_anchor->GetIdx(),
  1089. it->second,
  1090. src_node->GetName().c_str(),
  1091. out_data_anchor->GetIdx());
  1092. node_item.reuse_outputs.emplace(in_data_anchor->GetIdx(), it->second);
  1093. }
  1094. }
  1095. return SUCCESS;
  1096. }
  1097. Status HybridModelBuilder::IdentifyVariableOutputs(NodeItem &node_item) {
  1098. GELOGD("Start to parse outputs of node: %s", node_item.NodeName().c_str());
  1099. auto subgraph = NodeUtils::GetSubgraph(*node_item.node, kSubgraphIndex);
  1100. GE_CHECK_NOTNULL(subgraph);
  1101. auto net_output_node = subgraph->FindFirstNodeMatchType(NETOUTPUT);
  1102. if (net_output_node == nullptr) {
  1103. GELOGD("[%s] Subgraph do not got net output", subgraph->GetName().c_str());
  1104. return SUCCESS;
  1105. }
  1106. auto net_output_desc = net_output_node->GetOpDesc();
  1107. GE_CHECK_NOTNULL(net_output_desc);
  1108. // constant/variable connected to net output
  1109. for (const auto &in_data_anchor : net_output_node->GetAllInDataAnchors()) {
  1110. auto src_node = GetPeerNode(in_data_anchor);
  1111. GE_CHECK_NOTNULL(src_node);
  1112. auto src_op_type = src_node->GetType();
  1113. GELOGD("Node %s, output %d, src node = %s, src node type = %s",
  1114. node_item.NodeName().c_str(),
  1115. in_data_anchor->GetIdx(),
  1116. src_node->GetName().c_str(),
  1117. src_op_type.c_str());
  1118. if (src_op_type != CONSTANTOP && src_op_type != VARIABLE) {
  1119. continue;
  1120. }
  1121. uint32_t parent_index = 0;
  1122. GE_CHK_STATUS_RET_NOLOG(GetParentNodeOutputIndex(*net_output_desc, in_data_anchor->GetIdx(), parent_index));
  1123. GELOGD("Got parent output index = %u", parent_index);
  1124. GE_CHECK_LE(parent_index, INT32_MAX);
  1125. node_item.ref_outputs.emplace(static_cast<int>(parent_index), src_node);
  1126. }
  1127. // Data nodes marked with REF_VAR_SRC_VAR_NAME
  1128. // Using variable tensor as data's output
  1129. for (auto &node : subgraph->GetDirectNode()) {
  1130. if (node->GetType() != DATA) {
  1131. continue;
  1132. }
  1133. string ref_var_name;
  1134. (void) AttrUtils::GetStr(node->GetOpDesc(), REF_VAR_SRC_VAR_NAME, ref_var_name);
  1135. if (ref_var_name.empty()) {
  1136. continue;
  1137. }
  1138. GELOGD("Data node ref to variable: %s", ref_var_name.c_str());
  1139. NodePtr src_node;
  1140. auto var_node = hybrid_model_.GetVariableNode(ref_var_name);
  1141. GE_CHECK_NOTNULL(var_node);
  1142. GELOGD("Found var node [%s] by ref_var_name [%s]", var_node->GetName().c_str(), ref_var_name.c_str());
  1143. int peer_output_index = -1;
  1144. GE_CHK_STATUS_RET_NOLOG(GetPeerNodeAcrossSubGraphs(node, src_node, peer_output_index));
  1145. auto src_node_item = MutableNodeItem(src_node);
  1146. GE_CHECK_NOTNULL(src_node_item);
  1147. src_node_item->ref_outputs.emplace(peer_output_index, var_node);
  1148. }
  1149. return SUCCESS;
  1150. }
  1151. NodePtr HybridModelBuilder::GetPeerNode(const InDataAnchorPtr &in_data_anchor) {
  1152. auto peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  1153. if (peer_out_anchor != nullptr) {
  1154. return peer_out_anchor->GetOwnerNode();
  1155. }
  1156. return nullptr;
  1157. }
  1158. Status HybridModelBuilder::GetParentNodeOutputIndex(const OpDesc &op_desc, int index, uint32_t &out_index) {
  1159. auto input_desc = op_desc.MutableInputDesc(index);
  1160. GE_CHECK_NOTNULL(input_desc);
  1161. if (!AttrUtils::GetInt(input_desc, ATTR_NAME_PARENT_NODE_INDEX, out_index)) {
  1162. GELOGE(INTERNAL_ERROR, "NetOutput input tensor %d, attr %s not found.",
  1163. index, ATTR_NAME_PARENT_NODE_INDEX.c_str());
  1164. return INTERNAL_ERROR;
  1165. }
  1166. return SUCCESS;
  1167. }
  1168. Status HybridModelBuilder::InitModelMem() {
  1169. hybrid_model_.var_mem_base_ = var_manager_->GetVarMemoryBase(RT_MEMORY_HBM);
  1170. auto total_var_size = hybrid_model_.TotalVarMemSize();
  1171. if (total_var_size == 0 && !hybrid_model_.constant_op_nodes_.empty()) {
  1172. total_var_size = var_manager_->GetVarMemSize(RT_MEMORY_HBM) > 0 ? var_manager_->GetVarMemMaxSize() : 0;
  1173. GELOGD("Model var size = 0. but got uninitialized constant. set var size to %zu.", total_var_size);
  1174. }
  1175. if (total_var_size > 0 && hybrid_model_.var_mem_base_ == nullptr) {
  1176. GE_CHK_STATUS_RET(var_manager_->MallocVarMemory(total_var_size),
  1177. "Malloc Var Memory Fail.");
  1178. hybrid_model_.var_mem_base_ = var_manager_->GetVarMemoryBase(RT_MEMORY_HBM);
  1179. }
  1180. runtime_param_.var_base = hybrid_model_.var_mem_base_;
  1181. return SUCCESS;
  1182. }
  1183. Status HybridModelBuilder::TransAllVarData() {
  1184. GELOGI("TransAllVarData start: session_id:%lu, graph_id: %u.", runtime_param_.session_id, runtime_param_.graph_id);
  1185. rtContext_t ctx = nullptr;
  1186. rtError_t rt_ret = rtCtxGetCurrent(&ctx);
  1187. if (rt_ret != RT_ERROR_NONE) {
  1188. GELOGE(RT_FAILED, "Failed to get current context, error_code is: 0x%X.", rt_ret);
  1189. return RT_FAILED;
  1190. }
  1191. std::vector<NodePtr> variable_node_list;
  1192. for (auto &it : hybrid_model_.device_variable_nodes_) {
  1193. variable_node_list.emplace_back(it.second);
  1194. GELOGD("[%s] added for trans var data", it.first.c_str());
  1195. }
  1196. GE_CHK_STATUS_RET(TransVarDataUtils::TransAllVarData(variable_node_list,
  1197. runtime_param_.session_id,
  1198. ctx,
  1199. runtime_param_.graph_id),
  1200. "TransAllVarData failed.");
  1201. GELOGI("TransAllVarData success.");
  1202. return SUCCESS;
  1203. }
  1204. Status HybridModelBuilder::CopyVarData() {
  1205. GE_CHK_STATUS_RET(TransVarDataUtils::CopyVarData(ge_root_model_->GetRootGraph(),
  1206. runtime_param_.session_id,
  1207. hybrid_model_.device_id_),
  1208. "CopyVarData failed.");
  1209. GELOGI("CopyVarData success.");
  1210. return SUCCESS;
  1211. }
  1212. Status HybridModelBuilder::LoadKnownShapedSubgraph(ComputeGraph &graph, NodeItem *parent_node_item) {
  1213. GELOGD("Start to load known shaped subgraph [%s]", graph.GetName().c_str());
  1214. auto graph_item = std::unique_ptr<GraphItem>(new(std::nothrow)GraphItem());
  1215. GE_CHECK_NOTNULL(graph_item);
  1216. graph_item->is_dynamic_ = false;
  1217. auto subgraph_name = graph.GetName();
  1218. auto wrapper_op_desc = MakeShared<OpDesc>(subgraph_name + "_partitioned_call", PARTITIONEDCALL);
  1219. GE_CHECK_NOTNULL(wrapper_op_desc);
  1220. for (auto &node : graph.GetDirectNode()) {
  1221. GE_CHECK_NOTNULL(node);
  1222. auto op_desc = node->GetOpDesc();
  1223. GE_CHECK_NOTNULL(op_desc);
  1224. const auto &op_type = node->GetType();
  1225. if (op_type == DATA) {
  1226. int32_t data_index = 0;
  1227. if (!AttrUtils::GetInt(node->GetOpDesc(), ATTR_NAME_PARENT_NODE_INDEX, data_index)) {
  1228. GELOGE(FAILED,
  1229. "[%s] Failed to get attr [%s]",
  1230. node->GetName().c_str(),
  1231. ATTR_NAME_PARENT_NODE_INDEX.c_str());
  1232. return FAILED;
  1233. }
  1234. (void) wrapper_op_desc->AddInputDesc(op_desc->GetInputDesc(0));
  1235. graph_item->input_index_mapping_.emplace_back(data_index);
  1236. } else if (op_type == NETOUTPUT) {
  1237. int output_index = 0;
  1238. for (const auto &output_desc : op_desc->GetAllInputsDescPtr()) {
  1239. int32_t data_index = output_index++;
  1240. if (!AttrUtils::GetInt(output_desc, ATTR_NAME_PARENT_NODE_INDEX, data_index)) {
  1241. GELOGI("[%s] Failed to get attr [%s]", node->GetName().c_str(), ATTR_NAME_PARENT_NODE_INDEX.c_str());
  1242. }
  1243. GE_CHK_GRAPH_STATUS_RET(wrapper_op_desc->AddOutputDesc(*output_desc),
  1244. "[%s] Failed to add output desc. output index = %d",
  1245. graph.GetName().c_str(),
  1246. output_index);
  1247. graph_item->output_index_mapping_.emplace_back(data_index);
  1248. }
  1249. }
  1250. }
  1251. auto temp_graph = MakeShared<ComputeGraph>("temp");
  1252. GE_CHECK_NOTNULL(temp_graph);
  1253. auto wrapper_node = temp_graph->AddNode(wrapper_op_desc);
  1254. GeModelPtr ge_model = subgraph_models_[subgraph_name];
  1255. GE_CHECK_NOTNULL(ge_model);
  1256. hybrid_model_.known_shape_sub_models_.emplace(wrapper_node, ge_model);
  1257. NodeItem *node_item = nullptr;
  1258. GE_CHK_STATUS_RET_NOLOG(GetOrCreateNodeItem(wrapper_node, &node_item));
  1259. node_item->input_start = 0;
  1260. node_item->output_start = 0;
  1261. node_item->outputs.resize(node_item->num_outputs);
  1262. graph_item->node_items_.emplace_back(node_item);
  1263. graph_item->output_node_ = node_item;
  1264. graph_item->total_inputs_ = node_item->num_inputs;
  1265. graph_item->total_outputs_ = node_item->num_outputs;
  1266. GELOGD("NodeItem create for known shape subgraph [%s], NodeItem = %s",
  1267. graph.GetName().c_str(),
  1268. node_item->DebugString().c_str());
  1269. GELOGD("Done parse known shape subgraph successfully. graph = [%s]", graph.GetName().c_str());
  1270. graph_item->SetName(graph.GetName());
  1271. GELOGD("Done loading known shape subgraph: [%s]", graph_item->GetName().c_str());
  1272. hybrid_model_.subgraph_items_.emplace(graph.GetName(), std::move(graph_item));
  1273. return SUCCESS;
  1274. }
  1275. Status HybridModelBuilder::RecoverGraphUnknownFlag() {
  1276. const auto &root_graph = ge_root_model_->GetRootGraph();
  1277. for (auto &sub_graph : root_graph->GetAllSubgraphs()) {
  1278. GE_CHECK_NOTNULL(sub_graph);
  1279. for (const auto &node : sub_graph->GetDirectNode()) {
  1280. bool is_unknown_shape = false;
  1281. (void)AttrUtils::GetBool(node->GetOpDesc(), kOwnerGraphIsUnknown, is_unknown_shape);
  1282. sub_graph->SetGraphUnknownFlag(is_unknown_shape);
  1283. break;
  1284. }
  1285. }
  1286. return SUCCESS;
  1287. }
  1288. Status HybridModelBuilder::LoadDynamicSubgraph(ComputeGraph &graph, bool is_root_graph) {
  1289. GELOGD("Start to load subgraph [%s]", graph.GetName().c_str());
  1290. // for known partitioned call, load all nodes
  1291. auto graph_item = std::unique_ptr<GraphItem>(new(std::nothrow)GraphItem());
  1292. GE_CHECK_NOTNULL(graph_item);
  1293. graph_item->is_dynamic_ = true;
  1294. graph_item->node_items_.reserve(graph.GetDirectNodesSize());
  1295. int input_start = 0;
  1296. int output_start = 0;
  1297. std::vector<NodeItem *> data_nodes;
  1298. for (auto &node : graph.GetDirectNode()) {
  1299. GE_CHECK_NOTNULL(node);
  1300. GE_CHECK_NOTNULL(node->GetOpDesc());
  1301. const auto &op_type = node->GetType();
  1302. NodeItem *node_item = nullptr;
  1303. GE_CHK_STATUS_RET_NOLOG(GetOrCreateNodeItem(node, &node_item));
  1304. GE_CHK_STATUS_RET_NOLOG(BuildNodeItem(node, *node_item));
  1305. GE_CHK_STATUS_RET_NOLOG(UpdateAnchorStatus(node)); // needed by FE generate task
  1306. node_item->input_start = input_start;
  1307. node_item->output_start = output_start;
  1308. input_start += node_item->num_inputs;
  1309. output_start += node_item->num_outputs;
  1310. if (op_type == DATA_TYPE || op_type == AIPP_DATA_TYPE) {
  1311. data_nodes.emplace_back(node_item);
  1312. } else if (op_type == NETOUTPUT) {
  1313. graph_item->output_node_ = node_item;
  1314. GE_CHK_STATUS_RET_NOLOG(BuildOutputMapping(*graph_item, *node_item, is_root_graph));
  1315. }
  1316. graph_item->node_items_.emplace_back(node_item);
  1317. // parse var outputs
  1318. GE_CHK_STATUS_RET_NOLOG(ParseVarOutputs(*node_item));
  1319. GELOGD("NodeItem created: %s", node_item->DebugString().c_str());
  1320. }
  1321. graph_item->total_inputs_ = input_start;
  1322. graph_item->total_outputs_ = output_start;
  1323. GE_CHK_STATUS_RET_NOLOG(BuildInputMapping(*graph_item, data_nodes, is_root_graph));
  1324. if (is_root_graph) {
  1325. graph_item->SetName("Root-Graph");
  1326. GELOGD("Done loading dynamic subgraph: [%s]", graph_item->GetName().c_str());
  1327. hybrid_model_.root_graph_item_ = std::move(graph_item);
  1328. } else {
  1329. graph_item->SetName(graph.GetName());
  1330. GELOGD("Done loading dynamic subgraph: [%s]", graph_item->GetName().c_str());
  1331. hybrid_model_.subgraph_items_.emplace(graph.GetName(), std::move(graph_item));
  1332. }
  1333. return SUCCESS;
  1334. }
  1335. Status HybridModelBuilder::ParseVarOutputs(NodeItem &node_item) {
  1336. for (int i = 0; i < node_item.num_outputs; ++i) {
  1337. auto output_tensor_desc = node_item.op_desc->GetOutputDesc(i);
  1338. std::string var_name;
  1339. (void) AttrUtils::GetStr(output_tensor_desc, ASSIGN_VAR_NAME, var_name);
  1340. if (!var_name.empty()) {
  1341. auto var_node = hybrid_model_.GetVariableNode(var_name);
  1342. GE_CHECK_NOTNULL(var_node);
  1343. node_item.ref_outputs.emplace(i, var_node);
  1344. }
  1345. }
  1346. return SUCCESS;
  1347. }
  1348. Status HybridModelBuilder::BuildInputMapping(GraphItem &graph_item,
  1349. vector<NodeItem *> &data_nodes,
  1350. bool is_root_graph) {
  1351. uint32_t data_op_index = 0;
  1352. for (auto &node_item : data_nodes) {
  1353. auto node = node_item->node;
  1354. int data_index = data_op_index;
  1355. if (is_root_graph) {
  1356. if (AttrUtils::GetInt(node->GetOpDesc(), ATTR_NAME_INDEX, data_index)) {
  1357. GELOGI("ge_train: get new index %u, old %u", data_index, data_op_index);
  1358. }
  1359. data_op_index++;
  1360. } else {
  1361. if (!AttrUtils::GetInt(node->GetOpDesc(), ATTR_NAME_PARENT_NODE_INDEX, data_index)) {
  1362. GELOGE(FAILED,
  1363. "[%s] Failed to get attr [%s]",
  1364. node->GetName().c_str(),
  1365. ATTR_NAME_PARENT_NODE_INDEX.c_str());
  1366. return FAILED;
  1367. }
  1368. }
  1369. if (graph_item.input_nodes_.size() <= static_cast<size_t>(data_index)) {
  1370. graph_item.input_nodes_.resize(data_index + 1);
  1371. }
  1372. graph_item.input_nodes_[data_index] = node_item;
  1373. }
  1374. return SUCCESS;
  1375. }
  1376. } // namespace hybrid
  1377. } // namespace ge

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