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

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

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