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 62 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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532
  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/new_model_manager/model_utils.h"
  23. #include "graph/manager/graph_var_manager.h"
  24. #include "graph/manager/host_mem_manager.h"
  25. #include "graph/manager/trans_var_data_utils.h"
  26. #include "graph/utils/graph_utils.h"
  27. #include "hybrid/common/npu_memory_allocator.h"
  28. #include "hybrid/node_executor/node_executor.h"
  29. namespace ge {
  30. namespace hybrid {
  31. namespace {
  32. const uint32_t kSubgraphIndex = 0U;
  33. const uint32_t kVarOutputIndex = 0U;
  34. const uint32_t kAlignment = 32;
  35. const int kBytes = 8;
  36. const char *const kOwnerGraphIsUnknown = "OwnerGraphIsUnknown";
  37. int64_t CalcVarSizeInBytes(const GeTensorDesc &desc) {
  38. int64_t var_size = 0;
  39. auto data_type = desc.GetDataType();
  40. if (data_type == DT_STRING) {
  41. (void) TensorUtils::GetSize(desc, var_size);
  42. return var_size;
  43. }
  44. if (TensorUtils::GetTensorMemorySizeInBytes(desc, var_size) != GRAPH_SUCCESS) {
  45. GELOGW("Failed to calc var data size");
  46. return -1;
  47. }
  48. return var_size;
  49. }
  50. Status CollectDependenciesForFusedGraph(NodeItem &node_item, std::set<OpDesc *> &data_ops) {
  51. for (const auto &node : node_item.fused_subgraph->nodes) {
  52. auto op_desc = node->GetOpDesc();
  53. GE_CHECK_NOTNULL(op_desc);
  54. const auto &depends = op_desc->GetOpInferDepends();
  55. if (depends.empty()) {
  56. continue;
  57. }
  58. for (auto &input_name : depends) {
  59. auto input_index = op_desc->GetInputIndexByName(input_name);
  60. auto src_node = NodeUtils::GetInDataNodeByIndex(*node, input_index);
  61. GE_CHECK_NOTNULL(src_node);
  62. auto src_op_desc = src_node->GetOpDesc();
  63. GE_CHECK_NOTNULL(src_op_desc);
  64. if (src_node->GetType() != DATA_TYPE) {
  65. GELOGE(UNSUPPORTED,
  66. "[%s::%s] Node in fused subgraph can only depend on Data nodes, but depend on %s",
  67. node_item.NodeName().c_str(),
  68. node->GetName().c_str(),
  69. src_node->GetType().c_str());
  70. return UNSUPPORTED;
  71. }
  72. data_ops.emplace(src_op_desc.get());
  73. }
  74. }
  75. return SUCCESS;
  76. }
  77. } // namespace
  78. HybridModelBuilder::HybridModelBuilder(HybridModel &hybrid_model)
  79. : hybrid_model_(hybrid_model), runtime_param_(hybrid_model.root_runtime_param_) {
  80. ge_root_model_ = hybrid_model_.ge_root_model_;
  81. }
  82. Status HybridModelBuilder::Build() {
  83. GE_CHK_STATUS_RET(ValidateParams(), "Failed to validate GeRootModel");
  84. hybrid_model_.model_name_ = ge_root_model_->GetRootGraph()->GetName();
  85. GELOGI("[%s] Start to build hybrid model.", GetGraphName());
  86. GE_CHK_STATUS_RET(InitRuntimeParams(), "[%s] Failed to InitRuntimeParams", GetGraphName());
  87. GE_CHK_STATUS_RET(RecoverGraphUnknownFlag(), "[%s] Failed to RecoverGraphUnknownFlag", GetGraphName());
  88. GE_CHK_STATUS_RET(IndexSpecialNodes(), "[%s] Failed to index nodes", GetGraphName());
  89. GE_CHK_STATUS_RET(IndexTaskDefs(), "[%s] Failed to index task defs", GetGraphName());
  90. GE_CHK_STATUS_RET(LoadGraph(), "[%s] Failed to load graph", GetGraphName());
  91. GE_CHK_STATUS_RET(AssignUninitializedConstantOps(), "[%s] Failed to assign uninitialized constants", GetGraphName());
  92. GE_CHK_STATUS_RET(TransAllVarData(), "[%s] Failed to trans all var data", GetGraphName());
  93. GE_CHK_STATUS_RET(CopyVarData(), "[%s] Failed to copy var data", GetGraphName());
  94. GE_CHK_STATUS_RET(InitModelMem(), "[%s] Failed to init memory", GetGraphName());
  95. GE_CHK_STATUS_RET(InitWeights(), "[%s] Failed to init weights", GetGraphName());
  96. GE_CHK_STATUS_RET(InitConstantOps(), "[%s] Failed to init constant op", GetGraphName());
  97. GE_CHK_STATUS_RET(InitVariableTensors(), "[%s] Failed to init variables", GetGraphName());
  98. GE_CHK_STATUS_RET(LoadTasks(), "[%s] Failed to load tasks", GetGraphName());
  99. GELOGI("[%s] Done building hybrid model successfully.", GetGraphName());
  100. return SUCCESS;
  101. }
  102. Status HybridModelBuilder::ValidateParams() {
  103. GE_CHECK_NOTNULL(ge_root_model_);
  104. GE_CHECK_NOTNULL(ge_root_model_->GetRootGraph());
  105. return SUCCESS;
  106. }
  107. Status HybridModelBuilder::BuildNodeItem(const NodePtr &node, NodeItem &node_item) {
  108. auto op_desc = node->GetOpDesc();
  109. vector<string> dependencies = node->GetOpDesc()->GetOpInferDepends();
  110. GE_CHK_STATUS_RET(ParseDependentInputNodes(node_item, dependencies),
  111. "[%s] Failed to parse node dependencies.",
  112. node_item.NodeName().c_str());
  113. node_item.outputs.resize(node_item.num_outputs);
  114. for (int i = 0; i < node_item.num_outputs; ++i) {
  115. auto out_data_anchor = node->GetOutDataAnchor(i);
  116. if (out_data_anchor == nullptr) {
  117. GELOGE(INTERNAL_ERROR, "out anchor[%d] of node %s is nullptr", i, node->GetName().c_str());
  118. return INTERNAL_ERROR;
  119. }
  120. for (auto &dst_in_anchor: out_data_anchor->GetPeerInDataAnchors()) {
  121. auto dst_node = dst_in_anchor->GetOwnerNode();
  122. if (dst_node == nullptr) {
  123. GELOGW("dst node is nullptr. out anchor = %d", out_data_anchor->GetIdx());
  124. continue;
  125. }
  126. NodeItem *dst_node_item = nullptr;
  127. GE_CHK_STATUS_RET(GetOrCreateNodeItem(dst_node, &dst_node_item),
  128. "[%s] Failed to get or create node item.",
  129. dst_node->GetName().c_str());
  130. int canonical_index;
  131. GE_CHK_STATUS_RET(dst_node_item->GetCanonicalInputIndex(dst_in_anchor->GetIdx(), canonical_index),
  132. "[%s] Failed to canonical input index",
  133. dst_node->GetName().c_str());
  134. node_item.outputs[i].emplace_back(canonical_index, dst_node_item);
  135. }
  136. }
  137. GE_CHK_STATUS_RET_NOLOG(ResolveRefIo(node_item));
  138. return SUCCESS;
  139. }
  140. Status HybridModelBuilder::ResolveRefIo(NodeItem &node_item) {
  141. bool is_ref = false;
  142. auto &op_desc = *node_item.op_desc;
  143. (void) AttrUtils::GetBool(op_desc, ATTR_NAME_REFERENCE, is_ref);
  144. if (!is_ref) {
  145. return SUCCESS;
  146. }
  147. auto inputs = op_desc.GetAllInputName();
  148. auto outputs = op_desc.GetAllOutputName();
  149. for (auto &output : outputs) {
  150. for (auto &input : inputs) {
  151. if (input.first == output.first) {
  152. int input_idx;
  153. GE_CHK_STATUS_RET_NOLOG(node_item.GetCanonicalInputIndex(input.second, input_idx));
  154. auto output_idx = static_cast<int>(output.second);
  155. node_item.reuse_inputs[output_idx] = input_idx;
  156. GELOGD("[%s] Output[%d] reuse input[%d]", node_item.NodeName().c_str(), output_idx, input_idx);
  157. }
  158. }
  159. }
  160. return SUCCESS;
  161. }
  162. Status HybridModelBuilder::GetOrCreateNodeItem(const NodePtr &node, NodeItem **node_item) {
  163. auto &node_items = hybrid_model_.node_items_;
  164. auto it = node_items.find(node);
  165. if (it != node_items.end()) {
  166. *node_item = it->second.get();
  167. return SUCCESS;
  168. }
  169. std::unique_ptr<NodeItem> new_node;
  170. GE_CHK_STATUS_RET(NodeItem::Create(node, new_node), "Failed to create node item");
  171. GE_CHK_STATUS_RET_NOLOG(NodeExecutorManager::GetInstance().GetExecutor(*node, &new_node->node_executor));
  172. // we do not need L2 Buffer
  173. const char *const kIsFirstNode = "is_first_node";
  174. const char *const kIsLastNode = "is_last_node";
  175. (void) AttrUtils::SetBool(new_node->op_desc, kIsFirstNode, false);
  176. (void) AttrUtils::SetBool(new_node->op_desc, kIsLastNode, false);
  177. new_node->node_id = node_index;
  178. new_node->op_desc->SetId(node_index);
  179. node_index += 1;
  180. *node_item = new_node.get();
  181. node_items[node] = std::move(new_node);
  182. return SUCCESS;
  183. }
  184. Status HybridModelBuilder::ParseDependentInputNodes(NodeItem &node_item, const std::vector<string> &dependencies) {
  185. std::set<NodePtr> dependent_input_nodes;
  186. auto &ge_node = node_item.node;
  187. bool is_hccl_op =
  188. NodeExecutorManager::GetInstance().ResolveExecutorType(*ge_node) == NodeExecutorManager::ExecutorType::HCCL;
  189. // The input tensors become valid after computation is done for parent nodes of type DEPEND_COMPUTE.
  190. // Wait for these parent nodes before execution.
  191. for (const auto &in_anchor : ge_node->GetAllInDataAnchors()) {
  192. const auto &peer_anchor = in_anchor->GetPeerOutAnchor();
  193. if (peer_anchor == nullptr) {
  194. GELOGD("[%s] Input[%d] do not have peer anchor", node_item.NodeName().c_str(), in_anchor->GetIdx());
  195. continue;
  196. }
  197. auto src_node = peer_anchor->GetOwnerNode();
  198. GE_CHECK_NOTNULL(src_node);
  199. auto src_node_item = MutableNodeItem(src_node);
  200. GE_CHECK_NOTNULL(src_node_item);
  201. if (is_hccl_op) {
  202. GELOGD("[%s] Add input data dependent node [%s] due to engine type is HCCL",
  203. node_item.NodeName().c_str(),
  204. src_node_item->NodeName().c_str());
  205. src_node_item->has_observer = true;
  206. node_item.dependents_for_execution.emplace_back(src_node);
  207. } else if (src_node_item->shape_inference_type == DEPEND_COMPUTE) {
  208. GELOGD("[%s] Add input data dependent node [%s] due to inference type = DEPEND_COMPUTE",
  209. node_item.NodeName().c_str(),
  210. src_node_item->NodeName().c_str());
  211. src_node_item->has_observer = true;
  212. node_item.dependents_for_execution.emplace_back(src_node);
  213. }
  214. if (src_node_item->shape_inference_type == DEPEND_SHAPE_RANGE) {
  215. GELOGD("[%s] Add input shape dependent node [%s] due to inference type = DEPEND_SHAPE_RANGE",
  216. node_item.NodeName().c_str(),
  217. src_node_item->NodeName().c_str());
  218. src_node_item->has_observer = true;
  219. dependent_input_nodes.emplace(src_node);
  220. }
  221. }
  222. // cond or branch need to be prepared before the execution of IF or CASE
  223. if (node_item.node_type == IF || node_item.node_type == STATELESSIF || node_item.node_type == CASE) {
  224. const auto &in_anchor = ge_node->GetInDataAnchor(0);
  225. GE_CHECK_NOTNULL(in_anchor);
  226. const auto &peer_anchor = in_anchor->GetPeerOutAnchor();
  227. GE_CHECK_NOTNULL(peer_anchor);
  228. auto src_node = peer_anchor->GetOwnerNode();
  229. GE_CHECK_NOTNULL(src_node);
  230. auto src_node_item = MutableNodeItem(src_node);
  231. GE_CHECK_NOTNULL(src_node_item);
  232. src_node_item->has_observer = true;
  233. node_item.dependents_for_execution.emplace_back(src_node);
  234. GELOGD("[%s] Dependent added from %s for control op's cond/branch",
  235. node_item.NodeName().c_str(),
  236. src_node_item->NodeName().c_str());
  237. }
  238. for (const auto &input_name : dependencies) {
  239. int input_index = node_item.op_desc->GetInputIndexByName(input_name);
  240. if (input_index < 0) {
  241. GELOGE(INTERNAL_ERROR,
  242. "[%s] Failed to get input index by name: %s",
  243. node_item.NodeName().c_str(),
  244. input_name.c_str());
  245. return INTERNAL_ERROR;
  246. }
  247. const auto &in_anchor = ge_node->GetInDataAnchor(input_index);
  248. GE_CHECK_NOTNULL(in_anchor);
  249. const auto &peer_out_anchor = in_anchor->GetPeerOutAnchor();
  250. GE_CHECK_NOTNULL(peer_out_anchor);
  251. const auto &src_node = peer_out_anchor->GetOwnerNode();
  252. GE_CHECK_NOTNULL(src_node);
  253. auto src_node_item = MutableNodeItem(src_node);
  254. src_node_item->to_const_output_id_list.emplace(peer_out_anchor->GetIdx());
  255. src_node_item->has_observer = true;
  256. dependent_input_nodes.emplace(src_node);
  257. GELOGD("[%s] Dependent added from output of [%s:%d]",
  258. node_item.NodeName().c_str(),
  259. src_node_item->NodeName().c_str(),
  260. peer_out_anchor->GetIdx());
  261. }
  262. for (const auto &dep_node : dependent_input_nodes) {
  263. node_item.dependents_for_shape_inference.emplace_back(dep_node);
  264. }
  265. GE_CHK_STATUS_RET(ParseDependentForFusedSubgraph(node_item));
  266. return SUCCESS;
  267. }
  268. Status HybridModelBuilder::ParseDependentForFusedSubgraph(NodeItem &node_item) {
  269. if (node_item.fused_subgraph == nullptr) {
  270. return SUCCESS;
  271. }
  272. std::set<OpDesc *> data_ops;
  273. GE_CHK_STATUS_RET_NOLOG(CollectDependenciesForFusedGraph(node_item, data_ops));
  274. for (auto &op_desc : data_ops) {
  275. uint32_t parent_index = 0;
  276. if (!AttrUtils::GetInt(*op_desc, ATTR_NAME_PARENT_NODE_INDEX, parent_index)) {
  277. GELOGE(INTERNAL_ERROR,
  278. "[%s] Failed to get attr [%s]",
  279. op_desc->GetName().c_str(),
  280. ATTR_NAME_PARENT_NODE_INDEX.c_str());
  281. return INTERNAL_ERROR;
  282. }
  283. const auto &in_anchor = node_item.node->GetInDataAnchor(parent_index);
  284. GE_CHECK_NOTNULL(in_anchor);
  285. const auto &peer_out_anchor = in_anchor->GetPeerOutAnchor();
  286. GE_CHECK_NOTNULL(peer_out_anchor);
  287. const auto &src_node = peer_out_anchor->GetOwnerNode();
  288. GE_CHECK_NOTNULL(src_node);
  289. NodeItem *src_node_item = nullptr;
  290. GE_CHK_STATUS_RET_NOLOG(GetOrCreateNodeItem(src_node, &src_node_item));
  291. op_desc->SetId(src_node_item->op_desc->GetId());
  292. GELOGD("[%s::%s] Node id was set to that of outer src node's, src_node = %s",
  293. node_item.NodeName().c_str(),
  294. op_desc->GetName().c_str(),
  295. src_node_item->NodeName().c_str());
  296. src_node_item->has_observer = true;
  297. src_node_item->to_const_output_id_list.emplace(peer_out_anchor->GetIdx());
  298. auto &depends = node_item.dependents_for_shape_inference;
  299. if (std::find(depends.begin(), depends.end(), src_node) == depends.end()) {
  300. depends.emplace_back(src_node);
  301. GELOGD("[%s] Dependent added from output of [%s:%d]",
  302. node_item.NodeName().c_str(),
  303. src_node_item->NodeName().c_str(),
  304. peer_out_anchor->GetIdx());
  305. }
  306. }
  307. return SUCCESS;
  308. }
  309. Status HybridModelBuilder::UpdateAnchorStatus(const NodePtr &node) {
  310. if (NodeUtils::SetAllAnchorStatus(node) != GRAPH_SUCCESS) {
  311. GELOGE(INTERNAL_ERROR, "[%s] NodeUtils::SetAllAnchorStatus failed.", node->GetName().c_str());
  312. return INTERNAL_ERROR;
  313. }
  314. for (auto &anchor : node->GetAllInDataAnchors()) {
  315. auto peer_anchor = anchor->GetPeerOutAnchor();
  316. if (peer_anchor == nullptr) {
  317. if (AnchorUtils::SetStatus(anchor, ANCHOR_SUSPEND) != GRAPH_SUCCESS) {
  318. GELOGE(INTERNAL_ERROR, "[%s] AnchorUtils::SetStatus failed.", node->GetName().c_str());
  319. return INTERNAL_ERROR;
  320. }
  321. } else if (peer_anchor->GetOwnerNode()->GetType() == CONSTANT) {
  322. if (AnchorUtils::SetStatus(anchor, ANCHOR_CONST) != GRAPH_SUCCESS) {
  323. GELOGE(INTERNAL_ERROR, "[%s] AnchorUtils::SetStatus failed.", node->GetName().c_str());
  324. return INTERNAL_ERROR;
  325. }
  326. } else {
  327. if (AnchorUtils::SetStatus(anchor, ANCHOR_DATA) != GRAPH_SUCCESS) {
  328. GELOGE(INTERNAL_ERROR, "[%s] AnchorUtils::SetStatus failed.", node->GetName().c_str());
  329. return INTERNAL_ERROR;
  330. }
  331. }
  332. }
  333. return SUCCESS;
  334. }
  335. Status HybridModelBuilder::DoUnlinkDataAnchors(const OutDataAnchorPtr &out_data_anchor,
  336. const InDataAnchorPtr &in_data_anchor) {
  337. GE_CHK_GRAPH_STATUS_RET(out_data_anchor->Unlink(in_data_anchor), "Failed to unlink %s:%d from %s:%d",
  338. out_data_anchor->GetOwnerNode()->GetName().c_str(),
  339. out_data_anchor->GetIdx(),
  340. in_data_anchor->GetOwnerNode()->GetName().c_str(),
  341. in_data_anchor->GetIdx());
  342. GELOGD("Succeeded in unlinking %s:%d from %s:%d",
  343. out_data_anchor->GetOwnerNode()->GetName().c_str(),
  344. out_data_anchor->GetIdx(),
  345. in_data_anchor->GetOwnerNode()->GetName().c_str(),
  346. in_data_anchor->GetIdx());
  347. return SUCCESS;
  348. }
  349. Status HybridModelBuilder::DoLinkDataAnchors(OutDataAnchorPtr &out_data_anchor, InDataAnchorPtr &in_data_anchor) {
  350. GE_CHK_GRAPH_STATUS_RET(out_data_anchor->LinkTo(in_data_anchor), "Failed to link %s:%d to %s:%d",
  351. out_data_anchor->GetOwnerNode()->GetName().c_str(),
  352. out_data_anchor->GetIdx(),
  353. in_data_anchor->GetOwnerNode()->GetName().c_str(),
  354. in_data_anchor->GetIdx());
  355. GELOGD("Succeeded in linking %s:%d to %s:%d",
  356. out_data_anchor->GetOwnerNode()->GetName().c_str(),
  357. out_data_anchor->GetIdx(),
  358. in_data_anchor->GetOwnerNode()->GetName().c_str(),
  359. in_data_anchor->GetIdx());
  360. return SUCCESS;
  361. }
  362. Status HybridModelBuilder::MergeInputNodes(ComputeGraph &graph) {
  363. const auto &wrapped_node = graph.GetParentNode();
  364. std::set<NodePtr> root_nodes;
  365. for (const auto &node : graph.GetDirectNode()) {
  366. GE_CHECK_NOTNULL(node);
  367. if (node->GetType() != DATA_TYPE) {
  368. if (node->GetInDataNodes().empty()) {
  369. root_nodes.emplace(node);
  370. }
  371. continue;
  372. }
  373. auto data_op_desc = node->GetOpDesc();
  374. GE_CHECK_NOTNULL(data_op_desc);
  375. uint32_t parent_index = 0;
  376. if (!AttrUtils::GetInt(data_op_desc, ATTR_NAME_PARENT_NODE_INDEX, parent_index)) {
  377. GELOGE(FAILED,
  378. "[%s] Failed to get attr [%s]",
  379. data_op_desc->GetName().c_str(),
  380. ATTR_NAME_PARENT_NODE_INDEX.c_str());
  381. return FAILED;
  382. }
  383. auto wrapped_node_in_anchor = wrapped_node->GetInDataAnchor(parent_index);
  384. GE_CHECK_NOTNULL(wrapped_node_in_anchor);
  385. auto src_out_anchor = wrapped_node_in_anchor->GetPeerOutAnchor();
  386. if (src_out_anchor == nullptr || src_out_anchor->GetOwnerNode() == nullptr) {
  387. continue;
  388. }
  389. wrapped_node_in_anchor->UnlinkAll();
  390. // link src to outputs of DataNode
  391. for (auto &out_data_anchor : node->GetAllOutDataAnchors()) {
  392. GE_CHECK_NOTNULL(out_data_anchor);
  393. for (auto &peer_in_data_anchor : out_data_anchor->GetPeerInDataAnchors()) {
  394. auto dst_node = peer_in_data_anchor->GetOwnerNode();
  395. GE_CHECK_NOTNULL(dst_node);
  396. root_nodes.emplace(dst_node);
  397. GE_CHK_STATUS_RET_NOLOG(DoUnlinkDataAnchors(out_data_anchor, peer_in_data_anchor));
  398. GE_CHK_STATUS_RET_NOLOG(DoLinkDataAnchors(src_out_anchor, peer_in_data_anchor));
  399. }
  400. }
  401. }
  402. // transfer in control edges to all root nodes
  403. for (auto &root_node : root_nodes) {
  404. auto in_nodes = root_node->GetInAllNodes();
  405. std::set<NodePtr> in_node_set(in_nodes.begin(), in_nodes.end());
  406. for (auto &in_control_node : wrapped_node->GetInControlNodes()) {
  407. if (in_node_set.count(in_control_node) == 0) {
  408. GELOGD("[%s] Restore control edge to [%s]", in_control_node->GetName().c_str(), root_node->GetName().c_str());
  409. GE_CHECK_NOTNULL(in_control_node->GetOutControlAnchor());
  410. (void) in_control_node->GetOutControlAnchor()->LinkTo(root_node->GetInControlAnchor());
  411. }
  412. }
  413. }
  414. wrapped_node->GetInControlAnchor()->UnlinkAll();
  415. return SUCCESS;
  416. }
  417. Status HybridModelBuilder::MergeNetOutputNode(ComputeGraph &graph) {
  418. const auto &parent_node = graph.GetParentNode();
  419. const NodePtr &net_output_node = graph.FindFirstNodeMatchType(NETOUTPUT);
  420. if (net_output_node == nullptr) {
  421. GELOGD("Graph has no netoutput no need to merge.");
  422. return SUCCESS;
  423. }
  424. const auto &net_output_desc = net_output_node->GetOpDesc();
  425. GE_CHECK_NOTNULL(net_output_desc);
  426. auto all_in_nodes = net_output_node->GetInAllNodes();
  427. auto all_out_nodes = parent_node->GetOutAllNodes();
  428. net_output_node->GetInControlAnchor()->UnlinkAll();
  429. parent_node->GetOutControlAnchor()->UnlinkAll();
  430. for (const auto &in_data_anchor : net_output_node->GetAllInDataAnchors()) {
  431. auto src_out_anchor = in_data_anchor->GetPeerOutAnchor();
  432. GE_CHECK_NOTNULL(src_out_anchor);
  433. GE_CHECK_NOTNULL(src_out_anchor->GetOwnerNode());
  434. GE_CHK_STATUS_RET_NOLOG(DoUnlinkDataAnchors(src_out_anchor, in_data_anchor));
  435. auto index = in_data_anchor->GetIdx();
  436. auto input_desc = net_output_desc->MutableInputDesc(index);
  437. if (input_desc == nullptr) {
  438. GELOGE(INTERNAL_ERROR, "[%s] Failed to get input desc[%d]", net_output_desc->GetName().c_str(), index);
  439. return INTERNAL_ERROR;
  440. }
  441. uint32_t parent_index = 0;
  442. if (!AttrUtils::GetInt(input_desc, ATTR_NAME_PARENT_NODE_INDEX, parent_index)) {
  443. GELOGW("SubGraph: %s NetOutput input tensor %d, attr %s not found.",
  444. graph.GetName().c_str(), index, ATTR_NAME_PARENT_NODE_INDEX.c_str());
  445. continue;
  446. }
  447. const OutDataAnchorPtr &parent_out_anchor = parent_node->GetOutDataAnchor(parent_index);
  448. GE_CHECK_NOTNULL(parent_out_anchor);
  449. for (InDataAnchorPtr &dst_in_anchor : parent_out_anchor->GetPeerInDataAnchors()) {
  450. if (dst_in_anchor == nullptr) {
  451. continue;
  452. }
  453. GE_CHECK_NOTNULL(dst_in_anchor->GetOwnerNode());
  454. GE_CHK_STATUS_RET_NOLOG(DoUnlinkDataAnchors(parent_out_anchor, dst_in_anchor));
  455. GE_CHK_STATUS_RET_NOLOG(DoLinkDataAnchors(src_out_anchor, dst_in_anchor));
  456. }
  457. }
  458. // transfer out control edges
  459. std::set<NodePtr> in_node_set(all_in_nodes.begin(), all_in_nodes.end());
  460. std::set<NodePtr> out_node_set(all_out_nodes.begin(), all_out_nodes.end());
  461. for (auto &src_node : in_node_set) {
  462. GELOGD("[%s] process in node.", src_node->GetName().c_str());
  463. auto out_nodes = src_node->GetOutAllNodes();
  464. std::set<NodePtr> node_set(out_nodes.begin(), out_nodes.end());
  465. for (auto &dst_node : out_node_set) {
  466. if (node_set.count(dst_node) == 0) {
  467. src_node->GetOutControlAnchor()->LinkTo(dst_node->GetInControlAnchor());
  468. GELOGD("[%s] Restore control edge to [%s]", src_node->GetName().c_str(), dst_node->GetName().c_str());
  469. }
  470. }
  471. }
  472. return SUCCESS;
  473. }
  474. Status HybridModelBuilder::UnfoldSubgraphs(ComputeGraph &root_graph, ComputeGraphPtr &merged_graph) {
  475. merged_graph = MakeShared<ComputeGraph>("MergedGraph");
  476. for (const auto &node : root_graph.GetDirectNode()) {
  477. GE_CHECK_NOTNULL(node);
  478. auto op_desc = node->GetOpDesc();
  479. GE_CHECK_NOTNULL(op_desc);
  480. const auto &op_type = node->GetType();
  481. if (op_type != PARTITIONEDCALL) {
  482. merged_graph->AddNode(node);
  483. GELOGD("[%s] Node added to merged graph.", op_desc->GetName().c_str());
  484. continue;
  485. }
  486. auto subgraph = NodeUtils::GetSubgraph(*node, kSubgraphIndex);
  487. GE_CHECK_NOTNULL(subgraph);
  488. bool is_unknown_shape = subgraph->GetGraphUnknownFlag();
  489. if (!is_unknown_shape) {
  490. merged_graph->AddNode(node);
  491. GELOGD("[%s] Known shape partitioned call added to merged graph.", op_desc->GetName().c_str());
  492. continue;
  493. }
  494. GE_CHK_GRAPH_STATUS_RET(UnfoldSubgraph(root_graph, *merged_graph, *subgraph),
  495. "[%s] Failed to merge subgraph.",
  496. subgraph->GetName().c_str());
  497. }
  498. // invoke before adding subgraphs. in case modify node id in known-shaped subgraphs.
  499. GE_CHK_GRAPH_STATUS_RET(merged_graph->TopologicalSorting(), "Failed to invoke TopologicalSorting on merged graph.");
  500. for (auto &remained_subgraph : root_graph.GetAllSubgraphs()) {
  501. GELOGD("Adding subgraph [%s] to merged-graph.", remained_subgraph->GetName().c_str());
  502. GE_CHK_GRAPH_STATUS_RET(merged_graph->AddSubgraph(remained_subgraph),
  503. "Failed to add subgraph [%s]",
  504. remained_subgraph->GetName().c_str());
  505. }
  506. return SUCCESS;
  507. }
  508. Status HybridModelBuilder::UnfoldSubgraph(ComputeGraph &root_graph,
  509. ComputeGraph &parent_graph,
  510. ComputeGraph &sub_graph) {
  511. auto parent_node = sub_graph.GetParentNode();
  512. GE_CHECK_NOTNULL(parent_node);
  513. GE_CHK_STATUS_RET(MergeInputNodes(sub_graph),
  514. "[%s] Failed to merge data nodes for subgraph",
  515. sub_graph.GetName().c_str());
  516. GE_CHK_STATUS_RET(MergeNetOutputNode(sub_graph),
  517. "[%s] Failed to merge net output nodes for subgraph",
  518. sub_graph.GetName().c_str());
  519. GELOGD("[%s] Done merging subgraph inputs and outputs successfully.", sub_graph.GetName().c_str());
  520. for (auto &sub_node : sub_graph.GetDirectNode()) {
  521. auto sub_op_type = sub_node->GetType();
  522. if (sub_op_type == DATA_TYPE || sub_op_type == NETOUTPUT) {
  523. continue;
  524. }
  525. if (sub_op_type == PARTITIONEDCALL) {
  526. auto sub_sub_graph = NodeUtils::GetSubgraph(*sub_node, kSubgraphIndex);
  527. GE_CHECK_NOTNULL(sub_sub_graph);
  528. if (sub_sub_graph->GetGraphUnknownFlag()) {
  529. GE_CHK_STATUS_RET(UnfoldSubgraph(root_graph, parent_graph, *sub_sub_graph),
  530. "[%s] Failed to merge subgraph",
  531. sub_sub_graph->GetName().c_str());
  532. continue;
  533. }
  534. }
  535. parent_graph.AddNode(sub_node);
  536. GELOGD("[%s::%s] added to parent graph: [%s].",
  537. sub_graph.GetName().c_str(),
  538. sub_node->GetName().c_str(),
  539. parent_graph.GetName().c_str());
  540. }
  541. GELOGD("[%s] Done merging subgraph. remove it from root graph.", sub_graph.GetName().c_str());
  542. root_graph.RemoveSubgraph(sub_graph.GetName());
  543. return SUCCESS;
  544. }
  545. Status HybridModelBuilder::BuildOutputMapping(GraphItem &graph_item,
  546. const NodeItem &node_item,
  547. bool is_root_graph) {
  548. auto output_size = node_item.num_inputs;
  549. graph_item.output_edges_.resize(output_size);
  550. for (auto &in_data_anchor : node_item.node->GetAllInDataAnchors()) {
  551. auto peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  552. GE_CHECK_NOTNULL(peer_out_anchor);
  553. auto src_node = peer_out_anchor->GetOwnerNode();
  554. GE_CHECK_NOTNULL(src_node);
  555. auto src_node_item = GetNodeItem(src_node);
  556. GE_CHECK_NOTNULL(src_node_item);
  557. auto output_idx = in_data_anchor->GetIdx();
  558. auto output_offset = src_node_item->output_start + peer_out_anchor->GetIdx();
  559. GELOGI("Output[%d], node = %s, output_index = %d, output_offset = %d ",
  560. output_idx,
  561. src_node_item->NodeName().c_str(),
  562. peer_out_anchor->GetIdx(),
  563. output_offset);
  564. GE_CHECK_LE(output_idx, output_size - 1);
  565. graph_item.output_edges_[output_idx] = {src_node_item, peer_out_anchor->GetIdx()};
  566. }
  567. if (!is_root_graph) {
  568. for (uint32_t i = 0; i < static_cast<uint32_t>(output_size); ++i) {
  569. uint32_t p_index = i;
  570. // Net output of Subgraph of while do not have parent index
  571. if (AttrUtils::GetInt(node_item.op_desc->GetInputDesc(i), ATTR_NAME_PARENT_NODE_INDEX, p_index)) {
  572. GELOGD("[%s] Parent index not set for input[%u].", node_item.NodeName().c_str(), i);
  573. }
  574. graph_item.output_index_mapping_.emplace_back(p_index);
  575. }
  576. }
  577. return SUCCESS;
  578. }
  579. Status HybridModelBuilder::LoadGraph() {
  580. auto root_graph = ge_root_model_->GetRootGraph();
  581. if (!GetContext().GetHostExecFlag()) {
  582. std::shared_ptr<ComputeGraph> merged_graph;
  583. GELOGI("Before merging subgraphs DirectNodesSize = %zu, GetAllNodesSize = %zu",
  584. root_graph->GetDirectNodesSize(),
  585. root_graph->GetAllNodesSize());
  586. GE_CHK_GRAPH_STATUS_RET(UnfoldSubgraphs(*root_graph, merged_graph), "Failed to unfold subgraphs.");
  587. root_graph = std::move(merged_graph);
  588. GELOGI("After merging subgraphs DirectNodesSize = %zu, GetAllNodesSize = %zu",
  589. root_graph->GetDirectNodesSize(),
  590. root_graph->GetAllNodesSize());
  591. GE_DUMP(root_graph, "hybrid_merged_graph");
  592. }
  593. GE_CHK_STATUS_RET(LoadDynamicSubgraph(*root_graph, true), "Failed to load root graph.");
  594. GELOGD("Done loading root graph successfully.");
  595. for (auto &sub_graph : root_graph->GetAllSubgraphs()) {
  596. GE_CHECK_NOTNULL(sub_graph);
  597. GELOGD("Start to load subgraph [%s]", sub_graph->GetName().c_str());
  598. auto parent_node = sub_graph->GetParentNode();
  599. GE_CHECK_NOTNULL(parent_node);
  600. auto parent_node_item = MutableNodeItem(parent_node);
  601. // parent node is in another known subgraph
  602. if (parent_node_item == nullptr) {
  603. GELOGD("[%s] Subgraph is in another known shaped subgraph, skip it.", sub_graph->GetName().c_str());
  604. continue;
  605. }
  606. if (sub_graph->GetGraphUnknownFlag()) {
  607. GE_CHK_STATUS_RET(LoadDynamicSubgraph(*sub_graph, false),
  608. "Failed to load subgraph: [%s]",
  609. sub_graph->GetName().c_str());
  610. } else {
  611. GE_CHK_STATUS_RET(IdentifyVariableOutputs(*parent_node_item),
  612. "[%s] Failed to identify ref outputs.",
  613. parent_node_item->NodeName().c_str());
  614. GE_CHK_STATUS_RET(IdentifySameInputs(*parent_node_item),
  615. "[%s] Failed to identify same outputs.",
  616. parent_node_item->NodeName().c_str());
  617. // if parent is function control op. need add a virtual partitioned call
  618. if (parent_node_item->IsControlOp()) {
  619. GE_CHK_STATUS_RET(LoadKnownShapedSubgraph(*sub_graph, parent_node_item),
  620. "Failed to load function control op subgraph [%s]",
  621. sub_graph->GetName().c_str());
  622. }
  623. }
  624. }
  625. GELOGI("Done loading all subgraphs successfully.");
  626. return SUCCESS;
  627. }
  628. const NodeItem *HybridModelBuilder::GetNodeItem(const NodePtr &node) const {
  629. return hybrid_model_.GetNodeItem(node);
  630. }
  631. NodeItem *HybridModelBuilder::MutableNodeItem(const NodePtr &node) {
  632. return hybrid_model_.MutableNodeItem(node);
  633. }
  634. Status HybridModelBuilder::VarNodeToTensor(const NodePtr &var_node, std::unique_ptr<TensorValue> &tensor) {
  635. string var_name = var_node->GetName();
  636. auto tensor_desc = var_node->GetOpDesc()->MutableOutputDesc(0);
  637. uint8_t *var_logic = nullptr;
  638. GE_CHK_STATUS_RET(var_manager_->GetVarAddr(var_name, *tensor_desc, &var_logic),
  639. "Failed to get var addr. var_name = %s, session_id = %ld",
  640. var_name.c_str(),
  641. hybrid_model_.GetSessionId());
  642. uint8_t *dev_mem = var_manager_->GetVarMemoryAddr(var_logic, RT_MEMORY_HBM);
  643. if (dev_mem == nullptr) {
  644. GELOGE(INTERNAL_ERROR,
  645. "Failed to copy var %s from device, cant not get "
  646. "var addr from logic addr %p",
  647. var_node->GetName().c_str(), var_logic);
  648. return INTERNAL_ERROR;
  649. }
  650. int64_t var_size = CalcVarSizeInBytes(*tensor_desc);
  651. // var size is only for checking, will not allocate any memory by it
  652. tensor.reset(new(std::nothrow)TensorValue(dev_mem, static_cast<size_t>(var_size)));
  653. GE_CHECK_NOTNULL(tensor);
  654. return SUCCESS;
  655. }
  656. Status HybridModelBuilder::HandleDtString(const GeTensor &tensor, void *var_addr) {
  657. auto desc = tensor.GetTensorDesc();
  658. if (desc.GetDataType() == DT_STRING) {
  659. GeShape tensor_shape = desc.GetShape();
  660. /// if tensor is a scaler, it's shape size if zero, according ge_tensor.cc.
  661. /// the logic of GetShapeSize is wrong, the scaler tensor's GetShapeSize is zero
  662. /// and that of unknown shape is zero too.
  663. /// unknown shape will not appear here, so we can use zero judge a tensor is scalar or not
  664. int64_t elem_num = tensor_shape.GetShapeSize();
  665. if (elem_num == 0 && tensor_shape.GetDims().empty()) {
  666. elem_num = 1;
  667. }
  668. auto &mutable_tensor = const_cast<GeTensor &>(tensor);
  669. uint64_t *buff = reinterpret_cast<uint64_t *>(mutable_tensor.MutableData().data());
  670. GE_CHK_BOOL_RET_STATUS(ge::CheckInt64Uint32MulOverflow(elem_num, kBytes) == SUCCESS, FAILED,
  671. "Shape size is invalid");
  672. auto offset = static_cast<uint64_t>(elem_num * kBytes);
  673. auto hbm_raw_data_base_addr =
  674. reinterpret_cast<uint64_t>(reinterpret_cast<uintptr_t>(var_addr) + offset);
  675. for (int64_t i = elem_num - 1; i >= 0; --i) {
  676. buff[i] = hbm_raw_data_base_addr + (buff[i] - buff[0]);
  677. }
  678. }
  679. return SUCCESS;
  680. }
  681. Status HybridModelBuilder::AssignUninitializedConstantOps() {
  682. if (GetContext().GetHostExecFlag()) {
  683. GELOGI("no need to assign when exec on host.");
  684. return SUCCESS;
  685. }
  686. for (auto &it : hybrid_model_.constant_op_nodes_) {
  687. const string &var_name = it.first;
  688. const NodePtr &var_node = it.second;
  689. auto tensor_desc = var_node->GetOpDesc()->MutableOutputDesc(0);
  690. if (!var_manager_->IsVarExist(var_name, *tensor_desc)) {
  691. // allocate constant
  692. GELOGD("[%s] Constant not allocated during graph building. now allocate it.", var_name.c_str());
  693. GE_CHK_STATUS_RET(var_manager_->AssignVarMem(var_name, *tensor_desc, RT_MEMORY_HBM));
  694. GE_CHK_STATUS_RET(var_manager_->SetAllocatedGraphId(var_name, runtime_param_.graph_id));
  695. }
  696. }
  697. for (auto &it : hybrid_model_.device_variable_nodes_) {
  698. const string &var_name = it.first;
  699. const NodePtr &var_node = it.second;
  700. auto tensor_desc = var_node->GetOpDesc()->MutableOutputDesc(0);
  701. if (!var_manager_->IsVarExist(var_name, *tensor_desc)) {
  702. // allocate constant
  703. GELOGD("[%s] Constant not allocated during graph building. now allocate it.", var_name.c_str());
  704. GE_CHK_STATUS_RET(var_manager_->AssignVarMem(var_name, *tensor_desc, RT_MEMORY_HBM));
  705. GE_CHK_STATUS_RET(VarMemAssignUtil::AssignData2Fp32Var(var_node, runtime_param_.session_id))
  706. GE_CHK_STATUS_RET(var_manager_->SetAllocatedGraphId(var_name, runtime_param_.graph_id));
  707. }
  708. }
  709. return SUCCESS;
  710. }
  711. Status HybridModelBuilder::InitConstantOps() {
  712. for (auto &it : hybrid_model_.constant_op_nodes_) {
  713. const string &var_name = it.first;
  714. const NodePtr &var_node = it.second;
  715. auto op_desc = var_node->GetOpDesc();
  716. auto v_weights = ModelUtils::GetWeights(op_desc);
  717. if (v_weights.empty()) {
  718. GELOGE(INTERNAL_ERROR, "[%s] Constant no not have value", var_node->GetName().c_str());
  719. return INTERNAL_ERROR;
  720. }
  721. auto *ge_tensor = const_cast<GeTensor *>(v_weights[0].get());
  722. std::unique_ptr<TensorValue> var_tensor;
  723. if (GetContext().GetHostExecFlag()) {
  724. auto buffer = ge_tensor->MutableData();
  725. GELOGD("Init tensor with host constant. size = %zu", buffer.GetSize());
  726. var_tensor.reset(new(std::nothrow)TensorValue(buffer.GetData(), buffer.GetSize()));
  727. } else {
  728. GE_CHK_STATUS_RET_NOLOG(VarNodeToTensor(var_node, var_tensor));
  729. GELOGD("Init const op tensor. name = %s, size = %ld", var_name.c_str(), var_tensor->GetSize());
  730. var_tensor->SetName("ConstOp_" + var_name);
  731. auto v_output_size = var_tensor->GetSize();
  732. auto v_output_addr = var_tensor->MutableData();
  733. if (ge_tensor->GetData().size() > 0) {
  734. GE_CHK_STATUS_RET_NOLOG(HandleDtString(*ge_tensor, v_output_addr));
  735. GELOGI("[IMAS]InitConstant memcpy graph_%u type[V] name[%s] output[%d] memaddr[%p] mem_size[%zu] datasize[%zu]",
  736. runtime_param_.graph_id, op_desc->GetName().c_str(), 0, v_output_addr, v_output_size,
  737. ge_tensor->GetData().size());
  738. GE_CHK_RT_RET(rtMemcpy(v_output_addr, v_output_size, ge_tensor->GetData().data(), ge_tensor->GetData().size(),
  739. RT_MEMCPY_HOST_TO_DEVICE));
  740. } else {
  741. GELOGI("[%s] Const op has no weight data.", op_desc->GetName().c_str());
  742. }
  743. }
  744. hybrid_model_.variable_tensors_.emplace(var_name, std::move(var_tensor));
  745. }
  746. return SUCCESS;
  747. }
  748. Status HybridModelBuilder::InitVariableTensors() {
  749. for (auto &it : hybrid_model_.device_variable_nodes_) {
  750. string var_name = it.first;
  751. NodePtr &var_node = it.second;
  752. std::unique_ptr<TensorValue> tensor;
  753. GE_CHK_STATUS_RET_NOLOG(VarNodeToTensor(var_node, tensor));
  754. GELOGD("Init variable tensor. name = %s, size = %ld, addr = %p",
  755. var_name.c_str(),
  756. tensor->GetSize(),
  757. tensor->GetData());
  758. tensor->SetName("Var_" + var_name);
  759. hybrid_model_.variable_tensors_.emplace(var_name, std::move(tensor));
  760. }
  761. for (const auto &it : hybrid_model_.host_variable_nodes_) {
  762. auto op_desc = it.second->GetOpDesc();
  763. GE_CHECK_NOTNULL(op_desc);
  764. GeTensorDesc output_tensor = op_desc->GetOutputDesc(0);
  765. int64_t tensor_size = 0;
  766. if (TensorUtils::CalcTensorMemSize(output_tensor.GetShape(), output_tensor.GetFormat(), output_tensor.GetDataType(),
  767. tensor_size) != SUCCESS) {
  768. GELOGE(INTERNAL_ERROR, "Calculate variable size failed, node name:%s", it.first.c_str());
  769. return INTERNAL_ERROR;
  770. }
  771. SharedMemInfo mem_info(it.first, tensor_size);
  772. if (HostMemManager::Instance().MallocSharedMemory(mem_info) != SUCCESS) {
  773. GELOGE(GE_GRAPH_MALLOC_FAILED, "Host variable [%s] malloc failed.", it.first.c_str());
  774. return GE_GRAPH_MALLOC_FAILED;
  775. }
  776. GELOGD("Host variable [%s] malloc success.", it.first.c_str());
  777. std::unique_ptr<TensorValue> tensor(new (std::nothrow) TensorValue(mem_info.host_address, tensor_size));
  778. GE_CHECK_NOTNULL(tensor);
  779. hybrid_model_.variable_tensors_.emplace(it.first, std::move(tensor));
  780. }
  781. return SUCCESS;
  782. }
  783. Status HybridModelBuilder::InitWeights() {
  784. // Train do not have weight. (only got ConstOp)
  785. return SUCCESS;
  786. }
  787. Status HybridModelBuilder::LoadTasks() {
  788. for (auto &it : hybrid_model_.node_items_) {
  789. auto &node_item = it.second;
  790. auto &node_ptr = node_item->node;
  791. if (node_item->node_type == NETOUTPUT) {
  792. continue;
  793. }
  794. GELOGD("[%s] Start to build kernel task", node_ptr->GetName().c_str());
  795. auto load_ret = node_item->node_executor->LoadTask(hybrid_model_,
  796. node_ptr,
  797. node_item->kernel_task);
  798. if (load_ret != UNSUPPORTED && load_ret != SUCCESS) {
  799. GELOGE(load_ret, "[%s] Failed to load task", node_ptr->GetName().c_str());
  800. return load_ret;
  801. }
  802. GELOGD("[%s] Done loading task successfully.", node_ptr->GetName().c_str());
  803. }
  804. return SUCCESS;
  805. }
  806. Status HybridModelBuilder::LoadGeModel(ComputeGraph &sub_graph, const GeModelPtr &ge_model) {
  807. auto parent_node = sub_graph.GetParentNode();
  808. GE_CHECK_NOTNULL(parent_node);
  809. auto op_type = parent_node->GetType();
  810. if (IsControlOp(op_type)) {
  811. GELOGD("Set ge_model for control op subgraph: [%s], task_size = %d",
  812. sub_graph.GetName().c_str(),
  813. ge_model->GetModelTaskDefPtr()->task_size());
  814. subgraph_models_.emplace(sub_graph.GetName(), ge_model);
  815. } else {
  816. GELOGD("Set ge_model for subgraph: [%s], task_size = %d",
  817. sub_graph.GetName().c_str(),
  818. ge_model->GetModelTaskDefPtr()->task_size());
  819. hybrid_model_.known_shape_sub_models_.emplace(parent_node, ge_model);
  820. }
  821. return SUCCESS;
  822. }
  823. Status HybridModelBuilder::IndexTaskDefs() {
  824. const auto &root_graph = ge_root_model_->GetRootGraph();
  825. for (auto &it : ge_root_model_->GetSubgraphInstanceNameToModel()) {
  826. auto &name = it.first;
  827. auto &ge_model = it.second;
  828. GE_CHECK_NOTNULL(ge_model);
  829. const auto &sub_graph = root_graph->GetSubgraph(name);
  830. if (sub_graph == nullptr) {
  831. continue;
  832. }
  833. bool is_unknown_shape = sub_graph->GetGraphUnknownFlag();
  834. if (!is_unknown_shape) {
  835. GE_CHK_STATUS_RET_NOLOG(LoadGeModel(*sub_graph, ge_model));
  836. continue;
  837. }
  838. // index task defs
  839. GELOGD("To index tasks for subgraph: %s", name.c_str());
  840. unordered_map<int64_t, NodePtr> node_map;
  841. for (const auto &node : sub_graph->GetDirectNode()) {
  842. GE_CHECK_NOTNULL(node);
  843. GE_CHECK_NOTNULL(node->GetOpDesc());
  844. auto node_id = node->GetOpDesc()->GetId();
  845. GELOGD("op_index = %ld, node_name = %s", node_id, node->GetName().c_str());
  846. node_map.emplace(node_id, node);
  847. }
  848. auto tasks = ge_model->GetModelTaskDefPtr()->task();
  849. for (int i = 0; i < tasks.size(); ++i) {
  850. const domi::TaskDef &task_def = tasks[i];
  851. GELOGI("Task id = %d, task type = %d", i, task_def.type());
  852. auto task_type = static_cast<rtModelTaskType_t>(task_def.type());
  853. uint32_t op_index = -1;
  854. if (task_type == RT_MODEL_TASK_KERNEL) {
  855. op_index = task_def.kernel().context().op_index();
  856. } else if (task_type == RT_MODEL_TASK_KERNEL_EX) {
  857. op_index = task_def.kernel_ex().op_index();
  858. } else if (task_type == RT_MODEL_TASK_HCCL) {
  859. op_index = task_def.kernel_hccl().op_index();
  860. } else {
  861. GELOGD("Skip task type: %d", static_cast<int>(task_type));
  862. continue;
  863. }
  864. auto iter = node_map.find(op_index);
  865. if (iter == node_map.end()) {
  866. GELOGE(INTERNAL_ERROR, "Failed to get node by index = %u", op_index);
  867. return INTERNAL_ERROR;
  868. }
  869. auto &node = iter->second;
  870. if (task_type == RT_MODEL_TASK_KERNEL) {
  871. ge_model->GetTBEKernelStore().LoadTBEKernelBinToOpDesc(node->GetOpDesc());
  872. }
  873. GELOGD("Task loaded for node: %s, task type = %d, op_index = %u", node->GetName().c_str(), task_type, op_index);
  874. hybrid_model_.task_defs_[node].emplace_back(task_def);
  875. }
  876. }
  877. return SUCCESS;
  878. }
  879. Status HybridModelBuilder::IndexSpecialNodes() {
  880. GELOGD("Start to index special nodes");
  881. const auto &root_graph = ge_root_model_->GetRootGraph();
  882. for (auto &node : root_graph->GetAllNodes()) {
  883. GE_CHECK_NOTNULL(node);
  884. GE_CHECK_NOTNULL(node->GetOpDesc());
  885. auto op_type = node->GetType();
  886. GELOGD("node name = %s, node type = %s", node->GetName().c_str(), node->GetType().c_str());
  887. if (op_type == VARIABLE) {
  888. string placement;
  889. (void) AttrUtils::GetStr(node->GetOpDesc(), ATTR_VARIABLE_PLACEMENT, placement);
  890. if (placement == "host") {
  891. hybrid_model_.host_variable_nodes_.emplace(node->GetName(), node);
  892. } else {
  893. hybrid_model_.device_variable_nodes_.emplace(node->GetName(), node);
  894. }
  895. } else if (op_type == CONSTANTOP) {
  896. hybrid_model_.constant_op_nodes_.emplace(node->GetName(), node);
  897. } else if (op_type == DATA && node->GetOwnerComputeGraph() != root_graph) {
  898. NodePtr src_node;
  899. int peer_out_index = -1;
  900. GE_CHK_STATUS_RET_NOLOG(GetPeerNodeAcrossSubGraphs(node, src_node, peer_out_index));
  901. GELOGD("Got peer node for data node %s, peer node = %s(%s)",
  902. node->GetName().c_str(),
  903. src_node->GetName().c_str(),
  904. src_node->GetType().c_str());
  905. auto src_op_type = src_node->GetType();
  906. if (src_op_type == CONSTANTOP || src_op_type == VARIABLE) {
  907. for (auto &dst_node_and_in_anchor : node->GetOutDataNodesAndAnchors()) {
  908. auto &dst_node = dst_node_and_in_anchor.first;
  909. auto &in_anchor = dst_node_and_in_anchor.second;
  910. node_ref_inputs_[dst_node].emplace_back(std::make_pair(in_anchor->GetIdx(), src_node));
  911. }
  912. }
  913. }
  914. }
  915. return SUCCESS;
  916. }
  917. Status HybridModelBuilder::GetPeerNodeAcrossSubGraphs(const NodePtr &data_node,
  918. NodePtr &peer_node,
  919. int &peer_out_index) {
  920. auto sub_graph = data_node->GetOwnerComputeGraph();
  921. GE_CHECK_NOTNULL(sub_graph);
  922. GELOGD("To get peer node of %s::%s", sub_graph->GetName().c_str(), data_node->GetName().c_str());
  923. auto wrapped_node = data_node->GetOwnerComputeGraph()->GetParentNode();
  924. if (wrapped_node == nullptr) {
  925. GELOGE(INTERNAL_ERROR, "[%s] Node is in root graph.", data_node->GetName().c_str());
  926. return INTERNAL_ERROR;
  927. }
  928. auto data_op_desc = data_node->GetOpDesc();
  929. uint32_t parent_index = 0;
  930. if (!AttrUtils::GetInt(data_op_desc, ATTR_NAME_PARENT_NODE_INDEX, parent_index)) {
  931. GELOGE(INTERNAL_ERROR,
  932. "[%s] Failed to get attr [%s]",
  933. data_op_desc->GetName().c_str(),
  934. ATTR_NAME_PARENT_NODE_INDEX.c_str());
  935. return INTERNAL_ERROR;
  936. }
  937. auto wrapped_node_in_anchor = wrapped_node->GetInDataAnchor(parent_index);
  938. GE_CHECK_NOTNULL(wrapped_node_in_anchor);
  939. auto src_out_anchor = wrapped_node_in_anchor->GetPeerOutAnchor();
  940. if (src_out_anchor == nullptr || src_out_anchor->GetOwnerNode() == nullptr) {
  941. GELOGE(INTERNAL_ERROR, "[%s] Parent node do not have peer anchor.", data_node->GetName().c_str());
  942. return INTERNAL_ERROR;
  943. }
  944. auto src_wrapped_node_out_anchor = wrapped_node_in_anchor->GetPeerOutAnchor();
  945. GE_CHECK_NOTNULL(src_wrapped_node_out_anchor);
  946. auto src_wrapped_node = src_wrapped_node_out_anchor->GetOwnerNode();
  947. GE_CHECK_NOTNULL(src_wrapped_node);
  948. // connected to root-graph's DATA
  949. auto src_node_type = src_wrapped_node->GetType();
  950. if (src_node_type != PARTITIONEDCALL) {
  951. peer_node = src_wrapped_node;
  952. peer_out_index = kVarOutputIndex;
  953. GELOGD("[%s] Node is connected to root graph's node: %s",
  954. data_node->GetName().c_str(),
  955. peer_node->GetName().c_str());
  956. return SUCCESS;
  957. }
  958. auto src_graph = NodeUtils::GetSubgraph(*src_wrapped_node, kSubgraphIndex);
  959. GE_CHECK_NOTNULL(src_graph);
  960. auto src_net_output_node = src_graph->FindFirstNodeMatchType(NETOUTPUT);
  961. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(src_net_output_node == nullptr,
  962. return INTERNAL_ERROR,
  963. "Failed to find NetOutput in subgraph: %s",
  964. src_graph->GetName().c_str());
  965. auto net_output_desc = src_net_output_node->GetOpDesc();
  966. GE_CHECK_NOTNULL(net_output_desc);
  967. auto out_index = static_cast<uint32_t>(src_wrapped_node_out_anchor->GetIdx());
  968. GELOGD("src graph = %s, src parent output index = %u", src_graph->GetName().c_str(), out_index);
  969. // link src to outputs of DataNode
  970. auto input_size = net_output_desc->GetAllInputsSize();
  971. GE_CHECK_LE(input_size, UINT32_MAX);
  972. for (uint32_t i = 0; i < static_cast<uint32_t>(input_size); ++i) {
  973. uint32_t p_index = 0;
  974. if (!AttrUtils::GetInt(net_output_desc->GetInputDesc(i), ATTR_NAME_PARENT_NODE_INDEX, p_index)) {
  975. GELOGW("SubGraph: %s input tensor %u attr %s not found.",
  976. src_graph->GetName().c_str(), i, ATTR_NAME_PARENT_NODE_INDEX.c_str());
  977. continue;
  978. }
  979. GELOGD("NetOutput's input[%u], parent_node_index = %u", i, p_index);
  980. if (p_index == out_index) {
  981. auto in_anchor = src_net_output_node->GetInDataAnchor(i);
  982. GE_CHECK_NOTNULL(in_anchor);
  983. auto peer_out_anchor = in_anchor->GetPeerOutAnchor();
  984. GE_CHECK_NOTNULL(peer_out_anchor);
  985. peer_node = peer_out_anchor->GetOwnerNode();
  986. GE_CHECK_NOTNULL(peer_node);
  987. peer_out_index = peer_out_anchor->GetIdx();
  988. GELOGD("Found peer node of Data node: %s::%s is %s::%s",
  989. sub_graph->GetName().c_str(),
  990. data_node->GetName().c_str(),
  991. src_graph->GetName().c_str(),
  992. peer_node->GetName().c_str());
  993. return SUCCESS;
  994. }
  995. }
  996. GELOGE(FAILED,
  997. "Failed to find peer node for %s::%s",
  998. sub_graph->GetName().c_str(),
  999. data_node->GetName().c_str());
  1000. return FAILED;
  1001. }
  1002. Status HybridModelBuilder::InitRuntimeParams() {
  1003. int64_t value = 0;
  1004. bool ret = false;
  1005. if (ge_root_model_->GetSubgraphInstanceNameToModel().empty()) {
  1006. GELOGE(INTERNAL_ERROR, "Root model has no sub model");
  1007. return INTERNAL_ERROR;
  1008. }
  1009. // session id and var size is same for every model
  1010. auto first_model = ge_root_model_->GetSubgraphInstanceNameToModel().begin()->second;
  1011. ret = ge::AttrUtils::GetInt(first_model, ge::MODEL_ATTR_SESSION_ID, value);
  1012. runtime_param_.session_id = ret ? static_cast<uint64_t>(value) : 0;
  1013. ret = ge::AttrUtils::GetInt(first_model, ATTR_MODEL_TASK_GEN_VAR_ADDR, value);
  1014. runtime_param_.logic_var_base = ret ? static_cast<uint64_t>(value) : 0;
  1015. runtime_param_.graph_id = ge_root_model_->GetRootGraph()->GetGraphID();
  1016. value = 0;
  1017. for (auto &it : ge_root_model_->GetSubgraphInstanceNameToModel()) {
  1018. (void) ge::AttrUtils::GetInt(it.second, ATTR_MODEL_VAR_SIZE, value);
  1019. if (value > 0) {
  1020. runtime_param_.var_size = static_cast<uint64_t>(value);
  1021. break;
  1022. }
  1023. }
  1024. GELOGI("InitRuntimeParams(), session_id:%lu, var_size:%lu. graph_id = %u",
  1025. runtime_param_.session_id, runtime_param_.var_size, runtime_param_.graph_id);
  1026. var_manager_ = VarManager::Instance(runtime_param_.session_id);
  1027. GE_CHECK_NOTNULL(var_manager_);
  1028. return SUCCESS;
  1029. }
  1030. Status HybridModelBuilder::IdentifySameInputs(NodeItem &node_item) {
  1031. GELOGD("Start to parse same inputs on net output: %s", node_item.NodeName().c_str());
  1032. auto subgraph = NodeUtils::GetSubgraph(*node_item.node, kSubgraphIndex);
  1033. GE_CHECK_NOTNULL(subgraph);
  1034. auto net_output_node = subgraph->FindFirstNodeMatchType(NETOUTPUT);
  1035. if (net_output_node == nullptr) {
  1036. GELOGD("Subgraph [%s] does not have net output", subgraph->GetName().c_str());
  1037. return SUCCESS;
  1038. }
  1039. auto net_output_desc = net_output_node->GetOpDesc();
  1040. GE_CHECK_NOTNULL(net_output_desc);
  1041. std::map<std::string, int> connected_inputs;
  1042. for (const auto &in_data_anchor : net_output_node->GetAllInDataAnchors()) {
  1043. auto out_data_anchor = in_data_anchor->GetPeerOutAnchor();
  1044. if (out_data_anchor == nullptr) {
  1045. continue;
  1046. }
  1047. auto src_node = out_data_anchor->GetOwnerNode();
  1048. GE_CHECK_NOTNULL(src_node);
  1049. auto op_desc = src_node->GetOpDesc();
  1050. GE_CHECK_NOTNULL(op_desc);
  1051. std::string input_key = std::to_string(op_desc->GetId()) + "_" + std::to_string(out_data_anchor->GetIdx());
  1052. auto it = connected_inputs.find(input_key);
  1053. if (it == connected_inputs.end()) {
  1054. connected_inputs.emplace(input_key, in_data_anchor->GetIdx());
  1055. } else {
  1056. GELOGD("[%s] output [%d] reuse output [%d] input node = %s, idx = %d.", node_item.NodeName().c_str(),
  1057. in_data_anchor->GetIdx(),
  1058. it->second,
  1059. src_node->GetName().c_str(),
  1060. out_data_anchor->GetIdx());
  1061. node_item.reuse_outputs.emplace(in_data_anchor->GetIdx(), it->second);
  1062. }
  1063. }
  1064. return SUCCESS;
  1065. }
  1066. Status HybridModelBuilder::IdentifyVariableOutputs(NodeItem &node_item) {
  1067. GELOGD("Start to parse outputs of node: %s", node_item.NodeName().c_str());
  1068. auto subgraph = NodeUtils::GetSubgraph(*node_item.node, kSubgraphIndex);
  1069. GE_CHECK_NOTNULL(subgraph);
  1070. auto net_output_node = subgraph->FindFirstNodeMatchType(NETOUTPUT);
  1071. if (net_output_node == nullptr) {
  1072. GELOGD("[%s] Subgraph do not got net output", subgraph->GetName().c_str());
  1073. return SUCCESS;
  1074. }
  1075. auto net_output_desc = net_output_node->GetOpDesc();
  1076. GE_CHECK_NOTNULL(net_output_desc);
  1077. // constant/variable connected to net output
  1078. for (const auto &in_data_anchor : net_output_node->GetAllInDataAnchors()) {
  1079. auto src_node = GetPeerNode(in_data_anchor);
  1080. GE_CHECK_NOTNULL(src_node);
  1081. auto src_op_type = src_node->GetType();
  1082. GELOGD("Node %s, output %d, src node = %s, src node type = %s",
  1083. node_item.NodeName().c_str(),
  1084. in_data_anchor->GetIdx(),
  1085. src_node->GetName().c_str(),
  1086. src_op_type.c_str());
  1087. if (src_op_type != CONSTANTOP && src_op_type != VARIABLE) {
  1088. continue;
  1089. }
  1090. uint32_t parent_index = 0;
  1091. GE_CHK_STATUS_RET_NOLOG(GetParentNodeOutputIndex(*net_output_desc, in_data_anchor->GetIdx(), parent_index));
  1092. GELOGD("Got parent output index = %u", parent_index);
  1093. GE_CHECK_LE(parent_index, INT32_MAX);
  1094. node_item.ref_outputs.emplace(static_cast<int>(parent_index), src_node);
  1095. }
  1096. // Data nodes marked with REF_VAR_SRC_VAR_NAME
  1097. // Using variable tensor as data's output
  1098. for (auto &node : subgraph->GetDirectNode()) {
  1099. if (node->GetType() != DATA) {
  1100. continue;
  1101. }
  1102. string ref_var_name;
  1103. (void) AttrUtils::GetStr(node->GetOpDesc(), REF_VAR_SRC_VAR_NAME, ref_var_name);
  1104. if (ref_var_name.empty()) {
  1105. continue;
  1106. }
  1107. GELOGD("Data node ref to variable: %s", ref_var_name.c_str());
  1108. NodePtr src_node;
  1109. auto var_node = hybrid_model_.GetVariableNode(ref_var_name);
  1110. GE_CHECK_NOTNULL(var_node);
  1111. GELOGD("Found var node [%s] by ref_var_name [%s]", var_node->GetName().c_str(), ref_var_name.c_str());
  1112. int peer_output_index = -1;
  1113. GE_CHK_STATUS_RET_NOLOG(GetPeerNodeAcrossSubGraphs(node, src_node, peer_output_index));
  1114. auto src_node_item = MutableNodeItem(src_node);
  1115. GE_CHECK_NOTNULL(src_node_item);
  1116. src_node_item->ref_outputs.emplace(peer_output_index, var_node);
  1117. }
  1118. return SUCCESS;
  1119. }
  1120. NodePtr HybridModelBuilder::GetPeerNode(const InDataAnchorPtr &in_data_anchor) {
  1121. auto peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  1122. if (peer_out_anchor != nullptr) {
  1123. return peer_out_anchor->GetOwnerNode();
  1124. }
  1125. return nullptr;
  1126. }
  1127. Status HybridModelBuilder::GetParentNodeOutputIndex(const OpDesc &op_desc, int index, uint32_t &out_index) {
  1128. auto input_desc = op_desc.MutableInputDesc(index);
  1129. GE_CHECK_NOTNULL(input_desc);
  1130. if (!AttrUtils::GetInt(input_desc, ATTR_NAME_PARENT_NODE_INDEX, out_index)) {
  1131. GELOGE(INTERNAL_ERROR, "NetOutput input tensor %d, attr %s not found.",
  1132. index, ATTR_NAME_PARENT_NODE_INDEX.c_str());
  1133. return INTERNAL_ERROR;
  1134. }
  1135. return SUCCESS;
  1136. }
  1137. Status HybridModelBuilder::InitModelMem() {
  1138. hybrid_model_.var_mem_base_ = var_manager_->GetVarMemoryBase(RT_MEMORY_HBM);
  1139. auto total_var_size = hybrid_model_.TotalVarMemSize();
  1140. if (total_var_size == 0 && !hybrid_model_.constant_op_nodes_.empty()) {
  1141. total_var_size = var_manager_->GetVarMemSize(RT_MEMORY_HBM) > 0 ? var_manager_->GetVarMemMaxSize() : 0;
  1142. GELOGD("Model var size = 0. but got uninitialized constant. set var size to %zu.", total_var_size);
  1143. }
  1144. if (total_var_size > 0 && hybrid_model_.var_mem_base_ == nullptr) {
  1145. GE_CHK_STATUS_RET(var_manager_->MallocVarMemory(total_var_size),
  1146. "Malloc Var Memory Fail.");
  1147. hybrid_model_.var_mem_base_ = var_manager_->GetVarMemoryBase(RT_MEMORY_HBM);
  1148. }
  1149. runtime_param_.var_base = hybrid_model_.var_mem_base_;
  1150. return SUCCESS;
  1151. }
  1152. Status HybridModelBuilder::TransAllVarData() {
  1153. GELOGI("TransAllVarData start: session_id:%lu, graph_id: %u.", runtime_param_.session_id, runtime_param_.graph_id);
  1154. rtContext_t ctx = nullptr;
  1155. rtError_t rt_ret = rtCtxGetCurrent(&ctx);
  1156. if (rt_ret != RT_ERROR_NONE) {
  1157. GELOGE(RT_FAILED, "Failed to get current context, error_code is: 0x%X.", rt_ret);
  1158. return RT_FAILED;
  1159. }
  1160. std::vector<NodePtr> variable_node_list;
  1161. for (auto &it : hybrid_model_.device_variable_nodes_) {
  1162. variable_node_list.emplace_back(it.second);
  1163. GELOGD("[%s] added for trans var data", it.first.c_str());
  1164. }
  1165. GE_CHK_STATUS_RET(TransVarDataUtils::TransAllVarData(variable_node_list,
  1166. runtime_param_.session_id,
  1167. ctx,
  1168. runtime_param_.graph_id),
  1169. "TransAllVarData failed.");
  1170. GELOGI("TransAllVarData success.");
  1171. return SUCCESS;
  1172. }
  1173. Status HybridModelBuilder::CopyVarData() {
  1174. GE_CHK_STATUS_RET(TransVarDataUtils::CopyVarData(ge_root_model_->GetRootGraph(),
  1175. runtime_param_.session_id,
  1176. hybrid_model_.device_id_),
  1177. "CopyVarData failed.");
  1178. GELOGI("CopyVarData success.");
  1179. return SUCCESS;
  1180. }
  1181. Status HybridModelBuilder::LoadKnownShapedSubgraph(ComputeGraph &graph, NodeItem *parent_node_item) {
  1182. GELOGD("Start to load known shaped subgraph [%s]", graph.GetName().c_str());
  1183. auto graph_item = std::unique_ptr<GraphItem>(new(std::nothrow)GraphItem());
  1184. GE_CHECK_NOTNULL(graph_item);
  1185. graph_item->is_dynamic_ = false;
  1186. auto subgraph_name = graph.GetName();
  1187. auto wrapper_op_desc = MakeShared<OpDesc>(subgraph_name + "_partitioned_call", PARTITIONEDCALL);
  1188. GE_CHECK_NOTNULL(wrapper_op_desc);
  1189. for (auto &node : graph.GetDirectNode()) {
  1190. GE_CHECK_NOTNULL(node);
  1191. auto op_desc = node->GetOpDesc();
  1192. GE_CHECK_NOTNULL(op_desc);
  1193. const auto &op_type = node->GetType();
  1194. if (op_type == DATA) {
  1195. int32_t data_index = 0;
  1196. if (!AttrUtils::GetInt(node->GetOpDesc(), ATTR_NAME_PARENT_NODE_INDEX, data_index)) {
  1197. GELOGE(FAILED,
  1198. "[%s] Failed to get attr [%s]",
  1199. node->GetName().c_str(),
  1200. ATTR_NAME_PARENT_NODE_INDEX.c_str());
  1201. return FAILED;
  1202. }
  1203. (void) wrapper_op_desc->AddInputDesc(op_desc->GetInputDesc(0));
  1204. graph_item->input_index_mapping_.emplace_back(data_index);
  1205. } else if (op_type == NETOUTPUT) {
  1206. int output_index = 0;
  1207. for (const auto &output_desc : op_desc->GetAllInputsDescPtr()) {
  1208. int32_t data_index = output_index++;
  1209. if (!AttrUtils::GetInt(output_desc, ATTR_NAME_PARENT_NODE_INDEX, data_index)) {
  1210. GELOGI("[%s] Failed to get attr [%s]", node->GetName().c_str(), ATTR_NAME_PARENT_NODE_INDEX.c_str());
  1211. }
  1212. GE_CHK_GRAPH_STATUS_RET(wrapper_op_desc->AddOutputDesc(*output_desc),
  1213. "[%s] Failed to add output desc. output index = %d",
  1214. graph.GetName().c_str(),
  1215. output_index);
  1216. graph_item->output_index_mapping_.emplace_back(data_index);
  1217. }
  1218. }
  1219. }
  1220. auto temp_graph = MakeShared<ComputeGraph>("temp");
  1221. GE_CHECK_NOTNULL(temp_graph);
  1222. auto wrapper_node = temp_graph->AddNode(wrapper_op_desc);
  1223. GeModelPtr ge_model = subgraph_models_[subgraph_name];
  1224. GE_CHECK_NOTNULL(ge_model);
  1225. hybrid_model_.known_shape_sub_models_.emplace(wrapper_node, ge_model);
  1226. NodeItem *node_item = nullptr;
  1227. GE_CHK_STATUS_RET_NOLOG(GetOrCreateNodeItem(wrapper_node, &node_item));
  1228. node_item->input_start = 0;
  1229. node_item->output_start = 0;
  1230. node_item->outputs.resize(node_item->num_outputs);
  1231. graph_item->node_items_.emplace_back(node_item);
  1232. graph_item->output_node_ = node_item;
  1233. graph_item->total_inputs_ = node_item->num_inputs;
  1234. graph_item->total_outputs_ = node_item->num_outputs;
  1235. GELOGD("NodeItem create for known shape subgraph [%s], NodeItem = %s",
  1236. graph.GetName().c_str(),
  1237. node_item->DebugString().c_str());
  1238. GELOGD("Done parse known shape subgraph successfully. graph = [%s]", graph.GetName().c_str());
  1239. graph_item->SetName(graph.GetName());
  1240. GELOGD("Done loading known shape subgraph: [%s]", graph_item->GetName().c_str());
  1241. hybrid_model_.subgraph_items_.emplace(graph.GetName(), std::move(graph_item));
  1242. return SUCCESS;
  1243. }
  1244. Status HybridModelBuilder::RecoverGraphUnknownFlag() {
  1245. const auto &root_graph = ge_root_model_->GetRootGraph();
  1246. for (auto &sub_graph : root_graph->GetAllSubgraphs()) {
  1247. GE_CHECK_NOTNULL(sub_graph);
  1248. for (const auto &node : sub_graph->GetDirectNode()) {
  1249. bool is_unknown_shape = false;
  1250. (void)AttrUtils::GetBool(node->GetOpDesc(), kOwnerGraphIsUnknown, is_unknown_shape);
  1251. sub_graph->SetGraphUnknownFlag(is_unknown_shape);
  1252. break;
  1253. }
  1254. }
  1255. return SUCCESS;
  1256. }
  1257. Status HybridModelBuilder::LoadDynamicSubgraph(ComputeGraph &graph, bool is_root_graph) {
  1258. GELOGD("Start to load subgraph [%s]", graph.GetName().c_str());
  1259. // for known partitioned call, load all nodes
  1260. auto graph_item = std::unique_ptr<GraphItem>(new(std::nothrow)GraphItem());
  1261. GE_CHECK_NOTNULL(graph_item);
  1262. graph_item->is_dynamic_ = true;
  1263. graph_item->node_items_.reserve(graph.GetDirectNodesSize());
  1264. int input_start = 0;
  1265. int output_start = 0;
  1266. std::vector<NodeItem *> data_nodes;
  1267. for (auto &node : graph.GetDirectNode()) {
  1268. GE_CHECK_NOTNULL(node);
  1269. GE_CHECK_NOTNULL(node->GetOpDesc());
  1270. const auto &op_type = node->GetType();
  1271. NodeItem *node_item = nullptr;
  1272. GE_CHK_STATUS_RET_NOLOG(GetOrCreateNodeItem(node, &node_item));
  1273. GE_CHK_STATUS_RET_NOLOG(BuildNodeItem(node, *node_item));
  1274. GE_CHK_STATUS_RET_NOLOG(UpdateAnchorStatus(node)); // needed by FE generate task
  1275. node_item->input_start = input_start;
  1276. node_item->output_start = output_start;
  1277. input_start += node_item->num_inputs;
  1278. output_start += node_item->num_outputs;
  1279. if (op_type == DATA_TYPE || op_type == AIPP_DATA_TYPE) {
  1280. data_nodes.emplace_back(node_item);
  1281. } else if (op_type == NETOUTPUT) {
  1282. graph_item->output_node_ = node_item;
  1283. GE_CHK_STATUS_RET_NOLOG(BuildOutputMapping(*graph_item, *node_item, is_root_graph));
  1284. }
  1285. graph_item->node_items_.emplace_back(node_item);
  1286. // parse var outputs
  1287. GE_CHK_STATUS_RET_NOLOG(ParseVarOutputs(*node_item));
  1288. GELOGD("NodeItem created: %s", node_item->DebugString().c_str());
  1289. }
  1290. graph_item->total_inputs_ = input_start;
  1291. graph_item->total_outputs_ = output_start;
  1292. GE_CHK_STATUS_RET_NOLOG(BuildInputMapping(*graph_item, data_nodes, is_root_graph));
  1293. if (is_root_graph) {
  1294. graph_item->SetName("Root-Graph");
  1295. GELOGD("Done loading dynamic subgraph: [%s]", graph_item->GetName().c_str());
  1296. hybrid_model_.root_graph_item_ = std::move(graph_item);
  1297. } else {
  1298. graph_item->SetName(graph.GetName());
  1299. GELOGD("Done loading dynamic subgraph: [%s]", graph_item->GetName().c_str());
  1300. hybrid_model_.subgraph_items_.emplace(graph.GetName(), std::move(graph_item));
  1301. }
  1302. return SUCCESS;
  1303. }
  1304. Status HybridModelBuilder::ParseVarOutputs(NodeItem &node_item) {
  1305. for (int i = 0; i < node_item.num_outputs; ++i) {
  1306. auto output_tensor_desc = node_item.op_desc->GetOutputDesc(i);
  1307. std::string var_name;
  1308. (void) AttrUtils::GetStr(output_tensor_desc, ASSIGN_VAR_NAME, var_name);
  1309. if (!var_name.empty()) {
  1310. auto var_node = hybrid_model_.GetVariableNode(var_name);
  1311. GE_CHECK_NOTNULL(var_node);
  1312. node_item.ref_outputs.emplace(i, var_node);
  1313. }
  1314. }
  1315. return SUCCESS;
  1316. }
  1317. Status HybridModelBuilder::BuildInputMapping(GraphItem &graph_item,
  1318. vector<NodeItem *> &data_nodes,
  1319. bool is_root_graph) {
  1320. uint32_t data_op_index = 0;
  1321. for (auto &node_item : data_nodes) {
  1322. auto node = node_item->node;
  1323. int data_index = data_op_index;
  1324. if (is_root_graph) {
  1325. if (AttrUtils::GetInt(node->GetOpDesc(), ATTR_NAME_INDEX, data_index)) {
  1326. GELOGI("ge_train: get new index %u, old %u", data_index, data_op_index);
  1327. }
  1328. data_op_index++;
  1329. } else {
  1330. if (!AttrUtils::GetInt(node->GetOpDesc(), ATTR_NAME_PARENT_NODE_INDEX, data_index)) {
  1331. GELOGE(FAILED,
  1332. "[%s] Failed to get attr [%s]",
  1333. node->GetName().c_str(),
  1334. ATTR_NAME_PARENT_NODE_INDEX.c_str());
  1335. return FAILED;
  1336. }
  1337. }
  1338. if (graph_item.input_nodes_.size() <= static_cast<size_t>(data_index)) {
  1339. graph_item.input_nodes_.resize(data_index + 1);
  1340. }
  1341. graph_item.input_nodes_[data_index] = node_item;
  1342. }
  1343. return SUCCESS;
  1344. }
  1345. } // namespace hybrid
  1346. } // namespace ge

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