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

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

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