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

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