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

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

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