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

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