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 87 kB

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

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