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_copy_graph.cc 71 kB

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
4 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
4 years ago
4 years ago
4 years ago
4 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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
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
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
4 years ago
4 years ago
4 years ago
5 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612
  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/preprocess/multi_batch_copy_graph.h"
  17. #include <queue>
  18. #include <set>
  19. #include <string>
  20. #include "common/formats/utils/formats_trans_utils.h"
  21. #include "common/ge/ge_util.h"
  22. #include "common/util/error_manager/error_manager.h"
  23. #include "framework/common/debug/ge_log.h"
  24. #include "framework/common/ge_inner_error_codes.h"
  25. #include "framework/common/string_util.h"
  26. #include "framework/common/types.h"
  27. #include "framework/omg/omg_inner_types.h"
  28. #include "graph/debug/ge_attr_define.h"
  29. #include "graph/ge_context.h"
  30. #include "graph/passes/multi_batch_clone_pass.h"
  31. #include "graph/passes/prune_pass.h"
  32. #include "graph/preprocess/multi_batch_options.h"
  33. #include "graph/utils/attr_utils.h"
  34. #include "graph/utils/graph_utils.h"
  35. #include "graph/utils/node_utils.h"
  36. #include "graph/utils/tensor_utils.h"
  37. #include "graph/utils/type_utils.h"
  38. #include "inc/pass_manager.h"
  39. #include "graph/common/local_context.h"
  40. #include "graph/common/omg_util.h"
  41. using std::set;
  42. using std::string;
  43. using std::vector;
  44. namespace ge {
  45. namespace multibatch {
  46. namespace {
  47. const char *const kMbatchSwitchnName = "mbatch-switch-name";
  48. const char *const kGetNextName = "IteratorV2";
  49. const int kSwitchNDataIndex = 0;
  50. const int kSwitchNPredIndex = 1;
  51. const int kDataOutIndex = 0;
  52. const int kDataInIndex = 0;
  53. const int kMergeDataOutIndex = 0;
  54. const int kStaticOutput = -1;
  55. const int kDivisionConst = 2;
  56. inline bool IsDataLikeType(const std::string &node_type) { return (node_type == DATA) || (node_type == AIPP); }
  57. inline bool IsGetNextType(const NodePtr &node) {
  58. std::string original_type;
  59. GE_IF_BOOL_EXEC(GetOriginalType(node, original_type) != SUCCESS,
  60. GELOGW("Get original type failed"); return false);
  61. return (original_type == kGetNextName);
  62. }
  63. NodePtr InsertMergeNodeToGraph(const std::string &name, size_t input_num, const ComputeGraphPtr &graph) {
  64. OpDescPtr desc = MakeShared<OpDesc>();
  65. if (desc == nullptr) {
  66. GELOGE(OUT_OF_MEMORY, "Failed to insert merge node, name %s", name.c_str());
  67. return nullptr;
  68. }
  69. desc->SetName(name);
  70. desc->SetType(MERGE);
  71. GeTensorDesc tensor_desc;
  72. for (size_t i = 0; i < input_num; ++i) {
  73. auto ret = desc->AddInputDesc("x" + std::to_string(i), tensor_desc);
  74. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS,
  75. GELOGE(INTERNAL_ERROR, "Failed to create merge node %s, failed to add input %zu, error-code %u",
  76. name.c_str(), i, ret);
  77. return nullptr);
  78. }
  79. auto ret = desc->AddOutputDesc("y", tensor_desc);
  80. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS,
  81. GELOGE(INTERNAL_ERROR, "Failed to create merge node %s, failed to add output 'y', error-code %u",
  82. name.c_str(), ret);
  83. return nullptr);
  84. tensor_desc.SetDataType(DT_INT32);
  85. ret = desc->AddOutputDesc("value_index", tensor_desc);
  86. if (ret != GRAPH_SUCCESS) {
  87. GELOGE(INTERNAL_ERROR, "Failed to create merge node %s, failed to add output 'value_index', error-code %u",
  88. name.c_str(), ret);
  89. return nullptr;
  90. }
  91. if (!AttrUtils::SetBool(desc, ATTR_INSERT_BY_MBATCH, true)) {
  92. GELOGE(INTERNAL_ERROR, "Failed to create merge node %s, failed to add attr", name.c_str());
  93. return nullptr;
  94. }
  95. return graph->AddNode(desc);
  96. }
  97. NodePtr InsertCopyNode(const NodePtr &node, size_t n) {
  98. const std::string &name = node->GetName() + "_ascend_mbatch_batch_" + std::to_string(n);
  99. auto src_op_desc = node->GetOpDesc();
  100. GE_IF_BOOL_EXEC(src_op_desc == nullptr, GELOGE(INTERNAL_ERROR, "Failed to copy node %s to %s, the OpDesc is null",
  101. node->GetName().c_str(), name.c_str());
  102. return nullptr);
  103. auto desc = AttrUtils::CopyOpDesc(src_op_desc);
  104. GE_IF_BOOL_EXEC(desc == nullptr, GELOGE(OUT_OF_MEMORY, "Failed to create op desc for copy node for node %s name %s",
  105. node->GetName().c_str(), name.c_str());
  106. return nullptr);
  107. desc->SetName(name);
  108. desc->CopyAttrsFrom(*src_op_desc);
  109. for (uint32_t i = 0; i < node->GetAllInDataAnchorsSize(); ++i) {
  110. auto input_desc = desc->MutableInputDesc(i);
  111. GE_IF_BOOL_EXEC(input_desc == nullptr,
  112. GELOGW("Get null input desc by index %u from node %s when copy from %s", i,
  113. desc->GetName().c_str(), node->GetName().c_str());
  114. continue);
  115. input_desc->CopyAttrsFrom(src_op_desc->GetInputDesc(i));
  116. }
  117. for (uint32_t i = 0; i < node->GetAllOutDataAnchorsSize(); ++i) {
  118. auto output_desc = desc->MutableOutputDesc(i);
  119. GE_IF_BOOL_EXEC(output_desc == nullptr,
  120. GELOGE(INTERNAL_ERROR, "Failed to get output desc by index %u from node %s when copy from %s", i,
  121. desc->GetName().c_str(), node->GetName().c_str());
  122. return nullptr);
  123. output_desc->CopyAttrsFrom(src_op_desc->GetOutputDesc(i));
  124. }
  125. const std::string &batch_label = "Batch_" + std::to_string(n);
  126. if (!AttrUtils::SetStr(desc, ATTR_NAME_BATCH_LABEL, batch_label)) {
  127. GELOGE(FAILED, "set attr ATTR_NAME_BATCH_LABEL failed, node:%s.", name.c_str());
  128. return nullptr;
  129. }
  130. (void)AttrUtils::SetListStr(desc, ATTR_NAME_DATA_DUMP_ORIGIN_OP_NAMES, {node->GetName()});
  131. auto graph = node->GetOwnerComputeGraph();
  132. return graph->AddNode(desc);
  133. }
  134. bool IsAllDimsPositive(const std::vector<int64_t> &dims) {
  135. for (auto dim : dims) {
  136. if (dim < 0) {
  137. return false;
  138. }
  139. }
  140. return true;
  141. }
  142. NodePtr InsertConst(const std::string &name, const ComputeGraphPtr &graph) {
  143. auto desc = MakeShared<OpDesc>();
  144. if (desc == nullptr) {
  145. GELOGE(OUT_OF_MEMORY, "Failed to create const op %s, out of memory", name.c_str());
  146. return nullptr;
  147. }
  148. desc->SetName(name);
  149. desc->SetType(CONSTANT);
  150. GeTensor tensor;
  151. tensor.SetData(std::vector<uint8_t>({0}));
  152. if (!AttrUtils::SetTensor(desc, ATTR_NAME_WEIGHTS, tensor)) {
  153. GELOGE(OUT_OF_MEMORY, "Failed to init tensor value for const %s", name.c_str());
  154. return nullptr;
  155. }
  156. if (!AttrUtils::SetBool(desc, ATTR_INSERT_BY_MBATCH, true)) {
  157. GELOGE(OUT_OF_MEMORY, "Failed to set insert flag for const node %s", name.c_str());
  158. return nullptr;
  159. }
  160. if (desc->AddOutputDesc(GeTensorDesc()) != GRAPH_SUCCESS) {
  161. GELOGE(OUT_OF_MEMORY, "Failed to add output desc for const node %s", name.c_str());
  162. return nullptr;
  163. }
  164. return graph->AddNode(desc);
  165. }
  166. bool IsOnlyOutputToAipp(const NodePtr &node) {
  167. for (const auto &out_node : node->GetOutDataNodes()) {
  168. if (out_node->GetType() != AIPP) {
  169. return false;
  170. }
  171. }
  172. return true;
  173. }
  174. } // namespace
  175. Status MultiBatchGraphCopyer::CopyGraph() {
  176. auto ret = Init();
  177. if (ret != SUCCESS) {
  178. return ret;
  179. }
  180. if (LabelStatus() != SUCCESS) {
  181. GELOGE(INTERNAL_ERROR, "Failed to label status for all nodes.");
  182. return INTERNAL_ERROR;
  183. }
  184. ret = CheckAndParseDynamicData();
  185. if (ret != SUCCESS) {
  186. return ret;
  187. }
  188. ret = CreateNewNodes();
  189. if (ret != SUCCESS) {
  190. return ret;
  191. }
  192. ret = LinkEdges();
  193. if (ret != SUCCESS) {
  194. return ret;
  195. }
  196. ret = InsertIdentityAfterSwitchN();
  197. if (ret != SUCCESS) {
  198. GELOGE(INTERNAL_ERROR, "Failed to insert identity nodes after switchn node.");
  199. return INTERNAL_ERROR;
  200. }
  201. GELOGI("Begin to remove useless nodes by prune pass after copy process");
  202. PrunePass prune_pass;
  203. ret = prune_pass.Run(graph_);
  204. if (ret != SUCCESS) {
  205. GELOGE(ret, "Failed to prune");
  206. return ret;
  207. }
  208. return CheckCopyResult(origin_data_nodes_);
  209. }
  210. Status MultiBatchGraphCopyer::Init() {
  211. auto ret = CheckArguments();
  212. if (ret != SUCCESS) {
  213. return ret;
  214. }
  215. for (auto &node : graph_->GetAllNodes()) {
  216. origin_all_nodes_.emplace_back(node);
  217. if (IsDataLikeType(node->GetType())) {
  218. origin_data_nodes_.emplace_back(node);
  219. }
  220. if (!GetLocalOmgContext().dynamic_node_type.empty() && IsGetNextType(node)) {
  221. origin_data_nodes_.emplace_back(node);
  222. }
  223. }
  224. return SUCCESS;
  225. }
  226. void MultiBatchGraphCopyer::LabelStatusForData(const NodePtr &data) {
  227. auto data_shape = NodeUtils::GetOutputDesc(*data, kDataOutIndex).GetShape();
  228. GELOGI("Label status for %s, shape_dims is %s.", data->GetName().c_str(),
  229. formats::JoinToString(data_shape.GetDims()).c_str());
  230. if (!IsAllDimsPositive(data_shape.GetDims())) {
  231. origin_nodes_status_[data.get()] = kNodeInBatchBranch;
  232. }
  233. }
  234. void MultiBatchGraphCopyer::LabelStatusForGetNextSink(const NodePtr &data) {
  235. auto op_desc = data->GetOpDesc();
  236. GELOGI("Out count of %s is %zu.", data->GetName().c_str(), op_desc->GetOutputsSize());
  237. size_t data_count = op_desc->GetOutputsSize() / kDivisionConst;
  238. for (size_t i = 0; i < data_count; ++i) {
  239. GeTensorDesc output_desc = op_desc->GetOutputDesc(i);
  240. GELOGD("The %zu data shape from getnext sink is %s.", i,
  241. formats::JoinToString(output_desc.GetShape().GetDims()).c_str());
  242. const auto &out_data_anchor = data->GetOutDataAnchor(i);
  243. if (out_data_anchor == nullptr) {
  244. continue;
  245. }
  246. size_t reference_times = out_data_anchor->GetPeerInDataAnchors().size();
  247. GELOGD("The %zu data has %zu referenced times.", i, reference_times);
  248. getnext_sink_dynamic_out_mapping_.emplace_back(std::make_pair(i, reference_times));
  249. if (!IsAllDimsPositive(output_desc.GetShape().GetDims())) {
  250. getnext_sink_dynamic_dims_ = true;
  251. }
  252. }
  253. if (getnext_sink_dynamic_dims_) {
  254. origin_nodes_status_[data.get()] = kNodeInBatchBranch;
  255. }
  256. }
  257. Status MultiBatchGraphCopyer::LabelInBatchBranchStatus() {
  258. GELOGD("Start label in batch branch status.");
  259. for (const auto &data : origin_data_nodes_) {
  260. auto op_desc = data->GetOpDesc();
  261. GE_IF_BOOL_EXEC(op_desc == nullptr, GELOGE(PARAM_INVALID, "Op desc is nullptr.");
  262. return PARAM_INVALID);
  263. LabelStatusForData(data);
  264. if (!GetLocalOmgContext().dynamic_node_type.empty()) {
  265. LabelStatusForGetNextSink(data);
  266. }
  267. }
  268. bool changed = true;
  269. // If anyone of in node is kNodeInBatchBranch, it is also kNodeInBatchBranch
  270. while (changed) {
  271. changed = false;
  272. for (const auto &node : origin_all_nodes_) {
  273. auto iter = origin_nodes_status_.find(node.get());
  274. if (iter != origin_nodes_status_.end()) {
  275. continue;
  276. }
  277. for (auto &in_node : node->GetInAllNodes()) {
  278. bool is_in_batch = origin_nodes_status_.find(in_node.get()) != origin_nodes_status_.end() &&
  279. origin_nodes_status_[in_node.get()] == kNodeInBatchBranch;
  280. if (is_in_batch) {
  281. origin_nodes_status_[node.get()] = kNodeInBatchBranch;
  282. changed = true;
  283. break;
  284. }
  285. }
  286. }
  287. }
  288. return SUCCESS;
  289. }
  290. Status MultiBatchGraphCopyer::LabelStatus() {
  291. if (LabelInBatchBranchStatus() != SUCCESS) {
  292. GELOGE(PARAM_INVALID, "Failed to label no in batch branch");
  293. return PARAM_INVALID;
  294. }
  295. for (const auto &node : origin_all_nodes_) {
  296. if (!(node->GetOpDesc()->GetSubgraphInstanceNames().empty())) {
  297. origin_nodes_status_[node.get()] = kNodeNotSupportNode;
  298. continue;
  299. }
  300. if (node->GetType() == NETOUTPUT) {
  301. origin_nodes_status_[node.get()] = kNodeOutBatchBranch;
  302. continue;
  303. }
  304. if (GetLocalOmgContext().dynamic_node_type.empty()) {
  305. if (IsDataLikeType(node->GetType())) {
  306. if (IsOnlyOutputToAipp(node)) {
  307. origin_nodes_status_[node.get()] = kNodeOutBatchBranch;
  308. } else {
  309. origin_nodes_status_[node.get()] = kNodeStartNode;
  310. }
  311. continue;
  312. }
  313. } else {
  314. if (IsDataLikeType(node->GetType())) {
  315. origin_nodes_status_[node.get()] = kNodeStartNode;
  316. continue;
  317. }
  318. if (IsGetNextType(node)) {
  319. origin_nodes_status_[node.get()] = kNodeStartNode;
  320. continue;
  321. }
  322. }
  323. if (origin_nodes_status_.find(node.get()) == origin_nodes_status_.end()) {
  324. origin_nodes_status_[node.get()] = kNodeOutBatchBranch;
  325. }
  326. }
  327. return SUCCESS;
  328. }
  329. Status MultiBatchGraphCopyer::CheckAndParseDynamicData(){
  330. size_t unknown_shape_count = 0;
  331. auto data_name_and_shape = GetLocalOmgContext().user_input_dims;
  332. GELOGD("raw data_name_and_shape size: %zu", data_name_and_shape.size());
  333. if (!getnext_sink_dynamic_dims_) {
  334. for (const auto &node : origin_all_nodes_) {
  335. auto data_desc = NodeUtils::GetOutputDesc(*node, kDataOutIndex);
  336. auto data_shape = data_desc.GetShape();
  337. auto data_format = data_desc.GetFormat() == Format::FORMAT_NCHW ? "NCHW" :
  338. data_desc.GetFormat() == Format::FORMAT_NHWC ? "NHWC" : "Others";
  339. auto data_name = node->GetName();
  340. auto branch_status = GetNodeStatus(node);
  341. if (branch_status != kNodeStartNode) {
  342. continue;
  343. }
  344. GELOGI("CheckAndParseDynamicData shape_dims is %s.", formats::JoinToString(data_shape.GetDims()).c_str());
  345. if (IsAllDimsPositive(data_shape.GetDims())) {
  346. continue;
  347. }
  348. std::vector<int64_t> data_shape_dims = data_shape.GetDims();
  349. ++unknown_shape_count;
  350. auto iter = find(data_name_order_.begin(), data_name_order_.end(), data_name);
  351. if (iter == data_name_order_.end()) {
  352. if (dynamic_type_ == DynamicType::kDynamicBatch) {
  353. auto ret = CheckDynamicBatchShape(data_shape_dims, data_name);
  354. GE_IF_BOOL_EXEC(ret == false, GELOGE(PARAM_INVALID, "Failed to check dynamic batch shape of %s.",
  355. data_name.c_str()); return PARAM_INVALID);
  356. } else if (dynamic_type_ == DynamicType::kDynamicImageSize) {
  357. auto ret = CheckDynamicImageSizeShape(data_shape_dims, data_name, data_format);
  358. GE_IF_BOOL_EXEC(ret == false, GELOGE(PARAM_INVALID, "Failed to check dynamic image size shape of %s.",
  359. data_name.c_str()); return PARAM_INVALID);
  360. } else if (dynamic_type_ == DynamicType::kDynamicDims) {
  361. ErrorManager::GetInstance().ATCReportErrMessage("E10001",
  362. {"parameter", "reason"},
  363. {"--input_shape",
  364. "all dynamic data must be set in --input_shape"});
  365. GELOGE(INTERNAL_ERROR, "data: %s shape:%s must be set int --input_shape",
  366. node->GetName().c_str(), data_shape.ToString().c_str());
  367. return INTERNAL_ERROR;
  368. }
  369. GELOGI("Data shape of %s is %s", data_name.c_str(), formats::JoinToString(data_shape_dims).c_str());
  370. data_name_and_shape.emplace_back(data_name, data_shape_dims);
  371. }
  372. }
  373. }
  374. auto ret = ParserDataToDynmaicInfo(shapes_, data_name_and_shape, data_to_dynamic_info_);
  375. GE_CHK_STATUS_RET(ret, "Failed to parse data to dynamic info.");
  376. if (!getnext_sink_dynamic_dims_ && unknown_shape_count == 0) {
  377. ErrorManager::GetInstance().ATCReportErrMessage("E10040");
  378. GELOGE(PARAM_INVALID,
  379. "Need unknow shape data when user set --dynamic_batch_size, --dynamic_image_size or --dynamic_dims");
  380. return PARAM_INVALID;
  381. }
  382. return SUCCESS;
  383. }
  384. Status MultiBatchGraphCopyer::CreateNewNodes() {
  385. if (!getnext_sink_dynamic_dims_) {
  386. shape_data_ = InsertShapeDataNode();
  387. } else {
  388. shape_data_ = InsertGetDynamicDimsNode();
  389. }
  390. GE_IF_BOOL_EXEC(shape_data_ == nullptr, GELOGE(INTERNAL_ERROR, "Failed to create the shape node for multi batch");
  391. return INTERNAL_ERROR);
  392. GE_CHECK_NOTNULL(shape_data_->GetOpDesc());
  393. for (const auto &node : origin_all_nodes_) {
  394. GE_CHECK_NOTNULL(node->GetOpDesc());
  395. auto node_type = node->GetType();
  396. Status ret = INTERNAL_ERROR;
  397. auto branch_status = GetNodeStatus(node);
  398. GELOGD("Process node %s, status %d", node->GetName().c_str(), static_cast<int>(branch_status));
  399. switch (branch_status) {
  400. case kNodeStartNode:
  401. GELOGD("Name: %s, type: %s, status: kNodeStartNode.", node->GetName().c_str(), node->GetType().c_str());
  402. ret = InsertSwitchNAndUpdateMaxShape(node);
  403. break;
  404. case kNodeInBatchBranch:
  405. GELOGD("Name: %s, type: %s, status: kNodeInBatchBranch.", node->GetName().c_str(), node->GetType().c_str());
  406. ret = CopyNodeInBatchBranch(node);
  407. break;
  408. case kNodeOutBatchBranch:
  409. GELOGD("Name: %s, type: %s, status: kNodeOutBatchBranch.", node->GetName().c_str(), node->GetType().c_str());
  410. ret = InsertMergeForEdgeNode(node);
  411. if (ret == SUCCESS) {
  412. ret = LinkGetDynamicDimsToNetOutput(node);
  413. }
  414. break;
  415. case kNodeNotSupportNode:
  416. GELOGD("Name: %s, type: %s, status: kNodeNotSupportNode.", node->GetName().c_str(), node->GetType().c_str());
  417. break;
  418. default:
  419. GELOGE(INTERNAL_ERROR, "Unexpected status %d on node %s", static_cast<int>(branch_status),
  420. node->GetName().c_str());
  421. break;
  422. }
  423. if (ret != SUCCESS) {
  424. GELOGE(ret, "Failed to deal with node %s in multi-batch process", node->GetName().c_str());
  425. return ret;
  426. }
  427. }
  428. return SUCCESS;
  429. }
  430. NodePtr MultiBatchGraphCopyer::InsertMergeNode(const NodePtr &node, int index) {
  431. if (index < 0) {
  432. // the merge node must has data inputs, if origin connection is a control
  433. // edge, we use data edge instead
  434. index = 0;
  435. }
  436. auto &merge_nodes = nodes_to_merge_nodes_[node.get()];
  437. if (merge_nodes.empty()) {
  438. auto count = node->GetAllOutDataAnchorsSize();
  439. if (count == 0) {
  440. count = 1;
  441. }
  442. merge_nodes.resize(count, nullptr);
  443. }
  444. if (merge_nodes.at(index) != nullptr) {
  445. return merge_nodes[index];
  446. }
  447. auto merge_node_name = node->GetName() + "_ascend_mbatch_merge_" + std::to_string(index);
  448. auto merge_node = InsertMergeNodeToGraph(merge_node_name, shapes_.size(), node->GetOwnerComputeGraph());
  449. GE_IF_BOOL_EXEC(merge_node == nullptr, GELOGE(INTERNAL_ERROR, "Failed to create merge node for node %s, out index %d",
  450. node->GetName().c_str(), index);
  451. return nullptr);
  452. merge_nodes[index] = merge_node;
  453. GELOGI("Create merge node %s for node %s index %d", merge_node_name.c_str(), node->GetName().c_str(), index);
  454. return merge_node;
  455. }
  456. NodePtr MultiBatchGraphCopyer::FindSwitchnNodeForDataEdge(const OutDataAnchorPtr &data_out_anchor,
  457. const NodePtr &origin_node) {
  458. auto data_node = data_out_anchor->GetOwnerNode();
  459. GELOGD("Start find switchn node insert between %s and %s", data_node->GetName().c_str(),
  460. origin_node->GetName().c_str());
  461. NodePtr switchn = nullptr;
  462. if (!getnext_sink_dynamic_dims_ && data_nodes_to_switchn_.count(data_node.get()) > 0) {
  463. switchn = data_nodes_to_switchn_[data_node.get()];
  464. return switchn;
  465. }
  466. bool is_getnext_sink_data = false;
  467. for (size_t i = 0; i < getnext_nodes_to_switchn_.size(); ++i) {
  468. for (size_t j = 0; j < getnext_nodes_to_switchn_.at(i).size(); ++j) {
  469. if (getnext_nodes_to_switchn_.at(i).at(j).first == data_node.get()) {
  470. is_getnext_sink_data = true;
  471. break;
  472. }
  473. }
  474. }
  475. // get output_idx of origin_node(getnext)
  476. if (is_getnext_sink_data) {
  477. auto output_idx = data_out_anchor->GetIdx();
  478. size_t referenced_index = 0;
  479. GELOGI("The output idx %zu has %zu referenced nums.", output_idx, data_out_anchor->GetPeerInDataAnchors().size());
  480. for (const auto &peer_in_anchor : data_out_anchor->GetPeerInDataAnchors()) {
  481. if (peer_in_anchor->GetOwnerNode()->GetOpDesc() == nullptr) {
  482. GELOGE(INTERNAL_ERROR, "Op desc should not be nullptr.");
  483. return nullptr;
  484. }
  485. if (getnext_nodes_to_switchn_.at(output_idx).empty()) {
  486. GELOGI("Output idx %zu of %s is static output.", output_idx, data_node->GetName().c_str());
  487. return nullptr;
  488. }
  489. if (output_idx >= static_cast<int>(getnext_nodes_to_switchn_.size()) ||
  490. referenced_index >= getnext_nodes_to_switchn_.at(output_idx).size()) {
  491. GELOGE(INTERNAL_ERROR, "Output idx is %zu, referenced index is %zu", output_idx, referenced_index);
  492. return nullptr;
  493. }
  494. if (peer_in_anchor->GetOwnerNode()->GetOpDesc()->GetName() == origin_node->GetName()) {
  495. switchn = getnext_nodes_to_switchn_.at(output_idx).at(referenced_index).second;
  496. GELOGI("Name of switchn is %s.", switchn->GetName().c_str());
  497. return switchn;
  498. }
  499. referenced_index++;
  500. }
  501. }
  502. return switchn;
  503. }
  504. // origin_node = Add, batch_num = 0,1,2,3; copyed_node = Add_0,Add_1,Add_2,Add_3
  505. Status MultiBatchGraphCopyer::CopyInDataEdges(const NodePtr &origin_node, int batch_num, const NodePtr &copyed_node) {
  506. GELOGI("Start copy data edges for %s and %s.", origin_node->GetName().c_str(), copyed_node->GetName().c_str());
  507. for (auto &in_anchor : origin_node->GetAllInDataAnchors()) {
  508. auto origin_src_anchor = in_anchor->GetPeerOutAnchor();
  509. if (origin_src_anchor == nullptr) {
  510. GELOGD("The node %s does not have input on index %d", origin_node->GetName().c_str(), in_anchor->GetIdx());
  511. continue;
  512. }
  513. auto origin_src_node = origin_src_anchor->GetOwnerNode();
  514. auto dst_anchor = copyed_node->GetInDataAnchor(in_anchor->GetIdx());
  515. GE_CHECK_NOTNULL(dst_anchor);
  516. auto switchn = FindSwitchnNodeForDataEdge(origin_src_anchor, origin_node);
  517. if (switchn != nullptr) {
  518. auto ret = GraphUtils::AddEdge(switchn->GetOutDataAnchor(batch_num), dst_anchor);
  519. if (ret != GRAPH_SUCCESS) {
  520. GELOGE(INTERNAL_ERROR, "Failed to add data edge between %s(%d) to %s(%d), error-code %u",
  521. switchn->GetName().c_str(), batch_num, copyed_node->GetName().c_str(), in_anchor->GetIdx(),
  522. ret);
  523. return INTERNAL_ERROR;
  524. }
  525. GELOGD("Add data edge from %s(%d) to %s(%d)", switchn->GetName().c_str(), batch_num,
  526. copyed_node->GetName().c_str(), in_anchor->GetIdx());
  527. continue;
  528. }
  529. auto batch_branch_iter = nodes_to_batch_nodes_.find(origin_src_node.get());
  530. if (batch_branch_iter != nodes_to_batch_nodes_.end()) {
  531. auto src_batch_node = batch_branch_iter->second.at(batch_num);
  532. auto ret = GraphUtils::AddEdge(src_batch_node->GetOutDataAnchor(origin_src_anchor->GetIdx()), dst_anchor);
  533. if (ret != GRAPH_SUCCESS) {
  534. GELOGE(INTERNAL_ERROR, "Failed to add data edge between %s(%d) to %s(%d), error-code %u",
  535. src_batch_node->GetName().c_str(), batch_num, copyed_node->GetName().c_str(), in_anchor->GetIdx(), ret);
  536. return INTERNAL_ERROR;
  537. }
  538. GELOGD("Add data edge from %s(%d) to %s(%d)", src_batch_node->GetName().c_str(), batch_num,
  539. copyed_node->GetName().c_str(), in_anchor->GetIdx());
  540. continue;
  541. }
  542. auto ret = GraphUtils::AddEdge(origin_src_anchor, dst_anchor);
  543. if (ret != GRAPH_SUCCESS) {
  544. GELOGE(INTERNAL_ERROR, "Failed to add data edge between origin node %s(%d) to copyed %s(%d)",
  545. origin_src_node->GetName().c_str(), origin_src_anchor->GetIdx(), copyed_node->GetName().c_str(),
  546. dst_anchor->GetIdx());
  547. return INTERNAL_ERROR;
  548. }
  549. GELOGD("Add data edge between branch-out %s(%d) to branch-in %s(%d)", origin_src_node->GetName().c_str(),
  550. origin_src_anchor->GetIdx(), copyed_node->GetName().c_str(), dst_anchor->GetIdx());
  551. }
  552. return SUCCESS;
  553. }
  554. Status MultiBatchGraphCopyer::CopyInControlEdges(const NodePtr &node, int batch_num, const NodePtr &copyed_node) {
  555. GELOGI("Start copy control edge for %s and %s.", node->GetName().c_str(), copyed_node->GetName().c_str());
  556. for (auto &origin_src_node : node->GetInControlNodes()) {
  557. auto switchn_iter = data_nodes_to_switchn_.find(origin_src_node.get());
  558. if (switchn_iter != data_nodes_to_switchn_.end()) {
  559. // reconnect data node
  560. auto ret = GraphUtils::AddEdge(switchn_iter->second->GetOutControlAnchor(), copyed_node->GetInControlAnchor());
  561. if (ret != GRAPH_SUCCESS) {
  562. GELOGE(INTERNAL_ERROR, "Failed to add control edge between %s to %s, error-code %u",
  563. switchn_iter->second->GetName().c_str(), copyed_node->GetName().c_str(), ret);
  564. return INTERNAL_ERROR;
  565. }
  566. GELOGD("Add control edge from %s to %s", switchn_iter->second->GetName().c_str(), copyed_node->GetName().c_str());
  567. continue;
  568. }
  569. auto batch_branch_iter = nodes_to_batch_nodes_.find(origin_src_node.get());
  570. if (batch_branch_iter != nodes_to_batch_nodes_.end()) {
  571. // reconnect node in batch branch
  572. auto src_batch_node = batch_branch_iter->second.at(batch_num);
  573. auto ret = GraphUtils::AddEdge(src_batch_node->GetOutControlAnchor(), copyed_node->GetInControlAnchor());
  574. if (ret != GRAPH_SUCCESS) {
  575. GELOGE(INTERNAL_ERROR, "Failed to add data edge between %s to %s, error-code %u",
  576. src_batch_node->GetName().c_str(), copyed_node->GetName().c_str(), ret);
  577. return INTERNAL_ERROR;
  578. }
  579. GELOGD("Add control edge from %s to %s", src_batch_node->GetName().c_str(), copyed_node->GetName().c_str());
  580. continue;
  581. }
  582. auto ret = GraphUtils::AddEdge(origin_src_node->GetOutControlAnchor(), copyed_node->GetInControlAnchor());
  583. if (ret != GRAPH_SUCCESS) {
  584. GELOGE(INTERNAL_ERROR, "Failed to add control edge from origin %s to copyed %s",
  585. origin_src_node->GetName().c_str(), copyed_node->GetName().c_str());
  586. return INTERNAL_ERROR;
  587. }
  588. GELOGD("Add control edge between branch-out %s to branch-in %s", origin_src_node->GetName().c_str(),
  589. copyed_node->GetName().c_str());
  590. }
  591. return SUCCESS;
  592. }
  593. NodePtr MultiBatchGraphCopyer::InsertShapeDataNode() {
  594. auto desc = MakeShared<OpDesc>();
  595. if (desc == nullptr) {
  596. GELOGE(OUT_OF_MEMORY, "Failed to create shape data node, out of memory");
  597. return nullptr;
  598. }
  599. string node_name = "ascend_mbatch_shape_data";
  600. // Only flush subgraph name
  601. if (graph_->GetParentGraph() != nullptr) {
  602. node_name = graph_->GetName() + "_" + node_name;
  603. }
  604. desc->SetName(node_name);
  605. desc->SetType(DATA);
  606. // input and output of DATA is gear_info
  607. GeTensorDesc tensor_desc(GeShape({static_cast<int64_t>(shapes_.at(0).size())}), FORMAT_ND, DT_INT64);
  608. auto ret = desc->AddInputDesc(tensor_desc);
  609. if (ret != GRAPH_SUCCESS) {
  610. GELOGE(INTERNAL_ERROR, "Failed to add input desc for created data");
  611. return nullptr;
  612. }
  613. ret = desc->AddOutputDesc(tensor_desc);
  614. if (ret != GRAPH_SUCCESS) {
  615. GELOGE(INTERNAL_ERROR, "Failed to add output desc for created data");
  616. return nullptr;
  617. }
  618. if (!AttrUtils::SetBool(desc, ATTR_INSERT_BY_MBATCH, true)) {
  619. GELOGE(INTERNAL_ERROR, "Failed to add attr for created data");
  620. return nullptr;
  621. }
  622. auto data_node = graph_->AddNode(desc);
  623. if (data_node == nullptr) {
  624. GELOGE(INTERNAL_ERROR, "Failed to add shape data node to graph");
  625. return nullptr;
  626. }
  627. ret = GraphUtils::AppendInputNode(graph_, data_node);
  628. if (ret != GRAPH_SUCCESS) {
  629. GELOGE(INTERNAL_ERROR, "Failed to append data node %s as input to graph", data_node->GetName().c_str());
  630. return nullptr;
  631. }
  632. return data_node;
  633. }
  634. NodePtr MultiBatchGraphCopyer::InsertGetDynamicDimsNode() {
  635. GELOGD("Start insert getdynamicdims node to get shape info.");
  636. auto desc = MakeShared<OpDesc>();
  637. if (desc == nullptr) {
  638. GELOGE(OUT_OF_MEMORY, "Failed to create shape data node, out of memory");
  639. return nullptr;
  640. }
  641. string node_name = "ascend_mbatch_get_dynamic_dims_node";
  642. // Only flush subgraph name
  643. if (graph_->GetParentGraph() != nullptr) {
  644. node_name = graph_->GetName() + "_" + node_name;
  645. }
  646. desc->SetName(node_name);
  647. desc->SetType(GETDYNAMICDIMS);
  648. // input of GetDynamicDims is shape_of_each_data, output is gear_info
  649. for (size_t i = 0; i < GetLocalOmgContext().user_input_dims.size(); ++i) {
  650. size_t input_shape_dims = GetLocalOmgContext().user_input_dims.at(i).second.size();
  651. if (input_shape_dims == 1 && GetLocalOmgContext().user_input_dims.at(i).second.at(0) == 0) {
  652. GeTensorDesc tensor_desc;
  653. tensor_desc.SetFormat(FORMAT_ND);
  654. tensor_desc.SetDataType(DT_INT64);
  655. auto ret = desc->AddInputDesc(tensor_desc);
  656. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to add input desc for created data");
  657. return nullptr);
  658. continue;
  659. }
  660. GeTensorDesc tensor_desc(GeShape({static_cast<int64_t>(input_shape_dims)}), FORMAT_ND, DT_INT64);
  661. auto ret = desc->AddInputDesc(tensor_desc);
  662. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to add input desc for created data");
  663. return nullptr);
  664. }
  665. GeTensorDesc tensor_desc(GeShape({static_cast<int64_t>(shapes_.at(0).size())}), FORMAT_ND, DT_INT64);
  666. auto ret = desc->AddOutputDesc(tensor_desc);
  667. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to add output desc for created data");
  668. return nullptr);
  669. if (!AttrUtils::SetBool(desc, ATTR_INSERT_BY_MBATCH, true)) {
  670. GELOGE(INTERNAL_ERROR, "Failed to add attr for created data");
  671. return nullptr;
  672. }
  673. auto data_node = graph_->AddNode(desc);
  674. if (data_node == nullptr) {
  675. GELOGE(INTERNAL_ERROR, "Failed to add shape data node to graph");
  676. return nullptr;
  677. }
  678. ret = GraphUtils::AppendInputNode(graph_, data_node);
  679. if (ret != GRAPH_SUCCESS) {
  680. GELOGE(INTERNAL_ERROR, "Failed to append data node %s as input to graph", data_node->GetName().c_str());
  681. return nullptr;
  682. }
  683. return data_node;
  684. }
  685. Status MultiBatchGraphCopyer::CheckArguments() {
  686. if (graph_ == nullptr) {
  687. GELOGE(PARAM_INVALID, "Failed to copy graph, the graph is null");
  688. return PARAM_INVALID;
  689. }
  690. return CheckDynamicParams(shapes_);
  691. }
  692. Status MultiBatchGraphCopyer::CheckCopyResult(const std::vector<NodePtr> &start_nodes) {
  693. for (auto &node : start_nodes) {
  694. if (IsOnlyOutputToAipp(node)) {
  695. continue;
  696. }
  697. auto dims = NodeUtils::GetOutputDesc(*node, kDataOutIndex).GetShape().GetDims();
  698. if (!IsAllDimsPositive(dims)) {
  699. GELOGE(INTERNAL_ERROR, "Failed to copy multi batch graph, the node %s still has unknown shape %s",
  700. node->GetName().c_str(), formats::ShapeToString(dims).c_str());
  701. return INTERNAL_ERROR;
  702. }
  703. }
  704. return SUCCESS;
  705. }
  706. bool MultiBatchGraphCopyer::IsInBatchBranch(const NodePtr &node) {
  707. if (!getnext_sink_dynamic_dims_) {
  708. return (nodes_to_batch_nodes_.count(node.get()) > 0) || (data_nodes_to_switchn_.count(node.get()) > 0);
  709. } else {
  710. for (size_t i = 0; i < getnext_nodes_to_switchn_.size(); ++i) {
  711. for (size_t j = 0; j < getnext_nodes_to_switchn_.at(i).size(); ++j) {
  712. if (getnext_nodes_to_switchn_.at(i).at(j).first == node.get()) {
  713. return true;
  714. }
  715. }
  716. }
  717. return nodes_to_batch_nodes_.count(node.get()) > 0;
  718. }
  719. }
  720. Status MultiBatchGraphCopyer::LinkDataToMerge(const NodePtr &data, const NodePtr &merge, const NodePtr &switchn) {
  721. // The caller should make sure that the there is a SwitchN node in the map
  722. GELOGI("Link edge between data %s to merge %s throw switchn %s", data->GetName().c_str(), merge->GetName().c_str(),
  723. switchn->GetName().c_str());
  724. for (size_t i = 0; i < shapes_.size(); ++i) {
  725. auto ret = GraphUtils::AddEdge(switchn->GetOutDataAnchor(i), merge->GetInDataAnchor(i));
  726. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS,
  727. GELOGE(INTERNAL_ERROR, "Failed to add edge between switchn %s(%zu) to merge %s(%zu), error-code %u",
  728. switchn->GetName().c_str(), i, merge->GetName().c_str(), i, ret);
  729. return INTERNAL_ERROR);
  730. }
  731. return SUCCESS;
  732. }
  733. Status MultiBatchGraphCopyer::LinkNodeToMerge(const NodePtr &node, int out_index, const NodePtr &merge) {
  734. auto &copyed_nodes = nodes_to_batch_nodes_[node.get()];
  735. if (copyed_nodes.size() != shapes_.size()) {
  736. GELOGE(INTERNAL_ERROR,
  737. "Failed to create merge node for node %s, the copyed nodes for it count %zu different with shape %zu",
  738. node->GetName().c_str(), copyed_nodes.size(), shapes_.size());
  739. return INTERNAL_ERROR;
  740. }
  741. for (size_t i = 0; i < copyed_nodes.size(); ++i) {
  742. auto src_node = copyed_nodes[i];
  743. if (src_node->GetAllOutDataAnchorsSize() == 0) {
  744. // if the node does not has any data output, we should create an const for it, like this:
  745. // c d
  746. // node ---> const ---> merge
  747. auto const_name = src_node->GetName() + "_merge_const";
  748. GELOGI("The node %s on the batch branch edge does not have any data output, create a const %s for it",
  749. src_node->GetName().c_str(), const_name.c_str());
  750. auto const_node = InsertConst(const_name, graph_);
  751. GE_IF_BOOL_EXEC(const_node == nullptr,
  752. GELOGE(OUT_OF_MEMORY, "Failed to create const for node %s to connect to a merge node",
  753. src_node->GetName().c_str());
  754. return OUT_OF_MEMORY);
  755. auto ret = GraphUtils::AddEdge(src_node->GetOutControlAnchor(), const_node->GetInControlAnchor());
  756. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to add control edge from %s to %s",
  757. src_node->GetName().c_str(), const_node->GetName().c_str());
  758. return INTERNAL_ERROR);
  759. src_node = const_node;
  760. }
  761. auto ret = GraphUtils::AddEdge(src_node->GetOutDataAnchor(out_index), merge->GetInDataAnchor(i));
  762. if (ret != GRAPH_SUCCESS) {
  763. GELOGE(INTERNAL_ERROR,
  764. "Failed to add edge between copyed node %s(%d) to inserted merge node %s(%zu), error-code %u",
  765. copyed_nodes[i]->GetName().c_str(), out_index, merge->GetName().c_str(), i, ret);
  766. return INTERNAL_ERROR;
  767. }
  768. }
  769. return SUCCESS;
  770. }
  771. Status MultiBatchGraphCopyer::InsertSwitchNAndUpdateMaxShape(const NodePtr &node) {
  772. std::vector<std::pair<Node *, NodePtr>> dynamic_out_to_switchn;
  773. if (!getnext_sink_dynamic_dims_) {
  774. if (InsertSwitchNForData(node, kDataOutIndex, kDataOutIndex, dynamic_out_to_switchn) != SUCCESS) {
  775. GELOGE(PARAM_INVALID, "Failed to insert switchn for %s.", node->GetName().c_str());
  776. return PARAM_INVALID;
  777. }
  778. if (UpdateMaxShapeToData(node, kDataOutIndex) != SUCCESS) {
  779. GELOGE(PARAM_INVALID, "Failed to update max shape of %s.", node->GetName().c_str());
  780. return PARAM_INVALID;
  781. }
  782. } else {
  783. if (!IsGetNextType(node)) {
  784. GELOGI("No need to insert switchn and update max shape for %s when get sink dynamic.", node->GetName().c_str());
  785. return SUCCESS;
  786. }
  787. for (size_t i = 0; i < getnext_sink_dynamic_out_mapping_.size(); ++i) {
  788. dynamic_out_to_switchn.clear();
  789. for (size_t j = 0; j < getnext_sink_dynamic_out_mapping_.at(i).second; ++j) {
  790. GELOGI("The %zu data_index has %zu referenced nums.", getnext_sink_dynamic_out_mapping_.at(i).first,
  791. getnext_sink_dynamic_out_mapping_.at(i).second);
  792. if (InsertSwitchNForData(node, getnext_sink_dynamic_out_mapping_.at(i).first, j, dynamic_out_to_switchn) !=
  793. SUCCESS) {
  794. GELOGE(PARAM_INVALID, "Failed to insert switchn for %s of %zu out anchor when referenced index is %zu",
  795. node->GetName().c_str(), getnext_sink_dynamic_out_mapping_.at(i).first, j);
  796. return PARAM_INVALID;
  797. }
  798. }
  799. getnext_nodes_to_switchn_.emplace_back(dynamic_out_to_switchn);
  800. }
  801. for (size_t i = 0; i < getnext_sink_dynamic_out_mapping_.size(); ++i) {
  802. if(UpdateMaxShapeToData(node, i) != SUCCESS) {
  803. GELOGE(PARAM_INVALID, "Failed to update max shape of %zu out anchor", node->GetName().c_str(), i);
  804. return PARAM_INVALID;
  805. }
  806. }
  807. }
  808. return SUCCESS;
  809. }
  810. Status MultiBatchGraphCopyer::UpdateShapeOfShapeNode(const NodePtr &node, size_t out_anchor_index) {
  811. auto data_shape = NodeUtils::GetOutputDesc(*node, out_anchor_index).GetShape();
  812. size_t shape_index = out_anchor_index + (node->GetAllOutDataAnchors().size() / kDivisionConst);
  813. GeTensorDesc output_desc = node->GetOpDesc()->GetOutputDesc(shape_index);
  814. std::vector<int64_t> output_dims = {static_cast<int64_t>(data_shape.GetDims().size())};
  815. GeShape output_shape(output_dims);
  816. output_desc.SetShape(output_shape);
  817. if (node->GetOpDesc()->UpdateOutputDesc(shape_index, output_desc) != SUCCESS) {
  818. GELOGE(FAILED, "Update output desc fail.");
  819. return FAILED;
  820. }
  821. return SUCCESS;
  822. }
  823. Status MultiBatchGraphCopyer::UpdateMaxShapeToData(const NodePtr &node, size_t out_anchor_index) {
  824. GELOGD("Start update max shape of %s, %zu output.", node->GetName().c_str(), out_anchor_index);
  825. auto data_shape = NodeUtils::GetOutputDesc(*node, out_anchor_index).GetShape();
  826. string data_name = node->GetName();
  827. if (getnext_sink_dynamic_dims_) {
  828. data_name.append("_").append(std::to_string(out_anchor_index));
  829. }
  830. GELOGD("Update max shape of %s, shape dims is %s.", data_name, formats::JoinToString(data_shape.GetDims()).c_str());
  831. if (!getnext_sink_dynamic_dims_) {
  832. if (IsAllDimsPositive(data_shape.GetDims())) {
  833. GELOGD("No need to do anything for static data.");
  834. return SUCCESS;
  835. }
  836. } else {
  837. if (IsAllDimsPositive(data_shape.GetDims())) {
  838. // need to update shape of Shape_node
  839. GE_CHK_STATUS_RET(UpdateShapeOfShapeNode(node, out_anchor_index), "Failed to update shape of shape node");
  840. return SUCCESS;
  841. }
  842. }
  843. size_t max_shape_index = 0;
  844. int64_t max_size = 0;
  845. for (size_t i = 0; i < shapes_.size(); ++i) {
  846. int64_t size = 1;
  847. for (auto dim : data_to_dynamic_info_.at(data_name).at(i)) {
  848. if (INT64_MAX / dim < size) {
  849. GELOGE(PARAM_INVALID, "The shape %s size overflow",
  850. formats::ShapeToString(data_to_dynamic_info_[data_name].at(i)).c_str());
  851. return PARAM_INVALID;
  852. }
  853. size *= dim;
  854. }
  855. if (size > max_size) {
  856. max_size = size;
  857. max_shape_index = i;
  858. }
  859. }
  860. // must not be error, the calc result has been checked in function InsertSwitchNForData
  861. (void)CalcShape(data_to_dynamic_info_.at(data_name).at(max_shape_index), data_shape);
  862. auto ret = NodeUtils::UpdateOutputShape(*node, out_anchor_index, data_shape);
  863. GE_CHK_STATUS_RET(ret, "Failed to update output shape for data %s", node->GetName().c_str());
  864. // getnext_sink not has input
  865. if (!getnext_sink_dynamic_dims_) {
  866. ret = NodeUtils::UpdateInputShape(*node, kDataInIndex, data_shape);
  867. GE_CHK_STATUS_RET(ret, "Failed to update input shape for data %s", node->GetName().c_str());
  868. } else {
  869. // need to update shape of Shape_node when getnext_sink_dynamic
  870. GE_CHK_STATUS_RET(UpdateShapeOfShapeNode(node, out_anchor_index), "Failed to update shape of shape node");
  871. }
  872. GELOGI("Update the data %s input/output shape to the max %s", node->GetName().c_str(),
  873. formats::ShapeToString(data_shape).c_str());
  874. return SUCCESS;
  875. }
  876. Status MultiBatchGraphCopyer::InsertSwitchNForData(const NodePtr &node, const size_t &out_anchor_index,
  877. const size_t &peer_in_anchor_index,
  878. std::vector<std::pair<Node *, NodePtr>> &dynamic_out_to_switchn) {
  879. auto data_shape = NodeUtils::GetOutputDesc(*node, out_anchor_index).GetShape();
  880. string data_name = node->GetName();
  881. if (getnext_sink_dynamic_dims_) {
  882. data_name.append("_").append(std::to_string(out_anchor_index));
  883. }
  884. (void)AttrUtils::SetListInt(node->GetOpDesc(), ATTR_MBATCH_ORIGIN_INPUT_DIMS, data_shape.GetDims());
  885. GELOGI("Insert switchn node of %s, shape dims is %s.", data_name.c_str(),
  886. formats::JoinToString(data_shape.GetDims()).c_str());
  887. if (IsAllDimsPositive(data_shape.GetDims())) {
  888. GELOGI("The shape of data %s are positive(%s), skip the multi batch process", node->GetName().c_str(),
  889. data_shape.ToString().c_str());
  890. return SUCCESS;
  891. }
  892. auto switchn_desc = MakeShared<OpDesc>();
  893. GE_IF_BOOL_EXEC(switchn_desc == nullptr,
  894. GELOGE(OUT_OF_MEMORY, "Failed to create switchn for data %s", node->GetName().c_str());
  895. return OUT_OF_MEMORY);
  896. string switchn_name = node->GetName() + "_ascend_mbatch_switchn";
  897. if (getnext_sink_dynamic_dims_) {
  898. switchn_name.append("_").append(std::to_string(out_anchor_index))
  899. .append("_").append(std::to_string(peer_in_anchor_index));
  900. }
  901. GELOGI("name of switchn is %s.", switchn_name.c_str());
  902. switchn_desc->SetName(switchn_name);
  903. switchn_desc->SetType(SWITCHN);
  904. GeTensorDesc tensor(NodeUtils::GetOutputDesc(*node, out_anchor_index));
  905. GE_IF_BOOL_EXEC(switchn_desc->AddInputDesc("data", tensor) != GRAPH_SUCCESS,
  906. GELOGE(OUT_OF_MEMORY, "Failed to add input tensor desc for %s", switchn_desc->GetName().c_str());
  907. return OUT_OF_MEMORY);
  908. GeTensorDesc pred_tensor;
  909. GE_IF_BOOL_EXEC(switchn_desc->AddInputDesc("pred_value", pred_tensor) != GRAPH_SUCCESS,
  910. GELOGE(OUT_OF_MEMORY, "Failed to add input pred tensor desc for %s", switchn_desc->GetName().c_str());
  911. return OUT_OF_MEMORY);
  912. std::vector<std::string> input_dims_str;
  913. for (size_t i = 0; i < shapes_.size(); ++i) {
  914. GELOGI("Start clac shape for data %s, batch shape is %s.", data_name.c_str(),
  915. formats::JoinToString(data_to_dynamic_info_.at(data_name).at(i)).c_str());
  916. auto shape = data_shape;
  917. auto ret = CalcShape(data_to_dynamic_info_.at(data_name).at(i), shape);
  918. if (ret != SUCCESS) {
  919. GELOGE(ret, "Failed to calculate the batched shape for data node %s, the shapes may not match",
  920. node->GetName().c_str());
  921. return ret;
  922. }
  923. tensor.SetShape(shape);
  924. string input_str;
  925. int64_t tensor_size = 0;
  926. (void)TensorUtils::GetTensorSizeInBytes(tensor, tensor_size);
  927. input_str = TypeUtils::FormatToSerialString(tensor.GetFormat()) + ":" +
  928. TypeUtils::DataTypeToSerialString(tensor.GetDataType()) + ":" + node->GetName() + ":" +
  929. std::to_string(tensor_size) + ":" + std::to_string(tensor.GetShape().GetDimNum()) + ":" +
  930. formats::JoinToString(tensor.GetShape().GetDims());
  931. input_dims_str.emplace_back(input_str);
  932. if (!AttrUtils::SetListInt(tensor, ATTR_NAME_SWITCHN_PRED_VALUE, shapes_.at(i))) {
  933. GELOGE(INTERNAL_ERROR, "Failed to add attr value on output %zu tensor", i);
  934. return INTERNAL_ERROR;
  935. }
  936. (void) AttrUtils::SetListInt(tensor, ATTR_NAME_COMBINED_DYNAMIC_DIMS, shape.GetDims());
  937. if (switchn_desc->AddOutputDesc("output" + std::to_string(i), tensor) != GRAPH_SUCCESS) {
  938. GELOGE(GRAPH_FAILED, "Opdesc AddOutputDesc failed");
  939. return GRAPH_FAILED;
  940. }
  941. GELOGD("The switchn %s output index %zu, shape %s", switchn_desc->GetName().c_str(), i, shape.ToString().c_str());
  942. }
  943. (void)AttrUtils::SetListStr(node->GetOpDesc(), "_all_origin_gears_inputs", input_dims_str);
  944. if (!AttrUtils::SetListStr(switchn_desc, ATTR_USER_DESIGNEATE_SHAPE_ORDER, data_name_order_)) {
  945. GELOGE(INTERNAL_ERROR, "Failed to add user designate shape order attr on switchn node %s",
  946. switchn_desc->GetName().c_str());
  947. return INTERNAL_ERROR;
  948. }
  949. if (!AttrUtils::SetBool(switchn_desc, ATTR_INSERT_BY_MBATCH, true)) {
  950. GELOGE(INTERNAL_ERROR, "Failed to add insert attr on switchn node %s", switchn_desc->GetName().c_str());
  951. return INTERNAL_ERROR;
  952. }
  953. if (!AttrUtils::SetStr(node->GetOpDesc(), kMbatchSwitchnName, switchn_desc->GetName())) {
  954. GELOGE(INTERNAL_ERROR, "Failed to add switchn attr on data node %s", node->GetName().c_str());
  955. return INTERNAL_ERROR;
  956. }
  957. if (StampDynamicType(switchn_desc) != SUCCESS) {
  958. GELOGE(INTERNAL_ERROR, "Failed to add dynamic type attr on switchn node %s", switchn_desc->GetName().c_str());
  959. return INTERNAL_ERROR;
  960. }
  961. auto switchn = graph_->AddNode(switchn_desc);
  962. GE_IF_BOOL_EXEC(switchn == nullptr,
  963. GELOGE(OUT_OF_MEMORY, "Failed to create switchn %s from desc", switchn_desc->GetName().c_str());
  964. return OUT_OF_MEMORY);
  965. if (!getnext_sink_dynamic_dims_) {
  966. data_nodes_to_switchn_[node.get()] = switchn;
  967. } else {
  968. dynamic_out_to_switchn.emplace_back(std::make_pair(node.get(), switchn));
  969. GELOGD("Insert %s for %s.", switchn->GetName().c_str(), node->GetName().c_str());
  970. }
  971. return SUCCESS;
  972. }
  973. Status MultiBatchGraphCopyer::InsertMergeForEdgeNode(const NodePtr &node) {
  974. for (auto &in_data_anchor : node->GetAllInDataAnchors()) {
  975. auto src_out_anchor = in_data_anchor->GetPeerOutAnchor();
  976. if (src_out_anchor == nullptr) {
  977. GELOGD("The node %s does not has input at index %d", node->GetName().c_str(), in_data_anchor->GetIdx());
  978. continue;
  979. }
  980. auto in_node = src_out_anchor->GetOwnerNode();
  981. if (!IsInBatchBranch(in_node)) {
  982. continue;
  983. }
  984. auto merge_node = InsertMergeNode(in_node, src_out_anchor->GetIdx());
  985. if (merge_node == nullptr) {
  986. return INTERNAL_ERROR;
  987. }
  988. }
  989. for (auto &in_node : node->GetInControlNodes()) {
  990. if (!IsInBatchBranch(in_node)) {
  991. continue;
  992. }
  993. auto merge_node = InsertMergeNode(in_node, -1);
  994. if (merge_node == nullptr) {
  995. return INTERNAL_ERROR;
  996. }
  997. }
  998. return SUCCESS;
  999. }
  1000. Status MultiBatchGraphCopyer::LinkGetDynamicDimsToNetOutput(const NodePtr &node) {
  1001. if (node->GetType() == NETOUTPUT) {
  1002. if (!GetLocalOmgContext().dynamic_node_type.empty()) {
  1003. if (!AttrUtils::SetStr(node->GetOpDesc(), ATTR_ALL_GEARS_INFO, GetLocalOmgContext().dynamic_dims)) {
  1004. GELOGE(INTERNAL_ERROR, "Failed to set all gears info attr on netoutput %s.", node->GetName().c_str());
  1005. return INTERNAL_ERROR;
  1006. }
  1007. }
  1008. if (getnext_sink_dynamic_dims_) {
  1009. size_t input_index = node->GetAllInDataAnchors().size();
  1010. if (NodeUtils::AppendInputAnchor(node, input_index + 1) != GRAPH_SUCCESS) {
  1011. GELOGE(INTERNAL_ERROR, "Append input anchor of %s of %zu failed.", node->GetName().c_str(), input_index);
  1012. return INTERNAL_ERROR;
  1013. }
  1014. auto ret =
  1015. ge::GraphUtils::AddEdge(shape_data_->GetOutDataAnchor(kDataOutIndex), node->GetInDataAnchor(input_index));
  1016. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to link netoutput %s to getdynamicdims %s",
  1017. node->GetName().c_str(), shape_data_->GetName().c_str());
  1018. return INTERNAL_ERROR);
  1019. if (!AttrUtils::SetBool(node->GetOpDesc(), ATTR_GETNEXT_SINK_DYNMAIC, true)) {
  1020. GELOGE(INTERNAL_ERROR, "Failed to set getnext sink dynamic attr on netoutput %s.", node->GetName().c_str());
  1021. return INTERNAL_ERROR;
  1022. }
  1023. }
  1024. }
  1025. return SUCCESS;
  1026. }
  1027. Status MultiBatchGraphCopyer::CopyNodeInBatchBranch(const NodePtr &node) {
  1028. auto &copyed_nodes = nodes_to_batch_nodes_[node.get()];
  1029. for (size_t i = 0; i < shapes_.size(); ++i) {
  1030. auto copyed_node = InsertCopyNode(node, i);
  1031. if (copyed_node == nullptr) {
  1032. GELOGE(INTERNAL_ERROR, "Failed to add node to graph when copy node %s", node->GetName().c_str());
  1033. return INTERNAL_ERROR;
  1034. }
  1035. copyed_nodes.emplace_back(copyed_node);
  1036. GELOGI("Copy node %s type %s for shape %s, new node name %s", node->GetName().c_str(), node->GetType().c_str(),
  1037. formats::JoinToString(shapes_.at(i)).c_str(), copyed_node->GetName().c_str());
  1038. }
  1039. return SUCCESS;
  1040. }
  1041. Status MultiBatchGraphCopyer::AddAttrForGetDynamicDims(const NodePtr &node) {
  1042. GELOGD("Add attr for :%s, type is %s:", shape_data_->GetName().c_str(), shape_data_->GetType().c_str());
  1043. size_t data_count = node->GetAllOutDataAnchors().size() / kDivisionConst;
  1044. if (!AttrUtils::SetInt(shape_data_->GetOpDesc(), ATTR_GETNEXT_SINK_DATA_COUNT, data_count)) {
  1045. GELOGE(INTERNAL_ERROR, "set ATTR_GETNEXT_SINK_DATA_COUNT failed");
  1046. return INTERNAL_ERROR;
  1047. }
  1048. vector<int64_t> shape_info;
  1049. for (size_t i = 0; i < GetLocalOmgContext().user_input_dims.size(); ++i) {
  1050. if (GetLocalOmgContext().user_input_dims.at(i).second.size() == 1 &&
  1051. GetLocalOmgContext().user_input_dims.at(i).second.at(0) == 0) {
  1052. shape_info.emplace_back(0);
  1053. continue;
  1054. }
  1055. shape_info.emplace_back(GetLocalOmgContext().user_input_dims.at(i).second.size());
  1056. for (size_t j = 0; j < GetLocalOmgContext().user_input_dims.at(i).second.size(); ++j) {
  1057. shape_info.emplace_back(GetLocalOmgContext().user_input_dims.at(i).second.at(j));
  1058. }
  1059. }
  1060. if (!AttrUtils::SetListInt(shape_data_->GetOpDesc(), ATTR_GETNEXT_SINK_SHAPE_INFO, shape_info)) {
  1061. GELOGE(INTERNAL_ERROR, "set ATTR_GETNEXT_SINK_SHAPE_INFO failed");
  1062. return INTERNAL_ERROR;
  1063. }
  1064. return SUCCESS;
  1065. }
  1066. Status MultiBatchGraphCopyer::AddLinkForGetDynamicDims(const NodePtr &node) {
  1067. GELOGD("Start relink out anchor from shape node to getdynamicdims, and delete link between shape node and identity.");
  1068. size_t input_index = 0;
  1069. GELOGD("Out count of %s is %zu.", node->GetName().c_str(), node->GetAllOutDataAnchors().size());
  1070. size_t data_count = node->GetAllOutDataAnchors().size() / kDivisionConst;
  1071. for (size_t out_index = data_count; out_index < node->GetAllOutDataAnchors().size(); ++out_index, ++input_index) {
  1072. GELOGI("Start add %s of %zu out_anchor to %s of %zu in_anchor.", node->GetName().c_str(), out_index,
  1073. shape_data_->GetName().c_str(), input_index);
  1074. auto out_data_anchor = node->GetOutDataAnchor(out_index);
  1075. auto ret = GraphUtils::AddEdge(out_data_anchor, shape_data_->GetInDataAnchor(input_index));
  1076. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to link getnext %s to getdynamicdims %s",
  1077. node->GetName().c_str(), shape_data_->GetName().c_str());
  1078. return INTERNAL_ERROR);
  1079. }
  1080. return SUCCESS;
  1081. }
  1082. Status MultiBatchGraphCopyer::LinkEdges() {
  1083. Status ret;
  1084. for (const auto &node : origin_all_nodes_) {
  1085. GE_CHECK_NOTNULL(node->GetOpDesc());
  1086. if (!getnext_sink_dynamic_dims_) {
  1087. if (data_nodes_to_switchn_.count(node.get()) > 0) {
  1088. auto switchn = data_nodes_to_switchn_[node.get()];
  1089. GE_IF_BOOL_EXEC(switchn == nullptr,
  1090. GELOGE(PARAM_INVALID, "Switchn should not be nullptr for %s.", node->GetName().c_str());
  1091. return OUT_OF_MEMORY);
  1092. ret = LinkDataToSwitchN(node, switchn, kDataOutIndex);
  1093. GE_CHK_STATUS_RET(ret, "Link data to switchn failed.");
  1094. }
  1095. } else {
  1096. if (IsGetNextType(node)) {
  1097. GELOGD("Start add attr and link edge for %s.", node->GetName().c_str());
  1098. GE_CHK_STATUS_RET(AddAttrForGetDynamicDims(node), "Failed to add attr for %s.", node->GetName().c_str());
  1099. GE_CHK_STATUS_RET(AddLinkForGetDynamicDims(node), "Failed to add link for %s.", node->GetName().c_str());
  1100. }
  1101. for (size_t i = 0; i < getnext_nodes_to_switchn_.size(); ++i) {
  1102. for (size_t j = 0; j < getnext_nodes_to_switchn_.at(i).size(); ++j) {
  1103. if (getnext_nodes_to_switchn_.at(i).at(j).first == node.get()) {
  1104. auto switchn = getnext_nodes_to_switchn_.at(i).at(j).second;
  1105. GE_CHK_STATUS_RET(LinkDataToSwitchN(node, switchn, i), "Link %s to %s failed.", node->GetName().c_str(),
  1106. switchn->GetName().c_str());
  1107. }
  1108. }
  1109. }
  1110. }
  1111. if (nodes_to_merge_nodes_.count(node.get()) > 0) {
  1112. GE_CHK_STATUS_RET(LinkToMerge(node), "Link %s to merge failed.", node->GetName().c_str());
  1113. }
  1114. if (nodes_to_batch_nodes_.count(node.get()) > 0) {
  1115. ret = LinkToNodeInBranch(node);
  1116. } else {
  1117. ret = LinkToNodeOutBranch(node);
  1118. }
  1119. if (ret != SUCCESS) {
  1120. return ret;
  1121. }
  1122. }
  1123. return SUCCESS;
  1124. }
  1125. Status MultiBatchGraphCopyer::LinkDataToSwitchN(const NodePtr &data, const NodePtr &switchn, const int &out_index) {
  1126. auto ret =
  1127. GraphUtils::AddEdge(shape_data_->GetOutDataAnchor(kDataOutIndex), switchn->GetInDataAnchor(kSwitchNPredIndex));
  1128. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to link shape data %s to switchn %s",
  1129. shape_data_->GetName().c_str(), switchn->GetName().c_str());
  1130. return INTERNAL_ERROR);
  1131. ret = GraphUtils::AddEdge(data->GetOutDataAnchor(out_index), switchn->GetInDataAnchor(kSwitchNDataIndex));
  1132. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to link data %s to switchn %s",
  1133. data->GetName().c_str(), switchn->GetName().c_str());
  1134. return INTERNAL_ERROR);
  1135. return SUCCESS;
  1136. }
  1137. Status MultiBatchGraphCopyer::LinkToMerge(const NodePtr &node) {
  1138. auto &merge_nodes = nodes_to_merge_nodes_[node.get()];
  1139. for (size_t i = 0; i < merge_nodes.size(); ++i) {
  1140. auto merge_node = merge_nodes[i];
  1141. if (merge_node == nullptr) {
  1142. continue;
  1143. }
  1144. if (nodes_to_batch_nodes_.count(node.get()) > 0) {
  1145. auto ret = LinkNodeToMerge(node, i, merge_node);
  1146. if (ret != SUCCESS) {
  1147. return ret;
  1148. }
  1149. continue;
  1150. }
  1151. if (!getnext_sink_dynamic_dims_) {
  1152. if (data_nodes_to_switchn_.count(node.get()) > 0) {
  1153. auto &switchn = data_nodes_to_switchn_[node.get()];
  1154. auto ret = LinkDataToMerge(node, merge_node, switchn);
  1155. if (ret != SUCCESS) {
  1156. return ret;
  1157. }
  1158. continue;
  1159. }
  1160. } else {
  1161. for (size_t j = 0; j < getnext_nodes_to_switchn_.size(); ++j) {
  1162. for (size_t k = 0; k < getnext_nodes_to_switchn_.at(j).size(); ++k) {
  1163. if (getnext_nodes_to_switchn_.at(j).at(k).first == node.get()) {
  1164. auto &switchn = getnext_nodes_to_switchn_.at(j).at(k).second;
  1165. auto ret = LinkDataToMerge(node, merge_node, switchn);
  1166. if (ret != SUCCESS) {
  1167. return ret;
  1168. }
  1169. }
  1170. }
  1171. }
  1172. continue;
  1173. }
  1174. GELOGE(INTERNAL_ERROR, "The merge node %s is created, index %zu, but can not find the src node",
  1175. merge_node->GetName().c_str(), i);
  1176. return INTERNAL_ERROR;
  1177. }
  1178. return SUCCESS;
  1179. }
  1180. Status MultiBatchGraphCopyer::LinkToNodeInBranch(const NodePtr &node) {
  1181. GELOGI("Start LinkToNodeInBranch for %s.", node->GetName().c_str());
  1182. auto &branch_nodes = nodes_to_batch_nodes_[node.get()];
  1183. for (size_t i = 0; i < branch_nodes.size(); ++i) {
  1184. auto ret = CopyInDataEdges(node, i, branch_nodes[i]);
  1185. if (ret != SUCCESS) {
  1186. return ret;
  1187. }
  1188. ret = CopyInControlEdges(node, i, branch_nodes[i]);
  1189. if (ret != SUCCESS) {
  1190. return ret;
  1191. }
  1192. }
  1193. return SUCCESS;
  1194. }
  1195. Status MultiBatchGraphCopyer::LinkToNodeOutBranch(const NodePtr &node) {
  1196. for (auto &in_data_anchor : node->GetAllInDataAnchors()) {
  1197. auto src_out_anchor = in_data_anchor->GetPeerOutAnchor();
  1198. if (src_out_anchor == nullptr) {
  1199. GELOGD("The node %s does not has input at index %d", node->GetName().c_str(), in_data_anchor->GetIdx());
  1200. continue;
  1201. }
  1202. auto in_node = src_out_anchor->GetOwnerNode();
  1203. if (!IsInBatchBranch(in_node)) {
  1204. continue;
  1205. }
  1206. auto iter = nodes_to_merge_nodes_.find(in_node.get());
  1207. if (iter == nodes_to_merge_nodes_.end()) {
  1208. GELOGE(INTERNAL_ERROR, "Failed to link IO data edge from %s(%d) to %s(%d), no merge node found",
  1209. in_node->GetName().c_str(), src_out_anchor->GetIdx(), node->GetName().c_str(), in_data_anchor->GetIdx());
  1210. return INTERNAL_ERROR;
  1211. }
  1212. auto merge_node = iter->second[src_out_anchor->GetIdx()];
  1213. if (merge_node == nullptr) {
  1214. GELOGE(INTERNAL_ERROR, "Failed to link IO data edge from %s(%d) to %s(%d), no merge node found",
  1215. in_node->GetName().c_str(), src_out_anchor->GetIdx(), node->GetName().c_str(), in_data_anchor->GetIdx());
  1216. return INTERNAL_ERROR;
  1217. }
  1218. auto ret = src_out_anchor->Unlink(in_data_anchor);
  1219. if (ret != GRAPH_SUCCESS) {
  1220. GELOGE(INTERNAL_ERROR, "Failed to unlink the control edge from %s(%d) to %s(%d)", in_node->GetName().c_str(),
  1221. src_out_anchor->GetIdx(), node->GetName().c_str(), in_data_anchor->GetIdx());
  1222. return INTERNAL_ERROR;
  1223. }
  1224. ret = GraphUtils::AddEdge(merge_node->GetOutDataAnchor(kMergeDataOutIndex), in_data_anchor);
  1225. if (ret != GRAPH_SUCCESS) {
  1226. GELOGE(INTERNAL_ERROR, "Failed to add data edge from %s(%d) to %s(%d)", merge_node->GetName().c_str(),
  1227. src_out_anchor->GetIdx(), node->GetName().c_str(), in_data_anchor->GetIdx());
  1228. return INTERNAL_ERROR;
  1229. }
  1230. GELOGI("Link data edge from merge %s(from %s(%d)) to %s(%d)", merge_node->GetName().c_str(),
  1231. in_node->GetName().c_str(), src_out_anchor->GetIdx(), node->GetName().c_str(), in_data_anchor->GetIdx());
  1232. }
  1233. for (auto &in_node : node->GetInControlNodes()) {
  1234. if (!IsInBatchBranch(in_node)) {
  1235. continue;
  1236. }
  1237. auto iter = nodes_to_merge_nodes_.find(in_node.get());
  1238. if (iter == nodes_to_merge_nodes_.end()) {
  1239. GELOGE(INTERNAL_ERROR, "Failed to link IO control edge from %s to %s, no merge node found",
  1240. in_node->GetName().c_str(), node->GetName().c_str());
  1241. return INTERNAL_ERROR;
  1242. }
  1243. auto merge_node = iter->second[0];
  1244. if (merge_node == nullptr) {
  1245. GELOGE(INTERNAL_ERROR, "Failed to link IO control edge from %s to %s, no merge node found",
  1246. in_node->GetName().c_str(), node->GetName().c_str());
  1247. return INTERNAL_ERROR;
  1248. }
  1249. GE_IF_BOOL_EXEC(in_node->GetOutControlAnchor() == nullptr,
  1250. GELOGE(INTERNAL_ERROR, "Innode outputControlAnchor is null");
  1251. return INTERNAL_ERROR);
  1252. auto ret = in_node->GetOutControlAnchor()->Unlink(node->GetInControlAnchor());
  1253. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to unlink the control edge from %s to %s",
  1254. in_node->GetName().c_str(), node->GetName().c_str());
  1255. return INTERNAL_ERROR);
  1256. ret = GraphUtils::AddEdge(merge_node->GetOutControlAnchor(), node->GetInControlAnchor());
  1257. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to add control edge from %s to %s",
  1258. merge_node->GetName().c_str(), node->GetName().c_str());
  1259. return INTERNAL_ERROR);
  1260. GELOGI("Link control edge from merge %s(from %s) to %s", merge_node->GetName().c_str(), in_node->GetName().c_str(),
  1261. node->GetName().c_str());
  1262. }
  1263. return SUCCESS;
  1264. }
  1265. Status MultiBatchGraphCopyer::InsertIdentityAfterSwitchN() {
  1266. for (auto &node : graph_->GetAllNodes()) {
  1267. if (node->GetType() != SWITCHN) {
  1268. continue;
  1269. }
  1270. auto switchn_desc = node->GetOpDesc();
  1271. GE_CHECK_NOTNULL(switchn_desc);
  1272. size_t i = 0;
  1273. for (auto &out_data_anchor : node->GetAllOutDataAnchors()) {
  1274. for (auto &in_data_anchor : out_data_anchor->GetPeerInDataAnchors()) {
  1275. auto out_node = in_data_anchor->GetOwnerNode();
  1276. auto op_desc = out_node->GetOpDesc();
  1277. GE_CHECK_NOTNULL(op_desc);
  1278. if ((out_node->GetType() == MERGE) && (op_desc->HasAttr(ATTR_INSERT_BY_MBATCH))) {
  1279. GELOGD("No need to insert identity between %s and %s.", node->GetName().c_str(), out_node->GetName().c_str());
  1280. continue;
  1281. }
  1282. auto identity_desc = MakeShared<OpDesc>(node->GetName() + "_identity_" + std::to_string(i), IDENTITY);
  1283. GE_CHECK_NOTNULL(identity_desc);
  1284. string batch_label;
  1285. if (AttrUtils::GetStr(op_desc, ATTR_NAME_BATCH_LABEL, batch_label)) {
  1286. if (!AttrUtils::SetStr(identity_desc, ATTR_NAME_BATCH_LABEL, batch_label)) {
  1287. GELOGE(FAILED, "Set attr ATTR_NAME_BATCH_LABEL failed, node:%s.", identity_desc->GetName().c_str());
  1288. return FAILED;
  1289. }
  1290. }
  1291. auto data_desc = switchn_desc->GetOutputDesc(i);
  1292. i++;
  1293. GE_CHK_STATUS_RET(identity_desc->AddInputDesc("x", data_desc));
  1294. GE_CHK_STATUS_RET(identity_desc->AddOutputDesc("y", data_desc));
  1295. auto identity_node = graph_->AddNode(identity_desc);
  1296. GE_CHECK_NOTNULL(identity_node);
  1297. GE_CHK_STATUS_RET(out_data_anchor->LinkTo(identity_node->GetInDataAnchor(0)));
  1298. GE_CHECK_NOTNULL(identity_node->GetOutControlAnchor());
  1299. GE_CHK_STATUS_RET(identity_node->GetOutControlAnchor()->LinkTo(out_node->GetInControlAnchor()));
  1300. }
  1301. }
  1302. }
  1303. return SUCCESS;
  1304. }
  1305. Status ProcessMultiBatch(ComputeGraphPtr &graph) {
  1306. if (!GetLocalOmgContext().need_multi_batch) {
  1307. GELOGI("No need to process_multi for no_train graph.");
  1308. return SUCCESS;
  1309. }
  1310. std::vector<NodePtr> data_nodes;
  1311. std::vector<NodePtr> getnext_nosink_nodes;
  1312. std::vector<NodePtr> getnext_sink_nodes;
  1313. if (CheckSequenceOfOptions(graph, data_nodes, getnext_nosink_nodes, getnext_sink_nodes) != SUCCESS) {
  1314. GELOGE(PARAM_INVALID, "[Train_Dynamic] CheckSequenceOfOptions failed.");
  1315. return PARAM_INVALID;
  1316. }
  1317. if (UpdateNameOfInputShape(graph, data_nodes, getnext_nosink_nodes, getnext_sink_nodes) != SUCCESS) {
  1318. GELOGE(PARAM_INVALID, "[Train_Dynamic] UpdateNameForInputShapeOfOption failed.");
  1319. return PARAM_INVALID;
  1320. }
  1321. if (DeleteIdentityInsertByAdapter(graph) != SUCCESS) {
  1322. GELOGE(PARAM_INVALID, "DeleteIdentityInsertByAdapter failed.");
  1323. return PARAM_INVALID;
  1324. }
  1325. std::vector<std::vector<int64_t>> shapes;
  1326. if (!InitDynamicParams(shapes)) {
  1327. GELOGD("There is no multi-batch options, no need to process multi-batch copy");
  1328. return SUCCESS;
  1329. }
  1330. if (CheckNegativeCountOfOptions(shapes) != SUCCESS) {
  1331. GELOGE(PARAM_INVALID, "Input_shape and dynamic_dims should set correct params.");
  1332. return PARAM_INVALID;
  1333. }
  1334. DynamicType dynamic_type = DynamicType::kDynamicUnknown;
  1335. if (!GetLocalOmgContext().dynamic_batch_size.empty()) {
  1336. dynamic_type = DynamicType::kDynamicBatch;
  1337. } else if (!GetLocalOmgContext().dynamic_image_size.empty()) {
  1338. dynamic_type = DynamicType::kDynamicImageSize;
  1339. } else if (!GetLocalOmgContext().dynamic_dims.empty()) {
  1340. dynamic_type = DynamicType::kDynamicDims;
  1341. }
  1342. std::vector<std::pair<std::string, std::vector<int64_t>>> user_designate_shape;
  1343. user_designate_shape = GetLocalOmgContext().user_input_dims;
  1344. GELOGI("Begin to copy graph for multi-batch");
  1345. multibatch::MultiBatchGraphCopyer copyer(graph);
  1346. for (auto &shape : shapes) {
  1347. copyer.AddShape(shape);
  1348. }
  1349. copyer.SetDynamicType(dynamic_type);
  1350. copyer.SetUserDesignateShape(user_designate_shape);
  1351. return copyer.CopyGraph();
  1352. }
  1353. // +-----------+
  1354. // | Data | +-----------+ +-----------+ +-----------+
  1355. // +-----------+ | Data | ----> | SoftmaxV2 | ----> | NetOutput |
  1356. // \ /. +-----------+ +-----------+ +-----------+
  1357. // \ /.
  1358. // +-----------+ +-----------+ /. +-----------+ +-----------+ +-----------+
  1359. // | Data | ----> | Case | S--- | Data | ----> | SoftmaxV2 | ----> | NetOutput |
  1360. // +-----------+ +-----------+ \. +-----------+ +-----------+ +-----------+
  1361. // \ \.
  1362. // \ \. +-----------+ +-----------+ +-----------+
  1363. // +-----------+ | Data | ----> | SoftmaxV2 | ----> | NetOutput |
  1364. // | NetOutput | +-----------+ +-----------+ +-----------+
  1365. // +-----------+
  1366. // +-----------+ /
  1367. // | Data | --------------->/
  1368. // +-----------+
  1369. void GetDynamicShapeByGraph(const ComputeGraphPtr &graph, const NodePtr &node,
  1370. set<size_t> &dynamic_output_index, vector<string> &dynamic_output_dims) {
  1371. GELOGD("Try get dynamic shape info, Graph: %s, Node: %s", graph->GetName().c_str(), node->GetName().c_str());
  1372. const auto &func_desc = node->GetOpDesc();
  1373. if (!func_desc->HasAttr(ATTR_NAME_BATCH_NUM)) {
  1374. GELOGD("Graph: %s Not multi-batch, Node: %s", graph->GetName().c_str(), node->GetName().c_str());
  1375. return;
  1376. }
  1377. const auto &dynamic_branch_names = func_desc->GetSubgraphInstanceNames();
  1378. for (size_t i = 0; i < func_desc->GetOutputsSize(); ++i) {
  1379. for (size_t j = 0; j < dynamic_branch_names.size(); ++j) {
  1380. const auto &subgraph = graph->GetSubgraph(dynamic_branch_names[j]);
  1381. if (subgraph == nullptr) {
  1382. GELOGE(GE_GRAPH_EMPTY_SUBGRAPH, "Subgraph not found, name: %s", dynamic_branch_names[j].c_str());
  1383. dynamic_output_dims.clear();
  1384. return;
  1385. }
  1386. const auto &out_node = subgraph->FindFirstNodeMatchType(NETOUTPUT);
  1387. if (out_node == nullptr) {
  1388. GELOGE(GE_GRAPH_GRAPH_NODE_NULL, "NetOutput not found, name: %s", dynamic_branch_names[j].c_str());
  1389. dynamic_output_dims.clear();
  1390. return;
  1391. }
  1392. GELOGI("Find the subgraph Output node %s and the index is %zu", out_node->GetName().c_str(), i);
  1393. const auto &out_desc = out_node->GetOpDesc();
  1394. if (out_desc == nullptr || out_desc->GetInputsSize() <= i) {
  1395. GELOGE(GE_GRAPH_GRAPH_NODE_NULL, "Get Input desc failed, name: %s, index: %zu", out_node->GetName().c_str(), i);
  1396. dynamic_output_dims.clear();
  1397. return;
  1398. }
  1399. const auto &input_tensor = out_desc->GetInputDesc(i);
  1400. const auto &shape_msg = input_tensor.GetShape().ToString();
  1401. string output_shape = std::to_string(j) + "," + std::to_string(i) + "," + shape_msg;
  1402. GELOGI("The shape msg in dynamic batch is %s", output_shape.c_str());
  1403. dynamic_output_dims.emplace_back(output_shape);
  1404. uint32_t parent_index = 0;
  1405. (void)AttrUtils::GetInt(input_tensor, ATTR_NAME_PARENT_NODE_INDEX, parent_index);
  1406. dynamic_output_index.insert(parent_index);
  1407. }
  1408. }
  1409. }
  1410. // +-----------+ +-----------+ i = 0
  1411. // +----> | SoftmaxV2 | ----> |MemcpyAsync| ----> \.
  1412. // / +-----------+ +-----------+ \.
  1413. // / \.
  1414. // +-----------+ +-----------+ +-----------+ +-----------+ i = 1 +-----------+
  1415. // | Data | ----> | SwitchN | ----> | SoftmaxV2 | ----> |MemcpyAsync| ----> | Merge |
  1416. // +-----------+ +-----------+ +-----------+ +-----------+ +-----------+
  1417. // \ / \. j = 0
  1418. // \ +-----------+ +-----------+ i = 2 / \.
  1419. // +----> | SoftmaxV2 | ----> |MemcpyAsync| ----> / +-----------+
  1420. // +-----------+ +-----------+ | NetOutput |
  1421. // +-----------+
  1422. // +-----------+ /.
  1423. // | Data | --------------------------------------------------------------------------->/. j = 1
  1424. // +-----------+
  1425. void GetDynamicShapeByMerge(const ComputeGraphPtr &graph, const NodePtr &node,
  1426. set<size_t> &dynamic_output_index, vector<string> &dynamic_output_dims) {
  1427. GELOGD("Try get dynamic shape info, Graph: %s, Node: %s", graph->GetName().c_str(), node->GetName().c_str());
  1428. const auto &netoutput_desc = node->GetOpDesc();
  1429. const auto &inputnode_to_netoutput = node->GetInAllNodes();
  1430. GELOGI("Train_Dynamic Find the merge node size is %zu.", inputnode_to_netoutput.size());
  1431. for (size_t i = 0; i < inputnode_to_netoutput.size(); ++i) {
  1432. bool insert_by_mbatch = false;
  1433. (void)AttrUtils::GetBool(inputnode_to_netoutput.at(i)->GetOpDesc(), ATTR_INSERT_BY_MBATCH, insert_by_mbatch);
  1434. GELOGI("Train_Dynamic type is %s", inputnode_to_netoutput.at(i)->GetType().c_str());
  1435. if (inputnode_to_netoutput.at(i)->GetType() == MERGE && insert_by_mbatch) {
  1436. GELOGI("Find the merge node %s with mbatch attr and the index is %zu",
  1437. inputnode_to_netoutput.at(i)->GetName().c_str(), i);
  1438. dynamic_output_index.insert(i);
  1439. for (size_t j = 0; j < inputnode_to_netoutput.at(i)->GetInNodes().size(); ++j) {
  1440. auto input_desc = inputnode_to_netoutput.at(i)->GetOpDesc();
  1441. auto input_tensor_desc = input_desc->GetInputDesc(j);
  1442. auto shape_msg = input_tensor_desc.GetShape().ToString();
  1443. string output_shape = std::to_string(j) + "," + std::to_string(i) + "," + shape_msg;
  1444. GELOGI("The shape msg in dynamic batch is %s", output_shape.c_str());
  1445. dynamic_output_dims.emplace_back(output_shape);
  1446. }
  1447. }
  1448. }
  1449. }
  1450. // Connect NetOutput directly
  1451. void GetDirectOutputShape(const ComputeGraphPtr &graph, const NodePtr &node,
  1452. const set<size_t> &dynamic_output_index, vector<string> &dynamic_output_dims) {
  1453. GELOGD("Try get directly shape info, Graph: %s, Node: %s", graph->GetName().c_str(), node->GetName().c_str());
  1454. const auto &netoutput_desc = node->GetOpDesc();
  1455. const auto &inputnode_to_netoutput = node->GetInAllNodes();
  1456. for (size_t i = 0; i < inputnode_to_netoutput.size(); ++i) {
  1457. if (dynamic_output_index.count(i) > 0) {
  1458. continue;
  1459. }
  1460. if (inputnode_to_netoutput.at(i)->GetType() == GETDYNAMICDIMS) {
  1461. continue;
  1462. }
  1463. auto tensor_desc = netoutput_desc->GetInputDesc(i);
  1464. auto shape = tensor_desc.GetShape().ToString();
  1465. string static_output_shape = std::to_string(kStaticOutput) + "," + std::to_string(i) + "," + shape;
  1466. GELOGI("The static output shape msg is %s", static_output_shape.c_str());
  1467. dynamic_output_dims.emplace_back(static_output_shape);
  1468. }
  1469. }
  1470. Status GetDynamicOutputShape(ComputeGraphPtr &graph) {
  1471. GE_CHECK_NOTNULL(graph);
  1472. GELOGI("Start to get output dynamic batch shape message");
  1473. NodePtr net_output;
  1474. set<size_t> dynamic_output_index;
  1475. vector<string> dynamic_output_dims;
  1476. for (auto &node : graph->GetDirectNode()) {
  1477. if (node->GetType() == NETOUTPUT) {
  1478. net_output = node;
  1479. GetDynamicShapeByMerge(graph, node, dynamic_output_index, dynamic_output_dims);
  1480. } else if (node->GetType() == CASE) {
  1481. GetDynamicShapeByGraph(graph, node, dynamic_output_index, dynamic_output_dims);
  1482. }
  1483. }
  1484. if ((net_output != nullptr) && !dynamic_output_dims.empty()) {
  1485. GetDirectOutputShape(graph, net_output, dynamic_output_index, dynamic_output_dims);
  1486. if (!AttrUtils::SetListStr(net_output->GetOpDesc(), ATTR_NAME_DYNAMIC_OUTPUT_DIMS, dynamic_output_dims)) {
  1487. GELOGE(FAILED, "Set dynamic output dims attr failed");
  1488. return FAILED;
  1489. }
  1490. }
  1491. return SUCCESS;
  1492. }
  1493. } // namespace multibatch
  1494. } // namespace ge

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