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
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
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
4 years ago
4 years ago
4 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  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. GE_CHECK_NOTNULL(in_node);
  289. OpDescBuilder op_desc_builder(name, MEMCPYADDRASYNC);
  290. OpDescPtr op_desc = op_desc_builder.AddInput("x", in_node->GetOpDesc()->GetOutputDesc(0))
  291. .AddOutput("y", in_node->GetOpDesc()->GetOutputDesc(0))
  292. .Build();
  293. (void)AttrUtils::SetBool(op_desc, ATTR_NO_NEED_CONSTANT_FOLDING, false);
  294. if (GraphUtils::InsertNodeAfter(out_anchor, in_anchors, graph->AddNode(op_desc)) != GRAPH_SUCCESS) {
  295. GELOGE(FAILED, "Insert IDENTITY node %s after %s failed.", name.c_str(), in_node->GetName().c_str());
  296. return FAILED;
  297. }
  298. return SUCCESS;
  299. }
  300. static Status GenerateTaskForConstant(const std::shared_ptr<ComputeGraph> &graph) {
  301. for (auto &node : graph->GetDirectNode()) {
  302. // CONSTANT not generate task, so insert IDENTITY between CONSTANT and NETOUTPUT
  303. auto op_desc = node->GetOpDesc();
  304. if (op_desc == nullptr) {
  305. continue;
  306. }
  307. auto op_type = op_desc->GetType();
  308. if (op_type == NETOUTPUT) {
  309. for (InDataAnchorPtr &in_data_anchor : node->GetAllInDataAnchors()) {
  310. const OutDataAnchorPtr &peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  311. GE_IF_BOOL_EXEC(peer_out_anchor == nullptr, continue);
  312. NodePtr in_node = peer_out_anchor->GetOwnerNode();
  313. GE_CHECK_NOTNULL(in_node);
  314. std::string in_node_op_type = in_node->GetType();
  315. if (in_node_op_type == CONSTANT) {
  316. GELOGD("Insert MemcpyAsync node between %s and %s.", in_node->GetName().c_str(), node->GetName().c_str());
  317. std::string name = node->GetName() + "_input_" + std::to_string(in_data_anchor->GetIdx()) + "_Memcpy";
  318. if (InsertMemcpyNode(graph, peer_out_anchor, {in_data_anchor}, name) != SUCCESS) {
  319. GELOGE(FAILED, "Insert memcpy between %s and %s failed.", in_node->GetName().c_str(), node->GetName().c_str());
  320. return FAILED;
  321. }
  322. }
  323. }
  324. }
  325. }
  326. return SUCCESS;
  327. }
  328. Status GraphBuilder::BuildForDynamicShapeGraph(ComputeGraphPtr &comp_graph,
  329. std::vector<SubGraphInfoPtr> &subgraph_ptr_list,
  330. GeRootModelPtr &ge_root_model_ptr, GeModelPtr &ge_model_ptr,
  331. uint64_t session_id) {
  332. GELOGI("Start to build BuildForDynamicShape for dynamic shape.");
  333. // Update Root Graph Data size
  334. for (auto &node : comp_graph->GetDirectNode()) {
  335. auto op_desc = node->GetOpDesc();
  336. GE_CHECK_NOTNULL(op_desc);
  337. op_desc->SetStreamId(kInvalidStream);
  338. if (node->GetType() == DATA) {
  339. GE_CHK_STATUS_RET(CalcDynShapeRootGraphDataSize(op_desc), "Calc dynamic shape root graph data[%s] size failed.",
  340. op_desc->GetName().c_str());
  341. }
  342. }
  343. //
  344. for (auto &sub_graph : comp_graph->GetAllSubgraphs()) {
  345. // exclude functional subgraph in known subgraph
  346. if (sub_graph->GetParentGraph() != comp_graph && !sub_graph->GetParentGraph()->GetGraphUnknownFlag()) {
  347. continue;
  348. }
  349. GE_CHK_STATUS_RET(GenerateTaskForConstant(sub_graph), "Generate task For constant node in subgraph failed.");
  350. if (sub_graph->GetGraphUnknownFlag()) {
  351. // unknown shape build flow
  352. GE_CHK_STATUS_RET(BuildForUnknownShapeGraph(sub_graph, ge_model_ptr, session_id),
  353. "Build for unknown shape graph failed.");
  354. } else {
  355. // reset functional subgraph parent graph as known subgraph
  356. for (const auto &node : sub_graph->GetDirectNode()) {
  357. for (const auto &sub_graph_name : node->GetOpDesc()->GetSubgraphInstanceNames()) {
  358. auto sub_sub_graph = comp_graph->GetSubgraph(sub_graph_name);
  359. GE_CHK_STATUS_RET(sub_graph->AddSubgraph(sub_sub_graph), "Failed add subgraph to known graph.");
  360. }
  361. }
  362. // known shape build flow
  363. GE_CHK_STATUS_RET(BuildForKnownShapeGraph(sub_graph, subgraph_ptr_list, ge_model_ptr, session_id),
  364. "Build for known shape graph failed.");
  365. }
  366. ge_root_model_ptr->SetSubgraphInstanceNameToModel(sub_graph->GetName(), ge_model_ptr);
  367. }
  368. return SUCCESS;
  369. }
  370. Status GraphBuilder::GetTaskInfo(const ge::ModelBuilder &builder, const ModelPtr &model_ptr,
  371. ComputeGraphPtr &comp_graph, Graph2SubGraphInfoList &subgraph_map,
  372. uint64_t session_id) {
  373. GE_CHECK_NOTNULL(model_ptr);
  374. GE_CHECK_NOTNULL(comp_graph);
  375. int64_t memory_size = 0;
  376. if (!AttrUtils::GetInt(model_ptr, ATTR_MODEL_MEMORY_SIZE, memory_size)) {
  377. GELOGE(INTERNAL_ERROR, "Get memory size fail.");
  378. return INTERNAL_ERROR;
  379. }
  380. int64_t p2p_memory_size = 0;
  381. if (!AttrUtils::GetInt(model_ptr, ATTR_MODEL_P2P_MEMORY_SIZE, p2p_memory_size)) {
  382. GELOGE(INTERNAL_ERROR, "Get p2p memory size fail.");
  383. return INTERNAL_ERROR;
  384. }
  385. int64_t weight_size = 0;
  386. if (!AttrUtils::GetInt(model_ptr, ATTR_MODEL_WEIGHT_SIZE, weight_size)) {
  387. GELOGE(INTERNAL_ERROR, "Get weight memory size fail.");
  388. return INTERNAL_ERROR;
  389. }
  390. auto var_manager = VarManager::Instance(session_id);
  391. // since var_mem_logic_base_ = graph_mem_max_size_ + kGraphMemoryBuffer in graph_var_manager.cc,
  392. // get_mem_base should not bigger than kGraphMemoryBuffer
  393. auto *get_mem_base = reinterpret_cast<uint8_t *>(reinterpret_cast<uintptr_t>(kGraphMemoryBuffer>>1));
  394. uint8_t *get_weight_mem_base = get_mem_base;
  395. if (weight_size > 0) {
  396. get_weight_mem_base = get_mem_base + memory_size + p2p_memory_size;
  397. }
  398. std::map<int64_t, uint8_t *> mem_type_to_data_mem_base;
  399. mem_type_to_data_mem_base[RT_MEMORY_HBM] = get_mem_base;
  400. if (p2p_memory_size == 0) {
  401. mem_type_to_data_mem_base[RT_MEMORY_P2P_DDR] = nullptr;
  402. } else {
  403. mem_type_to_data_mem_base[RT_MEMORY_P2P_DDR] = get_mem_base + memory_size;
  404. }
  405. std::map<int64_t, uint64_t> mem_type_to_data_mem_size;
  406. mem_type_to_data_mem_size[RT_MEMORY_HBM] = memory_size;
  407. mem_type_to_data_mem_size[RT_MEMORY_P2P_DDR] = p2p_memory_size;
  408. RunContextUtil run_context;
  409. Status ret = run_context.InitMemInfo(get_mem_base, memory_size, mem_type_to_data_mem_base, mem_type_to_data_mem_size,
  410. get_weight_mem_base, weight_size);
  411. if (ret != SUCCESS) {
  412. GELOGE(ret, "task_generator init mem info fail.");
  413. return ret;
  414. }
  415. auto weight_buffer = builder.GetWeightBuffer();
  416. ret = run_context.CreateRunContext(*model_ptr, comp_graph, weight_buffer, session_id);
  417. if (ret != SUCCESS) {
  418. GELOGE(ret, "runContext create run context fail.");
  419. return ret;
  420. }
  421. StreamGraphOptimizer stream_optimizer;
  422. ret = stream_optimizer.OptimizeStreamedSubGraph(comp_graph, subgraph_map, run_context.GetRunContext());
  423. if (ret != SUCCESS) {
  424. GELOGE(ret, "Optimize streamed subGraph fail.");
  425. return ret;
  426. }
  427. GE_DUMP(comp_graph, "AfterOptimizeStreamedSubGraph");
  428. auto *get_var_mem_base = reinterpret_cast<uint8_t *>(reinterpret_cast<uintptr_t>(var_manager->GetVarMemLogicBase()));
  429. uint64_t var_size = (var_manager->GetVarMemSize(RT_MEMORY_HBM) > 0) ? var_manager->GetVarMemMaxSize() : 0;
  430. TaskGenerator task_generator(get_var_mem_base, var_size);
  431. ret = task_generator.GetTaskInfo(*model_ptr, comp_graph, session_id, run_context.GetRunContext());
  432. return ret;
  433. }
  434. Status GraphBuilder::SetInputSize(const ge::NodePtr &node_ptr) {
  435. // set input_desc.size = src_node.output_desc.size
  436. if (node_ptr->GetType() == DATA) {
  437. bool is_unknown_shape = false;
  438. GE_CHK_STATUS_RET(ge::NodeUtils::GetNodeUnknownShapeStatus(*node_ptr, is_unknown_shape),
  439. "Get data node[%s] shape status failed!", node_ptr->GetName().c_str());
  440. if (is_unknown_shape) {
  441. GELOGD("data node: %s is unknown shape, do not set input size!", node_ptr->GetName().c_str());
  442. return SUCCESS;
  443. }
  444. if (UpdateDataInputSize(node_ptr) != SUCCESS) {
  445. GELOGE(FAILED, "Update data input size failed.");
  446. return FAILED;
  447. }
  448. }
  449. for (const auto &in_data_anchor : node_ptr->GetAllInDataAnchors()) {
  450. const auto &peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  451. GE_IF_BOOL_EXEC(peer_out_anchor == nullptr, continue);
  452. const auto &src_node = peer_out_anchor->GetOwnerNode();
  453. const auto &src_op = src_node->GetOpDesc();
  454. GE_IF_BOOL_EXEC(src_op == nullptr, continue);
  455. auto node_op_desc = node_ptr->GetOpDesc();
  456. GE_IF_BOOL_EXEC(node_op_desc == nullptr, continue);
  457. // set dst_node.input_desc = src_node.output_desc
  458. auto output_desc = src_op->GetOutputDescPtr(peer_out_anchor->GetIdx());
  459. int64_t size = 0;
  460. GE_IF_BOOL_EXEC(ge::TensorUtils::GetSize(*output_desc, size) != SUCCESS, GELOGI("Get size failed!"));
  461. GELOGD("src node %s output desc, dim_size: %zu, mem_size: %ld, format: %s, type: %s.", src_node->GetName().c_str(),
  462. output_desc->GetShape().GetDimNum(), size, TypeUtils::FormatToSerialString(output_desc->GetFormat()).c_str(),
  463. TypeUtils::DataTypeToSerialString(output_desc->GetDataType()).c_str());
  464. for (size_t i = 0; i < output_desc->GetShape().GetDimNum(); ++i) {
  465. GELOGD("dims[%zu]: %ld", i, output_desc->GetShape().GetDim(i));
  466. }
  467. auto input_desc = node_op_desc->MutableInputDesc(in_data_anchor->GetIdx());
  468. GE_CHECK_NOTNULL(input_desc);
  469. (void) ge::TensorUtils::SetSize(*input_desc, size);
  470. GE_CHK_STATUS_RET(node_op_desc->UpdateInputDesc(in_data_anchor->GetIdx(), *input_desc));
  471. GELOGD("%s input desc, dim_size: %zu, mem_size: %ld, format: %s, type: %s.", node_ptr->GetName().c_str(),
  472. input_desc->GetShape().GetDimNum(), size, TypeUtils::FormatToSerialString(input_desc->GetFormat()).c_str(),
  473. TypeUtils::DataTypeToSerialString(input_desc->GetDataType()).c_str());
  474. // inherit some attr
  475. int64_t tensor_size_attr;
  476. if (AttrUtils::GetInt(output_desc, ATTR_NAME_SPECIAL_OUTPUT_SIZE, tensor_size_attr) && (tensor_size_attr > 0)) {
  477. GE_IF_BOOL_EXEC(!AttrUtils::SetInt(*input_desc, ATTR_NAME_SPECIAL_OUTPUT_SIZE, tensor_size_attr),
  478. GELOGW("Set size attr failed!"); continue);
  479. GELOGD("node[%s] [%d]th output has sepcial size[%ld], and update to node[%s] [%d]th input",
  480. src_op->GetName().c_str(), peer_out_anchor->GetIdx(), tensor_size_attr,
  481. node_op_desc->GetName().c_str(), in_data_anchor->GetIdx());
  482. }
  483. }
  484. return SUCCESS;
  485. }
  486. Status GraphBuilder::UpdateDataInputSize(const ge::NodePtr &node_ptr) {
  487. const auto &op_desc = node_ptr->GetOpDesc();
  488. if (op_desc == nullptr) {
  489. GELOGE(FAILED, "Op desc is nullptr.");
  490. return FAILED;
  491. }
  492. // data op only has one output anchor
  493. ge::GeTensorDesc output_desc = op_desc->GetOutputDesc(0);
  494. int64_t output_size = 0;
  495. if (ge::TensorUtils::GetSize(output_desc, output_size) != SUCCESS) {
  496. GELOGW("Get size failed!");
  497. }
  498. if (output_size > 0) {
  499. GELOGI("No need to update data input size.");
  500. return SUCCESS;
  501. } else {
  502. int64_t real_dim_size = 0;
  503. ge::graphStatus graph_status = TensorUtils::GetTensorSizeInBytes(output_desc, real_dim_size);
  504. if (graph_status != GRAPH_SUCCESS) {
  505. GELOGE(FAILED, "Get tensor size in bytes failed.");
  506. return FAILED;
  507. }
  508. // data op only has one input anchor
  509. ge::GeTensorDesc input_desc = op_desc->GetInputDesc(0);
  510. ge::TensorUtils::SetSize(input_desc, real_dim_size);
  511. if (op_desc->UpdateInputDesc(0, input_desc) != GRAPH_SUCCESS) {
  512. GELOGE(FAILED, "Update input desc size failed.");
  513. return FAILED;
  514. }
  515. }
  516. return SUCCESS;
  517. }
  518. Status GraphBuilder::CalcDynShapeRootGraphDataSize(const ge::OpDescPtr &op_desc) {
  519. GELOGI("Begin to calc dynamic shape graph data[%s] size.", op_desc->GetName().c_str());
  520. // data op only has one output anchor
  521. ge::GeTensorDesc output_desc = op_desc->GetOutputDesc(0);
  522. if (output_desc.MutableShape().IsUnknownShape()) {
  523. GELOGI("No need to update dynamic shape graph data output size for unknown shape data.");
  524. return SUCCESS;
  525. }
  526. int64_t output_size = 0;
  527. if (ge::TensorUtils::GetSize(output_desc, output_size) != SUCCESS) {
  528. GELOGW("Get size failed!");
  529. }
  530. if (output_size > 0) {
  531. GELOGI("No need to update dynamic shape graph data output size[%ld].", output_size);
  532. return SUCCESS;
  533. } else {
  534. int64_t real_dim_size = 0;
  535. ge::graphStatus graph_status = TensorUtils::GetTensorSizeInBytes(output_desc, real_dim_size);
  536. if (graph_status != GRAPH_SUCCESS) {
  537. GELOGE(FAILED, "Get tensor size in bytes failed.");
  538. return FAILED;
  539. }
  540. ge::TensorUtils::SetSize(output_desc, real_dim_size);
  541. GELOGI("Update dynamic shape graph data output size to [%ld].", real_dim_size);
  542. if (op_desc->UpdateOutputDesc(0, output_desc) != GRAPH_SUCCESS) {
  543. GELOGE(FAILED, "Update dynamic shape graph data output desc size failed.");
  544. return FAILED;
  545. }
  546. }
  547. return SUCCESS;
  548. }
  549. Status GraphBuilder::SecondPartition(ge::ComputeGraphPtr &comp_graph, vector<ge::SubGraphInfoPtr> &subgraph_ptr_list) {
  550. GE_TIMESTAMP_START(GraphPartition2);
  551. auto ret = graph_partitioner_.Partition(comp_graph, GraphPartitioner::kSecondPartitioning);
  552. if (ret != SUCCESS) {
  553. GELOGE(ret, "Graph partition Failed");
  554. return ret;
  555. }
  556. GE_CHK_STATUS_RET(ret, "Graph partition Failed.");
  557. auto graph_2_subgraphlist = graph_partitioner_.GetSubGraphMap();
  558. if (graph_2_subgraphlist.find(comp_graph) != graph_2_subgraphlist.end()) {
  559. subgraph_ptr_list = graph_2_subgraphlist[comp_graph];
  560. } else {
  561. GELOGE(FAILED, "Find subgraph failed.");
  562. return FAILED;
  563. }
  564. GE_TIMESTAMP_END(GraphPartition2, "GraphPartitioner::Partition2");
  565. return ret;
  566. }
  567. Status GraphBuilder::AddOutputMemTypeForNode(const NodePtr &node) {
  568. auto op_desc = node->GetOpDesc();
  569. GE_CHECK_NOTNULL(op_desc);
  570. uint32_t mem_type;
  571. if (!AttrUtils::GetInt(op_desc, ATTR_INPUT_MEMORY_TYPE, mem_type)) {
  572. return SUCCESS;
  573. }
  574. GELOGD("[%s] has attr input_memory_type %ld", op_desc->GetName().c_str(), mem_type);
  575. for (const auto &in_data_anchor : node->GetAllInDataAnchors()) {
  576. const auto &peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  577. GE_IF_BOOL_EXEC(peer_out_anchor == nullptr, continue);
  578. bool valid_flag = false;
  579. auto src_node = peer_out_anchor->GetOwnerNode();
  580. auto src_out_anchor = peer_out_anchor;
  581. while (true) {
  582. const auto &src_desc = src_node->GetOpDesc();
  583. GE_IF_BOOL_EXEC(src_desc == nullptr, continue);
  584. GELOGD("[%s:%u] set attr output_memory_type %ld", src_desc->GetName().c_str(), src_out_anchor->GetIdx(),
  585. mem_type);
  586. if (!AttrUtils::SetInt(src_desc->MutableOutputDesc(src_out_anchor->GetIdx()), ATTR_OUTPUT_MEMORY_TYPE,
  587. mem_type)) {
  588. GELOGE(INTERNAL_ERROR, "Set out_memory_type attr for [%s:%d] failed.", src_desc->GetName().c_str(),
  589. src_out_anchor->GetIdx());
  590. return INTERNAL_ERROR;
  591. }
  592. switch (TransferNodeType(src_node)) {
  593. case kSubgraphNode:
  594. GE_CHK_STATUS_RET(HandleSubgraphNode(src_node, src_out_anchor), "Handle subgraph node %s failed",
  595. src_node->GetName().c_str());
  596. break;
  597. case kSubgraphData:
  598. GE_CHK_STATUS_RET(HandleSubgraphDataNode(src_node, src_out_anchor), "Handle Data node %s in subgraph failed",
  599. src_node->GetName().c_str());
  600. break;
  601. case kOthers:
  602. default:
  603. valid_flag = true;
  604. break;
  605. }
  606. if (valid_flag) {
  607. break;
  608. }
  609. }
  610. }
  611. return SUCCESS;
  612. }
  613. } // namespace ge

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