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

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