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

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