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

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

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