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 72 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
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
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621
  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. Status MultiBatchGraphCopyer::CopyInDataEdges(const NodePtr &origin_node, int batch_num, const NodePtr &copyed_node) {
  505. GELOGI("Start copy data edges for %s and %s.", origin_node->GetName().c_str(), copyed_node->GetName().c_str());
  506. for (auto &in_anchor : origin_node->GetAllInDataAnchors()) {
  507. auto origin_src_anchor = in_anchor->GetPeerOutAnchor();
  508. if (origin_src_anchor == nullptr) {
  509. GELOGD("The node %s does not have input on index %d", origin_node->GetName().c_str(), in_anchor->GetIdx());
  510. continue;
  511. }
  512. auto origin_src_node = origin_src_anchor->GetOwnerNode();
  513. auto dst_anchor = copyed_node->GetInDataAnchor(in_anchor->GetIdx());
  514. GE_CHECK_NOTNULL(dst_anchor);
  515. auto switchn = FindSwitchnNodeForDataEdge(origin_src_anchor, origin_node);
  516. if (switchn != nullptr) {
  517. auto ret = GraphUtils::AddEdge(switchn->GetOutDataAnchor(batch_num), dst_anchor);
  518. if (ret != GRAPH_SUCCESS) {
  519. GELOGE(INTERNAL_ERROR, "Failed to add data edge between %s(%d) to %s(%d), error-code %u",
  520. switchn->GetName().c_str(), batch_num, copyed_node->GetName().c_str(), in_anchor->GetIdx(),
  521. ret);
  522. return INTERNAL_ERROR;
  523. }
  524. GELOGD("Add data edge from %s(%d) to %s(%d)", switchn->GetName().c_str(), batch_num,
  525. copyed_node->GetName().c_str(), in_anchor->GetIdx());
  526. continue;
  527. }
  528. auto batch_branch_iter = nodes_to_batch_nodes_.find(origin_src_node.get());
  529. if (batch_branch_iter != nodes_to_batch_nodes_.end()) {
  530. auto src_batch_node = batch_branch_iter->second.at(batch_num);
  531. auto ret = GraphUtils::AddEdge(src_batch_node->GetOutDataAnchor(origin_src_anchor->GetIdx()), dst_anchor);
  532. if (ret != GRAPH_SUCCESS) {
  533. GELOGE(INTERNAL_ERROR, "Failed to add data edge between %s(%d) to %s(%d), error-code %u",
  534. src_batch_node->GetName().c_str(), batch_num, copyed_node->GetName().c_str(), in_anchor->GetIdx(), ret);
  535. return INTERNAL_ERROR;
  536. }
  537. GELOGD("Add data edge from %s(%d) to %s(%d)", src_batch_node->GetName().c_str(), batch_num,
  538. copyed_node->GetName().c_str(), in_anchor->GetIdx());
  539. continue;
  540. }
  541. auto ret = GraphUtils::AddEdge(origin_src_anchor, dst_anchor);
  542. if (ret != GRAPH_SUCCESS) {
  543. GELOGE(INTERNAL_ERROR, "Failed to add data edge between origin node %s(%d) to copyed %s(%d)",
  544. origin_src_node->GetName().c_str(), origin_src_anchor->GetIdx(), copyed_node->GetName().c_str(),
  545. dst_anchor->GetIdx());
  546. return INTERNAL_ERROR;
  547. }
  548. GELOGD("Add data edge between branch-out %s(%d) to branch-in %s(%d)", origin_src_node->GetName().c_str(),
  549. origin_src_anchor->GetIdx(), copyed_node->GetName().c_str(), dst_anchor->GetIdx());
  550. }
  551. return SUCCESS;
  552. }
  553. Status MultiBatchGraphCopyer::CopyInControlEdges(const NodePtr &node, int batch_num, const NodePtr &copyed_node) {
  554. GELOGI("Start copy control edge for %s and %s.", node->GetName().c_str(), copyed_node->GetName().c_str());
  555. for (auto &origin_src_node : node->GetInControlNodes()) {
  556. auto switchn_iter = data_nodes_to_switchn_.find(origin_src_node.get());
  557. if (switchn_iter != data_nodes_to_switchn_.end()) {
  558. // reconnect data node
  559. auto ret = GraphUtils::AddEdge(switchn_iter->second->GetOutControlAnchor(), copyed_node->GetInControlAnchor());
  560. if (ret != GRAPH_SUCCESS) {
  561. GELOGE(INTERNAL_ERROR, "Failed to add control edge between %s to %s, error-code %u",
  562. switchn_iter->second->GetName().c_str(), copyed_node->GetName().c_str(), ret);
  563. return INTERNAL_ERROR;
  564. }
  565. GELOGD("Add control edge from %s to %s", switchn_iter->second->GetName().c_str(), copyed_node->GetName().c_str());
  566. continue;
  567. }
  568. auto batch_branch_iter = nodes_to_batch_nodes_.find(origin_src_node.get());
  569. if (batch_branch_iter != nodes_to_batch_nodes_.end()) {
  570. // reconnect node in batch branch
  571. auto src_batch_node = batch_branch_iter->second.at(batch_num);
  572. auto ret = GraphUtils::AddEdge(src_batch_node->GetOutControlAnchor(), copyed_node->GetInControlAnchor());
  573. if (ret != GRAPH_SUCCESS) {
  574. GELOGE(INTERNAL_ERROR, "Failed to add data edge between %s to %s, error-code %u",
  575. src_batch_node->GetName().c_str(), copyed_node->GetName().c_str(), ret);
  576. return INTERNAL_ERROR;
  577. }
  578. GELOGD("Add control edge from %s to %s", src_batch_node->GetName().c_str(), copyed_node->GetName().c_str());
  579. continue;
  580. }
  581. auto ret = GraphUtils::AddEdge(origin_src_node->GetOutControlAnchor(), copyed_node->GetInControlAnchor());
  582. if (ret != GRAPH_SUCCESS) {
  583. GELOGE(INTERNAL_ERROR, "Failed to add control edge from origin %s to copyed %s",
  584. origin_src_node->GetName().c_str(), copyed_node->GetName().c_str());
  585. return INTERNAL_ERROR;
  586. }
  587. GELOGD("Add control edge between branch-out %s to branch-in %s", origin_src_node->GetName().c_str(),
  588. copyed_node->GetName().c_str());
  589. }
  590. return SUCCESS;
  591. }
  592. NodePtr MultiBatchGraphCopyer::InsertShapeDataNode() {
  593. auto desc = MakeShared<OpDesc>();
  594. if (desc == nullptr) {
  595. GELOGE(OUT_OF_MEMORY, "Failed to create shape data node, out of memory");
  596. return nullptr;
  597. }
  598. string node_name = "ascend_mbatch_shape_data";
  599. // Only flush subgraph name
  600. if (graph_->GetParentGraph() != nullptr) {
  601. node_name = graph_->GetName() + "_" + node_name;
  602. }
  603. desc->SetName(node_name);
  604. desc->SetType(DATA);
  605. // input and output of DATA is gear_info
  606. GeTensorDesc tensor_desc(GeShape({static_cast<int64_t>(shapes_.at(0).size())}), FORMAT_ND, DT_INT64);
  607. auto ret = desc->AddInputDesc(tensor_desc);
  608. if (ret != GRAPH_SUCCESS) {
  609. GELOGE(INTERNAL_ERROR, "Failed to add input desc for created data");
  610. return nullptr;
  611. }
  612. ret = desc->AddOutputDesc(tensor_desc);
  613. if (ret != GRAPH_SUCCESS) {
  614. GELOGE(INTERNAL_ERROR, "Failed to add output desc for created data");
  615. return nullptr;
  616. }
  617. if (!AttrUtils::SetBool(desc, ATTR_INSERT_BY_MBATCH, true)) {
  618. GELOGE(INTERNAL_ERROR, "Failed to add attr for created data");
  619. return nullptr;
  620. }
  621. auto data_node = graph_->AddNode(desc);
  622. if (data_node == nullptr) {
  623. GELOGE(INTERNAL_ERROR, "Failed to add shape data node to graph");
  624. return nullptr;
  625. }
  626. ret = GraphUtils::AppendInputNode(graph_, data_node);
  627. if (ret != GRAPH_SUCCESS) {
  628. GELOGE(INTERNAL_ERROR, "Failed to append data node %s as input to graph", data_node->GetName().c_str());
  629. return nullptr;
  630. }
  631. return data_node;
  632. }
  633. NodePtr MultiBatchGraphCopyer::InsertGetDynamicDimsNode() {
  634. GELOGD("Start insert getdynamicdims node to get shape info.");
  635. auto desc = MakeShared<OpDesc>();
  636. if (desc == nullptr) {
  637. GELOGE(OUT_OF_MEMORY, "Failed to create shape data node, out of memory");
  638. return nullptr;
  639. }
  640. string node_name = "ascend_mbatch_get_dynamic_dims_node";
  641. // Only flush subgraph name
  642. if (graph_->GetParentGraph() != nullptr) {
  643. node_name = graph_->GetName() + "_" + node_name;
  644. }
  645. desc->SetName(node_name);
  646. desc->SetType(GETDYNAMICDIMS);
  647. // input of GetDynamicDims is shape_of_each_data, output is gear_info
  648. for (size_t i = 0; i < GetLocalOmgContext().user_input_dims.size(); ++i) {
  649. size_t input_shape_dims = GetLocalOmgContext().user_input_dims.at(i).second.size();
  650. if (input_shape_dims == 1 && GetLocalOmgContext().user_input_dims.at(i).second.at(0) == 0) {
  651. GeTensorDesc tensor_desc;
  652. tensor_desc.SetFormat(FORMAT_ND);
  653. tensor_desc.SetDataType(DT_INT64);
  654. auto ret = desc->AddInputDesc(tensor_desc);
  655. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to add input desc for created data");
  656. return nullptr);
  657. continue;
  658. }
  659. GeTensorDesc tensor_desc(GeShape({static_cast<int64_t>(input_shape_dims)}), FORMAT_ND, DT_INT64);
  660. auto ret = desc->AddInputDesc(tensor_desc);
  661. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to add input desc for created data");
  662. return nullptr);
  663. }
  664. GeTensorDesc tensor_desc(GeShape({static_cast<int64_t>(shapes_.at(0).size())}), FORMAT_ND, DT_INT64);
  665. auto ret = desc->AddOutputDesc(tensor_desc);
  666. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to add output desc for created data");
  667. return nullptr);
  668. if (!AttrUtils::SetBool(desc, ATTR_INSERT_BY_MBATCH, true)) {
  669. GELOGE(INTERNAL_ERROR, "Failed to add attr for created data");
  670. return nullptr;
  671. }
  672. auto data_node = graph_->AddNode(desc);
  673. if (data_node == nullptr) {
  674. GELOGE(INTERNAL_ERROR, "Failed to add shape data node to graph");
  675. return nullptr;
  676. }
  677. ret = GraphUtils::AppendInputNode(graph_, data_node);
  678. if (ret != GRAPH_SUCCESS) {
  679. GELOGE(INTERNAL_ERROR, "Failed to append data node %s as input to graph", data_node->GetName().c_str());
  680. return nullptr;
  681. }
  682. return data_node;
  683. }
  684. Status MultiBatchGraphCopyer::CheckArguments() {
  685. if (graph_ == nullptr) {
  686. GELOGE(PARAM_INVALID, "Failed to copy graph, the graph is null");
  687. return PARAM_INVALID;
  688. }
  689. return CheckDynamicParams(shapes_);
  690. }
  691. Status MultiBatchGraphCopyer::CheckCopyResult(const std::vector<NodePtr> &start_nodes) {
  692. for (auto &node : start_nodes) {
  693. if (IsOnlyOutputToAipp(node)) {
  694. continue;
  695. }
  696. auto dims = NodeUtils::GetOutputDesc(*node, kDataOutIndex).GetShape().GetDims();
  697. if (!IsAllDimsPositive(dims)) {
  698. ErrorManager::GetInstance().ATCReportErrMessage("E15004", {"opname", "shape"},
  699. {node->GetName(), formats::ShapeToString(dims)});
  700. GELOGE(INTERNAL_ERROR, "Failed to copy multi batch graph, the node %s still has unknown shape %s",
  701. node->GetName().c_str(), formats::ShapeToString(dims).c_str());
  702. return INTERNAL_ERROR;
  703. }
  704. }
  705. return SUCCESS;
  706. }
  707. bool MultiBatchGraphCopyer::IsInBatchBranch(const NodePtr &node) {
  708. if (!getnext_sink_dynamic_dims_) {
  709. return (nodes_to_batch_nodes_.count(node.get()) > 0) || (data_nodes_to_switchn_.count(node.get()) > 0);
  710. } else {
  711. for (size_t i = 0; i < getnext_nodes_to_switchn_.size(); ++i) {
  712. for (size_t j = 0; j < getnext_nodes_to_switchn_.at(i).size(); ++j) {
  713. if (getnext_nodes_to_switchn_.at(i).at(j).first == node.get()) {
  714. return true;
  715. }
  716. }
  717. }
  718. return nodes_to_batch_nodes_.count(node.get()) > 0;
  719. }
  720. }
  721. Status MultiBatchGraphCopyer::LinkDataToMerge(const NodePtr &data, const NodePtr &merge, const NodePtr &switchn) {
  722. // The caller should make sure that the there is a SwitchN node in the map
  723. GELOGI("Link edge between data %s to merge %s throw switchn %s", data->GetName().c_str(), merge->GetName().c_str(),
  724. switchn->GetName().c_str());
  725. for (size_t i = 0; i < shapes_.size(); ++i) {
  726. auto ret = GraphUtils::AddEdge(switchn->GetOutDataAnchor(i), merge->GetInDataAnchor(i));
  727. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS,
  728. GELOGE(INTERNAL_ERROR, "Failed to add edge between switchn %s(%zu) to merge %s(%zu), error-code %u",
  729. switchn->GetName().c_str(), i, merge->GetName().c_str(), i, ret);
  730. return INTERNAL_ERROR);
  731. }
  732. return SUCCESS;
  733. }
  734. Status MultiBatchGraphCopyer::LinkNodeToMerge(const NodePtr &node, int out_index, const NodePtr &merge) {
  735. auto &copyed_nodes = nodes_to_batch_nodes_[node.get()];
  736. if (copyed_nodes.size() != shapes_.size()) {
  737. GELOGE(INTERNAL_ERROR,
  738. "Failed to create merge node for node %s, the copyed nodes for it count %zu different with shape %zu",
  739. node->GetName().c_str(), copyed_nodes.size(), shapes_.size());
  740. return INTERNAL_ERROR;
  741. }
  742. for (size_t i = 0; i < copyed_nodes.size(); ++i) {
  743. auto src_node = copyed_nodes[i];
  744. if (src_node->GetAllOutDataAnchorsSize() == 0) {
  745. // if the node does not has any data output, we should create an const for it, like this:
  746. // c d
  747. // node ---> const ---> merge
  748. auto const_name = src_node->GetName() + "_merge_const";
  749. GELOGI("The node %s on the batch branch edge does not have any data output, create a const %s for it",
  750. src_node->GetName().c_str(), const_name.c_str());
  751. auto const_node = InsertConst(const_name, graph_);
  752. GE_IF_BOOL_EXEC(const_node == nullptr,
  753. GELOGE(OUT_OF_MEMORY, "Failed to create const for node %s to connect to a merge node",
  754. src_node->GetName().c_str());
  755. return OUT_OF_MEMORY);
  756. auto ret = GraphUtils::AddEdge(src_node->GetOutControlAnchor(), const_node->GetInControlAnchor());
  757. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to add control edge from %s to %s",
  758. src_node->GetName().c_str(), const_node->GetName().c_str());
  759. return INTERNAL_ERROR);
  760. src_node = const_node;
  761. }
  762. auto ret = GraphUtils::AddEdge(src_node->GetOutDataAnchor(out_index), merge->GetInDataAnchor(i));
  763. if (ret != GRAPH_SUCCESS) {
  764. GELOGE(INTERNAL_ERROR,
  765. "Failed to add edge between copyed node %s(%d) to inserted merge node %s(%zu), error-code %u",
  766. copyed_nodes[i]->GetName().c_str(), out_index, merge->GetName().c_str(), i, ret);
  767. return INTERNAL_ERROR;
  768. }
  769. }
  770. return SUCCESS;
  771. }
  772. Status MultiBatchGraphCopyer::InsertSwitchNAndUpdateMaxShape(const NodePtr &node) {
  773. std::vector<std::pair<Node *, NodePtr>> dynamic_out_to_switchn;
  774. if (!getnext_sink_dynamic_dims_) {
  775. if (InsertSwitchNForData(node, kDataOutIndex, kDataOutIndex, dynamic_out_to_switchn) != SUCCESS) {
  776. GELOGE(PARAM_INVALID, "Failed to insert switchn for %s.", node->GetName().c_str());
  777. return PARAM_INVALID;
  778. }
  779. if (UpdateMaxShapeToData(node, kDataOutIndex) != SUCCESS) {
  780. GELOGE(PARAM_INVALID, "Failed to update max shape of %s.", node->GetName().c_str());
  781. return PARAM_INVALID;
  782. }
  783. } else {
  784. if (!IsGetNextType(node)) {
  785. GELOGI("No need to insert switchn and update max shape for %s when get sink dynamic.", node->GetName().c_str());
  786. return SUCCESS;
  787. }
  788. for (size_t i = 0; i < getnext_sink_dynamic_out_mapping_.size(); ++i) {
  789. dynamic_out_to_switchn.clear();
  790. for (size_t j = 0; j < getnext_sink_dynamic_out_mapping_.at(i).second; ++j) {
  791. GELOGI("The %zu data_index has %zu referenced nums.", getnext_sink_dynamic_out_mapping_.at(i).first,
  792. getnext_sink_dynamic_out_mapping_.at(i).second);
  793. if (InsertSwitchNForData(node, getnext_sink_dynamic_out_mapping_.at(i).first, j, dynamic_out_to_switchn) !=
  794. SUCCESS) {
  795. GELOGE(PARAM_INVALID, "Failed to insert switchn for %s of %zu out anchor when referenced index is %zu",
  796. node->GetName().c_str(), getnext_sink_dynamic_out_mapping_.at(i).first, j);
  797. return PARAM_INVALID;
  798. }
  799. }
  800. getnext_nodes_to_switchn_.emplace_back(dynamic_out_to_switchn);
  801. }
  802. for (size_t i = 0; i < getnext_sink_dynamic_out_mapping_.size(); ++i) {
  803. if(UpdateMaxShapeToData(node, i) != SUCCESS) {
  804. GELOGE(PARAM_INVALID, "Failed to update max shape of %zu out anchor", node->GetName().c_str(), i);
  805. return PARAM_INVALID;
  806. }
  807. }
  808. }
  809. return SUCCESS;
  810. }
  811. Status MultiBatchGraphCopyer::UpdateShapeOfShapeNode(const NodePtr &node, size_t out_anchor_index) {
  812. auto data_shape = NodeUtils::GetOutputDesc(*node, out_anchor_index).GetShape();
  813. size_t shape_index = out_anchor_index + (node->GetAllOutDataAnchors().size() / kDivisionConst);
  814. GeTensorDesc output_desc = node->GetOpDesc()->GetOutputDesc(shape_index);
  815. std::vector<int64_t> output_dims = {static_cast<int64_t>(data_shape.GetDims().size())};
  816. GeShape output_shape(output_dims);
  817. output_desc.SetShape(output_shape);
  818. if (node->GetOpDesc()->UpdateOutputDesc(shape_index, output_desc) != SUCCESS) {
  819. GELOGE(FAILED, "Update output desc fail.");
  820. return FAILED;
  821. }
  822. return SUCCESS;
  823. }
  824. Status MultiBatchGraphCopyer::UpdateMaxShapeToData(const NodePtr &node, size_t out_anchor_index) {
  825. GELOGD("Start update max shape of %s, %zu output.", node->GetName().c_str(), out_anchor_index);
  826. auto data_shape = NodeUtils::GetOutputDesc(*node, out_anchor_index).GetShape();
  827. string data_name = node->GetName();
  828. if (getnext_sink_dynamic_dims_) {
  829. data_name.append("_").append(std::to_string(out_anchor_index));
  830. }
  831. GELOGD("Update max shape of %s, shape dims is %s.", data_name.c_str(),
  832. formats::JoinToString(data_shape.GetDims()).c_str());
  833. if (!getnext_sink_dynamic_dims_) {
  834. if (IsAllDimsPositive(data_shape.GetDims())) {
  835. GELOGD("No need to do anything for static data.");
  836. return SUCCESS;
  837. }
  838. } else {
  839. if (IsAllDimsPositive(data_shape.GetDims())) {
  840. // need to update shape of Shape_node
  841. GE_CHK_STATUS_RET(UpdateShapeOfShapeNode(node, out_anchor_index), "Failed to update shape of shape node");
  842. return SUCCESS;
  843. }
  844. }
  845. size_t max_shape_index = 0;
  846. int64_t max_size = 0;
  847. for (size_t i = 0; i < shapes_.size(); ++i) {
  848. int64_t size = 1;
  849. for (auto dim : data_to_dynamic_info_.at(data_name).at(i)) {
  850. if (INT64_MAX / dim < size) {
  851. GELOGE(PARAM_INVALID, "The shape %s size overflow",
  852. formats::ShapeToString(data_to_dynamic_info_[data_name].at(i)).c_str());
  853. return PARAM_INVALID;
  854. }
  855. size *= dim;
  856. }
  857. if (size > max_size) {
  858. max_size = size;
  859. max_shape_index = i;
  860. }
  861. }
  862. // must not be error, the calc result has been checked in function InsertSwitchNForData
  863. (void)CalcShape(data_to_dynamic_info_.at(data_name).at(max_shape_index), data_shape);
  864. auto ret = NodeUtils::UpdateOutputShape(*node, out_anchor_index, data_shape);
  865. GE_CHK_STATUS_RET(ret, "Failed to update output shape for data %s", node->GetName().c_str());
  866. // getnext_sink not has input
  867. if (!getnext_sink_dynamic_dims_) {
  868. ret = NodeUtils::UpdateInputShape(*node, kDataInIndex, data_shape);
  869. GE_CHK_STATUS_RET(ret, "Failed to update input shape for data %s", node->GetName().c_str());
  870. } else {
  871. // need to update shape of Shape_node when getnext_sink_dynamic
  872. GE_CHK_STATUS_RET(UpdateShapeOfShapeNode(node, out_anchor_index), "Failed to update shape of shape node");
  873. }
  874. GELOGI("Update the data %s input/output shape to the max %s", node->GetName().c_str(),
  875. formats::ShapeToString(data_shape).c_str());
  876. return SUCCESS;
  877. }
  878. Status MultiBatchGraphCopyer::InsertSwitchNForData(const NodePtr &node, const size_t &out_anchor_index,
  879. const size_t &peer_in_anchor_index,
  880. std::vector<std::pair<Node *, NodePtr>> &dynamic_out_to_switchn) {
  881. auto data_shape = NodeUtils::GetOutputDesc(*node, out_anchor_index).GetShape();
  882. string data_name = node->GetName();
  883. if (getnext_sink_dynamic_dims_) {
  884. data_name.append("_").append(std::to_string(out_anchor_index));
  885. }
  886. (void)AttrUtils::SetListInt(node->GetOpDesc(), ATTR_MBATCH_ORIGIN_INPUT_DIMS, data_shape.GetDims());
  887. GELOGI("Insert switchn node of %s, shape dims is %s.", data_name.c_str(),
  888. formats::JoinToString(data_shape.GetDims()).c_str());
  889. if (IsAllDimsPositive(data_shape.GetDims())) {
  890. GELOGI("The shape of data %s are positive(%s), skip the multi batch process", node->GetName().c_str(),
  891. data_shape.ToString().c_str());
  892. return SUCCESS;
  893. }
  894. auto switchn_desc = MakeShared<OpDesc>();
  895. GE_IF_BOOL_EXEC(switchn_desc == nullptr,
  896. GELOGE(OUT_OF_MEMORY, "Failed to create switchn for data %s", node->GetName().c_str());
  897. return OUT_OF_MEMORY);
  898. string switchn_name = node->GetName() + "_ascend_mbatch_switchn";
  899. if (getnext_sink_dynamic_dims_) {
  900. switchn_name.append("_").append(std::to_string(out_anchor_index))
  901. .append("_").append(std::to_string(peer_in_anchor_index));
  902. }
  903. GELOGI("name of switchn is %s.", switchn_name.c_str());
  904. switchn_desc->SetName(switchn_name);
  905. switchn_desc->SetType(SWITCHN);
  906. GeTensorDesc tensor(NodeUtils::GetOutputDesc(*node, out_anchor_index));
  907. GE_IF_BOOL_EXEC(switchn_desc->AddInputDesc("data", tensor) != GRAPH_SUCCESS,
  908. GELOGE(OUT_OF_MEMORY, "Failed to add input tensor desc for %s", switchn_desc->GetName().c_str());
  909. return OUT_OF_MEMORY);
  910. GeTensorDesc pred_tensor;
  911. GE_IF_BOOL_EXEC(switchn_desc->AddInputDesc("pred_value", pred_tensor) != GRAPH_SUCCESS,
  912. GELOGE(OUT_OF_MEMORY, "Failed to add input pred tensor desc for %s", switchn_desc->GetName().c_str());
  913. return OUT_OF_MEMORY);
  914. std::vector<std::string> input_dims_str;
  915. for (size_t i = 0; i < shapes_.size(); ++i) {
  916. GELOGI("Start clac shape for data %s, batch shape is %s.", data_name.c_str(),
  917. formats::JoinToString(data_to_dynamic_info_.at(data_name).at(i)).c_str());
  918. auto shape = data_shape;
  919. auto ret = CalcShape(data_to_dynamic_info_.at(data_name).at(i), shape);
  920. if (ret != SUCCESS) {
  921. GELOGE(ret, "Failed to calculate the batched shape for data node %s, the shapes may not match",
  922. node->GetName().c_str());
  923. return ret;
  924. }
  925. tensor.SetShape(shape);
  926. string input_str;
  927. int64_t tensor_size = 0;
  928. (void)TensorUtils::GetTensorSizeInBytes(tensor, tensor_size);
  929. input_str = TypeUtils::FormatToSerialString(tensor.GetFormat()) + ":" +
  930. TypeUtils::DataTypeToSerialString(tensor.GetDataType()) + ":" + node->GetName() + ":" +
  931. std::to_string(tensor_size) + ":" + std::to_string(tensor.GetShape().GetDimNum()) + ":" +
  932. formats::JoinToString(tensor.GetShape().GetDims());
  933. input_dims_str.emplace_back(input_str);
  934. if (!AttrUtils::SetListInt(tensor, ATTR_NAME_SWITCHN_PRED_VALUE, shapes_.at(i))) {
  935. GELOGE(INTERNAL_ERROR, "Failed to add attr value on output %zu tensor", i);
  936. return INTERNAL_ERROR;
  937. }
  938. (void) AttrUtils::SetListInt(tensor, ATTR_NAME_COMBINED_DYNAMIC_DIMS, shape.GetDims());
  939. if (switchn_desc->AddOutputDesc("output" + std::to_string(i), tensor) != GRAPH_SUCCESS) {
  940. GELOGE(GRAPH_FAILED, "Opdesc AddOutputDesc failed");
  941. return GRAPH_FAILED;
  942. }
  943. GELOGD("The switchn %s output index %zu, shape %s", switchn_desc->GetName().c_str(), i, shape.ToString().c_str());
  944. }
  945. (void)AttrUtils::SetListStr(node->GetOpDesc(), "_all_origin_gears_inputs", input_dims_str);
  946. if (!AttrUtils::SetListStr(switchn_desc, ATTR_USER_DESIGNEATE_SHAPE_ORDER, data_name_order_)) {
  947. GELOGE(INTERNAL_ERROR, "Failed to add user designate shape order attr on switchn node %s",
  948. switchn_desc->GetName().c_str());
  949. return INTERNAL_ERROR;
  950. }
  951. if (!AttrUtils::SetBool(switchn_desc, ATTR_INSERT_BY_MBATCH, true)) {
  952. GELOGE(INTERNAL_ERROR, "Failed to add insert attr on switchn node %s", switchn_desc->GetName().c_str());
  953. return INTERNAL_ERROR;
  954. }
  955. if (!AttrUtils::SetStr(node->GetOpDesc(), kMbatchSwitchnName, switchn_desc->GetName())) {
  956. GELOGE(INTERNAL_ERROR, "Failed to add switchn attr on data node %s", node->GetName().c_str());
  957. return INTERNAL_ERROR;
  958. }
  959. if (StampDynamicType(switchn_desc) != SUCCESS) {
  960. GELOGE(INTERNAL_ERROR, "Failed to add dynamic type attr on switchn node %s", switchn_desc->GetName().c_str());
  961. return INTERNAL_ERROR;
  962. }
  963. auto switchn = graph_->AddNode(switchn_desc);
  964. GE_IF_BOOL_EXEC(switchn == nullptr,
  965. GELOGE(OUT_OF_MEMORY, "Failed to create switchn %s from desc", switchn_desc->GetName().c_str());
  966. return OUT_OF_MEMORY);
  967. if (!getnext_sink_dynamic_dims_) {
  968. data_nodes_to_switchn_[node.get()] = switchn;
  969. } else {
  970. dynamic_out_to_switchn.emplace_back(std::make_pair(node.get(), switchn));
  971. GELOGD("Insert %s for %s.", switchn->GetName().c_str(), node->GetName().c_str());
  972. }
  973. return SUCCESS;
  974. }
  975. Status MultiBatchGraphCopyer::InsertMergeForEdgeNode(const NodePtr &node) {
  976. for (auto &in_data_anchor : node->GetAllInDataAnchors()) {
  977. auto src_out_anchor = in_data_anchor->GetPeerOutAnchor();
  978. if (src_out_anchor == nullptr) {
  979. GELOGD("The node %s does not has input at index %d", node->GetName().c_str(), in_data_anchor->GetIdx());
  980. continue;
  981. }
  982. auto in_node = src_out_anchor->GetOwnerNode();
  983. if (!IsInBatchBranch(in_node)) {
  984. continue;
  985. }
  986. auto merge_node = InsertMergeNode(in_node, src_out_anchor->GetIdx());
  987. if (merge_node == nullptr) {
  988. return INTERNAL_ERROR;
  989. }
  990. }
  991. for (auto &in_node : node->GetInControlNodes()) {
  992. if (!IsInBatchBranch(in_node)) {
  993. continue;
  994. }
  995. auto merge_node = InsertMergeNode(in_node, -1);
  996. if (merge_node == nullptr) {
  997. return INTERNAL_ERROR;
  998. }
  999. }
  1000. return SUCCESS;
  1001. }
  1002. Status MultiBatchGraphCopyer::LinkGetDynamicDimsToNetOutput(const NodePtr &node) {
  1003. if (node->GetType() == NETOUTPUT) {
  1004. if (!GetLocalOmgContext().dynamic_node_type.empty()) {
  1005. if (!AttrUtils::SetStr(node->GetOpDesc(), ATTR_ALL_GEARS_INFO, GetLocalOmgContext().dynamic_dims)) {
  1006. GELOGE(INTERNAL_ERROR, "Failed to set all gears info attr on netoutput %s.", node->GetName().c_str());
  1007. return INTERNAL_ERROR;
  1008. }
  1009. }
  1010. if (getnext_sink_dynamic_dims_) {
  1011. size_t input_index = node->GetAllInDataAnchors().size();
  1012. if (NodeUtils::AppendInputAnchor(node, input_index + 1) != GRAPH_SUCCESS) {
  1013. GELOGE(INTERNAL_ERROR, "Append input anchor of %s of %zu failed.", node->GetName().c_str(), input_index);
  1014. return INTERNAL_ERROR;
  1015. }
  1016. auto ret =
  1017. ge::GraphUtils::AddEdge(shape_data_->GetOutDataAnchor(kDataOutIndex), node->GetInDataAnchor(input_index));
  1018. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to link netoutput %s to getdynamicdims %s",
  1019. node->GetName().c_str(), shape_data_->GetName().c_str());
  1020. return INTERNAL_ERROR);
  1021. if (!AttrUtils::SetBool(node->GetOpDesc(), ATTR_GETNEXT_SINK_DYNMAIC, true)) {
  1022. GELOGE(INTERNAL_ERROR, "Failed to set getnext sink dynamic attr on netoutput %s.", node->GetName().c_str());
  1023. return INTERNAL_ERROR;
  1024. }
  1025. }
  1026. }
  1027. return SUCCESS;
  1028. }
  1029. Status MultiBatchGraphCopyer::CopyNodeInBatchBranch(const NodePtr &node) {
  1030. auto &copyed_nodes = nodes_to_batch_nodes_[node.get()];
  1031. for (size_t i = 0; i < shapes_.size(); ++i) {
  1032. auto copyed_node = InsertCopyNode(node, i);
  1033. if (copyed_node == nullptr) {
  1034. GELOGE(INTERNAL_ERROR, "Failed to add node to graph when copy node %s", node->GetName().c_str());
  1035. return INTERNAL_ERROR;
  1036. }
  1037. copyed_nodes.emplace_back(copyed_node);
  1038. GELOGI("Copy node %s type %s for shape %s, new node name %s", node->GetName().c_str(), node->GetType().c_str(),
  1039. formats::JoinToString(shapes_.at(i)).c_str(), copyed_node->GetName().c_str());
  1040. }
  1041. return SUCCESS;
  1042. }
  1043. Status MultiBatchGraphCopyer::AddAttrForGetDynamicDims(const NodePtr &node) {
  1044. GELOGD("Add attr for :%s, type is %s:", shape_data_->GetName().c_str(), shape_data_->GetType().c_str());
  1045. size_t data_count = node->GetAllOutDataAnchors().size() / kDivisionConst;
  1046. if (!AttrUtils::SetInt(shape_data_->GetOpDesc(), ATTR_GETNEXT_SINK_DATA_COUNT, data_count)) {
  1047. GELOGE(INTERNAL_ERROR, "set ATTR_GETNEXT_SINK_DATA_COUNT failed");
  1048. return INTERNAL_ERROR;
  1049. }
  1050. vector<int64_t> shape_info;
  1051. for (size_t i = 0; i < GetLocalOmgContext().user_input_dims.size(); ++i) {
  1052. if (GetLocalOmgContext().user_input_dims.at(i).second.size() == 1 &&
  1053. GetLocalOmgContext().user_input_dims.at(i).second.at(0) == 0) {
  1054. shape_info.emplace_back(0);
  1055. continue;
  1056. }
  1057. shape_info.emplace_back(GetLocalOmgContext().user_input_dims.at(i).second.size());
  1058. for (size_t j = 0; j < GetLocalOmgContext().user_input_dims.at(i).second.size(); ++j) {
  1059. shape_info.emplace_back(GetLocalOmgContext().user_input_dims.at(i).second.at(j));
  1060. }
  1061. }
  1062. if (!AttrUtils::SetListInt(shape_data_->GetOpDesc(), ATTR_GETNEXT_SINK_SHAPE_INFO, shape_info)) {
  1063. GELOGE(INTERNAL_ERROR, "set ATTR_GETNEXT_SINK_SHAPE_INFO failed");
  1064. return INTERNAL_ERROR;
  1065. }
  1066. return SUCCESS;
  1067. }
  1068. Status MultiBatchGraphCopyer::AddLinkForGetDynamicDims(const NodePtr &node) {
  1069. GELOGD("Start relink out anchor from shape node to getdynamicdims, and delete link between shape node and identity.");
  1070. size_t input_index = 0;
  1071. GELOGD("Out count of %s is %zu.", node->GetName().c_str(), node->GetAllOutDataAnchors().size());
  1072. size_t data_count = node->GetAllOutDataAnchors().size() / kDivisionConst;
  1073. for (size_t out_index = data_count; out_index < node->GetAllOutDataAnchors().size(); ++out_index, ++input_index) {
  1074. GELOGI("Start add %s of %zu out_anchor to %s of %zu in_anchor.", node->GetName().c_str(), out_index,
  1075. shape_data_->GetName().c_str(), input_index);
  1076. auto out_data_anchor = node->GetOutDataAnchor(out_index);
  1077. auto ret = GraphUtils::AddEdge(out_data_anchor, shape_data_->GetInDataAnchor(input_index));
  1078. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to link getnext %s to getdynamicdims %s",
  1079. node->GetName().c_str(), shape_data_->GetName().c_str());
  1080. return INTERNAL_ERROR);
  1081. }
  1082. return SUCCESS;
  1083. }
  1084. Status MultiBatchGraphCopyer::LinkEdges() {
  1085. Status ret;
  1086. for (const auto &node : origin_all_nodes_) {
  1087. GE_CHECK_NOTNULL(node->GetOpDesc());
  1088. if (!getnext_sink_dynamic_dims_) {
  1089. if (data_nodes_to_switchn_.count(node.get()) > 0) {
  1090. auto switchn = data_nodes_to_switchn_[node.get()];
  1091. GE_IF_BOOL_EXEC(switchn == nullptr,
  1092. GELOGE(PARAM_INVALID, "Switchn should not be nullptr for %s.", node->GetName().c_str());
  1093. return OUT_OF_MEMORY);
  1094. ret = LinkDataToSwitchN(node, switchn, kDataOutIndex);
  1095. GE_CHK_STATUS_RET(ret, "Link data to switchn failed.");
  1096. }
  1097. } else {
  1098. if (IsGetNextType(node)) {
  1099. GELOGD("Start add attr and link edge for %s.", node->GetName().c_str());
  1100. GE_CHK_STATUS_RET(AddAttrForGetDynamicDims(node), "Failed to add attr for %s.", node->GetName().c_str());
  1101. GE_CHK_STATUS_RET(AddLinkForGetDynamicDims(node), "Failed to add link for %s.", node->GetName().c_str());
  1102. }
  1103. for (size_t i = 0; i < getnext_nodes_to_switchn_.size(); ++i) {
  1104. for (size_t j = 0; j < getnext_nodes_to_switchn_.at(i).size(); ++j) {
  1105. if (getnext_nodes_to_switchn_.at(i).at(j).first == node.get()) {
  1106. auto switchn = getnext_nodes_to_switchn_.at(i).at(j).second;
  1107. GE_CHK_STATUS_RET(LinkDataToSwitchN(node, switchn, i), "Link %s to %s failed.", node->GetName().c_str(),
  1108. switchn->GetName().c_str());
  1109. }
  1110. }
  1111. }
  1112. }
  1113. if (nodes_to_merge_nodes_.count(node.get()) > 0) {
  1114. GE_CHK_STATUS_RET(LinkToMerge(node), "Link %s to merge failed.", node->GetName().c_str());
  1115. }
  1116. if (nodes_to_batch_nodes_.count(node.get()) > 0) {
  1117. ret = LinkToNodeInBranch(node);
  1118. } else {
  1119. ret = LinkToNodeOutBranch(node);
  1120. }
  1121. if (ret != SUCCESS) {
  1122. return ret;
  1123. }
  1124. }
  1125. return SUCCESS;
  1126. }
  1127. Status MultiBatchGraphCopyer::LinkDataToSwitchN(const NodePtr &data, const NodePtr &switchn, const int &out_index) {
  1128. auto ret =
  1129. GraphUtils::AddEdge(shape_data_->GetOutDataAnchor(kDataOutIndex), switchn->GetInDataAnchor(kSwitchNPredIndex));
  1130. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to link shape data %s to switchn %s",
  1131. shape_data_->GetName().c_str(), switchn->GetName().c_str());
  1132. return INTERNAL_ERROR);
  1133. ret = GraphUtils::AddEdge(data->GetOutDataAnchor(out_index), switchn->GetInDataAnchor(kSwitchNDataIndex));
  1134. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to link data %s to switchn %s",
  1135. data->GetName().c_str(), switchn->GetName().c_str());
  1136. return INTERNAL_ERROR);
  1137. return SUCCESS;
  1138. }
  1139. Status MultiBatchGraphCopyer::LinkToMerge(const NodePtr &node) {
  1140. auto &merge_nodes = nodes_to_merge_nodes_[node.get()];
  1141. for (size_t i = 0; i < merge_nodes.size(); ++i) {
  1142. auto merge_node = merge_nodes[i];
  1143. if (merge_node == nullptr) {
  1144. continue;
  1145. }
  1146. if (nodes_to_batch_nodes_.count(node.get()) > 0) {
  1147. auto ret = LinkNodeToMerge(node, i, merge_node);
  1148. if (ret != SUCCESS) {
  1149. return ret;
  1150. }
  1151. continue;
  1152. }
  1153. if (!getnext_sink_dynamic_dims_) {
  1154. if (data_nodes_to_switchn_.count(node.get()) > 0) {
  1155. auto &switchn = data_nodes_to_switchn_[node.get()];
  1156. auto ret = LinkDataToMerge(node, merge_node, switchn);
  1157. if (ret != SUCCESS) {
  1158. return ret;
  1159. }
  1160. continue;
  1161. }
  1162. } else {
  1163. for (size_t j = 0; j < getnext_nodes_to_switchn_.size(); ++j) {
  1164. for (size_t k = 0; k < getnext_nodes_to_switchn_.at(j).size(); ++k) {
  1165. if (getnext_nodes_to_switchn_.at(j).at(k).first == node.get()) {
  1166. auto &switchn = getnext_nodes_to_switchn_.at(j).at(k).second;
  1167. auto ret = LinkDataToMerge(node, merge_node, switchn);
  1168. if (ret != SUCCESS) {
  1169. return ret;
  1170. }
  1171. }
  1172. }
  1173. }
  1174. continue;
  1175. }
  1176. GELOGE(INTERNAL_ERROR, "The merge node %s is created, index %zu, but can not find the src node",
  1177. merge_node->GetName().c_str(), i);
  1178. return INTERNAL_ERROR;
  1179. }
  1180. return SUCCESS;
  1181. }
  1182. Status MultiBatchGraphCopyer::LinkToNodeInBranch(const NodePtr &node) {
  1183. GELOGI("Start LinkToNodeInBranch for %s.", node->GetName().c_str());
  1184. auto &branch_nodes = nodes_to_batch_nodes_[node.get()];
  1185. for (size_t i = 0; i < branch_nodes.size(); ++i) {
  1186. auto ret = CopyInDataEdges(node, i, branch_nodes[i]);
  1187. if (ret != SUCCESS) {
  1188. return ret;
  1189. }
  1190. ret = CopyInControlEdges(node, i, branch_nodes[i]);
  1191. if (ret != SUCCESS) {
  1192. return ret;
  1193. }
  1194. }
  1195. return SUCCESS;
  1196. }
  1197. Status MultiBatchGraphCopyer::LinkToNodeOutBranch(const NodePtr &node) {
  1198. for (auto &in_data_anchor : node->GetAllInDataAnchors()) {
  1199. auto src_out_anchor = in_data_anchor->GetPeerOutAnchor();
  1200. if (src_out_anchor == nullptr) {
  1201. GELOGD("The node %s does not has input at index %d", node->GetName().c_str(), in_data_anchor->GetIdx());
  1202. continue;
  1203. }
  1204. auto in_node = src_out_anchor->GetOwnerNode();
  1205. if (!IsInBatchBranch(in_node)) {
  1206. continue;
  1207. }
  1208. auto iter = nodes_to_merge_nodes_.find(in_node.get());
  1209. if (iter == nodes_to_merge_nodes_.end()) {
  1210. GELOGE(INTERNAL_ERROR, "Failed to link IO data edge from %s(%d) to %s(%d), no merge node found",
  1211. in_node->GetName().c_str(), src_out_anchor->GetIdx(), node->GetName().c_str(), in_data_anchor->GetIdx());
  1212. return INTERNAL_ERROR;
  1213. }
  1214. auto merge_node = iter->second[src_out_anchor->GetIdx()];
  1215. if (merge_node == nullptr) {
  1216. GELOGE(INTERNAL_ERROR, "Failed to link IO data edge from %s(%d) to %s(%d), no merge node found",
  1217. in_node->GetName().c_str(), src_out_anchor->GetIdx(), node->GetName().c_str(), in_data_anchor->GetIdx());
  1218. return INTERNAL_ERROR;
  1219. }
  1220. auto ret = src_out_anchor->Unlink(in_data_anchor);
  1221. if (ret != GRAPH_SUCCESS) {
  1222. GELOGE(INTERNAL_ERROR, "Failed to unlink the control edge from %s(%d) to %s(%d)", in_node->GetName().c_str(),
  1223. src_out_anchor->GetIdx(), node->GetName().c_str(), in_data_anchor->GetIdx());
  1224. return INTERNAL_ERROR;
  1225. }
  1226. ret = GraphUtils::AddEdge(merge_node->GetOutDataAnchor(kMergeDataOutIndex), in_data_anchor);
  1227. if (ret != GRAPH_SUCCESS) {
  1228. GELOGE(INTERNAL_ERROR, "Failed to add data edge from %s(%d) to %s(%d)", merge_node->GetName().c_str(),
  1229. src_out_anchor->GetIdx(), node->GetName().c_str(), in_data_anchor->GetIdx());
  1230. return INTERNAL_ERROR;
  1231. }
  1232. GELOGI("Link data edge from merge %s(from %s(%d)) to %s(%d)", merge_node->GetName().c_str(),
  1233. in_node->GetName().c_str(), src_out_anchor->GetIdx(), node->GetName().c_str(), in_data_anchor->GetIdx());
  1234. }
  1235. for (auto &in_node : node->GetInControlNodes()) {
  1236. if (!IsInBatchBranch(in_node)) {
  1237. continue;
  1238. }
  1239. auto iter = nodes_to_merge_nodes_.find(in_node.get());
  1240. if (iter == nodes_to_merge_nodes_.end()) {
  1241. GELOGE(INTERNAL_ERROR, "Failed to link IO control edge from %s to %s, no merge node found",
  1242. in_node->GetName().c_str(), node->GetName().c_str());
  1243. return INTERNAL_ERROR;
  1244. }
  1245. auto merge_node = iter->second[0];
  1246. if (merge_node == nullptr) {
  1247. GELOGE(INTERNAL_ERROR, "Failed to link IO control edge from %s to %s, no merge node found",
  1248. in_node->GetName().c_str(), node->GetName().c_str());
  1249. return INTERNAL_ERROR;
  1250. }
  1251. GE_IF_BOOL_EXEC(in_node->GetOutControlAnchor() == nullptr,
  1252. GELOGE(INTERNAL_ERROR, "Innode outputControlAnchor is null");
  1253. return INTERNAL_ERROR);
  1254. auto ret = in_node->GetOutControlAnchor()->Unlink(node->GetInControlAnchor());
  1255. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to unlink the control edge from %s to %s",
  1256. in_node->GetName().c_str(), node->GetName().c_str());
  1257. return INTERNAL_ERROR);
  1258. ret = GraphUtils::AddEdge(merge_node->GetOutControlAnchor(), node->GetInControlAnchor());
  1259. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to add control edge from %s to %s",
  1260. merge_node->GetName().c_str(), node->GetName().c_str());
  1261. return INTERNAL_ERROR);
  1262. GELOGI("Link control edge from merge %s(from %s) to %s", merge_node->GetName().c_str(), in_node->GetName().c_str(),
  1263. node->GetName().c_str());
  1264. }
  1265. return SUCCESS;
  1266. }
  1267. Status MultiBatchGraphCopyer::InsertIdentityAfterSwitchN() {
  1268. for (auto &node : graph_->GetAllNodes()) {
  1269. if (node->GetType() != SWITCHN) {
  1270. continue;
  1271. }
  1272. auto switchn_desc = node->GetOpDesc();
  1273. GE_CHECK_NOTNULL(switchn_desc);
  1274. size_t i = 0;
  1275. for (auto &out_data_anchor : node->GetAllOutDataAnchors()) {
  1276. for (auto &in_data_anchor : out_data_anchor->GetPeerInDataAnchors()) {
  1277. auto out_node = in_data_anchor->GetOwnerNode();
  1278. auto op_desc = out_node->GetOpDesc();
  1279. GE_CHECK_NOTNULL(op_desc);
  1280. if ((out_node->GetType() == MERGE) && (op_desc->HasAttr(ATTR_INSERT_BY_MBATCH))) {
  1281. GELOGD("No need to insert identity between %s and %s.", node->GetName().c_str(), out_node->GetName().c_str());
  1282. continue;
  1283. }
  1284. auto identity_desc = MakeShared<OpDesc>(node->GetName() + "_identity_" + std::to_string(i), IDENTITY);
  1285. GE_CHECK_NOTNULL(identity_desc);
  1286. string batch_label;
  1287. if (AttrUtils::GetStr(op_desc, ATTR_NAME_BATCH_LABEL, batch_label)) {
  1288. if (!AttrUtils::SetStr(identity_desc, ATTR_NAME_BATCH_LABEL, batch_label)) {
  1289. GELOGE(FAILED, "Set attr ATTR_NAME_BATCH_LABEL failed, node:%s.", identity_desc->GetName().c_str());
  1290. return FAILED;
  1291. }
  1292. }
  1293. auto data_desc = switchn_desc->GetOutputDesc(i);
  1294. i++;
  1295. GE_CHK_STATUS_RET(identity_desc->AddInputDesc("x", data_desc));
  1296. GE_CHK_STATUS_RET(identity_desc->AddOutputDesc("y", data_desc));
  1297. auto identity_node = graph_->AddNode(identity_desc);
  1298. GE_CHECK_NOTNULL(identity_node);
  1299. GE_CHK_STATUS_RET(out_data_anchor->LinkTo(identity_node->GetInDataAnchor(0)));
  1300. GE_CHECK_NOTNULL(identity_node->GetOutControlAnchor());
  1301. GE_CHK_STATUS_RET(identity_node->GetOutControlAnchor()->LinkTo(out_node->GetInControlAnchor()));
  1302. }
  1303. }
  1304. }
  1305. return SUCCESS;
  1306. }
  1307. Status ProcessMultiBatch(ComputeGraphPtr &graph) {
  1308. const char *multi_batch_with_case = std::getenv("MULTI_BATCH_WITH_CASE");
  1309. if (multi_batch_with_case != nullptr) {
  1310. PassManager pass_manager;
  1311. GE_CHK_STATUS_RET(pass_manager.AddPass("MultiBatchClonePass", new (std::nothrow) MultiBatchClonePass));
  1312. return pass_manager.Run(graph);
  1313. }
  1314. if (!GetLocalOmgContext().need_multi_batch) {
  1315. GELOGI("No need to process_multi for no_train graph.");
  1316. return SUCCESS;
  1317. }
  1318. std::vector<NodePtr> data_nodes;
  1319. std::vector<NodePtr> getnext_nosink_nodes;
  1320. std::vector<NodePtr> getnext_sink_nodes;
  1321. if (CheckSequenceOfOptions(graph, data_nodes, getnext_nosink_nodes, getnext_sink_nodes) != SUCCESS) {
  1322. GELOGE(PARAM_INVALID, "[Train_Dynamic] CheckSequenceOfOptions failed.");
  1323. return PARAM_INVALID;
  1324. }
  1325. if (UpdateNameOfInputShape(graph, data_nodes, getnext_nosink_nodes, getnext_sink_nodes) != SUCCESS) {
  1326. GELOGE(PARAM_INVALID, "[Train_Dynamic] UpdateNameForInputShapeOfOption failed.");
  1327. return PARAM_INVALID;
  1328. }
  1329. if (DeleteIdentityInsertByAdapter(graph) != SUCCESS) {
  1330. GELOGE(PARAM_INVALID, "DeleteIdentityInsertByAdapter failed.");
  1331. return PARAM_INVALID;
  1332. }
  1333. std::vector<std::vector<int64_t>> shapes;
  1334. if (!InitDynamicParams(shapes)) {
  1335. GELOGD("There is no multi-batch options, no need to process multi-batch copy");
  1336. return SUCCESS;
  1337. }
  1338. if (CheckNegativeCountOfOptions(shapes) != SUCCESS) {
  1339. GELOGE(PARAM_INVALID, "Input_shape and dynamic_dims should set correct params.");
  1340. return PARAM_INVALID;
  1341. }
  1342. DynamicType dynamic_type = DynamicType::kDynamicUnknown;
  1343. if (!GetLocalOmgContext().dynamic_batch_size.empty()) {
  1344. dynamic_type = DynamicType::kDynamicBatch;
  1345. } else if (!GetLocalOmgContext().dynamic_image_size.empty()) {
  1346. dynamic_type = DynamicType::kDynamicImageSize;
  1347. } else if (!GetLocalOmgContext().dynamic_dims.empty()) {
  1348. dynamic_type = DynamicType::kDynamicDims;
  1349. }
  1350. std::vector<std::pair<std::string, std::vector<int64_t>>> user_designate_shape;
  1351. user_designate_shape = GetLocalOmgContext().user_input_dims;
  1352. GELOGI("Begin to copy graph for multi-batch");
  1353. multibatch::MultiBatchGraphCopyer copyer(graph);
  1354. for (auto &shape : shapes) {
  1355. copyer.AddShape(shape);
  1356. }
  1357. copyer.SetDynamicType(dynamic_type);
  1358. copyer.SetUserDesignateShape(user_designate_shape);
  1359. return copyer.CopyGraph();
  1360. }
  1361. // +-----------+
  1362. // | Data | +-----------+ +-----------+ +-----------+
  1363. // +-----------+ | Data | ----> | SoftmaxV2 | ----> | NetOutput |
  1364. // \ /. +-----------+ +-----------+ +-----------+
  1365. // \ /.
  1366. // +-----------+ +-----------+ /. +-----------+ +-----------+ +-----------+
  1367. // | Data | ----> | Case | S--- | Data | ----> | SoftmaxV2 | ----> | NetOutput |
  1368. // +-----------+ +-----------+ \. +-----------+ +-----------+ +-----------+
  1369. // \ \.
  1370. // \ \. +-----------+ +-----------+ +-----------+
  1371. // +-----------+ | Data | ----> | SoftmaxV2 | ----> | NetOutput |
  1372. // | NetOutput | +-----------+ +-----------+ +-----------+
  1373. // +-----------+
  1374. // +-----------+ /
  1375. // | Data | --------------->/
  1376. // +-----------+
  1377. void GetDynamicShapeByGraph(const ComputeGraphPtr &graph, const NodePtr &node,
  1378. set<size_t> &dynamic_output_index, vector<string> &dynamic_output_dims) {
  1379. GELOGD("Try get dynamic shape info, Graph: %s, Node: %s", graph->GetName().c_str(), node->GetName().c_str());
  1380. const auto &func_desc = node->GetOpDesc();
  1381. if (!func_desc->HasAttr(ATTR_NAME_BATCH_NUM)) {
  1382. GELOGD("Graph: %s Not multi-batch, Node: %s", graph->GetName().c_str(), node->GetName().c_str());
  1383. return;
  1384. }
  1385. const auto &dynamic_branch_names = func_desc->GetSubgraphInstanceNames();
  1386. for (size_t i = 0; i < func_desc->GetOutputsSize(); ++i) {
  1387. for (size_t j = 0; j < dynamic_branch_names.size(); ++j) {
  1388. const auto &subgraph = graph->GetSubgraph(dynamic_branch_names[j]);
  1389. if (subgraph == nullptr) {
  1390. GELOGE(GE_GRAPH_EMPTY_SUBGRAPH, "Subgraph not found, name: %s", dynamic_branch_names[j].c_str());
  1391. dynamic_output_dims.clear();
  1392. return;
  1393. }
  1394. const auto &out_node = subgraph->FindFirstNodeMatchType(NETOUTPUT);
  1395. if (out_node == nullptr) {
  1396. GELOGE(GE_GRAPH_GRAPH_NODE_NULL, "NetOutput not found, name: %s", dynamic_branch_names[j].c_str());
  1397. dynamic_output_dims.clear();
  1398. return;
  1399. }
  1400. GELOGI("Find the subgraph Output node %s and the index is %zu", out_node->GetName().c_str(), i);
  1401. const auto &out_desc = out_node->GetOpDesc();
  1402. if (out_desc == nullptr || out_desc->GetInputsSize() <= i) {
  1403. GELOGE(GE_GRAPH_GRAPH_NODE_NULL, "Get Input desc failed, name: %s, index: %zu", out_node->GetName().c_str(), i);
  1404. dynamic_output_dims.clear();
  1405. return;
  1406. }
  1407. const auto &input_tensor = out_desc->GetInputDesc(i);
  1408. const auto &shape_msg = input_tensor.GetShape().ToString();
  1409. string output_shape = std::to_string(j) + "," + std::to_string(i) + "," + shape_msg;
  1410. GELOGI("The shape msg in dynamic batch is %s", output_shape.c_str());
  1411. dynamic_output_dims.emplace_back(output_shape);
  1412. uint32_t parent_index = 0;
  1413. (void)AttrUtils::GetInt(input_tensor, ATTR_NAME_PARENT_NODE_INDEX, parent_index);
  1414. dynamic_output_index.insert(parent_index);
  1415. }
  1416. }
  1417. }
  1418. // +-----------+ +-----------+ i = 0
  1419. // +----> | SoftmaxV2 | ----> |MemcpyAsync| ----> \.
  1420. // / +-----------+ +-----------+ \.
  1421. // / \.
  1422. // +-----------+ +-----------+ +-----------+ +-----------+ i = 1 +-----------+
  1423. // | Data | ----> | SwitchN | ----> | SoftmaxV2 | ----> |MemcpyAsync| ----> | Merge |
  1424. // +-----------+ +-----------+ +-----------+ +-----------+ +-----------+
  1425. // \ / \. j = 0
  1426. // \ +-----------+ +-----------+ i = 2 / \.
  1427. // +----> | SoftmaxV2 | ----> |MemcpyAsync| ----> / +-----------+
  1428. // +-----------+ +-----------+ | NetOutput |
  1429. // +-----------+
  1430. // +-----------+ /.
  1431. // | Data | --------------------------------------------------------------------------->/. j = 1
  1432. // +-----------+
  1433. void GetDynamicShapeByMerge(const ComputeGraphPtr &graph, const NodePtr &node,
  1434. set<size_t> &dynamic_output_index, vector<string> &dynamic_output_dims) {
  1435. GELOGD("Try get dynamic shape info, Graph: %s, Node: %s", graph->GetName().c_str(), node->GetName().c_str());
  1436. const auto &netoutput_desc = node->GetOpDesc();
  1437. const auto &inputnode_to_netoutput = node->GetInAllNodes();
  1438. GELOGI("Train_Dynamic Find the merge node size is %zu.", inputnode_to_netoutput.size());
  1439. for (size_t i = 0; i < inputnode_to_netoutput.size(); ++i) {
  1440. bool insert_by_mbatch = false;
  1441. (void)AttrUtils::GetBool(inputnode_to_netoutput.at(i)->GetOpDesc(), ATTR_INSERT_BY_MBATCH, insert_by_mbatch);
  1442. GELOGI("Train_Dynamic type is %s", inputnode_to_netoutput.at(i)->GetType().c_str());
  1443. if (inputnode_to_netoutput.at(i)->GetType() == MERGE && insert_by_mbatch) {
  1444. GELOGI("Find the merge node %s with mbatch attr and the index is %zu",
  1445. inputnode_to_netoutput.at(i)->GetName().c_str(), i);
  1446. dynamic_output_index.insert(i);
  1447. for (size_t j = 0; j < inputnode_to_netoutput.at(i)->GetInNodes().size(); ++j) {
  1448. auto input_desc = inputnode_to_netoutput.at(i)->GetOpDesc();
  1449. auto input_tensor_desc = input_desc->GetInputDesc(j);
  1450. auto shape_msg = input_tensor_desc.GetShape().ToString();
  1451. string output_shape = std::to_string(j) + "," + std::to_string(i) + "," + shape_msg;
  1452. GELOGI("The shape msg in dynamic batch is %s", output_shape.c_str());
  1453. dynamic_output_dims.emplace_back(output_shape);
  1454. }
  1455. }
  1456. }
  1457. }
  1458. // Connect NetOutput directly
  1459. void GetDirectOutputShape(const ComputeGraphPtr &graph, const NodePtr &node,
  1460. const set<size_t> &dynamic_output_index, vector<string> &dynamic_output_dims) {
  1461. if (!GetLocalOmgContext().dynamic_node_type.empty()) {
  1462. GELOGD("No need to get directly shape info of %s when train.", node->GetName().c_str());
  1463. return;
  1464. }
  1465. GELOGD("Try get directly shape info, Graph: %s, Node: %s", graph->GetName().c_str(), node->GetName().c_str());
  1466. const auto &netoutput_desc = node->GetOpDesc();
  1467. const auto &inputnode_to_netoutput = node->GetInAllNodes();
  1468. for (size_t i = 0; i < inputnode_to_netoutput.size(); ++i) {
  1469. if (dynamic_output_index.count(i) > 0) {
  1470. continue;
  1471. }
  1472. auto tensor_desc = netoutput_desc->GetInputDesc(i);
  1473. auto shape = tensor_desc.GetShape().ToString();
  1474. string static_output_shape = std::to_string(kStaticOutput) + "," + std::to_string(i) + "," + shape;
  1475. GELOGI("The static output shape msg is %s", static_output_shape.c_str());
  1476. dynamic_output_dims.emplace_back(static_output_shape);
  1477. }
  1478. }
  1479. Status GetDynamicOutputShape(ComputeGraphPtr &graph) {
  1480. GE_CHECK_NOTNULL(graph);
  1481. GELOGI("Start to get output dynamic batch shape message");
  1482. NodePtr net_output;
  1483. set<size_t> dynamic_output_index;
  1484. vector<string> dynamic_output_dims;
  1485. for (auto &node : graph->GetDirectNode()) {
  1486. if (node->GetType() == NETOUTPUT) {
  1487. net_output = node;
  1488. GetDynamicShapeByMerge(graph, node, dynamic_output_index, dynamic_output_dims);
  1489. } else if (node->GetType() == CASE) {
  1490. GetDynamicShapeByGraph(graph, node, dynamic_output_index, dynamic_output_dims);
  1491. }
  1492. }
  1493. if ((net_output != nullptr) && !dynamic_output_dims.empty()) {
  1494. GetDirectOutputShape(graph, net_output, dynamic_output_index, dynamic_output_dims);
  1495. if (!AttrUtils::SetListStr(net_output->GetOpDesc(), ATTR_NAME_DYNAMIC_OUTPUT_DIMS, dynamic_output_dims)) {
  1496. GELOGE(FAILED, "Set dynamic output dims attr failed");
  1497. return FAILED;
  1498. }
  1499. }
  1500. return SUCCESS;
  1501. }
  1502. } // namespace multibatch
  1503. } // namespace ge

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