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

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

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