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 75 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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867
  1. /**
  2. * Copyright 2019-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. GELOGE(INTERNAL_ERROR, "The trans node type %s does not exists", node_type.c_str());
  208. return nullptr;
  209. }
  210. OpDescPtr op_desc = MakeShared<OpDesc>(name, node_type);
  211. if (op_desc == nullptr) {
  212. GELOGE(INTERNAL_ERROR, "Create shared ptr for OpDesc failed");
  213. return nullptr;
  214. }
  215. // for data dump
  216. GE_IF_BOOL_EXEC(
  217. !AttrUtils::SetListStr(op_desc, ATTR_NAME_DATA_DUMP_ORIGIN_OP_NAMES, std::move(std::vector<std::string>())),
  218. GELOGW("CreateTransNode: SetListStr failed");)
  219. // Default single input and single output
  220. auto ret = op_desc->AddInputDesc(input);
  221. if (ret != GRAPH_SUCCESS) {
  222. GELOGE(INTERNAL_ERROR, "Failed to add input desc when create node %s type %s", name.c_str(), node_type.c_str());
  223. return nullptr;
  224. }
  225. ret = op_desc->AddOutputDesc(output);
  226. if (ret != GRAPH_SUCCESS) {
  227. GELOGE(INTERNAL_ERROR, "Failed to add output desc when create node %s type %s", name.c_str(), node_type.c_str());
  228. return nullptr;
  229. }
  230. AddTransNodeAttr(node_type, input, output, op_desc);
  231. NodePtr shape_node = nullptr;
  232. if (node_type == RESHAPE) {
  233. auto shape_desc = CreateTensorShape(output);
  234. if (shape_desc == nullptr) {
  235. GELOGE(INTERNAL_ERROR, "Failed to add shape for reshape %s, can not create the shape input",
  236. node->GetName().c_str());
  237. return nullptr;
  238. }
  239. ret = op_desc->AddInputDesc(shape_desc->GetOutputDesc(0));
  240. if (ret != GRAPH_SUCCESS) {
  241. GELOGE(INTERNAL_ERROR, "Failed to add the first input for reshape %s", name.c_str());
  242. return nullptr;
  243. }
  244. shape_node = graph->AddNode(shape_desc);
  245. if (shape_node == nullptr) {
  246. GELOGE(INTERNAL_ERROR, "Failed to add shape node for reshape %s, can not add the shape to graph", name.c_str());
  247. return nullptr;
  248. }
  249. }
  250. auto trans_node = graph->AddNode(op_desc);
  251. if (trans_node == nullptr) {
  252. GELOGE(INTERNAL_ERROR, "Failed to add trans node %s to graph", name.c_str());
  253. return nullptr;
  254. }
  255. if (node_type == RESHAPE) {
  256. if (GraphUtils::AddEdge(shape_node->GetOutDataAnchor(0), trans_node->GetInDataAnchor(1)) != GRAPH_SUCCESS) {
  257. GELOGE(INTERNAL_ERROR, "Failed to add shape node for reshape %s, can not add the edge", name.c_str());
  258. return nullptr;
  259. }
  260. }
  261. return trans_node;
  262. }
  263. Status RecoverOneTransNodeForVar(const std::string &name, const TransNodeInfo &trans_node_info, NodePtr node,
  264. NodePtr &trans_node) {
  265. GE_CHECK_NOTNULL(node);
  266. trans_node = CreateTransNode(name, trans_node_info.node_type, trans_node_info.output, trans_node_info.input, node);
  267. if (trans_node == nullptr) {
  268. return INTERNAL_ERROR;
  269. }
  270. auto ret = GraphUtils::ReplaceNodeDataAnchors(trans_node, node, {}, {0});
  271. if (ret != GRAPH_SUCCESS) {
  272. GELOGE(INTERNAL_ERROR, "Failed to replace out anchors when recover trans node for %s type %s",
  273. node->GetName().c_str(), node->GetType().c_str());
  274. return INTERNAL_ERROR;
  275. }
  276. ret = GraphUtils::AddEdge(node->GetOutDataAnchor(0), trans_node->GetInDataAnchor(0));
  277. if (ret != GRAPH_SUCCESS) {
  278. GELOGE(INTERNAL_ERROR, "Failed to connect node %s to trans node %s", node->GetName().c_str(),
  279. trans_node->GetName().c_str());
  280. return INTERNAL_ERROR;
  281. }
  282. ret = GraphUtils::MoveOutCtrlEdges(node, trans_node);
  283. if (ret != GRAPH_SUCCESS) {
  284. GELOGE(INTERNAL_ERROR, "Failed to move out control edges from %s to %s when recover trans node.",
  285. node->GetName().c_str(), trans_node->GetName().c_str());
  286. return INTERNAL_ERROR;
  287. }
  288. return SUCCESS;
  289. }
  290. Status RecoverOneTransNodeForVarRef(const std::string &name, const TransNodeInfo &trans_node_info, NodePtr node,
  291. NodePtr &trans_node) {
  292. GE_CHECK_NOTNULL(node);
  293. trans_node = CreateTransNode(name, trans_node_info.node_type, trans_node_info.input, trans_node_info.output, node);
  294. if (trans_node == nullptr) {
  295. return INTERNAL_ERROR;
  296. }
  297. auto ret = GraphUtils::ReplaceNodeDataAnchors(trans_node, node, {0}, {});
  298. if (ret != GRAPH_SUCCESS) {
  299. GELOGE(INTERNAL_ERROR, "Failed to replace int anchors when recover trans node for %s type %s",
  300. node->GetName().c_str(), node->GetType().c_str());
  301. return INTERNAL_ERROR;
  302. }
  303. ret = GraphUtils::AddEdge(trans_node->GetOutDataAnchor(0), node->GetInDataAnchor(0));
  304. if (ret != GRAPH_SUCCESS) {
  305. GELOGE(INTERNAL_ERROR, "Failed to connect trans node %s to node %s", trans_node->GetName().c_str(),
  306. node->GetName().c_str());
  307. return INTERNAL_ERROR;
  308. }
  309. ret = GraphUtils::MoveInCtrlEdges(node, trans_node);
  310. if (ret != GRAPH_SUCCESS) {
  311. GELOGE(INTERNAL_ERROR, "Failed to move int control edges from %s to %s when recover trans node.",
  312. node->GetName().c_str(), trans_node->GetName().c_str());
  313. return INTERNAL_ERROR;
  314. }
  315. return SUCCESS;
  316. }
  317. Status UpdateVarFormats(const NodePtr &var, const GeTensorDesc &tensor_desc) {
  318. GE_IF_BOOL_EXEC(var == nullptr, GELOGW("node : var is nullptr"); return INTERNAL_ERROR);
  319. GE_CHECK_NOTNULL(var->GetOpDesc());
  320. if (var->GetOpDesc()->GetOutputsSize() > 0) {
  321. auto output_desc = var->GetOpDesc()->GetOutputDesc(0);
  322. output_desc.SetFormat(tensor_desc.GetFormat());
  323. output_desc.SetDataType(tensor_desc.GetDataType());
  324. output_desc.SetShape(tensor_desc.GetShape());
  325. output_desc.SetOriginFormat(tensor_desc.GetOriginFormat());
  326. output_desc.SetOriginDataType(tensor_desc.GetOriginDataType());
  327. output_desc.SetOriginShape(tensor_desc.GetOriginShape());
  328. GE_IF_BOOL_EXEC(var->GetOpDesc()->UpdateOutputDesc(0, output_desc) != GRAPH_SUCCESS,
  329. GELOGE(INTERNAL_ERROR, "UpdateOutputDesc failed");
  330. return INTERNAL_ERROR;);
  331. }
  332. if (var->GetOpDesc()->GetInputsSize() > 0) {
  333. auto desc = var->GetOpDesc()->GetInputDesc(0);
  334. desc.SetFormat(tensor_desc.GetFormat());
  335. desc.SetDataType(tensor_desc.GetDataType());
  336. desc.SetShape(tensor_desc.GetShape());
  337. desc.SetOriginFormat(tensor_desc.GetOriginFormat());
  338. desc.SetOriginDataType(tensor_desc.GetOriginDataType());
  339. desc.SetOriginShape(tensor_desc.GetOriginShape());
  340. GE_IF_BOOL_EXEC(var->GetOpDesc()->UpdateInputDesc(0, desc) != GRAPH_SUCCESS,
  341. GELOGE(INTERNAL_ERROR, "UpdateInputDesc failed");
  342. return INTERNAL_ERROR;)
  343. }
  344. return SUCCESS;
  345. }
  346. Status RecoverTransRoadForVar(const NodePtr &var, const VarTransRoad &road) {
  347. GE_CHECK_NOTNULL(var);
  348. int index = 0;
  349. NodePtr last_node = var;
  350. for (auto iter = road.rbegin(); iter != road.rend(); ++iter) {
  351. auto trans_name = var->GetName() + "_trans_" + std::to_string(index++);
  352. auto ret = RecoverOneTransNodeForVar(trans_name, *iter, last_node, last_node);
  353. if (ret != SUCCESS) {
  354. GELOGE(INTERNAL_ERROR, "Failed to recover trans node for variable %s, index %d, type %s", var->GetName().c_str(),
  355. index, iter->node_type.c_str());
  356. return INTERNAL_ERROR;
  357. }
  358. // set stream_label
  359. OpDescPtr var_desc = var->GetOpDesc();
  360. GE_CHECK_NOTNULL(var_desc);
  361. std::string stream_label;
  362. (void)AttrUtils::GetStr(var_desc, ATTR_NAME_STREAM_LABEL, stream_label);
  363. if (!stream_label.empty()) {
  364. GE_CHK_STATUS_RET(SetStreamLabel(last_node, stream_label), "set stream label failed");
  365. }
  366. GE_CHK_BOOL_EXEC((ge::AttrUtils::SetBool(last_node->GetOpDesc(), ge::ATTR_INSERTED_BY_GE, true)),
  367. return INTERNAL_ERROR, "Set attr ATTR_INSERTED_BY_GE failed.");
  368. GELOGD("Recover trans node %s type %s success", trans_name.c_str(), iter->node_type.c_str());
  369. }
  370. if (road.empty()) {
  371. return SUCCESS;
  372. }
  373. return UpdateVarFormats(var, road.rbegin()->output);
  374. }
  375. Status RecoverTransRoadForVarRef(const std::set<NodePtr> &nodes, const VarTransRoad &road) {
  376. for (auto &var : nodes) {
  377. GE_CHECK_NOTNULL(var);
  378. int index = 0;
  379. NodePtr last_node = var;
  380. GELOGI("Recover trans nodes for variable ref %s", var->GetName().c_str());
  381. for (auto iter = road.rbegin(); iter != road.rend(); ++iter) {
  382. auto trans_name = var->GetName() + "_trans_" + std::to_string(index++);
  383. auto ret = RecoverOneTransNodeForVarRef(trans_name, *iter, last_node, last_node);
  384. if (ret != SUCCESS) {
  385. GELOGE(INTERNAL_ERROR, "Failed to recover trans node for variable %s, index %d, type %s",
  386. var->GetName().c_str(), index, iter->node_type.c_str());
  387. return INTERNAL_ERROR;
  388. }
  389. // set stream_label
  390. OpDescPtr var_desc = var->GetOpDesc();
  391. GE_CHECK_NOTNULL(var_desc);
  392. std::string stream_label;
  393. (void)AttrUtils::GetStr(var_desc, ATTR_NAME_STREAM_LABEL, stream_label);
  394. if (!stream_label.empty()) {
  395. GE_CHK_STATUS_RET(SetStreamLabel(last_node, stream_label), "set stream label failed");
  396. }
  397. GE_CHK_BOOL_EXEC((ge::AttrUtils::SetBool(last_node->GetOpDesc(), ge::ATTR_INSERTED_BY_GE, true)),
  398. return INTERNAL_ERROR, "Set attr ATTR_INSERTED_BY_GE failed.");
  399. }
  400. if (!(road.empty()) && (UpdateVarFormats(var, road.rbegin()->output) != SUCCESS)) {
  401. return INTERNAL_ERROR;
  402. }
  403. }
  404. return SUCCESS;
  405. }
  406. using VarNamesToRefs = std::map<std::string, std::set<NodePtr>>;
  407. VarNamesToRefs CollectVarNamesToRefs(const ComputeGraphPtr &graph) {
  408. VarNamesToRefs names_to_refs;
  409. std::string var_name;
  410. if (graph == nullptr) {
  411. GELOGE(PARAM_INVALID, "graph is null.");
  412. return names_to_refs;
  413. }
  414. for (auto &node : graph->GetAllNodes()) {
  415. if (node->GetType() != VARIABLE) {
  416. continue;
  417. }
  418. if (AttrUtils::GetStr(node->GetOpDesc(), REF_VAR_SRC_VAR_NAME, var_name)) {
  419. (void)names_to_refs[var_name].insert(node);
  420. }
  421. }
  422. return names_to_refs;
  423. }
  424. Status TransferShape2NC1HWC0(Format src_format, const std::vector<int64_t> &src_shape, DataType dt, Format dst_format,
  425. std::vector<int64_t> &dst_shape) {
  426. if (src_format == FORMAT_NCHW) {
  427. formats::FormatTransferNchwNc1hwc0 transfer;
  428. if (transfer.TransShape(src_format, src_shape, dt, dst_format, dst_shape) != SUCCESS) {
  429. GELOGE(INTERNAL_ERROR, "TransShape failed");
  430. return FAILED;
  431. }
  432. } else if (src_format == FORMAT_NHWC) {
  433. formats::FormatTransferNhwcNc1hwc0 transfer;
  434. if (transfer.TransShape(src_format, src_shape, dt, dst_format, dst_shape) != SUCCESS) {
  435. GELOGE(INTERNAL_ERROR, "TransShape failed");
  436. return FAILED;
  437. }
  438. }
  439. return SUCCESS;
  440. }
  441. Status ModifyInputFormatAndShape(NodePtr &node_ptr) {
  442. GE_CHECK_NOTNULL(node_ptr);
  443. auto op_desc = node_ptr->GetOpDesc();
  444. GE_CHECK_NOTNULL(op_desc);
  445. const GeTensorDescPtr &input = op_desc->MutableInputDesc(0);
  446. GE_CHECK_NOTNULL(input);
  447. ge::Format old_format = input->GetFormat();
  448. std::vector<int64_t> old_shape = input->GetShape().GetDims();
  449. ge::DataType dt = input->GetDataType();
  450. std::vector<int64_t> dst_shape_dims;
  451. if (TransferShape2NC1HWC0(old_format, old_shape, dt, FORMAT_NC1HWC0, dst_shape_dims) != SUCCESS) {
  452. GELOGE(INTERNAL_ERROR, "Trans shape failed");
  453. return FAILED;
  454. }
  455. input->SetFormat(FORMAT_NC1HWC0);
  456. input->SetShape(ge::GeShape(dst_shape_dims));
  457. auto output = op_desc->MutableOutputDesc(0);
  458. GE_CHECK_NOTNULL(output);
  459. output->SetFormat(FORMAT_NC1HWC0);
  460. output->SetShape(ge::GeShape(dst_shape_dims));
  461. int64_t size = 0;
  462. graphStatus graph_status = TensorUtils::GetTensorMemorySizeInBytes(*output, size);
  463. if (graph_status != ge::GRAPH_SUCCESS) {
  464. GELOGE(graph_status, "GetTensorSizeInBytes failed!");
  465. return FAILED;
  466. }
  467. ge::TensorUtils::SetSize(*output, size);
  468. ge::TensorUtils::SetSize(*input, size);
  469. return SUCCESS;
  470. }
  471. Status ModifyFormatAndShapeForSingleTensor(const GeTensorDescPtr &input_output) {
  472. GE_CHECK_NOTNULL(input_output);
  473. ge::Format old_format = input_output->GetFormat();
  474. std::vector<int64_t> old_shape = input_output->GetShape().GetDims();
  475. ge::DataType dt = input_output->GetDataType();
  476. std::vector<int64_t> dst_shape_dims;
  477. if (TransferShape2NC1HWC0(old_format, old_shape, dt, FORMAT_NC1HWC0, dst_shape_dims) != SUCCESS) {
  478. GELOGE(INTERNAL_ERROR, "Trans shape failed");
  479. return FAILED;
  480. }
  481. input_output->SetFormat(FORMAT_NC1HWC0);
  482. input_output->SetShape(ge::GeShape(dst_shape_dims));
  483. return SUCCESS;
  484. }
  485. Status ModifyDataNetOutputFormatAndShape(OpDescPtr &op_desc, uint32_t index, Format storage_format,
  486. vector<int64_t> &dst_shape_dims) {
  487. GE_CHECK_NOTNULL(op_desc);
  488. const GeTensorDescPtr &input = op_desc->MutableInputDesc(index);
  489. GE_CHECK_NOTNULL(input);
  490. ge::Format old_format = input->GetFormat();
  491. std::vector<int64_t> old_shape = input->GetShape().GetDims();
  492. input->SetShape(ge::GeShape(dst_shape_dims));
  493. input->SetFormat(storage_format);
  494. auto output = op_desc->MutableOutputDesc(index);
  495. GE_CHECK_NOTNULL(output);
  496. output->SetShape(ge::GeShape(dst_shape_dims));
  497. output->SetFormat(storage_format);
  498. if (!output->MutableShape().IsUnknownShape()) {
  499. int64_t size = 0;
  500. graphStatus graph_status = TensorUtils::GetTensorMemorySizeInBytes(*output, size);
  501. if (graph_status != ge::GRAPH_SUCCESS) {
  502. GELOGE(graph_status, "GetTensorSizeInBytes failed!");
  503. return FAILED;
  504. }
  505. ge::TensorUtils::SetSize(*input, size);
  506. ge::TensorUtils::SetSize(*output, size);
  507. GELOGI(
  508. "Modify Data NetOutput format and shape success, node:%s, index:%d, old_shape:%s, old_Format:%s, "
  509. "new_shape:%s, new_format:%s, new_size:%lu",
  510. op_desc->GetName().c_str(), index, formats::JoinToString(old_shape).c_str(),
  511. ge::TypeUtils::FormatToSerialString(old_format).c_str(), formats::JoinToString(dst_shape_dims).c_str(),
  512. ge::TypeUtils::FormatToSerialString(storage_format).c_str(), size);
  513. }
  514. return SUCCESS;
  515. }
  516. Status CheckIfDynamicBatchScene(NodePtr &data_node, bool &is_dynamic_batch, NodePtr &switchn_node) {
  517. is_dynamic_batch = false;
  518. std::string related_node_name;
  519. if (AttrUtils::GetStr(data_node->GetOpDesc(), kMbatchSwitchnName, related_node_name)) {
  520. if (related_node_name.empty()) {
  521. GELOGE(INTERNAL_ERROR, "The data node %s has switchn node flag, but the value is empty",
  522. data_node->GetName().c_str());
  523. return INTERNAL_ERROR;
  524. }
  525. for (const NodePtr &next_node : data_node->GetOutNodes()) {
  526. if (next_node->GetName() == related_node_name) {
  527. switchn_node = next_node;
  528. break;
  529. }
  530. }
  531. if (switchn_node == nullptr) {
  532. GELOGE(INTERNAL_ERROR, "The data node %s has switchn node %s, but can not find it on the graph",
  533. data_node->GetName().c_str(), related_node_name.c_str());
  534. return INTERNAL_ERROR;
  535. }
  536. is_dynamic_batch = true;
  537. }
  538. return SUCCESS;
  539. }
  540. bool CheckOpType(const NodePtr &node, const std::string type) {
  541. if (node->GetType() == type) {
  542. return true;
  543. }
  544. return false;
  545. }
  546. Status CheckIfNeedSetNdFormat(const NodePtr &node_ptr) {
  547. auto op = node_ptr->GetOpDesc();
  548. GE_CHECK_NOTNULL(op);
  549. auto inputDescsPtr = op->GetAllInputsDescPtr();
  550. auto outputDescsPtr = op->GetAllOutputsDescPtr();
  551. ge::Format format = ge::FORMAT_ND;
  552. // if user set shape larger than 4, inferformat may set NCHW or NHWC, GE should set ND before FE
  553. // process, otherwise fe will insert transdata.
  554. for (auto &inputDescPtr : inputDescsPtr) {
  555. GE_CHECK_NOTNULL(inputDescPtr);
  556. if ((inputDescPtr->GetShape().GetDims().size() > ge::DIM_DEFAULT_SIZE) &&
  557. ((inputDescPtr->GetFormat() == ge::FORMAT_NCHW) || (inputDescPtr->GetFormat() == ge::FORMAT_NHWC))) {
  558. GELOGI("The node inputdesc [%s] format need to be set ND", op->GetName().c_str());
  559. inputDescPtr->SetFormat(format);
  560. inputDescPtr->SetOriginFormat(format);
  561. }
  562. }
  563. for (auto &outputDescPtr : outputDescsPtr) {
  564. GE_CHECK_NOTNULL(outputDescPtr);
  565. if ((outputDescPtr->GetShape().GetDims().size() > ge::DIM_DEFAULT_SIZE) &&
  566. ((outputDescPtr->GetFormat() == ge::FORMAT_NCHW) || (outputDescPtr->GetFormat() == ge::FORMAT_NHWC))) {
  567. GELOGI("The node outputdesc [%s] format need to be set ND", op->GetName().c_str());
  568. outputDescPtr->SetFormat(format);
  569. outputDescPtr->SetOriginFormat(format);
  570. }
  571. }
  572. return SUCCESS;
  573. }
  574. // A new function ending in 'DynShape' has been added for the dynamic shape processing.
  575. // In the dynamic shape process, transnode insertion by FE is advanced to the stage of whole
  576. // graph optimization, GE only sets the final data_type/format/shape information for variable,
  577. // data and netoutput, and no longer inserts the transnode.
  578. Status ProcessInputDtDynShape(NodePtr &node_ptr, bool &is_dynamic_batch, NodePtr &switchn_node, DataType &dt_set) {
  579. GE_CHECK_NOTNULL(node_ptr);
  580. auto op_desc = node_ptr->GetOpDesc();
  581. GE_CHECK_NOTNULL(op_desc);
  582. const GeTensorDescPtr &input = op_desc->MutableInputDesc(0);
  583. GE_CHECK_NOTNULL(input);
  584. ge::DataType src_dtype = input->GetDataType();
  585. if (src_dtype == dt_set) {
  586. GELOGI("The node name, %s dtype is fp16", node_ptr->GetName().c_str());
  587. return SUCCESS;
  588. }
  589. input->SetDataType(dt_set);
  590. int64_t input_shape_size = 0;
  591. int64_t output_shape_size = 0;
  592. ge::graphStatus input_graph_status = ge::TensorUtils::GetTensorSizeInBytes(*input, input_shape_size);
  593. ge::graphStatus output_graph_status = ge::TensorUtils::GetTensorMemorySizeInBytes(*input, output_shape_size);
  594. if (input_graph_status != ge::GRAPH_SUCCESS && output_graph_status != ge::GRAPH_SUCCESS) {
  595. GELOGE(GRAPH_FAILED, "GetTensorSize failed!");
  596. return FAILED;
  597. }
  598. ge::TensorUtils::SetSize(*input, input_shape_size);
  599. const GeTensorDescPtr &output = op_desc->MutableOutputDesc(0);
  600. GE_CHECK_NOTNULL(output);
  601. output->SetDataType(dt_set);
  602. ge::TensorUtils::SetSize(*output, output_shape_size);
  603. if (is_dynamic_batch) {
  604. GELOGI("The node [%s] dtype set fp16", switchn_node->GetName().c_str());
  605. auto switchn_op_desc = switchn_node->GetOpDesc();
  606. GE_CHECK_NOTNULL(switchn_op_desc);
  607. auto switchn_input = switchn_op_desc->MutableInputDesc(0);
  608. GE_CHECK_NOTNULL(switchn_input);
  609. switchn_input->SetDataType(dt_set);
  610. for (uint32_t i = 0; i < switchn_node->GetAllOutDataAnchorsSize(); ++i) {
  611. const GeTensorDescPtr &switchn_output = switchn_op_desc->MutableOutputDesc(i);
  612. GE_CHECK_NOTNULL(switchn_output);
  613. switchn_output->SetDataType(dt_set);
  614. }
  615. }
  616. return SUCCESS;
  617. }
  618. Status ProcessInputNC1HWC0DynShape(NodePtr &node_ptr, bool &is_dynamic_batch, NodePtr &switchn_node) {
  619. GE_CHECK_NOTNULL(node_ptr);
  620. auto op_desc = node_ptr->GetOpDesc();
  621. GE_CHECK_NOTNULL(op_desc);
  622. const GeTensorDescPtr &input = op_desc->MutableInputDesc(0);
  623. GE_CHECK_NOTNULL(input);
  624. ge::Format old_format = input->GetFormat();
  625. ge::GeShape old_shape = input->GetShape();
  626. bool support = ((old_format == FORMAT_NC1HWC0) || (old_format == FORMAT_NCHW) || (old_format == FORMAT_NHWC));
  627. if (!support) {
  628. GELOGE(INTERNAL_ERROR, "The format [%s] is unsupported", TypeUtils::FormatToSerialString(old_format).c_str());
  629. return FAILED;
  630. }
  631. if (ModifyInputFormatAndShape(node_ptr) != SUCCESS) {
  632. GELOGE(INTERNAL_ERROR, "modify format and shape failed");
  633. return FAILED;
  634. }
  635. if (is_dynamic_batch) {
  636. auto switchn_op_desc = switchn_node->GetOpDesc();
  637. GE_CHECK_NOTNULL(switchn_op_desc);
  638. const GeTensorDescPtr &switchn_input = switchn_op_desc->MutableInputDesc(0);
  639. if (ModifyFormatAndShapeForSingleTensor(switchn_input) != SUCCESS) {
  640. GELOGE(INTERNAL_ERROR, "modify format and shape failed");
  641. return FAILED;
  642. }
  643. for (uint32_t i = 0; i < switchn_node->GetAllOutDataAnchorsSize(); ++i) {
  644. auto switchn_output = switchn_op_desc->MutableOutputDesc(i);
  645. GE_CHECK_NOTNULL(switchn_output);
  646. old_format = switchn_output->GetFormat();
  647. old_shape = switchn_output->GetShape();
  648. if (ModifyFormatAndShapeForSingleTensor(switchn_output) != SUCCESS) {
  649. GELOGE(INTERNAL_ERROR, "modify format and shape failed");
  650. return FAILED;
  651. }
  652. }
  653. }
  654. return SUCCESS;
  655. }
  656. Status ProcessDataNodeDynShape(NodePtr &node_ptr) {
  657. auto op_desc = node_ptr->GetOpDesc();
  658. GE_CHECK_NOTNULL(op_desc);
  659. string set_dt_str;
  660. if (!ge::AttrUtils::GetStr(node_ptr->GetOpDesc(), ATTR_ATC_USER_DEFINE_DATATYPE, set_dt_str)) {
  661. return SUCCESS;
  662. }
  663. DataType dt_set = TypeUtils::SerialStringToDataType(set_dt_str);
  664. GELOGI("input_fp16 is found, the node name is %s.", node_ptr->GetName().c_str());
  665. bool is_dynamic_batch = false;
  666. NodePtr switchn_node = nullptr;
  667. if (CheckIfDynamicBatchScene(node_ptr, is_dynamic_batch, switchn_node)) {
  668. GELOGE(INTERNAL_ERROR, "CheckIfDynamicBatchScene failed");
  669. return FAILED;
  670. }
  671. if (ProcessInputDtDynShape(node_ptr, is_dynamic_batch, switchn_node, dt_set) != SUCCESS) {
  672. GELOGE(INTERNAL_ERROR, "ProcessInputFP16 failed");
  673. return FAILED;
  674. }
  675. // check if need to set format
  676. string set_format;
  677. bool ret = ge::AttrUtils::GetStr(node_ptr->GetOpDesc(), ATTR_ATC_USER_DEFINE_FORMAT, set_format);
  678. if (ret && (!set_format.empty()) && TypeUtils::SerialStringToFormat(set_format) == FORMAT_NC1HWC0) {
  679. GELOGI("The format of node [%s] should be set NC1HWC0.", node_ptr->GetName().c_str());
  680. if (ProcessInputNC1HWC0DynShape(node_ptr, is_dynamic_batch, switchn_node) != SUCCESS) {
  681. GELOGE(INTERNAL_ERROR, "ProcessInputNC1HWC0 failed");
  682. return FAILED;
  683. }
  684. }
  685. return SUCCESS;
  686. }
  687. Status GetStorageFormatAndShape(OpDescPtr &op_desc, const GeTensorDescPtr &tensor_desc_ptr, Format &storage_format,
  688. vector<int64_t> &dst_shape_dims) {
  689. GE_CHECK_NOTNULL(op_desc);
  690. GE_CHECK_NOTNULL(tensor_desc_ptr);
  691. storage_format = FORMAT_RESERVED;
  692. int64_t format = FORMAT_RESERVED;
  693. dst_shape_dims.clear();
  694. if (ge::AttrUtils::GetInt(*tensor_desc_ptr, ATTR_NAME_STORAGE_FORMAT, format)) {
  695. storage_format = static_cast<Format>(format);
  696. vector<int32_t> storage_shape;
  697. if (ge::AttrUtils::GetListInt(*tensor_desc_ptr, ATTR_NAME_STORAGE_SHAPE, storage_shape)) {
  698. for (auto dim : storage_shape) {
  699. dst_shape_dims.push_back(static_cast<int64_t>(dim));
  700. }
  701. GELOGI("Update node by storage format, node: [%s], storage_format: [%s], storage_shape:[%s]",
  702. op_desc->GetName().c_str(), TypeUtils::FormatToSerialString(storage_format).c_str(),
  703. formats::JoinToString(storage_shape).c_str());
  704. } else {
  705. GELOGE(PARAM_INVALID,
  706. "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("E19012", {"function", "reason"},
  1017. {"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. GeTensorDesc desc(user_input[index].GetTensorDesc());
  1046. auto format = desc.GetFormat();
  1047. auto origin_format = desc.GetOriginFormat();
  1048. // data maybe internal format [FRACTAL_NZ] at singleop process such as GEMM.
  1049. bool need_check_internal_format = (!IsTansDataOpData(input_node)) && (!options_.is_single_op);
  1050. if (need_check_internal_format) {
  1051. bool is_internal = TypeUtils::IsInternalFormat(format) || TypeUtils::IsInternalFormat(origin_format);
  1052. if (is_internal) {
  1053. GELOGE(PARAM_INVALID, "Input format %s or origin_format %s is not support.",
  1054. TypeUtils::FormatToSerialString(format).c_str(),
  1055. TypeUtils::FormatToSerialString(origin_format).c_str());
  1056. return FAILED;
  1057. }
  1058. }
  1059. auto data_type = desc.GetDataType();
  1060. uint32_t length = 1;
  1061. bool type_ret = TypeUtils::GetDataTypeLength(data_type, length);
  1062. if (!type_ret) {
  1063. GELOGE(PARAM_INVALID, "Input datatype %s is not support.",
  1064. TypeUtils::DataTypeToSerialString(data_type).c_str());
  1065. return FAILED;
  1066. }
  1067. int64_t desc_shape = desc.GetShape().GetShapeSize();
  1068. FMK_INT64_UINT32_MULCHECK(desc_shape, length);
  1069. int64_t shape_size = desc_shape * length;
  1070. GE_IF_BOOL_EXEC(shape_size == 0 && desc.GetShape().GetDimNum() == 0, shape_size = static_cast<int64_t>(length));
  1071. int64_t size = 0;
  1072. GE_IF_BOOL_EXEC(ge::TensorUtils::GetSize(desc, size) != GRAPH_SUCCESS,
  1073. GELOGE(INTERNAL_ERROR, "TensorUtils GetSize failed");
  1074. return FAILED);
  1075. bool size_check = (size != 0 && shape_size != size);
  1076. if (size_check) {
  1077. GELOGE(PARAM_INVALID, "input data size =%ld, shape_size =%ld.", size, shape_size);
  1078. return FAILED;
  1079. }
  1080. ge::TensorUtils::SetSize(desc, shape_size);
  1081. graphStatus graph_ret = op->UpdateInputDesc(0, desc);
  1082. if (graph_ret != GRAPH_SUCCESS) {
  1083. GELOGE(graph_ret, "UpdateInputDesc fail, graph_ret:%u", graph_ret);
  1084. return graph_ret;
  1085. }
  1086. // Size will be recalculated in the build stage
  1087. ge::TensorUtils::SetSize(desc, 0);
  1088. graph_ret = op->UpdateOutputDesc(0, desc);
  1089. if (graph_ret != GRAPH_SUCCESS) {
  1090. GELOGE(graph_ret, "UpdateOutputDesc fail, graph_ret:%u", graph_ret);
  1091. return graph_ret;
  1092. }
  1093. if (!options_.train_graph_flag) {
  1094. Status ret = AdjustDataOpOutput(input_node);
  1095. if (ret != SUCCESS) {
  1096. GELOGE(ret, "AdjustDataOpOutput fail, ret:%u", ret);
  1097. return ret;
  1098. }
  1099. }
  1100. }
  1101. }
  1102. return SUCCESS;
  1103. }
  1104. Status GraphPrepare::TryDoAipp() {
  1105. // infer and with aipp configure file, then call aipp insert
  1106. if ((!options_.train_graph_flag) && (!options_.insert_op_file.empty())) {
  1107. GE_DUMP(compute_graph_, "Before_insert_aipp");
  1108. Status ret = ge::InsertNewOpUtil::Instance().Init();
  1109. if (ret != SUCCESS) {
  1110. GELOGE(INTERNAL_ERROR, "TryDoAipp: InsertNewOpUtil instance failed.");
  1111. return INTERNAL_ERROR;
  1112. }
  1113. ret = ge::InsertNewOpUtil::Instance().Parse(options_.insert_op_file.c_str());
  1114. if (ret != SUCCESS) {
  1115. GELOGE(GE_GRAPH_OPTIMIZE_INSERT_OP_PARSE_FAILED, "TryDoAipp: parse config file %s failed",
  1116. options_.insert_op_file.c_str());
  1117. return GE_GRAPH_OPTIMIZE_INSERT_OP_PARSE_FAILED;
  1118. }
  1119. ret = ge::InsertNewOpUtil::Instance().InsertAippOps(compute_graph_, options_.insert_op_file);
  1120. if (ret != SUCCESS) {
  1121. GELOGE(GE_GRAPH_OPTIMIZE_INSERT_DYN_OP_FAILED, "TryDoAipp: insert aipp op ret failed, ret:%u", ret);
  1122. return GE_GRAPH_OPTIMIZE_INSERT_DYN_OP_FAILED;
  1123. }
  1124. }
  1125. return SUCCESS;
  1126. }
  1127. Status GraphPrepare::FormatAndShapeProcess() {
  1128. Status ret = ResourcePairProcess("add");
  1129. if (ret != SUCCESS) {
  1130. GELOGE(ret, "ResourcePairProcess failed");
  1131. return ret;
  1132. }
  1133. GE_TIMESTAMP_START(InferOriginFormat1);
  1134. ret = compute_graph_->InferOriginFormat();
  1135. GE_TIMESTAMP_END(InferOriginFormat1, "GraphPrepare::InferOriginFormat1");
  1136. GE_DUMP(compute_graph_, "after_first_inferformat");
  1137. if (ret != SUCCESS) {
  1138. GELOGE(ret, "Prepare Graph first inferformat failed");
  1139. return ret;
  1140. }
  1141. GE_TIMESTAMP_START(InferShapeForPreprocess);
  1142. ret = InferShapeForPreprocess();
  1143. GE_TIMESTAMP_END(InferShapeForPreprocess, "GraphPrepare::InferShapeForPreprocess");
  1144. GE_DUMP(compute_graph_, "after_infershape");
  1145. if (ret != SUCCESS) {
  1146. GELOGE(GE_GRAPH_INFERSHAPE_FAILED, "Prepare Graph infershape failed");
  1147. return GE_GRAPH_INFERSHAPE_FAILED;
  1148. }
  1149. GE_TIMESTAMP_START(InferOriginFormat2);
  1150. ret = compute_graph_->InferOriginFormat();
  1151. GE_TIMESTAMP_END(InferOriginFormat2, "GraphPrepare::InferOriginFormat2");
  1152. if (ret != SUCCESS) {
  1153. GELOGE(ret, "Prepare Graph inferformat failed");
  1154. return ret;
  1155. }
  1156. ret = ResourcePairProcess("remove");
  1157. if (ret != SUCCESS) {
  1158. return ret;
  1159. }
  1160. return ret;
  1161. }
  1162. Status GraphPrepare::ResourcePairProcess(const std::string &action) {
  1163. PassManager control_pass;
  1164. // Graph pass tmp logic for resource infershape
  1165. if (options_.train_graph_flag) {
  1166. try {
  1167. if (action == "add") {
  1168. (void)control_pass.AddPass("ResourcePairProcess::ResourcePairAddControlPass", new ResourcePairAddControlPass);
  1169. } else {
  1170. (void)control_pass.AddPass("ResourcePairProcess::ResourcePairRemoveControlPass",
  1171. new ResourcePairRemoveControlPass);
  1172. }
  1173. } catch (std::bad_alloc &e) {
  1174. GELOGE(INTERNAL_ERROR, "Add pass failed, bad memory allocation occur, action:%s.", action.c_str());
  1175. return INTERNAL_ERROR;
  1176. }
  1177. }
  1178. Status ret = control_pass.Run(compute_graph_);
  1179. if (ret != SUCCESS && ret != NOT_CHANGED) {
  1180. GELOGE(ret, "Run ResourcePairControlPass failed, action:%s, ret:%u.", action.c_str(), ret);
  1181. return ret;
  1182. }
  1183. return SUCCESS;
  1184. }
  1185. Status GraphPrepare::UpdateDataNetOutputByStorageFormat() {
  1186. for (auto &node_ptr : compute_graph_->GetAllNodes()) {
  1187. GE_CHECK_NOTNULL(node_ptr);
  1188. if (node_ptr->GetType() == DATA) {
  1189. uint32_t index = 0;
  1190. auto op_desc = node_ptr->GetOpDesc();
  1191. GE_CHECK_NOTNULL(op_desc);
  1192. const GeTensorDescPtr input = op_desc->MutableInputDesc(index);
  1193. Format storage_format = FORMAT_RESERVED;
  1194. vector<int64_t> dst_shape_dims;
  1195. if (GetStorageFormatAndShape(op_desc, input, storage_format, dst_shape_dims) != SUCCESS) {
  1196. GELOGE(INTERNAL_ERROR, "Get storage format for input failed");
  1197. return FAILED;
  1198. }
  1199. if (storage_format == FORMAT_RESERVED) {
  1200. continue;
  1201. }
  1202. if (ModifyDataNetOutputFormatAndShape(op_desc, index, storage_format, dst_shape_dims) != SUCCESS) {
  1203. GELOGE(INTERNAL_ERROR, "Modify format and shape for inputfailed");
  1204. return FAILED;
  1205. }
  1206. }
  1207. if (node_ptr->GetType() == ge::NETOUTPUT) {
  1208. auto op_desc = node_ptr->GetOpDesc();
  1209. GE_CHECK_NOTNULL(op_desc);
  1210. for (uint32_t index = 0; index < op_desc->GetOutputsSize(); index++) {
  1211. const GeTensorDescPtr output = op_desc->MutableOutputDesc(index);
  1212. Format storage_format = FORMAT_RESERVED;
  1213. vector<int64_t> dst_shape_dims;
  1214. if (GetStorageFormatAndShape(op_desc, output, storage_format, dst_shape_dims) != SUCCESS) {
  1215. GELOGE(INTERNAL_ERROR, "Get storage format from output failed");
  1216. return FAILED;
  1217. }
  1218. if (storage_format == FORMAT_RESERVED) {
  1219. continue;
  1220. }
  1221. if (ModifyDataNetOutputFormatAndShape(op_desc, index, storage_format, dst_shape_dims) != SUCCESS) {
  1222. GELOGE(INTERNAL_ERROR, "Modify format and shape for output failed");
  1223. return FAILED;
  1224. }
  1225. }
  1226. }
  1227. }
  1228. return SUCCESS;
  1229. }
  1230. Status GraphPrepare::SaveOriginalGraphToOmModel() {
  1231. if (options_.save_original_model == "true") {
  1232. ModelHelper model_helper;
  1233. Status ret = model_helper.SaveOriginalGraphToOmModel(ge::GraphUtils::CreateGraphFromComputeGraph(compute_graph_),
  1234. options_.original_model_file);
  1235. if (ret != SUCCESS) {
  1236. // If save original model fail, process continue
  1237. GELOGW("SaveOriginalGraphToOmModel fail");
  1238. }
  1239. }
  1240. return SUCCESS;
  1241. }
  1242. #define PP_RUN_AND_DUMP(name, func, ...) \
  1243. do { \
  1244. GE_RUN(Prepare, func, __VA_ARGS__); \
  1245. GE_DUMP(compute_graph, "PrepareAfter" name); \
  1246. GELOGI("Prepare %s on graph %s success.", name, compute_graph->GetName().c_str()); \
  1247. } while (0)
  1248. #define PP_RUN(name, func, ...) \
  1249. do { \
  1250. GE_RUN(Prepare, func, __VA_ARGS__); \
  1251. GELOGI("Prepare %s on graph %s success.", name, compute_graph->GetName().c_str()); \
  1252. } while (0)
  1253. Status GraphPrepare::PrepareDynShape(ConstGraphPtr graph, const std::vector<GeTensor> &user_input,
  1254. ge::ComputeGraphPtr &compute_graph, uint64_t session_id) {
  1255. GE_CHECK_NOTNULL(graph);
  1256. GE_CHECK_NOTNULL(compute_graph);
  1257. GetLocalOmgContext().type = static_cast<domi::FrameworkType>(options_.framework_type);
  1258. const Graph &const_graph = *graph;
  1259. PP_RUN("Init", Init, const_graph, session_id);
  1260. PP_RUN("SetRtContext", SetRtContext, rtContext_t(), RT_CTX_GEN_MODE);
  1261. PP_RUN_AND_DUMP("CheckAndUpdateInput", CheckAndUpdateInput, user_input);
  1262. PP_RUN_AND_DUMP("GraphEquivalentTransformation", GraphEquivalentTransformation);
  1263. PP_RUN_AND_DUMP("ProcessOutput", ProcessNetOutput);
  1264. PP_RUN_AND_DUMP("ProcessMultiBatch", multibatch::ProcessMultiBatch, compute_graph_);
  1265. PP_RUN_AND_DUMP("InsertAipp", TryDoAipp);
  1266. PP_RUN_AND_DUMP("ProcessBeforeInfershape", ProcessBeforeInfershape);
  1267. PP_RUN_AND_DUMP("InferFormatAndShape", FormatAndShapeProcess);
  1268. PP_RUN_AND_DUMP("GetDynamicOutputShape", multibatch::GetDynamicOutputShape, compute_graph_);
  1269. PP_RUN_AND_DUMP("ProcessAippStage2", InsertNewOpUtil::Instance().UpdateDataNodeByAipp, compute_graph_);
  1270. PP_RUN("SaveOriginalGraphToOmModel", SaveOriginalGraphToOmModel);
  1271. PP_RUN_AND_DUMP("PrepareOptimize", PrepareOptimize);
  1272. return SUCCESS;
  1273. }
  1274. Status GraphPrepare::RecordAIPPInfo(ge::ComputeGraphPtr &compute_graph) {
  1275. PP_RUN("RecordAIPPInfo", InsertNewOpUtil::Instance().RecordAIPPInfoToData, compute_graph_);
  1276. return SUCCESS;
  1277. }
  1278. Status GraphPrepare::PrepareRunningFormatRefiner() {
  1279. auto compute_graph = compute_graph_;
  1280. PassManager pass_manager;
  1281. GE_CHK_STATUS_RET(pass_manager.AddPass("PrepareRunningFormatRefiner::VariablePrepareOpPass",
  1282. new (std::nothrow) VariablePrepareOpPass))
  1283. GE_TIMESTAMP_START(pass_manager);
  1284. auto ret = pass_manager.Run(compute_graph);
  1285. GE_TIMESTAMP_END(pass_manager, "GraphPrepare::PrepareRunningFormatRefiner");
  1286. if (ret != SUCCESS && ret != NOT_CHANGED) {
  1287. GELOGE(ret, "Run passes for running format refiner failed, ret:%u.", ret);
  1288. return ret;
  1289. }
  1290. PP_RUN_AND_DUMP("UpdateInputOutputByUserOptions", UpdateInputOutputByOptions);
  1291. PP_RUN_AND_DUMP("UpdateVariableFormats", UpdateVariableFormats, compute_graph_);
  1292. return SUCCESS;
  1293. }
  1294. Status GraphPrepare::SwitchOpOptimize(ComputeGraphPtr &compute_graph) {
  1295. if (compute_graph == nullptr) {
  1296. GELOGE(GE_GRAPH_NULL_INPUT, "Input Graph is NULL");
  1297. return GE_GRAPH_NULL_INPUT;
  1298. }
  1299. GEPass ge_passes(compute_graph);
  1300. NamesToPass hccl_group;
  1301. HcclGroupPass hccl_group_pass;
  1302. GELOGD("Add hccl group pass success");
  1303. hccl_group.emplace_back("HcclGroupPass", &hccl_group_pass);
  1304. auto ret = ge_passes.Run(hccl_group);
  1305. if (ret != SUCCESS) {
  1306. GELOGE(ret, "Run HcclGroupPass pass for preprocess failed, ret:%u.", ret);
  1307. return ret;
  1308. }
  1309. ret = compute_graph->TopologicalSorting();
  1310. if (ret != SUCCESS) {
  1311. GELOGE(ret, "Graph topological sort failed, ret:%u.", ret);
  1312. return ret;
  1313. }
  1314. return SUCCESS;
  1315. }
  1316. #undef PP_RUN_AND_DUMP
  1317. #undef PP_RUN
  1318. Status GraphPrepare::GenerateInfershapeGraph(ConstGraphPtr graph) {
  1319. if (graph == nullptr) {
  1320. GELOGE(GE_GRAPH_NULL_INPUT, "Input Graph is NULL");
  1321. return GE_GRAPH_NULL_INPUT;
  1322. }
  1323. const Graph &const_graph = *graph;
  1324. Status ret = Init(const_graph, 0);
  1325. if (ret != SUCCESS) {
  1326. GELOGE(ret, "Init graph_prepare fail, ret:%u", ret);
  1327. return ret;
  1328. }
  1329. GE_DUMP(compute_graph_, "after_parser");
  1330. GELOGI("Start infershape for dump json process.");
  1331. ret = compute_graph_->InferOriginFormat();
  1332. GE_DUMP(compute_graph_, "after_inferformat");
  1333. if (ret != SUCCESS) {
  1334. GELOGE(ret, "Prepare Graph inferformat failed");
  1335. return ret;
  1336. }
  1337. InferShapePass infer_shape_pass;
  1338. NamesToPass names_to_passes;
  1339. names_to_passes.emplace_back("InferShapePass", &infer_shape_pass);
  1340. GEPass ge_passes(compute_graph_);
  1341. ret = ge_passes.Run(names_to_passes);
  1342. GE_DUMP(compute_graph_, "after_infershape");
  1343. if (ret != SUCCESS) {
  1344. GELOGE(ret, "Run ge_passes infershape for preprocess failed, ret:%u.", ret);
  1345. return ret;
  1346. }
  1347. ShapeRefiner::ClearContextMap();
  1348. return SUCCESS;
  1349. }
  1350. Status GraphPrepare::CheckConstOp() {
  1351. for (auto &node_ptr : compute_graph_->GetAllNodes()) {
  1352. GE_CHECK_NOTNULL(node_ptr);
  1353. if (node_ptr->GetType() == CONSTANT) {
  1354. Status ret = VerifyConstOp(node_ptr);
  1355. GE_CHK_BOOL_RET_STATUS(ret == SUCCESS, ret, "Const Op Check failed");
  1356. } else if (node_ptr->GetType() == FRAMEWORKOP) {
  1357. auto op_desc = node_ptr->GetOpDesc();
  1358. if (op_desc == nullptr) {
  1359. GELOGE(PARAM_INVALID, "Get op desc failed");
  1360. return PARAM_INVALID;
  1361. }
  1362. std::string original_type;
  1363. GE_IF_BOOL_EXEC(ge::AttrUtils::GetStr(op_desc, ATTR_NAME_FRAMEWORK_ORIGINAL_TYPE, original_type),
  1364. GELOGI("Get FrameWorkOp original type [%s]", original_type.c_str()));
  1365. GELOGI("original type is %s", original_type.c_str());
  1366. if (original_type == CONSTANT) {
  1367. Status ret = VerifyConstOp(node_ptr);
  1368. GE_CHK_BOOL_RET_STATUS(ret == SUCCESS, ret, "Const Op Check failed");
  1369. }
  1370. }
  1371. }
  1372. return SUCCESS;
  1373. }
  1374. Status GraphPrepare::VerifyConstOp(const NodePtr &node) {
  1375. GE_CHECK_NOTNULL(node);
  1376. auto op_desc = node->GetOpDesc();
  1377. GE_CHECK_NOTNULL(op_desc);
  1378. ConstGeTensorPtr ge_tensor_ptr;
  1379. if (!(AttrUtils::GetTensor(op_desc, ATTR_NAME_WEIGHTS, ge_tensor_ptr))) {
  1380. GELOGE(PARAM_INVALID, "Get value from const attr failed");
  1381. return PARAM_INVALID;
  1382. }
  1383. GE_CHECK_NOTNULL(ge_tensor_ptr);
  1384. auto data_size = ge_tensor_ptr->GetData().GetSize();
  1385. auto ge_tensor_desc = ge_tensor_ptr->GetTensorDesc();
  1386. int64_t shape_size = ge_tensor_desc.GetShape().GetShapeSize();
  1387. auto data_type = ge_tensor_desc.GetDataType();
  1388. uint32_t length = 1;
  1389. bool type_ret = TypeUtils::GetDataTypeLength(data_type, length);
  1390. if (!type_ret) {
  1391. GELOGE(PARAM_INVALID, "Input datatype %s is not support.", TypeUtils::DataTypeToSerialString(data_type).c_str());
  1392. return FAILED;
  1393. }
  1394. FMK_INT64_UINT32_MULCHECK(shape_size, length);
  1395. GELOGI("Const real value Size:%zu, op_desc Shape Size:%ld, data_type:%s.", data_size, shape_size * length,
  1396. TypeUtils::DataTypeToSerialString(data_type).c_str());
  1397. if (shape_size == 0) {
  1398. if (ge_tensor_desc.GetShape().GetDims().size() == 0) {
  1399. // shape = [], means it's a sclar tensor.
  1400. GE_CHK_BOOL_EXEC(data_size / length == 1, return PARAM_INVALID, "Const is invalid scalar tensor.");
  1401. } else {
  1402. // shape = [x, y, 0,...], means it's a vector tensor that value is [].
  1403. GE_CHK_BOOL_EXEC(data_size == 0, return PARAM_INVALID, "Const is invalid vector scalar.");
  1404. }
  1405. } else {
  1406. GE_CHK_BOOL_EXEC(data_size == static_cast<size_t>(shape_size * length) && data_size != 0, return PARAM_INVALID,
  1407. "Const input data size is not equal with tensor desc shape");
  1408. }
  1409. return SUCCESS;
  1410. }
  1411. Status GraphPrepare::CheckUserInput(const std::vector<GeTensor> &user_input) {
  1412. if (GetLocalOmgContext().is_dynamic_input) {
  1413. return SUCCESS;
  1414. }
  1415. unsigned int node_num = 0;
  1416. unsigned int data_num = 0;
  1417. for (NodePtr &input_node : compute_graph_->GetDirectNode()) {
  1418. GE_CHECK_NOTNULL(input_node);
  1419. OpDescPtr op = input_node->GetOpDesc();
  1420. GE_CHECK_NOTNULL(op);
  1421. node_num++;
  1422. if (op->GetType() == DATA || op->GetType() == AIPPDATA) {
  1423. data_num++;
  1424. GeAttrValue::INT index = 0;
  1425. if (!(AttrUtils::GetInt(op, ATTR_NAME_INDEX, index))) {
  1426. GELOGE(GE_GRAPH_INIT_FAILED, "Get index from attr failed");
  1427. return GE_GRAPH_INIT_FAILED;
  1428. }
  1429. if ((index < 0) || (static_cast<size_t>(index) >= user_input.size())) {
  1430. GELOGE(GE_GRAPH_INIT_FAILED, "user_input size:%zu, data op index:%ld.", user_input.size(), index);
  1431. return GE_GRAPH_INIT_FAILED;
  1432. }
  1433. GeTensorDesc desc(user_input[index].GetTensorDesc());
  1434. for (size_t i = 0; i < desc.GetShape().GetDimNum(); ++i) {
  1435. if (desc.GetShape().GetDim(i) < 0) {
  1436. GELOGE(GE_GRAPH_INIT_FAILED, "data dim %zu is not supported, need >= 0, real:%ld.", i,
  1437. desc.GetShape().GetDim(i));
  1438. return GE_GRAPH_INIT_FAILED;
  1439. }
  1440. }
  1441. }
  1442. }
  1443. if (node_num <= data_num) {
  1444. GELOGW("Prepare check user input, data_num = %u, node_num = %u", data_num, node_num);
  1445. }
  1446. return SUCCESS;
  1447. }
  1448. Status GraphPrepare::InferShapeForPreprocess() {
  1449. GELOGI("Start infershape for preprocess.");
  1450. GEPass ge_passes(compute_graph_);
  1451. NamesToPass names_to_passes;
  1452. AssertPass assert_pass;
  1453. if (!options_.train_graph_flag) {
  1454. names_to_passes.emplace_back("AssertPass", &assert_pass);
  1455. }
  1456. InferShapePass infer_shape_pass;
  1457. names_to_passes.emplace_back("InferShapePass", &infer_shape_pass);
  1458. ReplaceWithEmptyConstPass replace_with_empty_const_pass;
  1459. names_to_passes.emplace_back("ReplaceWithEmptyConstPass", &replace_with_empty_const_pass);
  1460. DimensionComputePass dimension_compute_pass;
  1461. names_to_passes.emplace_back("DimensionComputePass", &dimension_compute_pass);
  1462. ConstantFoldingPass constant_folding_pass;
  1463. names_to_passes.emplace_back("ConstantFoldingPass", &constant_folding_pass);
  1464. int32_t dev_count = 0;
  1465. AicpuConstantFoldingPass aicpu_constant_folding_pass;
  1466. const char *aicpu_constant_folding_on = std::getenv("AICPU_CONSTANT_FOLDING_ON");
  1467. rtError_t rt_err = RT_ERROR_NONE;
  1468. if (aicpu_constant_folding_on != nullptr) {
  1469. rt_err = rtGetDeviceCount(&dev_count);
  1470. if (rt_err == RT_ERROR_NONE) {
  1471. Status result = SetRtContext(rtContext_t(), RT_CTX_NORMAL_MODE);
  1472. if (result != SUCCESS) {
  1473. GELOGE(result, "Set rt context failed.");
  1474. return result;
  1475. }
  1476. names_to_passes.emplace_back("AicpuConstantFoldingPass", &aicpu_constant_folding_pass);
  1477. }
  1478. }
  1479. Status ret = ge_passes.Run(names_to_passes);
  1480. if (aicpu_constant_folding_on != nullptr) {
  1481. if (rt_err == RT_ERROR_NONE) {
  1482. Status result = SetRtContext(rtContext_t(), RT_CTX_GEN_MODE);
  1483. if (result != SUCCESS) {
  1484. GELOGE(result, "Set rt context failed.");
  1485. return result;
  1486. }
  1487. }
  1488. }
  1489. ShapeRefiner::ClearContextMap();
  1490. if (ret != SUCCESS) {
  1491. GELOGE(ret, "Run ge_passes infershape for preprocess failed, ret:%u.", ret);
  1492. return ret;
  1493. }
  1494. return SUCCESS;
  1495. }
  1496. Status GraphPrepare::PrepareOptimize() {
  1497. GELOGI("Start optimize for preprocess.");
  1498. // check rw type
  1499. GraphOptimize graph_optimize;
  1500. bool has_conflict = false;
  1501. graph_optimize.CheckRWConflict(compute_graph_, has_conflict);
  1502. if (has_conflict) {
  1503. GELOGE(GRAPH_PARAM_INVALID, "There has rw conflict.Stop optimize.");
  1504. return FAILED;
  1505. }
  1506. PassManager original_graph_passes;
  1507. // Graph pass
  1508. try {
  1509. (void)original_graph_passes.AddPass("PrepareOptimize::ShapeOperateOpRemovePass", new ShapeOperateOpRemovePass);
  1510. (void)original_graph_passes.AddPass("PrepareOptimize::ReplaceTransShapePass", new ReplaceTransShapePass);
  1511. } catch (std::bad_alloc &e) {
  1512. GELOGE(INTERNAL_ERROR, "Add pass failed, bad memory allocation occurs.");
  1513. return INTERNAL_ERROR;
  1514. }
  1515. GE_TIMESTAMP_START(original_graph_passes);
  1516. Status ret = original_graph_passes.Run(compute_graph_);
  1517. GE_TIMESTAMP_END(original_graph_passes, "GraphPrepare::OriginalGraphPasses");
  1518. if (ret != SUCCESS && ret != NOT_CHANGED) {
  1519. GELOGE(ret, "Run graph passes optimize for preprocess failed, ret:%u.", ret);
  1520. return ret;
  1521. }
  1522. // New pass
  1523. GEPass ge_passes(compute_graph_);
  1524. NamesToPass names_to_passes;
  1525. EnterPass enter_pass;
  1526. names_to_passes.emplace_back("EnterPass", &enter_pass);
  1527. CondPass cond_pass;
  1528. names_to_passes.emplace_back("CondPass", &cond_pass);
  1529. PrintOpPass print_pass;
  1530. if (options_.enable_print_op_pass) {
  1531. names_to_passes.emplace_back("PrintOpPass", &print_pass);
  1532. }
  1533. NoUseReshapeRemovePass no_use_reshape_remove_pass;
  1534. names_to_passes.emplace_back("NoUseReshapeRemovePass", &no_use_reshape_remove_pass);
  1535. DropOutPass dropout_pass;
  1536. AssertPass assert_pass;
  1537. UnusedConstPass unused_const_pass;
  1538. StopGradientPass stop_gradient_pass;
  1539. PreventGradientPass prevent_gradient_pass;
  1540. PlaceholderWithDefaultPass placeholder_with_default_pass;
  1541. GuaranteeConstPass guarantee_const_pass;
  1542. VarIsInitializedOpPass var_is_initialized_pass;
  1543. ParallelConcatStartOpPass parallel_concat_start_op_pass;
  1544. IdentityPass identity_pass(false);
  1545. AssignPass assign_pass;
  1546. SnapshotPass snapshot_pass;
  1547. if (!options_.train_graph_flag) {
  1548. names_to_passes.emplace_back("DropOutPass", &dropout_pass);
  1549. names_to_passes.emplace_back("AssertPass", &assert_pass);
  1550. }
  1551. names_to_passes.emplace_back("UnusedConstPass", &unused_const_pass);
  1552. names_to_passes.emplace_back("StopGradientPass", &stop_gradient_pass);
  1553. names_to_passes.emplace_back("PreventGradientPass", &prevent_gradient_pass);
  1554. names_to_passes.emplace_back("PlaceholderWithDefaultPass", &placeholder_with_default_pass);
  1555. names_to_passes.emplace_back("SnapshotPass", &snapshot_pass);
  1556. names_to_passes.emplace_back("GuaranteeConstPass", &guarantee_const_pass);
  1557. names_to_passes.emplace_back("VarIsInitializedOpPass", &var_is_initialized_pass);
  1558. names_to_passes.emplace_back("ParallelConcatStartOpPass", &parallel_concat_start_op_pass);
  1559. names_to_passes.emplace_back("IdentityPass", &identity_pass);
  1560. if (GetContext().GetHostExecFlag()) {
  1561. names_to_passes.emplace_back("AssignPass", &assign_pass);
  1562. }
  1563. GE_TIMESTAMP_START(names_to_passes);
  1564. ret = ge_passes.Run(names_to_passes);
  1565. GE_TIMESTAMP_END(names_to_passes, "GraphPrepare::NamesToPasses");
  1566. if (ret != SUCCESS) {
  1567. GELOGE(ret, "Run ge_passes optimize for preprocess failed, ret:%u.", ret);
  1568. return ret;
  1569. }
  1570. PassManager graph_pass;
  1571. try {
  1572. (void)graph_pass.AddPass("PrepareOptimize::PrunePass", new PrunePass);
  1573. // todo 临时把hccl的memcpy插入放到图准备,为了防止其多插memcpy
  1574. (void)graph_pass.AddPass("PrepareOptimize::HcclMemcpyPass", new (std::nothrow) HcclMemcpyPass);
  1575. } catch (std::bad_alloc &e) {
  1576. GELOGE(INTERNAL_ERROR, "Add pass failed, bad memory allocation occurs.");
  1577. return INTERNAL_ERROR;
  1578. }
  1579. GE_TIMESTAMP_START(graph_passes);
  1580. ret = graph_pass.Run(compute_graph_);
  1581. GE_TIMESTAMP_END(graph_passes, "GraphPrepare::GraphPasses");
  1582. if (ret != SUCCESS && ret != NOT_CHANGED) {
  1583. GELOGE(ret, "Run graph passes optimize for preprocess failed, ret:%u.", ret);
  1584. return ret;
  1585. }
  1586. // The constant for train is CONSTANTOP, and is CONSTANT for inference. They will be unified in future.
  1587. TypeConversionOfConstant();
  1588. ret = compute_graph_->TopologicalSorting();
  1589. if (ret != SUCCESS) {
  1590. GELOGE(ret, "Graph topological sort failed, ret:%u.", ret);
  1591. return ret;
  1592. }
  1593. GELOGI("End optimize for preprocess.");
  1594. return SUCCESS;
  1595. }
  1596. void GraphPrepare::TypeConversionOfConstant() {
  1597. if (options_.train_graph_flag) {
  1598. GELOGD("trans CONSTANT to CONSTANTOP in train.");
  1599. for (ge::NodePtr &n : compute_graph_->GetAllNodes()) {
  1600. // This can ensure that n is not a null pointer
  1601. if (n->GetOpDesc()->GetType() == CONSTANT) {
  1602. n->GetOpDesc()->SetType(CONSTANTOP);
  1603. }
  1604. }
  1605. } else {
  1606. GELOGD("trans CONSTANTOP to CONSTANT in inferrence.");
  1607. for (ge::NodePtr &n : compute_graph_->GetAllNodes()) {
  1608. // This can ensure that n is not a null pointer
  1609. if (n->GetOpDesc()->GetType() == CONSTANTOP) {
  1610. n->GetOpDesc()->SetType(CONSTANT);
  1611. }
  1612. }
  1613. }
  1614. }
  1615. Status GraphPrepare::GraphEquivalentTransformation() {
  1616. NamesToPass names_to_pass;
  1617. ForPass for_pass;
  1618. names_to_pass.emplace_back("ForToWhilePass", &for_pass);
  1619. return GEPass(compute_graph_).Run(names_to_pass);
  1620. }
  1621. Status GraphPrepare::ProcessBeforeInfershape() {
  1622. NamesToPass names_to_passes;
  1623. CondRemovePass condition_remove_pass;
  1624. names_to_passes.emplace_back("CondRemovePass", &condition_remove_pass);
  1625. GE_TIMESTAMP_START(ProcessCondRemove);
  1626. auto ret = GEPass(compute_graph_).Run(names_to_passes);
  1627. GE_TIMESTAMP_END(ProcessCondRemove, "GraphManager::ProcessCondRemove");
  1628. if (ret != SUCCESS) {
  1629. GELOGE(ret, "Run ge_passes optimize for OptimizeAfterMergeSubGraph failed, ret:%d.", ret);
  1630. return ret;
  1631. }
  1632. return SUCCESS;
  1633. }
  1634. Status GraphPrepare::ProcessNetOutput() {
  1635. PassManager graph_passes_before_infershape;
  1636. try {
  1637. if (options_.train_graph_flag) {
  1638. graph_passes_before_infershape.AddPass("ProcessNetOutput::SavePass", new (std::nothrow) SavePass);
  1639. }
  1640. graph_passes_before_infershape.AddPass("ProcessNetOutput::NetOutputPass", new (std::nothrow) NetOutputPass);
  1641. graph_passes_before_infershape.AddPass("ProcessNetOutput::DataPass",
  1642. new (std::nothrow) DataPass); // Add NetOutput first.
  1643. } catch (std::bad_alloc) {
  1644. GELOGE(INTERNAL_ERROR, "Add pass failed, bad memory allocation occurs.");
  1645. return INTERNAL_ERROR;
  1646. }
  1647. auto ret = graph_passes_before_infershape.Run(compute_graph_);
  1648. if ((ret != SUCCESS) && (ret != NOT_CHANGED)) {
  1649. GELOGE(ret, "Run graph_passes_before_infershape failed, ret:%d.", ret);
  1650. return ret;
  1651. }
  1652. return SUCCESS;
  1653. }
  1654. Status GraphPrepare::CheckAndUpdateInput(const std::vector<GeTensor> &user_input) {
  1655. compute_graph_->SetInputSize(user_input.size());
  1656. if (user_input.empty()) {
  1657. return SUCCESS;
  1658. }
  1659. auto ret = CheckUserInput(user_input);
  1660. if (ret != SUCCESS) {
  1661. GELOGE(ret, "Check user input failed.");
  1662. return ret;
  1663. }
  1664. ret = UpdateInput(user_input);
  1665. if (ret != SUCCESS) {
  1666. GELOGE(ret, "UpdateInput fail, ret:%u", ret);
  1667. return ret;
  1668. }
  1669. if (user_input.size() != 0) {
  1670. ret = CheckConstOp();
  1671. if (ret != SUCCESS) {
  1672. GELOGE(ret, "CheckConstOp fail, ret:%u", ret);
  1673. return ret;
  1674. }
  1675. } else {
  1676. ret = compute_graph_->TopologicalSorting();
  1677. if (ret != SUCCESS) {
  1678. GELOGE(ret, "graph prepare error: compute_graph_->Topological Sorting");
  1679. return FAILED;
  1680. }
  1681. }
  1682. return SUCCESS;
  1683. }
  1684. Status GraphPrepare::UpdateInputOutputByOptions() {
  1685. auto ret = UpdateDataNetOutputByStorageFormat();
  1686. if (ret != SUCCESS) {
  1687. GELOGE(ret, "Update format acoording to storage format failed.");
  1688. return ret;
  1689. }
  1690. if (options_.train_graph_flag) {
  1691. GELOGI("This is train mode, no need to do this schedule.");
  1692. return SUCCESS;
  1693. }
  1694. for (auto &node_ptr : compute_graph_->GetDirectNode()) {
  1695. GE_CHECK_NOTNULL(node_ptr);
  1696. if (CheckIfNeedSetNdFormat(node_ptr) != SUCCESS) {
  1697. GELOGE(INTERNAL_ERROR, "Set node [%s] format ND failed", node_ptr->GetName().c_str());
  1698. return FAILED;
  1699. }
  1700. if (node_ptr->GetType() == DATA) {
  1701. if (ProcessDataNodeDynShape(node_ptr) != SUCCESS) {
  1702. GELOGE(INTERNAL_ERROR, "Process data node failed");
  1703. return FAILED;
  1704. }
  1705. }
  1706. if (node_ptr->GetType() == ge::NETOUTPUT) {
  1707. if (ProcessNetoutputNodeDynShape(node_ptr) != SUCCESS) {
  1708. GELOGE(INTERNAL_ERROR, "Process netoutput node failed");
  1709. return FAILED;
  1710. }
  1711. }
  1712. }
  1713. return SUCCESS;
  1714. }
  1715. bool GraphPrepare::IsTansDataOpData(const ge::NodePtr &var_node) {
  1716. for (auto &out_anchor : var_node->GetAllOutDataAnchors()) {
  1717. GE_RT_FALSE_CHECK_NOTNULL(out_anchor);
  1718. for (auto &in_anchor : out_anchor->GetPeerInDataAnchors()) {
  1719. GE_RT_FALSE_CHECK_NOTNULL(in_anchor);
  1720. ge::NodePtr dst_node = in_anchor->GetOwnerNode();
  1721. GE_RT_FALSE_CHECK_NOTNULL(dst_node);
  1722. if (dst_node->GetType() == TRANSDATA) {
  1723. return true;
  1724. }
  1725. }
  1726. }
  1727. return false;
  1728. }
  1729. } // namespace ge

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