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

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