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.

ge_ir_build.cc 32 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  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 "external/ge/ge_ir_build.h"
  17. #include <vector>
  18. #include "common/auth/file_saver.h"
  19. #include "external/register/register_types.h"
  20. #include "framework/common/debug/ge_log.h"
  21. #include "framework/common/ge_inner_error_codes.h"
  22. #include "framework/common/string_util.h"
  23. #include "framework/common/types.h"
  24. #include "framework/common/util.h"
  25. #include "framework/omg/omg_inner_types.h"
  26. #include "framework/omg/omg_inner_types.h"
  27. #include "ge/ge_api_types.h"
  28. #include "generator/ge_generator.h"
  29. #include "graph/compute_graph.h"
  30. #include "graph/ge_tensor.h"
  31. #include "graph/utils/type_utils.h"
  32. #include "graph/ge_global_options.h"
  33. #include "init/gelib.h"
  34. #include "ir_build/atc_ir_common.h"
  35. #include "model/ge_model.h"
  36. #include "graph/shape_refiner.h"
  37. #include "graph/opsproto_manager.h"
  38. using std::string;
  39. using namespace std;
  40. namespace ge {
  41. namespace {
  42. const std::string IR_OPTION_TARGET = "target";
  43. const std::string IR_OPTION_MODE = "mode";
  44. const std::string IR_OP_CONF_DELIMITER = ":";
  45. const std::string IR_OPTION_LOG_LEVEL_DEFAULT = "default";
  46. const std::string IR_OPTION_BUFFER_OPTIMIZE_DEFAULT = "l2_optimize";
  47. const std::string IR_OPTION_DISABLE_REUSE_MEMORY_DEFAULT = "0";
  48. const std::string IR_OPTION_ENABLE_COMPRESS_WEIGHT_DEFAULT = "false";
  49. const std::string kInputShape = "input_shape";
  50. const std::string kInputFormat = "input_format";
  51. } // namespace
  52. static graphStatus CheckGlobalOptions(std::map<std::string, std::string> &global_options) {
  53. // check param disable_reuse_memory
  54. std::string disable_reuse_memory = global_options.find(ge::ir_option::EXEC_DISABLE_REUSED_MEMORY) ==
  55. global_options.end()
  56. ? IR_OPTION_DISABLE_REUSE_MEMORY_DEFAULT
  57. : global_options[ge::ir_option::EXEC_DISABLE_REUSED_MEMORY];
  58. GE_CHK_BOOL_EXEC(ge::CheckDisableReuseMemoryParamValid(disable_reuse_memory) == ge::SUCCESS,
  59. return ge::GRAPH_PARAM_INVALID, "check disable_reuse_memory failed!");
  60. global_options[ge::ir_option::EXEC_DISABLE_REUSED_MEMORY] = disable_reuse_memory;
  61. // check buffer_optimize
  62. std::string buffer_optimize = global_options.find(ge::ir_option::BUFFER_OPTIMIZE) == global_options.end()
  63. ? IR_OPTION_BUFFER_OPTIMIZE_DEFAULT
  64. : global_options[ge::ir_option::BUFFER_OPTIMIZE];
  65. GE_CHK_BOOL_EXEC(ge::CheckBufferOptimizeParamValid(buffer_optimize) == ge::SUCCESS,
  66. return ge::GRAPH_PARAM_INVALID, "check buffer optimize failed!");
  67. global_options[ge::ir_option::BUFFER_OPTIMIZE] = buffer_optimize;
  68. // check enable_single_stream
  69. std::string enable_single_stream = global_options.find(ge::ir_option::ENABLE_SINGLE_STREAM) == global_options.end()
  70. ? ""
  71. : global_options[ge::ir_option::ENABLE_SINGLE_STREAM];
  72. GE_CHK_BOOL_EXEC(ge::CheckEnableSingleStreamParamValid(enable_single_stream) == ge::SUCCESS,
  73. return ge::GRAPH_PARAM_INVALID, "check enable single stream failed!");
  74. // check compress_weight
  75. std::string enable_compress_weight = global_options.find(ge::ir_option::ENABLE_COMPRESS_WEIGHT) ==
  76. global_options.end()
  77. ? IR_OPTION_ENABLE_COMPRESS_WEIGHT_DEFAULT
  78. : global_options[ge::ir_option::ENABLE_COMPRESS_WEIGHT];
  79. std::string compress_weight_conf = global_options.find(ge::ir_option::COMPRESS_WEIGHT_CONF) == global_options.end()
  80. ? ""
  81. : global_options[ge::ir_option::COMPRESS_WEIGHT_CONF];
  82. GE_CHK_BOOL_EXEC(ge::CheckCompressWeightParamValid(enable_compress_weight, compress_weight_conf) == ge::SUCCESS,
  83. return ge::GRAPH_PARAM_INVALID, "check compress weight failed!");
  84. global_options[ge::ir_option::ENABLE_COMPRESS_WEIGHT] = (enable_compress_weight == "true") ?
  85. ge::kEnableCompressWeightTrue :
  86. ge::kEnableCompressWeightFalse;
  87. // check optypelist_for_implmode and op_select_implmode
  88. std::string optypelist_for_implmode = global_options.find(ge::ir_option::OPTYPELIST_FOR_IMPLMODE) ==
  89. global_options.end()
  90. ? ""
  91. : global_options[ge::ir_option::OPTYPELIST_FOR_IMPLMODE];
  92. std::string op_select_implmode = global_options.find(ge::ir_option::OP_SELECT_IMPL_MODE) ==
  93. global_options.end()
  94. ? ""
  95. : global_options[ge::ir_option::OP_SELECT_IMPL_MODE];
  96. GE_CHK_BOOL_EXEC(
  97. ge::CheckImplmodeParamValid(optypelist_for_implmode, op_select_implmode) == ge::SUCCESS,
  98. return ge::GRAPH_PARAM_INVALID, "check optypelist_for_implmode and op_select_implmode failed!");
  99. global_options[ge::ir_option::OP_SELECT_IMPL_MODE] = op_select_implmode;
  100. // set precision mode default value
  101. std::string precision_mode = global_options.find(ge::ir_option::PRECISION_MODE) ==
  102. global_options.end()
  103. ? "force_fp16"
  104. : global_options[ge::ir_option::PRECISION_MODE];
  105. global_options[ge::ir_option::PRECISION_MODE] = precision_mode;
  106. return GRAPH_SUCCESS;
  107. }
  108. static void GetOpsProtoPath(string &opsproto_path) {
  109. GELOGI("Start to get ops proto path schedule.");
  110. const char *path_env = std::getenv("ASCEND_OPP_PATH");
  111. if (path_env != nullptr) {
  112. string path = path_env;
  113. string file_path = RealPath(path.c_str());
  114. if (file_path.empty()) {
  115. GELOGE(FAILED, "File path %s is invalid.", path.c_str());
  116. return;
  117. }
  118. opsproto_path = (path + "/op_proto/custom/" + ":") + (path + "/op_proto/built-in/");
  119. GELOGI("Get opsproto so path from env : %s", path.c_str());
  120. return;
  121. }
  122. string path_base = PluginManager::GetPath();
  123. GELOGI("path_base is %s", path_base.c_str());
  124. path_base = path_base.substr(0, path_base.rfind('/'));
  125. path_base = path_base.substr(0, path_base.rfind('/') + 1);
  126. opsproto_path = (path_base + "ops/op_proto/custom/" + ":") + (path_base + "ops/op_proto/built-in/");
  127. }
  128. static void LoadOpsProto() {
  129. string opsproto_path;
  130. GetOpsProtoPath(opsproto_path);
  131. GELOGI("Get opsproto path is %s", opsproto_path.c_str());
  132. OpsProtoManager *manager = OpsProtoManager::Instance();
  133. map<string, string> option_tmp;
  134. option_tmp.emplace(std::pair<string, string>(string("ge.opsProtoLibPath"), opsproto_path));
  135. (void)manager->Initialize(option_tmp);
  136. }
  137. graphStatus aclgrphBuildInitializeImpl(std::map<std::string, std::string> &global_options) {
  138. GELOGD("Enter aclgrphInitialize start!");
  139. // check global options
  140. if (CheckGlobalOptions(global_options) != GRAPH_SUCCESS) {
  141. GELOGE(GRAPH_PARAM_INVALID, "Check global options falied!");
  142. return GRAPH_PARAM_INVALID;
  143. }
  144. // print global option map
  145. ge::PrintOptionMap(global_options, "global option");
  146. LoadOpsProto();
  147. std::shared_ptr<ge::GELib> instance_ptr = ge::GELib::GetInstance();
  148. if (instance_ptr == nullptr || !instance_ptr->InitFlag()) {
  149. GELOGI("aclgrphInitialize start!");
  150. auto ret = ge::GELib::Initialize(global_options);
  151. if (ret != ge::SUCCESS) {
  152. GELOGE(ret, "GE initialize failed!");
  153. return GRAPH_FAILED;
  154. }
  155. }
  156. GELOGW("gelib has been initialized!");
  157. std::string path_base = ge::GELib::GetPath();
  158. int ret = ErrorManager::GetInstance().Init(path_base);
  159. if (ret != 0) {
  160. DOMI_LOGE("ErrorManager init fail !");
  161. return GRAPH_FAILED;
  162. }
  163. return GRAPH_SUCCESS;
  164. }
  165. graphStatus aclgrphBuildInitialize(std::map<std::string, std::string> global_options) {
  166. return aclgrphBuildInitializeImpl(global_options);
  167. }
  168. graphStatus aclgrphBuildInitialize(std::map<AscendString, AscendString> &global_options) {
  169. std::map<std::string, std::string> tmp_global_options;
  170. for (auto &option : global_options) {
  171. if (option.first.GetString() == nullptr || option.second.GetString() == nullptr) {
  172. GELOGE(GRAPH_FAILED, "AclgrphBuildInitialize option is nullptr.");
  173. return GRAPH_FAILED;
  174. }
  175. std::string key = option.first.GetString();
  176. std::string val = option.second.GetString();
  177. tmp_global_options[key] = val;
  178. }
  179. return aclgrphBuildInitializeImpl(tmp_global_options);
  180. }
  181. void aclgrphBuildFinalize() {
  182. if (ge::GELib::GetInstance() != nullptr && ge::GELib::GetInstance()->InitFlag()) {
  183. (void)ge::GELib::GetInstance()->Finalize();
  184. return;
  185. }
  186. GELOGW("[Notice] gelib has not been initialized!do nothing!");
  187. }
  188. class Impl {
  189. public:
  190. Impl() {
  191. omg_context_ = domi::GetContext();
  192. omg_context_.format = domi::DOMI_TENSOR_ND;
  193. omg_context_.input_nodes_format_map.clear();
  194. omg_context_.output_formats.clear();
  195. omg_context_.user_input_dims.clear();
  196. omg_context_.input_dims.clear();
  197. omg_context_.op_conf_map.clear();
  198. omg_context_.out_nodes_map.clear();
  199. omg_context_.user_out_nodes.clear();
  200. omg_context_.net_format = domi::DOMI_TENSOR_RESERVED;
  201. omg_context_.type = domi::FRAMEWORK_RESERVED;
  202. omg_context_.run_mode = ONLY_PRE_CHECK;
  203. omg_context_.train_flag = false;
  204. omg_context_.output_type.clear();
  205. omg_context_.is_dynamic_input = false;
  206. omg_context_.dynamic_batch_size.clear();
  207. omg_context_.dynamic_image_size.clear();
  208. omg_context_.dynamic_dims.clear();
  209. };
  210. ~Impl() { (void)generator_.Finalize(); };
  211. graphStatus CheckOptions(const std::map<std::string, std::string> &options);
  212. graphStatus CreateInputsForIRBuild(const ge::Graph &graph, vector<ge::GeTensor> &inputs);
  213. graphStatus GetDefaultInputShape(const Graph &graph, string &default_shape);
  214. graphStatus UpdateDataOpAttr(const Graph &graph);
  215. graphStatus Init(const Graph &graph, const std::map<std::string, std::string> &options);
  216. graphStatus BuildModel(const Graph &graph, const std::map<std::string, std::string> &options,
  217. ModelBufferData &ge_models);
  218. graphStatus InitDomiOmgContext(const string &input_shape, const string &input_format, const string &net_format,
  219. bool is_dynamic_input);
  220. void SetRtSocVersion();
  221. void UpdateThreadContext();
  222. void LoadOpsProto();
  223. public:
  224. ge::GeGenerator generator_;
  225. std::map<std::string, std::string> options_;
  226. bool is_dynamic_input_ = false;
  227. OmgContext omg_context_;
  228. };
  229. graphStatus Impl::UpdateDataOpAttr(const Graph &graph) {
  230. GELOGD("Enter Update Data Attr Process!");
  231. if (options_.find(kInputShape) == options_.end()) {
  232. return GRAPH_SUCCESS;
  233. }
  234. unordered_map<string, vector<int64_t>> shape_map;
  235. vector<pair<string, vector<int64_t>>> user_shape_map;
  236. GE_CHK_BOOL_EXEC(ParseInputShape(options_[kInputShape], shape_map, user_shape_map, true),
  237. return GRAPH_PARAM_INVALID, "parse input shape failed!");
  238. auto compute_graph = ge::GraphUtils::GetComputeGraph(graph);
  239. GE_CHECK_NOTNULL(compute_graph);
  240. for (ge::NodePtr &input_node : compute_graph->GetDirectNode()) {
  241. GE_CHECK_NOTNULL(input_node);
  242. ge::OpDescPtr op = input_node->GetOpDesc();
  243. GE_CHECK_NOTNULL(op);
  244. if (op->GetType() == DATA) {
  245. auto tensor_input = op->MutableInputDesc(0);
  246. auto tensor_output = op->MutableOutputDesc(0);
  247. GE_CHECK_NOTNULL(tensor_input);
  248. GE_CHECK_NOTNULL(tensor_output);
  249. string data_op_name = op->GetName();
  250. auto iter = shape_map.find(data_op_name);
  251. if (iter != shape_map.end()) {
  252. tensor_input->SetShape(ge::GeShape(iter->second));
  253. tensor_output->SetShape(ge::GeShape(iter->second));
  254. GELOGD("update input [%s] shape info", data_op_name.c_str());
  255. } else {
  256. GELOGI("no need update input [%s] attr because not found from input_shape.", data_op_name.c_str());
  257. }
  258. }
  259. }
  260. return GRAPH_SUCCESS;
  261. }
  262. graphStatus Impl::CheckOptions(const std::map<std::string, std::string> &options) {
  263. for (auto &ele : options) {
  264. auto it = ge::ir_option::ir_builder_suppported_options.find(ele.first);
  265. if (it == ge::ir_option::ir_builder_suppported_options.end()) {
  266. auto it_lx_fusion = ir_builder_supported_options_for_lx_fusion.find(ele.first);
  267. if (it_lx_fusion == ir_builder_supported_options_for_lx_fusion.end()) {
  268. GELOGE(GRAPH_PARAM_INVALID, "input options include unsupported option(%s).Please check!",
  269. ele.first.c_str());
  270. return GRAPH_PARAM_INVALID;
  271. }
  272. }
  273. options_.insert(ele);
  274. }
  275. // Check options build_mode and build_step.
  276. std::string build_mode;
  277. auto it = options_.find(BUILD_MODE);
  278. if (it != options_.end() && !(it->second.empty())) {
  279. if (build_mode_options.find(it->second) == build_mode_options.end()) {
  280. GELOGE(GRAPH_PARAM_INVALID, "Build mode:%s is unsupported. Please check!", it->second.c_str());
  281. return GRAPH_PARAM_INVALID;
  282. }
  283. build_mode = it->second;
  284. }
  285. it = options_.find(BUILD_STEP);
  286. if (it != options_.end() && !(it->second.empty())) {
  287. if (build_step_options.find(it->second) == build_step_options.end()) {
  288. GELOGE(GRAPH_PARAM_INVALID, "Build step:%s is unsupported. Please check!", it->second.c_str());
  289. return GRAPH_PARAM_INVALID;
  290. }
  291. } else {
  292. if (build_mode == BUILD_MODE_TUNING) {
  293. GELOGE(GRAPH_PARAM_INVALID, "Build mode tuning must specify build step. Please check!");
  294. return GRAPH_PARAM_INVALID;
  295. }
  296. }
  297. // Check option EXEC_DISABLE_REUSED_MEMORY
  298. it = options_.find(ge::ir_option::EXEC_DISABLE_REUSED_MEMORY);
  299. if (it != options_.end() && (CheckDisableReuseMemoryParamValid(it->second) != GRAPH_SUCCESS)) {
  300. return GRAPH_PARAM_INVALID;
  301. }
  302. return GRAPH_SUCCESS;
  303. }
  304. graphStatus Impl::GetDefaultInputShape(const Graph &graph, string &default_shape) {
  305. auto compute_graph = ge::GraphUtils::GetComputeGraph(graph);
  306. GE_CHECK_NOTNULL(compute_graph);
  307. for (ge::NodePtr &input_node : compute_graph->GetDirectNode()) {
  308. GE_CHECK_NOTNULL(input_node);
  309. ge::OpDescPtr op = input_node->GetOpDesc();
  310. GE_CHECK_NOTNULL(op);
  311. if (op->GetType() == DATA) {
  312. string data_op_name = op->GetName();
  313. GELOGD("Data op name: %s, data op inputDesc size: %zu", data_op_name.c_str(), op->GetAllInputsDesc().size());
  314. ge::GeTensorDesc tensor = op->GetInputDesc(0);
  315. ge::GeShape data_shape = tensor.GetShape();
  316. GELOGD("Data op get shape from InputDesc in ge ir graph.");
  317. string tmp_shape_str;
  318. const std::vector<int64_t> &tmp_shape = data_shape.GetDims();
  319. if (tmp_shape.empty()) {
  320. GELOGW("Data op: %s has zero shape dims!", data_op_name.c_str());
  321. } else {
  322. tmp_shape_str += data_op_name + ":";
  323. for (auto tmp_dim : tmp_shape) {
  324. tmp_shape_str += to_string((long)tmp_dim) + ",";
  325. }
  326. tmp_shape_str = tmp_shape_str.substr(0, tmp_shape_str.size() - 1);
  327. tmp_shape_str += ";";
  328. default_shape += tmp_shape_str;
  329. }
  330. GELOGD("Data op name: %s, data shape: %s.", data_op_name.c_str(), tmp_shape_str.c_str());
  331. }
  332. }
  333. default_shape = (default_shape.empty() ? default_shape : default_shape.substr(0, default_shape.size() - 1));
  334. GELOGI("Get default data op shape: %s from ge ir graph.", default_shape.c_str());
  335. return GRAPH_SUCCESS;
  336. }
  337. graphStatus Impl::Init(const Graph &graph, const std::map<std::string, std::string> &options) {
  338. // 1. check options
  339. graphStatus ret = CheckOptions(options);
  340. if (ret != GRAPH_SUCCESS) {
  341. GELOGE(ret, "User input options are illegal! Please check!");
  342. return ret;
  343. }
  344. ret = UpdateDataOpAttr(graph);
  345. if (ret != GRAPH_SUCCESS) {
  346. return ret;
  347. }
  348. std::string build_mode = (options_.find(BUILD_MODE) == options_.end() || options_[BUILD_MODE] == BUILD_MODE_NORMAL)
  349. ? "" : options_[BUILD_MODE];
  350. options_[BUILD_MODE] = build_mode;
  351. // set log level
  352. std::string log = options_.find(ge::ir_option::LOG_LEVEL) == options_.end()
  353. ? IR_OPTION_LOG_LEVEL_DEFAULT
  354. : options_[ge::ir_option::LOG_LEVEL];
  355. GE_CHK_BOOL_RET_STATUS_NOLOG(ge::CheckLogParamValidAndSetLogLevel(log) == 0, GRAPH_PARAM_INVALID);
  356. options_[ge::ir_option::LOG_LEVEL] = log;
  357. string input_shape;
  358. if (options_.find("input_shape") == options_.end()) {
  359. GE_CHK_BOOL_EXEC(GetDefaultInputShape(graph, input_shape) == ge::SUCCESS,
  360. return ge::GRAPH_PARAM_INVALID, "Get default data op shape from graph failed!");
  361. } else {
  362. input_shape = options_["input_shape"];
  363. }
  364. string input_format = options_.find("input_format") == options_.end() ? "" : options_["input_format"];
  365. string net_format = options_.find("net_format") == options_.end() ? "" : options_["net_format"];
  366. string dynamic_batch_size = options_.find(ge::ir_option::DYNAMIC_BATCH_SIZE) == options_.end()
  367. ? ""
  368. : options_[ge::ir_option::DYNAMIC_BATCH_SIZE];
  369. string dynamic_image_size = options_.find(ge::ir_option::DYNAMIC_IMAGE_SIZE) == options_.end()
  370. ? ""
  371. : options_[ge::ir_option::DYNAMIC_IMAGE_SIZE];
  372. string dynamic_dims =
  373. options_.find(ge::ir_option::DYNAMIC_DIMS) == options_.end() ? "" : options_[ge::ir_option::DYNAMIC_DIMS];
  374. auto status = CheckDynamicInputParamValid(dynamic_batch_size, dynamic_image_size, dynamic_dims, input_shape,
  375. input_format, is_dynamic_input_);
  376. if (status != ge::SUCCESS) {
  377. GELOGE(GRAPH_PARAM_INVALID, "Check dynamic input size failed!");
  378. return GRAPH_PARAM_INVALID;
  379. }
  380. GELOGD("User input dynamic_batch_size:%s, dynamic_image_size:%s, dynamic_dims:%s.", dynamic_batch_size.c_str(),
  381. dynamic_image_size.c_str(), dynamic_dims.c_str());
  382. omg_context_.dynamic_batch_size = dynamic_batch_size;
  383. omg_context_.dynamic_image_size = dynamic_image_size;
  384. omg_context_.dynamic_dims = dynamic_dims;
  385. // check output_type
  386. std::string output_type = options_.find(ge::ir_option::OUTPUT_TYPE) == options_.end()
  387. ? ""
  388. : options_[ge::ir_option::OUTPUT_TYPE];
  389. GE_CHK_BOOL_EXEC(ge::CheckOutputTypeParamValid(output_type) == ge::SUCCESS,
  390. return ge::GRAPH_PARAM_INVALID, "check output type failed!");
  391. // check insert_op_conf
  392. std::string insert_op_conf = options_.find(ge::ir_option::INSERT_OP_FILE) == options_.end()
  393. ? ""
  394. : options_[ge::ir_option::INSERT_OP_FILE];
  395. GE_CHK_BOOL_EXEC(ge::CheckInsertOpConfParamValid(std::string(insert_op_conf)) == ge::SUCCESS,
  396. return ge::GRAPH_PARAM_INVALID, "check insert op conf failed!");
  397. GE_CHK_BOOL_EXEC(insert_op_conf.empty() || dynamic_dims.empty(),
  398. return ge::GRAPH_PARAM_INVALID, "dynamic dims function does not support aipp");
  399. // for IR builder.Only support om mode, so here fixed;
  400. options_.insert(std::pair<string, string>(string(IR_OPTION_MODE), to_string(0)));
  401. options_.insert(std::pair<string, string>(string(IR_OPTION_TARGET), "mini"));
  402. options_.insert(std::pair<string, string>(string(ge::RUN_FLAG), to_string(0)));
  403. options_.insert(std::pair<string, string>(string(ge::TRAIN_FLAG), to_string(0)));
  404. options_.insert(std::pair<string, string>(string(ge::SAVE_ORIGINAL_MODEL), to_string(0)));
  405. // print ge option map
  406. ge::PrintOptionMap(options_, "ge option");
  407. SetRtSocVersion();
  408. UpdateThreadContext();
  409. // 3. init generator with options_
  410. ret = generator_.Initialize(options_, omg_context_);
  411. if (ret != GRAPH_SUCCESS) {
  412. GELOGE(ret, "generator Initialize failed!");
  413. return ret;
  414. }
  415. // 4.parse and init Context with input shape format and net format info
  416. return this->InitDomiOmgContext(input_shape, input_format, net_format, is_dynamic_input_);
  417. }
  418. void Impl::SetRtSocVersion() {
  419. const auto &global_options = GetMutableGlobalOptions();
  420. auto it = global_options.find(ge::SOC_VERSION);
  421. if (it != global_options.end()) {
  422. const char *soc_version = it->second.c_str();
  423. rtError_t rt_ret = rtSetSocVersion(soc_version);
  424. if (rt_ret != RT_ERROR_NONE) {
  425. GELOGW("Set soc version %s failed. ret:0x%X", soc_version, rt_ret);
  426. }
  427. GELOGD("Set soc version %s success.", soc_version);
  428. }
  429. }
  430. void Impl::UpdateThreadContext() {
  431. GetThreadLocalContext().SetGlobalOption(GetMutableGlobalOptions());
  432. GetThreadLocalContext().SetGraphOption(options_);
  433. }
  434. graphStatus Impl::CreateInputsForIRBuild(const ge::Graph &graph, vector<ge::GeTensor> &inputs) {
  435. auto compute_graph = ge::GraphUtils::GetComputeGraph(graph);
  436. GE_CHECK_NOTNULL(compute_graph);
  437. int64_t index = 0;
  438. for (ge::NodePtr &input_node : compute_graph->GetDirectNode()) {
  439. GE_CHECK_NOTNULL(input_node);
  440. ge::OpDescPtr op = input_node->GetOpDesc();
  441. GE_CHECK_NOTNULL(op);
  442. if (op->GetType() == DATA) {
  443. (void)AttrUtils::SetInt(op, ATTR_NAME_INDEX, index++);
  444. GELOGD("Data op inputDesc size: %zu", op->GetAllInputsDesc().size());
  445. ge::GeTensorDesc tensor = op->GetInputDesc(0);
  446. string data_op_name = op->GetName();
  447. GELOGD("Data op name: %s", data_op_name.c_str());
  448. ge::GeShape data_shape;
  449. auto iter = omg_context_.input_dims.find(data_op_name);
  450. if (iter != omg_context_.input_dims.end()) {
  451. data_shape = ge::GeShape(iter->second);
  452. GELOGD("Data op get shape from Context.");
  453. } else {
  454. data_shape = tensor.GetShape();
  455. GELOGD("Data op get shape from InputDesc in ge ir graph.");
  456. }
  457. // If user point input format, do work for all data ops; else do according to tensor_desc
  458. auto data_format = omg_context_.format != domi::DOMI_TENSOR_ND ?
  459. ge::TypeUtils::DomiFormatToFormat(omg_context_.format) : tensor.GetFormat();
  460. ge::DataType data_type = tensor.GetDataType();
  461. string data_type_str = ge::TypeUtils::DataTypeToSerialString(data_type);
  462. GELOGD("Data op get data type:%s from InputDesc in ge ir graph.", data_type_str.c_str());
  463. ge::GeTensor inputTensor;
  464. ge::GeTensorDesc desc(data_shape, ge::Format(data_format), data_type);
  465. inputTensor.SetTensorDesc(desc);
  466. inputs.push_back(inputTensor);
  467. }
  468. }
  469. GELOGD("CreateInputsForIRBuild, inputs size: %zu", inputs.size());
  470. return GRAPH_SUCCESS;
  471. }
  472. graphStatus Impl::BuildModel(const Graph &graph, const std::map<std::string, std::string> &options,
  473. ModelBufferData &model) {
  474. // 1. init GeGenerator with user optios
  475. graphStatus ret = Init(graph, options);
  476. if (ret != GRAPH_SUCCESS) {
  477. GELOGE(ret, "Build ir model Init failed!");
  478. return ret;
  479. }
  480. // 2. construct input
  481. std::vector<GeTensor> inputs;
  482. if (!omg_context_.is_dynamic_input) { // if dynamic input , no need to creat inputs
  483. ret = CreateInputsForIRBuild(graph, inputs);
  484. if (ret != GRAPH_SUCCESS) {
  485. GELOGE(ret, "CreateInputsForIRBuild failed!");
  486. return ret;
  487. }
  488. }
  489. // 3. build IR model
  490. ret = generator_.GenerateOnlineModel(graph, inputs, model);
  491. if (ret != GRAPH_SUCCESS) {
  492. GELOGE(ret, "GenerateOnlineModel failed!");
  493. return ret;
  494. }
  495. return GRAPH_SUCCESS;
  496. }
  497. graphStatus Impl::InitDomiOmgContext(const string &input_shape, const string &input_format, const string &net_format,
  498. bool is_dynamic_input) {
  499. // Clear omgcontext data first
  500. omg_context_.input_dims.clear();
  501. omg_context_.user_input_dims.clear();
  502. omg_context_.is_dynamic_input = is_dynamic_input;
  503. // the default value is ND
  504. omg_context_.format = domi::DOMI_TENSOR_ND;
  505. if (!input_format.empty()) {
  506. auto iter = ge::input_format_str_to_geformat.find(input_format);
  507. if (iter != ge::input_format_str_to_geformat.end()) {
  508. omg_context_.format = iter->second;
  509. } else {
  510. GELOGE(GRAPH_PARAM_INVALID, "Input format %s not support , expect ND/NCHW/NHWC/CHWN/NC1HWC0/NHWC1C0.",
  511. input_format.c_str());
  512. return GRAPH_PARAM_INVALID;
  513. }
  514. }
  515. // Input is empty, do not process
  516. if (input_shape.empty()) {
  517. return GRAPH_SUCCESS;
  518. }
  519. if (!ParseInputShape(input_shape, omg_context_.input_dims, omg_context_.user_input_dims, is_dynamic_input)) {
  520. GELOGE(GRAPH_PARAM_INVALID, "Failed to parse input shape: %s", input_shape.c_str());
  521. return GRAPH_PARAM_INVALID;
  522. }
  523. return GRAPH_SUCCESS;
  524. }
  525. graphStatus aclgrphBuildModel(const ge::Graph &graph, const std::map<std::string, std::string> &build_options,
  526. ModelBufferData &model) {
  527. GELOGD("Enter aclmdlBuildModel process!");
  528. Impl builder;
  529. return builder.BuildModel(graph, build_options, model);
  530. }
  531. graphStatus aclgrphBuildModel(const ge::Graph &graph, const std::map<AscendString, AscendString> &build_options,
  532. ModelBufferData &model) {
  533. GELOGD("Enter aclmdlBuildModel process!");
  534. std::map<std::string, std::string> tmp_build_options;
  535. for (auto &option : build_options) {
  536. if (option.first.GetString() == nullptr || option.second.GetString() == nullptr) {
  537. GELOGE(GRAPH_FAILED, "AclgrphBuildInitialize option is nullptr.");
  538. return GRAPH_FAILED;
  539. }
  540. std::string key = option.first.GetString();
  541. std::string val = option.second.GetString();
  542. tmp_build_options[key] = val;
  543. }
  544. Impl builder;
  545. return builder.BuildModel(graph, tmp_build_options, model);
  546. }
  547. graphStatus aclgrphSaveModel(const string &output_file, const ModelBufferData &model) {
  548. GELOGD("Enter aclmdlSaveModel process!");
  549. if (model.data.get() == nullptr || model.length == 0) {
  550. GELOGE(GRAPH_PARAM_INVALID, "input model is illegal");
  551. return GRAPH_PARAM_INVALID;
  552. }
  553. return FileSaver::SaveToFile((output_file + ".om"), reinterpret_cast<void *>(model.data.get()),
  554. static_cast<uint32_t>(model.length));
  555. }
  556. graphStatus aclgrphSaveModel(const char *output_file, const ModelBufferData &model) {
  557. GELOGD("Enter aclmdlSaveModel process!");
  558. if (model.data.get() == nullptr || model.length == 0) {
  559. GELOGE(GRAPH_PARAM_INVALID, "Input model is illegal");
  560. return GRAPH_PARAM_INVALID;
  561. }
  562. if (output_file == nullptr) {
  563. GELOGE(GRAPH_PARAM_INVALID, "Output file is nullptr.");
  564. return GRAPH_PARAM_INVALID;
  565. }
  566. std::string str_output_file = output_file;
  567. return FileSaver::SaveToFile((str_output_file + ".om"), reinterpret_cast<void *>(model.data.get()),
  568. static_cast<uint32_t>(model.length));
  569. }
  570. graphStatus aclgrphGetIRVersion(int *major_version, int *minor_version, int *patch_version) {
  571. GELOGD("Enter aclgrphGetIRVersion process!");
  572. GE_CHECK_NOTNULL(major_version);
  573. GE_CHECK_NOTNULL(minor_version);
  574. GE_CHECK_NOTNULL(patch_version);
  575. *major_version = IR_MAJOR_VERSION;
  576. *minor_version = IR_MINOR_VERSION;
  577. *patch_version = IR_PATCH_VERSION;
  578. return GRAPH_SUCCESS;
  579. }
  580. graphStatus aclgrphInferShapeAndType(ge::Graph &graph) {
  581. auto compute_graph = GraphUtils::GetComputeGraph(graph);
  582. GE_CHECK_NOTNULL(compute_graph);
  583. auto root_graph = compute_graph->GetParentGraph();
  584. if (root_graph != nullptr) {
  585. GELOGE(GRAPH_PARAM_INVALID, "Input param should not be subgraph");
  586. return GRAPH_PARAM_INVALID;
  587. }
  588. auto ret = compute_graph->TopologicalSorting();
  589. if (ret != GRAPH_SUCCESS) {
  590. GELOGE(ret, "Acl topo logical sort failed.");
  591. return ret;
  592. }
  593. ret = compute_graph->InferOriginFormat();
  594. if (ret != GRAPH_SUCCESS) {
  595. GELOGE(ret, "Acl InferOriginFormat failed.");
  596. return ret;
  597. }
  598. for (auto &node: compute_graph->GetAllNodes()) {
  599. graphStatus ret = ShapeRefiner::InferShapeAndType(node);
  600. if (ret == GRAPH_PARAM_INVALID) {
  601. GELOGW("Can not find infershape func.");
  602. continue;
  603. } else if (ret != GRAPH_SUCCESS) {
  604. GELOGE(ret, "Acl infershape failed.");
  605. return ret;
  606. }
  607. }
  608. return GRAPH_SUCCESS;
  609. }
  610. graphStatus aclgrphDumpGraph(const ge::Graph &graph, const char *file, const size_t len) {
  611. GE_CHECK_NOTNULL(file);
  612. if (len > PATH_MAX || len != strlen(file) || strlen(file) == 0) {
  613. GELOGE(GRAPH_PARAM_INVALID, "File path invalid.");
  614. return GRAPH_PARAM_INVALID;
  615. }
  616. auto compute_graph = GraphUtils::GetComputeGraph(graph);
  617. GE_CHECK_NOTNULL(compute_graph);
  618. string full_path(file, len);
  619. for (size_t i = 0; i < len; i++) {
  620. if (full_path[i] == '\\') {
  621. full_path.replace(i, 1, "/");
  622. }
  623. }
  624. string suffix;
  625. string file_path;
  626. int pos = full_path.rfind("/");
  627. if (pos != -1) {
  628. suffix = full_path.substr(pos + 1, -1);
  629. file_path = full_path.substr(0, pos);
  630. } else {
  631. suffix = full_path;
  632. file_path = "./";
  633. }
  634. if (suffix.empty()) {
  635. suffix = compute_graph->GetName();
  636. if (suffix.empty()) {
  637. suffix = "graph";
  638. }
  639. }
  640. char path[PATH_MAX] = {0};
  641. if (realpath(file_path.c_str(), path) == nullptr) {
  642. GELOGE(GRAPH_PARAM_INVALID, "Dump file path:%s is invalid.", file);
  643. return GRAPH_PARAM_INVALID;
  644. }
  645. GraphUtils::DumpGEGrph(compute_graph, string(path), suffix);
  646. GraphUtils::DumpGrphToOnnx(*compute_graph, string(path), suffix);
  647. uint64_t i = 0;
  648. for (const auto &sub_graph_func : compute_graph->GetAllSubgraphs()) {
  649. auto sub_graph_func_name = suffix + std::string("_sub_graph_") + std::to_string(i++);
  650. GraphUtils::DumpGEGrph(sub_graph_func, string(path), sub_graph_func_name);
  651. GraphUtils::DumpGrphToOnnx(*sub_graph_func, string(path), sub_graph_func_name);
  652. }
  653. return GRAPH_SUCCESS;
  654. }
  655. graphStatus aclgrphGenerateForOp(const AscendString &op_type, const vector<TensorDesc> &inputs,
  656. const vector<TensorDesc> &outputs, Graph &graph) {
  657. auto op_type_str = std::string(op_type.GetString());
  658. auto op_name = op_type_str + "_" + std::to_string(ge::GetCurrentTimestamp());
  659. auto op_desc = ge::MakeShared<ge::OpDesc>(op_name, op_type_str);
  660. GE_CHECK_NOTNULL(op_desc);
  661. // convert input tensordesc to getensor
  662. std::vector<ge::GeTensor> input_tensors;
  663. for (const auto &input : inputs) {
  664. ge::GeTensorDesc tensor_desc(ge::GeShape(input.GetShape().GetDims()), input.GetFormat(), input.GetDataType());
  665. tensor_desc.SetOriginFormat(input.GetFormat());
  666. ge::TensorUtils::SetRealDimCnt(tensor_desc, static_cast<uint32_t>(input.GetShape().GetDims().size()));
  667. ge::TensorUtils::SetInputTensor(tensor_desc, true);
  668. ge::TensorUtils::SetOutputTensor(tensor_desc, false);
  669. if (op_desc->AddInputDesc(tensor_desc) != ge::GRAPH_SUCCESS) {
  670. GELOGE(ge::FAILED, "AddInputDesc fail.");
  671. return ge::FAILED;
  672. }
  673. input_tensors.emplace_back(tensor_desc);
  674. }
  675. // convert output tensordesc to getensor
  676. std::vector<ge::GeTensor> output_tensors;
  677. for (const auto &output : outputs) {
  678. ge::GeTensorDesc tensor_desc(ge::GeShape(output.GetShape().GetDims()), output.GetFormat(), output.GetDataType());
  679. tensor_desc.SetOriginFormat(output.GetFormat());
  680. ge::TensorUtils::SetRealDimCnt(tensor_desc, static_cast<uint32_t>(output.GetShape().GetDims().size()));
  681. ge::TensorUtils::SetInputTensor(tensor_desc, false);
  682. ge::TensorUtils::SetOutputTensor(tensor_desc, true);
  683. (void)op_desc->AddOutputDesc(tensor_desc);
  684. output_tensors.emplace_back(tensor_desc);
  685. }
  686. // call api to get graph
  687. ge::GeGenerator generator;
  688. std::string graph_name = ge::CurrentTimeInStr() + "_graph";
  689. if (generator.BuildSingleOpGraph(op_desc, input_tensors, output_tensors, graph_name, graph) != ge::SUCCESS) {
  690. GELOGE(GRAPH_FAILED, "make graph fail.");
  691. return GRAPH_FAILED;
  692. }
  693. return GRAPH_SUCCESS;
  694. }
  695. } // namespace ge

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