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

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

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