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

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

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