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

graph_preprocess.cc 104 kB

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

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