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

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