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

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

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