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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619
  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, formats::JoinToString(data_shape.GetDims()).c_str());
  832. if (!getnext_sink_dynamic_dims_) {
  833. if (IsAllDimsPositive(data_shape.GetDims())) {
  834. GELOGD("No need to do anything for static data.");
  835. return SUCCESS;
  836. }
  837. } else {
  838. if (IsAllDimsPositive(data_shape.GetDims())) {
  839. // need to update shape of Shape_node
  840. GE_CHK_STATUS_RET(UpdateShapeOfShapeNode(node, out_anchor_index), "Failed to update shape of shape node");
  841. return SUCCESS;
  842. }
  843. }
  844. size_t max_shape_index = 0;
  845. int64_t max_size = 0;
  846. for (size_t i = 0; i < shapes_.size(); ++i) {
  847. int64_t size = 1;
  848. for (auto dim : data_to_dynamic_info_.at(data_name).at(i)) {
  849. if (INT64_MAX / dim < size) {
  850. GELOGE(PARAM_INVALID, "The shape %s size overflow",
  851. formats::ShapeToString(data_to_dynamic_info_[data_name].at(i)).c_str());
  852. return PARAM_INVALID;
  853. }
  854. size *= dim;
  855. }
  856. if (size > max_size) {
  857. max_size = size;
  858. max_shape_index = i;
  859. }
  860. }
  861. // must not be error, the calc result has been checked in function InsertSwitchNForData
  862. (void)CalcShape(data_to_dynamic_info_.at(data_name).at(max_shape_index), data_shape);
  863. auto ret = NodeUtils::UpdateOutputShape(*node, out_anchor_index, data_shape);
  864. GE_CHK_STATUS_RET(ret, "Failed to update output shape for data %s", node->GetName().c_str());
  865. // getnext_sink not has input
  866. if (!getnext_sink_dynamic_dims_) {
  867. ret = NodeUtils::UpdateInputShape(*node, kDataInIndex, data_shape);
  868. GE_CHK_STATUS_RET(ret, "Failed to update input shape for data %s", node->GetName().c_str());
  869. } else {
  870. // need to update shape of Shape_node when getnext_sink_dynamic
  871. GE_CHK_STATUS_RET(UpdateShapeOfShapeNode(node, out_anchor_index), "Failed to update shape of shape node");
  872. }
  873. GELOGI("Update the data %s input/output shape to the max %s", node->GetName().c_str(),
  874. formats::ShapeToString(data_shape).c_str());
  875. return SUCCESS;
  876. }
  877. Status MultiBatchGraphCopyer::InsertSwitchNForData(const NodePtr &node, const size_t &out_anchor_index,
  878. const size_t &peer_in_anchor_index,
  879. std::vector<std::pair<Node *, NodePtr>> &dynamic_out_to_switchn) {
  880. auto data_shape = NodeUtils::GetOutputDesc(*node, out_anchor_index).GetShape();
  881. string data_name = node->GetName();
  882. if (getnext_sink_dynamic_dims_) {
  883. data_name.append("_").append(std::to_string(out_anchor_index));
  884. }
  885. (void)AttrUtils::SetListInt(node->GetOpDesc(), ATTR_MBATCH_ORIGIN_INPUT_DIMS, data_shape.GetDims());
  886. GELOGI("Insert switchn node of %s, shape dims is %s.", data_name.c_str(),
  887. formats::JoinToString(data_shape.GetDims()).c_str());
  888. if (IsAllDimsPositive(data_shape.GetDims())) {
  889. GELOGI("The shape of data %s are positive(%s), skip the multi batch process", node->GetName().c_str(),
  890. data_shape.ToString().c_str());
  891. return SUCCESS;
  892. }
  893. auto switchn_desc = MakeShared<OpDesc>();
  894. GE_IF_BOOL_EXEC(switchn_desc == nullptr,
  895. GELOGE(OUT_OF_MEMORY, "Failed to create switchn for data %s", node->GetName().c_str());
  896. return OUT_OF_MEMORY);
  897. string switchn_name = node->GetName() + "_ascend_mbatch_switchn";
  898. if (getnext_sink_dynamic_dims_) {
  899. switchn_name.append("_").append(std::to_string(out_anchor_index))
  900. .append("_").append(std::to_string(peer_in_anchor_index));
  901. }
  902. GELOGI("name of switchn is %s.", switchn_name.c_str());
  903. switchn_desc->SetName(switchn_name);
  904. switchn_desc->SetType(SWITCHN);
  905. GeTensorDesc tensor(NodeUtils::GetOutputDesc(*node, out_anchor_index));
  906. GE_IF_BOOL_EXEC(switchn_desc->AddInputDesc("data", tensor) != GRAPH_SUCCESS,
  907. GELOGE(OUT_OF_MEMORY, "Failed to add input tensor desc for %s", switchn_desc->GetName().c_str());
  908. return OUT_OF_MEMORY);
  909. GeTensorDesc pred_tensor;
  910. GE_IF_BOOL_EXEC(switchn_desc->AddInputDesc("pred_value", pred_tensor) != GRAPH_SUCCESS,
  911. GELOGE(OUT_OF_MEMORY, "Failed to add input pred tensor desc for %s", switchn_desc->GetName().c_str());
  912. return OUT_OF_MEMORY);
  913. std::vector<std::string> input_dims_str;
  914. for (size_t i = 0; i < shapes_.size(); ++i) {
  915. GELOGI("Start clac shape for data %s, batch shape is %s.", data_name.c_str(),
  916. formats::JoinToString(data_to_dynamic_info_.at(data_name).at(i)).c_str());
  917. auto shape = data_shape;
  918. auto ret = CalcShape(data_to_dynamic_info_.at(data_name).at(i), shape);
  919. if (ret != SUCCESS) {
  920. GELOGE(ret, "Failed to calculate the batched shape for data node %s, the shapes may not match",
  921. node->GetName().c_str());
  922. return ret;
  923. }
  924. tensor.SetShape(shape);
  925. string input_str;
  926. int64_t tensor_size = 0;
  927. (void)TensorUtils::GetTensorSizeInBytes(tensor, tensor_size);
  928. input_str = TypeUtils::FormatToSerialString(tensor.GetFormat()) + ":" +
  929. TypeUtils::DataTypeToSerialString(tensor.GetDataType()) + ":" + node->GetName() + ":" +
  930. std::to_string(tensor_size) + ":" + std::to_string(tensor.GetShape().GetDimNum()) + ":" +
  931. formats::JoinToString(tensor.GetShape().GetDims());
  932. input_dims_str.emplace_back(input_str);
  933. if (!AttrUtils::SetListInt(tensor, ATTR_NAME_SWITCHN_PRED_VALUE, shapes_.at(i))) {
  934. GELOGE(INTERNAL_ERROR, "Failed to add attr value on output %zu tensor", i);
  935. return INTERNAL_ERROR;
  936. }
  937. (void) AttrUtils::SetListInt(tensor, ATTR_NAME_COMBINED_DYNAMIC_DIMS, shape.GetDims());
  938. if (switchn_desc->AddOutputDesc("output" + std::to_string(i), tensor) != GRAPH_SUCCESS) {
  939. GELOGE(GRAPH_FAILED, "Opdesc AddOutputDesc failed");
  940. return GRAPH_FAILED;
  941. }
  942. GELOGD("The switchn %s output index %zu, shape %s", switchn_desc->GetName().c_str(), i, shape.ToString().c_str());
  943. }
  944. (void)AttrUtils::SetListStr(node->GetOpDesc(), "_all_origin_gears_inputs", input_dims_str);
  945. if (!AttrUtils::SetListStr(switchn_desc, ATTR_USER_DESIGNEATE_SHAPE_ORDER, data_name_order_)) {
  946. GELOGE(INTERNAL_ERROR, "Failed to add user designate shape order attr on switchn node %s",
  947. switchn_desc->GetName().c_str());
  948. return INTERNAL_ERROR;
  949. }
  950. if (!AttrUtils::SetBool(switchn_desc, ATTR_INSERT_BY_MBATCH, true)) {
  951. GELOGE(INTERNAL_ERROR, "Failed to add insert attr on switchn node %s", switchn_desc->GetName().c_str());
  952. return INTERNAL_ERROR;
  953. }
  954. if (!AttrUtils::SetStr(node->GetOpDesc(), kMbatchSwitchnName, switchn_desc->GetName())) {
  955. GELOGE(INTERNAL_ERROR, "Failed to add switchn attr on data node %s", node->GetName().c_str());
  956. return INTERNAL_ERROR;
  957. }
  958. if (StampDynamicType(switchn_desc) != SUCCESS) {
  959. GELOGE(INTERNAL_ERROR, "Failed to add dynamic type attr on switchn node %s", switchn_desc->GetName().c_str());
  960. return INTERNAL_ERROR;
  961. }
  962. auto switchn = graph_->AddNode(switchn_desc);
  963. GE_IF_BOOL_EXEC(switchn == nullptr,
  964. GELOGE(OUT_OF_MEMORY, "Failed to create switchn %s from desc", switchn_desc->GetName().c_str());
  965. return OUT_OF_MEMORY);
  966. if (!getnext_sink_dynamic_dims_) {
  967. data_nodes_to_switchn_[node.get()] = switchn;
  968. } else {
  969. dynamic_out_to_switchn.emplace_back(std::make_pair(node.get(), switchn));
  970. GELOGD("Insert %s for %s.", switchn->GetName().c_str(), node->GetName().c_str());
  971. }
  972. return SUCCESS;
  973. }
  974. Status MultiBatchGraphCopyer::InsertMergeForEdgeNode(const NodePtr &node) {
  975. for (auto &in_data_anchor : node->GetAllInDataAnchors()) {
  976. auto src_out_anchor = in_data_anchor->GetPeerOutAnchor();
  977. if (src_out_anchor == nullptr) {
  978. GELOGD("The node %s does not has input at index %d", node->GetName().c_str(), in_data_anchor->GetIdx());
  979. continue;
  980. }
  981. auto in_node = src_out_anchor->GetOwnerNode();
  982. if (!IsInBatchBranch(in_node)) {
  983. continue;
  984. }
  985. auto merge_node = InsertMergeNode(in_node, src_out_anchor->GetIdx());
  986. if (merge_node == nullptr) {
  987. return INTERNAL_ERROR;
  988. }
  989. }
  990. for (auto &in_node : node->GetInControlNodes()) {
  991. if (!IsInBatchBranch(in_node)) {
  992. continue;
  993. }
  994. auto merge_node = InsertMergeNode(in_node, -1);
  995. if (merge_node == nullptr) {
  996. return INTERNAL_ERROR;
  997. }
  998. }
  999. return SUCCESS;
  1000. }
  1001. Status MultiBatchGraphCopyer::LinkGetDynamicDimsToNetOutput(const NodePtr &node) {
  1002. if (node->GetType() == NETOUTPUT) {
  1003. if (!GetLocalOmgContext().dynamic_node_type.empty()) {
  1004. if (!AttrUtils::SetStr(node->GetOpDesc(), ATTR_ALL_GEARS_INFO, GetLocalOmgContext().dynamic_dims)) {
  1005. GELOGE(INTERNAL_ERROR, "Failed to set all gears info attr on netoutput %s.", node->GetName().c_str());
  1006. return INTERNAL_ERROR;
  1007. }
  1008. }
  1009. if (getnext_sink_dynamic_dims_) {
  1010. size_t input_index = node->GetAllInDataAnchors().size();
  1011. if (NodeUtils::AppendInputAnchor(node, input_index + 1) != GRAPH_SUCCESS) {
  1012. GELOGE(INTERNAL_ERROR, "Append input anchor of %s of %zu failed.", node->GetName().c_str(), input_index);
  1013. return INTERNAL_ERROR;
  1014. }
  1015. auto ret =
  1016. ge::GraphUtils::AddEdge(shape_data_->GetOutDataAnchor(kDataOutIndex), node->GetInDataAnchor(input_index));
  1017. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to link netoutput %s to getdynamicdims %s",
  1018. node->GetName().c_str(), shape_data_->GetName().c_str());
  1019. return INTERNAL_ERROR);
  1020. if (!AttrUtils::SetBool(node->GetOpDesc(), ATTR_GETNEXT_SINK_DYNMAIC, true)) {
  1021. GELOGE(INTERNAL_ERROR, "Failed to set getnext sink dynamic attr on netoutput %s.", node->GetName().c_str());
  1022. return INTERNAL_ERROR;
  1023. }
  1024. }
  1025. }
  1026. return SUCCESS;
  1027. }
  1028. Status MultiBatchGraphCopyer::CopyNodeInBatchBranch(const NodePtr &node) {
  1029. auto &copyed_nodes = nodes_to_batch_nodes_[node.get()];
  1030. for (size_t i = 0; i < shapes_.size(); ++i) {
  1031. auto copyed_node = InsertCopyNode(node, i);
  1032. if (copyed_node == nullptr) {
  1033. GELOGE(INTERNAL_ERROR, "Failed to add node to graph when copy node %s", node->GetName().c_str());
  1034. return INTERNAL_ERROR;
  1035. }
  1036. copyed_nodes.emplace_back(copyed_node);
  1037. GELOGI("Copy node %s type %s for shape %s, new node name %s", node->GetName().c_str(), node->GetType().c_str(),
  1038. formats::JoinToString(shapes_.at(i)).c_str(), copyed_node->GetName().c_str());
  1039. }
  1040. return SUCCESS;
  1041. }
  1042. Status MultiBatchGraphCopyer::AddAttrForGetDynamicDims(const NodePtr &node) {
  1043. GELOGD("Add attr for :%s, type is %s:", shape_data_->GetName().c_str(), shape_data_->GetType().c_str());
  1044. size_t data_count = node->GetAllOutDataAnchors().size() / kDivisionConst;
  1045. if (!AttrUtils::SetInt(shape_data_->GetOpDesc(), ATTR_GETNEXT_SINK_DATA_COUNT, data_count)) {
  1046. GELOGE(INTERNAL_ERROR, "set ATTR_GETNEXT_SINK_DATA_COUNT failed");
  1047. return INTERNAL_ERROR;
  1048. }
  1049. vector<int64_t> shape_info;
  1050. for (size_t i = 0; i < GetLocalOmgContext().user_input_dims.size(); ++i) {
  1051. if (GetLocalOmgContext().user_input_dims.at(i).second.size() == 1 &&
  1052. GetLocalOmgContext().user_input_dims.at(i).second.at(0) == 0) {
  1053. shape_info.emplace_back(0);
  1054. continue;
  1055. }
  1056. shape_info.emplace_back(GetLocalOmgContext().user_input_dims.at(i).second.size());
  1057. for (size_t j = 0; j < GetLocalOmgContext().user_input_dims.at(i).second.size(); ++j) {
  1058. shape_info.emplace_back(GetLocalOmgContext().user_input_dims.at(i).second.at(j));
  1059. }
  1060. }
  1061. if (!AttrUtils::SetListInt(shape_data_->GetOpDesc(), ATTR_GETNEXT_SINK_SHAPE_INFO, shape_info)) {
  1062. GELOGE(INTERNAL_ERROR, "set ATTR_GETNEXT_SINK_SHAPE_INFO failed");
  1063. return INTERNAL_ERROR;
  1064. }
  1065. return SUCCESS;
  1066. }
  1067. Status MultiBatchGraphCopyer::AddLinkForGetDynamicDims(const NodePtr &node) {
  1068. GELOGD("Start relink out anchor from shape node to getdynamicdims, and delete link between shape node and identity.");
  1069. size_t input_index = 0;
  1070. GELOGD("Out count of %s is %zu.", node->GetName().c_str(), node->GetAllOutDataAnchors().size());
  1071. size_t data_count = node->GetAllOutDataAnchors().size() / kDivisionConst;
  1072. for (size_t out_index = data_count; out_index < node->GetAllOutDataAnchors().size(); ++out_index, ++input_index) {
  1073. GELOGI("Start add %s of %zu out_anchor to %s of %zu in_anchor.", node->GetName().c_str(), out_index,
  1074. shape_data_->GetName().c_str(), input_index);
  1075. auto out_data_anchor = node->GetOutDataAnchor(out_index);
  1076. auto ret = GraphUtils::AddEdge(out_data_anchor, shape_data_->GetInDataAnchor(input_index));
  1077. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to link getnext %s to getdynamicdims %s",
  1078. node->GetName().c_str(), shape_data_->GetName().c_str());
  1079. return INTERNAL_ERROR);
  1080. }
  1081. return SUCCESS;
  1082. }
  1083. Status MultiBatchGraphCopyer::LinkEdges() {
  1084. Status ret;
  1085. for (const auto &node : origin_all_nodes_) {
  1086. GE_CHECK_NOTNULL(node->GetOpDesc());
  1087. if (!getnext_sink_dynamic_dims_) {
  1088. if (data_nodes_to_switchn_.count(node.get()) > 0) {
  1089. auto switchn = data_nodes_to_switchn_[node.get()];
  1090. GE_IF_BOOL_EXEC(switchn == nullptr,
  1091. GELOGE(PARAM_INVALID, "Switchn should not be nullptr for %s.", node->GetName().c_str());
  1092. return OUT_OF_MEMORY);
  1093. ret = LinkDataToSwitchN(node, switchn, kDataOutIndex);
  1094. GE_CHK_STATUS_RET(ret, "Link data to switchn failed.");
  1095. }
  1096. } else {
  1097. if (IsGetNextType(node)) {
  1098. GELOGD("Start add attr and link edge for %s.", node->GetName().c_str());
  1099. GE_CHK_STATUS_RET(AddAttrForGetDynamicDims(node), "Failed to add attr for %s.", node->GetName().c_str());
  1100. GE_CHK_STATUS_RET(AddLinkForGetDynamicDims(node), "Failed to add link for %s.", node->GetName().c_str());
  1101. }
  1102. for (size_t i = 0; i < getnext_nodes_to_switchn_.size(); ++i) {
  1103. for (size_t j = 0; j < getnext_nodes_to_switchn_.at(i).size(); ++j) {
  1104. if (getnext_nodes_to_switchn_.at(i).at(j).first == node.get()) {
  1105. auto switchn = getnext_nodes_to_switchn_.at(i).at(j).second;
  1106. GE_CHK_STATUS_RET(LinkDataToSwitchN(node, switchn, i), "Link %s to %s failed.", node->GetName().c_str(),
  1107. switchn->GetName().c_str());
  1108. }
  1109. }
  1110. }
  1111. }
  1112. if (nodes_to_merge_nodes_.count(node.get()) > 0) {
  1113. GE_CHK_STATUS_RET(LinkToMerge(node), "Link %s to merge failed.", node->GetName().c_str());
  1114. }
  1115. if (nodes_to_batch_nodes_.count(node.get()) > 0) {
  1116. ret = LinkToNodeInBranch(node);
  1117. } else {
  1118. ret = LinkToNodeOutBranch(node);
  1119. }
  1120. if (ret != SUCCESS) {
  1121. return ret;
  1122. }
  1123. }
  1124. return SUCCESS;
  1125. }
  1126. Status MultiBatchGraphCopyer::LinkDataToSwitchN(const NodePtr &data, const NodePtr &switchn, const int &out_index) {
  1127. auto ret =
  1128. GraphUtils::AddEdge(shape_data_->GetOutDataAnchor(kDataOutIndex), switchn->GetInDataAnchor(kSwitchNPredIndex));
  1129. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to link shape data %s to switchn %s",
  1130. shape_data_->GetName().c_str(), switchn->GetName().c_str());
  1131. return INTERNAL_ERROR);
  1132. ret = GraphUtils::AddEdge(data->GetOutDataAnchor(out_index), switchn->GetInDataAnchor(kSwitchNDataIndex));
  1133. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to link data %s to switchn %s",
  1134. data->GetName().c_str(), switchn->GetName().c_str());
  1135. return INTERNAL_ERROR);
  1136. return SUCCESS;
  1137. }
  1138. Status MultiBatchGraphCopyer::LinkToMerge(const NodePtr &node) {
  1139. auto &merge_nodes = nodes_to_merge_nodes_[node.get()];
  1140. for (size_t i = 0; i < merge_nodes.size(); ++i) {
  1141. auto merge_node = merge_nodes[i];
  1142. if (merge_node == nullptr) {
  1143. continue;
  1144. }
  1145. if (nodes_to_batch_nodes_.count(node.get()) > 0) {
  1146. auto ret = LinkNodeToMerge(node, i, merge_node);
  1147. if (ret != SUCCESS) {
  1148. return ret;
  1149. }
  1150. continue;
  1151. }
  1152. if (!getnext_sink_dynamic_dims_) {
  1153. if (data_nodes_to_switchn_.count(node.get()) > 0) {
  1154. auto &switchn = data_nodes_to_switchn_[node.get()];
  1155. auto ret = LinkDataToMerge(node, merge_node, switchn);
  1156. if (ret != SUCCESS) {
  1157. return ret;
  1158. }
  1159. continue;
  1160. }
  1161. } else {
  1162. for (size_t j = 0; j < getnext_nodes_to_switchn_.size(); ++j) {
  1163. for (size_t k = 0; k < getnext_nodes_to_switchn_.at(j).size(); ++k) {
  1164. if (getnext_nodes_to_switchn_.at(j).at(k).first == node.get()) {
  1165. auto &switchn = getnext_nodes_to_switchn_.at(j).at(k).second;
  1166. auto ret = LinkDataToMerge(node, merge_node, switchn);
  1167. if (ret != SUCCESS) {
  1168. return ret;
  1169. }
  1170. }
  1171. }
  1172. }
  1173. continue;
  1174. }
  1175. GELOGE(INTERNAL_ERROR, "The merge node %s is created, index %zu, but can not find the src node",
  1176. merge_node->GetName().c_str(), i);
  1177. return INTERNAL_ERROR;
  1178. }
  1179. return SUCCESS;
  1180. }
  1181. Status MultiBatchGraphCopyer::LinkToNodeInBranch(const NodePtr &node) {
  1182. GELOGI("Start LinkToNodeInBranch for %s.", node->GetName().c_str());
  1183. auto &branch_nodes = nodes_to_batch_nodes_[node.get()];
  1184. for (size_t i = 0; i < branch_nodes.size(); ++i) {
  1185. auto ret = CopyInDataEdges(node, i, branch_nodes[i]);
  1186. if (ret != SUCCESS) {
  1187. return ret;
  1188. }
  1189. ret = CopyInControlEdges(node, i, branch_nodes[i]);
  1190. if (ret != SUCCESS) {
  1191. return ret;
  1192. }
  1193. }
  1194. return SUCCESS;
  1195. }
  1196. Status MultiBatchGraphCopyer::LinkToNodeOutBranch(const NodePtr &node) {
  1197. for (auto &in_data_anchor : node->GetAllInDataAnchors()) {
  1198. auto src_out_anchor = in_data_anchor->GetPeerOutAnchor();
  1199. if (src_out_anchor == nullptr) {
  1200. GELOGD("The node %s does not has input at index %d", node->GetName().c_str(), in_data_anchor->GetIdx());
  1201. continue;
  1202. }
  1203. auto in_node = src_out_anchor->GetOwnerNode();
  1204. if (!IsInBatchBranch(in_node)) {
  1205. continue;
  1206. }
  1207. auto iter = nodes_to_merge_nodes_.find(in_node.get());
  1208. if (iter == nodes_to_merge_nodes_.end()) {
  1209. GELOGE(INTERNAL_ERROR, "Failed to link IO data edge from %s(%d) to %s(%d), no merge node found",
  1210. in_node->GetName().c_str(), src_out_anchor->GetIdx(), node->GetName().c_str(), in_data_anchor->GetIdx());
  1211. return INTERNAL_ERROR;
  1212. }
  1213. auto merge_node = iter->second[src_out_anchor->GetIdx()];
  1214. if (merge_node == nullptr) {
  1215. GELOGE(INTERNAL_ERROR, "Failed to link IO data edge from %s(%d) to %s(%d), no merge node found",
  1216. in_node->GetName().c_str(), src_out_anchor->GetIdx(), node->GetName().c_str(), in_data_anchor->GetIdx());
  1217. return INTERNAL_ERROR;
  1218. }
  1219. auto ret = src_out_anchor->Unlink(in_data_anchor);
  1220. if (ret != GRAPH_SUCCESS) {
  1221. GELOGE(INTERNAL_ERROR, "Failed to unlink the control edge from %s(%d) to %s(%d)", in_node->GetName().c_str(),
  1222. src_out_anchor->GetIdx(), node->GetName().c_str(), in_data_anchor->GetIdx());
  1223. return INTERNAL_ERROR;
  1224. }
  1225. ret = GraphUtils::AddEdge(merge_node->GetOutDataAnchor(kMergeDataOutIndex), in_data_anchor);
  1226. if (ret != GRAPH_SUCCESS) {
  1227. GELOGE(INTERNAL_ERROR, "Failed to add data edge from %s(%d) to %s(%d)", merge_node->GetName().c_str(),
  1228. src_out_anchor->GetIdx(), node->GetName().c_str(), in_data_anchor->GetIdx());
  1229. return INTERNAL_ERROR;
  1230. }
  1231. GELOGI("Link data edge from merge %s(from %s(%d)) to %s(%d)", merge_node->GetName().c_str(),
  1232. in_node->GetName().c_str(), src_out_anchor->GetIdx(), node->GetName().c_str(), in_data_anchor->GetIdx());
  1233. }
  1234. for (auto &in_node : node->GetInControlNodes()) {
  1235. if (!IsInBatchBranch(in_node)) {
  1236. continue;
  1237. }
  1238. auto iter = nodes_to_merge_nodes_.find(in_node.get());
  1239. if (iter == nodes_to_merge_nodes_.end()) {
  1240. GELOGE(INTERNAL_ERROR, "Failed to link IO control edge from %s to %s, no merge node found",
  1241. in_node->GetName().c_str(), node->GetName().c_str());
  1242. return INTERNAL_ERROR;
  1243. }
  1244. auto merge_node = iter->second[0];
  1245. if (merge_node == nullptr) {
  1246. GELOGE(INTERNAL_ERROR, "Failed to link IO control edge from %s to %s, no merge node found",
  1247. in_node->GetName().c_str(), node->GetName().c_str());
  1248. return INTERNAL_ERROR;
  1249. }
  1250. GE_IF_BOOL_EXEC(in_node->GetOutControlAnchor() == nullptr,
  1251. GELOGE(INTERNAL_ERROR, "Innode outputControlAnchor is null");
  1252. return INTERNAL_ERROR);
  1253. auto ret = in_node->GetOutControlAnchor()->Unlink(node->GetInControlAnchor());
  1254. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to unlink the control edge from %s to %s",
  1255. in_node->GetName().c_str(), node->GetName().c_str());
  1256. return INTERNAL_ERROR);
  1257. ret = GraphUtils::AddEdge(merge_node->GetOutControlAnchor(), node->GetInControlAnchor());
  1258. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS, GELOGE(INTERNAL_ERROR, "Failed to add control edge from %s to %s",
  1259. merge_node->GetName().c_str(), node->GetName().c_str());
  1260. return INTERNAL_ERROR);
  1261. GELOGI("Link control edge from merge %s(from %s) to %s", merge_node->GetName().c_str(), in_node->GetName().c_str(),
  1262. node->GetName().c_str());
  1263. }
  1264. return SUCCESS;
  1265. }
  1266. Status MultiBatchGraphCopyer::InsertIdentityAfterSwitchN() {
  1267. for (auto &node : graph_->GetAllNodes()) {
  1268. if (node->GetType() != SWITCHN) {
  1269. continue;
  1270. }
  1271. auto switchn_desc = node->GetOpDesc();
  1272. GE_CHECK_NOTNULL(switchn_desc);
  1273. size_t i = 0;
  1274. for (auto &out_data_anchor : node->GetAllOutDataAnchors()) {
  1275. for (auto &in_data_anchor : out_data_anchor->GetPeerInDataAnchors()) {
  1276. auto out_node = in_data_anchor->GetOwnerNode();
  1277. auto op_desc = out_node->GetOpDesc();
  1278. GE_CHECK_NOTNULL(op_desc);
  1279. if ((out_node->GetType() == MERGE) && (op_desc->HasAttr(ATTR_INSERT_BY_MBATCH))) {
  1280. GELOGD("No need to insert identity between %s and %s.", node->GetName().c_str(), out_node->GetName().c_str());
  1281. continue;
  1282. }
  1283. auto identity_desc = MakeShared<OpDesc>(node->GetName() + "_identity_" + std::to_string(i), IDENTITY);
  1284. GE_CHECK_NOTNULL(identity_desc);
  1285. string batch_label;
  1286. if (AttrUtils::GetStr(op_desc, ATTR_NAME_BATCH_LABEL, batch_label)) {
  1287. if (!AttrUtils::SetStr(identity_desc, ATTR_NAME_BATCH_LABEL, batch_label)) {
  1288. GELOGE(FAILED, "Set attr ATTR_NAME_BATCH_LABEL failed, node:%s.", identity_desc->GetName().c_str());
  1289. return FAILED;
  1290. }
  1291. }
  1292. auto data_desc = switchn_desc->GetOutputDesc(i);
  1293. i++;
  1294. GE_CHK_STATUS_RET(identity_desc->AddInputDesc("x", data_desc));
  1295. GE_CHK_STATUS_RET(identity_desc->AddOutputDesc("y", data_desc));
  1296. auto identity_node = graph_->AddNode(identity_desc);
  1297. GE_CHECK_NOTNULL(identity_node);
  1298. GE_CHK_STATUS_RET(out_data_anchor->LinkTo(identity_node->GetInDataAnchor(0)));
  1299. GE_CHECK_NOTNULL(identity_node->GetOutControlAnchor());
  1300. GE_CHK_STATUS_RET(identity_node->GetOutControlAnchor()->LinkTo(out_node->GetInControlAnchor()));
  1301. }
  1302. }
  1303. }
  1304. return SUCCESS;
  1305. }
  1306. Status ProcessMultiBatch(ComputeGraphPtr &graph) {
  1307. const char *multi_batch_with_case = std::getenv("MULTI_BATCH_WITH_CASE");
  1308. if (multi_batch_with_case != nullptr) {
  1309. PassManager pass_manager;
  1310. GE_CHK_STATUS_RET(pass_manager.AddPass("MultiBatchClonePass", new (std::nothrow) MultiBatchClonePass));
  1311. return pass_manager.Run(graph);
  1312. }
  1313. if (!GetLocalOmgContext().need_multi_batch) {
  1314. GELOGI("No need to process_multi for no_train graph.");
  1315. return SUCCESS;
  1316. }
  1317. std::vector<NodePtr> data_nodes;
  1318. std::vector<NodePtr> getnext_nosink_nodes;
  1319. std::vector<NodePtr> getnext_sink_nodes;
  1320. if (CheckSequenceOfOptions(graph, data_nodes, getnext_nosink_nodes, getnext_sink_nodes) != SUCCESS) {
  1321. GELOGE(PARAM_INVALID, "[Train_Dynamic] CheckSequenceOfOptions failed.");
  1322. return PARAM_INVALID;
  1323. }
  1324. if (UpdateNameOfInputShape(graph, data_nodes, getnext_nosink_nodes, getnext_sink_nodes) != SUCCESS) {
  1325. GELOGE(PARAM_INVALID, "[Train_Dynamic] UpdateNameForInputShapeOfOption failed.");
  1326. return PARAM_INVALID;
  1327. }
  1328. if (DeleteIdentityInsertByAdapter(graph) != SUCCESS) {
  1329. GELOGE(PARAM_INVALID, "DeleteIdentityInsertByAdapter failed.");
  1330. return PARAM_INVALID;
  1331. }
  1332. std::vector<std::vector<int64_t>> shapes;
  1333. if (!InitDynamicParams(shapes)) {
  1334. GELOGD("There is no multi-batch options, no need to process multi-batch copy");
  1335. return SUCCESS;
  1336. }
  1337. if (CheckNegativeCountOfOptions(shapes) != SUCCESS) {
  1338. GELOGE(PARAM_INVALID, "Input_shape and dynamic_dims should set correct params.");
  1339. return PARAM_INVALID;
  1340. }
  1341. DynamicType dynamic_type = DynamicType::kDynamicUnknown;
  1342. if (!GetLocalOmgContext().dynamic_batch_size.empty()) {
  1343. dynamic_type = DynamicType::kDynamicBatch;
  1344. } else if (!GetLocalOmgContext().dynamic_image_size.empty()) {
  1345. dynamic_type = DynamicType::kDynamicImageSize;
  1346. } else if (!GetLocalOmgContext().dynamic_dims.empty()) {
  1347. dynamic_type = DynamicType::kDynamicDims;
  1348. }
  1349. std::vector<std::pair<std::string, std::vector<int64_t>>> user_designate_shape;
  1350. user_designate_shape = GetLocalOmgContext().user_input_dims;
  1351. GELOGI("Begin to copy graph for multi-batch");
  1352. multibatch::MultiBatchGraphCopyer copyer(graph);
  1353. for (auto &shape : shapes) {
  1354. copyer.AddShape(shape);
  1355. }
  1356. copyer.SetDynamicType(dynamic_type);
  1357. copyer.SetUserDesignateShape(user_designate_shape);
  1358. return copyer.CopyGraph();
  1359. }
  1360. // +-----------+
  1361. // | Data | +-----------+ +-----------+ +-----------+
  1362. // +-----------+ | Data | ----> | SoftmaxV2 | ----> | NetOutput |
  1363. // \ /. +-----------+ +-----------+ +-----------+
  1364. // \ /.
  1365. // +-----------+ +-----------+ /. +-----------+ +-----------+ +-----------+
  1366. // | Data | ----> | Case | S--- | Data | ----> | SoftmaxV2 | ----> | NetOutput |
  1367. // +-----------+ +-----------+ \. +-----------+ +-----------+ +-----------+
  1368. // \ \.
  1369. // \ \. +-----------+ +-----------+ +-----------+
  1370. // +-----------+ | Data | ----> | SoftmaxV2 | ----> | NetOutput |
  1371. // | NetOutput | +-----------+ +-----------+ +-----------+
  1372. // +-----------+
  1373. // +-----------+ /
  1374. // | Data | --------------->/
  1375. // +-----------+
  1376. void GetDynamicShapeByGraph(const ComputeGraphPtr &graph, const NodePtr &node,
  1377. set<size_t> &dynamic_output_index, vector<string> &dynamic_output_dims) {
  1378. GELOGD("Try get dynamic shape info, Graph: %s, Node: %s", graph->GetName().c_str(), node->GetName().c_str());
  1379. const auto &func_desc = node->GetOpDesc();
  1380. if (!func_desc->HasAttr(ATTR_NAME_BATCH_NUM)) {
  1381. GELOGD("Graph: %s Not multi-batch, Node: %s", graph->GetName().c_str(), node->GetName().c_str());
  1382. return;
  1383. }
  1384. const auto &dynamic_branch_names = func_desc->GetSubgraphInstanceNames();
  1385. for (size_t i = 0; i < func_desc->GetOutputsSize(); ++i) {
  1386. for (size_t j = 0; j < dynamic_branch_names.size(); ++j) {
  1387. const auto &subgraph = graph->GetSubgraph(dynamic_branch_names[j]);
  1388. if (subgraph == nullptr) {
  1389. GELOGE(GE_GRAPH_EMPTY_SUBGRAPH, "Subgraph not found, name: %s", dynamic_branch_names[j].c_str());
  1390. dynamic_output_dims.clear();
  1391. return;
  1392. }
  1393. const auto &out_node = subgraph->FindFirstNodeMatchType(NETOUTPUT);
  1394. if (out_node == nullptr) {
  1395. GELOGE(GE_GRAPH_GRAPH_NODE_NULL, "NetOutput not found, name: %s", dynamic_branch_names[j].c_str());
  1396. dynamic_output_dims.clear();
  1397. return;
  1398. }
  1399. GELOGI("Find the subgraph Output node %s and the index is %zu", out_node->GetName().c_str(), i);
  1400. const auto &out_desc = out_node->GetOpDesc();
  1401. if (out_desc == nullptr || out_desc->GetInputsSize() <= i) {
  1402. GELOGE(GE_GRAPH_GRAPH_NODE_NULL, "Get Input desc failed, name: %s, index: %zu", out_node->GetName().c_str(), i);
  1403. dynamic_output_dims.clear();
  1404. return;
  1405. }
  1406. const auto &input_tensor = out_desc->GetInputDesc(i);
  1407. const auto &shape_msg = input_tensor.GetShape().ToString();
  1408. string output_shape = std::to_string(j) + "," + std::to_string(i) + "," + shape_msg;
  1409. GELOGI("The shape msg in dynamic batch is %s", output_shape.c_str());
  1410. dynamic_output_dims.emplace_back(output_shape);
  1411. uint32_t parent_index = 0;
  1412. (void)AttrUtils::GetInt(input_tensor, ATTR_NAME_PARENT_NODE_INDEX, parent_index);
  1413. dynamic_output_index.insert(parent_index);
  1414. }
  1415. }
  1416. }
  1417. // +-----------+ +-----------+ i = 0
  1418. // +----> | SoftmaxV2 | ----> |MemcpyAsync| ----> \.
  1419. // / +-----------+ +-----------+ \.
  1420. // / \.
  1421. // +-----------+ +-----------+ +-----------+ +-----------+ i = 1 +-----------+
  1422. // | Data | ----> | SwitchN | ----> | SoftmaxV2 | ----> |MemcpyAsync| ----> | Merge |
  1423. // +-----------+ +-----------+ +-----------+ +-----------+ +-----------+
  1424. // \ / \. j = 0
  1425. // \ +-----------+ +-----------+ i = 2 / \.
  1426. // +----> | SoftmaxV2 | ----> |MemcpyAsync| ----> / +-----------+
  1427. // +-----------+ +-----------+ | NetOutput |
  1428. // +-----------+
  1429. // +-----------+ /.
  1430. // | Data | --------------------------------------------------------------------------->/. j = 1
  1431. // +-----------+
  1432. void GetDynamicShapeByMerge(const ComputeGraphPtr &graph, const NodePtr &node,
  1433. set<size_t> &dynamic_output_index, vector<string> &dynamic_output_dims) {
  1434. GELOGD("Try get dynamic shape info, Graph: %s, Node: %s", graph->GetName().c_str(), node->GetName().c_str());
  1435. const auto &netoutput_desc = node->GetOpDesc();
  1436. const auto &inputnode_to_netoutput = node->GetInAllNodes();
  1437. GELOGI("Train_Dynamic Find the merge node size is %zu.", inputnode_to_netoutput.size());
  1438. for (size_t i = 0; i < inputnode_to_netoutput.size(); ++i) {
  1439. bool insert_by_mbatch = false;
  1440. (void)AttrUtils::GetBool(inputnode_to_netoutput.at(i)->GetOpDesc(), ATTR_INSERT_BY_MBATCH, insert_by_mbatch);
  1441. GELOGI("Train_Dynamic type is %s", inputnode_to_netoutput.at(i)->GetType().c_str());
  1442. if (inputnode_to_netoutput.at(i)->GetType() == MERGE && insert_by_mbatch) {
  1443. GELOGI("Find the merge node %s with mbatch attr and the index is %zu",
  1444. inputnode_to_netoutput.at(i)->GetName().c_str(), i);
  1445. dynamic_output_index.insert(i);
  1446. for (size_t j = 0; j < inputnode_to_netoutput.at(i)->GetInNodes().size(); ++j) {
  1447. auto input_desc = inputnode_to_netoutput.at(i)->GetOpDesc();
  1448. auto input_tensor_desc = input_desc->GetInputDesc(j);
  1449. auto shape_msg = input_tensor_desc.GetShape().ToString();
  1450. string output_shape = std::to_string(j) + "," + std::to_string(i) + "," + shape_msg;
  1451. GELOGI("The shape msg in dynamic batch is %s", output_shape.c_str());
  1452. dynamic_output_dims.emplace_back(output_shape);
  1453. }
  1454. }
  1455. }
  1456. }
  1457. // Connect NetOutput directly
  1458. void GetDirectOutputShape(const ComputeGraphPtr &graph, const NodePtr &node,
  1459. const set<size_t> &dynamic_output_index, vector<string> &dynamic_output_dims) {
  1460. GELOGD("Try get directly shape info, Graph: %s, Node: %s", graph->GetName().c_str(), node->GetName().c_str());
  1461. const auto &netoutput_desc = node->GetOpDesc();
  1462. const auto &inputnode_to_netoutput = node->GetInAllNodes();
  1463. for (size_t i = 0; i < inputnode_to_netoutput.size(); ++i) {
  1464. if (dynamic_output_index.count(i) > 0) {
  1465. continue;
  1466. }
  1467. if (inputnode_to_netoutput.at(i)->GetType() == GETDYNAMICDIMS) {
  1468. continue;
  1469. }
  1470. auto tensor_desc = netoutput_desc->GetInputDesc(i);
  1471. auto shape = tensor_desc.GetShape().ToString();
  1472. string static_output_shape = std::to_string(kStaticOutput) + "," + std::to_string(i) + "," + shape;
  1473. GELOGI("The static output shape msg is %s", static_output_shape.c_str());
  1474. dynamic_output_dims.emplace_back(static_output_shape);
  1475. }
  1476. }
  1477. Status GetDynamicOutputShape(ComputeGraphPtr &graph) {
  1478. GE_CHECK_NOTNULL(graph);
  1479. GELOGI("Start to get output dynamic batch shape message");
  1480. NodePtr net_output;
  1481. set<size_t> dynamic_output_index;
  1482. vector<string> dynamic_output_dims;
  1483. for (auto &node : graph->GetDirectNode()) {
  1484. if (node->GetType() == NETOUTPUT) {
  1485. net_output = node;
  1486. GetDynamicShapeByMerge(graph, node, dynamic_output_index, dynamic_output_dims);
  1487. } else if (node->GetType() == CASE) {
  1488. GetDynamicShapeByGraph(graph, node, dynamic_output_index, dynamic_output_dims);
  1489. }
  1490. }
  1491. if ((net_output != nullptr) && !dynamic_output_dims.empty()) {
  1492. GetDirectOutputShape(graph, net_output, dynamic_output_index, dynamic_output_dims);
  1493. if (!AttrUtils::SetListStr(net_output->GetOpDesc(), ATTR_NAME_DYNAMIC_OUTPUT_DIMS, dynamic_output_dims)) {
  1494. GELOGE(FAILED, "Set dynamic output dims attr failed");
  1495. return FAILED;
  1496. }
  1497. }
  1498. return SUCCESS;
  1499. }
  1500. } // namespace multibatch
  1501. } // namespace ge

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