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

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