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

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

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