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

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

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