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

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