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.

main.cc 62 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430
  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 <dirent.h>
  17. #include <dlfcn.h>
  18. #include <gflags/gflags.h>
  19. #include <sys/types.h>
  20. #include <unistd.h>
  21. #include <cctype>
  22. #include <climits>
  23. #include <cstdlib>
  24. #include <iostream>
  25. #include "common/gflags_util.h"
  26. #include "common/util.h"
  27. #include "common/util/error_manager/error_manager.h"
  28. #include "framework/common/debug/ge_log.h"
  29. #include "ge/ge_api.h"
  30. #include "generator/ge_generator.h"
  31. #include "graph/anchor.h"
  32. #include "graph/debug/ge_attr_define.h"
  33. #include "graph/graph.h"
  34. #include "graph/op_desc.h"
  35. #include "graph/utils/graph_utils.h"
  36. #include "graph/utils/type_utils.h"
  37. #include "init/gelib.h"
  38. #include "ir_build/atc_ir_common.h"
  39. #include "omg/omg.h"
  40. #include "omg/parser/parser_factory.h"
  41. #include "omg/parser/parser_inner_ctx.h"
  42. #include "parser/common/register_tbe.h"
  43. #include "register/op_registry.h"
  44. #include "single_op_parser.h"
  45. #include "external/ge/ge_ir_build.h"
  46. using domi::BuildMode;
  47. using domi::OpRegistrationData;
  48. using domi::OpRegistry;
  49. using domi::Status;
  50. using domi::SUCCESS;
  51. using ge::GEN_OM_MODEL;
  52. using ge::GflagsUtils;
  53. using ge::MODEL_TO_JSON;
  54. using ge::ONLY_PRE_CHECK;
  55. using ge::ParseInputShape;
  56. using ge::PBTXT_TO_JSON;
  57. using std::map;
  58. using std::pair;
  59. using std::shared_ptr;
  60. using std::string;
  61. using std::vector;
  62. static bool is_dynamic_input = false;
  63. const char *const kModeSupport = "only support 0(model to framework model), "
  64. "1(framework model to json), 3(only pre-check), "
  65. "5(pbtxt to json), 6(display model info)";
  66. const char *const kModelToJsonSupport = "only support 0(Caffe) 3(TensorFlow) 5(Onnx)";
  67. static const char *const kCaffeFormatSupport = "only support NCHW, ND in Caffe model";
  68. static const char *const kTFFormatSupport = "only support NCHW, NHWC, ND, NCDHW, NDHWC in TF model";
  69. static const char *const kONNXFormatSupport = "only support NCHW, ND in ONNX model";
  70. // limit available mem size 2G
  71. const long kMinAvailableMem = 2097152; // 2 * 1024 * 1024
  72. DEFINE_string(model, "", "The model file.");
  73. DEFINE_string(output, "", "The output file path&name.");
  74. DEFINE_int32(framework, -1, "Framework type(0:Caffe; 1:MindSpore; 3:Tensorflow; 5:Onnx).");
  75. DEFINE_string(weight, "", "Optional; weight file. Required when framework is Caffe.");
  76. DEFINE_string(input_shape, "",
  77. "Optional; shape of input data. Required when framework is caffe "
  78. "or TensorFLow or MindSpore or Onnx. "
  79. "Format: \"input_name1:n1,c1,h1,w1;input_name2:n2,c2,h2,w2\"");
  80. DEFINE_bool(h, false, "show this help message");
  81. DEFINE_string(cal_conf, "", "Optional; the calibration config file.");
  82. DEFINE_string(insert_op_conf, "", "Optional; the config file to insert new op, for example AIPP op.");
  83. DEFINE_string(op_name_map, "", "Optional; custom op name mapping file.");
  84. DEFINE_string(target, "", "Optional; mini.");
  85. DEFINE_string(om, "", "The model file to be converted to json.");
  86. DEFINE_string(json, "", "The output json file path&name which is converted from a model.");
  87. DEFINE_int32(mode, 0,
  88. "Optional; run mode, 0(default): model => framework model; 1: "
  89. "framework model => json; 3: only pre-check; 5: txt => json.");
  90. #if !defined(__ANDROID__) && !defined(ANDROID)
  91. DEFINE_int32(encrypt_mode, -1, "Optional; the encrypt flag. 0: encrypt; -1(default): not encrypt");
  92. DEFINE_string(encrypt_key, "", "Optional; the encrypt_key file.");
  93. DEFINE_string(certificate, "", "Optional; the certificate file.");
  94. DEFINE_string(hardware_key, "", "Optional; the ISV key file.");
  95. DEFINE_string(private_key, "", "Optional; the private key file.");
  96. #endif
  97. DEFINE_string(out_nodes, "",
  98. "Optional; output nodes designated by users."
  99. "Format: \"node_name1:0;node_name1:1;node_name2:0\"");
  100. DEFINE_string(precision_mode, "force_fp16",
  101. "Optional; precision mode."
  102. "Support force_fp16, allow_mix_precision, allow_fp32_to_fp16, must_keep_origin_dtype.");
  103. DEFINE_string(keep_dtype, "",
  104. "Optional; config file to specify the precision used by the operator during compilation.");
  105. DEFINE_string(input_format, "",
  106. "Optional; input_format, format of input data, NCHW;NHWC."
  107. "Format:\"NHWC\"");
  108. DEFINE_string(check_report, "check_result.json", "Optional; the pre-checking report file.");
  109. DEFINE_string(input_fp16_nodes, "",
  110. "Optional; input node datatype is fp16 and format is NC1HWC0."
  111. "Format:\"node_name1;node_name2\"");
  112. DEFINE_string(is_output_adjust_hw_layout, "",
  113. "Optional; Net output node's datatype is fp16 and format is "
  114. "NC1HWC0, or not."
  115. "Format:\"false,true,false,true\"");
  116. DEFINE_string(is_input_adjust_hw_layout, "",
  117. "Optional; Intput node's datatype is fp16 and format is "
  118. "NC1HWC0, or not."
  119. "Format:\"false,true,false,true\"");
  120. DEFINE_string(output_type, "",
  121. "Optional; output type! "
  122. "Support FP32,FP16,INT8,INT16,UINT16,UINT8,INT32,INT64,UINT32,UINT64,DOUBLE.");
  123. DEFINE_string(op_select_implmode, "",
  124. "Optional; op select implmode! "
  125. "Support high_precision, high_performance.");
  126. DEFINE_string(optypelist_for_implmode, "",
  127. "Optional; Nodes need use implmode selected in op_select_implmode "
  128. "Format:\"node_name1,node_name2\"");
  129. DEFINE_string(singleop, "", "Optional; If set, generate single op model with the given json file.");
  130. DEFINE_int32(disable_reuse_memory, 0, "Optional; If set to 1, disable reuse memory when generating if.");
  131. DEFINE_string(auto_tune_mode, "", "Optional; Set tune mode.");
  132. DEFINE_string(soc_version, "", "The soc version.");
  133. DEFINE_string(core_type, "AiCore", "Optional; If set to VectorCore, only use vector core.");
  134. DEFINE_string(aicore_num, "", "Optional; Set aicore num");
  135. DEFINE_string(buffer_optimize, "l2_optimize", "Optional; buffer optimize");
  136. DEFINE_string(fusion_switch_file, "", "Optional; Set fusion switch file path");
  137. DEFINE_string(save_original_model, "", "Optional; enable output original offline model. false(default)");
  138. DEFINE_string(dynamic_batch_size, "",
  139. "Optional; If set, generate dynamic multi batch model. "
  140. "Different batch sizes are split by ','."
  141. "dynamic_batch_size, dynamic_image_size and dynamic_dims can only be set one.");
  142. DEFINE_string(dynamic_image_size, "",
  143. "Optional; If set, generate dynamic multi image size model."
  144. "Different groups of image size are split by ';',"
  145. "while different dimensions of each group are split by ','."
  146. "dynamic_batch_size, dynamic_image_size and dynamic_dims can only be set one.");
  147. DEFINE_string(dynamic_dims, "",
  148. "Optional; If set, generate dynamic input size model. "
  149. "Different groups of size are split by ';', while different dimensions of each group are split by ','."
  150. "dynamic_batch_size, dynamic_image_size and dynamic_dims can only be set one.");
  151. DEFINE_string(enable_small_channel, "0", "Optional; If set to 1, small channel is enabled.");
  152. DEFINE_string(enable_compress_weight, "false",
  153. "Optional; enable compress weight. true: enable; false(default): disable");
  154. DEFINE_string(compress_weight_conf, "", "Optional; the config file to compress weight");
  155. DEFINE_string(enable_single_stream, "", "Optional; enable single stream. true: enable; false(default): disable");
  156. DEFINE_string(log, "null", "Optional; generate atc log. Support debug, info, warning, error, null");
  157. DEFINE_string(dump_mode, "0", "Optional; generate infershape json,only support 1 , 0.");
  158. DEFINE_int32(op_debug_level, 0, "Optional; configure debug level of compiler. 0(default): close debug;"
  159. "1: open TBE compiler, export ccec file and TBE instruction mapping file; 2: open ccec compiler");
  160. DEFINE_string(enable_scope_fusion_passes, "", "Optional; validate the non-general scope fusion pass,"
  161. "multiple names can be set and separated by ','.");
  162. DEFINE_string(debug_dir, "", "Optional; the path to save the intermediate files of operator compilation");
  163. DEFINE_string(op_compiler_cache_dir, "", "Optional; the path to cache operator compilation files");
  164. DEFINE_string(op_compiler_cache_mode, "", "Optional; choose the operator compiler cache mode");
  165. DEFINE_string(mdl_bank_path, "", "Optional; model bank path");
  166. DEFINE_string(op_bank_path, "", "Optional; op bank path");
  167. DEFINE_string(display_model_info, "0", "Optional; display model info");
  168. class GFlagUtils {
  169. public:
  170. /**
  171. * @name InitGFlag
  172. * @brief initialize gflag
  173. * @return void
  174. */
  175. static void InitGFlag(int argc, char *argv[]) {
  176. // -help
  177. gflags::SetUsageMessage(
  178. "usage: ./atc <args>\n"
  179. "generate offline model example:\n"
  180. "./atc --model=./alexnet.prototxt --weight=./alexnet.caffemodel \n"
  181. "--framework=0 --output=./domi \n"
  182. "generate offline model for single op example:\n"
  183. "./atc --singleop=./op_list.json --output=./op_model \n"
  184. "===== Basic Functionality =====\n"
  185. "[General]\n"
  186. " --h/help Show this help message\n"
  187. " --mode Run mode. 0(default): generate offline model; 1: convert model to JSON format; "
  188. "3: only pre-check; 5: convert ge dump txt file to JSON format; 6: display model info\n"
  189. "\n[Input]\n"
  190. " --model Model file\n"
  191. " --weight Weight file. Required when framework is Caffe\n"
  192. " --om The model file to be converted to json\n"
  193. " --framework Framework type. 0:Caffe; 1:MindSpore; 3:Tensorflow; 5:Onnx\n"
  194. " --input_format Format of input data. E.g.: \"NCHW\"\n"
  195. " --input_shape Shape of input data. Separate multiple nodes with semicolons (;). "
  196. "Use double quotation marks (\") to enclose each argument.\n"
  197. " E.g.: \"input_name1:n1,c1,h1,w1;input_name2:n2,c2,h2,w2\"\n"
  198. " --dynamic_batch_size Set dynamic batch size. E.g.: \"batchsize1,batchsize2,batchsize3\"\n"
  199. " --dynamic_image_size Set dynamic image size. Separate multiple nodes with semicolons (;). "
  200. "Use double quotation marks (\") to enclose each argument.\n"
  201. " E.g.: \"imagesize1_height,imagesize1_width;imagesize2_height,imagesize2_width\"\n"
  202. " --dynamic_dims Set dynamic dims. Separate multiple nodes with semicolons (;). "
  203. "Use double quotation marks (\") to enclose each argument.\n"
  204. " E.g.: \"dims1_n1,dims1_n2;dims2_n1,dims2_n2\"\n"
  205. " --singleop Single op definition file. atc will generate offline "
  206. "model(s) for single op if --singleop is set.\n"
  207. "\n[Output]\n"
  208. " --output Output file path&name(needn't suffix, will add .om automatically). \n"
  209. " If --singleop is set, this arg specifies the directory to "
  210. "which the single op offline model will be generated\n"
  211. " --output_type Set net output type. Support FP32, FP16, UINT8. "
  212. "E.g.: FP16, indicates that all out nodes are set to FP16.\n"
  213. " \"node1:0:FP16;node2:1:FP32\", indicates setting the datatype of multiple out nodes.\n"
  214. " --check_report The pre-checking report file. Default value is: \"check_result.json\"\n"
  215. " --json The output json file path&name which is converted from a model\n"
  216. "\n[Target]\n"
  217. " --soc_version The soc version.\n"
  218. " --core_type Set core type AiCore or VectorCore. VectorCore: use vector core. "
  219. "Default value is: AiCore\n"
  220. " --aicore_num Set aicore num\n"
  221. "===== Advanced Functionality =====\n"
  222. "[Feature]\n"
  223. " --out_nodes Output nodes designated by users. Separate multiple nodes with semicolons (;)."
  224. "Use double quotation marks (\") to enclose each argument.\n"
  225. " E.g.: \"node_name1:0;node_name1:1;node_name2:0\"\n"
  226. " --input_fp16_nodes Input node datatype is fp16. Separate multiple nodes with semicolons (;). "
  227. "Use double quotation marks (\") to enclose each argument. "
  228. "E.g.: \"node_name1;node_name2\"\n"
  229. " --insert_op_conf Config file to insert new op\n"
  230. " --op_name_map Custom op name mapping file\n"
  231. " Note: A semicolon(;) cannot be included in each "
  232. "path, otherwise the resolved path will not match the expected one.\n"
  233. " --is_input_adjust_hw_layout Intput node datatype is fp16 and format is "
  234. "NC1HWC0, used with input_fp16_nodes. E.g.: \"true,true,false,true\"\n"
  235. " --is_output_adjust_hw_layout Net output node datatype is fp16 and format is "
  236. "NC1HWC0, used with out_nodes. E.g.: \"true,true,false,true\"\n"
  237. "\n[Model Tuning]\n"
  238. " --disable_reuse_memory The switch of reuse memory. Default value is : 0. "
  239. "0 means reuse memory, 1 means do not reuse memory.\n"
  240. " --fusion_switch_file Set fusion switch file path\n"
  241. " --enable_scope_fusion_passes validate the non-general scope fusion passes, "
  242. "multiple names can be set and separated by ','. E.g.: ScopePass1,ScopePass2,...\n"
  243. " --enable_single_stream Enable single stream. true: enable; false(default): disable\n"
  244. " --enable_small_channel Set enable small channel. 0(default): disable; 1: enable\n"
  245. " --enable_compress_weight Enable compress weight. true: enable; false(default): disable\n"
  246. " --compress_weight_conf Config file to compress weight\n"
  247. " --buffer_optimize Set buffer optimize. Support \"l2_optimize\" (default), "
  248. "\"l1_optimize\", \"off_optimize\"\n"
  249. " --mdl_bank_path Set the path of the custom repository generated after model tuning.\n"
  250. "\n[Operator Tuning]\n"
  251. " --precision_mode precision mode, support force_fp16(default), allow_mix_precision, "
  252. "allow_fp32_to_fp16, must_keep_origin_dtype.\n"
  253. " --keep_dtype Retains the precision of certain operators in inference "
  254. "scenarios by using a configuration file.\n"
  255. " --auto_tune_mode Set tune mode. E.g.: \"GA,RL\", support configure multiple, spit by ,\n"
  256. " --op_bank_path Set the path of the custom repository generated after operator tuning with Auto Tune.\n"
  257. " --op_select_implmode Set op select implmode. Support high_precision, high_performance. "
  258. "default: high_performance\n"
  259. " --optypelist_for_implmode Appoint which op to select implmode, cooperated with op_select_implmode.\n"
  260. " Separate multiple nodes with commas (,). Use double quotation marks (\") "
  261. "to enclose each argument. E.g.: \"node_name1,node_name2\"\n"
  262. " --op_debug_level Debug enable for TBE operator building.\n"
  263. " 0 (default): Disable debug; 1: Enable TBE pipe_all, "
  264. "and generate the operator CCE file and Python-CCE mapping file (.json);\n"
  265. " 2: Enable TBE pipe_all, generate the operator CCE file and Python-CCE mapping file "
  266. "(.json), and enable the CCE compiler -O0-g.\n"
  267. " 3: Disable debug, and keep generating kernel file (.o and .json)\n"
  268. "\n[Debug]\n"
  269. " --save_original_model Control whether to output original model. E.g.: true: output original model\n"
  270. " --log Generate log with level. Support debug, info, warning, error, null\n"
  271. " --dump_mode The switch of dump json with shape, to be used with mode 1. "
  272. "0(default): disable; 1: enable.\n"
  273. " --debug_dir Set the save path of operator compilation intermediate files.\n"
  274. "Default value: ./kernel_meta\n"
  275. " --op_compiler_cache_dir Set the save path of operator compilation cache files.\n"
  276. "Default value: $HOME/atc_data\n"
  277. " --op_compiler_cache_mode Set the operator compilation cache mode."
  278. "Options are disable(default), enable and force(force to refresh the cache)\n"
  279. " --display_model_info enable for display model info; 0(default): close display, 1: open display");
  280. gflags::ParseCommandLineNonHelpFlags(&argc, &argv, true);
  281. // Using gflags to analyze input parameters
  282. GflagsUtils::ChangeHelpFlags(FLAGS_h);
  283. gflags::HandleCommandLineHelpFlags();
  284. }
  285. static Status CheckDumpInfershapeJsonFlags() {
  286. Status ret = CheckFrameWorkValid(FLAGS_framework, FLAGS_weight);
  287. GE_CHK_BOOL_EXEC(ret == domi::SUCCESS, return domi::FAILED,
  288. "check custom aicpu run so failed!");
  289. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  290. FLAGS_weight != "" && !ge::CheckInputPathValid(FLAGS_weight, "--weight"),
  291. return domi::FAILED, "Input parameter[--weight]'s value[%s] is invalid!",
  292. FLAGS_weight.c_str());
  293. return domi::SUCCESS;
  294. }
  295. static Status CheckFlags() {
  296. Status ret = ge::SUCCESS;
  297. // No model file information passed in
  298. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  299. FLAGS_model == "",
  300. ErrorManager::GetInstance().ATCReportErrMessage("E10004", {"parameter"}, {"model"});
  301. ret = ge::FAILED, "Input parameter[--model]'s value is empty!");
  302. // check param disable_reuse_memory
  303. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  304. ge::CheckDisableReuseMemoryParamValid(to_string(FLAGS_disable_reuse_memory)) != ge::SUCCESS,
  305. ret = ge::FAILED, "check disable_reuse_memory failed!");
  306. // check optypelist_for_implmode and op_select_implmode
  307. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  308. ge::CheckImplmodeParamValid(FLAGS_optypelist_for_implmode,
  309. FLAGS_op_select_implmode) != ge::SUCCESS,
  310. ret = ge::FAILED, "check optypelist_for_implmode and op_select_implmode failed!");
  311. // No output file information passed in
  312. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  313. FLAGS_mode == GEN_OM_MODEL && FLAGS_output == "",
  314. ErrorManager::GetInstance().ATCReportErrMessage("E10004", {"parameter"}, {"output"});
  315. ret = ge::FAILED, "Input parameter[--output]'s value is empty!");
  316. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  317. CheckFrameWorkValid(FLAGS_framework, FLAGS_weight) != ge::SUCCESS,
  318. ret = ge::FAILED,
  319. "CheckFrameWorkValid failed");
  320. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  321. ge::CheckDynamicInputParamValid(FLAGS_dynamic_batch_size, FLAGS_dynamic_image_size,
  322. FLAGS_dynamic_dims, FLAGS_input_shape,
  323. FLAGS_input_format, is_dynamic_input) != ge::SUCCESS,
  324. ret = ge::FAILED, "check dynamic size(batch size, image size or dims) failed!");
  325. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  326. !FLAGS_insert_op_conf.empty() && !FLAGS_dynamic_dims.empty(),
  327. ErrorManager::GetInstance().ATCReportErrMessage("E10001",
  328. {"parameter", "value", "reason"},
  329. {"--insert_op_conf", FLAGS_insert_op_conf,
  330. "dynamic dims function does not support aipp"});
  331. ret = ge::FAILED, "dynamic dims function does not support aipp");
  332. #if !defined(__ANDROID__) && !defined(ANDROID)
  333. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(!CheckEncryptModeValid(FLAGS_encrypt_mode), ret = ge::FAILED,
  334. "encrypt_mode %d not valid!!", FLAGS_encrypt_mode);
  335. if (FLAGS_encrypt_mode == 0) { // Encryption mode
  336. GELOGI("ge will run with encrypt!");
  337. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(!ge::CheckInputPathValid(FLAGS_encrypt_key), ret = ge::FAILED,
  338. "encrypt_key file not found!!");
  339. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(!ge::CheckInputPathValid(FLAGS_certificate), ret = ge::FAILED,
  340. "certificate file not found!!");
  341. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(!ge::CheckInputPathValid(FLAGS_hardware_key), ret = ge::FAILED,
  342. "hardware_key file not found!!");
  343. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(!ge::CheckInputPathValid(FLAGS_private_key), ret = ge::FAILED,
  344. "private_key file not found!!");
  345. } else { // No encryption
  346. GELOGI("ge will run without encrypt!");
  347. }
  348. #endif
  349. /**
  350. * Check the validity of the I / O file path
  351. */
  352. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  353. FLAGS_model != "" && !ge::CheckInputPathValid(FLAGS_model, "--model"), ret = ge::FAILED,
  354. "model file %s not found!!", FLAGS_model.c_str());
  355. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  356. FLAGS_weight != "" && !ge::CheckInputPathValid(FLAGS_weight, "--weight"),
  357. ret = ge::FAILED, "weight file %s not found!!",
  358. FLAGS_weight.c_str());
  359. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  360. FLAGS_cal_conf != "" && !ge::CheckInputPathValid(FLAGS_cal_conf, "--cal_conf"),
  361. ret = ge::FAILED, "calibration config file %s not found!!",
  362. FLAGS_cal_conf.c_str());
  363. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  364. FLAGS_op_name_map != "" && !ge::CheckInputPathValid(FLAGS_op_name_map, "--op_name_map"),
  365. ret = ge::FAILED, "op config file %s not found!!",
  366. FLAGS_op_name_map.c_str());
  367. GE_CHK_BOOL_EXEC(ge::CheckInsertOpConfParamValid(std::string(FLAGS_insert_op_conf)) == ge::SUCCESS,
  368. ret = ge::FAILED, "check insert op conf failed!");
  369. GE_CHK_BOOL_EXEC(ge::CheckCompressWeightParamValid(
  370. FLAGS_enable_compress_weight, FLAGS_compress_weight_conf) == ge::SUCCESS,
  371. ret = ge::FAILED, "check compress weight failed!");
  372. GE_CHK_BOOL_EXEC(ge::CheckKeepTypeParamValid(FLAGS_keep_dtype) == ge::SUCCESS,
  373. ret = ge::FAILED, "check keep dtype failed!");
  374. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  375. !ge::CheckOutputPathValid(FLAGS_check_report, "--check_report"), ret = ge::FAILED,
  376. "check_report file %s not found!!", FLAGS_check_report.c_str());
  377. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  378. FLAGS_mode == GEN_OM_MODEL && FLAGS_output != "" &&
  379. (!ge::CheckOutputPathValid(FLAGS_output, "--output") || !CheckPathWithName(FLAGS_output)),
  380. ret = ge::FAILED, "output path %s is not valid!!", FLAGS_output.c_str());
  381. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  382. FLAGS_save_original_model != "" &&
  383. FLAGS_save_original_model != "true" &&
  384. FLAGS_save_original_model != "false",
  385. ErrorManager::GetInstance().ATCReportErrMessage(
  386. "E10005", {"parameter", "value"}, {"save_original_model", FLAGS_save_original_model});
  387. ret = ge::FAILED,
  388. "Input parameter[--save_original_model]'s value[%s] must be true or false.",
  389. FLAGS_save_original_model.c_str());
  390. GE_CHK_BOOL_EXEC(ge::CheckBufferOptimizeParamValid(FLAGS_buffer_optimize) == ge::SUCCESS,
  391. ret = ge::FAILED, "check output type failed!");
  392. GE_CHK_BOOL_EXEC(
  393. ge::CheckEnableSingleStreamParamValid(std::string(FLAGS_enable_single_stream)) == ge::SUCCESS,
  394. ret = ge::FAILED, "check enable single stream failed!");
  395. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((FLAGS_display_model_info != "0") && (FLAGS_display_model_info != "1"),
  396. ErrorManager::GetInstance().ATCReportErrMessage("E10006", {"parameter"}, {"display_model_info"});
  397. ret = ge::FAILED, "Input parameter[--display_model_info]'s value must be 1 or 0.");
  398. return ret;
  399. }
  400. /**
  401. * Verifying the parameters of converting model to JSON
  402. * 1. Fmk_model
  403. * 2. out_json
  404. **/
  405. static Status CheckConverJsonParamFlags() {
  406. Status ret = ge::SUCCESS;
  407. // No model path passed in
  408. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(FLAGS_om == "",
  409. ErrorManager::GetInstance().ATCReportErrMessage("E10004", {"parameter"}, {"om"});
  410. ret = ge::FAILED,
  411. "Input parameter[--om]'s value is empty!!");
  412. // JSON path not passed in
  413. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(FLAGS_json == "",
  414. ErrorManager::GetInstance().ATCReportErrMessage("E10004", {"parameter"}, {"json"});
  415. ret = ge::FAILED,
  416. "Input parameter[--json]'s value is empty!!");
  417. // Check if the model path is valid
  418. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  419. FLAGS_om != "" && !ge::CheckInputPathValid(FLAGS_om, "--om"),
  420. ret = ge::FAILED,
  421. "model file path is invalid: %s.", FLAGS_om.c_str());
  422. // Check whether the JSON path is valid
  423. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  424. FLAGS_json != "" && !ge::CheckOutputPathValid(FLAGS_json, "--json"),
  425. ret = ge::FAILED,
  426. "json file path is invalid: %s.", FLAGS_json.c_str());
  427. return ret;
  428. }
  429. /**
  430. * Check command line parameters for explicit settings
  431. * true: Explicit setup
  432. * false: Not set up
  433. * */
  434. static bool CheckFlagSet(string flag) {
  435. gflags::CommandLineFlagInfo info;
  436. return !(gflags::GetCommandLineFlagInfo(flag.c_str(), &info) && info.is_default);
  437. }
  438. private:
  439. static bool CheckEncryptModeValid(const int encrypt_mode) {
  440. #if !defined(__ANDROID__) && !defined(ANDROID)
  441. if (encrypt_mode != 0 && encrypt_mode != -1) {
  442. DOMI_LOGE("encrypt mode must be 0 or -1");
  443. return false;
  444. }
  445. #else
  446. if (encrypt_mode != -1) {
  447. DOMI_LOGE("encrypt mode must be -1");
  448. return false;
  449. }
  450. #endif
  451. return true;
  452. }
  453. static Status CheckFrameWorkValid(int framework, const std::string weight_file) {
  454. if (framework != (int32_t)domi::CAFFE && framework != (int32_t)domi::TENSORFLOW &&
  455. framework != (int32_t)domi::MINDSPORE && framework != (int32_t)domi::ONNX) {
  456. // No framework information was passed in or the entered framework is illegal
  457. ErrorManager::GetInstance().ATCReportErrMessage(
  458. "E10007", {"parameter", "support"},
  459. {"framework", "0(Caffe) or 1(MindSpore) or 3(TensorFlow) or 5(Onnx)"});
  460. DOMI_LOGE("Input parameter[--framework] is mandatory and it's value must be: "
  461. "0(Caffe) or 1(MindSpore) or 3(TensorFlow) or 5(Onnx).");
  462. return domi::PARAM_INVALID;
  463. }
  464. if ((framework == (int32_t)domi::CAFFE) && (weight_file == "")) {
  465. ErrorManager::GetInstance().ATCReportErrMessage("E10008", {"parameter"}, {"weight"});
  466. DOMI_LOGE("Input parameter[--weight]'s value is empty when framework is 0(CAFFE)!");
  467. return domi::PARAM_INVALID;
  468. }
  469. if ((framework == (int32_t)domi::TENSORFLOW) && (weight_file != "")) {
  470. GELOGW("Parameter weight is ignored for TensorFlow.");
  471. }
  472. if ((framework == (int32_t)domi::ONNX) && (weight_file != "")) {
  473. GELOGW("Parameter weight is ignored for Onnx.");
  474. }
  475. return domi::SUCCESS;
  476. }
  477. static bool CheckPathWithName(const std::string &fileName) {
  478. // Determine file path length
  479. if (fileName.size() > static_cast<int>(PATH_MAX)) {
  480. ErrorManager::GetInstance().ATCReportErrMessage(
  481. "E10021", {"parameter", "size"}, {"output", std::to_string(PATH_MAX)});
  482. GELOGE(ge::FAILED, "Input parameter[--output]'s path is too long, it must be less than %d", PATH_MAX);
  483. return false;
  484. }
  485. // Find the last separator
  486. int slashPosition = fileName.size() - 1;
  487. for (; slashPosition >= 0; slashPosition--) {
  488. if (fileName[slashPosition] == '\\' || fileName[slashPosition] == '/') {
  489. break;
  490. }
  491. }
  492. // Failure if no filename follows the path
  493. if (slashPosition == static_cast<int>(fileName.size() - 1)) {
  494. ErrorManager::GetInstance().ATCReportErrMessage("E10022", {"parameter", "filename"}, {"output", fileName});
  495. DOMI_LOGE("Input parameter[--output]'s path[%s] not include file name", fileName.c_str());
  496. return false;
  497. }
  498. return true;
  499. }
  500. };
  501. void SetDynamicInputSizeOptions() {
  502. if (!FLAGS_dynamic_batch_size.empty()) {
  503. domi::GetContext().dynamic_batch_size = FLAGS_dynamic_batch_size;
  504. }
  505. if (!FLAGS_dynamic_image_size.empty()) {
  506. domi::GetContext().dynamic_image_size = FLAGS_dynamic_image_size;
  507. }
  508. if (!FLAGS_dynamic_dims.empty()) {
  509. domi::GetContext().dynamic_dims = FLAGS_dynamic_dims;
  510. }
  511. }
  512. /// Validate the non-general scope fusion pass.
  513. /// The parameter is set to the name of the fusion rule.
  514. /// Multiple names can be set and separated by ",".
  515. void SetEnableScopeFusionPasses(const std::string pass_names) {
  516. ge::GetParserContext().enable_scope_fusion_passes = pass_names;
  517. }
  518. static bool CheckInputFormat() {
  519. if (FLAGS_input_format.empty()) {
  520. // Set default format
  521. if (FLAGS_framework == static_cast<int32_t>(domi::TENSORFLOW)) {
  522. FLAGS_input_format = "NHWC";
  523. } else {
  524. FLAGS_input_format = "NCHW";
  525. }
  526. return true;
  527. } else if ((FLAGS_framework == static_cast<int32_t>(domi::CAFFE))) { // caffe
  528. if (ge::caffe_support_input_format.find(FLAGS_input_format) != ge::caffe_support_input_format.end()) {
  529. return true;
  530. }
  531. // only support NCHW ND
  532. ErrorManager::GetInstance().ATCReportErrMessage(
  533. "E10001", {"parameter", "value", "reason"}, {"--input_format", FLAGS_input_format, kCaffeFormatSupport});
  534. GELOGE(ge::FAILED,
  535. "Invalid value for --input_format[%s], %s.", FLAGS_input_format.c_str(), kCaffeFormatSupport);
  536. return false;
  537. } else if ((FLAGS_framework == static_cast<int32_t>(domi::TENSORFLOW))) { // tf
  538. if (ge::tf_support_input_format.find(FLAGS_input_format) != ge::tf_support_input_format.end()) {
  539. return true;
  540. }
  541. // only support NCHW NHWC ND NCDHW NDHWC
  542. ErrorManager::GetInstance().ATCReportErrMessage(
  543. "E10001", {"parameter", "value", "reason"}, {"--input_format", FLAGS_input_format, kTFFormatSupport});
  544. GELOGE(ge::FAILED,
  545. "Invalid value for --input_format[%s], %s.", FLAGS_input_format.c_str(), kTFFormatSupport);
  546. return false;
  547. } else if (FLAGS_framework == static_cast<int32_t>(domi::ONNX)) {
  548. if (ge::onnx_support_input_format.find(FLAGS_input_format) != ge::onnx_support_input_format.end()) {
  549. return true;
  550. }
  551. // only support NCHW ND
  552. ErrorManager::GetInstance().ATCReportErrMessage(
  553. "E10001", {"parameter", "value", "reason"}, {"--input_format", FLAGS_input_format, kONNXFormatSupport});
  554. GELOGE(ge::FAILED,
  555. "Invalid value for --input_format[%s], %s.", FLAGS_input_format.c_str(), kONNXFormatSupport);
  556. return false;
  557. }
  558. return true;
  559. }
  560. #if !defined(__ANDROID__) && !defined(ANDROID)
  561. static void GetCustomOpPath(std::string &customop_path) {
  562. GELOGI("Enter get custom op path schedule");
  563. std::string fmk_type = ge::TypeUtils::FmkTypeToSerialString(static_cast<domi::FrameworkType>(FLAGS_framework));
  564. GELOGI("Framework type is %s.", fmk_type.c_str());
  565. const char *path_env = std::getenv("ASCEND_OPP_PATH");
  566. if (path_env != nullptr) {
  567. std::string path = path_env;
  568. customop_path = (path + "/framework/custom" + "/:") + (path + "/framework/built-in/" + fmk_type);
  569. GELOGI("Get custom so path from env : %s", path_env);
  570. return;
  571. }
  572. std::string path_base = ge::GELib::GetPath();
  573. GELOGI("path_base is %s", path_base.c_str());
  574. path_base = path_base.substr(0, path_base.rfind('/'));
  575. path_base = path_base.substr(0, path_base.rfind('/') + 1);
  576. customop_path = (path_base + "ops/framework/custom" + "/:") + (path_base + "ops/framework/built-in/" + fmk_type);
  577. return;
  578. }
  579. void GetPluginSoFileList(const string &path, vector<string> &fileList, string &caffe_parser_path) {
  580. // Support to split multiple so directories by ":"
  581. GELOGI("path is %s", path.c_str());
  582. vector<string> v_path = ge::StringUtils::Split(path, ':');
  583. for (size_t i = 0; i < v_path.size(); ++i) {
  584. ge::FindParserSo(v_path[i], fileList, caffe_parser_path);
  585. GELOGI("CustomOpLib full name = %s", v_path[i].c_str());
  586. }
  587. }
  588. void LoadModelParserLib(std::string caffe_parser_path) {
  589. if (FLAGS_framework == static_cast<int32_t>(domi::TENSORFLOW)) {
  590. void *tf_handle = dlopen("libfmk_parser.so", RTLD_NOW | RTLD_GLOBAL);
  591. if (tf_handle == nullptr) {
  592. GELOGW("dlopen fmk library [libfmk_parser.so] failed.");
  593. return;
  594. }
  595. GELOGI("plugin load libfmk_parser.so success.");
  596. } else if (FLAGS_framework == static_cast<int32_t>(domi::CAFFE)) {
  597. // What we are dealing with here is that the user modifies the caffe.proto scenario.
  598. // If no lib_Caffe_Parser.so is found under the plugin path, use the default lib_Caffe_Parser.so path.
  599. caffe_parser_path = caffe_parser_path.empty() ? "lib_caffe_parser.so" : caffe_parser_path;
  600. void *handle = dlopen(caffe_parser_path.c_str(), RTLD_NOW | RTLD_GLOBAL);
  601. if (handle == nullptr) {
  602. GELOGW("dlopen failed, plugin name:%s. Message(%s).", caffe_parser_path.c_str(), dlerror());
  603. return;
  604. }
  605. GELOGI("plugin load %s success.", caffe_parser_path.c_str());
  606. // According to the dependency, the Caffe parsing module of the framework is loaded here( libfmk_parser.so).
  607. // (depend on the lib_caffe_parser.so)
  608. void *fmk_handle = dlopen("libfmk_parser.so", RTLD_NOW | RTLD_GLOBAL);
  609. if (fmk_handle == nullptr) {
  610. GELOGW("dlopen fmk library [libfmk_parser.so] failed.");
  611. if (dlclose(handle) != 0) {
  612. GELOGW("dlclose lib_caffe_parser.so failed.");
  613. }
  614. return;
  615. }
  616. GELOGI("plugin load libfmk_parser.so success.");
  617. } else if (FLAGS_framework == static_cast<int32_t>(domi::ONNX)) {
  618. void *handle = dlopen("libfmk_onnx_parser.so", RTLD_NOW | RTLD_GLOBAL);
  619. if (handle == nullptr) {
  620. GELOGW("dlopen fmk library [libfmk_onnx_parser.so] failed.");
  621. return;
  622. }
  623. GELOGI("plugin load libfmk_onnx_parser.so success.");
  624. } else {
  625. GELOGW("Framework:%s is not support.",
  626. ge::TypeUtils::FmkTypeToSerialString(static_cast<domi::FrameworkType>(FLAGS_framework)).c_str());
  627. return;
  628. }
  629. return;
  630. }
  631. void LoadCustomOpLib(bool need_load_ops_plugin) {
  632. std::string plugin_path;
  633. GetCustomOpPath(plugin_path);
  634. vector<string> fileList;
  635. string caffe_parser_path = "";
  636. // whether there are files in the plugin so path
  637. GetPluginSoFileList(plugin_path, fileList, caffe_parser_path);
  638. // no file
  639. if (fileList.empty() && caffe_parser_path.empty()) {
  640. GELOGW("can not find any plugin file in plugin_path: %s", plugin_path.c_str());
  641. }
  642. LoadModelParserLib(caffe_parser_path);
  643. if (!need_load_ops_plugin) {
  644. GELOGI("No need to load ops plugin so.");
  645. return;
  646. }
  647. OpRegistry::Instance()->registrationDatas.clear();
  648. // load other so files except lib_caffe_parser.so in the plugin so path
  649. for (auto elem : fileList) {
  650. ge::StringUtils::Trim(elem);
  651. void *handle = dlopen(elem.c_str(), RTLD_NOW | RTLD_GLOBAL);
  652. if (handle == nullptr) {
  653. GELOGW("dlopen failed, plugin name:%s. Message(%s).", elem.c_str(), dlerror());
  654. } else {
  655. GELOGI("plugin load %s success.", elem.c_str());
  656. }
  657. }
  658. std::vector<OpRegistrationData> registrationDatas = OpRegistry::Instance()->registrationDatas;
  659. for (OpRegistrationData reg_data : registrationDatas) {
  660. if (reg_data.GetFrameworkType() == static_cast<domi::FrameworkType>(FLAGS_framework)) {
  661. (void)ge::OpRegistrationTbe::Instance()->Finalize(reg_data);
  662. (void)OpRegistry::Instance()->Register(reg_data);
  663. }
  664. }
  665. }
  666. void SaveCustomCaffeProtoPath() {
  667. GELOGI("Enter save custom caffe proto path.");
  668. std::string path_base = ge::GELib::GetPath();
  669. GELOGI("path_base is %s", path_base.c_str());
  670. path_base = path_base.substr(0, path_base.rfind('/'));
  671. path_base = path_base.substr(0, path_base.rfind('/') + 1);
  672. ge::GetParserContext().caffe_proto_path = path_base + "include/proto/";
  673. string customop_path;
  674. const char *path_env = std::getenv("ASCEND_OPP_PATH");
  675. if (path_env != nullptr) {
  676. std::string path = path_env;
  677. customop_path = path + "/framework/custom/caffe/";
  678. GELOGI("Get custom proto path from env : %s", path_env);
  679. ge::GetParserContext().custom_proto_path = customop_path;
  680. return;
  681. }
  682. customop_path = path_base + "ops/framework/custom/caffe/";
  683. ge::GetParserContext().custom_proto_path = customop_path;
  684. return;
  685. }
  686. #endif
  687. Status CreateInputsForInference(const ge::Graph &graph, vector<ge::GeTensor> &inputs) {
  688. auto compute_graph = ge::GraphUtils::GetComputeGraph(graph);
  689. GE_CHECK_NOTNULL(compute_graph);
  690. for (ge::NodePtr &input_node : compute_graph->GetAllNodes()) {
  691. GE_CHECK_NOTNULL(input_node);
  692. ge::OpDescPtr op = input_node->GetOpDesc();
  693. GE_CHECK_NOTNULL(op);
  694. if (op->GetType() == ge::DATA) {
  695. GELOGI("Data op inputDesc size is: %zu", op->GetAllInputsDesc().size());
  696. ge::GeTensorDesc tensor = op->GetInputDesc(0);
  697. string data_op_name = op->GetName();
  698. GELOGI("Data op name is: %s", data_op_name.c_str());
  699. ge::GeShape data_shape;
  700. auto iter = domi::GetContext().input_dims.find(data_op_name);
  701. if (iter != domi::GetContext().input_dims.end()) {
  702. data_shape = ge::GeShape(iter->second);
  703. GELOGI("Data op get shape from Context.");
  704. } else {
  705. data_shape = tensor.GetShape();
  706. GELOGI("Data op get shape from InputDesc in geir graph.");
  707. }
  708. ge::DataType data_type = tensor.GetDataType();
  709. string data_type_str = ge::TypeUtils::DataTypeToSerialString(data_type);
  710. GELOGI("Data op get data type:%s from InputDesc in geir graph.", data_type_str.c_str());
  711. ge::GeTensor input_tensor;
  712. ge::GeTensorDesc desc(data_shape, ge::Format(domi::GetContext().format), data_type);
  713. input_tensor.SetTensorDesc(desc);
  714. inputs.push_back(input_tensor);
  715. }
  716. }
  717. GELOGI("Build ME model, inputs size is: %zu", inputs.size());
  718. return ge::SUCCESS;
  719. }
  720. domi::Status GenerateInfershapeJson() {
  721. if (!CheckInputFormat()) {
  722. GELOGE(ge::FAILED, "Check input_format failed");
  723. return domi::FAILED;
  724. }
  725. Status ret = GFlagUtils::CheckDumpInfershapeJsonFlags();
  726. GE_CHK_BOOL_EXEC(ret == domi::SUCCESS, return domi::FAILED, "Check flags failed!");
  727. ge::GeGenerator ge_generator;
  728. std::map<string, string> options;
  729. ge::Status geRet = ge_generator.Initialize(options, domi::GetContext());
  730. if (geRet != ge::SUCCESS) {
  731. DOMI_LOGE("GeGenerator initialize failed!");
  732. return domi::FAILED;
  733. }
  734. ge::Graph graph;
  735. std::map<string, string> atc_params;
  736. atc_params.insert(std::pair<string, string>("input_format", FLAGS_input_format));
  737. ret = ParseGraph(graph, atc_params, FLAGS_om.c_str(), FLAGS_weight.c_str(), (domi::FrameworkType) FLAGS_framework,
  738. "", FLAGS_target.c_str(), (ge::RunMode) FLAGS_mode, false);
  739. if (ret != ge::SUCCESS) {
  740. DOMI_LOGE("ATC Parse graph domi::FAILED");
  741. (void)ge_generator.Finalize();
  742. return domi::FAILED;
  743. }
  744. geRet = ge_generator.GenerateInfershapeGraph(graph);
  745. if (geRet != ge::SUCCESS) {
  746. DOMI_LOGE("ATC GenerateInfershapeJson failed");
  747. (void)ge_generator.Finalize();
  748. return domi::FAILED;
  749. }
  750. if (DumpInfershapeJson(graph, FLAGS_json.c_str()) != SUCCESS) {
  751. DOMI_LOGE("ATC DumpInfershapeJson failed");
  752. (void)ge_generator.Finalize();
  753. return domi::FAILED;
  754. }
  755. (void)ge_generator.Finalize();
  756. return ge::SUCCESS;
  757. }
  758. static Status ConvertModelToJson(int fwk_type, const string &model_file, const string &json_file) {
  759. Status ret = ge::SUCCESS;
  760. if (fwk_type == -1) {
  761. ret = ge::ConvertOm(model_file.c_str(), json_file.c_str(), true);
  762. return ret;
  763. }
  764. if ((fwk_type != domi::TENSORFLOW) && (fwk_type != domi::CAFFE) && (fwk_type != domi::ONNX)) {
  765. ErrorManager::GetInstance().ATCReportErrMessage(
  766. "E10001", {"parameter", "value", "reason"},
  767. {"--framework", std::to_string(fwk_type), kModelToJsonSupport});
  768. GELOGE(ge::FAILED, "Invalid value for --framework[%d], %s.", fwk_type, kModelToJsonSupport);
  769. ret = ge::FAILED;
  770. }
  771. if (FLAGS_dump_mode != "0" && FLAGS_dump_mode != "1") {
  772. ErrorManager::GetInstance().ATCReportErrMessage("E10006", {"parameter"}, {"dump_mode"});
  773. GELOGE(ge::FAILED, "Input parameter[--dump_mode]'s value must be 1 or 0.");
  774. ret = ge::FAILED;
  775. }
  776. if (ret != ge::SUCCESS) return ret;
  777. // Need to save caffe.proto path
  778. SaveCustomCaffeProtoPath();
  779. if (FLAGS_dump_mode == "0") {
  780. // Caffe or tf model to json depend on lib_caffe_parser.so or libfmk_parser.so.
  781. LoadCustomOpLib(false);
  782. ret = ge::ConvertFwkModelToJson((domi::FrameworkType)fwk_type, model_file.c_str(), json_file.c_str());
  783. } else if (FLAGS_dump_mode == "1") {
  784. // Caffe or tf model to json depend on lib_caffe_parser.so or libfmk_parser.so and ops plugin so.
  785. LoadCustomOpLib(true);
  786. ret = GenerateInfershapeJson();
  787. }
  788. return ret;
  789. }
  790. static Status SetAttrOptions(ge::Graph &graph) {
  791. if (!FLAGS_keep_dtype.empty()) {
  792. if (ge::aclgrphSetOpAttr(graph, ge::ATTR_TYPE_KEEP_DTYPE, FLAGS_keep_dtype.c_str()) != ge::GRAPH_SUCCESS) {
  793. return ge::FAILED;
  794. }
  795. }
  796. if (!FLAGS_compress_weight_conf.empty()) {
  797. if (ge::aclgrphSetOpAttr(graph, ge::ATTR_TYPE_WEIGHT_COMPRESS, FLAGS_compress_weight_conf.c_str())
  798. != ge::GRAPH_SUCCESS) {
  799. return ge::FAILED;
  800. }
  801. }
  802. return ge::SUCCESS;
  803. }
  804. domi::Status GenerateModel(std::map<string, string> &options, std::string output) {
  805. ge::GeGenerator ge_generator;
  806. ge::Status geRet = ge::SUCCESS;
  807. std::shared_ptr<ge::GELib> instance_ptr = ge::GELib::GetInstance();
  808. if (instance_ptr == nullptr || !instance_ptr->InitFlag()) {
  809. geRet = ge::GELib::Initialize(options);
  810. if (geRet != ge::SUCCESS) {
  811. DOMI_LOGE("GE initialize failed!");
  812. return domi::FAILED;
  813. }
  814. }
  815. geRet = ge_generator.Initialize(options, domi::GetContext());
  816. if (geRet != ge::SUCCESS) {
  817. DOMI_LOGE("GeGenerator initialize failed!");
  818. (void)ge::GELib::GetInstance()->Finalize();
  819. return domi::FAILED;
  820. }
  821. ge::Graph graph;
  822. std::vector<ge::GeTensor> inputs;
  823. if (FLAGS_framework == domi::MINDSPORE) {
  824. // load model from file
  825. ge::Model load_model = ge::Model("loadmodel", "version2");
  826. auto ret1 = load_model.LoadFromFile(FLAGS_model);
  827. if (ret1 != ge::GRAPH_SUCCESS) {
  828. ErrorManager::GetInstance().ATCReportErrMessage("E10041", {"parameter"}, {FLAGS_model});
  829. DOMI_LOGE("Load model from %s failed, please check model file or "
  830. "input parameter[--framework] is correct", FLAGS_model.c_str());
  831. (void)ge_generator.Finalize();
  832. (void)ge::GELib::GetInstance()->Finalize();
  833. return domi::FAILED;
  834. }
  835. graph = load_model.GetGraph();
  836. GE_CHK_STATUS_EXEC(ge::InitDomiOmgContext(FLAGS_input_shape, FLAGS_input_format, "", is_dynamic_input),
  837. GELOGE(ge::FAILED, "ATC Generate call InitDomiOmgContext ret fail");
  838. (void)ge_generator.Finalize(); (void)ge::GELib::GetInstance()->Finalize(); return domi::FAILED);
  839. Status ret = CreateInputsForInference(graph, inputs);
  840. if (ret != ge::SUCCESS) {
  841. GELOGE(ge::FAILED, "create inputs for inference failed.");
  842. (void)ge_generator.Finalize();
  843. (void)ge::GELib::GetInstance()->Finalize();
  844. return domi::FAILED;
  845. }
  846. } else {
  847. std::map<string, string> atc_params;
  848. atc_params.insert(std::pair<string, string>("input_shape", FLAGS_input_shape));
  849. atc_params.insert(std::pair<string, string>("out_nodes", FLAGS_out_nodes));
  850. atc_params.insert(std::pair<string, string>("input_format", FLAGS_input_format));
  851. atc_params.insert(std::pair<string, string>("check_report", FLAGS_check_report));
  852. atc_params.insert(std::pair<string, string>("input_fp16_nodes", FLAGS_input_fp16_nodes));
  853. atc_params.insert(std::pair<string, string>("is_input_adjust_hw_layout", FLAGS_is_input_adjust_hw_layout));
  854. atc_params.insert(std::pair<string, string>("is_output_adjust_hw_layout", FLAGS_is_output_adjust_hw_layout));
  855. atc_params.insert(std::pair<string, string>(string(ge::OUTPUT_DATATYPE), FLAGS_output_type));
  856. atc_params.insert(std::pair<string, string>("output", output));
  857. Status ret =
  858. ParseGraph(graph, atc_params, FLAGS_model.c_str(), FLAGS_weight.c_str(), (domi::FrameworkType)FLAGS_framework,
  859. FLAGS_op_name_map.c_str(), FLAGS_target.c_str(), (ge::RunMode)FLAGS_mode, is_dynamic_input);
  860. // in ONLY_PRE_CHECK mode, pre-checking report has already saved in ParseGraph
  861. if (FLAGS_mode == ge::ONLY_PRE_CHECK) {
  862. (void)ge_generator.Finalize();
  863. (void)ge::GELib::GetInstance()->Finalize();
  864. if (ret != ge::SUCCESS) {
  865. DOMI_LOGE("ATC precheck fail.");
  866. return domi::FAILED;
  867. }
  868. return domi::SUCCESS;
  869. }
  870. if (ret != ge::SUCCESS) {
  871. DOMI_LOGE("ATC Parse graph domi::FAILED");
  872. DOMI_LOGE("ATC Generate execute failed"); // Duplicate log. (for test case
  873. (void)ge_generator.Finalize();
  874. (void)ge::GELib::GetInstance()->Finalize();
  875. return domi::FAILED;
  876. }
  877. if (ge::SetOutputNodeInfo(graph, FLAGS_output_type, "") != domi::SUCCESS) {
  878. DOMI_LOGE("Set output node info fail.");
  879. (void)ge_generator.Finalize();
  880. (void)ge::GELib::GetInstance()->Finalize();
  881. return domi::FAILED;
  882. }
  883. }
  884. if (SetAttrOptions(graph) != ge::SUCCESS) {
  885. (void)ge_generator.Finalize();
  886. (void)ge::GELib::GetInstance()->Finalize();
  887. return domi::FAILED;
  888. }
  889. geRet = ge_generator.GenerateOfflineModel(graph, output, inputs);
  890. if (geRet != ge::SUCCESS) {
  891. DOMI_LOGE("GE GenerateOfflineModel execute failed");
  892. DOMI_LOGE("ATC Generate execute failed"); // Duplicate log. (for test case
  893. // checking error log)
  894. (void)ge_generator.Finalize();
  895. (void)ge::GELib::GetInstance()->Finalize();
  896. return domi::FAILED;
  897. }
  898. (void)ge_generator.Finalize();
  899. (void)ge::GELib::GetInstance()->Finalize();
  900. return ge::SUCCESS;
  901. }
  902. static void SetEnvForSingleOp(std::map<string, string> &options) {
  903. string flag_on = "1";
  904. string flag_off = "0";
  905. options.emplace(ge::GE_FE_FLAG, flag_on);
  906. options.emplace(ge::STREAM_NUM, "1"); // single op only use one stream
  907. options.emplace(ge::RUN_FLAG, flag_off);
  908. options.emplace(ge::OPTION_GRAPH_RUN_MODE, flag_off);
  909. options.emplace(ge::SINGLE_OP_FLAG, flag_on);
  910. options.emplace(ge::PRECISION_MODE, FLAGS_precision_mode);
  911. options.emplace(ge::SOC_VERSION, FLAGS_soc_version);
  912. options.emplace(ge::CORE_TYPE, FLAGS_core_type);
  913. options.emplace(ge::AICORE_NUM, FLAGS_aicore_num);
  914. options.emplace(ge::OP_SELECT_IMPL_MODE, FLAGS_op_select_implmode);
  915. options.emplace(ge::OPTYPELIST_FOR_IMPLMODE, FLAGS_optypelist_for_implmode);
  916. options.emplace(ge::AUTO_TUNE_MODE, FLAGS_auto_tune_mode);
  917. options.emplace(ge::OP_DEBUG_LEVEL, to_string(FLAGS_op_debug_level));
  918. options.emplace(ge::DEBUG_DIR, FLAGS_debug_dir);
  919. options.emplace(ge::OP_COMPILER_CACHE_DIR, FLAGS_op_compiler_cache_dir);
  920. options.emplace(ge::OP_COMPILER_CACHE_MODE, FLAGS_op_compiler_cache_mode);
  921. options.emplace(ge::MDL_BANK_PATH_FLAG, FLAGS_mdl_bank_path);
  922. options.emplace(ge::OP_BANK_PATH_FLAG, FLAGS_op_bank_path);
  923. }
  924. domi::Status GenerateSingleOp(const std::string& json_file_path) {
  925. if (!FLAGS_output.empty() && !ge::CheckOutputPathValid(FLAGS_output, "--output")) {
  926. DOMI_LOGE("output path %s is not valid!", FLAGS_output.c_str());
  927. return domi::FAILED;
  928. }
  929. // check optypelist_for_implmode and op_select_implmode
  930. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  931. ge::CheckImplmodeParamValid(FLAGS_optypelist_for_implmode, FLAGS_op_select_implmode) != ge::SUCCESS,
  932. return ge::FAILED, "check optypelist_for_implmode and op_select_implmode failed!");
  933. std::map<string, string> options;
  934. // need to be changed when ge.ini plan is done
  935. SetEnvForSingleOp(options);
  936. auto ret = ge::GELib::Initialize(options);
  937. if (ret != ge::SUCCESS) {
  938. DOMI_LOGE("GE initialize failed!");
  939. return domi::FAILED;
  940. }
  941. ge::GeGenerator generator;
  942. ret = generator.Initialize(options, domi::GetContext());
  943. if (ret != SUCCESS) {
  944. DOMI_LOGE("GeGenerator initialize failed!");
  945. (void)ge::GELib::GetInstance()->Finalize();
  946. return domi::FAILED;
  947. }
  948. vector<ge::SingleOpBuildParam> build_params;
  949. if (ge::SingleOpParser::ParseSingleOpList(json_file_path, build_params) != ge::SUCCESS) {
  950. DOMI_LOGE("parse single op json file failed");
  951. (void)generator.Finalize();
  952. (void)ge::GELib::GetInstance()->Finalize();
  953. return domi::FAILED;
  954. }
  955. int index = 0;
  956. for (auto &param : build_params) {
  957. string output_path;
  958. if (!FLAGS_output.empty()) {
  959. output_path = FLAGS_output + "/";
  960. }
  961. output_path += param.file_name;
  962. ret = generator.BuildSingleOpModel(param.op_desc, param.inputs, param.outputs, output_path);
  963. if (ret != SUCCESS) {
  964. DOMI_LOGE("Compile op failed. ge ret = %u, op index = %d", ret, index);
  965. ret = domi::FAILED;
  966. break;
  967. }
  968. GELOGI("Compile op success. op index = %d, output = %s", index, output_path.c_str());
  969. index += 1;
  970. }
  971. (void)generator.Finalize();
  972. (void)ge::GELib::GetInstance()->Finalize();
  973. return ret;
  974. }
  975. domi::Status GenerateOmModel() {
  976. if (!CheckInputFormat()) {
  977. GELOGE(ge::FAILED, "Check input_format failed");
  978. return domi::FAILED;
  979. }
  980. Status ret = GFlagUtils::CheckFlags();
  981. GE_CHK_BOOL_EXEC(ret == domi::SUCCESS, return domi::FAILED,
  982. "Check flags failed! Please check whether some atc params that include semicolons[;] use double "
  983. "quotation marks (\") to enclose each argument such as out_nodes, input_shape, dynamic_image_size");
  984. #if !defined(__ANDROID__) && !defined(ANDROID)
  985. // Load custom operator Library
  986. LoadCustomOpLib(true);
  987. SaveCustomCaffeProtoPath();
  988. GE_CHK_BOOL_EXEC(ret == domi::SUCCESS, return domi::FAILED, "check custom aicpu run so failed!");
  989. #endif
  990. const int f_stream_num = 1;
  991. std::map<string, string> options;
  992. options.insert(std::pair<string, string>(string(ge::FRAMEWORK_TYPE), to_string(FLAGS_framework)));
  993. options.insert(std::pair<string, string>(string(ge::STREAM_NUM), to_string(f_stream_num)));
  994. options.insert(std::pair<string, string>(string(ge::CALIBRATION_CONF_FILE), FLAGS_cal_conf));
  995. options.insert(std::pair<string, string>(string(ge::ENCRYPT_MODE), to_string(FLAGS_encrypt_mode)));
  996. options.insert(std::pair<string, string>(string(ge::EK_FILE), FLAGS_encrypt_key));
  997. options.insert(std::pair<string, string>(string(ge::CERT_FILE), FLAGS_certificate));
  998. options.insert(std::pair<string, string>(string(ge::HW_KEY_FILE), FLAGS_hardware_key));
  999. options.insert(std::pair<string, string>(string(ge::PRIVATE_KEY_FILE), FLAGS_private_key));
  1000. options.insert(std::pair<string, string>(string(ge::OUTPUT_NODE_NAME), FLAGS_out_nodes));
  1001. options.insert(std::pair<string, string>(string(ge::INSERT_OP_FILE), FLAGS_insert_op_conf));
  1002. options.insert(std::pair<string, string>(string(ge::PRECISION_MODE), FLAGS_precision_mode));
  1003. options.insert(std::pair<string, string>(string(ge::RUN_FLAG), to_string(0)));
  1004. options.insert(std::pair<string, string>(string(ge::TRAIN_FLAG), to_string(0)));
  1005. if (!FLAGS_output_type.empty()) {
  1006. options.insert(std::pair<string, string>(string(ge::OUTPUT_DATATYPE), FLAGS_output_type));
  1007. }
  1008. options.insert(std::pair<string, string>(string(ge::OP_SELECT_IMPL_MODE), FLAGS_op_select_implmode));
  1009. options.insert(std::pair<string, string>(string(ge::OPTYPELIST_FOR_IMPLMODE), FLAGS_optypelist_for_implmode));
  1010. if (!FLAGS_input_fp16_nodes.empty()) {
  1011. GELOGI("FLAGS_input_fp16_nodes : %s .", FLAGS_input_fp16_nodes.c_str());
  1012. options.insert(std::pair<string, string>(ge::INPUT_FP16_NODES, FLAGS_input_fp16_nodes));
  1013. }
  1014. options.insert(std::pair<string, string>(string(ge::AUTO_TUNE_MODE), FLAGS_auto_tune_mode));
  1015. options.insert(
  1016. std::pair<string, string>(string(ge::OPTION_EXEC_DISABLE_REUSED_MEMORY), to_string(FLAGS_disable_reuse_memory)));
  1017. options.insert(std::pair<string, string>(string(ge::SOC_VERSION), FLAGS_soc_version));
  1018. options.insert(std::pair<string, string>(string(ge::CORE_TYPE), FLAGS_core_type));
  1019. options.insert(std::pair<string, string>(string(ge::AICORE_NUM), FLAGS_aicore_num));
  1020. options.insert(std::pair<string, string>(string(ge::BUFFER_OPTIMIZE), FLAGS_buffer_optimize));
  1021. options.insert(std::pair<string, string>(string(ge::ENABLE_SMALL_CHANNEL), FLAGS_enable_small_channel));
  1022. options.insert(std::pair<string, string>(string(ge::FUSION_SWITCH_FILE), FLAGS_fusion_switch_file));
  1023. options.insert(std::pair<string, string>(string(ge::ENABLE_COMPRESS_WEIGHT),
  1024. (FLAGS_enable_compress_weight == "true") ?
  1025. ge::kEnableCompressWeightTrue : ge::kEnableCompressWeightFalse));
  1026. options.insert(std::pair<string, string>(string(ge::ENABLE_SINGLE_STREAM), FLAGS_enable_single_stream));
  1027. options.insert(std::pair<string, string>(string(ge::DEBUG_DIR), FLAGS_debug_dir));
  1028. options.insert(std::pair<string, string>(string(ge::OP_COMPILER_CACHE_DIR), FLAGS_op_compiler_cache_dir));
  1029. options.insert(std::pair<string, string>(string(ge::OP_COMPILER_CACHE_MODE), FLAGS_op_compiler_cache_mode));
  1030. SetDynamicInputSizeOptions();
  1031. if (!FLAGS_save_original_model.empty()) {
  1032. options.insert(std::pair<string, string>(string(ge::SAVE_ORIGINAL_MODEL), FLAGS_save_original_model));
  1033. options.insert(std::pair<string, string>(string(ge::ORIGINAL_MODEL_FILE), FLAGS_output + "_original.om"));
  1034. }
  1035. options.insert(std::pair<string, string>(string(ge::OP_DEBUG_LEVEL), to_string(FLAGS_op_debug_level)));
  1036. options.insert(std::pair<string, string>(string(ge::MDL_BANK_PATH_FLAG), FLAGS_mdl_bank_path));
  1037. options.insert(std::pair<string, string>(string(ge::OP_BANK_PATH_FLAG), FLAGS_op_bank_path));
  1038. options.insert(std::pair<string, string>(string(ge::DISPLAY_MODEL_INFO), FLAGS_display_model_info));
  1039. // set enable scope fusion passes
  1040. SetEnableScopeFusionPasses(FLAGS_enable_scope_fusion_passes);
  1041. // print atc option map
  1042. ge::PrintOptionMap(options, "atc option");
  1043. // When the ATC module is transferred to a model, the suffix ".om" is automatically added to the model name
  1044. FLAGS_output = FLAGS_output + ".om";
  1045. ret = GenerateModel(options, FLAGS_output);
  1046. if (ret != domi::SUCCESS) {
  1047. return domi::FAILED;
  1048. }
  1049. if (FLAGS_display_model_info == "1") {
  1050. GELOGI("need to display model info.");
  1051. return ge::ConvertOm(FLAGS_output.c_str(), "", false);
  1052. }
  1053. return domi::SUCCESS;
  1054. }
  1055. domi::Status ConvertModelToJson() {
  1056. Status ret = GFlagUtils::CheckConverJsonParamFlags();
  1057. GE_CHK_BOOL_EXEC(ret == domi::SUCCESS, return domi::FAILED, "Check convert json params flags failed!");
  1058. ret = ConvertModelToJson(FLAGS_framework, FLAGS_om, FLAGS_json);
  1059. GE_IF_BOOL_EXEC(ret != domi::SUCCESS, return domi::FAILED);
  1060. return domi::SUCCESS;
  1061. }
  1062. domi::Status DisplayModelInfo() {
  1063. // No model path passed in
  1064. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(FLAGS_om == "",
  1065. ErrorManager::GetInstance().ATCReportErrMessage("E10004", {"parameter"}, {"om"});
  1066. return ge::FAILED,
  1067. "Input parameter[--om]'s value is empty!!");
  1068. // Check if the model path is valid
  1069. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  1070. FLAGS_om != "" && !ge::CheckInputPathValid(FLAGS_om, "--om"),
  1071. return ge::FAILED,
  1072. "model file path is invalid: %s.", FLAGS_om.c_str());
  1073. if (FLAGS_framework == -1) {
  1074. return ge::ConvertOm(FLAGS_om.c_str(), "", false);
  1075. }
  1076. return ge::FAILED;
  1077. }
  1078. bool CheckRet(domi::Status ret) {
  1079. if (ret != domi::SUCCESS) {
  1080. if (FLAGS_mode == ONLY_PRE_CHECK) {
  1081. GELOGW("ATC precheck failed.");
  1082. } else if (FLAGS_mode == GEN_OM_MODEL) {
  1083. GELOGW("ATC generate offline model failed.");
  1084. } else if (FLAGS_mode == MODEL_TO_JSON) {
  1085. GELOGW("ATC convert model to json file failed.");
  1086. } else if (FLAGS_mode == PBTXT_TO_JSON) {
  1087. GELOGW("ATC convert pbtxt to json file failed.");
  1088. } else {
  1089. return false;
  1090. }
  1091. return false;
  1092. }
  1093. if (FLAGS_mode == ONLY_PRE_CHECK) {
  1094. GELOGI("ATC precheck success.");
  1095. } else if (FLAGS_mode == GEN_OM_MODEL) {
  1096. GELOGI("ATC generate offline model success.");
  1097. } else if (FLAGS_mode == MODEL_TO_JSON) {
  1098. GELOGI("ATC convert model to json file success.");
  1099. } else if (FLAGS_mode == PBTXT_TO_JSON) {
  1100. GELOGI("ATC convert pbtxt to json file success.");
  1101. }
  1102. return true;
  1103. }
  1104. domi::Status ConvertPbtxtToJson() {
  1105. Status ret = GFlagUtils::CheckConverJsonParamFlags();
  1106. if (ret != domi::SUCCESS) {
  1107. GELOGE(ge::FAILED, "Check convert json params flags failed!");
  1108. return domi::FAILED;
  1109. }
  1110. ret = ge::ConvertPbtxtToJson(FLAGS_om.c_str(), FLAGS_json.c_str());
  1111. if (ret != domi::SUCCESS) {
  1112. GELOGE(ge::FAILED, "ConvertPbtxtToJson fail.");
  1113. return domi::FAILED;
  1114. }
  1115. return domi::SUCCESS;
  1116. }
  1117. int init(int argc, char* argv[]) {
  1118. GFlagUtils::InitGFlag(argc, argv);
  1119. // set log level
  1120. int ret = -1;
  1121. const std::set<string> log_level = {"null", "debug", "info", "warning", "error"};
  1122. if (log_level.count(FLAGS_log) == 0) {
  1123. std::cout << "E10010: invalid value for --log:" << FLAGS_log
  1124. <<", only support debug, info, warning, error, null"<< std::endl;
  1125. return ret;
  1126. }
  1127. ret = ge::CheckLogParamValidAndSetLogLevel(FLAGS_log);
  1128. if (ret != 0) {
  1129. return ret;
  1130. }
  1131. std::string path_base = ge::GELib::GetPath();
  1132. ret = ErrorManager::GetInstance().Init(path_base);
  1133. if (ret != 0) {
  1134. DOMI_LOGE("ErrorManager init fail !");
  1135. return ret;
  1136. }
  1137. return 0;
  1138. }
  1139. long GetMemInfo(const std::string &key) {
  1140. std::string file_path = "/proc/meminfo";
  1141. std::ifstream fs(file_path, std::ifstream::in);
  1142. if (!fs.is_open()) {
  1143. GELOGW("Can not open %s .", file_path.c_str());
  1144. return 0;
  1145. }
  1146. std::string line;
  1147. while (getline(fs, line)) { // line not with \n
  1148. if (line.find(key) != std::string::npos) {
  1149. GELOGI("Find mem [%s] info line [%s]", key.c_str(), line.c_str());
  1150. fs.close();
  1151. size_t pos = line.find(":");
  1152. if (pos == std::string::npos) {
  1153. return 0;
  1154. }
  1155. std::string current_mem_info_str = line.substr(pos + 1);
  1156. ge::StringUtils::Trim(current_mem_info_str);
  1157. GELOGI("Find mem [%s] info [%s].", key.c_str(), current_mem_info_str.c_str());
  1158. return stol(current_mem_info_str);
  1159. }
  1160. }
  1161. fs.close(); // close the file
  1162. return 0;
  1163. }
  1164. bool CheckMemInfo() {
  1165. if (FLAGS_auto_tune_mode.empty()) {
  1166. return true;
  1167. }
  1168. // only check current available mem when auto_tune_mode is set.
  1169. long current_mem_available = GetMemInfo("MemAvailable");
  1170. GELOGI("Get mem available [%lu kB].", current_mem_available);
  1171. std::cout << "Current available mem is " << current_mem_available << "kB." << std::endl;
  1172. if ((current_mem_available > 0) && (current_mem_available < kMinAvailableMem)) {
  1173. GELOGE(ge::PARAM_INVALID, "Current available mem [%lu kB] can not be smaller than [%lu kB] .",
  1174. current_mem_available, kMinAvailableMem);
  1175. ErrorManager::GetInstance().ATCReportErrMessage("E10044", {"value", "min_value"},
  1176. {to_string(current_mem_available), to_string(kMinAvailableMem)});
  1177. return false;
  1178. }
  1179. return true;
  1180. }
  1181. int main(int argc, char* argv[]) {
  1182. Status ret = domi::SUCCESS;
  1183. std::cout << "ATC start working now, please wait for a moment." << std::endl;
  1184. // Initialize
  1185. if (init(argc, argv) != 0) {
  1186. std::cout << "ATC run failed, Please check the detail log, Try \'atc --help\' for more information" << std::endl;
  1187. return -1;
  1188. }
  1189. do {
  1190. if (!CheckMemInfo()) {
  1191. GELOGE(ge::PARAM_INVALID, "Current available mem is too small");
  1192. ret = domi::FAILED;
  1193. break;
  1194. }
  1195. if (!FLAGS_singleop.empty()) {
  1196. ret = GenerateSingleOp(FLAGS_singleop);
  1197. break;
  1198. }
  1199. // default mode(mode:0), Open source model to model
  1200. if (GEN_OM_MODEL == FLAGS_mode || ONLY_PRE_CHECK == FLAGS_mode) {
  1201. GE_IF_BOOL_EXEC(GenerateOmModel() != domi::SUCCESS, ret = domi::FAILED; break);
  1202. } else if (MODEL_TO_JSON == FLAGS_mode) { // Mode 1, transfer model to JSON
  1203. GE_CHK_BOOL_EXEC(ConvertModelToJson() == domi::SUCCESS, ret = domi::FAILED;
  1204. break, "ATC ConvertJson execute failed!!");
  1205. } else if (FLAGS_mode == ge::RunMode::PBTXT_TO_JSON) {
  1206. GE_CHK_BOOL_EXEC(ConvertPbtxtToJson() == domi::SUCCESS, ret = domi::FAILED;
  1207. break, "ATC convert pbtxt to json execute failed!!");
  1208. } else if (FLAGS_mode == ge::RunMode::DISPLAY_OM_INFO) {
  1209. GE_CHK_BOOL_EXEC(DisplayModelInfo() == domi::SUCCESS, ret = domi::FAILED;
  1210. break, "ATC DisplayModelInfo failed!!");
  1211. } else {
  1212. ErrorManager::GetInstance().ATCReportErrMessage(
  1213. "E10001", {"parameter", "value", "reason"}, {"--mode", std::to_string(FLAGS_mode), kModeSupport});
  1214. GELOGE(ge::PARAM_INVALID, "Invalid value for --mode[%d], %s.", FLAGS_mode, kModeSupport);
  1215. ret = domi::FAILED;
  1216. break;
  1217. }
  1218. } while (0);
  1219. if (!CheckRet(ret)) {
  1220. std::cout << "ATC run failed, Please check the detail log, Try \'atc --help\' for more information" << std::endl;
  1221. int result = ErrorManager::GetInstance().OutputErrMessage(STDOUT_FILENO);
  1222. if (result != 0) {
  1223. DOMI_LOGE("ErrorManager outputErrMessage fail !");
  1224. }
  1225. GELOGI("Current mem available mem is [%lu kB]", GetMemInfo("MemAvailable"));
  1226. return ret;
  1227. } else {
  1228. std::cout << "ATC run success, welcome to the next use." << std::endl;
  1229. (void)ErrorManager::GetInstance().OutputMessage(STDOUT_FILENO);
  1230. return 0;
  1231. }
  1232. } /*lint +e530*/

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