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.

graph_builder.cc 29 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. /**
  2. * Copyright 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 "graph/build/graph_builder.h"
  17. #include "common/ge/ge_util.h"
  18. #include "common/helper/model_helper.h"
  19. #include "graph/build/logical_stream_allocator.h"
  20. #include "graph/build/run_context.h"
  21. #include "graph/build/stream_graph_optimizer.h"
  22. #include "graph/common/ge_call_wrapper.h"
  23. #include "graph/ge_context.h"
  24. #include "graph/manager/graph_var_manager.h"
  25. #include "graph/passes/mark_same_addr_pass.h"
  26. #include "graph/utils/node_utils.h"
  27. #include "graph/utils/type_utils.h"
  28. #include "init/gelib.h"
  29. #include "model/ge_model.h"
  30. #include "graph/ge_context.h"
  31. #include "opskernel_manager/ops_kernel_builder_manager.h"
  32. #include "graph/utils/op_desc_utils.h"
  33. using domi::BuildMode;
  34. namespace {
  35. const int32_t kInvalidPerfLevel = -1;
  36. enum NodeType { kSubgraphData, kSubgraphNode, kOthers };
  37. } // namespace
  38. namespace ge {
  39. NodeType TransferNodeType(const NodePtr &node) {
  40. const std::string type = node->GetType();
  41. if (type == ge::DATA) {
  42. if (node->GetOwnerComputeGraph()->GetParentNode() == nullptr) {
  43. GELOGD("access src data node:%s", node->GetName().c_str());
  44. return kOthers;
  45. }
  46. GELOGD("access subgraph input node:%s", node->GetName().c_str());
  47. return kSubgraphData;
  48. } else if (type == PARTITIONEDCALL) {
  49. GELOGD("access subgraph node:%s", node->GetName().c_str());
  50. return kSubgraphNode;
  51. }
  52. GELOGD("access other node:%s", node->GetName().c_str());
  53. return kOthers;
  54. }
  55. Status HandleSubgraphNode(NodePtr &src_node, OutDataAnchorPtr &src_out_anchor) {
  56. auto subgraph = NodeUtils::GetSubgraph(*src_node, 0);
  57. GE_CHECK_NOTNULL(subgraph);
  58. const NodePtr &net_output_node = subgraph->FindFirstNodeMatchType(NETOUTPUT);
  59. GE_CHECK_NOTNULL(net_output_node);
  60. const InDataAnchorPtr &in_data_anchor = net_output_node->GetInDataAnchor(src_out_anchor->GetIdx());
  61. GE_CHECK_NOTNULL(in_data_anchor);
  62. const OutDataAnchorPtr &peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  63. GE_CHECK_NOTNULL(peer_out_anchor);
  64. src_node = peer_out_anchor->GetOwnerNode();
  65. src_out_anchor = peer_out_anchor;
  66. return SUCCESS;
  67. }
  68. Status HandleSubgraphDataNode(NodePtr &src_node, OutDataAnchorPtr &src_out_anchor) {
  69. uint32_t index = 0;
  70. if (!AttrUtils::GetInt(src_node->GetOpDesc(), ATTR_NAME_PARENT_NODE_INDEX, index)) {
  71. GELOGE(FAILED, "Get attr ATTR_NAME_PARENT_NODE_INDEX failed, node:%s.", src_node->GetName().c_str());
  72. return FAILED;
  73. }
  74. const NodePtr &parent_node = src_node->GetOwnerComputeGraph()->GetParentNode();
  75. GE_CHECK_NOTNULL(parent_node);
  76. const InDataAnchorPtr &in_data_anchor = parent_node->GetInDataAnchor(index);
  77. GE_CHECK_NOTNULL(in_data_anchor);
  78. const OutDataAnchorPtr &peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  79. GE_CHECK_NOTNULL(peer_out_anchor);
  80. src_node = peer_out_anchor->GetOwnerNode();
  81. src_out_anchor = peer_out_anchor;
  82. return SUCCESS;
  83. }
  84. GraphBuilder::GraphBuilder() : build_mode_(BuildMode::GEN_TASK_WITH_FUSION), hcom_parallel_(false) {}
  85. void GraphBuilder::SetOptions(const ge::GraphManagerOptions &options) {
  86. stream_max_parallel_num_ = options.stream_max_parallel_num;
  87. hcom_parallel_ = options.hcom_parallel;
  88. if (options.perf_level == kInvalidPerfLevel) {
  89. build_mode_ = static_cast<int>(BuildMode::GEN_TASK_WITH_FUSION);
  90. } else {
  91. build_mode_ = options.perf_level;
  92. }
  93. }
  94. Status GraphBuilder::CalcOpParam(const ge::ComputeGraphPtr &graph) {
  95. GE_CHECK_NOTNULL(graph);
  96. auto instance_ptr = ge::GELib::GetInstance();
  97. if (instance_ptr == nullptr || !instance_ptr->InitFlag()) {
  98. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "GraphBuilder: GE is not initialized");
  99. return GE_CLI_GE_NOT_INITIALIZED;
  100. }
  101. for (const auto &node_ptr : graph->GetNodes(graph->GetGraphUnknownFlag())) {
  102. GE_CHECK_NOTNULL(node_ptr->GetOpDesc());
  103. std::string kernel_lib_name = node_ptr->GetOpDesc()->GetOpKernelLibName();
  104. if (kernel_lib_name.empty()) {
  105. // reset op kernel lib
  106. (void)instance_ptr->DNNEngineManagerObj().GetDNNEngineName(node_ptr);
  107. kernel_lib_name = node_ptr->GetOpDesc()->GetOpKernelLibName();
  108. if (kernel_lib_name.empty()) {
  109. GELOGE(INTERNAL_ERROR, "Get node:%s(%s) kernel lib failed.", node_ptr->GetName().c_str(),
  110. node_ptr->GetType().c_str());
  111. return INTERNAL_ERROR;
  112. }
  113. }
  114. auto ret = SetInputSize(node_ptr);
  115. if (ret != SUCCESS) {
  116. GELOGE(ret, "Set node inputDesc size failed, node name is %s", node_ptr->GetName().c_str());
  117. return ret;
  118. }
  119. ret = OpsKernelBuilderManager::Instance().CalcOpRunningParam(*node_ptr);
  120. if (ret != SUCCESS) {
  121. GELOGE(ret, "Calculate op running param failed, node name is %s", node_ptr->GetName().c_str());
  122. return ret;
  123. }
  124. GE_CHK_STATUS_RET(AddOutputMemTypeForNode(node_ptr));
  125. }
  126. auto parent_node = graph->GetParentNode();
  127. if (parent_node == nullptr) {
  128. return SUCCESS;
  129. }
  130. GE_CHK_STATUS_RET(UpdateParentNodeOutputSize(graph, parent_node));
  131. GELOGI("Success to calculate op running param.");
  132. return SUCCESS;
  133. }
  134. Status GraphBuilder::UpdateParentNodeOutputSize(const ge::ComputeGraphPtr &graph, ge::NodePtr &parent_node_ptr) {
  135. GELOGI("Begin to update parent node[%s] of graph[%s] output size.", parent_node_ptr->GetName().c_str(),
  136. graph->GetName().c_str());
  137. auto parent_op_desc = parent_node_ptr->GetOpDesc();
  138. GE_CHECK_NOTNULL(parent_op_desc);
  139. bool is_unknown_shape = graph->GetGraphUnknownFlag();
  140. if (is_unknown_shape) {
  141. GELOGI("Current graph[%s] is unknown, no need to update parent node[%s] output size.", graph->GetName().c_str(),
  142. parent_node_ptr->GetName().c_str());
  143. return SUCCESS;
  144. }
  145. for (const auto &node_ptr : graph->GetDirectNode()) {
  146. if (node_ptr->GetType() != NETOUTPUT) {
  147. continue;
  148. }
  149. auto op_desc = node_ptr->GetOpDesc();
  150. GE_CHECK_NOTNULL(op_desc);
  151. for (const auto &in_data_anchor : node_ptr->GetAllInDataAnchors()) {
  152. auto index = in_data_anchor->GetIdx();
  153. ge::GeTensorDesc desc_temp = op_desc->GetInputDesc(index);
  154. uint32_t parent_index = 0;
  155. if (!AttrUtils::GetInt(desc_temp, ATTR_NAME_PARENT_NODE_INDEX, parent_index)) {
  156. GELOGI("NetOutput input tensor %d, attr %s not found.", index, ATTR_NAME_PARENT_NODE_INDEX.c_str());
  157. continue;
  158. }
  159. int64_t size = 0;
  160. GE_IF_BOOL_EXEC(ge::TensorUtils::GetSize(desc_temp, size) != SUCCESS, GELOGI("Get size failed!"));
  161. ge::GeTensorDesc parent_desc_temp = parent_op_desc->GetOutputDesc(parent_index);
  162. ge::TensorUtils::SetSize(parent_desc_temp, size);
  163. GE_CHK_STATUS_RET(parent_op_desc->UpdateOutputDesc(parent_index, parent_desc_temp));
  164. GELOGI("Update parent node[%s] output index[%u] to size[%ld].", parent_node_ptr->GetName().c_str(), parent_index,
  165. size);
  166. }
  167. }
  168. return SUCCESS;
  169. }
  170. Status GraphBuilder::Build(ComputeGraphPtr &comp_graph, std::vector<SubGraphInfoPtr> &subgraph_ptr_list,
  171. GeRootModelPtr &ge_root_model_ptr, uint64_t session_id) {
  172. if (comp_graph == nullptr) {
  173. GELOGE(GE_GRAPH_PARAM_NULLPTR, "Graph build comp_graph is null.");
  174. return GE_GRAPH_PARAM_NULLPTR;
  175. }
  176. ge_root_model_ptr = MakeShared<ge::GeRootModel>(comp_graph);
  177. if (ge_root_model_ptr == nullptr) {
  178. return MEMALLOC_FAILED;
  179. }
  180. GeModelPtr ge_model_ptr = nullptr;
  181. bool is_dynamic_shape = false;
  182. // To be compatible with the old process, do not verify the return value temporarily.
  183. (void)AttrUtils::GetBool(comp_graph, ATTR_NAME_DYNAMIC_SHAPE_PARTITIONED, is_dynamic_shape);
  184. if (is_dynamic_shape) {
  185. GE_CHK_STATUS_RET(
  186. BuildForDynamicShapeGraph(comp_graph, subgraph_ptr_list, ge_root_model_ptr, ge_model_ptr, session_id),
  187. "Build for dynamic shape graph failed.");
  188. return SUCCESS;
  189. }
  190. GE_CHK_STATUS_RET(BuildForKnownShapeGraph(comp_graph, subgraph_ptr_list, ge_model_ptr, session_id),
  191. "Build for known shape graph failed.");
  192. ge_root_model_ptr->SetSubgraphInstanceNameToModel(comp_graph->GetName(), ge_model_ptr);
  193. return SUCCESS;
  194. }
  195. Status GraphBuilder::BuildForKnownShapeGraph(ComputeGraphPtr &comp_graph, std::vector<SubGraphInfoPtr> &subgraph_list,
  196. GeModelPtr &ge_model_ptr, uint64_t session_id) {
  197. if (ge::GetContext().GetHostExecFlag()) {
  198. GE_CHK_STATUS_RET(BuildForHostCpuGraph(comp_graph, ge_model_ptr, session_id), "Build for host-cpu graph failed.");
  199. return SUCCESS;
  200. }
  201. GELOGI("Begin to build known shape graph[%s].", comp_graph->GetName().c_str());
  202. Status ret = SecondPartition(comp_graph, subgraph_list);
  203. GE_CHK_STATUS_RET(ret, "Graph[%s] second partition Failed.", comp_graph->GetName().c_str());
  204. auto subgraph_map = graph_partitioner_.GetSubGraphMap();
  205. GE_TIMESTAMP_START(BuildSubgraph);
  206. ge::ModelBuilder builder(session_id, comp_graph, subgraph_map, stream_max_parallel_num_, hcom_parallel_, build_mode_);
  207. GE_DUMP(comp_graph, "BeforePreBuildModel");
  208. GE_TIMESTAMP_START(PreBuildModel);
  209. GE_CHK_STATUS_RET(builder.PreBuildModel(), "Graph[%s] builder PreBuildModel() return fail.",
  210. comp_graph->GetName().c_str());
  211. GE_TIMESTAMP_END(PreBuildModel, "GraphBuilder::PreBuildModel");
  212. GE_DUMP(comp_graph, "AfterPreBuildModel");
  213. GE_TIMESTAMP_START(CalcOpParam);
  214. GE_CHK_STATUS_RET(CalcOpParam(comp_graph), "Graph[%s] builder CalcOpParam() return fail.",
  215. comp_graph->GetName().c_str());
  216. GE_TIMESTAMP_END(CalcOpParam, "GraphBuilder::CalcOpParam");
  217. GE_DUMP(comp_graph, "AfterCalcOpParam");
  218. ModelPtr model_ptr = MakeShared<ge::Model>();
  219. if (model_ptr == nullptr) {
  220. return MEMALLOC_FAILED;
  221. }
  222. GE_TIMESTAMP_START(BuildModelForGetTask);
  223. GE_CHK_STATUS_RET(builder.BuildModelForGetTask(*model_ptr), "Graph[%s] builder BuildModelForGetTask() return fail.",
  224. comp_graph->GetName().c_str());
  225. GE_TIMESTAMP_END(BuildModelForGetTask, "GraphBuilder::BuildModelForGetTask");
  226. GE_DUMP(comp_graph, "AfterBuildModel");
  227. GE_TIMESTAMP_START(GetTaskInfo);
  228. ret = GetTaskInfo(builder, model_ptr, comp_graph, subgraph_map, session_id);
  229. GE_TIMESTAMP_END(GetTaskInfo, "GraphBuilder::GetTaskInfo");
  230. GE_DUMP(comp_graph, "AfterGetTask");
  231. if (ret != SUCCESS) {
  232. GELOGE(ret, "Graph[%s] builder GetTaskInfo() return fail.", comp_graph->GetName().c_str());
  233. return ret;
  234. }
  235. ge_model_ptr = MakeShared<ge::GeModel>();
  236. if (ge_model_ptr == nullptr) {
  237. return MEMALLOC_FAILED;
  238. }
  239. GE_CHK_STATUS_RET(builder.SaveDataToModel(*model_ptr, *ge_model_ptr),
  240. "Graph[%s] builder SaveDataToModel() return fail.", comp_graph->GetName().c_str());
  241. GELOGD("Success to build graph[%s] model.", comp_graph->GetName().c_str());
  242. GE_TIMESTAMP_END(BuildSubgraph, "GraphBuilder::Build");
  243. return SUCCESS;
  244. }
  245. Status GraphBuilder::BuildForUnknownShapeGraph(ComputeGraphPtr &comp_graph, GeModelPtr &ge_model_ptr,
  246. uint64_t session_id) {
  247. GELOGI("Begin to build unknown shape graph[%s].", comp_graph->GetName().c_str());
  248. GE_TIMESTAMP_START(CalcOpParam);
  249. GE_CHK_STATUS_RET(CalcOpParam(comp_graph), "Graph[%s] builder CalcOpParam() return fail.",
  250. comp_graph->GetName().c_str());
  251. GE_TIMESTAMP_END(CalcOpParam, "GraphBuilder::CalcOpParam");
  252. GE_DUMP(comp_graph, "AfterCalcOpParam");
  253. Graph2SubGraphInfoList subgraph_map;
  254. ge::ModelBuilder builder(session_id, comp_graph, subgraph_map, stream_max_parallel_num_, hcom_parallel_, build_mode_);
  255. ModelPtr model_ptr = MakeShared<ge::Model>();
  256. if (model_ptr == nullptr) {
  257. return MEMALLOC_FAILED;
  258. }
  259. GE_TIMESTAMP_START(BuildModelForGetDynShapeTask);
  260. GE_CHK_STATUS_RET(builder.BuildModelForGetDynShapeTask(*model_ptr),
  261. "Graph[%s] builder BuildModelForGetDynShapeTask() return fail.", comp_graph->GetName().c_str());
  262. GE_TIMESTAMP_END(BuildModelForGetDynShapeTask, "GraphBuilder::BuildModelForGetDynShapeTask");
  263. GE_TIMESTAMP_START(GetTaskInfo);
  264. Status ret = GetTaskInfo(builder, model_ptr, comp_graph, subgraph_map, session_id);
  265. GE_TIMESTAMP_END(GetTaskInfo, "GraphBuilder::GetTaskInfo");
  266. GraphUtils::DumpGEGraph(comp_graph, "AfterGetTask");
  267. GraphUtils::DumpGEGraphToOnnx(*comp_graph, "AfterGetTask");
  268. if (ret != SUCCESS) {
  269. GELOGE(ret, "Graph[%s] builder GetTaskInfo() return fail.", comp_graph->GetName().c_str());
  270. return ret;
  271. }
  272. ge_model_ptr = MakeShared<ge::GeModel>();
  273. if (ge_model_ptr == nullptr) {
  274. return MEMALLOC_FAILED;
  275. }
  276. GE_CHK_STATUS_RET(builder.SaveDataToModel(*model_ptr, *ge_model_ptr),
  277. "Graph[%s] builder SaveDataToModel() return fail.", comp_graph->GetName().c_str());
  278. GELOGD("Success to build graph[%s] model.", comp_graph->GetName().c_str());
  279. return SUCCESS;
  280. }
  281. Status GraphBuilder::BuildForHostCpuGraph(ComputeGraphPtr &comp_graph, GeModelPtr &ge_model_ptr, uint64_t session_id) {
  282. return BuildForUnknownShapeGraph(comp_graph, ge_model_ptr, session_id);
  283. }
  284. static Status InsertMemcpyNode(const ComputeGraphPtr &graph, const OutDataAnchorPtr &out_anchor,
  285. const std::vector<InDataAnchorPtr> &in_anchors, const std::string &name) {
  286. GE_CHECK_NOTNULL(out_anchor);
  287. NodePtr in_node = out_anchor->GetOwnerNode();
  288. OpDescBuilder op_desc_builder(name, MEMCPYADDRASYNC);
  289. OpDescPtr op_desc = op_desc_builder.AddInput("x", in_node->GetOpDesc()->GetOutputDesc(0))
  290. .AddOutput("y", in_node->GetOpDesc()->GetOutputDesc(0))
  291. .Build();
  292. (void)AttrUtils::SetBool(op_desc, ATTR_NO_NEED_CONSTANT_FOLDING, false);
  293. if (GraphUtils::InsertNodeAfter(out_anchor, in_anchors, graph->AddNode(op_desc)) != GRAPH_SUCCESS) {
  294. GELOGE(FAILED, "Insert IDENTITY node %s after %s failed.", name.c_str(), in_node->GetName().c_str());
  295. return FAILED;
  296. }
  297. return SUCCESS;
  298. }
  299. static Status GenerateTaskForConstant(const std::shared_ptr<ComputeGraph> &graph) {
  300. for (auto &node : graph->GetDirectNode()) {
  301. // CONSTANT not generate task, so insert IDENTITY between CONSTANT and NETOUTPUT
  302. auto op_desc = node->GetOpDesc();
  303. if (op_desc == nullptr) {
  304. continue;
  305. }
  306. auto op_type = op_desc->GetType();
  307. if (op_type == NETOUTPUT) {
  308. for (InDataAnchorPtr &in_data_anchor : node->GetAllInDataAnchors()) {
  309. const OutDataAnchorPtr &peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  310. GE_IF_BOOL_EXEC(peer_out_anchor == nullptr, continue);
  311. NodePtr in_node = peer_out_anchor->GetOwnerNode();
  312. GE_CHECK_NOTNULL(in_node);
  313. std::string in_node_op_type = in_node->GetType();
  314. if (in_node_op_type == CONSTANT) {
  315. GELOGD("Insert MemcpyAsync node between %s and %s.", in_node->GetName().c_str(), node->GetName().c_str());
  316. std::string name = node->GetName() + "_input_" + std::to_string(in_data_anchor->GetIdx()) + "_Memcpy";
  317. if (InsertMemcpyNode(graph, peer_out_anchor, {in_data_anchor}, name) != SUCCESS) {
  318. GELOGE(FAILED, "Insert memcpy between %s and %s failed.", in_node->GetName().c_str(), node->GetName().c_str());
  319. return FAILED;
  320. }
  321. }
  322. }
  323. }
  324. }
  325. return SUCCESS;
  326. }
  327. Status GraphBuilder::BuildForDynamicShapeGraph(ComputeGraphPtr &comp_graph,
  328. std::vector<SubGraphInfoPtr> &subgraph_ptr_list,
  329. GeRootModelPtr &ge_root_model_ptr, GeModelPtr &ge_model_ptr,
  330. uint64_t session_id) {
  331. GELOGI("Start to build BuildForDynamicShape for dynamic shape.");
  332. // Update Root Graph Data size
  333. for (auto &node : comp_graph->GetDirectNode()) {
  334. auto op_desc = node->GetOpDesc();
  335. GE_CHECK_NOTNULL(op_desc);
  336. op_desc->SetStreamId(kInvalidStream);
  337. if (node->GetType() == DATA) {
  338. GE_CHK_STATUS_RET(CalcDynShapeRootGraphDataSize(op_desc), "Calc dynamic shape root graph data[%s] size failed.",
  339. op_desc->GetName().c_str());
  340. }
  341. }
  342. //
  343. for (auto &sub_graph : comp_graph->GetAllSubgraphs()) {
  344. // exclude functional subgraph in known subgraph
  345. if (sub_graph->GetParentGraph() != comp_graph && !sub_graph->GetParentGraph()->GetGraphUnknownFlag()) {
  346. continue;
  347. }
  348. GE_CHK_STATUS_RET(GenerateTaskForConstant(sub_graph), "Generate task For constant node in subgraph failed.");
  349. if (sub_graph->GetGraphUnknownFlag()) {
  350. // unknown shape build flow
  351. GE_CHK_STATUS_RET(BuildForUnknownShapeGraph(sub_graph, ge_model_ptr, session_id),
  352. "Build for unknown shape graph failed.");
  353. } else {
  354. // reset functional subgraph parent graph as known subgraph
  355. for (const auto &node : sub_graph->GetDirectNode()) {
  356. for (const auto &sub_graph_name : node->GetOpDesc()->GetSubgraphInstanceNames()) {
  357. auto sub_sub_graph = comp_graph->GetSubgraph(sub_graph_name);
  358. GE_CHK_STATUS_RET(sub_graph->AddSubgraph(sub_sub_graph), "Failed add subgraph to known graph.");
  359. }
  360. }
  361. // known shape build flow
  362. GE_CHK_STATUS_RET(BuildForKnownShapeGraph(sub_graph, subgraph_ptr_list, ge_model_ptr, session_id),
  363. "Build for known shape graph failed.");
  364. }
  365. ge_root_model_ptr->SetSubgraphInstanceNameToModel(sub_graph->GetName(), ge_model_ptr);
  366. }
  367. return SUCCESS;
  368. }
  369. Status GraphBuilder::GetTaskInfo(const ge::ModelBuilder &builder, const ModelPtr &model_ptr,
  370. ComputeGraphPtr &comp_graph, Graph2SubGraphInfoList &subgraph_map,
  371. uint64_t session_id) {
  372. GE_CHECK_NOTNULL(model_ptr);
  373. GE_CHECK_NOTNULL(comp_graph);
  374. int64_t memory_size = 0;
  375. if (!AttrUtils::GetInt(model_ptr, ATTR_MODEL_MEMORY_SIZE, memory_size)) {
  376. GELOGE(INTERNAL_ERROR, "Get memory size fail.");
  377. return INTERNAL_ERROR;
  378. }
  379. int64_t p2p_memory_size = 0;
  380. if (!AttrUtils::GetInt(model_ptr, ATTR_MODEL_P2P_MEMORY_SIZE, p2p_memory_size)) {
  381. GELOGE(INTERNAL_ERROR, "Get p2p memory size fail.");
  382. return INTERNAL_ERROR;
  383. }
  384. int64_t weight_size = 0;
  385. if (!AttrUtils::GetInt(model_ptr, ATTR_MODEL_WEIGHT_SIZE, weight_size)) {
  386. GELOGE(INTERNAL_ERROR, "Get weight memory size fail.");
  387. return INTERNAL_ERROR;
  388. }
  389. auto var_manager = VarManager::Instance(session_id);
  390. // since var_mem_logic_base_ = graph_mem_max_size_ + kGraphMemoryBuffer in graph_var_manager.cc,
  391. // get_mem_base should not bigger than kGraphMemoryBuffer
  392. auto *get_mem_base = reinterpret_cast<uint8_t *>(reinterpret_cast<uintptr_t>(kGraphMemoryBuffer>>1));
  393. uint8_t *get_weight_mem_base = get_mem_base;
  394. if (weight_size > 0) {
  395. get_weight_mem_base = get_mem_base + memory_size + p2p_memory_size;
  396. }
  397. std::map<int64_t, uint8_t *> mem_type_to_data_mem_base;
  398. mem_type_to_data_mem_base[RT_MEMORY_HBM] = get_mem_base;
  399. if (p2p_memory_size == 0) {
  400. mem_type_to_data_mem_base[RT_MEMORY_P2P_DDR] = nullptr;
  401. } else {
  402. mem_type_to_data_mem_base[RT_MEMORY_P2P_DDR] = get_mem_base + memory_size;
  403. }
  404. std::map<int64_t, uint64_t> mem_type_to_data_mem_size;
  405. mem_type_to_data_mem_size[RT_MEMORY_HBM] = memory_size;
  406. mem_type_to_data_mem_size[RT_MEMORY_P2P_DDR] = p2p_memory_size;
  407. RunContextUtil run_context;
  408. Status ret = run_context.InitMemInfo(get_mem_base, memory_size, mem_type_to_data_mem_base, mem_type_to_data_mem_size,
  409. get_weight_mem_base, weight_size);
  410. if (ret != SUCCESS) {
  411. GELOGE(ret, "task_generator init mem info fail.");
  412. return ret;
  413. }
  414. auto weight_buffer = builder.GetWeightBuffer();
  415. ret = run_context.CreateRunContext(*model_ptr, comp_graph, weight_buffer, session_id);
  416. if (ret != SUCCESS) {
  417. GELOGE(ret, "runContext create run context fail.");
  418. return ret;
  419. }
  420. StreamGraphOptimizer stream_optimizer;
  421. ret = stream_optimizer.OptimizeStreamedSubGraph(comp_graph, subgraph_map, run_context.GetRunContext());
  422. if (ret != SUCCESS) {
  423. GELOGE(ret, "Optimize streamed subGraph fail.");
  424. return ret;
  425. }
  426. GE_DUMP(comp_graph, "AfterOptimizeStreamedSubGraph");
  427. auto *get_var_mem_base = reinterpret_cast<uint8_t *>(reinterpret_cast<uintptr_t>(var_manager->GetVarMemLogicBase()));
  428. uint64_t var_size = (var_manager->GetVarMemSize(RT_MEMORY_HBM) > 0) ? var_manager->GetVarMemMaxSize() : 0;
  429. TaskGenerator task_generator(get_var_mem_base, var_size);
  430. ret = task_generator.GetTaskInfo(*model_ptr, comp_graph, session_id, run_context.GetRunContext());
  431. return ret;
  432. }
  433. Status GraphBuilder::SetInputSize(const ge::NodePtr &node_ptr) {
  434. // set input_desc.size = src_node.output_desc.size
  435. if (node_ptr->GetType() == DATA) {
  436. bool is_unknown_shape = false;
  437. GE_CHK_STATUS_RET(ge::NodeUtils::GetNodeUnknownShapeStatus(*node_ptr, is_unknown_shape),
  438. "Get data node[%s] shape status failed!", node_ptr->GetName().c_str());
  439. if (is_unknown_shape) {
  440. GELOGD("data node: %s is unknown shape, do not set input size!", node_ptr->GetName().c_str());
  441. return SUCCESS;
  442. }
  443. if (UpdateDataInputSize(node_ptr) != SUCCESS) {
  444. GELOGE(FAILED, "Update data input size failed.");
  445. return FAILED;
  446. }
  447. }
  448. for (const auto &in_data_anchor : node_ptr->GetAllInDataAnchors()) {
  449. const auto &peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  450. GE_IF_BOOL_EXEC(peer_out_anchor == nullptr, continue);
  451. const auto &src_node = peer_out_anchor->GetOwnerNode();
  452. const auto &src_op = src_node->GetOpDesc();
  453. GE_IF_BOOL_EXEC(src_op == nullptr, continue);
  454. auto node_op_desc = node_ptr->GetOpDesc();
  455. GE_IF_BOOL_EXEC(node_op_desc == nullptr, continue);
  456. // set dst_node.input_desc = src_node.output_desc
  457. auto output_desc = src_op->GetOutputDescPtr(peer_out_anchor->GetIdx());
  458. int64_t size = 0;
  459. GE_IF_BOOL_EXEC(ge::TensorUtils::GetSize(*output_desc, size) != SUCCESS, GELOGI("Get size failed!"));
  460. GELOGD("src node %s output desc, dim_size: %zu, mem_size: %ld, format: %s, type: %s.", src_node->GetName().c_str(),
  461. output_desc->GetShape().GetDimNum(), size, TypeUtils::FormatToSerialString(output_desc->GetFormat()).c_str(),
  462. TypeUtils::DataTypeToSerialString(output_desc->GetDataType()).c_str());
  463. for (size_t i = 0; i < output_desc->GetShape().GetDimNum(); ++i) {
  464. GELOGD("dims[%zu]: %ld", i, output_desc->GetShape().GetDim(i));
  465. }
  466. auto input_desc = node_op_desc->MutableInputDesc(in_data_anchor->GetIdx());
  467. GE_CHECK_NOTNULL(input_desc);
  468. (void) ge::TensorUtils::SetSize(*input_desc, size);
  469. GE_CHK_STATUS_RET(node_op_desc->UpdateInputDesc(in_data_anchor->GetIdx(), *input_desc));
  470. GELOGD("%s input desc, dim_size: %zu, mem_size: %ld, format: %s, type: %s.", node_ptr->GetName().c_str(),
  471. input_desc->GetShape().GetDimNum(), size, TypeUtils::FormatToSerialString(input_desc->GetFormat()).c_str(),
  472. TypeUtils::DataTypeToSerialString(input_desc->GetDataType()).c_str());
  473. // inherit some attr
  474. int64_t tensor_size_attr;
  475. if (AttrUtils::GetInt(output_desc, ATTR_NAME_SPECIAL_OUTPUT_SIZE, tensor_size_attr) && (tensor_size_attr > 0)) {
  476. GE_IF_BOOL_EXEC(!AttrUtils::SetInt(*input_desc, ATTR_NAME_SPECIAL_OUTPUT_SIZE, tensor_size_attr),
  477. GELOGW("Set size attr failed!"); continue);
  478. GELOGD("node[%s] [%d]th output has sepcial size[%ld], and update to node[%s] [%d]th input",
  479. src_op->GetName().c_str(), peer_out_anchor->GetIdx(), tensor_size_attr,
  480. node_op_desc->GetName().c_str(), in_data_anchor->GetIdx());
  481. }
  482. }
  483. return SUCCESS;
  484. }
  485. Status GraphBuilder::UpdateDataInputSize(const ge::NodePtr &node_ptr) {
  486. const auto &op_desc = node_ptr->GetOpDesc();
  487. if (op_desc == nullptr) {
  488. GELOGE(FAILED, "Op desc is nullptr.");
  489. return FAILED;
  490. }
  491. // data op only has one output anchor
  492. ge::GeTensorDesc output_desc = op_desc->GetOutputDesc(0);
  493. int64_t output_size = 0;
  494. if (ge::TensorUtils::GetSize(output_desc, output_size) != SUCCESS) {
  495. GELOGW("Get size failed!");
  496. }
  497. if (output_size > 0) {
  498. GELOGI("No need to update data input size.");
  499. return SUCCESS;
  500. } else {
  501. int64_t real_dim_size = 0;
  502. ge::graphStatus graph_status = TensorUtils::GetTensorSizeInBytes(output_desc, real_dim_size);
  503. if (graph_status != GRAPH_SUCCESS) {
  504. GELOGE(FAILED, "Get tensor size in bytes failed.");
  505. return FAILED;
  506. }
  507. // data op only has one input anchor
  508. ge::GeTensorDesc input_desc = op_desc->GetInputDesc(0);
  509. ge::TensorUtils::SetSize(input_desc, real_dim_size);
  510. if (op_desc->UpdateInputDesc(0, input_desc) != GRAPH_SUCCESS) {
  511. GELOGE(FAILED, "Update input desc size failed.");
  512. return FAILED;
  513. }
  514. }
  515. return SUCCESS;
  516. }
  517. Status GraphBuilder::CalcDynShapeRootGraphDataSize(const ge::OpDescPtr &op_desc) {
  518. GELOGI("Begin to calc dynamic shape graph data[%s] size.", op_desc->GetName().c_str());
  519. // data op only has one output anchor
  520. ge::GeTensorDesc output_desc = op_desc->GetOutputDesc(0);
  521. if (output_desc.MutableShape().IsUnknownShape()) {
  522. GELOGI("No need to update dynamic shape graph data output size for unknown shape data.");
  523. return SUCCESS;
  524. }
  525. int64_t output_size = 0;
  526. if (ge::TensorUtils::GetSize(output_desc, output_size) != SUCCESS) {
  527. GELOGW("Get size failed!");
  528. }
  529. if (output_size > 0) {
  530. GELOGI("No need to update dynamic shape graph data output size[%ld].", output_size);
  531. return SUCCESS;
  532. } else {
  533. int64_t real_dim_size = 0;
  534. ge::graphStatus graph_status = TensorUtils::GetTensorSizeInBytes(output_desc, real_dim_size);
  535. if (graph_status != GRAPH_SUCCESS) {
  536. GELOGE(FAILED, "Get tensor size in bytes failed.");
  537. return FAILED;
  538. }
  539. ge::TensorUtils::SetSize(output_desc, real_dim_size);
  540. GELOGI("Update dynamic shape graph data output size to [%ld].", real_dim_size);
  541. if (op_desc->UpdateOutputDesc(0, output_desc) != GRAPH_SUCCESS) {
  542. GELOGE(FAILED, "Update dynamic shape graph data output desc size failed.");
  543. return FAILED;
  544. }
  545. }
  546. return SUCCESS;
  547. }
  548. Status GraphBuilder::SecondPartition(ge::ComputeGraphPtr &comp_graph, vector<ge::SubGraphInfoPtr> &subgraph_ptr_list) {
  549. GE_TIMESTAMP_START(GraphPartition2);
  550. auto ret = graph_partitioner_.Partition(comp_graph, GraphPartitioner::kSecondPartitioning);
  551. if (ret != SUCCESS) {
  552. GELOGE(ret, "Graph partition Failed");
  553. return ret;
  554. }
  555. GE_CHK_STATUS_RET(ret, "Graph partition Failed.");
  556. auto graph_2_subgraphlist = graph_partitioner_.GetSubGraphMap();
  557. if (graph_2_subgraphlist.find(comp_graph) != graph_2_subgraphlist.end()) {
  558. subgraph_ptr_list = graph_2_subgraphlist[comp_graph];
  559. } else {
  560. GELOGE(FAILED, "Find subgraph failed.");
  561. return FAILED;
  562. }
  563. GE_TIMESTAMP_END(GraphPartition2, "GraphPartitioner::Partition2");
  564. return ret;
  565. }
  566. Status GraphBuilder::AddOutputMemTypeForNode(const NodePtr &node) {
  567. auto op_desc = node->GetOpDesc();
  568. GE_CHECK_NOTNULL(op_desc);
  569. uint32_t mem_type;
  570. if (!AttrUtils::GetInt(op_desc, ATTR_INPUT_MEMORY_TYPE, mem_type)) {
  571. return SUCCESS;
  572. }
  573. GELOGD("[%s] has attr input_memory_type %ld", op_desc->GetName().c_str(), mem_type);
  574. for (const auto &in_data_anchor : node->GetAllInDataAnchors()) {
  575. const auto &peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  576. GE_IF_BOOL_EXEC(peer_out_anchor == nullptr, continue);
  577. bool valid_flag = false;
  578. auto src_node = peer_out_anchor->GetOwnerNode();
  579. auto src_out_anchor = peer_out_anchor;
  580. while (true) {
  581. const auto &src_desc = src_node->GetOpDesc();
  582. GE_IF_BOOL_EXEC(src_desc == nullptr, continue);
  583. GELOGD("[%s:%u] set attr output_memory_type %ld", src_desc->GetName().c_str(), src_out_anchor->GetIdx(),
  584. mem_type);
  585. if (!AttrUtils::SetInt(src_desc->MutableOutputDesc(src_out_anchor->GetIdx()), ATTR_OUTPUT_MEMORY_TYPE,
  586. mem_type)) {
  587. GELOGE(INTERNAL_ERROR, "Set out_memory_type attr for [%s:%d] failed.", src_desc->GetName().c_str(),
  588. src_out_anchor->GetIdx());
  589. return INTERNAL_ERROR;
  590. }
  591. switch (TransferNodeType(src_node)) {
  592. case kSubgraphNode:
  593. GE_CHK_STATUS_RET(HandleSubgraphNode(src_node, src_out_anchor), "Handle subgraph node %s failed",
  594. src_node->GetName().c_str());
  595. break;
  596. case kSubgraphData:
  597. GE_CHK_STATUS_RET(HandleSubgraphDataNode(src_node, src_out_anchor), "Handle Data node %s in subgraph failed",
  598. src_node->GetName().c_str());
  599. break;
  600. case kOthers:
  601. default:
  602. valid_flag = true;
  603. break;
  604. }
  605. if (valid_flag) {
  606. break;
  607. }
  608. }
  609. }
  610. return SUCCESS;
  611. }
  612. } // namespace ge

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