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

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

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