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

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

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