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

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

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