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

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

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