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.

omg.cc 47 kB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114
  1. /**
  2. * Copyright 2019-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 "omg/omg.h"
  17. #include <fstream>
  18. #include <iostream>
  19. #include <memory>
  20. #include "common/auth/file_saver.h"
  21. #include "common/convert/pb2json.h"
  22. #include "common/debug/log.h"
  23. #include "common/debug/memory_dumper.h"
  24. #include "common/ge/ge_util.h"
  25. #include "common/helper/model_helper.h"
  26. #include "common/model_parser/base.h"
  27. #include "common/model_saver.h"
  28. #include "common/properties_manager.h"
  29. #include "common/string_util.h"
  30. #include "common/types.h"
  31. #include "common/util.h"
  32. #include "common/util/error_manager/error_manager.h"
  33. #include "framework/common/debug/ge_log.h"
  34. #include "framework/omg/parser/parser_inner_ctx.h"
  35. #include "google/protobuf/io/zero_copy_stream_impl.h"
  36. #include "graph/compute_graph.h"
  37. #include "graph/debug/ge_attr_define.h"
  38. #include "graph/debug/ge_attr_define.h"
  39. #include "graph/optimize/common/params.h"
  40. #include "graph/utils/type_utils.h"
  41. #include "ir_build/atc_ir_common.h"
  42. #include "omg/omg_inner_types.h"
  43. #include "omg/parser/model_parser.h"
  44. #include "omg/parser/parser_factory.h"
  45. #include "omg/parser/weights_parser.h"
  46. #include "parser/common/pre_checker.h"
  47. #include "proto/ge_ir.pb.h"
  48. #include "register/op_registry.h"
  49. using nlohmann::json;
  50. using ProcParam = struct PROC_PARAM;
  51. using domi::ModelParserFactory;
  52. using domi::WeightsParserFactory;
  53. using std::ostringstream;
  54. namespace google {
  55. namespace protobuf {
  56. namespace io {
  57. class FileOutputStream;
  58. }
  59. } // namespace protobuf
  60. } // namespace google
  61. namespace ge {
  62. namespace {
  63. const std::string kGraphDefaultName = "domi_default";
  64. const std::string kScopeIdAttr = "fusion_scope";
  65. const char *const kOutputTypeSample = "correct sample is \"opname:index:dtype\"";
  66. const char *const kOutputTypeSupport = "only support FP32, FP16, UINT8";
  67. const char *const kOutputTypeError = "The multiple out nodes set in output_type must be found in out_nodes.";
  68. const size_t kOmInfoSize = 5;
  69. } // namespace
  70. // When the model is converted to a JSON file, the following operator attributes in the blacklist will be ignored
  71. const std::set<string> kOmBlackFields = {"output", "data_offset", "data", "workspace", "workspace_bytes",
  72. "memory_size", "weight_size", "size", "bt", "quantize_factor"};
  73. static std::map<std::string, ge::DataType> output_type_str_to_datatype = {
  74. {"FP32", ge::DT_FLOAT}, {"FP16", ge::DT_FLOAT16}, {"UINT8", ge::DT_UINT8}};
  75. static bool CheckInputTrueOrFalse(const std::string &s, const std::string &atc_param) {
  76. if ((s == "true") || (s == "false")) {
  77. return true;
  78. } else {
  79. ErrorManager::GetInstance().ATCReportErrMessage("E10005", {"parameter", "value"}, {atc_param, s});
  80. GELOGE(PARAM_INVALID, "Input parameter[--%s]'s value[%s] must be true or false.", atc_param.c_str(), s.c_str());
  81. return false;
  82. }
  83. }
  84. static void ParseAtcParms(const std::map<std::string, std::string> &atc_params, const std::string &key,
  85. std::string &param) {
  86. auto iter = atc_params.find(key);
  87. if (iter != atc_params.end()) {
  88. param = iter->second;
  89. }
  90. }
  91. static Status CheckInputShapeNode(const ComputeGraphPtr &graph, const bool is_dynamic_input) {
  92. if (!is_dynamic_input) {
  93. for (auto node : graph->GetDirectNode()) {
  94. if (node->GetType() == DATA) {
  95. auto data_op_desc = node->GetOpDesc();
  96. GE_CHECK_NOTNULL(data_op_desc);
  97. auto tensor_desc = data_op_desc->MutableInputDesc(0);
  98. GE_CHECK_NOTNULL(tensor_desc);
  99. for (auto dim : tensor_desc->GetShape().GetDims()) {
  100. if (dim < 0) {
  101. GELOGE(PARAM_INVALID,
  102. "Input op [%s] shape %ld is negative, maybe you should set input_shape to specify its shape",
  103. node->GetName().c_str(), dim);
  104. const string reason = "maybe you should set input_shape to specify its shape";
  105. ErrorManager::GetInstance().ATCReportErrMessage("E10001", {"parameter", "value", "reason"},
  106. {node->GetName(), to_string(dim), reason});
  107. return PARAM_INVALID;
  108. }
  109. }
  110. }
  111. }
  112. }
  113. for (auto it : domi::GetContext().user_input_dims) {
  114. std::string node_name = it.first;
  115. ge::NodePtr node = graph->FindNode(node_name);
  116. if (node == nullptr) {
  117. ErrorManager::GetInstance().ATCReportErrMessage("E10016", {"parameter", "opname"}, {"input_shape", node_name});
  118. GELOGE(PARAM_INVALID, "Input parameter[--input_shape]'s opname[%s] is not exist in model", node_name.c_str());
  119. return PARAM_INVALID;
  120. }
  121. if (node->GetType() != DATA) {
  122. ErrorManager::GetInstance().ATCReportErrMessage("E10017", {"parameter", "opname"}, {"input_shape", node_name});
  123. GELOGE(PARAM_INVALID, "Input parameter[--input_shape]'s opname[%s] is not a input opname", node_name.c_str());
  124. return PARAM_INVALID;
  125. }
  126. }
  127. return SUCCESS;
  128. }
  129. void AddAttrsForInputNodes(const vector<string> &adjust_fp16_format_vec, const string &fp16_nodes_name, uint32_t index,
  130. OpDescPtr &op_desc) {
  131. if (AttrUtils::SetStr(op_desc, ATTR_ATC_USER_DEFINE_DATATYPE, TypeUtils::DataTypeToSerialString(DT_FLOAT16))) {
  132. if ((index < adjust_fp16_format_vec.size()) && (adjust_fp16_format_vec[index] == "true")) {
  133. GELOGI("This node [%s] should be set NC1HWC0", fp16_nodes_name.c_str());
  134. if (!AttrUtils::SetStr(op_desc, ATTR_ATC_USER_DEFINE_FORMAT, TypeUtils::FormatToSerialString(FORMAT_NC1HWC0))) {
  135. GELOGW("This node [%s] set NC1HWC0 failed", fp16_nodes_name.c_str());
  136. }
  137. }
  138. }
  139. }
  140. static Status CheckInputFp16Nodes(const ComputeGraphPtr &graph, const string &input_fp16_nodes,
  141. const string &is_input_adjust_hw_layout) {
  142. GE_CHECK_NOTNULL(graph);
  143. vector<string> adjust_fp16_format_vec;
  144. if (!is_input_adjust_hw_layout.empty()) {
  145. adjust_fp16_format_vec = StringUtils::Split(is_input_adjust_hw_layout, ',');
  146. for (auto &s : adjust_fp16_format_vec) {
  147. StringUtils::Trim(s);
  148. if (!CheckInputTrueOrFalse(s, "is_input_adjust_hw_layout")) {
  149. GELOGE(PARAM_INVALID, "Invalid Param, is_input_adjust_hw_layout only support true/false: but is [%s]",
  150. is_input_adjust_hw_layout.c_str());
  151. return PARAM_INVALID;
  152. }
  153. }
  154. }
  155. if (input_fp16_nodes.empty()) {
  156. return SUCCESS;
  157. }
  158. GELOGI("The input_fp16_nodes is set %s", input_fp16_nodes.c_str());
  159. vector<string> input_fp16_nodes_vec = StringUtils::Split(input_fp16_nodes, ';');
  160. for (uint32_t i = 0; i < input_fp16_nodes_vec.size(); ++i) {
  161. ge::NodePtr node = graph->FindNode(input_fp16_nodes_vec[i]);
  162. if (node == nullptr) {
  163. ErrorManager::GetInstance().ATCReportErrMessage("E10016", {"parameter", "opname"},
  164. {"input_fp16_nodes", input_fp16_nodes_vec[i]});
  165. GELOGE(PARAM_INVALID, "Input parameter[--input_fp16_nodes]'s opname[%s] is not exist in model",
  166. input_fp16_nodes_vec[i].c_str());
  167. return PARAM_INVALID;
  168. }
  169. auto op_desc = node->GetOpDesc();
  170. GE_CHECK_NOTNULL(op_desc);
  171. if (op_desc->GetType() != DATA) {
  172. ErrorManager::GetInstance().ATCReportErrMessage("E10017", {"parameter", "opname"},
  173. {"input_fp16_nodes", input_fp16_nodes_vec[i]});
  174. GELOGE(PARAM_INVALID, "Input parameter[--input_fp16_nodes]'s opname[%s] is not a input opname",
  175. input_fp16_nodes_vec[i].c_str());
  176. return PARAM_INVALID;
  177. }
  178. AddAttrsForInputNodes(adjust_fp16_format_vec, input_fp16_nodes_vec[i], i, op_desc);
  179. }
  180. return SUCCESS;
  181. }
  182. static Status SetWeightCompressNodes(const ComputeGraphPtr &graph, const string &compress_weight_conf) {
  183. GE_CHECK_NOTNULL(graph);
  184. if (compress_weight_conf.empty()) {
  185. return SUCCESS;
  186. }
  187. std::string real_path = RealPath(compress_weight_conf.c_str());
  188. if (real_path.empty()) {
  189. GELOGE(PARAM_INVALID, "Can not get real path for %s.", compress_weight_conf.c_str());
  190. return PARAM_INVALID;
  191. }
  192. std::ifstream ifs(real_path);
  193. if (!ifs.is_open()) {
  194. GELOGE(domi::FAILED, "Open file %s failed", compress_weight_conf.c_str());
  195. return domi::FAILED;
  196. }
  197. std::string compress_nodes;
  198. ifs >> compress_nodes;
  199. ifs.close();
  200. GELOGI("Compress weight of nodes: %s", compress_nodes.c_str());
  201. vector<string> compress_node_vec = StringUtils::Split(compress_nodes, ';');
  202. for (size_t i = 0; i < compress_node_vec.size(); ++i) {
  203. ge::NodePtr node = graph->FindNode(compress_node_vec[i]);
  204. if (node == nullptr) {
  205. GELOGW("node %s is not in graph", compress_node_vec[i].c_str());
  206. continue;
  207. }
  208. auto op_desc = node->GetOpDesc();
  209. GE_CHECK_NOTNULL(op_desc);
  210. if (!ge::AttrUtils::SetBool(op_desc, ge::ATTR_NAME_COMPRESS_WEIGHT, true)) {
  211. GELOGE(domi::FAILED, "node %s SetBool failed.", compress_node_vec[i].c_str());
  212. return domi::FAILED;
  213. }
  214. }
  215. return SUCCESS;
  216. }
  217. static Status ParseOutputFp16NodesFormat(const string &is_output_fp16) {
  218. if (is_output_fp16.empty()) {
  219. return SUCCESS;
  220. }
  221. vector<domiTensorFormat_t> &output_formats = domi::GetContext().output_formats;
  222. output_formats.clear();
  223. vector<string> node_format_vec = StringUtils::Split(is_output_fp16, ',');
  224. for (auto &is_fp16 : node_format_vec) {
  225. StringUtils::Trim(is_fp16);
  226. if (!CheckInputTrueOrFalse(is_fp16, "is_output_adjust_hw_layout")) {
  227. GELOGE(PARAM_INVALID, "Invalid Param, is_output_adjust_hw_layout only support true/false: but is [%s]",
  228. is_output_fp16.c_str());
  229. return PARAM_INVALID;
  230. }
  231. if (is_fp16 == "false") {
  232. output_formats.push_back(DOMI_TENSOR_ND);
  233. } else if (is_fp16 == "true") {
  234. output_formats.push_back(domi::DOMI_TENSOR_NC1HWC0);
  235. }
  236. }
  237. return SUCCESS;
  238. }
  239. void FindParserSo(const string &path, vector<string> &file_list, string &caffe_parser_path) {
  240. // path, Change to absolute path
  241. string real_path = RealPath(path.c_str());
  242. if (real_path.empty()) { // plugin path does not exist
  243. return;
  244. }
  245. struct dirent *dent(nullptr);
  246. DIR *dir = opendir(real_path.c_str());
  247. if (nullptr == dir) { // plugin path does not exist
  248. GELOGW("Open directory %s failed.", path.c_str());
  249. return;
  250. }
  251. while ((dent = readdir(dir)) != nullptr) {
  252. if (strcmp(dent->d_name, ".") == 0 || strcmp(dent->d_name, "..") == 0) continue;
  253. string name = dent->d_name;
  254. string full_name = real_path + "/" + name;
  255. const string so_suff = ".so";
  256. const string caffe_parser_so_suff = "lib_caffe_parser.so";
  257. const string aicpu_so_suff = "_aicpu.so";
  258. const string aicpu_host_so_suff = "_online.so";
  259. if (name.size() >= so_suff.size() && name.compare(name.size() - so_suff.size(), so_suff.size(), so_suff) == 0) {
  260. if (full_name.size() >= caffe_parser_so_suff.size() &&
  261. full_name.compare(full_name.size() - caffe_parser_so_suff.size(), caffe_parser_so_suff.size(),
  262. caffe_parser_so_suff) == 0) {
  263. caffe_parser_path = full_name;
  264. } else if ((full_name.size() >= aicpu_so_suff.size() &&
  265. full_name.compare(full_name.size() - aicpu_so_suff.size(), aicpu_so_suff.size(), aicpu_so_suff) ==
  266. 0) ||
  267. (full_name.size() >= aicpu_host_so_suff.size() &&
  268. full_name.compare(full_name.size() - aicpu_host_so_suff.size(), aicpu_host_so_suff.size(),
  269. aicpu_host_so_suff) == 0)) {
  270. // aicpu so, Put the file path into the omgcontext and save into the model in the builder stage;
  271. domi::GetContext().aicpu_op_run_paths.push_back(full_name);
  272. } else { // save parser so path into file_list vector
  273. file_list.push_back(full_name);
  274. }
  275. continue;
  276. }
  277. FindParserSo(full_name, file_list, caffe_parser_path);
  278. }
  279. closedir(dir);
  280. return;
  281. }
  282. Status CheckCustomAiCpuOpLib() {
  283. std::vector<std::string> vec_op_type;
  284. domi::OpRegistry::Instance()->GetOpTypeByImplyType(vec_op_type, domi::ImplyType::CUSTOM);
  285. for (uint32_t i = 0; i < vec_op_type.size(); i++) {
  286. bool aicpu_so_exist = false;
  287. std::string ai_cpu_so_name = "lib" + vec_op_type[i] + "_aicpu.so";
  288. for (uint32_t j = 0; j < domi::GetContext().aicpu_op_run_paths.size(); j++) {
  289. string bin_file_path = domi::GetContext().aicpu_op_run_paths[j];
  290. if (bin_file_path.size() >= ai_cpu_so_name.size() &&
  291. bin_file_path.compare(bin_file_path.size() - ai_cpu_so_name.size(), ai_cpu_so_name.size(), ai_cpu_so_name) ==
  292. 0) {
  293. aicpu_so_exist = true;
  294. break;
  295. }
  296. }
  297. if (!aicpu_so_exist) {
  298. GELOGE(domi::FAILED, "cant find aicpu run so(%s), please check the plugin path!", ai_cpu_so_name.c_str());
  299. return domi::FAILED;
  300. }
  301. }
  302. return domi::SUCCESS;
  303. }
  304. Status SetOutFormatAndDataTypeAttr(ge::OpDescPtr op_desc, const ge::Format format, const ge::DataType data_type) {
  305. if (op_desc == nullptr) {
  306. GELOGE(domi::FAILED, "Input op desc invalid.");
  307. return domi::FAILED;
  308. }
  309. (void)ge::AttrUtils::SetInt(op_desc, ATTR_NAME_NET_OUTPUT_FORMAT, format);
  310. (void)ge::AttrUtils::SetInt(op_desc, ATTR_NAME_NET_OUTPUT_DATATYPE, data_type);
  311. return domi::SUCCESS;
  312. }
  313. bool CheckDigitStr(std::string &str) {
  314. for (char c : str) {
  315. if (!isdigit(c)) {
  316. GELOGE(domi::FAILED, "value[%s] is not positive integer", str.c_str());
  317. return false;
  318. }
  319. }
  320. return true;
  321. }
  322. Status StringToInt(std::string &str, int32_t &value) {
  323. try {
  324. if (!CheckDigitStr(str)) {
  325. GELOGE(PARAM_INVALID, "Invalid of digit string: %s ", str.c_str());
  326. ErrorManager::GetInstance().ATCReportErrMessage("E10001", {"parameter", "value", "reason"},
  327. {"--output_type", str, "is not positive integer"});
  328. return PARAM_INVALID;
  329. }
  330. value = stoi(str);
  331. } catch (std::invalid_argument &) {
  332. GELOGE(PARAM_INVALID, "Invalid of digit string: %s, catch invalid_argument.", str.c_str());
  333. ErrorManager::GetInstance().ATCReportErrMessage("E10014", {"parameter", "value"}, {"--output_type", str});
  334. return PARAM_INVALID;
  335. } catch (std::out_of_range &) {
  336. GELOGE(PARAM_INVALID, "Invalid of digit string: %s, catch out_of_range.", str.c_str());
  337. ErrorManager::GetInstance().ATCReportErrMessage("E10013", {"parameter", "value"}, {"--output_type", str});
  338. return PARAM_INVALID;
  339. }
  340. return SUCCESS;
  341. }
  342. Status VerifyOutputTypeAndOutNodes(std::vector<std::string> &out_type_vec) {
  343. std::vector<std::pair<std::string, int32_t>> user_out_nodes = domi::GetContext().user_out_nodes;
  344. std::set<std::string> out_nodes_info;
  345. for (uint32_t i = 0; i < user_out_nodes.size(); ++i) {
  346. // out_nodes set should include output_type and output_format
  347. std::string tmp = user_out_nodes[i].first + ":" + to_string(user_out_nodes[i].second);
  348. out_nodes_info.emplace(tmp);
  349. }
  350. for (uint32_t i = 0; i < out_type_vec.size(); ++i) {
  351. if (out_nodes_info.find(out_type_vec[i]) == out_nodes_info.end()) {
  352. ErrorManager::GetInstance().ATCReportErrMessage("E10001", {"parameter", "value", "reason"},
  353. {"--output_type", out_type_vec[i], kOutputTypeError});
  354. GELOGE(domi::FAILED, "Invalid value for --output_type[%s], %s.", out_type_vec[i].c_str(), kOutputTypeError);
  355. return domi::FAILED;
  356. }
  357. }
  358. return domi::SUCCESS;
  359. }
  360. Status CheckOutPutDataTypeSupport(const std::string &output_type) {
  361. auto it = output_type_str_to_datatype.find(output_type);
  362. if (it == output_type_str_to_datatype.end()) {
  363. ErrorManager::GetInstance().ATCReportErrMessage("E10001", {"parameter", "value", "reason"},
  364. {"--output_type", output_type, kOutputTypeSupport});
  365. GELOGE(PARAM_INVALID, "Invalid value for --output_type[%s], %s.", output_type.c_str(), kOutputTypeSupport);
  366. return domi::FAILED;
  367. }
  368. return domi::SUCCESS;
  369. }
  370. Status ParseOutputType(const std::string &output_type, std::map<std::string, vector<std::string>> &output_node_dt_map) {
  371. if (output_type.find(':') == std::string::npos) {
  372. GELOGI("output_type is not multiple nodes, means all out nodes");
  373. return CheckOutPutDataTypeSupport(output_type);
  374. }
  375. std::vector<std::string> out_type_vec;
  376. vector<string> nodes_v = StringUtils::Split(output_type, ';');
  377. for (const string &node : nodes_v) {
  378. vector<string> node_index_type_v = StringUtils::Split(node, ':');
  379. if (node_index_type_v.size() != 3) { // The size must be 3.
  380. ErrorManager::GetInstance().ATCReportErrMessage("E10001", {"parameter", "value", "reason"},
  381. {"--output_type", node, kOutputTypeSample});
  382. GELOGE(PARAM_INVALID, "Invalid value for --output_type[%s], %s.", node.c_str(), kOutputTypeSample);
  383. return domi::FAILED;
  384. }
  385. ge::DataType tmp_dt;
  386. std::string node_name = StringUtils::Trim(node_index_type_v[0]);
  387. std::string index_str = StringUtils::Trim(node_index_type_v[1]);
  388. int32_t index;
  389. if (StringToInt(index_str, index) != SUCCESS) {
  390. GELOGE(PARAM_INVALID, "This str must be digit string, while the actual input is %s.", index_str.c_str());
  391. return domi::FAILED;
  392. }
  393. std::string dt_value = StringUtils::Trim(node_index_type_v[2]);
  394. auto it = output_type_str_to_datatype.find(dt_value);
  395. if (it == output_type_str_to_datatype.end()) {
  396. ErrorManager::GetInstance().ATCReportErrMessage("E10001", {"parameter", "value", "reason"},
  397. {"--output_type", dt_value, kOutputTypeSupport});
  398. GELOGE(ge::PARAM_INVALID, "Invalid value for --output_type[%s], %s.", dt_value.c_str(), kOutputTypeSupport);
  399. return domi::FAILED;
  400. } else {
  401. tmp_dt = it->second;
  402. }
  403. out_type_vec.push_back(node_name + ":" + index_str);
  404. std::string index_dt_str = index_str + ":" + TypeUtils::DataTypeToSerialString(tmp_dt);
  405. auto it1 = output_node_dt_map.find(node_name);
  406. if (it1 == output_node_dt_map.end()) {
  407. vector<string> tmp_vec;
  408. tmp_vec.push_back(index_dt_str);
  409. output_node_dt_map.emplace(node_name, tmp_vec);
  410. } else {
  411. it1->second.push_back(index_dt_str);
  412. }
  413. }
  414. return VerifyOutputTypeAndOutNodes(out_type_vec);
  415. }
  416. Status CheckOutNode(ge::OpDescPtr op_desc, int32_t index) {
  417. int32_t out_size = op_desc->GetOutputsSize();
  418. if (index < 0 || index >= out_size) {
  419. GELOGE(domi::FAILED,
  420. "out_node [%s] output index:%d must be smaller "
  421. "than node output size:%d and can not be negative!",
  422. op_desc->GetName().c_str(), index, out_size);
  423. std::string fail_reason = "output index:" + to_string(index) +
  424. " must be smaller than output size:" + to_string(out_size) + " and can not be negative!";
  425. ErrorManager::GetInstance().ATCReportErrMessage("E10003", {"parameter", "value", "reason"},
  426. {"out_nodes", op_desc->GetName(), fail_reason});
  427. return domi::FAILED;
  428. }
  429. return domi::SUCCESS;
  430. }
  431. Status SetOutputNodeInfo(ge::Graph &graph, const std::string &output_type, const std::string &output) {
  432. ge::ComputeGraphPtr compute_graph = ge::GraphUtils::GetComputeGraph(graph);
  433. GE_CHECK_NOTNULL(compute_graph);
  434. std::vector<std::pair<std::string, int32_t>> user_out_nodes = domi::GetContext().user_out_nodes;
  435. std::vector<domiTensorFormat_t> output_formats = domi::GetContext().output_formats;
  436. std::vector<std::pair<ge::NodePtr, int32_t>> output_nodes_info;
  437. std::vector<std::string> output_nodes_name;
  438. std::map<std::string, vector<std::string>> output_node_dt_map;
  439. if (!output_type.empty()) {
  440. if (ParseOutputType(output_type, output_node_dt_map) != SUCCESS) {
  441. GELOGE(domi::FAILED, "Parse output_type failed.");
  442. return domi::FAILED;
  443. }
  444. }
  445. // User declared outputs
  446. for (uint32_t i = 0; i < user_out_nodes.size(); ++i) {
  447. ge::NodePtr out_node = compute_graph->FindNode(user_out_nodes[i].first);
  448. if (out_node == nullptr) {
  449. ErrorManager::GetInstance().ATCReportErrMessage("E10016", {"parameter", "opname"},
  450. {"out_nodes", user_out_nodes[i].first});
  451. GELOGE(domi::FAILED, "Can not find src node (%s) in graph.", user_out_nodes[i].first.c_str());
  452. return domi::FAILED;
  453. }
  454. auto op_desc = out_node->GetOpDesc();
  455. GE_CHECK_NOTNULL(op_desc);
  456. if (CheckOutNode(op_desc, user_out_nodes[i].second) != SUCCESS) {
  457. GELOGE(domi::FAILED, "Check out node (%s) fail.", user_out_nodes[i].first.c_str());
  458. return domi::FAILED;
  459. }
  460. if (i < output_formats.size()) {
  461. if (output_formats[i] == domi::DOMI_TENSOR_NC1HWC0) {
  462. GELOGI("The output node [%s] should be set NC1HWC0", user_out_nodes[i].first.c_str());
  463. vector<string> output_fp16_5hd_vec;
  464. (void)ge::AttrUtils::GetListStr(op_desc, "_user_defined_output_fp16_5hd", output_fp16_5hd_vec);
  465. output_fp16_5hd_vec.push_back(std::to_string(user_out_nodes[i].second) + ":" + "NC1HWC0");
  466. (void)ge::AttrUtils::SetListStr(op_desc, "_user_defined_output_fp16_5hd", output_fp16_5hd_vec);
  467. }
  468. }
  469. auto it = output_node_dt_map.find(user_out_nodes[i].first);
  470. if (it != output_node_dt_map.end()) {
  471. GELOGI("The output node [%s] need to be set output_type", user_out_nodes[i].first.c_str());
  472. (void)ge::AttrUtils::SetListStr(op_desc, "_user_defined_output_data_type", it->second);
  473. }
  474. output_nodes_info.push_back(std::make_pair(out_node, user_out_nodes[i].second));
  475. }
  476. // default output node (leaf)
  477. if (user_out_nodes.empty()) {
  478. for (ge::NodePtr node : compute_graph->GetDirectNode()) {
  479. if (!node->GetInAllNodes().empty() && node->GetOutAllNodes().empty()) {
  480. Status ret = GetOutputLeaf(node, output_nodes_info);
  481. GE_CHK_BOOL_RET_STATUS(ret == SUCCESS, ret, "find leaf fail.");
  482. }
  483. }
  484. }
  485. GetOutputNodesNameAndIndex(output_nodes_info, output_nodes_name);
  486. compute_graph->SetGraphOutNodesInfo(output_nodes_info);
  487. domi::GetContext().net_out_nodes = output_nodes_name;
  488. return domi::SUCCESS;
  489. }
  490. void GetOutputNodesNameAndIndex(std::vector<std::pair<ge::NodePtr, int32_t>> &output_nodes_info,
  491. std::vector<std::string> &output_nodes_name) {
  492. output_nodes_name.clear();
  493. if (domi::GetContext().out_top_names.empty()) {
  494. // tf process, no top name.
  495. for (const auto output_node_info : output_nodes_info) {
  496. std::string node_name = output_node_info.first->GetName();
  497. int32_t index = output_node_info.second;
  498. output_nodes_name.push_back(node_name + ":" + std::to_string(index));
  499. }
  500. return;
  501. }
  502. // caffe process, need add top name after node_name:index
  503. for (size_t i = 0; i < output_nodes_info.size(); ++i) {
  504. std::string node_name = output_nodes_info[i].first->GetName();
  505. int32_t index = output_nodes_info[i].second;
  506. if (i < domi::GetContext().out_top_names.size()) {
  507. output_nodes_name.push_back(node_name + ":" + std::to_string(index) + ":" + domi::GetContext().out_top_names[i]);
  508. } else {
  509. GELOGW("Get top name of node [%s] fail.", node_name.c_str());
  510. output_nodes_name.push_back(node_name + ":" + std::to_string(index));
  511. }
  512. }
  513. }
  514. Status GetOutputLeaf(NodePtr node, std::vector<std::pair<ge::NodePtr, int32_t>> &output_nodes_info) {
  515. ge::OpDescPtr tmpDescPtr = node->GetOpDesc();
  516. if (tmpDescPtr == nullptr) {
  517. GELOGE(domi::FAILED, "Get outnode op desc fail.");
  518. return domi::FAILED;
  519. }
  520. size_t size = tmpDescPtr->GetOutputsSize();
  521. if (node->GetType() != NETOUTPUT) {
  522. for (size_t index = 0; index < size; ++index) {
  523. output_nodes_info.push_back(std::make_pair(node, index));
  524. }
  525. } else {
  526. const auto in_anchors = node->GetAllInDataAnchors();
  527. for (auto in_anchor : in_anchors) {
  528. auto out_anchor = in_anchor->GetPeerOutAnchor();
  529. if (out_anchor == nullptr) {
  530. GELOGE(domi::FAILED, "Get leaf node op desc fail.");
  531. return domi::FAILED;
  532. }
  533. auto out_node = out_anchor->GetOwnerNode();
  534. output_nodes_info.push_back(std::make_pair(out_node, out_anchor->GetIdx()));
  535. }
  536. }
  537. return SUCCESS;
  538. }
  539. ///
  540. /// @ingroup domi_common
  541. /// @brief Initialize omgcontext based on command line input
  542. /// @param [in] input_shape Input shape string to be parsed
  543. /// @return SUCCESS: parse successfully; PARAM_INVALID:parse failed
  544. ///
  545. Status InitDomiOmgContext(const string &input_shape, const string &input_format, const string &net_format,
  546. bool is_dynamic_input) {
  547. // Clear omgcontext data first
  548. domi::GetContext().input_dims.clear();
  549. domi::GetContext().user_input_dims.clear();
  550. domi::GetContext().is_dynamic_input = is_dynamic_input;
  551. // the default value is ND
  552. domi::GetContext().format = DOMI_TENSOR_ND;
  553. if (!input_format.empty()) {
  554. auto iter = ge::input_format_str_to_geformat.find(input_format);
  555. if (iter != ge::input_format_str_to_geformat.end()) {
  556. domi::GetContext().format = iter->second;
  557. } else {
  558. GELOGE(PARAM_INVALID, "Input format %s not support , expect ND/NCHW/NHWC/CHWN/NC1HWC0/NHWC1C0.",
  559. input_format.c_str());
  560. return PARAM_INVALID;
  561. }
  562. }
  563. // Input is empty, do not process
  564. if (input_shape.empty()) {
  565. return SUCCESS;
  566. }
  567. // Analyze the input shape paramete
  568. unordered_map<string, vector<int64_t>> &shape_map = domi::GetContext().input_dims;
  569. if (!ge::ParseInputShape(input_shape, domi::GetContext().input_dims, domi::GetContext().user_input_dims,
  570. is_dynamic_input) ||
  571. shape_map.empty()) {
  572. GELOGE(PARAM_INVALID, "Failed to parse input shape: %s", input_shape.c_str());
  573. return PARAM_INVALID;
  574. }
  575. return SUCCESS;
  576. }
  577. Status ParseOutNodes(const string &out_nodes) {
  578. try {
  579. // parse output node
  580. if (!out_nodes.empty()) {
  581. domi::GetContext().out_nodes_map.clear();
  582. domi::GetContext().user_out_nodes.clear();
  583. domi::GetContext().user_out_nodes_top_vec.clear();
  584. vector<string> nodes_v = StringUtils::Split(out_nodes, ';');
  585. for (const string &node : nodes_v) {
  586. vector<string> key_value_v = StringUtils::Split(node, ':');
  587. if (key_value_v.size() != 2) { // The size must be 2.
  588. if (key_value_v.size() == 1 && domi::GetContext().type == domi::CAFFE) {
  589. domi::GetContext().user_out_nodes_top_vec.push_back(node);
  590. continue;
  591. }
  592. ErrorManager::GetInstance().ATCReportErrMessage(
  593. "E10001", {"parameter", "value", "reason"},
  594. {"--out_nodes", node, "the correct format is \"node_name1:0;node_name1:1;node_name2:0\""});
  595. GELOGE(PARAM_INVALID,
  596. "The input format of --out_nodes is invalid, the correct format is "
  597. "\"node_name1:0;node_name1:1;node_name2:0\", while the actual input is %s.",
  598. node.c_str());
  599. return PARAM_INVALID;
  600. }
  601. if (!domi::GetContext().user_out_nodes_top_vec.empty()) {
  602. ErrorManager::GetInstance().ATCReportErrMessage("E10001", {"parameter", "value", "reason"},
  603. {"--out_nodes", out_nodes, "is not all index or top_name"});
  604. GELOGE(PARAM_INVALID, "This out_nodes str must be all index or top_name, while the actual input is %s",
  605. out_nodes.c_str());
  606. return PARAM_INVALID;
  607. }
  608. // stoi: The method may throw an exception: invalid_argument/out_of_range
  609. if (!CheckDigitStr(key_value_v[1])) {
  610. ErrorManager::GetInstance().ATCReportErrMessage("E10001", {"parameter", "value", "reason"},
  611. {"--out_nodes", out_nodes, "is not positive integer"});
  612. GELOGE(PARAM_INVALID, "This str must be digit string, while the actual input is %s", out_nodes.c_str());
  613. return PARAM_INVALID;
  614. }
  615. auto iter = domi::GetContext().out_nodes_map.find(key_value_v[0]);
  616. int32_t index = stoi(StringUtils::Trim(key_value_v[1]));
  617. GELOGD("Get output info: node[%s] and index[%ld]", key_value_v[0].c_str(), index);
  618. if (iter != domi::GetContext().out_nodes_map.end()) {
  619. iter->second.emplace_back(index);
  620. } else {
  621. std::vector<int32_t> index_v;
  622. index_v.emplace_back(index);
  623. domi::GetContext().out_nodes_map.emplace(key_value_v[0], index_v);
  624. }
  625. domi::GetContext().user_out_nodes.push_back(std::make_pair(key_value_v[0], index));
  626. }
  627. }
  628. } catch (std::invalid_argument &) {
  629. GELOGE(PARAM_INVALID, "Invalid of out_nodes: %s ", out_nodes.c_str());
  630. ErrorManager::GetInstance().ATCReportErrMessage("E10014", {"parameter", "value"}, {"--out_nodes", out_nodes});
  631. return PARAM_INVALID;
  632. } catch (std::out_of_range &) {
  633. GELOGE(PARAM_INVALID, "Invalid of out_nodes: %s ", out_nodes.c_str());
  634. ErrorManager::GetInstance().ATCReportErrMessage("E10013", {"parameter", "value"}, {"--out_nodes", out_nodes});
  635. return PARAM_INVALID;
  636. }
  637. return SUCCESS;
  638. }
  639. /// @ingroup domi_common
  640. /// @brief Judge whether the op_Name_Map parameter matches the network
  641. /// @param [in] graph Input network graph
  642. /// @return SUCCESS: Input parameters are correct; PARAM_INVALID: Input parameters are incorrect
  643. ///
  644. static Status CheckOpNameMap(const ComputeGraphPtr &graph, const std::string &op_conf) {
  645. GE_CHECK_NOTNULL(graph);
  646. unordered_map<string, string> graphNodeTypes;
  647. for (const NodePtr &node : graph->GetAllNodes()) {
  648. auto op_desc = node->GetOpDesc();
  649. if (op_desc == nullptr) {
  650. GELOGE(PARAM_INVALID, "Invalid parameter for opDesc.");
  651. return PARAM_INVALID;
  652. }
  653. graphNodeTypes[op_desc->GetType()] = "";
  654. }
  655. std::map<std::string, std::string> &propertiesMap = domi::GetContext().op_conf_map;
  656. if (propertiesMap.empty()) {
  657. ErrorManager::GetInstance().ATCReportErrMessage("E10003", {"parameter", "value", "reason"},
  658. {"op_name_map", op_conf, "the file content is empty"});
  659. GELOGE(PARAM_INVALID, "op_name_map file content is empty, please check file!");
  660. return PARAM_INVALID;
  661. }
  662. for (auto iter = propertiesMap.begin(); iter != propertiesMap.end(); iter++) {
  663. GE_IF_BOOL_EXEC(graphNodeTypes.find(iter->second) == graphNodeTypes.end(),
  664. ErrorManager::GetInstance().ATCReportErrMessage(
  665. "E10003", {"parameter", "value", "reason"},
  666. {"op_name_map", op_conf, "type[" + iter->second + "] is not found in model"});
  667. GELOGE(PARAM_INVALID, "Invalid parameter for op_name_map."); return PARAM_INVALID;);
  668. }
  669. return SUCCESS;
  670. }
  671. FMK_FUNC_HOST_VISIBILITY Status ParseGraph(ge::Graph &graph, const std::map<string, string> &atc_params,
  672. const char *model_file, const char *weights_file, domi::FrameworkType type,
  673. const char *op_conf, const char *target, RunMode run_mode,
  674. bool is_dynamic_input) {
  675. GE_CHECK_NOTNULL(model_file);
  676. GE_CHECK_NOTNULL(weights_file);
  677. domi::GetContext().type = type;
  678. domi::GetContext().run_mode = run_mode;
  679. // Prevent data residue in multiple calls
  680. PreChecker::Instance().Clear();
  681. Params::Instance()->SetTarget(target);
  682. // Create an empty computegraph
  683. std::string om_name;
  684. ParseAtcParms(atc_params, "output", om_name);
  685. ModelHelper model_helper;
  686. string graph_name = "";
  687. Status name_ret = model_helper.GetBaseNameFromFileName(om_name, graph_name);
  688. if (name_ret != SUCCESS) {
  689. graph_name = kGraphDefaultName + "_" + CurrentTimeInStr();
  690. }
  691. ComputeGraphPtr compute_graph = MakeShared<ComputeGraph>(graph_name);
  692. GE_CHECK_NOTNULL(compute_graph);
  693. graph = GraphUtils::CreateGraphFromComputeGraph(compute_graph);
  694. // initialize omgContext
  695. std::string input_shape;
  696. ParseAtcParms(atc_params, "input_shape", input_shape);
  697. std::string input_format;
  698. ParseAtcParms(atc_params, "input_format", input_format);
  699. GE_RETURN_WITH_LOG_IF_ERROR(InitDomiOmgContext(input_shape, input_format, "", is_dynamic_input),
  700. "ATC Generate call InitDomiOmgContext ret fail");
  701. std::string is_output_adjust_hw_layout;
  702. ParseAtcParms(atc_params, "is_output_adjust_hw_layout", is_output_adjust_hw_layout);
  703. GE_RETURN_WITH_LOG_IF_ERROR(ParseOutputFp16NodesFormat(is_output_adjust_hw_layout), "Parse is_output_fp16 failed");
  704. std::string out_nodes;
  705. ParseAtcParms(atc_params, "out_nodes", out_nodes);
  706. GE_RETURN_WITH_LOG_IF_ERROR(ParseOutNodes(out_nodes), "ATC Generate parse out nodes fail");
  707. std::string output_type;
  708. ParseAtcParms(atc_params, "output_type", output_type);
  709. // parse configuration item
  710. if (op_conf != nullptr && *op_conf != '\0') {
  711. // divided by ":"
  712. PropertiesManager::Instance().SetPropertyDelimiter(OP_CONF_DELIMITER);
  713. // Parsing the op_conf configuration item file
  714. GE_IF_BOOL_EXEC(!PropertiesManager::Instance().Init(op_conf),
  715. ErrorManager::GetInstance().ATCReportErrMessage("E10003", {"parameter", "value", "reason"},
  716. {"op_name_map", op_conf, "file content error"});
  717. GELOGE(FAILED, "op_name_map init failed!"); return FAILED);
  718. // Return map and put it into ATC global variable
  719. domi::GetContext().op_conf_map = PropertiesManager::Instance().GetPropertyMap();
  720. }
  721. // parse network model
  722. auto model_parser = ModelParserFactory::Instance()->CreateModelParser(type);
  723. GE_CHK_BOOL_RET_STATUS(model_parser != nullptr, FAILED, "ATC create model parser ret fail, type:%d.", type);
  724. UpdateParserCtxWithOmgCtx();
  725. Status ret = model_parser->Parse(model_file, graph);
  726. UpdateOmgCtxWithParserCtx();
  727. // Generate the report in case of pre inspection failure or only pre inspection mode
  728. if (PreChecker::Instance().HasError() || run_mode == ONLY_PRE_CHECK) {
  729. std::string check_report;
  730. ParseAtcParms(atc_params, "check_report", check_report);
  731. GE_RETURN_WITH_LOG_IF_ERROR(PreChecker::Instance().Save(check_report), "Generate pre-checking report failed.");
  732. GEEVENT("The pre-checking report has been saved to %s.", check_report.c_str());
  733. }
  734. GE_CHK_BOOL_RET_STATUS(ret == SUCCESS, ret, "ATC model parse ret fail.");
  735. std::string input_fp16_nodes;
  736. ParseAtcParms(atc_params, "input_fp16_nodes", input_fp16_nodes);
  737. std::string is_input_adjust_hw_layout;
  738. ParseAtcParms(atc_params, "is_input_adjust_hw_layout", is_input_adjust_hw_layout);
  739. compute_graph = GraphUtils::GetComputeGraph(graph);
  740. GE_RETURN_IF_ERROR(CheckInputFp16Nodes(compute_graph, input_fp16_nodes, is_input_adjust_hw_layout));
  741. GE_RETURN_IF_ERROR(CheckInputShapeNode(compute_graph, is_dynamic_input));
  742. std::string compress_weight_conf;
  743. ParseAtcParms(atc_params, "compress_weight_conf", compress_weight_conf);
  744. GE_RETURN_IF_ERROR(SetWeightCompressNodes(compute_graph, compress_weight_conf));
  745. // Verify the contents of the op_name_map
  746. if (op_conf != nullptr && *op_conf != '\0') {
  747. GE_RETURN_WITH_LOG_IF_ERROR(CheckOpNameMap(compute_graph, op_conf),
  748. "op_name_map parameter is not fit with input net!");
  749. }
  750. // Print parse network structure
  751. compute_graph->Dump();
  752. // parse weight
  753. graph = GraphUtils::CreateGraphFromComputeGraph(compute_graph);
  754. auto weights_parser = WeightsParserFactory::Instance()->CreateWeightsParser(type);
  755. ret = weights_parser->Parse(weights_file, graph);
  756. // IN ONLY_PRE_CHECK mode, generate pre inspection report only.
  757. if (PreChecker::Instance().HasError() || run_mode == ONLY_PRE_CHECK) {
  758. std::string check_report;
  759. ParseAtcParms(atc_params, "check_report", check_report);
  760. GE_RETURN_WITH_LOG_IF_ERROR(PreChecker::Instance().Save(check_report), "Generate pre-checking report failed.");
  761. GEEVENT("The pre-checking report has been saved to %s.", check_report.c_str());
  762. }
  763. // Prevent data residue in multiple calls
  764. PreChecker::Instance().Clear();
  765. GE_CHK_BOOL_RET_STATUS(ret == SUCCESS, ret, "ATC weights parse ret fail.");
  766. GELOGI("ATC parser success.");
  767. return SUCCESS;
  768. }
  769. void GetGroupName(ge::proto::ModelDef &model_def) {
  770. auto modelAttrMap = model_def.mutable_attr();
  771. auto fusionModelOpListIter = modelAttrMap->find(MODEL_ATTR_FUSION_MODEL_DEF);
  772. GE_IF_BOOL_EXEC(
  773. fusionModelOpListIter != modelAttrMap->end(), int fusionOpIndex = 0;
  774. for (int i = 0; i < model_def.graph_size(); i++) {
  775. auto graph = model_def.mutable_graph(i);
  776. for (int j = 0; j < graph->op_size(); j++) {
  777. int64_t scope_id = 0;
  778. auto bt = fusionModelOpListIter->second.list().bt(fusionOpIndex++);
  779. ge::proto::OpDef fusion_op_def;
  780. GE_CHK_BOOL_EXEC(bt.size() != 0, GELOGW("Invalid bt size"); return;);
  781. (void)(fusion_op_def.ParseFromArray(bt.data(), bt.size()));
  782. auto fusion_attr_map = fusion_op_def.mutable_attr();
  783. auto fusion_iter = fusion_attr_map->find(kScopeIdAttr);
  784. GE_IF_BOOL_EXEC(fusion_iter == fusion_attr_map->end(), continue;);
  785. scope_id = fusion_iter->second.i();
  786. ge::proto::OpDef *opdef = graph->mutable_op(j);
  787. auto attr_map = opdef->mutable_attr();
  788. int64_t stream_id = opdef->stream_id();
  789. uint16_t l1_id = (((uint64_t)scope_id & 0xFFFF0000)) >> 16;
  790. GE_IF_BOOL_EXEC(l1_id != 0, ostringstream groupName; groupName << "group_op_l1_" << l1_id << "_" << stream_id;
  791. (*attr_map)["group_op_name"].set_s(groupName.str()); continue;);
  792. uint16_t ub_id = ((uint64_t)scope_id & 0xFFFF);
  793. GE_IF_BOOL_EXEC(ub_id != 0, ostringstream groupName; groupName << "group_op_ub_" << ub_id << "_" << stream_id;
  794. (*attr_map)["group_op_name"].set_s(groupName.str()););
  795. }
  796. });
  797. }
  798. FMK_FUNC_HOST_VISIBILITY void PrintModelInfo(ge::proto::ModelDef *model_def) {
  799. std::cout << "============ Display Model Info start ============" << std::endl;
  800. auto model_attr_map = model_def->mutable_attr();
  801. // system info
  802. auto iter = model_attr_map->find(ATTR_MODEL_ATC_VERSION);
  803. auto atc_version = (iter != model_attr_map->end()) ? iter->second.s() : "";
  804. iter = model_attr_map->find("soc_version");
  805. auto soc_version = (iter != model_attr_map->end()) ? iter->second.s() : "";
  806. iter = model_attr_map->find("framework_type");
  807. auto framework_type = (iter != model_attr_map->end()) ? iter->second.s() : "";
  808. std::cout << "system info: "
  809. << ATTR_MODEL_ATC_VERSION
  810. << "[" << atc_version << "], "
  811. << "soc_version"
  812. << "[" << soc_version << "], "
  813. << "framework_type"
  814. << "[" << framework_type << "]." << std::endl;
  815. // resource info
  816. iter = model_attr_map->find(ATTR_MODEL_MEMORY_SIZE);
  817. auto memory_size = (iter != model_attr_map->end()) ? iter->second.i() : -1;
  818. iter = model_attr_map->find(ATTR_MODEL_WEIGHT_SIZE);
  819. auto weight_size = (iter != model_attr_map->end()) ? iter->second.i() : -1;
  820. iter = model_attr_map->find(ATTR_MODEL_STREAM_NUM);
  821. auto stream_num = (iter != model_attr_map->end()) ? iter->second.i() : -1;
  822. iter = model_attr_map->find(ATTR_MODEL_EVENT_NUM);
  823. auto event_num = (iter != model_attr_map->end()) ? iter->second.i() : -1;
  824. std::cout << "resource info: "
  825. << ATTR_MODEL_MEMORY_SIZE
  826. << "[" << memory_size << " B], "
  827. << ATTR_MODEL_WEIGHT_SIZE
  828. << "[" << weight_size << " B], "
  829. << ATTR_MODEL_STREAM_NUM
  830. << "[" << stream_num << "], "
  831. << ATTR_MODEL_EVENT_NUM
  832. << "[" << event_num << "]."
  833. << std::endl;
  834. // om info
  835. iter = model_attr_map->find("om_info_list");
  836. if (iter == model_attr_map->end()) {
  837. std::cout << "Display Model Info failed, attr \"om_info_list\" is not found in om, check the version is matched."
  838. << std::endl;
  839. std::cout << "============ Display Model Info end ============" << std::endl;
  840. return;
  841. }
  842. auto list_size = iter->second.list().i_size();
  843. if (list_size == kOmInfoSize) {
  844. std::cout << "om info: "
  845. << "modeldef_size"
  846. << "[" << iter->second.list().i(0) << " B], "
  847. << "weight_data_size"
  848. << "[" << iter->second.list().i(1) << " B], "
  849. << "tbe_kernels_size"
  850. << "[" << iter->second.list().i(2) << " B], "
  851. << "cust_aicpu_kernel_store_size"
  852. << "[" << iter->second.list().i(3) << " B], "
  853. << "task_info_size"
  854. << "[" << iter->second.list().i(4) << " B]." << std::endl;
  855. } else {
  856. std::cout << "Display Model Info error, please check!" << std::endl;
  857. };
  858. std::cout << "============ Display Model Info end ============" << std::endl;
  859. }
  860. FMK_FUNC_HOST_VISIBILITY Status ConvertOm(const char *model_file, const char *json_file, bool is_covert_to_json) {
  861. GE_CHECK_NOTNULL(model_file);
  862. if (is_covert_to_json) {
  863. GE_CHECK_NOTNULL(json_file);
  864. }
  865. ge::ModelData model;
  866. // Mode 2 does not need to verify the priority, and a default value of 0 is passed
  867. int32_t priority = 0;
  868. // Load model from file
  869. Status ret = ModelParserBase::LoadFromFile(model_file, "", priority, model);
  870. if (ret != SUCCESS) {
  871. GELOGE(ret, "LoadFromFile failed.");
  872. return ret;
  873. }
  874. uint8_t *model_data = nullptr;
  875. uint32_t model_len = 0;
  876. // Parse the contents of the file to get the modeldef object
  877. ret = ModelParserBase::ParseModelContent(model, model_data, model_len);
  878. if (ret == SUCCESS) {
  879. OmFileLoadHelper omFileLoadHelper;
  880. ge::graphStatus status = omFileLoadHelper.Init(model_data, model_len);
  881. if (status != ge::GRAPH_SUCCESS) {
  882. GELOGE(ge::FAILED, "Om file init failed.");
  883. if (model.model_data != nullptr) {
  884. delete[](char *) model.model_data;
  885. model.model_data = nullptr;
  886. }
  887. return status;
  888. }
  889. ModelPartition ir_part;
  890. status = omFileLoadHelper.GetModelPartition(MODEL_DEF, ir_part);
  891. if (status != ge::GRAPH_SUCCESS) {
  892. GELOGE(ge::FAILED, "Get model part failed.");
  893. if (model.model_data != nullptr) {
  894. delete[](char *) model.model_data;
  895. model.model_data = nullptr;
  896. }
  897. return status;
  898. }
  899. ge::proto::ModelDef model_def;
  900. // De serialization
  901. bool flag = ReadProtoFromArray(ir_part.data, ir_part.size, &model_def);
  902. if (flag) {
  903. if (is_covert_to_json) {
  904. GetGroupName(model_def);
  905. json j;
  906. Pb2Json::Message2Json(model_def, kOmBlackFields, j, true);
  907. ret = ModelSaver::SaveJsonToFile(json_file, j);
  908. } else {
  909. PrintModelInfo(&model_def);
  910. }
  911. } else {
  912. ret = INTERNAL_ERROR;
  913. GELOGE(ret, "ReadProtoFromArray failed.");
  914. }
  915. } else {
  916. GELOGE(PARAM_INVALID, "ParseModelContent failed because of invalid om file. Please check --om param.");
  917. }
  918. if (model.model_data != nullptr) {
  919. delete[](char *) model.model_data;
  920. model.model_data = nullptr;
  921. }
  922. return ret;
  923. }
  924. FMK_FUNC_HOST_VISIBILITY Status ConvertPbtxtToJson(const char *model_file, const char *json_file) {
  925. ge::ModelData model;
  926. // Mode 2 does not need to verify the priority, and a default value of 0 is passed
  927. int32_t priority = 0;
  928. // Load model from file
  929. Status ret = ModelParserBase::LoadFromFile(model_file, "", priority, model);
  930. auto free_model_data = [](void **ptr) -> void {
  931. if (ptr != nullptr && *ptr != nullptr) {
  932. delete[] reinterpret_cast<char *>(*ptr);
  933. *ptr = nullptr;
  934. }
  935. };
  936. if (ret != SUCCESS) {
  937. free_model_data(&model.model_data);
  938. GELOGE(ret, "LoadFromFile failed.");
  939. return ret;
  940. }
  941. bool flag = false;
  942. ge::proto::ModelDef model_def;
  943. try {
  944. flag = google::protobuf::TextFormat::ParseFromString(reinterpret_cast<char *>(model.model_data), &model_def);
  945. } catch (google::protobuf::FatalException &e) {
  946. free_model_data(&model.model_data);
  947. GELOGE(FAILED, "ParseFromString fail. exception message : %s", e.what());
  948. return FAILED;
  949. }
  950. if (!flag) {
  951. free_model_data(&model.model_data);
  952. GELOGE(FAILED, "ParseFromString fail.");
  953. return FAILED;
  954. }
  955. GetGroupName(model_def);
  956. json j;
  957. Pb2Json::Message2Json(model_def, kOmBlackFields, j, true);
  958. ret = ModelSaver::SaveJsonToFile(json_file, j);
  959. if (ret != SUCCESS) {
  960. free_model_data(&model.model_data);
  961. GELOGE(ret, "Save json to file fail.");
  962. return ret;
  963. }
  964. free_model_data(&model.model_data);
  965. return SUCCESS;
  966. }
  967. FMK_FUNC_HOST_VISIBILITY Status ConvertFwkModelToJson(const domi::FrameworkType framework, const char *model_file,
  968. const char *json_file) {
  969. if (framework == domi::CAFFE || framework == domi::TENSORFLOW || framework == domi::ONNX) {
  970. auto model_parser = ModelParserFactory::Instance()->CreateModelParser(framework);
  971. GE_CHK_BOOL_RET_STATUS(model_parser != nullptr, FAILED, "ATC create model parser ret fail, framework:%d.",
  972. framework);
  973. return model_parser->ToJson(model_file, json_file);
  974. }
  975. ErrorManager::GetInstance().ATCReportErrMessage(
  976. "E10001", {"parameter", "value", "reason"},
  977. {"--framework", std::to_string(framework), "only support 0(Caffe) 3(TensorFlow)"});
  978. GELOGE(PARAM_INVALID, "Input parameter[--framework] is mandatory and it's value must be: 0(Caffe) 3(TensorFlow).");
  979. return PARAM_INVALID;
  980. }
  981. FMK_FUNC_HOST_VISIBILITY Status DumpInfershapeJson(const ge::Graph &graph, const char *json_file) {
  982. // Create buffer
  983. GELOGI("Enter to dump infershape json schedule.");
  984. ge::Model model("", "");
  985. model.SetGraph(graph);
  986. Buffer buffer;
  987. model.Save(buffer, true);
  988. ge::proto::ModelDef ge_proto;
  989. if (buffer.GetData() != nullptr) {
  990. std::string str(reinterpret_cast<const char *>(buffer.GetData()), buffer.GetSize());
  991. if (!ge_proto.ParseFromString(str)) {
  992. GELOGE(GRAPH_FAILED, "parse from string failed.");
  993. return FAILED;
  994. }
  995. nlohmann::json j;
  996. Pb2Json::Message2Json(ge_proto, std::set<string>(), j);
  997. ModelSaver::SaveJsonToFile(json_file, j);
  998. }
  999. return SUCCESS;
  1000. }
  1001. void UpdateOmgCtxWithParserCtx() {
  1002. domi::GetContext().format = GetParserContext().format;
  1003. domi::GetContext().input_dims = GetParserContext().input_dims;
  1004. return;
  1005. }
  1006. void UpdateParserCtxWithOmgCtx() {
  1007. GetParserContext().format = domi::GetContext().format;
  1008. GetParserContext().input_dims = domi::GetContext().input_dims;
  1009. GetParserContext().run_mode = domi::GetContext().run_mode;
  1010. return;
  1011. }
  1012. } // namespace ge

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