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.

multi_batch_clone_pass.cc 52 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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  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/passes/multi_batch_clone_pass.h"
  17. #include "common/formats/utils/formats_trans_utils.h"
  18. #include "common/ge/ge_util.h"
  19. #include "graph/common/local_context.h"
  20. #include "graph/preprocess/multi_batch_options.h"
  21. #include "graph/utils/node_utils.h"
  22. #include "graph/utils/op_desc_utils.h"
  23. #include "graph/utils/tensor_utils.h"
  24. #include "graph/utils/type_utils.h"
  25. #include "register/op_registry.h"
  26. #include "graph/common/omg_util.h"
  27. namespace ge {
  28. namespace {
  29. constexpr uint8_t kDataInIndex = 0;
  30. constexpr uint8_t kDataOutIndex = 0;
  31. constexpr uint8_t kCaseArgIndex = 1;
  32. const int kDivisionConst = 2;
  33. const size_t kNumOfGetnextNode = 1;
  34. const std::string kMultiBatchCaseNode = "ascend_mbatch_shape_case";
  35. const std::string kMultiBatchDataNode = "ascend_mbatch_shape_data";
  36. const std::string kMultiBatchGetDynamicDimsNode = "ascend_mbatch_get_dynamic_dims_node";
  37. const std::string kMultiBatchConstNode = "ascend_mbatch_shape_const";
  38. const std::string kMultiBatchMapIndexNode = "ascend_mbatch_shape_mapindex";
  39. const std::string kMultiBatchNodePostfix = "_ascend_mbatch_batch_";
  40. const char *const kGetNextName = "IteratorV2";
  41. } // namespace
  42. inline bool IsGetNextType(const NodePtr &node) {
  43. std::string original_type;
  44. GE_IF_BOOL_EXEC(GetOriginalType(node, original_type) != SUCCESS,
  45. GELOGW("Get original type failed."); return false);
  46. return (original_type == kGetNextName);
  47. }
  48. Status MultiBatchClonePass::Run(ComputeGraphPtr graph) {
  49. GE_IF_BOOL_EXEC(graph == nullptr, GELOGE(FAILED, "Original graph is nullptr"); return FAILED);
  50. if (graph->GetParentGraph() != nullptr) {
  51. GELOGD("Subgraph %s skip the MultiBatchClonePass", graph->GetName().c_str());
  52. return SUCCESS;
  53. }
  54. if (!GetLocalOmgContext().need_multi_batch) {
  55. GELOGI("No need to process_multi for no_train graph.");
  56. return SUCCESS;
  57. }
  58. std::vector<NodePtr> data_nodes;
  59. std::vector<NodePtr> getnext_nosink_nodes;
  60. std::vector<NodePtr> getnext_sink_nodes;
  61. if (multibatch::CheckSequenceOfOptions(graph, data_nodes, getnext_nosink_nodes, getnext_sink_nodes) != SUCCESS) {
  62. GELOGE(PARAM_INVALID, "[Train_Dynamic] CheckSequenceOfOptions failed.");
  63. return PARAM_INVALID;
  64. }
  65. if (multibatch::UpdateNameOfInputShape(graph, data_nodes, getnext_nosink_nodes, getnext_sink_nodes) != SUCCESS) {
  66. GELOGE(PARAM_INVALID, "[Train_Dynamic] UpdateNameForInputShapeOfOption failed.");
  67. return PARAM_INVALID;
  68. }
  69. if (multibatch::DeleteIdentityInsertByAdapter(graph) != SUCCESS) {
  70. GELOGE(PARAM_INVALID, "[Train_Dynamic] DeleteIdentityInsertByAdapter failed.");
  71. return PARAM_INVALID;
  72. }
  73. if (!multibatch::InitDynamicParams(batch_shapes_)) {
  74. GELOGD("There is no multi-batch options, no need clone multi-batch graph");
  75. return SUCCESS;
  76. }
  77. if (multibatch::CheckNegativeCountOfOptions(batch_shapes_) != SUCCESS) {
  78. GELOGE(PARAM_INVALID, "[Train_Dynamic] Input_shape and dynamic_dims should set correct params.");
  79. return PARAM_INVALID;
  80. }
  81. GELOGD("Begin to run Multi-batch clone on graph: %s", graph->GetName().c_str());
  82. GE_CHK_STATUS_RET(multibatch::CheckDynamicParams(batch_shapes_), "Invalid multi-batch param");
  83. if (CollectIoNodes(graph) != SUCCESS) {
  84. GELOGE(INTERNAL_ERROR, "Collect input output nodes failed");
  85. return INTERNAL_ERROR;
  86. }
  87. // parser data dynamic info from atc parameter --input_shape
  88. if (CheckAndParseDynamicData() != SUCCESS) {
  89. GELOGE(PARAM_INVALID, "Parse each data's own dynamic info failed");
  90. return PARAM_INVALID;
  91. }
  92. (void)AttrUtils::GetStr(graph, ATTR_NAME_SESSION_GRAPH_ID, session_graph_id_);
  93. ComputeGraphPtr branch = MakeShared<ComputeGraph>(graph->GetName());
  94. GE_IF_BOOL_EXEC(branch == nullptr, GELOGE(OUT_OF_MEMORY, "Create multi batch graph failed"); return OUT_OF_MEMORY);
  95. (void)AttrUtils::SetStr(branch, ATTR_NAME_SESSION_GRAPH_ID, session_graph_id_);
  96. graph->InValid(); // Will modify, need topological again.
  97. graph->Swap(*branch);
  98. GE_CHK_STATUS_RET(CreateRootGraph(graph), "Construct root graph failed.");
  99. GE_CHK_STATUS_RET(CreateOriGraph(branch), "Construct original graph failed.")
  100. GE_CHK_STATUS_RET(CreateSubgraphs(graph, branch), "Construct subgraph failed.");
  101. GE_CHK_STATUS_RET(PruneDirectOutput(graph), "Prune direct output failed");
  102. GELOGD("MultiBatchClonePass Leave");
  103. return SUCCESS;
  104. }
  105. ///
  106. /// @ingroup ge
  107. /// @brief Collect input output node from original graph.
  108. /// @param [in] const ComputeGraphPtr &graph: original graph.
  109. /// @return 0: SUCCESS / others: FAILED
  110. ///
  111. Status MultiBatchClonePass::CollectIoNodes(const ComputeGraphPtr &graph) {
  112. for (const auto &node : graph->GetDirectNode()) {
  113. if (!GetLocalOmgContext().dynamic_node_type.empty() && IsGetNextType(node)) {
  114. all_data_nodes_.emplace_back(node);
  115. GE_CHK_STATUS_RET(InitParamsOfGetNext(node), "Init params of %s failed.", node->GetName().c_str());
  116. }
  117. if (node->GetType() == DATA) {
  118. all_data_nodes_.emplace_back(node);
  119. } else if (node->GetType() == CONSTANT || node->GetType() == CONSTANTOP) {
  120. all_const_nodes_.emplace_back(node);
  121. } else if (node->GetType() == NETOUTPUT) {
  122. all_output_nodes_.emplace_back(node);
  123. }
  124. // If the node save as input/output node, delete record.
  125. (void)graph->RemoveInputNode(node);
  126. (void)graph->RemoveOutputNode(node);
  127. }
  128. if (all_data_nodes_.empty() || all_output_nodes_.size() != 1) {
  129. GELOGE(FAILED, "data nodes: %zu, output nodes: %zu", all_data_nodes_.size(), all_output_nodes_.size());
  130. return FAILED;
  131. }
  132. int64_t data_index = 0;
  133. size_t getnext_node_count = 0;
  134. for (size_t i = 0; i < all_data_nodes_.size(); ++i) {
  135. if (IsGetNextType(all_data_nodes_[i])) {
  136. // just one getnext node in graph
  137. getnext_node_count++;
  138. continue;
  139. }
  140. const auto &op_desc = all_data_nodes_[i]->GetOpDesc();
  141. if (!AttrUtils::GetInt(op_desc, ATTR_NAME_INDEX, data_index)) {
  142. (void)AttrUtils::SetInt(op_desc, ATTR_NAME_INDEX, i - getnext_node_count);
  143. }
  144. }
  145. const auto &output = all_output_nodes_[0];
  146. for (size_t i = 0; i < output->GetAllInDataAnchorsSize(); ++i) {
  147. const auto in_anchor = output->GetInDataAnchor(i);
  148. const auto out_anchor = in_anchor->GetPeerOutAnchor();
  149. const auto data_node = out_anchor->GetOwnerNode();
  150. if (data_node->GetType() == DATA) {
  151. direct_output_[i] = data_node->GetName();
  152. GE_CHK_GRAPH_STATUS_RET(
  153. GraphUtils::RemoveEdge(data_node->GetOutDataAnchor(kDataOutIndex), output->GetInDataAnchor(i)),
  154. "Remove edge failed");
  155. }
  156. }
  157. GELOGD("Data count is %zu, const count is %zu, getnext count is %zu, output count is %zu, direct out count is %zu.",
  158. all_data_nodes_.size(), all_const_nodes_.size(), getnext_node_count, all_output_nodes_.size(),
  159. direct_output_.size());
  160. return SUCCESS;
  161. }
  162. Status MultiBatchClonePass::CheckAndParseDynamicData() {
  163. size_t unknown_shape_count = 0;
  164. auto data_name_and_shape = GetLocalOmgContext().user_input_dims;
  165. std::vector<std::string> data_name_order;
  166. for (auto &item : data_name_and_shape) {
  167. data_name_order.push_back(item.first);
  168. }
  169. if (!getnext_sink_dynamic_dims_) {
  170. for (const auto &node : all_data_nodes_) {
  171. auto data_desc = NodeUtils::GetOutputDesc(*node, kDataOutIndex);
  172. auto data_shape = data_desc.GetShape();
  173. auto data_format = data_desc.GetFormat() == Format::FORMAT_NCHW ? "NCHW" :
  174. data_desc.GetFormat() == Format::FORMAT_NHWC ? "NHWC" : "Others";
  175. auto data_name = node->GetName();
  176. const auto &data_shape_dims = data_shape.GetDims();
  177. if (std::all_of(data_shape_dims.begin(), data_shape_dims.end(), [](int64_t val) { return val >= 0; })) {
  178. continue;
  179. }
  180. ++unknown_shape_count;
  181. auto iter = find(data_name_order.begin(), data_name_order.end(), data_name);
  182. if (iter == data_name_order.end()) {
  183. if (!GetLocalOmgContext().dynamic_batch_size.empty()) {
  184. auto ret = multibatch::CheckDynamicBatchShape(data_shape_dims, data_name);
  185. GE_IF_BOOL_EXEC(ret == false, GELOGE(PARAM_INVALID, "Failed to check dynamic batch shape of %s.",
  186. data_name.c_str()); return PARAM_INVALID);
  187. } else if (!GetLocalOmgContext().dynamic_image_size.empty()) {
  188. auto ret = multibatch::CheckDynamicImageSizeShape(data_shape_dims, data_name, data_format);
  189. GE_IF_BOOL_EXEC(ret == false, GELOGE(PARAM_INVALID, "Failed to check dynamic image size shape of %s.",
  190. data_name.c_str()); return PARAM_INVALID);
  191. } else if (!GetLocalOmgContext().dynamic_dims.empty()) {
  192. ErrorManager::GetInstance().ATCReportErrMessage("E10001", {"parameter", "reason"},
  193. {"--input_shape", "all dynamic data must be set in --input_shape"});
  194. GELOGE(INTERNAL_ERROR, "data: %s shape:%s must be set int --input_shape",
  195. node->GetName().c_str(), data_shape.ToString().c_str());
  196. return INTERNAL_ERROR;
  197. }
  198. data_name_and_shape.emplace_back(data_name, data_shape_dims);
  199. }
  200. }
  201. }
  202. auto ret = multibatch::ParserDataToDynamicInfo(batch_shapes_, data_name_and_shape, data_to_dynamic_info_);
  203. GE_CHK_STATUS_RET(ret, "Failed to parse data to dynamic info.");
  204. if (!getnext_sink_dynamic_dims_ && unknown_shape_count == 0) {
  205. ErrorManager::GetInstance().ATCReportErrMessage("E10040");
  206. GELOGE(PARAM_INVALID,
  207. "Need unknow shape data when user set --dynamic_batch_size, --dynamic_image_size or --dynamic_dims");
  208. return PARAM_INVALID;
  209. }
  210. return SUCCESS;
  211. }
  212. Status MultiBatchClonePass::InitParamsOfGetNext(const NodePtr &node) {
  213. data_count_from_getnext_ = 0;
  214. getnext_sink_dynamic_dims_ = false;
  215. GE_CHECK_NOTNULL(node->GetOpDesc());
  216. data_count_from_getnext_ = node->GetOpDesc()->GetOutputsSize();
  217. if (GetLocalOmgContext().dynamic_node_type == GETNEXT) {
  218. data_count_from_getnext_ = data_count_from_getnext_ / kDivisionConst;
  219. for (size_t i = 0; i < data_count_from_getnext_; ++i) {
  220. GeTensorDesc output_desc = node->GetOpDesc()->GetOutputDesc(i);
  221. GELOGD("The %zu data shape from getnext sink is %s.", i,
  222. formats::JoinToString(output_desc.GetShape().GetDims()).c_str());
  223. const auto &dims = output_desc.GetShape().GetDims();
  224. if (std::all_of(dims.begin(), dims.end(), [](int64_t val) {return val >= 0; })) {
  225. GELOGD("The %zu data from %s is static.", i, node->GetName().c_str());
  226. } else {
  227. getnext_sink_dynamic_dims_ = true;
  228. GELOGD("Dynamic dims in the pattern of getnext sink.");
  229. }
  230. }
  231. }
  232. if (node->GetOutControlAnchor() != nullptr) {
  233. for (const auto &peer_in_control_anchor : node->GetOutControlAnchor()->GetPeerInControlAnchors()) {
  234. NodePtr next_node = peer_in_control_anchor->GetOwnerNode();
  235. GE_CHECK_NOTNULL(next_node);
  236. if (next_node->GetType() == CONSTANTOP) {
  237. out_control_nodes_.insert(next_node);
  238. GELOGD("Control edge: %s connect with %s.", node->GetName().c_str(), next_node->GetName().c_str());
  239. }
  240. }
  241. }
  242. return SUCCESS;
  243. }
  244. ///
  245. /// @ingroup ge
  246. /// @brief Create nodes for root graph.
  247. /// @param [in] const ComputeGraphPtr &graph: Root/Case graph.
  248. /// @return 0: SUCCESS / others: FAILED
  249. ///
  250. Status MultiBatchClonePass::CreateRootGraph(const ComputeGraphPtr &graph) {
  251. GELOGD("Start create root graph of %s.", graph->GetName().c_str());
  252. uint32_t input_num = all_data_nodes_.size() + all_const_nodes_.size();
  253. if (data_count_from_getnext_ != 0) {
  254. input_num = input_num + data_count_from_getnext_ - kNumOfGetnextNode;
  255. }
  256. uint32_t output_num = all_output_nodes_[0]->GetAllInDataAnchorsSize();
  257. OpDescBuilder op_builder(kMultiBatchCaseNode, CASE);
  258. op_builder.AddInput("branch_index").AddDynamicInput("input", input_num).AddDynamicOutput("output", output_num);
  259. const OpDescPtr op_desc = op_builder.Build();
  260. if (op_desc == nullptr) {
  261. GELOGE(OUT_OF_MEMORY, "Create multi-batch case desc failed");
  262. return OUT_OF_MEMORY;
  263. }
  264. op_desc->RegisterSubgraphIrName("branches", kDynamic);
  265. case_node_ = graph->AddNode(op_desc);
  266. if (case_node_ == nullptr) {
  267. GELOGE(OUT_OF_MEMORY, "Create multi-batch case node failed");
  268. return OUT_OF_MEMORY;
  269. }
  270. uint32_t batch_num = static_cast<uint32_t>(batch_shapes_.size());
  271. if (!AttrUtils::SetInt(op_desc, ATTR_NAME_BATCH_NUM, batch_num)) {
  272. GELOGE(FAILED, "Set attr ATTR_NAME_BATCH_NUM failed, Case: %s.", op_desc->GetName().c_str());
  273. return FAILED;
  274. }
  275. for (uint32_t i = 0; i < batch_num; i++) {
  276. const std::string &attr_name = ATTR_NAME_PRED_VALUE + "_" + std::to_string(i);
  277. if (!AttrUtils::SetListInt(op_desc, attr_name, batch_shapes_[i])) {
  278. GELOGE(FAILED, "Set attr ATTR_NAME_PRED_VALUE failed, Case: %s.", op_desc->GetName().c_str());
  279. return FAILED;
  280. }
  281. }
  282. std::vector<std::string> data_name_order;
  283. for (auto &item : GetLocalOmgContext().user_input_dims) {
  284. data_name_order.push_back(item.first);
  285. }
  286. if (!AttrUtils::SetListStr(op_desc, ATTR_USER_DESIGNEATE_SHAPE_ORDER, data_name_order)) {
  287. GELOGE(FAILED, "Failed to add user designate shape order attr on case node %s",
  288. op_desc->GetName().c_str());
  289. return FAILED;
  290. }
  291. if (!AttrUtils::SetBool(op_desc, ATTR_INSERT_BY_MBATCH, true)) {
  292. GELOGE(INTERNAL_ERROR, "Failed to add insert attr on case node %s", op_desc->GetName().c_str());
  293. return INTERNAL_ERROR;
  294. }
  295. GE_CHK_STATUS_RET(multibatch::StampDynamicType(op_desc), "Set dynamic type failed");
  296. GE_CHK_STATUS_RET(CreateIndexNode(graph), "Create index node failed");
  297. GE_CHK_STATUS_RET(CreateInputNode(graph), "Create input node failed");
  298. GE_CHK_STATUS_RET(CreateConstNode(graph), "Create const node failed");
  299. GE_CHK_STATUS_RET(CreateOutputNode(graph), "Create output node failed");
  300. return SUCCESS;
  301. }
  302. ///
  303. /// @ingroup ge
  304. /// @brief Create index data node for root graph.
  305. /// @param [in] const ComputeGraphPtr &graph: Root/Case graph.
  306. /// @param [in] NodePtr node: index data node.
  307. /// @return 0: SUCCESS / others: FAILED
  308. ///
  309. Status MultiBatchClonePass::CreateIndexDataNode(const ComputeGraphPtr &graph, NodePtr &shape_node) {
  310. const OpDescPtr data_desc = MakeShared<OpDesc>(kMultiBatchDataNode, DATA);
  311. if (data_desc == nullptr) {
  312. GELOGE(OUT_OF_MEMORY, "Create multi-batch data node failed");
  313. return FAILED;
  314. }
  315. GeTensorDesc data_tensor(GeShape({static_cast<int64_t>(batch_shapes_[0].size())}), FORMAT_ND, DT_INT32);
  316. if (data_desc->AddInputDesc(data_tensor) != GRAPH_SUCCESS) {
  317. GELOGE(FAILED, "Add input desc failed");
  318. return FAILED;
  319. }
  320. if (data_desc->AddOutputDesc(data_tensor) != GRAPH_SUCCESS) {
  321. GELOGE(FAILED, "Add output desc failed");
  322. return FAILED;
  323. }
  324. size_t data_index = all_data_nodes_.size();
  325. data_index = data_count_from_getnext_ != 0 ? data_index - kNumOfGetnextNode : data_index;
  326. (void)AttrUtils::SetInt(data_desc, ATTR_NAME_INDEX, data_index);
  327. (void)AttrUtils::SetBool(data_desc, ATTR_INSERT_BY_MBATCH, true);
  328. shape_node = graph->AddNode(data_desc);
  329. if (shape_node == nullptr) {
  330. GELOGE(OUT_OF_MEMORY, "Create multi-batch data node failed");
  331. return OUT_OF_MEMORY;
  332. }
  333. return SUCCESS;
  334. }
  335. ///
  336. /// @ingroup ge
  337. /// @brief Create index const node for root graph.
  338. /// @param [in] const ComputeGraphPtr &graph: Root/Case graph.
  339. /// @param [in] NodePtr node: index const node.
  340. /// @return 0: SUCCESS / others: FAILED
  341. ///
  342. Status MultiBatchClonePass::CreateIndexConstNode(const ComputeGraphPtr &graph, NodePtr &node) {
  343. const OpDescPtr const_desc = MakeShared<OpDesc>(kMultiBatchConstNode, CONSTANT);
  344. if (const_desc == nullptr) {
  345. GELOGE(OUT_OF_MEMORY, "Create multi-batch const node failed");
  346. return FAILED;
  347. }
  348. int64_t count = batch_shapes_.size() * batch_shapes_[0].size();
  349. std::unique_ptr<int32_t[]> addr(new (std::nothrow) int32_t[count]);
  350. GE_CHECK_NOTNULL(addr);
  351. size_t i = 0;
  352. for (auto &batch_shape : batch_shapes_) {
  353. for (int64_t dim : batch_shape) {
  354. addr[i++] = static_cast<int32_t>(dim);
  355. }
  356. }
  357. GeTensorDesc const_tensor(GeShape({count}), FORMAT_ND, DT_INT32);
  358. GeTensor tensor(const_tensor);
  359. (void)tensor.SetData(reinterpret_cast<uint8_t *>(addr.get()), count * sizeof(int32_t));
  360. if (!AttrUtils::SetTensor(const_desc, ATTR_NAME_WEIGHTS, tensor)) {
  361. GELOGE(OUT_OF_MEMORY, "Failed to init tensor value for const %s", const_desc->GetName().c_str());
  362. return FAILED;
  363. }
  364. if (const_desc->AddOutputDesc(const_tensor) != GRAPH_SUCCESS) {
  365. GELOGE(OUT_OF_MEMORY, "Failed to add output desc for const node %s", const_desc->GetName().c_str());
  366. return FAILED;
  367. }
  368. node = graph->AddNode(const_desc);
  369. if (node == nullptr) {
  370. GELOGE(OUT_OF_MEMORY, "Create multi-batch const node failed");
  371. return OUT_OF_MEMORY;
  372. }
  373. return SUCCESS;
  374. }
  375. ///
  376. /// @ingroup ge
  377. /// @brief Create index node for root graph.
  378. /// @param [in] const ComputeGraphPtr &graph: Root/Case graph.
  379. /// @return 0: SUCCESS / others: FAILED
  380. ///
  381. Status MultiBatchClonePass::CreateIndexNode(const ComputeGraphPtr &graph) {
  382. // Data/GetDynamicDims --> MapIndex --> Case
  383. if (!getnext_sink_dynamic_dims_) {
  384. GE_CHK_STATUS_RET(CreateIndexDataNode(graph, shape_node_), "Create data node failed");
  385. } else {
  386. GE_CHK_STATUS_RET(CreateGetDynamicDimsNode(graph, shape_node_), "Create get dynamic dims node failed");
  387. }
  388. NodePtr const_node;
  389. GE_CHK_STATUS_RET(CreateIndexConstNode(graph, const_node), "Create const node failed");
  390. GELOGD("Shape node name is %s, type is %s, const node name is %s.", shape_node_->GetName().c_str(),
  391. shape_node_->GetType().c_str(), const_node->GetName().c_str());
  392. OpDescBuilder op_builder(kMultiBatchMapIndexNode, "MapIndex");
  393. op_builder.AddInput("x", shape_node_->GetOpDesc()->GetOutputDesc(0))
  394. .AddInput("data_seq", const_node->GetOpDesc()->GetOutputDesc(0))
  395. .AddOutput("y", GeTensorDesc(GeShape(), FORMAT_ND, DT_INT32));
  396. const OpDescPtr op_desc = op_builder.Build();
  397. if (op_desc == nullptr) {
  398. GELOGE(OUT_OF_MEMORY, "Create multi-batch index desc failed");
  399. return FAILED;
  400. }
  401. NodePtr index_node = graph->AddNode(op_desc);
  402. if (index_node == nullptr) {
  403. GELOGE(OUT_OF_MEMORY, "Create multi-batch index node failed");
  404. return OUT_OF_MEMORY;
  405. }
  406. GE_CHK_STATUS_RET(AddAttrForGetDynamicDims(shape_node_), "Failed to add attr for %s.",
  407. shape_node_->GetName().c_str());
  408. if (GraphUtils::AddEdge(shape_node_->GetOutDataAnchor(0), index_node->GetInDataAnchor(0)) != GRAPH_SUCCESS) {
  409. GELOGE(FAILED, "Failed to add edge between node:%s to MapIndex:%s", shape_node_->GetName().c_str(),
  410. index_node->GetName().c_str());
  411. return FAILED;
  412. }
  413. if (GraphUtils::AddEdge(const_node->GetOutDataAnchor(0), index_node->GetInDataAnchor(1)) != GRAPH_SUCCESS) {
  414. GELOGE(FAILED, "Failed to add edge between node:%s to MapIndex:%s", const_node->GetName().c_str(),
  415. index_node->GetName().c_str());
  416. return FAILED;
  417. }
  418. if (GraphUtils::AddEdge(index_node->GetOutDataAnchor(0), case_node_->GetInDataAnchor(0)) != GRAPH_SUCCESS) {
  419. GELOGE(FAILED, "Failed to add edge between MapIndex:%s to Case:%s", index_node->GetName().c_str(),
  420. case_node_->GetName().c_str());
  421. return FAILED;
  422. }
  423. return SUCCESS;
  424. }
  425. Status MultiBatchClonePass::CreateGetDynamicDimsNode(const ComputeGraphPtr &graph, NodePtr &shape_node) {
  426. const OpDescPtr data_desc = MakeShared<OpDesc>(kMultiBatchGetDynamicDimsNode, GETDYNAMICDIMS);
  427. if (data_desc == nullptr) {
  428. GELOGE(OUT_OF_MEMORY, "Create multi-batch get dynamic dims node failed");
  429. return OUT_OF_MEMORY;
  430. }
  431. // input of GetDynamicDims is shape_of_each_data, output is gear_info
  432. for (size_t i = 0; i < GetLocalOmgContext().user_input_dims.size(); ++i) {
  433. size_t input_shape_dims = GetLocalOmgContext().user_input_dims.at(i).second.size();
  434. // add input desc without GeShape for const input, value of input_shape is 1 transferred by adapter
  435. if (input_shape_dims == 1 && GetLocalOmgContext().user_input_dims.at(i).second.at(0) == 0) {
  436. GeTensorDesc tensor_desc;
  437. tensor_desc.SetFormat(FORMAT_ND);
  438. tensor_desc.SetDataType(DT_INT32);
  439. auto ret = data_desc->AddInputDesc(tensor_desc);
  440. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to add input desc for created data");
  441. return FAILED);
  442. continue;
  443. }
  444. GeTensorDesc tensor_desc(GeShape({static_cast<int32_t>(input_shape_dims)}), FORMAT_ND, DT_INT32);
  445. auto ret = data_desc->AddInputDesc(tensor_desc);
  446. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to add input desc for created data");
  447. return FAILED);
  448. }
  449. GeTensorDesc tensor_desc(GeShape({static_cast<int32_t>(batch_shapes_.at(0).size())}), FORMAT_ND, DT_INT32);
  450. auto ret = data_desc->AddOutputDesc(tensor_desc);
  451. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to add output desc for created data");
  452. return FAILED);
  453. (void)AttrUtils::SetBool(data_desc, ATTR_INSERT_BY_MBATCH, true);
  454. shape_node = graph->AddNode(data_desc);
  455. if (shape_node == nullptr) {
  456. GELOGE(OUT_OF_MEMORY, "Create multi-batch dynamic dims node failed");
  457. return OUT_OF_MEMORY;
  458. }
  459. return SUCCESS;
  460. }
  461. Status MultiBatchClonePass::AddAttrForGetDynamicDims(const NodePtr &shape_node) {
  462. if (!getnext_sink_dynamic_dims_) {
  463. GELOGD("No need to add attr when not insert get dynamic dims node.");
  464. return SUCCESS;
  465. }
  466. GELOGD("Add attr for :%s, type is %s:", shape_node->GetName().c_str(), shape_node->GetType().c_str());
  467. if (!AttrUtils::SetInt(shape_node->GetOpDesc(), ATTR_GETNEXT_SINK_DATA_COUNT, data_count_from_getnext_)) {
  468. GELOGE(INTERNAL_ERROR, "set ATTR_GETNEXT_SINK_DATA_COUNT failed");
  469. return INTERNAL_ERROR;
  470. }
  471. vector<int64_t> shape_info;
  472. for (size_t i = 0; i < GetLocalOmgContext().user_input_dims.size(); ++i) {
  473. if (GetLocalOmgContext().user_input_dims.at(i).second.size() == 1 &&
  474. GetLocalOmgContext().user_input_dims.at(i).second.at(0) == 0) {
  475. shape_info.emplace_back(0);
  476. continue;
  477. }
  478. shape_info.emplace_back(GetLocalOmgContext().user_input_dims.at(i).second.size());
  479. for (size_t j = 0; j < GetLocalOmgContext().user_input_dims.at(i).second.size(); ++j) {
  480. shape_info.emplace_back(GetLocalOmgContext().user_input_dims.at(i).second.at(j));
  481. }
  482. }
  483. if (!AttrUtils::SetListInt(shape_node->GetOpDesc(), ATTR_GETNEXT_SINK_SHAPE_INFO, shape_info)) {
  484. GELOGE(INTERNAL_ERROR, "set ATTR_GETNEXT_SINK_SHAPE_INFO failed");
  485. return INTERNAL_ERROR;
  486. }
  487. return SUCCESS;
  488. }
  489. Status MultiBatchClonePass::LinkGetNextToGetDynamicDims(const NodePtr &getnext_node, const NodePtr &shape_node) {
  490. GELOGD("Start relink shape anchor of %s to %s.", getnext_node->GetName().c_str(), shape_node->GetName().c_str());
  491. size_t input_index = 0;
  492. size_t data_count = getnext_node->GetAllOutDataAnchors().size() / kDivisionConst;
  493. for (size_t out_index = data_count; out_index < getnext_node->GetAllOutDataAnchors().size(); ++out_index,
  494. ++input_index) {
  495. GELOGD("Start add %s of %zu out_anchor to %s of %zu in_anchor.", getnext_node->GetName().c_str(), out_index,
  496. shape_node->GetName().c_str(), input_index);
  497. auto out_data_anchor = getnext_node->GetOutDataAnchor(out_index);
  498. auto ret = GraphUtils::AddEdge(out_data_anchor, shape_node->GetInDataAnchor(input_index));
  499. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to link getnext %s to getdynamicdims %s",
  500. getnext_node->GetName().c_str(), shape_node->GetName().c_str());
  501. return INTERNAL_ERROR);
  502. }
  503. return SUCCESS;
  504. }
  505. Status MultiBatchClonePass::LinkGetDynamicDimsToNetOutput(const NodePtr &output_node) {
  506. if (!GetLocalOmgContext().dynamic_node_type.empty()) {
  507. if (!AttrUtils::SetStr(output_node->GetOpDesc(), ATTR_ALL_GEARS_INFO, GetLocalOmgContext().dynamic_dims)) {
  508. GELOGE(INTERNAL_ERROR, "Failed to set all gears info attr on netoutput %s.", output_node->GetName().c_str());
  509. return INTERNAL_ERROR;
  510. }
  511. }
  512. if (getnext_sink_dynamic_dims_) {
  513. GELOGD("Start link %s to %s.", shape_node_->GetName().c_str(), output_node->GetName().c_str());
  514. size_t input_index = output_node->GetAllInDataAnchors().size();
  515. if (NodeUtils::AppendInputAnchor(output_node, input_index + 1) != GRAPH_SUCCESS) {
  516. GELOGE(INTERNAL_ERROR, "Append input anchor of %s of %zu failed.", output_node->GetName().c_str(), input_index);
  517. return INTERNAL_ERROR;
  518. }
  519. auto ret = GraphUtils::AddEdge(shape_node_->GetOutDataAnchor(kDataOutIndex),
  520. output_node->GetInDataAnchor(input_index));
  521. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to link netoutput %s to getdynamicdims %s",
  522. output_node->GetName().c_str(), shape_node_->GetName().c_str());
  523. return INTERNAL_ERROR);
  524. if (!AttrUtils::SetBool(output_node->GetOpDesc(), ATTR_GETNEXT_SINK_DYNMAIC, true)) {
  525. GELOGE(INTERNAL_ERROR, "Failed to set getnext sink dynamic attr on netoutput %s.",
  526. output_node->GetName().c_str());
  527. return INTERNAL_ERROR;
  528. }
  529. }
  530. return SUCCESS;
  531. }
  532. ///
  533. /// @ingroup ge
  534. /// @brief Create input node for root graph.
  535. /// @param [in] const ComputeGraphPtr &graph: Root/Case graph.
  536. /// @return 0: SUCCESS / others: FAILED
  537. ///
  538. Status MultiBatchClonePass::CreateInputNode(const ComputeGraphPtr &graph) {
  539. // Data --> Case
  540. std::vector<NodePtr> all_data_nodes;
  541. size_t case_input_index = kCaseArgIndex;
  542. NodePtr getnext_node = nullptr;
  543. size_t input_index_of_getnext = 0;
  544. for (size_t i = 0; i < all_data_nodes_.size(); ++i, ++case_input_index) {
  545. const auto &node = all_data_nodes_[i];
  546. const OpDescPtr op_desc = AttrUtils::CopyOpDesc(node->GetOpDesc());
  547. if (op_desc == nullptr) {
  548. GELOGE(OUT_OF_MEMORY, "Create multi-batch Data node failed, name: %s", node->GetName().c_str());
  549. return FAILED;
  550. }
  551. if (GraphUtils::CopyTensorAttrs(op_desc, node) != GRAPH_SUCCESS) {
  552. return FAILED;
  553. }
  554. op_desc->SetName(node->GetName());
  555. const NodePtr &data = graph->AddNode(op_desc);
  556. GE_CHK_BOOL_EXEC(data != nullptr, return FAILED, "Add node[%s] to graph failed", op_desc->GetName().c_str());
  557. if (IsGetNextType(node)) {
  558. getnext_node = data;
  559. input_index_of_getnext = case_input_index;
  560. case_input_index = case_input_index + data_count_from_getnext_;
  561. continue;
  562. } else {
  563. if (GraphUtils::AddEdge(data->GetOutDataAnchor(0), case_node_->GetInDataAnchor(case_input_index)) !=
  564. GRAPH_SUCCESS) {
  565. GELOGE(FAILED, "Failed to add edge between Data:%s to Case:%s", data->GetName().c_str(),
  566. case_node_->GetName().c_str());
  567. return FAILED;
  568. }
  569. }
  570. if (SetMaxShape(data) != SUCCESS) {
  571. GELOGE(FAILED, "Set max shape of %s failed.", data->GetName().c_str());
  572. return FAILED;
  573. }
  574. all_data_nodes.emplace_back(data);
  575. }
  576. if (getnext_node != nullptr) {
  577. if (LinkEdgeForGetNext(getnext_node, input_index_of_getnext) != SUCCESS) {
  578. GELOGE(FAILED, "Failed to link edge for %s.", getnext_node->GetName().c_str());
  579. return FAILED;
  580. }
  581. if (SetMaxShape(getnext_node) != SUCCESS) {
  582. GELOGE(FAILED, "Set max shape of %s failed.", getnext_node->GetName().c_str());
  583. return FAILED;
  584. }
  585. all_data_nodes.emplace_back(getnext_node);
  586. }
  587. all_data_nodes_.swap(all_data_nodes);
  588. return SUCCESS;
  589. }
  590. Status MultiBatchClonePass::LinkEdgeForGetNext(const NodePtr &getnext_node, size_t &case_input_index) {
  591. GELOGD("Start link edge for %s, which is the %zu input of %s.", getnext_node->GetName().c_str(),
  592. case_input_index, case_node_->GetName().c_str());
  593. for (size_t out_index = 0; out_index < data_count_from_getnext_; ++out_index, ++case_input_index) {
  594. if (GraphUtils::AddEdge(getnext_node->GetOutDataAnchor(out_index),
  595. case_node_->GetInDataAnchor(case_input_index)) != GRAPH_SUCCESS) {
  596. GELOGE(FAILED, "Failed to add data edge between %zu Data:%s to %zu Case:%s", out_index,
  597. getnext_node->GetName().c_str(), case_input_index, case_node_->GetName().c_str());
  598. return FAILED;
  599. }
  600. }
  601. if (getnext_sink_dynamic_dims_) {
  602. GE_CHK_STATUS_RET(LinkGetNextToGetDynamicDims(getnext_node, shape_node_), "Failed to add link for %s.",
  603. shape_node_->GetName().c_str());
  604. }
  605. return SUCCESS;
  606. }
  607. ///
  608. /// @ingroup ge
  609. /// @brief Create Const node for root graph.
  610. /// @param [in] const ComputeGraphPtr &graph: Root/Case graph.
  611. /// @return 0: SUCCESS / others: FAILED
  612. ///
  613. Status MultiBatchClonePass::CreateConstNode(const ComputeGraphPtr &graph) {
  614. // Const --> Case
  615. std::vector<NodePtr> all_const_nodes;
  616. size_t arg_index = kCaseArgIndex + all_data_nodes_.size();
  617. if (data_count_from_getnext_ != 0) {
  618. arg_index = arg_index + data_count_from_getnext_ - kNumOfGetnextNode;
  619. }
  620. for (size_t i = 0; i < all_const_nodes_.size(); ++i) {
  621. const auto &node = all_const_nodes_[i];
  622. const OpDescPtr op_desc = AttrUtils::CopyOpDesc(node->GetOpDesc());
  623. if (op_desc == nullptr) {
  624. GELOGE(OUT_OF_MEMORY, "Create multi-batch Const node failed, name: %s", node->GetName().c_str());
  625. return FAILED;
  626. }
  627. op_desc->SetName(node->GetName());
  628. if (GraphUtils::CopyTensorAttrs(op_desc, node) != GRAPH_SUCCESS) {
  629. return FAILED;
  630. }
  631. const NodePtr &data = graph->AddNode(op_desc);
  632. GE_CHK_BOOL_EXEC(data != nullptr, return FAILED, "Add node[%s] to graph failed", op_desc->GetName().c_str());
  633. if (GraphUtils::AddEdge(data->GetOutDataAnchor(0), case_node_->GetInDataAnchor(arg_index + i)) != GRAPH_SUCCESS) {
  634. GELOGE(FAILED, "Failed to add edge between Const:%s to Case:%s", data->GetName().c_str(),
  635. case_node_->GetName().c_str());
  636. return FAILED;
  637. }
  638. all_const_nodes.emplace_back(data);
  639. }
  640. ChangeConstToData();
  641. all_const_nodes_.swap(all_const_nodes);
  642. return SUCCESS;
  643. }
  644. void MultiBatchClonePass::ChangeConstToData() {
  645. size_t data_index = all_data_nodes_.size();
  646. if (data_count_from_getnext_ != 0) {
  647. data_index = data_index + data_count_from_getnext_ - kNumOfGetnextNode;
  648. }
  649. for (size_t i = 0; i < all_const_nodes_.size(); ++i, ++data_index) { // Trans subgraph Const to Data.
  650. auto &const_node = all_const_nodes_[i];
  651. bool need_change_type = true;
  652. if (out_control_nodes_.find(const_node) != out_control_nodes_.end()) {
  653. GELOGD("No need to change %s to data type.", const_node->GetName().c_str());
  654. need_change_type = false;
  655. break;
  656. }
  657. if (!need_change_type) {
  658. continue;
  659. }
  660. const OpDescPtr &op_desc = all_const_nodes_[i]->GetOpDesc();
  661. op_desc->SetType(DATA);
  662. (void)op_desc->DelAttr(ATTR_NAME_WEIGHTS); // Delete weight.
  663. // Const no InputDesc, Data need InputDesc.
  664. (void)op_desc->AddInputDesc(op_desc->GetOutputDesc(kDataOutIndex));
  665. (void)AttrUtils::SetInt(op_desc, ATTR_NAME_INDEX, data_index);
  666. (void)NodeUtils::AppendInputAnchor(all_const_nodes_[i], 1);
  667. }
  668. }
  669. ///
  670. /// @ingroup ge
  671. /// @brief Create output node for root graph.
  672. /// @param [in] const ComputeGraphPtr &graph: Root/Case graph.
  673. /// @return 0: SUCCESS / others: FAILED
  674. ///
  675. Status MultiBatchClonePass::CreateOutputNode(const ComputeGraphPtr &graph) {
  676. const auto &output = all_output_nodes_[0];
  677. const OpDescPtr op_desc = AttrUtils::CopyOpDesc(output->GetOpDesc());
  678. if (op_desc == nullptr) {
  679. GELOGE(OUT_OF_MEMORY, "Create multi-batch output node failed");
  680. return FAILED;
  681. }
  682. if (GraphUtils::CopyTensorAttrs(op_desc, output) != GRAPH_SUCCESS) {
  683. return FAILED;
  684. }
  685. op_desc->SetName(output->GetName());
  686. const NodePtr &node = graph->AddNode(op_desc);
  687. GE_CHK_BOOL_EXEC(node != nullptr, return FAILED, "Add node[%s] to graph failed", op_desc->GetName().c_str());
  688. for (size_t i = 0; i < case_node_->GetAllOutDataAnchorsSize(); ++i) {
  689. const auto it = direct_output_.find(i);
  690. if (it == direct_output_.end()) {
  691. if (GraphUtils::AddEdge(case_node_->GetOutDataAnchor(i), node->GetInDataAnchor(i)) != GRAPH_SUCCESS) {
  692. GELOGE(FAILED, "Failed to add edge between Case:%s to NetOutput:%s",
  693. case_node_->GetName().c_str(), node->GetName().c_str());
  694. return FAILED;
  695. }
  696. } else {
  697. const auto data_node = graph->FindNode(it->second);
  698. if (data_node == nullptr) {
  699. GELOGE(GE_GRAPH_GRAPH_NODE_NULL, "Data node:%s not found", it->second.c_str());
  700. return GE_GRAPH_GRAPH_NODE_NULL;
  701. }
  702. if (GraphUtils::AddEdge(data_node->GetOutDataAnchor(kDataOutIndex), node->GetInDataAnchor(i)) != GRAPH_SUCCESS) {
  703. GELOGE(FAILED, "Failed to add edge between Data:%s to NetOutput:%s",
  704. data_node->GetName().c_str(), node->GetName().c_str());
  705. return FAILED;
  706. }
  707. }
  708. }
  709. GE_CHK_STATUS_RET(LinkGetDynamicDimsToNetOutput(node), "Failed to add edge between %s to netoutput: %s.",
  710. shape_node_->GetName().c_str(), output->GetName().c_str());
  711. all_output_nodes_.clear();
  712. all_output_nodes_.emplace_back(node);
  713. return SUCCESS;
  714. }
  715. ///
  716. /// @ingroup ge
  717. /// @brief Set max shape to Data node in root graph.
  718. /// @param [in] const NodePtr &data: data in Root/Case graph.
  719. /// @return 0: SUCCESS / others: FAILED
  720. ///
  721. Status MultiBatchClonePass::SetMaxShape(const NodePtr &data) {
  722. GELOGD("Start set max shape for %s.", data->GetName().c_str());
  723. if (!IsGetNextType(data)) {
  724. if (SetMaxShapeToData(data, kDataOutIndex) != SUCCESS) {
  725. GELOGE(PARAM_INVALID, "Failed to update max shape of %s.", data->GetName().c_str());
  726. return PARAM_INVALID;
  727. }
  728. } else {
  729. for (size_t out_anchor_index = 0; out_anchor_index < data_count_from_getnext_; ++out_anchor_index) {
  730. if (SetMaxShapeToData(data, out_anchor_index) != SUCCESS) {
  731. GELOGE(PARAM_INVALID, "Failed to update max shape of %s.", data->GetName().c_str());
  732. return PARAM_INVALID;
  733. }
  734. }
  735. }
  736. return SUCCESS;
  737. }
  738. Status MultiBatchClonePass::SetMaxShapeToData(const NodePtr &node, size_t out_anchor_index) {
  739. GELOGD("Start update max shape of %s, %zu output.", node->GetName().c_str(), out_anchor_index);
  740. auto data_shape = NodeUtils::GetOutputDesc(*node, out_anchor_index).GetShape();
  741. string data_name = node->GetName();
  742. if (IsGetNextType(node)) {
  743. data_name.append("_").append(std::to_string(out_anchor_index));
  744. }
  745. GELOGD("Update max shape of %s, shape dims is %s.", data_name.c_str(),
  746. formats::JoinToString(data_shape.GetDims()).c_str());
  747. const auto &dims = data_shape.GetDims();
  748. if (!IsGetNextType(node)) {
  749. if (std::all_of(dims.begin(), dims.end(), [](int64_t val) { return val >= 0; })) {
  750. GELOGD("No need to do anything for static data.");
  751. return SUCCESS;
  752. }
  753. } else {
  754. if (std::all_of(dims.begin(), dims.end(), [](int64_t val) { return val >= 0; })) {
  755. if (getnext_sink_dynamic_dims_) {
  756. // need to update shape of Shape_node when getnext node has dynamic data
  757. GE_CHK_STATUS_RET(UpdateShapeOfShapeNode(node, out_anchor_index), "Failed to update shape of shape node");
  758. }
  759. return SUCCESS;
  760. }
  761. }
  762. (void)AttrUtils::SetListInt(node->GetOpDesc(), ATTR_MBATCH_ORIGIN_INPUT_DIMS, data_shape.GetDims());
  763. GeTensorDesc tensor(NodeUtils::GetOutputDesc(*node, kDataOutIndex));
  764. std::vector<std::string> input_dims_str;
  765. for (size_t i = 0; i < batch_shapes_.size(); ++i) {
  766. auto shape = data_shape;
  767. auto ret = multibatch::CalcShape(data_to_dynamic_info_.at(data_name).at(i), shape);
  768. if (ret != SUCCESS) {
  769. GELOGE(ret, "Failed to calculate the shape for data node %s, the shape may not match", node->GetName().c_str());
  770. return ret;
  771. }
  772. tensor.SetShape(shape);
  773. int64_t tensor_size = 0;
  774. (void)TensorUtils::GetTensorSizeInBytes(tensor, tensor_size);
  775. string input_str = TypeUtils::FormatToSerialString(tensor.GetFormat()) + ":" +
  776. TypeUtils::DataTypeToSerialString(tensor.GetDataType()) + ":" + node->GetName() + ":" +
  777. std::to_string(tensor_size) + ":" + std::to_string(tensor.GetShape().GetDimNum()) + ":" +
  778. formats::JoinToString(tensor.GetShape().GetDims());
  779. input_dims_str.emplace_back(input_str);
  780. }
  781. (void)AttrUtils::SetListStr(node->GetOpDesc(), "_all_origin_gears_inputs", input_dims_str);
  782. size_t max_shape_index = 0;
  783. int64_t max_size = 0;
  784. for (size_t i = 0; i < batch_shapes_.size(); ++i) {
  785. int64_t size = 1;
  786. for (auto dim : data_to_dynamic_info_.at(data_name).at(i)) {
  787. if (INT64_MAX / dim < size) {
  788. GELOGE(PARAM_INVALID, "The shape %s size overflow",
  789. formats::ShapeToString(data_to_dynamic_info_.at(data_name).at(i)).c_str());
  790. return PARAM_INVALID;
  791. }
  792. size *= dim;
  793. }
  794. if (size > max_size) {
  795. max_size = size;
  796. max_shape_index = i;
  797. }
  798. }
  799. return SetShapeToData(data_to_dynamic_info_.at(data_name).at(max_shape_index), node, data_shape, out_anchor_index);
  800. }
  801. ///
  802. /// @ingroup ge
  803. /// @brief Set max shape to Data/GetNext node in root graph.
  804. /// @param [in] const std::vector<int64_t> &shapes: dims of shape.
  805. /// @param [in] const NodePtr &data: data in Root/Case graph.
  806. /// @param [in] GeShape &data_shape: dims of data node.
  807. /// @param [in] size_t out_anchor_index: out anchor index of data node.
  808. /// @return 0: SUCCESS / others: FAILED
  809. ///
  810. Status MultiBatchClonePass::SetShapeToData(const std::vector<int64_t> &shapes, const NodePtr &data, GeShape &data_shape,
  811. size_t out_anchor_index) {
  812. GELOGD("Start set shape to %zu out of %s.", out_anchor_index, data->GetName().c_str());
  813. if (multibatch::CalcShape(shapes, data_shape) != SUCCESS) {
  814. GELOGE(INTERNAL_ERROR, "Failed to calculate the batched shape for data node %s, the shapes may not match",
  815. data->GetName().c_str());
  816. return INTERNAL_ERROR;
  817. }
  818. if (NodeUtils::UpdateOutputShape(*data, out_anchor_index, data_shape) != GRAPH_SUCCESS) {
  819. GELOGE(INTERNAL_ERROR, "Failed to update output shape for data %s", data->GetName().c_str());
  820. return INTERNAL_ERROR;
  821. }
  822. if (!IsGetNextType(data)) {
  823. if (NodeUtils::UpdateInputShape(*data, kDataInIndex, data_shape) != GRAPH_SUCCESS) {
  824. GELOGE(INTERNAL_ERROR, "Failed to update input shape for data %s", data->GetName().c_str());
  825. return INTERNAL_ERROR;
  826. }
  827. } else {
  828. if (getnext_sink_dynamic_dims_) {
  829. // need to update shape of Shape_node when getnext_sink_dynamic
  830. GE_CHK_STATUS_RET(UpdateShapeOfShapeNode(data, out_anchor_index), "Failed to update shape of shape node");
  831. }
  832. }
  833. GELOGI("Update the data %s input/output shape to the max %s", data->GetName().c_str(),
  834. formats::ShapeToString(data_shape).c_str());
  835. return SUCCESS;
  836. }
  837. Status MultiBatchClonePass::UpdateShapeOfShapeNode(const NodePtr &node, size_t out_anchor_index) {
  838. GELOGD("Start update output shape of shape node insert by adapter, which is the %zu out of %s.", out_anchor_index,
  839. node->GetName().c_str());
  840. auto data_shape = NodeUtils::GetOutputDesc(*node, out_anchor_index).GetShape();
  841. size_t shape_index = out_anchor_index + (node->GetAllOutDataAnchors().size() / kDivisionConst);
  842. GeTensorDesc output_desc = node->GetOpDesc()->GetOutputDesc(shape_index);
  843. std::vector<int64_t> output_dims = {static_cast<int64_t>(data_shape.GetDims().size())};
  844. GeShape output_shape(output_dims);
  845. output_desc.SetShape(output_shape);
  846. if (node->GetOpDesc()->UpdateOutputDesc(shape_index, output_desc) != SUCCESS) {
  847. GELOGE(FAILED, "Update output desc fail.");
  848. return FAILED;
  849. }
  850. return SUCCESS;
  851. }
  852. ///
  853. /// @ingroup ge
  854. /// @brief Update Data node in Subgraph.
  855. /// @param [in] const NodePtr &data: data in Subgraph.
  856. /// @param [in] size_t batch_index: The batch index.
  857. /// @return 0: SUCCESS / others: FAILED
  858. ///
  859. Status MultiBatchClonePass::UpdateSubgraphData(const NodePtr &data, size_t batch_index) {
  860. int node_index = -1;
  861. if (!AttrUtils::GetInt(data->GetOpDesc(), ATTR_NAME_INDEX, node_index)) {
  862. GELOGE(FAILED, "Failed to get index from data[%s]", data->GetName().c_str());
  863. return FAILED;
  864. }
  865. int parent_index = node_index + 1;
  866. if (!AttrUtils::SetInt(data->GetOpDesc(), ATTR_NAME_PARENT_NODE_INDEX, parent_index)) {
  867. GELOGE(FAILED, "Failed to set parent index for node %s", data->GetName().c_str());
  868. return FAILED;
  869. }
  870. auto data_shape = NodeUtils::GetOutputDesc(*data, kDataOutIndex).GetShape();
  871. const auto &dims = data_shape.GetDims();
  872. GELOGD("Start update shape of %s , batch index is %zu, dims is %s.", data->GetName().c_str(), batch_index,
  873. formats::JoinToString(dims).c_str());
  874. if (std::all_of(dims.begin(), dims.end(), [](int64_t val) { return val >= 0; })) {
  875. return SUCCESS;
  876. }
  877. (void)AttrUtils::SetListInt(data->GetOpDesc(), ATTR_MBATCH_ORIGIN_INPUT_DIMS, data_shape.GetDims());
  878. auto data_name = data->GetName();
  879. size_t pos = data_name.find(kMultiBatchNodePostfix);
  880. if (pos == string::npos) {
  881. GELOGE(FAILED, "Cannot find key string [%s] of multi-batch in name of virtual input node, node name: %s.",
  882. kMultiBatchNodePostfix.c_str(), data_name.c_str());
  883. return FAILED;
  884. }
  885. auto parent_name = data_name.substr(0, pos);
  886. return SetShapeToData(data_to_dynamic_info_.at(parent_name).at(batch_index), data, data_shape, kDataOutIndex);
  887. }
  888. Status MultiBatchClonePass::CreateOriGraph(const ComputeGraphPtr &graph) {
  889. if (data_count_from_getnext_ == 0) {
  890. GELOGD("No need to change original graph without getnext node.");
  891. return SUCCESS;
  892. }
  893. GELOGD("Start change original graph: %s when exit getnext node.", graph->GetName().c_str());
  894. size_t data_index = all_data_nodes_.size() - kNumOfGetnextNode;
  895. for (const auto &node : graph->GetDirectNode()) {
  896. if (IsGetNextType(node)) {
  897. for (size_t out_index = 0; out_index < data_count_from_getnext_; ++out_index, ++data_index) {
  898. auto out_data_anchor = node->GetOutDataAnchor(out_index);
  899. GE_IF_BOOL_EXEC(out_data_anchor == nullptr, continue);
  900. NodePtr data_node = CreateDataNode(graph, out_data_anchor, data_index);
  901. GE_IF_BOOL_EXEC(data_node == nullptr, GELOGE(INTERNAL_ERROR, "Create %d data node failed.",
  902. out_data_anchor->GetIdx()); return INTERNAL_ERROR);
  903. for (auto &in_anchor : out_data_anchor->GetPeerInDataAnchors()) {
  904. GE_IF_BOOL_EXEC(in_anchor == nullptr, continue);
  905. NodePtr dst_node = in_anchor->GetOwnerNode();
  906. if (GraphUtils::RemoveEdge(out_data_anchor, in_anchor) != GRAPH_SUCCESS) {
  907. GELOGE(INTERNAL_ERROR, "Failed to remove edge between %s to %s", node->GetName().c_str(),
  908. dst_node->GetName().c_str());
  909. return INTERNAL_ERROR;
  910. }
  911. if (GraphUtils::AddEdge(data_node->GetOutDataAnchor(0), dst_node->GetInDataAnchor(in_anchor->GetIdx())) !=
  912. GRAPH_SUCCESS) {
  913. GELOGE(INTERNAL_ERROR, "Failed to add edge between %s to %s", data_node->GetName().c_str(),
  914. dst_node->GetName().c_str());
  915. return INTERNAL_ERROR;
  916. }
  917. }
  918. }
  919. if (graph->RemoveNode(node) != GRAPH_SUCCESS) {
  920. GELOGE(GRAPH_FAILED, "Remove node %s failed!", node->GetName().c_str());
  921. return GRAPH_FAILED;
  922. }
  923. break;
  924. }
  925. }
  926. return SUCCESS;
  927. }
  928. NodePtr MultiBatchClonePass::CreateDataNode(const ComputeGraphPtr &graph, const OutDataAnchorPtr &out_data_anchor,
  929. size_t data_index) {
  930. size_t out_anchor_index = out_data_anchor->GetIdx();
  931. std::string node_name = out_data_anchor->GetOwnerNode()->GetName() + "_" + std::to_string(out_anchor_index);
  932. OpDescPtr op_desc = MakeShared<OpDesc>(node_name, DATA);
  933. if (op_desc == nullptr) {
  934. GELOGE(OUT_OF_MEMORY, "Create data node failed.");
  935. return nullptr;
  936. }
  937. (void)AttrUtils::SetInt(op_desc, ATTR_NAME_INDEX, data_index);
  938. OpDescPtr getnext_op_desc = out_data_anchor->GetOwnerNode()->GetOpDesc();
  939. if (getnext_op_desc == nullptr) {
  940. GELOGE(OUT_OF_MEMORY, "Op desc of %s is nullptr.", out_data_anchor->GetOwnerNode()->GetName().c_str());
  941. return nullptr;
  942. }
  943. if (op_desc->AddInputDesc(getnext_op_desc->GetOutputDesc(out_anchor_index)) != GRAPH_SUCCESS) {
  944. GELOGE(INTERNAL_ERROR, "Add %s input desc failed.", op_desc->GetName().c_str());
  945. return nullptr;
  946. }
  947. if (op_desc->AddOutputDesc(getnext_op_desc->GetOutputDesc(out_anchor_index)) != GRAPH_SUCCESS) {
  948. GELOGE(INTERNAL_ERROR, "Add %s output desc failed.", op_desc->GetName().c_str());
  949. return nullptr;
  950. }
  951. NodePtr data_node = graph->AddNode(op_desc);
  952. GELOGD("Success create %s node.", data_node->GetName().c_str());
  953. return data_node;
  954. }
  955. ///
  956. /// @ingroup ge
  957. /// @brief Create nodes for root graph.
  958. /// @param [in] const ComputeGraphPtr &graph: Root/Case graph.
  959. /// @param [in] const ComputeGraphPtr &branch: original graph.
  960. /// @return 0: SUCCESS / others: FAILED
  961. ///
  962. Status MultiBatchClonePass::CreateSubgraphs(const ComputeGraphPtr &graph, const ComputeGraphPtr &branch) {
  963. GELOGD("Start create subgraphs for %s.", graph->GetName().c_str());
  964. const auto &op_desc = case_node_->GetOpDesc();
  965. for (size_t i = 0; i < batch_shapes_.size(); ++i) {
  966. std::vector<NodePtr> input_nodes;
  967. std::vector<NodePtr> output_nodes;
  968. const std::string postfix = kMultiBatchNodePostfix + std::to_string(i);
  969. ComputeGraphPtr subgraph = (i == 0) ? branch : GraphUtils::CloneGraph(branch, postfix, input_nodes, output_nodes);
  970. GE_IF_BOOL_EXEC(subgraph == nullptr, GELOGE(FAILED, "Create multi-batch case node failed"); return FAILED);
  971. subgraph->SetName("Batch_" + std::to_string(i));
  972. subgraph->SetParentNode(case_node_);
  973. subgraph->SetParentGraph(graph);
  974. graph->AddSubgraph(subgraph->GetName(), subgraph);
  975. all_branch_output_[subgraph] = subgraph->FindFirstNodeMatchType(NETOUTPUT);
  976. GE_CHK_STATUS_RET(UpdateSubgraphOutput(all_branch_output_[subgraph]),
  977. "Update %s failed", all_branch_output_[subgraph]->GetName().c_str());
  978. const string key_name = "branches" + std::to_string(i);
  979. op_desc->AddSubgraphName(key_name);
  980. op_desc->SetSubgraphInstanceName(i, subgraph->GetName());
  981. GELOGD("The %s has %zu input, %zu output.", subgraph->GetName().c_str(), input_nodes.size(), output_nodes.size());
  982. for (const auto &data : input_nodes) {
  983. GE_CHK_STATUS_RET(UpdateSubgraphData(data, i), "Update %s failed", subgraph->GetName().c_str());
  984. }
  985. }
  986. // Origninal graph take as first subgraph, update node name.
  987. for (const auto &n : branch->GetDirectNode()) {
  988. const auto &op_desc = n->GetOpDesc();
  989. op_desc->SetName(n->GetName() + kMultiBatchNodePostfix + "0");
  990. if (n->GetType() == DATA) {
  991. GE_CHK_STATUS_RET(UpdateSubgraphData(n, 0), "Update %s failed", branch->GetName().c_str());
  992. }
  993. }
  994. return SUCCESS;
  995. }
  996. ///
  997. /// @ingroup ge
  998. /// @brief Update output_node in Subgraph.
  999. /// @param [in] const NodePtr &output_node: output_node in Subgraph.
  1000. /// @return 0: SUCCESS / others: FAILED
  1001. ///
  1002. Status MultiBatchClonePass::UpdateSubgraphOutput(const NodePtr &output_node) {
  1003. const auto &op_desc = output_node->GetOpDesc();
  1004. GE_CHECK_NOTNULL(op_desc);
  1005. for (size_t index = 0; index < op_desc->GetInputsSize(); ++index) {
  1006. GeTensorDescPtr tensor = op_desc->MutableInputDesc(index);
  1007. GE_CHECK_NOTNULL(tensor);
  1008. if (!AttrUtils::SetInt(tensor, ATTR_NAME_PARENT_NODE_INDEX, index)) {
  1009. GELOGE(FAILED, "Failed to set parent index for node %s", output_node->GetName().c_str());
  1010. return FAILED;
  1011. }
  1012. }
  1013. return SUCCESS;
  1014. }
  1015. ///
  1016. /// @ingroup ge
  1017. /// @brief Remove subgraph suspend output anchor.
  1018. /// @param [in] ComputeGraphPtr &graph: Parent compute graph.
  1019. /// @return 0: SUCCESS / others: FAILED
  1020. ///
  1021. Status MultiBatchClonePass::PruneDirectOutput(const ComputeGraphPtr &graph) {
  1022. GELOGD("Start prune direct output.");
  1023. const auto &func_desc = case_node_->GetOpDesc();
  1024. uint32_t unused_num = 0;
  1025. uint32_t output_num = func_desc->GetOutputsSize();
  1026. for (size_t i = 0; i < output_num; ++i) {
  1027. bool is_unused_tensor = true;
  1028. for (const auto &item : all_branch_output_) {
  1029. const auto &netoutput = item.second;
  1030. GE_CHECK_NOTNULL(netoutput);
  1031. const auto in_anchor = netoutput->GetInDataAnchor(i);
  1032. if (in_anchor->GetPeerOutAnchor() != nullptr) {
  1033. is_unused_tensor = false;
  1034. break;
  1035. }
  1036. }
  1037. if (is_unused_tensor) {
  1038. unused_num++;
  1039. continue;
  1040. }
  1041. GE_CHK_STATUS_RET(UpdateOutputTensor(i, unused_num), "Graph:%s Update output failed", graph->GetName().c_str());
  1042. }
  1043. if (unused_num == 0) {
  1044. return SUCCESS;
  1045. }
  1046. GE_CHK_STATUS_RET(NodeUtils::RemoveOutputAnchor(case_node_, output_num - unused_num), "Remove output failed");
  1047. for (const auto &item : all_branch_output_) {
  1048. GE_CHK_STATUS_RET(NodeUtils::RemoveInputAnchor(item.second, output_num - unused_num), "Remove input failed");
  1049. }
  1050. return SUCCESS;
  1051. }
  1052. ///
  1053. /// @ingroup ge
  1054. /// @brief Update subgraph suspend output tensor.
  1055. /// @param [in] parent_index: parent index for check.
  1056. /// @param [in] unused_num: total unused tensor.
  1057. /// @return 0: SUCCESS / others: FAILED
  1058. ///
  1059. Status MultiBatchClonePass::UpdateOutputTensor(uint32_t parent_index, uint32_t unused_num) {
  1060. if (unused_num == 0) {
  1061. GELOGD("No need to update output tensor.");
  1062. return SUCCESS;
  1063. }
  1064. uint32_t update_index = parent_index - unused_num;
  1065. for (const auto &item : all_branch_output_) {
  1066. const auto &node = item.second;
  1067. const auto &new_anchor = node->GetInDataAnchor(update_index);
  1068. const auto &old_anchor = node->GetInDataAnchor(parent_index);
  1069. const auto &out_anchor = old_anchor->GetPeerOutAnchor();
  1070. const auto &out_node = out_anchor->GetOwnerNode();
  1071. const auto &op_desc = node->GetOpDesc();
  1072. (void)op_desc->UpdateInputDesc(update_index, op_desc->GetInputDesc(parent_index));
  1073. GE_CHK_GRAPH_STATUS_RET(GraphUtils::AddEdge(out_anchor, new_anchor), "Add edge failed");
  1074. GELOGI("Add edge success, func node: %s, node: %s, parent index: %u, update index: %u",
  1075. case_node_->GetName().c_str(), out_node->GetName().c_str(), parent_index, update_index);
  1076. GE_CHK_GRAPH_STATUS_RET(GraphUtils::RemoveEdge(out_anchor, old_anchor), "Remove edge failed");
  1077. GELOGI("Remove edge success, func node: %s, node: %s", case_node_->GetName().c_str(), out_node->GetName().c_str());
  1078. }
  1079. const auto &new_anchor = case_node_->GetOutDataAnchor(update_index);
  1080. const auto &old_anchor = case_node_->GetOutDataAnchor(parent_index);
  1081. for (const auto in_anchor : old_anchor->GetPeerInDataAnchors()) {
  1082. const auto &in_node = in_anchor->GetOwnerNode();
  1083. GE_CHK_GRAPH_STATUS_RET(GraphUtils::RemoveEdge(old_anchor, in_anchor), "Remove edge failed");
  1084. GELOGI("Remove edge success, func node: %s, node: %s", case_node_->GetName().c_str(), in_node->GetName().c_str());
  1085. GE_CHK_GRAPH_STATUS_RET(GraphUtils::AddEdge(new_anchor, in_anchor), "Add edge failed");
  1086. GELOGI("Add edge success, func node: %s, node: %s, parent index: %u, update index: %u",
  1087. case_node_->GetName().c_str(), in_node->GetName().c_str(), parent_index, update_index);
  1088. }
  1089. return SUCCESS;
  1090. }
  1091. } // namespace ge

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