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.

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

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