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

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

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