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

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