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

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