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

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