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

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

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