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.

graph_preprocess.cc 79 kB

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
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 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
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
4 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
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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919
  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/graph_preprocess.h"
  17. #include <map>
  18. #include <set>
  19. #include <string>
  20. #include <utility>
  21. #include "common/formats/format_transfers/format_transfer_fractal_nz.h"
  22. #include "common/formats/format_transfers/format_transfer_fractal_z.h"
  23. #include "common/formats/format_transfers/format_transfer_nchw_nc1hwc0.h"
  24. #include "common/formats/format_transfers/format_transfer_nhwc_nc1hwc0.h"
  25. #include "common/formats/format_transfers/format_transfer_transpose.h"
  26. #include "common/formats/utils/formats_trans_utils.h"
  27. #include "common/helper/model_helper.h"
  28. #include "common/math/math_util.h"
  29. #include "common/op/ge_op_utils.h"
  30. #include "common/util/error_manager/error_manager.h"
  31. #include "common/formats/utils/formats_trans_utils.h"
  32. #include "framework/common/debug/ge_log.h"
  33. #include "graph/common/ge_call_wrapper.h"
  34. #include "graph/common/local_context.h"
  35. #include "graph/common/transop_util.h"
  36. #include "graph/debug/ge_attr_define.h"
  37. #include "graph/ge_context.h"
  38. #include "graph/shape_refiner.h"
  39. #include "graph/manager/graph_var_manager.h"
  40. #include "graph/manager/util/rt_context_util.h"
  41. #include "graph/optimize/graph_optimize.h"
  42. #include "graph/passes/addn_pass.h"
  43. #include "graph/passes/aicpu_constant_folding_pass.h"
  44. #include "graph/passes/assert_pass.h"
  45. #include "graph/passes/assign_pass.h"
  46. #include "graph/passes/base_pass.h"
  47. #include "graph/passes/common_subexpression_elimination_pass.h"
  48. #include "graph/passes/cond_pass.h"
  49. #include "graph/passes/cond_remove_pass.h"
  50. #include "graph/passes/constant_folding_pass.h"
  51. #include "graph/passes/constant_fuse_same_pass.h"
  52. #include "graph/passes/control_trigger_pass.h"
  53. #include "graph/passes/dimension_adjust_pass.h"
  54. #include "graph/passes/dimension_compute_pass.h"
  55. #include "graph/passes/dropout_pass.h"
  56. #include "graph/passes/enter_pass.h"
  57. #include "graph/passes/flow_ctrl_pass.h"
  58. #include "graph/passes/for_pass.h"
  59. #include "graph/passes/get_original_format_pass.h"
  60. #include "graph/passes/guarantee_const_pass.h"
  61. #include "graph/passes/hccl_group_pass.h"
  62. #include "graph/passes/hccl_memcpy_pass.h"
  63. #include "graph/passes/identity_pass.h"
  64. #include "graph/passes/infershape_pass.h"
  65. #include "graph/passes/iterator_op_pass.h"
  66. #include "graph/passes/merge_pass.h"
  67. #include "graph/passes/net_output_pass.h"
  68. #include "graph/passes/next_iteration_pass.h"
  69. #include "graph/passes/no_use_reshape_remove_pass.h"
  70. #include "graph/passes/parallel_concat_start_op_pass.h"
  71. #include "graph/passes/placeholder_with_default_pass.h"
  72. #include "graph/passes/prevent_gradient_pass.h"
  73. #include "graph/passes/print_op_pass.h"
  74. #include "graph/passes/prune_pass.h"
  75. #include "graph/passes/replace_transshape_pass.h"
  76. #include "graph/passes/replace_with_empty_const_pass.h"
  77. #include "graph/passes/resource_pair_add_control_pass.h"
  78. #include "graph/passes/resource_pair_remove_control_pass.h"
  79. #include "graph/passes/save_pass.h"
  80. #include "graph/passes/shape_operate_op_remove_pass.h"
  81. #include "graph/passes/snapshot_pass.h"
  82. #include "graph/passes/stop_gradient_pass.h"
  83. #include "graph/passes/subgraph_pass.h"
  84. #include "graph/passes/switch_data_edges_bypass.h"
  85. #include "graph/passes/switch_dead_branch_elimination.h"
  86. #include "graph/passes/switch_logic_remove_pass.h"
  87. #include "graph/passes/merge_to_stream_merge_pass.h"
  88. #include "graph/passes/switch_to_stream_switch_pass.h"
  89. #include "graph/passes/attach_stream_label_pass.h"
  90. #include "graph/passes/unused_const_pass.h"
  91. #include "graph/passes/unused_op_remove_pass.h"
  92. #include "graph/passes/var_is_initialized_op_pass.h"
  93. #include "graph/passes/variable_prepare_op_pass.h"
  94. #include "graph/preprocess/insert_op/util_insert_aipp_op.h"
  95. #include "graph/types.h"
  96. #include "graph/utils/tensor_utils.h"
  97. #include "graph/utils/type_utils.h"
  98. #include "inc/pass_manager.h"
  99. #include "init/gelib.h"
  100. #include "multi_batch_copy_graph.h"
  101. #include "runtime/dev.h"
  102. #include "graph/passes/dimension_adjust_pass.h"
  103. #include "graph/passes/link_gen_mask_nodes_pass.h"
  104. #include "graph/passes/permute_pass.h"
  105. #include "graph/passes/reshape_remove_pass.h"
  106. #include "graph/passes/same_transdata_breadth_fusion_pass.h"
  107. #include "graph/passes/transop_breadth_fusion_pass.h"
  108. #include "graph/passes/transop_depth_fusion_pass.h"
  109. #include "graph/passes/transop_nearby_allreduce_fusion_pass.h"
  110. #include "graph/passes/cast_remove_pass.h"
  111. #include "graph/passes/data_pass.h"
  112. #include "graph/passes/transop_without_reshape_fusion_pass.h"
  113. #include "graph/passes/transpose_transdata_pass.h"
  114. #include "graph/passes/variable_op_pass.h"
  115. #include "graph/passes/variable_prepare_op_pass.h"
  116. #include "graph/passes/variable_ref_delete_op_pass.h"
  117. namespace ge {
  118. namespace {
  119. static std::map<std::string, ge::DataType> output_type_str_to_datatype = {
  120. {"FP32", ge::DT_FLOAT}, {"FP16", ge::DT_FLOAT16}, {"INT8", ge::DT_INT8}, {"INT16", ge::DT_INT16},
  121. {"UINT16", ge::DT_UINT16}, {"UINT8", ge::DT_UINT8}, {"INT32", ge::DT_INT32}, {"INT64", ge::DT_INT64},
  122. {"UINT32", ge::DT_UINT32}, {"UINT64", ge::DT_UINT64}, {"DOUBLE", ge::DT_DOUBLE}};
  123. const char *const kMbatchSwitchnName = "mbatch-switch-name";
  124. // the size of user defined output datatype or format string after split by ":".
  125. const size_t kUserDefinedElementCount = 2;
  126. OpDescPtr CreateTensorShape(const GeTensorDesc &data_tensor) {
  127. GeTensorPtr tensor = MakeShared<GeTensor>();
  128. if (tensor == nullptr) {
  129. GELOGE(INTERNAL_ERROR, "Create shared ptr for GeTensor failed");
  130. return nullptr;
  131. }
  132. tensor->MutableTensorDesc().SetDataType(DT_INT32);
  133. tensor->MutableTensorDesc().SetFormat(FORMAT_ND);
  134. auto dst_ge_shape = data_tensor.GetShape();
  135. auto dim_cnt = static_cast<int64_t>(dst_ge_shape.GetDimNum());
  136. if (dim_cnt == 0) { // if the dim_cnt is 0, the tensor is a scalar
  137. tensor->MutableTensorDesc().SetShape(GeShape());
  138. int32_t dst_shape = 1;
  139. if (tensor->SetData(reinterpret_cast<const uint8_t *>(&dst_shape), sizeof(int32_t)) != GRAPH_SUCCESS) {
  140. GELOGE(INTERNAL_ERROR, "tensor set data failed");
  141. return nullptr;
  142. }
  143. } else {
  144. tensor->MutableTensorDesc().SetShape(GeShape(std::vector<int64_t>({dim_cnt})));
  145. unique_ptr<int32_t[]> dst_shape(new (std::nothrow) int32_t[dim_cnt]());
  146. if (dst_shape == nullptr) {
  147. GELOGE(INTERNAL_ERROR, "Create unique ptr failed");
  148. return nullptr;
  149. }
  150. for (int64_t i = 0; i < dim_cnt; ++i) {
  151. dst_shape[i] = dst_ge_shape.GetDim(static_cast<size_t>(i));
  152. }
  153. GE_IF_BOOL_EXEC(
  154. tensor->SetData(reinterpret_cast<const uint8_t *>(dst_shape.get()), dim_cnt * sizeof(int32_t)) != GRAPH_SUCCESS,
  155. GELOGE(INTERNAL_ERROR, "tensor set data failed");
  156. return nullptr;)
  157. }
  158. GELOGD("Create shape input dim [%s]", dst_ge_shape.ToString().c_str());
  159. return OpDescUtils::CreateConstOp(tensor);
  160. }
  161. void AddTransNodeAttr(const std::string &node_type, const GeTensorDesc &input, const GeTensorDesc &output,
  162. OpDescPtr &op_desc) {
  163. // For format transfer node, the IR definition has src/dst format attrs
  164. if (node_type == TRANSDATA) {
  165. GE_IF_BOOL_EXEC(
  166. !AttrUtils::SetStr(op_desc, FORMAT_TRANSFER_SRC_FORMAT, TypeUtils::FormatToSerialString(input.GetFormat())),
  167. GELOGW("SetStr FORMAT_TRANSFER_SRC_FORMAT failed");)
  168. GE_IF_BOOL_EXEC(
  169. !AttrUtils::SetStr(op_desc, FORMAT_TRANSFER_DST_FORMAT, TypeUtils::FormatToSerialString(output.GetFormat())),
  170. GELOGW("SetStr FORMAT_TRANSFER_DST_FORMAT failed");)
  171. }
  172. // For TransposeD node, the IR definition has perm attrs
  173. if (node_type == TRANSPOSED) {
  174. Format src_format = input.GetFormat();
  175. Format dst_format = output.GetFormat();
  176. std::vector<int64_t> perm_arg;
  177. GE_CHK_BOOL_EXEC_WARN(formats::GetPermByForamt(src_format, dst_format, perm_arg) == SUCCESS, return,
  178. "Get perm by foramt failed.");
  179. GE_CHK_BOOL_EXEC_WARN(AttrUtils::SetListInt(op_desc, PERMUTE_ATTR_PERM, perm_arg), return,
  180. "SetStr PERMUTE_ATTR_PERM failed")
  181. }
  182. // For cast node, the IR definition has src/dst attrs
  183. if (node_type == CAST) {
  184. GE_IF_BOOL_EXEC(!AttrUtils::SetInt(op_desc, CAST_ATTR_SRCT, static_cast<int64_t>(input.GetDataType())),
  185. GELOGW("SetInt CAST_ATTR_SRCT failed");)
  186. GE_IF_BOOL_EXEC(!AttrUtils::SetInt(op_desc, CAST_ATTR_DSTT, static_cast<int64_t>(output.GetDataType())),
  187. GELOGW("SetInt CAST_ATTR_DSTT failed");)
  188. GE_IF_BOOL_EXEC(!AttrUtils::SetInt(op_desc, CAST_ATTR_DST_TYPE, static_cast<int64_t>(output.GetDataType())),
  189. GELOGW("SetInt CAST_ATTR_DST_TYPE failed");)
  190. GE_IF_BOOL_EXEC(!AttrUtils::SetBool(op_desc, CAST_ATTR_TRUNCATE, false),
  191. GELOGW("SetBool CAST_ATTR_TRUNCATE failed");)
  192. }
  193. }
  194. NodePtr CreateTransNode(const std::string &name, const std::string &node_type, const GeTensorDesc &input,
  195. const GeTensorDesc &output, NodePtr &node) {
  196. if (node == nullptr) {
  197. GELOGE(PARAM_INVALID, "node is null.");
  198. return nullptr;
  199. }
  200. auto graph = node->GetOwnerComputeGraph();
  201. if (graph == nullptr) {
  202. GELOGE(PARAM_INVALID, "Owner graph is null, node name:%s.", node->GetName().c_str());
  203. return nullptr;
  204. }
  205. auto index = TransOpUtil::GetTransOpDataIndex(node_type);
  206. if (index < 0) {
  207. ErrorManager::GetInstance().ATCReportErrMessage(
  208. "E19025", {"situation", "reason"},
  209. {"The trans node type[" + node_type + "]", "it must be " + TransOpUtil::TransopMapToString()});
  210. GELOGE(INTERNAL_ERROR, "The trans node type %s does not exists", node_type.c_str());
  211. return nullptr;
  212. }
  213. OpDescPtr op_desc = MakeShared<OpDesc>(name, node_type);
  214. if (op_desc == nullptr) {
  215. GELOGE(INTERNAL_ERROR, "Create shared ptr for OpDesc failed");
  216. return nullptr;
  217. }
  218. // for data dump
  219. GE_IF_BOOL_EXEC(
  220. !AttrUtils::SetListStr(op_desc, ATTR_NAME_DATA_DUMP_ORIGIN_OP_NAMES, std::move(std::vector<std::string>())),
  221. GELOGW("CreateTransNode: SetListStr failed");)
  222. // Default single input and single output
  223. auto ret = op_desc->AddInputDesc(input);
  224. if (ret != GRAPH_SUCCESS) {
  225. GELOGE(INTERNAL_ERROR, "Failed to add input desc when create node %s type %s", name.c_str(), node_type.c_str());
  226. return nullptr;
  227. }
  228. ret = op_desc->AddOutputDesc(output);
  229. if (ret != GRAPH_SUCCESS) {
  230. GELOGE(INTERNAL_ERROR, "Failed to add output desc when create node %s type %s", name.c_str(), node_type.c_str());
  231. return nullptr;
  232. }
  233. AddTransNodeAttr(node_type, input, output, op_desc);
  234. NodePtr shape_node = nullptr;
  235. if (node_type == RESHAPE) {
  236. auto shape_desc = CreateTensorShape(output);
  237. if (shape_desc == nullptr) {
  238. GELOGE(INTERNAL_ERROR, "Failed to add shape for reshape %s, can not create the shape input",
  239. node->GetName().c_str());
  240. return nullptr;
  241. }
  242. ret = op_desc->AddInputDesc(shape_desc->GetOutputDesc(0));
  243. if (ret != GRAPH_SUCCESS) {
  244. GELOGE(INTERNAL_ERROR, "Failed to add the first input for reshape %s", name.c_str());
  245. return nullptr;
  246. }
  247. shape_node = graph->AddNode(shape_desc);
  248. if (shape_node == nullptr) {
  249. GELOGE(INTERNAL_ERROR, "Failed to add shape node for reshape %s, can not add the shape to graph", name.c_str());
  250. return nullptr;
  251. }
  252. }
  253. auto trans_node = graph->AddNode(op_desc);
  254. if (trans_node == nullptr) {
  255. GELOGE(INTERNAL_ERROR, "Failed to add trans node %s to graph", name.c_str());
  256. return nullptr;
  257. }
  258. if (node_type == RESHAPE) {
  259. if (GraphUtils::AddEdge(shape_node->GetOutDataAnchor(0), trans_node->GetInDataAnchor(1)) != GRAPH_SUCCESS) {
  260. GELOGE(INTERNAL_ERROR, "Failed to add shape node for reshape %s, can not add the edge", name.c_str());
  261. return nullptr;
  262. }
  263. }
  264. return trans_node;
  265. }
  266. Status RecoverOneTransNodeForVar(const std::string &name, const TransNodeInfo &trans_node_info, NodePtr node,
  267. NodePtr &trans_node) {
  268. GE_CHECK_NOTNULL(node);
  269. trans_node = CreateTransNode(name, trans_node_info.node_type, trans_node_info.output, trans_node_info.input, node);
  270. if (trans_node == nullptr) {
  271. return INTERNAL_ERROR;
  272. }
  273. auto ret = GraphUtils::ReplaceNodeDataAnchors(trans_node, node, {}, {0});
  274. if (ret != GRAPH_SUCCESS) {
  275. GELOGE(INTERNAL_ERROR, "Failed to replace out anchors when recover trans node for %s type %s",
  276. node->GetName().c_str(), node->GetType().c_str());
  277. return INTERNAL_ERROR;
  278. }
  279. ret = GraphUtils::AddEdge(node->GetOutDataAnchor(0), trans_node->GetInDataAnchor(0));
  280. if (ret != GRAPH_SUCCESS) {
  281. GELOGE(INTERNAL_ERROR, "Failed to connect node %s to trans node %s", node->GetName().c_str(),
  282. trans_node->GetName().c_str());
  283. return INTERNAL_ERROR;
  284. }
  285. ret = GraphUtils::MoveOutCtrlEdges(node, trans_node);
  286. if (ret != GRAPH_SUCCESS) {
  287. GELOGE(INTERNAL_ERROR, "Failed to move out control edges from %s to %s when recover trans node.",
  288. node->GetName().c_str(), trans_node->GetName().c_str());
  289. return INTERNAL_ERROR;
  290. }
  291. return SUCCESS;
  292. }
  293. Status RecoverOneTransNodeForVarRef(const std::string &name, const TransNodeInfo &trans_node_info, NodePtr node,
  294. NodePtr &trans_node) {
  295. GE_CHECK_NOTNULL(node);
  296. trans_node = CreateTransNode(name, trans_node_info.node_type, trans_node_info.input, trans_node_info.output, node);
  297. if (trans_node == nullptr) {
  298. return INTERNAL_ERROR;
  299. }
  300. auto ret = GraphUtils::ReplaceNodeDataAnchors(trans_node, node, {0}, {});
  301. if (ret != GRAPH_SUCCESS) {
  302. GELOGE(INTERNAL_ERROR, "Failed to replace int anchors when recover trans node for %s type %s",
  303. node->GetName().c_str(), node->GetType().c_str());
  304. return INTERNAL_ERROR;
  305. }
  306. ret = GraphUtils::AddEdge(trans_node->GetOutDataAnchor(0), node->GetInDataAnchor(0));
  307. if (ret != GRAPH_SUCCESS) {
  308. GELOGE(INTERNAL_ERROR, "Failed to connect trans node %s to node %s", trans_node->GetName().c_str(),
  309. node->GetName().c_str());
  310. return INTERNAL_ERROR;
  311. }
  312. ret = GraphUtils::MoveInCtrlEdges(node, trans_node);
  313. if (ret != GRAPH_SUCCESS) {
  314. GELOGE(INTERNAL_ERROR, "Failed to move int control edges from %s to %s when recover trans node.",
  315. node->GetName().c_str(), trans_node->GetName().c_str());
  316. return INTERNAL_ERROR;
  317. }
  318. return SUCCESS;
  319. }
  320. Status UpdateVarFormats(const NodePtr &var, const GeTensorDesc &tensor_desc) {
  321. GE_IF_BOOL_EXEC(var == nullptr, GELOGW("node : var is nullptr"); return INTERNAL_ERROR);
  322. GE_CHECK_NOTNULL(var->GetOpDesc());
  323. if (var->GetOpDesc()->GetOutputsSize() > 0) {
  324. auto output_desc = var->GetOpDesc()->GetOutputDesc(0);
  325. output_desc.SetFormat(tensor_desc.GetFormat());
  326. output_desc.SetDataType(tensor_desc.GetDataType());
  327. output_desc.SetShape(tensor_desc.GetShape());
  328. output_desc.SetOriginFormat(tensor_desc.GetOriginFormat());
  329. output_desc.SetOriginDataType(tensor_desc.GetOriginDataType());
  330. output_desc.SetOriginShape(tensor_desc.GetOriginShape());
  331. GE_IF_BOOL_EXEC(var->GetOpDesc()->UpdateOutputDesc(0, output_desc) != GRAPH_SUCCESS,
  332. GELOGE(INTERNAL_ERROR, "UpdateOutputDesc failed");
  333. return INTERNAL_ERROR;);
  334. }
  335. if (var->GetOpDesc()->GetInputsSize() > 0) {
  336. auto desc = var->GetOpDesc()->GetInputDesc(0);
  337. desc.SetFormat(tensor_desc.GetFormat());
  338. desc.SetDataType(tensor_desc.GetDataType());
  339. desc.SetShape(tensor_desc.GetShape());
  340. desc.SetOriginFormat(tensor_desc.GetOriginFormat());
  341. desc.SetOriginDataType(tensor_desc.GetOriginDataType());
  342. desc.SetOriginShape(tensor_desc.GetOriginShape());
  343. GE_IF_BOOL_EXEC(var->GetOpDesc()->UpdateInputDesc(0, desc) != GRAPH_SUCCESS,
  344. GELOGE(INTERNAL_ERROR, "UpdateInputDesc failed");
  345. return INTERNAL_ERROR;)
  346. }
  347. return SUCCESS;
  348. }
  349. Status RecoverTransRoadForVar(const NodePtr &var, const VarTransRoad &road) {
  350. GE_CHECK_NOTNULL(var);
  351. int index = 0;
  352. NodePtr last_node = var;
  353. for (auto iter = road.rbegin(); iter != road.rend(); ++iter) {
  354. auto trans_name = var->GetName() + "_trans_" + std::to_string(index++);
  355. auto ret = RecoverOneTransNodeForVar(trans_name, *iter, last_node, last_node);
  356. if (ret != SUCCESS) {
  357. ErrorManager::GetInstance().ATCReportErrMessage(
  358. "E15001", {"variable", "index", "type"}, {var->GetName(), std::to_string(index), iter->node_type});
  359. GELOGE(INTERNAL_ERROR, "Failed to recover trans node for variable %s, index %d, type %s", var->GetName().c_str(),
  360. index, iter->node_type.c_str());
  361. return INTERNAL_ERROR;
  362. }
  363. // set stream_label
  364. OpDescPtr var_desc = var->GetOpDesc();
  365. GE_CHECK_NOTNULL(var_desc);
  366. std::string stream_label;
  367. (void)AttrUtils::GetStr(var_desc, ATTR_NAME_STREAM_LABEL, stream_label);
  368. if (!stream_label.empty()) {
  369. GE_CHK_STATUS_RET(SetStreamLabel(last_node, stream_label), "set stream label failed");
  370. }
  371. GE_CHK_BOOL_EXEC((ge::AttrUtils::SetBool(last_node->GetOpDesc(), ge::ATTR_INSERTED_BY_GE, true)),
  372. return INTERNAL_ERROR, "Set attr ATTR_INSERTED_BY_GE failed.");
  373. GELOGD("Recover trans node %s type %s success", trans_name.c_str(), iter->node_type.c_str());
  374. }
  375. if (road.empty()) {
  376. return SUCCESS;
  377. }
  378. return UpdateVarFormats(var, road.rbegin()->output);
  379. }
  380. Status RecoverTransRoadForVarRef(const std::set<NodePtr> &nodes, const VarTransRoad &road) {
  381. for (auto &var : nodes) {
  382. GE_CHECK_NOTNULL(var);
  383. int index = 0;
  384. NodePtr last_node = var;
  385. GELOGI("Recover trans nodes for variable ref %s", var->GetName().c_str());
  386. for (auto iter = road.rbegin(); iter != road.rend(); ++iter) {
  387. auto trans_name = var->GetName() + "_trans_" + std::to_string(index++);
  388. auto ret = RecoverOneTransNodeForVarRef(trans_name, *iter, last_node, last_node);
  389. if (ret != SUCCESS) {
  390. ErrorManager::GetInstance().ATCReportErrMessage(
  391. "E15001", {"variable", "index", "type"}, {var->GetName(), std::to_string(index), iter->node_type});
  392. GELOGE(INTERNAL_ERROR, "Failed to recover trans node for variable %s, index %d, type %s",
  393. var->GetName().c_str(), index, iter->node_type.c_str());
  394. return INTERNAL_ERROR;
  395. }
  396. // set stream_label
  397. OpDescPtr var_desc = var->GetOpDesc();
  398. GE_CHECK_NOTNULL(var_desc);
  399. std::string stream_label;
  400. (void)AttrUtils::GetStr(var_desc, ATTR_NAME_STREAM_LABEL, stream_label);
  401. if (!stream_label.empty()) {
  402. GE_CHK_STATUS_RET(SetStreamLabel(last_node, stream_label), "set stream label failed");
  403. }
  404. GE_CHK_BOOL_EXEC((ge::AttrUtils::SetBool(last_node->GetOpDesc(), ge::ATTR_INSERTED_BY_GE, true)),
  405. return INTERNAL_ERROR, "Set attr ATTR_INSERTED_BY_GE failed.");
  406. }
  407. if (!(road.empty()) && (UpdateVarFormats(var, road.rbegin()->output) != SUCCESS)) {
  408. return INTERNAL_ERROR;
  409. }
  410. }
  411. return SUCCESS;
  412. }
  413. using VarNamesToRefs = std::map<std::string, std::set<NodePtr>>;
  414. VarNamesToRefs CollectVarNamesToRefs(const ComputeGraphPtr &graph) {
  415. VarNamesToRefs names_to_refs;
  416. std::string var_name;
  417. if (graph == nullptr) {
  418. GELOGE(PARAM_INVALID, "graph is null.");
  419. return names_to_refs;
  420. }
  421. for (auto &node : graph->GetAllNodes()) {
  422. if (node->GetType() != VARIABLE) {
  423. continue;
  424. }
  425. if (AttrUtils::GetStr(node->GetOpDesc(), REF_VAR_SRC_VAR_NAME, var_name)) {
  426. (void)names_to_refs[var_name].insert(node);
  427. }
  428. }
  429. return names_to_refs;
  430. }
  431. Status TransferShape2NC1HWC0(Format src_format, const std::vector<int64_t> &src_shape, DataType dt, Format dst_format,
  432. std::vector<int64_t> &dst_shape) {
  433. if (src_format == FORMAT_NCHW) {
  434. formats::FormatTransferNchwNc1hwc0 transfer;
  435. if (transfer.TransShape(src_format, src_shape, dt, dst_format, dst_shape) != SUCCESS) {
  436. GELOGE(INTERNAL_ERROR, "TransShape failed");
  437. return FAILED;
  438. }
  439. } else if (src_format == FORMAT_NHWC) {
  440. formats::FormatTransferNhwcNc1hwc0 transfer;
  441. if (transfer.TransShape(src_format, src_shape, dt, dst_format, dst_shape) != SUCCESS) {
  442. GELOGE(INTERNAL_ERROR, "TransShape failed");
  443. return FAILED;
  444. }
  445. }
  446. return SUCCESS;
  447. }
  448. Status ModifyInputFormatAndShape(NodePtr &node_ptr) {
  449. GE_CHECK_NOTNULL(node_ptr);
  450. auto op_desc = node_ptr->GetOpDesc();
  451. GE_CHECK_NOTNULL(op_desc);
  452. const GeTensorDescPtr &input = op_desc->MutableInputDesc(0);
  453. GE_CHECK_NOTNULL(input);
  454. ge::Format old_format = input->GetFormat();
  455. std::vector<int64_t> old_shape = input->GetShape().GetDims();
  456. ge::DataType dt = input->GetDataType();
  457. std::vector<int64_t> dst_shape_dims;
  458. if (TransferShape2NC1HWC0(old_format, old_shape, dt, FORMAT_NC1HWC0, dst_shape_dims) != SUCCESS) {
  459. GELOGE(INTERNAL_ERROR, "Trans shape failed");
  460. return FAILED;
  461. }
  462. input->SetFormat(FORMAT_NC1HWC0);
  463. input->SetShape(ge::GeShape(dst_shape_dims));
  464. auto output = op_desc->MutableOutputDesc(0);
  465. GE_CHECK_NOTNULL(output);
  466. output->SetFormat(FORMAT_NC1HWC0);
  467. output->SetShape(ge::GeShape(dst_shape_dims));
  468. int64_t size = 0;
  469. graphStatus graph_status = TensorUtils::GetTensorMemorySizeInBytes(*output, size);
  470. if (graph_status != ge::GRAPH_SUCCESS) {
  471. GELOGE(graph_status, "GetTensorSizeInBytes failed!");
  472. return FAILED;
  473. }
  474. ge::TensorUtils::SetSize(*output, size);
  475. ge::TensorUtils::SetSize(*input, size);
  476. return SUCCESS;
  477. }
  478. Status ModifyFormatAndShapeForSingleTensor(const GeTensorDescPtr &input_output) {
  479. GE_CHECK_NOTNULL(input_output);
  480. ge::Format old_format = input_output->GetFormat();
  481. std::vector<int64_t> old_shape = input_output->GetShape().GetDims();
  482. ge::DataType dt = input_output->GetDataType();
  483. std::vector<int64_t> dst_shape_dims;
  484. if (TransferShape2NC1HWC0(old_format, old_shape, dt, FORMAT_NC1HWC0, dst_shape_dims) != SUCCESS) {
  485. GELOGE(INTERNAL_ERROR, "Trans shape failed");
  486. return FAILED;
  487. }
  488. input_output->SetFormat(FORMAT_NC1HWC0);
  489. input_output->SetShape(ge::GeShape(dst_shape_dims));
  490. return SUCCESS;
  491. }
  492. Status ModifyDataNetOutputFormatAndShape(OpDescPtr &op_desc, uint32_t index, Format storage_format,
  493. vector<int64_t> &dst_shape_dims) {
  494. GE_CHECK_NOTNULL(op_desc);
  495. const GeTensorDescPtr &input = op_desc->MutableInputDesc(index);
  496. GE_CHECK_NOTNULL(input);
  497. ge::Format old_format = input->GetFormat();
  498. std::vector<int64_t> old_shape = input->GetShape().GetDims();
  499. input->SetShape(ge::GeShape(dst_shape_dims));
  500. input->SetFormat(storage_format);
  501. auto output = op_desc->MutableOutputDesc(index);
  502. GE_CHECK_NOTNULL(output);
  503. output->SetShape(ge::GeShape(dst_shape_dims));
  504. output->SetFormat(storage_format);
  505. if (!output->MutableShape().IsUnknownShape()) {
  506. int64_t size = 0;
  507. graphStatus graph_status = TensorUtils::GetTensorMemorySizeInBytes(*output, size);
  508. if (graph_status != ge::GRAPH_SUCCESS) {
  509. GELOGE(graph_status, "GetTensorSizeInBytes failed!");
  510. return FAILED;
  511. }
  512. ge::TensorUtils::SetSize(*input, size);
  513. ge::TensorUtils::SetSize(*output, size);
  514. GELOGI("Modify Data NetOutput format and shape success, node:%s, index:%d, old_shape:%s, old_Format:%s, "
  515. "new_shape:%s, new_format:%s, new_size:%lu",
  516. op_desc->GetName().c_str(), index, formats::JoinToString(old_shape).c_str(),
  517. ge::TypeUtils::FormatToSerialString(old_format).c_str(), formats::JoinToString(dst_shape_dims).c_str(),
  518. ge::TypeUtils::FormatToSerialString(storage_format).c_str(), size);
  519. }
  520. return SUCCESS;
  521. }
  522. Status CheckIfDynamicBatchScene(NodePtr &data_node, bool &is_dynamic_batch, NodePtr &switchn_node) {
  523. is_dynamic_batch = false;
  524. std::string related_node_name;
  525. if (AttrUtils::GetStr(data_node->GetOpDesc(), kMbatchSwitchnName, related_node_name)) {
  526. if (related_node_name.empty()) {
  527. ErrorManager::GetInstance().ATCReportErrMessage(
  528. "E15002", {"opname", "value", "reason"}, {data_node->GetName(), "flag", "but the value is empty"});
  529. GELOGE(INTERNAL_ERROR, "The data node %s has switchn node flag, but the value is empty",
  530. data_node->GetName().c_str());
  531. return INTERNAL_ERROR;
  532. }
  533. for (const NodePtr &next_node : data_node->GetOutNodes()) {
  534. if (next_node->GetName() == related_node_name) {
  535. switchn_node = next_node;
  536. break;
  537. }
  538. }
  539. if (switchn_node == nullptr) {
  540. ErrorManager::GetInstance().ATCReportErrMessage(
  541. "E15002", {"opname", "value", "reason"},
  542. {data_node->GetName(), related_node_name, "but can not find it on the graph"});
  543. GELOGE(INTERNAL_ERROR, "The data node %s has switchn node %s, but can not find it on the graph",
  544. data_node->GetName().c_str(), related_node_name.c_str());
  545. return INTERNAL_ERROR;
  546. }
  547. is_dynamic_batch = true;
  548. }
  549. return SUCCESS;
  550. }
  551. bool CheckOpType(const NodePtr &node, const std::string type) {
  552. if (node->GetType() == type) {
  553. return true;
  554. }
  555. return false;
  556. }
  557. Status CheckIfNeedSetNdFormat(const NodePtr &node_ptr) {
  558. auto op = node_ptr->GetOpDesc();
  559. GE_CHECK_NOTNULL(op);
  560. auto inputDescsPtr = op->GetAllInputsDescPtr();
  561. auto outputDescsPtr = op->GetAllOutputsDescPtr();
  562. ge::Format format = ge::FORMAT_ND;
  563. // if user set shape larger than 4, inferformat may set NCHW or NHWC, GE should set ND before FE
  564. // process, otherwise fe will insert transdata.
  565. for (auto &inputDescPtr : inputDescsPtr) {
  566. GE_CHECK_NOTNULL(inputDescPtr);
  567. if ((inputDescPtr->GetShape().GetDims().size() > ge::DIM_DEFAULT_SIZE) &&
  568. ((inputDescPtr->GetFormat() == ge::FORMAT_NCHW) || (inputDescPtr->GetFormat() == ge::FORMAT_NHWC))) {
  569. GELOGI("The node inputdesc [%s] format need to be set ND", op->GetName().c_str());
  570. inputDescPtr->SetFormat(format);
  571. inputDescPtr->SetOriginFormat(format);
  572. }
  573. }
  574. for (auto &outputDescPtr : outputDescsPtr) {
  575. GE_CHECK_NOTNULL(outputDescPtr);
  576. if ((outputDescPtr->GetShape().GetDims().size() > ge::DIM_DEFAULT_SIZE) &&
  577. ((outputDescPtr->GetFormat() == ge::FORMAT_NCHW) || (outputDescPtr->GetFormat() == ge::FORMAT_NHWC))) {
  578. GELOGI("The node outputdesc [%s] format need to be set ND", op->GetName().c_str());
  579. outputDescPtr->SetFormat(format);
  580. outputDescPtr->SetOriginFormat(format);
  581. }
  582. }
  583. return SUCCESS;
  584. }
  585. // A new function ending in 'DynShape' has been added for the dynamic shape processing.
  586. // In the dynamic shape process, transnode insertion by FE is advanced to the stage of whole
  587. // graph optimization, GE only sets the final data_type/format/shape information for variable,
  588. // data and netoutput, and no longer inserts the transnode.
  589. Status ProcessInputDtDynShape(NodePtr &node_ptr, bool &is_dynamic_batch, NodePtr &switchn_node, DataType &dt_set) {
  590. GE_CHECK_NOTNULL(node_ptr);
  591. auto op_desc = node_ptr->GetOpDesc();
  592. GE_CHECK_NOTNULL(op_desc);
  593. const GeTensorDescPtr &input = op_desc->MutableInputDesc(0);
  594. GE_CHECK_NOTNULL(input);
  595. ge::DataType src_dtype = input->GetDataType();
  596. if (src_dtype == dt_set) {
  597. GELOGI("The node name, %s dtype is fp16", node_ptr->GetName().c_str());
  598. return SUCCESS;
  599. }
  600. input->SetDataType(dt_set);
  601. int64_t input_shape_size = 0;
  602. int64_t output_shape_size = 0;
  603. ge::graphStatus input_graph_status = ge::TensorUtils::GetTensorSizeInBytes(*input, input_shape_size);
  604. ge::graphStatus output_graph_status = ge::TensorUtils::GetTensorMemorySizeInBytes(*input, output_shape_size);
  605. if (input_graph_status != ge::GRAPH_SUCCESS && output_graph_status != ge::GRAPH_SUCCESS) {
  606. GELOGE(GRAPH_FAILED, "GetTensorSize failed!");
  607. return FAILED;
  608. }
  609. ge::TensorUtils::SetSize(*input, input_shape_size);
  610. const GeTensorDescPtr &output = op_desc->MutableOutputDesc(0);
  611. GE_CHECK_NOTNULL(output);
  612. output->SetDataType(dt_set);
  613. ge::TensorUtils::SetSize(*output, output_shape_size);
  614. if (is_dynamic_batch) {
  615. GELOGI("The node [%s] dtype set fp16", switchn_node->GetName().c_str());
  616. auto switchn_op_desc = switchn_node->GetOpDesc();
  617. GE_CHECK_NOTNULL(switchn_op_desc);
  618. auto switchn_input = switchn_op_desc->MutableInputDesc(0);
  619. GE_CHECK_NOTNULL(switchn_input);
  620. switchn_input->SetDataType(dt_set);
  621. for (uint32_t i = 0; i < switchn_node->GetAllOutDataAnchorsSize(); ++i) {
  622. const GeTensorDescPtr &switchn_output = switchn_op_desc->MutableOutputDesc(i);
  623. GE_CHECK_NOTNULL(switchn_output);
  624. switchn_output->SetDataType(dt_set);
  625. }
  626. }
  627. return SUCCESS;
  628. }
  629. Status ProcessInputNC1HWC0DynShape(NodePtr &node_ptr, bool &is_dynamic_batch, NodePtr &switchn_node) {
  630. GE_CHECK_NOTNULL(node_ptr);
  631. auto op_desc = node_ptr->GetOpDesc();
  632. GE_CHECK_NOTNULL(op_desc);
  633. const GeTensorDescPtr &input = op_desc->MutableInputDesc(0);
  634. GE_CHECK_NOTNULL(input);
  635. ge::Format old_format = input->GetFormat();
  636. ge::GeShape old_shape = input->GetShape();
  637. bool support = ((old_format == FORMAT_NC1HWC0) || (old_format == FORMAT_NCHW) || (old_format == FORMAT_NHWC));
  638. if (!support) {
  639. ErrorManager::GetInstance().ATCReportErrMessage(
  640. "E19014", {"opname", "value", "reason"},
  641. {op_desc->GetName(), "format[" + TypeUtils::FormatToSerialString(old_format) + "]",
  642. "only support FORMAT_NC1HWC0,FORMAT_NCHW,FORMAT_NHWC"});
  643. GELOGE(INTERNAL_ERROR, "The format [%s] is unsupported", TypeUtils::FormatToSerialString(old_format).c_str());
  644. return FAILED;
  645. }
  646. if (ModifyInputFormatAndShape(node_ptr) != SUCCESS) {
  647. GELOGE(INTERNAL_ERROR, "modify format and shape failed");
  648. return FAILED;
  649. }
  650. if (is_dynamic_batch) {
  651. auto switchn_op_desc = switchn_node->GetOpDesc();
  652. GE_CHECK_NOTNULL(switchn_op_desc);
  653. const GeTensorDescPtr &switchn_input = switchn_op_desc->MutableInputDesc(0);
  654. if (ModifyFormatAndShapeForSingleTensor(switchn_input) != SUCCESS) {
  655. GELOGE(INTERNAL_ERROR, "modify format and shape failed");
  656. return FAILED;
  657. }
  658. for (uint32_t i = 0; i < switchn_node->GetAllOutDataAnchorsSize(); ++i) {
  659. auto switchn_output = switchn_op_desc->MutableOutputDesc(i);
  660. GE_CHECK_NOTNULL(switchn_output);
  661. old_format = switchn_output->GetFormat();
  662. old_shape = switchn_output->GetShape();
  663. if (ModifyFormatAndShapeForSingleTensor(switchn_output) != SUCCESS) {
  664. GELOGE(INTERNAL_ERROR, "modify format and shape failed");
  665. return FAILED;
  666. }
  667. }
  668. }
  669. return SUCCESS;
  670. }
  671. Status ProcessDataNodeDynShape(NodePtr &node_ptr) {
  672. auto op_desc = node_ptr->GetOpDesc();
  673. GE_CHECK_NOTNULL(op_desc);
  674. string set_dt_str;
  675. if (!ge::AttrUtils::GetStr(node_ptr->GetOpDesc(), ATTR_ATC_USER_DEFINE_DATATYPE, set_dt_str)) {
  676. return SUCCESS;
  677. }
  678. DataType dt_set = TypeUtils::SerialStringToDataType(set_dt_str);
  679. GELOGI("input_fp16 is found, the node name is %s.", node_ptr->GetName().c_str());
  680. bool is_dynamic_batch = false;
  681. NodePtr switchn_node = nullptr;
  682. if (CheckIfDynamicBatchScene(node_ptr, is_dynamic_batch, switchn_node)) {
  683. GELOGE(INTERNAL_ERROR, "CheckIfDynamicBatchScene failed");
  684. return FAILED;
  685. }
  686. if (ProcessInputDtDynShape(node_ptr, is_dynamic_batch, switchn_node, dt_set) != SUCCESS) {
  687. GELOGE(INTERNAL_ERROR, "ProcessInputFP16 failed");
  688. return FAILED;
  689. }
  690. // check if need to set format
  691. string set_format;
  692. bool ret = ge::AttrUtils::GetStr(node_ptr->GetOpDesc(), ATTR_ATC_USER_DEFINE_FORMAT, set_format);
  693. if (ret && (!set_format.empty()) && TypeUtils::SerialStringToFormat(set_format) == FORMAT_NC1HWC0) {
  694. GELOGI("The format of node [%s] should be set NC1HWC0.", node_ptr->GetName().c_str());
  695. if (ProcessInputNC1HWC0DynShape(node_ptr, is_dynamic_batch, switchn_node) != SUCCESS) {
  696. GELOGE(INTERNAL_ERROR, "ProcessInputNC1HWC0 failed");
  697. return FAILED;
  698. }
  699. }
  700. return SUCCESS;
  701. }
  702. Status GetStorageFormatAndShape(OpDescPtr &op_desc, const GeTensorDescPtr &tensor_desc_ptr,
  703. Format &storage_format, vector<int64_t> &dst_shape_dims) {
  704. GE_CHECK_NOTNULL(op_desc);
  705. GE_CHECK_NOTNULL(tensor_desc_ptr);
  706. storage_format = FORMAT_RESERVED;
  707. int64_t format = FORMAT_RESERVED;
  708. dst_shape_dims.clear();
  709. if (ge::AttrUtils::GetInt(*tensor_desc_ptr, ATTR_NAME_STORAGE_FORMAT, format)) {
  710. storage_format = static_cast<Format>(format);
  711. vector<int32_t> storage_shape;
  712. if (ge::AttrUtils::GetListInt(*tensor_desc_ptr, ATTR_NAME_STORAGE_SHAPE, storage_shape)) {
  713. for (auto dim : storage_shape) {
  714. dst_shape_dims.push_back(static_cast<int64_t>(dim));
  715. }
  716. GELOGI("Update node by storage format, node: [%s], storage_format: [%s], storage_shape:[%s]",
  717. op_desc->GetName().c_str(), TypeUtils::FormatToSerialString(storage_format).c_str(),
  718. formats::JoinToString(storage_shape).c_str());
  719. } else {
  720. ErrorManager::GetInstance().ATCReportErrMessage(
  721. "15003", {"opname", "format"},
  722. {op_desc->GetName(), TypeUtils::FormatToSerialString(storage_format)});
  723. GELOGE(PARAM_INVALID, "Update node by storage format failed, storage_shape not set. "
  724. "node: [%s], storage_format [%s]",
  725. op_desc->GetName().c_str(), TypeUtils::FormatToSerialString(storage_format).c_str());
  726. return FAILED;
  727. }
  728. ge::Format old_format = tensor_desc_ptr->GetFormat();
  729. auto old_shape = tensor_desc_ptr->GetShape().GetDims();
  730. if (old_format == storage_format && old_shape == dst_shape_dims) {
  731. GELOGI("Update node by storage format, not changed.");
  732. storage_format = FORMAT_RESERVED;
  733. return SUCCESS;
  734. }
  735. }
  736. return SUCCESS;
  737. }
  738. Status ProcessNetoutputNodeFp16Nc1hwc0DynShape(GeTensorDesc &src_desc, GeTensorDescPtr &net_output_input_desc,
  739. NodePtr &node) {
  740. bool is_dynamic = CheckOpType(node, MERGE);
  741. auto src_op_desc = node->GetOpDesc();
  742. GE_CHECK_NOTNULL(src_op_desc);
  743. ge::GeShape src_shape = src_desc.GetShape();
  744. ge::Format src_format = src_desc.GetFormat();
  745. net_output_input_desc->SetDataType(DT_FLOAT16);
  746. if (is_dynamic) {
  747. auto merge_output = src_op_desc->MutableOutputDesc(0);
  748. GE_CHECK_NOTNULL(merge_output);
  749. merge_output->SetDataType(DT_FLOAT16);
  750. for (uint32_t i = 0; i < node->GetAllInDataAnchorsSize(); ++i) {
  751. auto merge_input = src_op_desc->MutableInputDesc(i);
  752. GE_CHECK_NOTNULL(merge_input);
  753. merge_input->SetDataType(DT_FLOAT16);
  754. }
  755. }
  756. std::vector<int64_t> dst_shape_dims;
  757. std::vector<int64_t> src_shape_dims = src_shape.GetDims();
  758. if (TransferShape2NC1HWC0(src_format, src_shape_dims, DT_FLOAT16, FORMAT_NC1HWC0, dst_shape_dims) != SUCCESS) {
  759. GELOGE(INTERNAL_ERROR, "Trans shape failed");
  760. return FAILED;
  761. }
  762. ge::GeShape dst_shape(dst_shape_dims);
  763. net_output_input_desc->SetFormat(FORMAT_NC1HWC0);
  764. net_output_input_desc->SetShape(dst_shape);
  765. if (is_dynamic) {
  766. auto merge_out = src_op_desc->MutableOutputDesc(0);
  767. GE_CHECK_NOTNULL(merge_out);
  768. if (ModifyFormatAndShapeForSingleTensor(merge_out) != SUCCESS) {
  769. GELOGE(INTERNAL_ERROR, "modify format and shape failed");
  770. return FAILED;
  771. }
  772. for (uint32_t i = 0; i < node->GetAllInDataAnchorsSize(); ++i) {
  773. auto merge_in = src_op_desc->MutableInputDesc(i);
  774. GE_CHECK_NOTNULL(merge_in);
  775. if (ModifyFormatAndShapeForSingleTensor(merge_in) != SUCCESS) {
  776. GELOGE(INTERNAL_ERROR, "modify format and shape failed");
  777. return FAILED;
  778. }
  779. }
  780. }
  781. return SUCCESS;
  782. }
  783. bool NeedUpdateDtByOutputTypeParm(OpDescPtr &netout_desc, uint32_t &index, ge::DataType &dt) {
  784. GE_CHECK_NOTNULL(netout_desc);
  785. vector<string> output_dt_str;
  786. if (ge::AttrUtils::GetListStr(netout_desc, ATTR_ATC_USER_DEFINE_DATATYPE, output_dt_str)) {
  787. for (auto dt_str : output_dt_str) {
  788. vector<string> dt_str_split = StringUtils::Split(dt_str, ':');
  789. if (dt_str_split.size() == kUserDefinedElementCount) {
  790. if (dt_str_split[0] == to_string(index)) {
  791. dt = TypeUtils::SerialStringToDataType(dt_str_split[1]);
  792. GELOGI("Find netoutput node output %u datatype should be set %s .", index,
  793. TypeUtils::DataTypeToSerialString(dt).c_str());
  794. return true;
  795. }
  796. }
  797. }
  798. }
  799. return false;
  800. }
  801. bool NeedUpdateFormatByOutputTypeParm(OpDescPtr &netout_desc, uint32_t &index) {
  802. GE_CHECK_NOTNULL(netout_desc);
  803. vector<string> output_format_str;
  804. if (ge::AttrUtils::GetListStr(netout_desc, ATTR_ATC_USER_DEFINE_FORMAT, output_format_str)) {
  805. for (auto format_str : output_format_str) {
  806. vector<string> format_str_split = StringUtils::Split(format_str, ':');
  807. if (format_str_split.size() == kUserDefinedElementCount) {
  808. if (format_str_split[0] == to_string(index)) {
  809. GELOGI("Find netoutput node output %u format should be set NC1HWC0.", index);
  810. return true;
  811. }
  812. }
  813. }
  814. }
  815. return false;
  816. }
  817. Status ProcessNetoutputNodeDynShape(NodePtr &node) {
  818. auto op_desc = node->GetOpDesc();
  819. GE_CHECK_NOTNULL(op_desc);
  820. ge::DataType output_data_type = ge::DT_FLOAT;
  821. for (const auto &in_anchor : node->GetAllInDataAnchors()) {
  822. auto index = static_cast<uint32_t>(in_anchor->GetIdx());
  823. auto peer_out = in_anchor->GetPeerOutAnchor();
  824. GE_CHECK_NOTNULL(peer_out);
  825. auto src_node = peer_out->GetOwnerNode();
  826. GE_CHECK_NOTNULL(src_node);
  827. bool is_dynamic = CheckOpType(src_node, MERGE);
  828. OpDescPtr src_op_desc = src_node->GetOpDesc();
  829. GE_CHECK_NOTNULL(src_op_desc);
  830. auto net_output_input_desc = op_desc->MutableInputDesc(index);
  831. GE_CHECK_NOTNULL(net_output_input_desc);
  832. ge::GeShape old_shape = net_output_input_desc->GetShape();
  833. ge::Format old_format = net_output_input_desc->GetFormat();
  834. ge::DataType old_dtype = net_output_input_desc->GetDataType();
  835. // Update datatype
  836. if (NeedUpdateDtByOutputTypeParm(op_desc, index, output_data_type)) {
  837. GELOGI("Enter into process output_type schedule");
  838. net_output_input_desc->SetDataType(output_data_type);
  839. if (is_dynamic) {
  840. auto merge_output = src_op_desc->MutableOutputDesc(0);
  841. GE_CHECK_NOTNULL(merge_output);
  842. merge_output->SetDataType(output_data_type);
  843. for (uint32_t i = 0; i < src_node->GetAllInDataAnchorsSize(); ++i) {
  844. auto merge_input = src_op_desc->MutableInputDesc(i);
  845. GE_CHECK_NOTNULL(merge_input);
  846. merge_input->SetDataType(output_data_type);
  847. }
  848. }
  849. }
  850. // check if is_output_adjust_hw_layout is set
  851. if (NeedUpdateFormatByOutputTypeParm(op_desc, index)) {
  852. if ((old_format != FORMAT_NCHW) && (old_format != FORMAT_NHWC) && (old_format != FORMAT_NC1HWC0)) {
  853. ErrorManager::GetInstance().ATCReportErrMessage(
  854. "E19014", {"opname", "value", "reason"},
  855. {op_desc->GetName(), "format[" + TypeUtils::FormatToSerialString(old_format) + "]",
  856. "only support FORMAT_NC1HWC0,FORMAT_NCHW,FORMAT_NHWC"});
  857. GELOGE(INTERNAL_ERROR, "Format is not one of NCHW, NHWC, NC1HWC0.");
  858. return FAILED;
  859. }
  860. GeTensorDesc old_desc(old_shape, old_format, old_dtype);
  861. if (ProcessNetoutputNodeFp16Nc1hwc0DynShape(old_desc, net_output_input_desc, src_node) != SUCCESS) {
  862. GELOGE(INTERNAL_ERROR, "Process netoutput fp16 nc1hwc0.");
  863. return FAILED;
  864. }
  865. }
  866. }
  867. return SUCCESS;
  868. }
  869. } // namespace
  870. GraphPrepare::GraphPrepare() : compute_graph_(nullptr) {}
  871. GraphPrepare::~GraphPrepare() {}
  872. /**
  873. * @param graph
  874. * @return
  875. */
  876. Status GraphPrepare::UpdateVariableFormats(ComputeGraphPtr &graph) {
  877. GE_CHECK_NOTNULL(graph);
  878. auto var_names_to_refs = CollectVarNamesToRefs(graph);
  879. for (auto &node : graph->GetAllNodes()) {
  880. if (node == nullptr) {
  881. continue;
  882. }
  883. if (node->GetType() != VARIABLE) {
  884. continue;
  885. }
  886. auto trans_road = VarManager::Instance(graph->GetSessionID())->GetTransRoad(node->GetName());
  887. if (trans_road == nullptr) {
  888. GELOGD("The variable %s does not have any trans road", node->GetName().c_str());
  889. continue;
  890. }
  891. GELOGI("Recover the trans road for var %s reversely", node->GetName().c_str());
  892. auto ret = RecoverTransRoadForVar(node, *trans_road);
  893. if (ret != SUCCESS) {
  894. GELOGE(INTERNAL_ERROR, "Failed to recovery trans road for var %s", node->GetName().c_str());
  895. return INTERNAL_ERROR;
  896. }
  897. auto iter = var_names_to_refs.find(node->GetName());
  898. if (iter != var_names_to_refs.end()) {
  899. ret = RecoverTransRoadForVarRef(iter->second, *trans_road);
  900. if (ret != SUCCESS) {
  901. GELOGE(INTERNAL_ERROR, "Failed to recovery trans road for var ref %s", node->GetName().c_str());
  902. return INTERNAL_ERROR;
  903. }
  904. }
  905. }
  906. return SUCCESS;
  907. }
  908. void GraphPrepare::SetOptions(const ge::GraphManagerOptions &options) { options_ = options; }
  909. Status GraphPrepare::Init(const ge::Graph &graph, uint64_t session_id) {
  910. compute_graph_ = GraphUtils::GetComputeGraph(graph);
  911. if (compute_graph_ != nullptr) {
  912. compute_graph_->SetSessionID(session_id);
  913. }
  914. session_id_ = session_id;
  915. Status ret = CheckGraph();
  916. if (ret != SUCCESS) {
  917. GELOGE(ret, "RunGraph graph check fail, ret:%u", ret);
  918. return ret;
  919. }
  920. (void)compute_graph_->TopologicalSorting();
  921. ret = CheckRefOp();
  922. if (ret != SUCCESS) {
  923. GELOGE(ret, "RunGraph check ref op fail, ret:%u", ret);
  924. return ret;
  925. }
  926. return SUCCESS;
  927. }
  928. Status GraphPrepare::CheckGraph() {
  929. if (compute_graph_ == nullptr) {
  930. GELOGE(GE_GRAPH_INIT_FAILED, "Graph prepare init compute graph is NULLPTR");
  931. return GE_GRAPH_INIT_FAILED;
  932. }
  933. auto nodes = compute_graph_->GetAllNodes();
  934. if (nodes.empty()) {
  935. GELOGE(GE_GRAPH_INIT_FAILED, "Invalid graph, no nodes in this graph.");
  936. return GE_GRAPH_INIT_FAILED;
  937. }
  938. for (const NodePtr &node : compute_graph_->GetAllNodes()) {
  939. GE_CHECK_NOTNULL(node);
  940. if (node->GetOpDesc() == nullptr) {
  941. GELOGE(GE_GRAPH_INIT_FAILED, "Check Graph node opdesc is NULL");
  942. return GE_GRAPH_INIT_FAILED;
  943. }
  944. }
  945. return SUCCESS;
  946. }
  947. Status GraphPrepare::CheckRefInputNode(const NodePtr &node, const std::string &input_name,
  948. const std::set<NodePtr> &ref_nodes) {
  949. // Acceptable input types should be ref node, variable or Switch operator, which is issued by ME for dynamic
  950. // lossscale and would be optimized in SwitchToStreamSwitchPass.
  951. // Since ME dont differentiate between RefSwitch and Switch, and only issue Switch.
  952. static std::set<std::string> acceptable_types = {ge::VARIABLE, ge::VARIABLEV2, ge::VARHANDLEOP,
  953. ge::REFSWITCH, ge::REFMERGE, ge::REFENTER,
  954. ge::REFNEXTITERATION, ge::REFEXIT, ge::SWITCH};
  955. GE_CHECK_NOTNULL(node);
  956. const auto &op_desc = node->GetOpDesc();
  957. GE_CHECK_NOTNULL(op_desc);
  958. const auto input_index = op_desc->GetInputIndexByName(input_name);
  959. const auto &in_anchor = node->GetInDataAnchor(input_index);
  960. GE_CHECK_NOTNULL(in_anchor);
  961. const auto &peer_out_anchor = in_anchor->GetPeerOutAnchor();
  962. GE_CHECK_NOTNULL(peer_out_anchor);
  963. const auto &input_node = peer_out_anchor->GetOwnerNode();
  964. GE_CHECK_NOTNULL(input_node);
  965. const auto &input_op_desc = input_node->GetOpDesc();
  966. GE_CHECK_NOTNULL(input_op_desc);
  967. bool is_ref = (ref_nodes.find(input_node) != ref_nodes.end());
  968. if (is_ref) {
  969. return SUCCESS;
  970. }
  971. auto input_type = input_op_desc->GetType();
  972. if (input_type == ge::FRAMEWORKOP) {
  973. if (!ge::AttrUtils::GetStr(input_op_desc, ATTR_NAME_FRAMEWORK_ORIGINAL_TYPE, input_type)) {
  974. GELOGE(PARAM_INVALID, "Get original type failed.");
  975. return PARAM_INVALID;
  976. }
  977. }
  978. bool is_acceptable = (acceptable_types.find(input_type) != acceptable_types.end());
  979. if (!is_acceptable) {
  980. ErrorManager::GetInstance().ATCReportErrMessage(
  981. "E15005", {"opname", "optype", "opname1", "optype1"},
  982. {op_desc->GetName(), node->GetType(), input_op_desc->GetName(), input_op_desc->GetType()});
  983. GELOGE(PARAM_INVALID, "The ref input of ref node %s[%s] must be ref node or variable, but %s[%s]isn't.",
  984. node->GetName().c_str(), node->GetType().c_str(), input_op_desc->GetName().c_str(),
  985. input_op_desc->GetType().c_str());
  986. return PARAM_INVALID;
  987. }
  988. return SUCCESS;
  989. }
  990. Status GraphPrepare::CheckRefOp() {
  991. GE_CHECK_NOTNULL(compute_graph_);
  992. std::set<NodePtr> ref_nodes;
  993. for (const NodePtr &node : compute_graph_->GetDirectNode()) {
  994. if (node == nullptr) {
  995. GELOGE(PARAM_INVALID, "param [node] must not be null.");
  996. return PARAM_INVALID;
  997. }
  998. auto op_desc = node->GetOpDesc();
  999. if (op_desc == nullptr) {
  1000. GELOGE(PARAM_INVALID, "OpDesc of param [node] must not be null.");
  1001. return PARAM_INVALID;
  1002. }
  1003. auto input_name_index = op_desc->GetAllInputName();
  1004. auto outputs = op_desc->GetAllOutputName();
  1005. for (const auto &name_index : input_name_index) {
  1006. if (op_desc->GetOutputIndexByName(name_index.first) != -1) {
  1007. if (CheckRefInputNode(node, name_index.first, ref_nodes) != SUCCESS) {
  1008. GELOGE(PARAM_INVALID, "CheckRefInputNode failed.");
  1009. return PARAM_INVALID;
  1010. }
  1011. (void)ref_nodes.insert(node); // no need to check value
  1012. }
  1013. }
  1014. }
  1015. return SUCCESS;
  1016. };
  1017. Status GraphPrepare::SetRtContext(rtContext_t rt_context, rtCtxMode_t mode) {
  1018. GE_CHECK_NOTNULL(compute_graph_);
  1019. GELOGI("set rt_context, session id: %lu, graph id: %u, mode %d, device id:%u.", session_id_,
  1020. compute_graph_->GetGraphID(), static_cast<int>(mode), ge::GetContext().DeviceId());
  1021. GE_CHK_RT_RET(rtCtxCreate(&rt_context, mode, ge::GetContext().DeviceId()));
  1022. GE_CHK_RT_RET(rtCtxSetCurrent(rt_context));
  1023. RtContextUtil::GetInstance().AddRtContext(session_id_, compute_graph_->GetGraphID(), rt_context);
  1024. return SUCCESS;
  1025. }
  1026. Status GraphPrepare::AdjustDataOpOutput(const NodePtr &node) {
  1027. if (node == nullptr) {
  1028. GELOGE(GE_GRAPH_GRAPH_NODE_NULL, "Input node is NULL");
  1029. return GE_GRAPH_GRAPH_NODE_NULL;
  1030. }
  1031. OpDescPtr op_desc_ptr = node->GetOpDesc();
  1032. if (op_desc_ptr == nullptr) {
  1033. GELOGE(GE_GRAPH_GRAPH_NODE_NULL, "Input node opdesc is NULL");
  1034. return GE_GRAPH_GRAPH_NODE_NULL;
  1035. }
  1036. GeTensorDesc output = op_desc_ptr->GetOutputDesc(0);
  1037. int64_t tensor_size = 0;
  1038. graphStatus graph_status = TensorUtils::GetTensorMemorySizeInBytes(output, tensor_size);
  1039. if (graph_status != GRAPH_SUCCESS) {
  1040. ErrorManager::GetInstance().ATCReportErrMessage(
  1041. "E19012", {"function", "reason"}, {"GetTensorMemorySizeInBytes", "opname is " + node->GetName()});
  1042. GELOGE(graph_status, "GetTensorMemorySizeInBytes failed!");
  1043. return FAILED;
  1044. }
  1045. TensorUtils::SetSize(output, tensor_size);
  1046. graphStatus graph_ret = op_desc_ptr->UpdateOutputDesc(0, output);
  1047. if (graph_ret != GRAPH_SUCCESS) {
  1048. GELOGE(graph_ret, "UpdateOutputDesc fail, graph_ret:%u", graph_ret);
  1049. return graph_ret;
  1050. }
  1051. return SUCCESS;
  1052. }
  1053. Status GraphPrepare::UpdateInput(const std::vector<GeTensor> &user_input) {
  1054. compute_graph_->SaveDataFormat(ge::TypeUtils::DomiFormatToFormat(GetLocalOmgContext().format));
  1055. for (NodePtr &input_node : compute_graph_->GetDirectNode()) {
  1056. GE_CHECK_NOTNULL(input_node);
  1057. OpDescPtr op = input_node->GetOpDesc();
  1058. GE_CHECK_NOTNULL(op);
  1059. if (op->GetType() == DATA) {
  1060. GeAttrValue::INT index = 0;
  1061. if ((!(AttrUtils::GetInt(op, ATTR_NAME_INDEX, index))) || (GetLocalOmgContext().is_dynamic_input)) {
  1062. GELOGW("Get index from data attr failed");
  1063. continue;
  1064. }
  1065. if ((index < 0) || (static_cast<size_t>(index) >= user_input.size())) {
  1066. std::string situation = "data op index[" + std::to_string(index) + "]";
  1067. std::string reason = "it must less than user_input size[" + std::to_string(user_input.size()) + "]";
  1068. ErrorManager::GetInstance().ATCReportErrMessage("E19025", {"situation", "reason"}, {situation, reason});
  1069. GELOGE(PARAM_INVALID, "user_input size = %zu, graph data op index = %ld.", user_input.size(), index);
  1070. return FAILED;
  1071. }
  1072. GeTensorDesc desc(user_input[index].GetTensorDesc());
  1073. auto format = desc.GetFormat();
  1074. auto origin_format = desc.GetOriginFormat();
  1075. // data maybe internal format [FRACTAL_NZ] at singleop process such as GEMM.
  1076. bool need_check_internal_format = (!IsTansDataOpData(input_node)) && (!options_.is_single_op);
  1077. if (need_check_internal_format) {
  1078. bool is_internal = TypeUtils::IsInternalFormat(format) || TypeUtils::IsInternalFormat(origin_format);
  1079. if (is_internal) {
  1080. ErrorManager::GetInstance().ATCReportErrMessage("E19025", {"situation", "reason"},
  1081. {"Input format[" + TypeUtils::FormatToSerialString(format) + "] or origin_format[" +
  1082. TypeUtils::FormatToSerialString(origin_format) + "]", "it is not support"});
  1083. GELOGE(PARAM_INVALID, "Input format %s or origin_format %s is not support.",
  1084. TypeUtils::FormatToSerialString(format).c_str(),
  1085. TypeUtils::FormatToSerialString(origin_format).c_str());
  1086. return FAILED;
  1087. }
  1088. }
  1089. auto data_type = desc.GetDataType();
  1090. uint32_t length = 1;
  1091. bool type_ret = TypeUtils::GetDataTypeLength(data_type, length);
  1092. if (!type_ret) {
  1093. ErrorManager::GetInstance().ATCReportErrMessage("E19025", {"situation", "reason"},
  1094. {"Input datatype[" + TypeUtils::DataTypeToSerialString(data_type) + "]", "it is not support"});
  1095. GELOGE(PARAM_INVALID, "Input datatype %s is not support.",
  1096. TypeUtils::DataTypeToSerialString(data_type).c_str());
  1097. return FAILED;
  1098. }
  1099. int64_t desc_shape = desc.GetShape().GetShapeSize();
  1100. FMK_INT64_UINT32_MULCHECK(desc_shape, length);
  1101. int64_t shape_size = desc_shape * length;
  1102. GE_IF_BOOL_EXEC(shape_size == 0 && desc.GetShape().GetDimNum() == 0, shape_size = static_cast<int64_t>(length));
  1103. int64_t size = 0;
  1104. GE_IF_BOOL_EXEC(ge::TensorUtils::GetSize(desc, size) != GRAPH_SUCCESS,
  1105. GELOGE(INTERNAL_ERROR, "TensorUtils GetSize failed");
  1106. return FAILED);
  1107. bool size_check = (size != 0 && shape_size != size);
  1108. if (size_check) {
  1109. std::string situation = "input data size[" + std::to_string(size) +
  1110. "] and shape_size[" + std::to_string(size) + "]";
  1111. std::string reason = "because size != 0 and shape_size != size";
  1112. ErrorManager::GetInstance().ATCReportErrMessage("E19025", {"situation", "reason"}, {situation, reason});
  1113. GELOGE(PARAM_INVALID, "input data size =%ld, shape_size =%ld.", size, shape_size);
  1114. return FAILED;
  1115. }
  1116. ge::TensorUtils::SetSize(desc, shape_size);
  1117. graphStatus graph_ret = op->UpdateInputDesc(0, desc);
  1118. if (graph_ret != GRAPH_SUCCESS) {
  1119. GELOGE(graph_ret, "UpdateInputDesc fail, graph_ret:%u", graph_ret);
  1120. return graph_ret;
  1121. }
  1122. // Size will be recalculated in the build stage
  1123. ge::TensorUtils::SetSize(desc, 0);
  1124. graph_ret = op->UpdateOutputDesc(0, desc);
  1125. if (graph_ret != GRAPH_SUCCESS) {
  1126. GELOGE(graph_ret, "UpdateOutputDesc fail, graph_ret:%u", graph_ret);
  1127. return graph_ret;
  1128. }
  1129. if (!options_.train_graph_flag) {
  1130. Status ret = AdjustDataOpOutput(input_node);
  1131. if (ret != SUCCESS) {
  1132. GELOGE(ret, "AdjustDataOpOutput fail, ret:%u", ret);
  1133. return ret;
  1134. }
  1135. }
  1136. }
  1137. }
  1138. return SUCCESS;
  1139. }
  1140. Status GraphPrepare::TryDoAipp() {
  1141. // infer and with aipp configure file, then call aipp insert
  1142. if ((!options_.train_graph_flag) && (!options_.insert_op_file.empty())) {
  1143. GE_DUMP(compute_graph_, "Before_insert_aipp");
  1144. Status ret = ge::InsertNewOpUtil::Instance().Init();
  1145. if (ret != SUCCESS) {
  1146. GELOGE(INTERNAL_ERROR, "TryDoAipp: InsertNewOpUtil instance failed.");
  1147. return INTERNAL_ERROR;
  1148. }
  1149. ret = ge::InsertNewOpUtil::Instance().Parse(options_.insert_op_file.c_str());
  1150. if (ret != SUCCESS) {
  1151. GELOGE(GE_GRAPH_OPTIMIZE_INSERT_OP_PARSE_FAILED, "TryDoAipp: parse config file %s failed",
  1152. options_.insert_op_file.c_str());
  1153. return GE_GRAPH_OPTIMIZE_INSERT_OP_PARSE_FAILED;
  1154. }
  1155. ret = ge::InsertNewOpUtil::Instance().InsertAippOps(compute_graph_, options_.insert_op_file);
  1156. if (ret != SUCCESS) {
  1157. GELOGE(GE_GRAPH_OPTIMIZE_INSERT_DYN_OP_FAILED, "TryDoAipp: insert aipp op ret failed, ret:%u", ret);
  1158. return GE_GRAPH_OPTIMIZE_INSERT_DYN_OP_FAILED;
  1159. }
  1160. }
  1161. return SUCCESS;
  1162. }
  1163. Status GraphPrepare::FormatAndShapeProcess() {
  1164. Status ret = ResourcePairProcess("add");
  1165. if (ret != SUCCESS) {
  1166. GELOGE(ret, "ResourcePairProcess failed");
  1167. return ret;
  1168. }
  1169. GE_TIMESTAMP_START(InferOriginFormat1);
  1170. ret = compute_graph_->InferOriginFormat();
  1171. GE_TIMESTAMP_END(InferOriginFormat1, "GraphPrepare::InferOriginFormat1");
  1172. GE_DUMP(compute_graph_, "after_first_inferformat");
  1173. if (ret != SUCCESS) {
  1174. GELOGE(ret, "Prepare Graph first inferformat failed");
  1175. return ret;
  1176. }
  1177. GE_TIMESTAMP_START(InferShapeForPreprocess);
  1178. ret = InferShapeForPreprocess();
  1179. GE_TIMESTAMP_END(InferShapeForPreprocess, "GraphPrepare::InferShapeForPreprocess");
  1180. GE_DUMP(compute_graph_, "after_infershape");
  1181. if (ret != SUCCESS) {
  1182. GELOGE(GE_GRAPH_INFERSHAPE_FAILED, "Prepare Graph infershape failed");
  1183. return GE_GRAPH_INFERSHAPE_FAILED;
  1184. }
  1185. GE_TIMESTAMP_START(InferOriginFormat2);
  1186. ret = compute_graph_->InferOriginFormat();
  1187. GE_TIMESTAMP_END(InferOriginFormat2, "GraphPrepare::InferOriginFormat2");
  1188. if (ret != SUCCESS) {
  1189. GELOGE(ret, "Prepare Graph inferformat failed");
  1190. return ret;
  1191. }
  1192. ret = ResourcePairProcess("remove");
  1193. if (ret != SUCCESS) {
  1194. return ret;
  1195. }
  1196. return ret;
  1197. }
  1198. Status GraphPrepare::ResourcePairProcess(const std::string &action) {
  1199. PassManager control_pass;
  1200. // Graph pass tmp logic for resource infershape
  1201. if (options_.train_graph_flag) {
  1202. try {
  1203. if (action == "add") {
  1204. (void)control_pass.AddPass("ResourcePairProcess::ResourcePairAddControlPass", new ResourcePairAddControlPass);
  1205. } else {
  1206. (void)control_pass.AddPass("ResourcePairProcess::ResourcePairRemoveControlPass",
  1207. new ResourcePairRemoveControlPass);
  1208. }
  1209. } catch (std::bad_alloc &e) {
  1210. GELOGE(INTERNAL_ERROR, "Add pass failed, bad memory allocation occur, action:%s.", action.c_str());
  1211. return INTERNAL_ERROR;
  1212. }
  1213. }
  1214. Status ret = control_pass.Run(compute_graph_);
  1215. if (ret != SUCCESS && ret != NOT_CHANGED) {
  1216. GELOGE(ret, "Run ResourcePairControlPass failed, action:%s, ret:%u.", action.c_str(), ret);
  1217. return ret;
  1218. }
  1219. return SUCCESS;
  1220. }
  1221. Status GraphPrepare::UpdateDataNetOutputByStorageFormat() {
  1222. for (auto &node_ptr : compute_graph_->GetAllNodes()) {
  1223. GE_CHECK_NOTNULL(node_ptr);
  1224. if (node_ptr->GetType() == DATA) {
  1225. uint32_t index = 0;
  1226. auto op_desc = node_ptr->GetOpDesc();
  1227. GE_CHECK_NOTNULL(op_desc);
  1228. const GeTensorDescPtr input = op_desc->MutableInputDesc(index);
  1229. Format storage_format = FORMAT_RESERVED;
  1230. vector<int64_t> dst_shape_dims;
  1231. if (GetStorageFormatAndShape(op_desc, input, storage_format, dst_shape_dims) != SUCCESS) {
  1232. GELOGE(INTERNAL_ERROR, "Get storage format for input failed");
  1233. return FAILED;
  1234. }
  1235. if (storage_format == FORMAT_RESERVED) {
  1236. continue;
  1237. }
  1238. if (ModifyDataNetOutputFormatAndShape(op_desc, index, storage_format, dst_shape_dims) != SUCCESS) {
  1239. GELOGE(INTERNAL_ERROR, "Modify format and shape for inputfailed");
  1240. return FAILED;
  1241. }
  1242. }
  1243. if (node_ptr->GetType() == ge::NETOUTPUT) {
  1244. auto op_desc = node_ptr->GetOpDesc();
  1245. GE_CHECK_NOTNULL(op_desc);
  1246. for (uint32_t index = 0; index < op_desc->GetOutputsSize(); index++) {
  1247. const GeTensorDescPtr output = op_desc->MutableOutputDesc(index);
  1248. Format storage_format = FORMAT_RESERVED;
  1249. vector<int64_t> dst_shape_dims;
  1250. if (GetStorageFormatAndShape(op_desc, output, storage_format, dst_shape_dims) != SUCCESS) {
  1251. GELOGE(INTERNAL_ERROR, "Get storage format from output failed");
  1252. return FAILED;
  1253. }
  1254. if (storage_format == FORMAT_RESERVED) {
  1255. continue;
  1256. }
  1257. if (ModifyDataNetOutputFormatAndShape(op_desc, index, storage_format, dst_shape_dims) != SUCCESS) {
  1258. GELOGE(INTERNAL_ERROR, "Modify format and shape for output failed");
  1259. return FAILED;
  1260. }
  1261. }
  1262. }
  1263. }
  1264. return SUCCESS;
  1265. }
  1266. Status GraphPrepare::SaveOriginalGraphToOmModel() {
  1267. if (options_.save_original_model == "true") {
  1268. ModelHelper model_helper;
  1269. Status ret = model_helper.SaveOriginalGraphToOmModel(ge::GraphUtils::CreateGraphFromComputeGraph(compute_graph_),
  1270. options_.original_model_file);
  1271. if (ret != SUCCESS) {
  1272. // If save original model fail, process continue
  1273. GELOGW("SaveOriginalGraphToOmModel fail");
  1274. }
  1275. }
  1276. return SUCCESS;
  1277. }
  1278. #define PP_RUN_AND_DUMP(name, func, ...) \
  1279. do { \
  1280. GE_RUN(Prepare, func, __VA_ARGS__); \
  1281. GE_DUMP(compute_graph, "PrepareAfter" name); \
  1282. GELOGI("Prepare %s on graph %s success.", name, compute_graph->GetName().c_str()); \
  1283. } while (0)
  1284. #define PP_RUN(name, func, ...) \
  1285. do { \
  1286. GE_RUN(Prepare, func, __VA_ARGS__); \
  1287. GELOGI("Prepare %s on graph %s success.", name, compute_graph->GetName().c_str()); \
  1288. } while (0)
  1289. Status GraphPrepare::PrepareDynShape(ConstGraphPtr graph, const std::vector<GeTensor> &user_input,
  1290. ge::ComputeGraphPtr &compute_graph, uint64_t session_id) {
  1291. GE_CHECK_NOTNULL(graph);
  1292. GE_CHECK_NOTNULL(compute_graph);
  1293. GetLocalOmgContext().type = static_cast<domi::FrameworkType>(options_.framework_type);
  1294. const Graph &const_graph = *graph;
  1295. PP_RUN("Init", Init, const_graph, session_id);
  1296. PP_RUN("SetRtContext", SetRtContext, rtContext_t(), RT_CTX_GEN_MODE);
  1297. PP_RUN_AND_DUMP("CheckAndUpdateInput", CheckAndUpdateInput, user_input);
  1298. PP_RUN_AND_DUMP("GraphEquivalentTransformation", GraphEquivalentTransformation);
  1299. PP_RUN_AND_DUMP("ProcessOutput", ProcessNetOutput);
  1300. PP_RUN_AND_DUMP("ProcessMultiBatch", multibatch::ProcessMultiBatch, compute_graph_);
  1301. PP_RUN_AND_DUMP("InsertAipp", TryDoAipp);
  1302. PP_RUN_AND_DUMP("ProcessBeforeInfershape", ProcessBeforeInfershape);
  1303. PP_RUN_AND_DUMP("InferFormatAndShape", FormatAndShapeProcess);
  1304. PP_RUN_AND_DUMP("GetDynamicOutputShape", multibatch::GetDynamicOutputShape, compute_graph_);
  1305. PP_RUN_AND_DUMP("ProcessAippStage2", InsertNewOpUtil::Instance().UpdateDataNodeByAipp, compute_graph_);
  1306. PP_RUN("SaveOriginalGraphToOmModel", SaveOriginalGraphToOmModel);
  1307. PP_RUN_AND_DUMP("PrepareOptimize", PrepareOptimize);
  1308. return SUCCESS;
  1309. }
  1310. Status GraphPrepare::RecordAIPPInfo(ge::ComputeGraphPtr &compute_graph) {
  1311. PP_RUN("RecordAIPPInfo", InsertNewOpUtil::Instance().RecordAIPPInfoToData, compute_graph_);
  1312. return SUCCESS;
  1313. }
  1314. Status GraphPrepare::PrepareRunningFormatRefiner() {
  1315. auto compute_graph = compute_graph_;
  1316. PassManager pass_manager;
  1317. GE_CHK_STATUS_RET(pass_manager.AddPass("PrepareRunningFormatRefiner::VariablePrepareOpPass",
  1318. new (std::nothrow) VariablePrepareOpPass))
  1319. GE_TIMESTAMP_START(pass_manager);
  1320. auto ret = pass_manager.Run(compute_graph);
  1321. GE_TIMESTAMP_END(pass_manager, "GraphPrepare::PrepareRunningFormatRefiner");
  1322. if (ret != SUCCESS && ret != NOT_CHANGED) {
  1323. GELOGE(ret, "Run passes for running format refiner failed, ret:%u.", ret);
  1324. return ret;
  1325. }
  1326. PP_RUN_AND_DUMP("UpdateInputOutputByUserOptions", UpdateInputOutputByOptions);
  1327. PP_RUN_AND_DUMP("UpdateVariableFormats", UpdateVariableFormats, compute_graph_);
  1328. return SUCCESS;
  1329. }
  1330. Status GraphPrepare::SwitchOpOptimize(ComputeGraphPtr &compute_graph) {
  1331. if (compute_graph == nullptr) {
  1332. GELOGE(GE_GRAPH_NULL_INPUT, "Input Graph is NULL");
  1333. return GE_GRAPH_NULL_INPUT;
  1334. }
  1335. GEPass ge_passes(compute_graph);
  1336. NamesToPass hccl_group;
  1337. HcclGroupPass hccl_group_pass;
  1338. GELOGD("Add hccl group pass success");
  1339. hccl_group.emplace_back("HcclGroupPass", &hccl_group_pass);
  1340. auto ret = ge_passes.Run(hccl_group);
  1341. if (ret != SUCCESS) {
  1342. GELOGE(ret, "Run HcclGroupPass pass for preprocess failed, ret:%u.", ret);
  1343. return ret;
  1344. }
  1345. ret = compute_graph->TopologicalSorting();
  1346. if (ret != SUCCESS) {
  1347. GELOGE(ret, "Graph topological sort failed, ret:%u.", ret);
  1348. return ret;
  1349. }
  1350. return SUCCESS;
  1351. }
  1352. #undef PP_RUN_AND_DUMP
  1353. #undef PP_RUN
  1354. Status GraphPrepare::GenerateInfershapeGraph(ConstGraphPtr graph) {
  1355. if (graph == nullptr) {
  1356. GELOGE(GE_GRAPH_NULL_INPUT, "Input Graph is NULL");
  1357. return GE_GRAPH_NULL_INPUT;
  1358. }
  1359. const Graph &const_graph = *graph;
  1360. Status ret = Init(const_graph, 0);
  1361. if (ret != SUCCESS) {
  1362. GELOGE(ret, "Init graph_prepare fail, ret:%u", ret);
  1363. return ret;
  1364. }
  1365. GE_DUMP(compute_graph_, "after_parser");
  1366. GELOGI("Start infershape for dump json process.");
  1367. ret = compute_graph_->InferOriginFormat();
  1368. GE_DUMP(compute_graph_, "after_inferformat");
  1369. if (ret != SUCCESS) {
  1370. GELOGE(ret, "Prepare Graph inferformat failed");
  1371. return ret;
  1372. }
  1373. InferShapePass infer_shape_pass;
  1374. NamesToPass names_to_passes;
  1375. names_to_passes.emplace_back("InferShapePass", &infer_shape_pass);
  1376. GEPass ge_passes(compute_graph_);
  1377. ret = ge_passes.Run(names_to_passes);
  1378. GE_DUMP(compute_graph_, "after_infershape");
  1379. if (ret != SUCCESS) {
  1380. GELOGE(ret, "Run ge_passes infershape for preprocess failed, ret:%u.", ret);
  1381. return ret;
  1382. }
  1383. ShapeRefiner::ClearContextMap();
  1384. return SUCCESS;
  1385. }
  1386. Status GraphPrepare::CheckConstOp() {
  1387. for (auto &node_ptr : compute_graph_->GetAllNodes()) {
  1388. GE_CHECK_NOTNULL(node_ptr);
  1389. if (node_ptr->GetType() == CONSTANT) {
  1390. Status ret = VerifyConstOp(node_ptr);
  1391. GE_CHK_BOOL_RET_STATUS(ret == SUCCESS, ret, "Const Op Check failed");
  1392. } else if (node_ptr->GetType() == FRAMEWORKOP) {
  1393. auto op_desc = node_ptr->GetOpDesc();
  1394. if (op_desc == nullptr) {
  1395. GELOGE(PARAM_INVALID, "Get op desc failed");
  1396. return PARAM_INVALID;
  1397. }
  1398. std::string original_type;
  1399. GE_IF_BOOL_EXEC(ge::AttrUtils::GetStr(op_desc, ATTR_NAME_FRAMEWORK_ORIGINAL_TYPE, original_type),
  1400. GELOGI("Get FrameWorkOp original type [%s]", original_type.c_str()));
  1401. GELOGI("original type is %s", original_type.c_str());
  1402. if (original_type == CONSTANT) {
  1403. Status ret = VerifyConstOp(node_ptr);
  1404. GE_CHK_BOOL_RET_STATUS(ret == SUCCESS, ret, "Const Op Check failed");
  1405. }
  1406. }
  1407. }
  1408. return SUCCESS;
  1409. }
  1410. Status GraphPrepare::VerifyConstOp(const NodePtr &node) {
  1411. GE_CHECK_NOTNULL(node);
  1412. auto op_desc = node->GetOpDesc();
  1413. GE_CHECK_NOTNULL(op_desc);
  1414. ConstGeTensorPtr ge_tensor_ptr;
  1415. if (!(AttrUtils::GetTensor(op_desc, ATTR_NAME_WEIGHTS, ge_tensor_ptr))) {
  1416. GELOGE(PARAM_INVALID, "Get value from const attr failed");
  1417. return PARAM_INVALID;
  1418. }
  1419. GE_CHECK_NOTNULL(ge_tensor_ptr);
  1420. auto data_size = ge_tensor_ptr->GetData().GetSize();
  1421. auto ge_tensor_desc = ge_tensor_ptr->GetTensorDesc();
  1422. int64_t shape_size = ge_tensor_desc.GetShape().GetShapeSize();
  1423. auto data_type = ge_tensor_desc.GetDataType();
  1424. uint32_t length = 1;
  1425. bool type_ret = TypeUtils::GetDataTypeLength(data_type, length);
  1426. if (!type_ret) {
  1427. ErrorManager::GetInstance().ATCReportErrMessage("E19025", {"situation", "reason"},
  1428. {"Input datatype[" + TypeUtils::DataTypeToSerialString(data_type) + "]", "it is not support"});
  1429. GELOGE(PARAM_INVALID, "Input datatype %s is not support.", TypeUtils::DataTypeToSerialString(data_type).c_str());
  1430. return FAILED;
  1431. }
  1432. FMK_INT64_UINT32_MULCHECK(shape_size, length);
  1433. GELOGI("Const real value Size:%zu, op_desc Shape Size:%ld, data_type:%s.", data_size, shape_size * length,
  1434. TypeUtils::DataTypeToSerialString(data_type).c_str());
  1435. if (shape_size == 0) {
  1436. if (ge_tensor_desc.GetShape().GetDims().size() == 0) {
  1437. // shape = [], means it's a sclar tensor.
  1438. GE_CHK_BOOL_EXEC(data_size / length == 1,
  1439. ErrorManager::GetInstance().ATCReportErrMessage("E10043", {"reason"}, {"Const is invalid scalar tensor."});
  1440. return PARAM_INVALID, "Const is invalid scalar tensor.");
  1441. } else {
  1442. // shape = [x, y, 0,...], means it's a vector tensor that value is [].
  1443. GE_CHK_BOOL_EXEC(data_size == 0,
  1444. ErrorManager::GetInstance().ATCReportErrMessage("E10043", {"reason"}, {"Const is invalid vector scalar."});
  1445. return PARAM_INVALID, "Const is invalid vector scalar.");
  1446. }
  1447. } else {
  1448. GE_CHK_BOOL_EXEC(data_size == static_cast<size_t>(shape_size * length) && data_size != 0,
  1449. ErrorManager::GetInstance().ATCReportErrMessage(
  1450. "E10043", {"reason"}, {"Const input data size is not equal with tensor desc shape"});
  1451. return PARAM_INVALID, "Const input data size is not equal with tensor desc shape");
  1452. }
  1453. return SUCCESS;
  1454. }
  1455. Status GraphPrepare::CheckUserInput(const std::vector<GeTensor> &user_input) {
  1456. if (GetLocalOmgContext().is_dynamic_input) {
  1457. return SUCCESS;
  1458. }
  1459. unsigned int node_num = 0;
  1460. unsigned int data_num = 0;
  1461. for (NodePtr &input_node : compute_graph_->GetDirectNode()) {
  1462. GE_CHECK_NOTNULL(input_node);
  1463. OpDescPtr op = input_node->GetOpDesc();
  1464. GE_CHECK_NOTNULL(op);
  1465. node_num++;
  1466. if (op->GetType() == DATA || op->GetType() == AIPPDATA) {
  1467. data_num++;
  1468. GeAttrValue::INT index = 0;
  1469. if (!(AttrUtils::GetInt(op, ATTR_NAME_INDEX, index))) {
  1470. GELOGE(GE_GRAPH_INIT_FAILED, "Get index from attr failed");
  1471. return GE_GRAPH_INIT_FAILED;
  1472. }
  1473. if ((index < 0) || (static_cast<size_t>(index) >= user_input.size())) {
  1474. std::string situation = "data op index[" + std::to_string(index) + "]";
  1475. std::string reason = "it must less than user_input size[" + std::to_string(user_input.size()) + "]";
  1476. ErrorManager::GetInstance().ATCReportErrMessage("E19025", {"situation", "reason"}, {situation, reason});
  1477. GELOGE(GE_GRAPH_INIT_FAILED, "user_input size:%zu, data op index:%ld.", user_input.size(), index);
  1478. return GE_GRAPH_INIT_FAILED;
  1479. }
  1480. GeTensorDesc desc(user_input[index].GetTensorDesc());
  1481. for (size_t i = 0; i < desc.GetShape().GetDimNum(); ++i) {
  1482. if (desc.GetShape().GetDim(i) < 0) {
  1483. std::string situation = "data dim[" + std::to_string(i) + "][" + std::to_string(desc.GetShape().GetDim(i)) + "]" ;
  1484. std::string reason = "it need >= 0";
  1485. ErrorManager::GetInstance().ATCReportErrMessage("E19025", {"situation", "reason"}, {situation, reason});
  1486. GELOGE(GE_GRAPH_INIT_FAILED, "data dim %zu is not supported, need >= 0, real:%ld.", i,
  1487. desc.GetShape().GetDim(i));
  1488. return GE_GRAPH_INIT_FAILED;
  1489. }
  1490. }
  1491. }
  1492. }
  1493. if (node_num <= data_num) {
  1494. GELOGW("Prepare check user input, data_num = %u, node_num = %u", data_num, node_num);
  1495. }
  1496. return SUCCESS;
  1497. }
  1498. Status GraphPrepare::InferShapeForPreprocess() {
  1499. GELOGI("Start infershape for preprocess.");
  1500. GEPass ge_passes(compute_graph_);
  1501. NamesToPass names_to_passes;
  1502. AssertPass assert_pass;
  1503. if (!options_.train_graph_flag) {
  1504. names_to_passes.emplace_back("AssertPass", &assert_pass);
  1505. }
  1506. InferShapePass infer_shape_pass;
  1507. names_to_passes.emplace_back("InferShapePass", &infer_shape_pass);
  1508. ReplaceWithEmptyConstPass replace_with_empty_const_pass;
  1509. names_to_passes.emplace_back("ReplaceWithEmptyConstPass", &replace_with_empty_const_pass);
  1510. DimensionComputePass dimension_compute_pass;
  1511. names_to_passes.emplace_back("DimensionComputePass", &dimension_compute_pass);
  1512. ConstantFoldingPass constant_folding_pass;
  1513. names_to_passes.emplace_back("ConstantFoldingPass", &constant_folding_pass);
  1514. int32_t dev_count = 0;
  1515. AicpuConstantFoldingPass aicpu_constant_folding_pass;
  1516. const char *aicpu_constant_folding_on = std::getenv("AICPU_CONSTANT_FOLDING_ON");
  1517. rtError_t rt_err = RT_ERROR_NONE;
  1518. if (aicpu_constant_folding_on != nullptr) {
  1519. rt_err = rtGetDeviceCount(&dev_count);
  1520. if (rt_err == RT_ERROR_NONE) {
  1521. Status result = SetRtContext(rtContext_t(), RT_CTX_NORMAL_MODE);
  1522. if (result != SUCCESS) {
  1523. GELOGE(result, "Set rt context failed.");
  1524. return result;
  1525. }
  1526. names_to_passes.emplace_back("AicpuConstantFoldingPass", &aicpu_constant_folding_pass);
  1527. }
  1528. }
  1529. Status ret = ge_passes.Run(names_to_passes);
  1530. if (aicpu_constant_folding_on != nullptr) {
  1531. if (rt_err == RT_ERROR_NONE) {
  1532. Status result = SetRtContext(rtContext_t(), RT_CTX_GEN_MODE);
  1533. if (result != SUCCESS) {
  1534. GELOGE(result, "Set rt context failed.");
  1535. return result;
  1536. }
  1537. }
  1538. }
  1539. ShapeRefiner::ClearContextMap();
  1540. if (ret != SUCCESS) {
  1541. GELOGE(ret, "Run ge_passes infershape for preprocess failed, ret:%u.", ret);
  1542. return ret;
  1543. }
  1544. return SUCCESS;
  1545. }
  1546. Status GraphPrepare::PrepareOptimize() {
  1547. GELOGI("Start optimize for preprocess.");
  1548. // check rw type
  1549. GraphOptimize graph_optimize;
  1550. bool has_conflict = false;
  1551. graph_optimize.CheckRWConflict(compute_graph_, has_conflict);
  1552. if (has_conflict) {
  1553. GELOGE(GRAPH_PARAM_INVALID, "There has rw conflict.Stop optimize.");
  1554. return FAILED;
  1555. }
  1556. PassManager original_graph_passes;
  1557. // Graph pass
  1558. try {
  1559. (void)original_graph_passes.AddPass("PrepareOptimize::ShapeOperateOpRemovePass", new ShapeOperateOpRemovePass);
  1560. (void)original_graph_passes.AddPass("PrepareOptimize::ReplaceTransShapePass", new ReplaceTransShapePass);
  1561. } catch (std::bad_alloc &e) {
  1562. GELOGE(INTERNAL_ERROR, "Add pass failed, bad memory allocation occurs.");
  1563. return INTERNAL_ERROR;
  1564. }
  1565. GE_TIMESTAMP_START(original_graph_passes);
  1566. Status ret = original_graph_passes.Run(compute_graph_);
  1567. GE_TIMESTAMP_END(original_graph_passes, "GraphPrepare::OriginalGraphPasses");
  1568. if (ret != SUCCESS && ret != NOT_CHANGED) {
  1569. GELOGE(ret, "Run graph passes optimize for preprocess failed, ret:%u.", ret);
  1570. return ret;
  1571. }
  1572. // New pass
  1573. GEPass ge_passes(compute_graph_);
  1574. NamesToPass names_to_passes;
  1575. EnterPass enter_pass;
  1576. names_to_passes.emplace_back("EnterPass", &enter_pass);
  1577. CondPass cond_pass;
  1578. names_to_passes.emplace_back("CondPass", &cond_pass);
  1579. PrintOpPass print_pass;
  1580. if (options_.enable_print_op_pass) {
  1581. names_to_passes.emplace_back("PrintOpPass", &print_pass);
  1582. }
  1583. NoUseReshapeRemovePass no_use_reshape_remove_pass;
  1584. names_to_passes.emplace_back("NoUseReshapeRemovePass", &no_use_reshape_remove_pass);
  1585. DropOutPass dropout_pass;
  1586. AssertPass assert_pass;
  1587. UnusedConstPass unused_const_pass;
  1588. StopGradientPass stop_gradient_pass;
  1589. PreventGradientPass prevent_gradient_pass;
  1590. PlaceholderWithDefaultPass placeholder_with_default_pass;
  1591. GuaranteeConstPass guarantee_const_pass;
  1592. VarIsInitializedOpPass var_is_initialized_pass;
  1593. ParallelConcatStartOpPass parallel_concat_start_op_pass;
  1594. IdentityPass identity_pass(false);
  1595. AssignPass assign_pass;
  1596. SnapshotPass snapshot_pass;
  1597. if (!options_.train_graph_flag) {
  1598. names_to_passes.emplace_back("DropOutPass", &dropout_pass);
  1599. names_to_passes.emplace_back("AssertPass", &assert_pass);
  1600. }
  1601. names_to_passes.emplace_back("UnusedConstPass", &unused_const_pass);
  1602. names_to_passes.emplace_back("StopGradientPass", &stop_gradient_pass);
  1603. names_to_passes.emplace_back("PreventGradientPass", &prevent_gradient_pass);
  1604. names_to_passes.emplace_back("PlaceholderWithDefaultPass", &placeholder_with_default_pass);
  1605. names_to_passes.emplace_back("SnapshotPass", &snapshot_pass);
  1606. names_to_passes.emplace_back("GuaranteeConstPass", &guarantee_const_pass);
  1607. names_to_passes.emplace_back("VarIsInitializedOpPass", &var_is_initialized_pass);
  1608. names_to_passes.emplace_back("ParallelConcatStartOpPass", &parallel_concat_start_op_pass);
  1609. names_to_passes.emplace_back("IdentityPass", &identity_pass);
  1610. if (GetContext().GetHostExecFlag()) {
  1611. names_to_passes.emplace_back("AssignPass", &assign_pass);
  1612. }
  1613. GE_TIMESTAMP_START(names_to_passes);
  1614. ret = ge_passes.Run(names_to_passes);
  1615. GE_TIMESTAMP_END(names_to_passes, "GraphPrepare::NamesToPasses");
  1616. if (ret != SUCCESS) {
  1617. GELOGE(ret, "Run ge_passes optimize for preprocess failed, ret:%u.", ret);
  1618. return ret;
  1619. }
  1620. PassManager graph_pass;
  1621. try {
  1622. (void)graph_pass.AddPass("PrepareOptimize::PrunePass", new PrunePass);
  1623. // todo 临时把hccl的memcpy插入放到图准备,为了防止其多插memcpy
  1624. (void)graph_pass.AddPass("PrepareOptimize::HcclMemcpyPass", new (std::nothrow) HcclMemcpyPass);
  1625. } catch (std::bad_alloc &e) {
  1626. GELOGE(INTERNAL_ERROR, "Add pass failed, bad memory allocation occurs.");
  1627. return INTERNAL_ERROR;
  1628. }
  1629. GE_TIMESTAMP_START(graph_passes);
  1630. ret = graph_pass.Run(compute_graph_);
  1631. GE_TIMESTAMP_END(graph_passes, "GraphPrepare::GraphPasses");
  1632. if (ret != SUCCESS && ret != NOT_CHANGED) {
  1633. GELOGE(ret, "Run graph passes optimize for preprocess failed, ret:%u.", ret);
  1634. return ret;
  1635. }
  1636. // The constant for train is CONSTANTOP, and is CONSTANT for inference. They will be unified in future.
  1637. TypeConversionOfConstant();
  1638. ret = compute_graph_->TopologicalSorting();
  1639. if (ret != SUCCESS) {
  1640. GELOGE(ret, "Graph topological sort failed, ret:%u.", ret);
  1641. return ret;
  1642. }
  1643. GELOGI("End optimize for preprocess.");
  1644. return SUCCESS;
  1645. }
  1646. void GraphPrepare::TypeConversionOfConstant() {
  1647. if (options_.train_graph_flag) {
  1648. GELOGD("trans CONSTANT to CONSTANTOP in train.");
  1649. for (ge::NodePtr &n : compute_graph_->GetAllNodes()) {
  1650. // This can ensure that n is not a null pointer
  1651. if (n->GetOpDesc()->GetType() == CONSTANT) {
  1652. n->GetOpDesc()->SetType(CONSTANTOP);
  1653. }
  1654. }
  1655. } else {
  1656. GELOGD("trans CONSTANTOP to CONSTANT in inferrence.");
  1657. for (ge::NodePtr &n : compute_graph_->GetAllNodes()) {
  1658. // This can ensure that n is not a null pointer
  1659. if (n->GetOpDesc()->GetType() == CONSTANTOP) {
  1660. n->GetOpDesc()->SetType(CONSTANT);
  1661. }
  1662. }
  1663. }
  1664. }
  1665. Status GraphPrepare::GraphEquivalentTransformation() {
  1666. NamesToPass names_to_pass;
  1667. ForPass for_pass;
  1668. names_to_pass.emplace_back("ForToWhilePass", &for_pass);
  1669. return GEPass(compute_graph_).Run(names_to_pass);
  1670. }
  1671. Status GraphPrepare::ProcessBeforeInfershape() {
  1672. NamesToPass names_to_passes;
  1673. CondRemovePass condition_remove_pass;
  1674. names_to_passes.emplace_back("CondRemovePass", &condition_remove_pass);
  1675. GE_TIMESTAMP_START(ProcessCondRemove);
  1676. auto ret = GEPass(compute_graph_).Run(names_to_passes);
  1677. GE_TIMESTAMP_END(ProcessCondRemove, "GraphManager::ProcessCondRemove");
  1678. if (ret != SUCCESS) {
  1679. GELOGE(ret, "Run ge_passes optimize for OptimizeAfterMergeSubGraph failed, ret:%d.", ret);
  1680. return ret;
  1681. }
  1682. return SUCCESS;
  1683. }
  1684. Status GraphPrepare::ProcessNetOutput() {
  1685. PassManager graph_passes_before_infershape;
  1686. try {
  1687. if (options_.train_graph_flag) {
  1688. graph_passes_before_infershape.AddPass("ProcessNetOutput::SavePass", new (std::nothrow) SavePass);
  1689. }
  1690. graph_passes_before_infershape.AddPass("ProcessNetOutput::NetOutputPass", new (std::nothrow) NetOutputPass);
  1691. graph_passes_before_infershape.AddPass("ProcessNetOutput::DataPass",
  1692. new (std::nothrow) DataPass); // Add NetOutput first.
  1693. } catch (std::bad_alloc) {
  1694. GELOGE(INTERNAL_ERROR, "Add pass failed, bad memory allocation occurs.");
  1695. return INTERNAL_ERROR;
  1696. }
  1697. auto ret = graph_passes_before_infershape.Run(compute_graph_);
  1698. if ((ret != SUCCESS) && (ret != NOT_CHANGED)) {
  1699. GELOGE(ret, "Run graph_passes_before_infershape failed, ret:%d.", ret);
  1700. return ret;
  1701. }
  1702. return SUCCESS;
  1703. }
  1704. Status GraphPrepare::CheckAndUpdateInput(const std::vector<GeTensor> &user_input) {
  1705. compute_graph_->SetInputSize(user_input.size());
  1706. if (user_input.empty()) {
  1707. return SUCCESS;
  1708. }
  1709. auto ret = CheckUserInput(user_input);
  1710. if (ret != SUCCESS) {
  1711. GELOGE(ret, "Check user input failed.");
  1712. return ret;
  1713. }
  1714. ret = UpdateInput(user_input);
  1715. if (ret != SUCCESS) {
  1716. GELOGE(ret, "UpdateInput fail, ret:%u", ret);
  1717. return ret;
  1718. }
  1719. if (user_input.size() != 0) {
  1720. ret = CheckConstOp();
  1721. if (ret != SUCCESS) {
  1722. GELOGE(ret, "CheckConstOp fail, ret:%u", ret);
  1723. return ret;
  1724. }
  1725. } else {
  1726. ret = compute_graph_->TopologicalSorting();
  1727. if (ret != SUCCESS) {
  1728. GELOGE(ret, "graph prepare error: compute_graph_->Topological Sorting");
  1729. return FAILED;
  1730. }
  1731. }
  1732. return SUCCESS;
  1733. }
  1734. Status GraphPrepare::UpdateInputOutputByOptions() {
  1735. auto ret = UpdateDataNetOutputByStorageFormat();
  1736. if (ret != SUCCESS) {
  1737. GELOGE(ret, "Update format acoording to storage format failed.");
  1738. return ret;
  1739. }
  1740. if (options_.train_graph_flag) {
  1741. GELOGI("This is train mode, no need to do this schedule.");
  1742. return SUCCESS;
  1743. }
  1744. for (auto &node_ptr : compute_graph_->GetDirectNode()) {
  1745. GE_CHECK_NOTNULL(node_ptr);
  1746. if (CheckIfNeedSetNdFormat(node_ptr) != SUCCESS) {
  1747. GELOGE(INTERNAL_ERROR, "Set node [%s] format ND failed", node_ptr->GetName().c_str());
  1748. return FAILED;
  1749. }
  1750. if (node_ptr->GetType() == DATA) {
  1751. if (ProcessDataNodeDynShape(node_ptr) != SUCCESS) {
  1752. GELOGE(INTERNAL_ERROR, "Process data node failed");
  1753. return FAILED;
  1754. }
  1755. }
  1756. if (node_ptr->GetType() == ge::NETOUTPUT) {
  1757. if (ProcessNetoutputNodeDynShape(node_ptr) != SUCCESS) {
  1758. GELOGE(INTERNAL_ERROR, "Process netoutput node failed");
  1759. return FAILED;
  1760. }
  1761. }
  1762. }
  1763. return SUCCESS;
  1764. }
  1765. bool GraphPrepare::IsTansDataOpData(const ge::NodePtr &var_node) {
  1766. for (auto &out_anchor : var_node->GetAllOutDataAnchors()) {
  1767. GE_RT_FALSE_CHECK_NOTNULL(out_anchor);
  1768. for (auto &in_anchor : out_anchor->GetPeerInDataAnchors()) {
  1769. GE_RT_FALSE_CHECK_NOTNULL(in_anchor);
  1770. ge::NodePtr dst_node = in_anchor->GetOwnerNode();
  1771. GE_RT_FALSE_CHECK_NOTNULL(dst_node);
  1772. if (dst_node->GetType() == TRANSDATA) {
  1773. return true;
  1774. }
  1775. }
  1776. }
  1777. return false;
  1778. }
  1779. } // namespace ge

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