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

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