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

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