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

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