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

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

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