You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

graph_preprocess.cc 98 kB

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

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