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

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