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 24 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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 "common/ge/tbe_plugin_manager.h"
  20. #include "external/register/register_types.h"
  21. #include "framework/common/debug/ge_log.h"
  22. #include "framework/common/ge_inner_error_codes.h"
  23. #include "framework/common/string_util.h"
  24. #include "framework/common/types.h"
  25. #include "framework/common/util.h"
  26. #include "framework/omg/omg_inner_types.h"
  27. #include "framework/omg/omg_inner_types.h"
  28. #include "ge/ge_api_types.h"
  29. #include "generator/ge_generator.h"
  30. #include "graph/compute_graph.h"
  31. #include "graph/ge_tensor.h"
  32. #include "graph/utils/type_utils.h"
  33. #include "graph/ge_global_options.h"
  34. #include "init/gelib.h"
  35. #include "ir_build/atc_ir_common.h"
  36. #include "model/ge_model.h"
  37. #include "graph/shape_refiner.h"
  38. #include "graph/opsproto_manager.h"
  39. using std::string;
  40. using namespace std;
  41. namespace ge {
  42. namespace {
  43. const std::string IR_OPTION_TARGET = "target";
  44. const std::string IR_OPTION_MODE = "mode";
  45. const std::string IR_OP_CONF_DELIMITER = ":";
  46. const std::string IR_OPTION_LOG_LEVEL_DEFAULT = "default";
  47. const std::string IR_OPTION_BUFFER_OPTIMIZE_DEFAULT = "l2_optimize";
  48. const std::string IR_OPTION_DISABLE_REUSE_MEMORY_DEFAULT = "0";
  49. const std::string IR_OPTION_ENABLE_COMPRESS_WEIGHT_DEFAULT = "false";
  50. } // namespace
  51. static graphStatus CheckGlobalOptions(std::map<std::string, std::string> &global_options) {
  52. // check param disable_reuse_memory
  53. std::string disable_reuse_memory = global_options.find(ge::ir_option::EXEC_DISABLE_REUSED_MEMORY) ==
  54. global_options.end()
  55. ? IR_OPTION_DISABLE_REUSE_MEMORY_DEFAULT
  56. : global_options[ge::ir_option::EXEC_DISABLE_REUSED_MEMORY];
  57. GE_CHK_BOOL_EXEC(ge::CheckDisableReuseMemoryParamValid(disable_reuse_memory) == ge::SUCCESS,
  58. return ge::GRAPH_PARAM_INVALID, "check disable_reuse_memory failed!");
  59. global_options[ge::ir_option::EXEC_DISABLE_REUSED_MEMORY] = disable_reuse_memory;
  60. // check buffer_optimize
  61. std::string buffer_optimize = global_options.find(ge::ir_option::BUFFER_OPTIMIZE) == global_options.end()
  62. ? IR_OPTION_BUFFER_OPTIMIZE_DEFAULT
  63. : global_options[ge::ir_option::BUFFER_OPTIMIZE];
  64. GE_CHK_BOOL_EXEC(ge::CheckBufferOptimizeParamValid(buffer_optimize) == ge::SUCCESS,
  65. return ge::GRAPH_PARAM_INVALID, "check buffer optimize failed!");
  66. global_options[ge::ir_option::BUFFER_OPTIMIZE] = buffer_optimize;
  67. // check enable_single_stream
  68. std::string enable_single_stream = global_options.find(ge::ir_option::ENABLE_SINGLE_STREAM) == global_options.end()
  69. ? ""
  70. : global_options[ge::ir_option::ENABLE_SINGLE_STREAM];
  71. GE_CHK_BOOL_EXEC(ge::CheckEnableSingleStreamParamValid(enable_single_stream) == ge::SUCCESS,
  72. return ge::GRAPH_PARAM_INVALID, "check enable single stream failed!");
  73. // check compress_weight
  74. std::string enable_compress_weight = global_options.find(ge::ir_option::ENABLE_COMPRESS_WEIGHT) ==
  75. global_options.end()
  76. ? IR_OPTION_ENABLE_COMPRESS_WEIGHT_DEFAULT
  77. : global_options[ge::ir_option::ENABLE_COMPRESS_WEIGHT];
  78. std::string compress_weight_conf = global_options.find(ge::ir_option::COMPRESS_WEIGHT_CONF) == global_options.end()
  79. ? ""
  80. : global_options[ge::ir_option::COMPRESS_WEIGHT_CONF];
  81. GE_CHK_BOOL_EXEC(ge::CheckCompressWeightParamValid(enable_compress_weight, compress_weight_conf) == ge::SUCCESS,
  82. return ge::GRAPH_PARAM_INVALID, "check compress weight failed!");
  83. global_options[ge::ir_option::ENABLE_COMPRESS_WEIGHT] = (enable_compress_weight == "true") ?
  84. ge::kEnableCompressWeightTrue :
  85. ge::kEnableCompressWeightFalse;
  86. // check optypelist_for_implmode and op_select_implmode
  87. std::string optypelist_for_implmode = global_options.find(ge::ir_option::OPTYPELIST_FOR_IMPLMODE) ==
  88. global_options.end()
  89. ? ""
  90. : global_options[ge::ir_option::OPTYPELIST_FOR_IMPLMODE];
  91. std::string op_select_implmode = global_options.find(ge::ir_option::OP_SELECT_IMPL_MODE) ==
  92. global_options.end()
  93. ? ""
  94. : global_options[ge::ir_option::OP_SELECT_IMPL_MODE];
  95. GE_CHK_BOOL_EXEC(
  96. ge::CheckImplmodeParamValid(optypelist_for_implmode, op_select_implmode) == ge::SUCCESS,
  97. return ge::GRAPH_PARAM_INVALID, "check optypelist_for_implmode and op_select_implmode failed!");
  98. global_options[ge::ir_option::OP_SELECT_IMPL_MODE] = op_select_implmode;
  99. // set precision mode default value
  100. std::string precision_mode = global_options.find(ge::ir_option::PRECISION_MODE) ==
  101. global_options.end()
  102. ? "force_fp16"
  103. : global_options[ge::ir_option::PRECISION_MODE];
  104. global_options[ge::ir_option::PRECISION_MODE] = precision_mode;
  105. return GRAPH_SUCCESS;
  106. }
  107. static void GetOpsProtoPath(string &opsproto_path) {
  108. GELOGI("Start to get ops proto path schedule.");
  109. const char *path_env = std::getenv("ASCEND_OPP_PATH");
  110. if (path_env != nullptr) {
  111. string path = path_env;
  112. string file_path = RealPath(path.c_str());
  113. if (file_path.empty()) {
  114. GELOGE(FAILED, "File path %s is invalid.", path.c_str());
  115. return;
  116. }
  117. opsproto_path = (path + "/op_proto/custom/" + ":") + (path + "/op_proto/built-in/");
  118. GELOGI("Get opsproto so path from env : %s", path.c_str());
  119. return;
  120. }
  121. string path_base = PluginManager::GetPath();
  122. GELOGI("path_base is %s", path_base.c_str());
  123. path_base = path_base.substr(0, path_base.rfind('/'));
  124. path_base = path_base.substr(0, path_base.rfind('/') + 1);
  125. opsproto_path = (path_base + "ops/op_proto/custom/" + ":") + (path_base + "ops/op_proto/built-in/");
  126. }
  127. static void LoadOpsProto() {
  128. string opsproto_path;
  129. GetOpsProtoPath(opsproto_path);
  130. GELOGI("Get opsproto path is %s", opsproto_path.c_str());
  131. OpsProtoManager *manager = OpsProtoManager::Instance();
  132. map<string, string> option_tmp;
  133. option_tmp.emplace(std::pair<string, string>(string("ge.opsProtoLibPath"), opsproto_path));
  134. (void)manager->Initialize(option_tmp);
  135. }
  136. graphStatus aclgrphBuildInitialize(std::map<std::string, std::string> global_options) {
  137. GELOGD("Enter aclgrphInitialize start!");
  138. // check global options
  139. if (CheckGlobalOptions(global_options) != GRAPH_SUCCESS) {
  140. GELOGE(GRAPH_PARAM_INVALID, "Check global options falied!");
  141. return GRAPH_PARAM_INVALID;
  142. }
  143. // print global option map
  144. ge::PrintOptionMap(global_options, "global option");
  145. LoadOpsProto();
  146. std::shared_ptr<ge::GELib> instance_ptr = ge::GELib::GetInstance();
  147. if (instance_ptr == nullptr || !instance_ptr->InitFlag()) {
  148. GELOGI("aclgrphInitialize start!");
  149. auto ret = ge::GELib::Initialize(global_options);
  150. if (ret != ge::SUCCESS) {
  151. GELOGE(ret, "GE initialize failed!");
  152. return GRAPH_FAILED;
  153. }
  154. // for functional subgraph assign _parent_index.
  155. TBEPluginManager::Instance().InitPreparation(global_options);
  156. }
  157. GELOGW("gelib has been initialized!");
  158. return GRAPH_SUCCESS;
  159. }
  160. void aclgrphBuildFinalize() {
  161. if (ge::GELib::GetInstance() != nullptr && ge::GELib::GetInstance()->InitFlag()) {
  162. (void)TBEPluginManager::Instance().Finalize();
  163. (void)ge::GELib::GetInstance()->Finalize();
  164. return;
  165. }
  166. GELOGW("[Notice] gelib has not been initialized!do nothing!");
  167. }
  168. class Impl {
  169. public:
  170. Impl() {
  171. omg_context_ = domi::GetContext();
  172. omg_context_.format = domi::DOMI_TENSOR_ND;
  173. omg_context_.input_nodes_format_map.clear();
  174. omg_context_.output_formats.clear();
  175. omg_context_.user_input_dims.clear();
  176. omg_context_.input_dims.clear();
  177. omg_context_.op_conf_map.clear();
  178. omg_context_.out_nodes_map.clear();
  179. omg_context_.user_out_nodes.clear();
  180. omg_context_.net_format = domi::DOMI_TENSOR_RESERVED;
  181. omg_context_.type = domi::FRAMEWORK_RESERVED;
  182. omg_context_.run_mode = ONLY_PRE_CHECK;
  183. omg_context_.train_flag = false;
  184. omg_context_.output_type.clear();
  185. omg_context_.is_dynamic_input = false;
  186. omg_context_.dynamic_batch_size.clear();
  187. omg_context_.dynamic_image_size.clear();
  188. omg_context_.dynamic_dims.clear();
  189. };
  190. ~Impl() { (void)generator_.Finalize(); };
  191. graphStatus CheckOptions(const std::map<std::string, std::string> &options);
  192. graphStatus CreateInputsForIRBuild(const ge::Graph &graph, vector<ge::GeTensor> &inputs);
  193. graphStatus Init(const std::map<std::string, std::string> &options);
  194. graphStatus BuildModel(const Graph &graph, const std::map<std::string, std::string> &options,
  195. ModelBufferData &ge_models);
  196. graphStatus InitDomiOmgContext(const string &input_shape, const string &input_format, const string &net_format,
  197. bool is_dynamic_input);
  198. void SetRtSocVersion();
  199. void UpdateThreadContext();
  200. void LoadOpsProto();
  201. public:
  202. ge::GeGenerator generator_;
  203. std::map<std::string, std::string> options_;
  204. bool is_dynamic_input_ = false;
  205. OmgContext omg_context_;
  206. };
  207. graphStatus Impl::CheckOptions(const std::map<std::string, std::string> &options) {
  208. for (auto &ele : options) {
  209. auto it = ge::ir_option::ir_builder_suppported_options.find(ele.first);
  210. if (it == ge::ir_option::ir_builder_suppported_options.end()) {
  211. auto it_lx_fusion = ir_builder_supported_options_for_lx_fusion.find(ele.first);
  212. if (it_lx_fusion == ir_builder_supported_options_for_lx_fusion.end()) {
  213. GELOGE(GRAPH_PARAM_INVALID, "input options include unsupported option(%s).Please check!",
  214. ele.first.c_str());
  215. return GRAPH_PARAM_INVALID;
  216. }
  217. }
  218. options_.insert(ele);
  219. }
  220. // Check options build_mode and build_step.
  221. std::string build_mode;
  222. auto it = options_.find(BUILD_MODE);
  223. if (it != options_.end() && !(it->second.empty())) {
  224. if (build_mode_options.find(it->second) == build_mode_options.end()) {
  225. GELOGE(GRAPH_PARAM_INVALID, "Build mode:%s is unsupported. Please check!", it->second.c_str());
  226. return GRAPH_PARAM_INVALID;
  227. }
  228. build_mode = it->second;
  229. }
  230. it = options_.find(BUILD_STEP);
  231. if (it != options_.end() && !(it->second.empty())) {
  232. if (build_step_options.find(it->second) == build_step_options.end()) {
  233. GELOGE(GRAPH_PARAM_INVALID, "Build step:%s is unsupported. Please check!", it->second.c_str());
  234. return GRAPH_PARAM_INVALID;
  235. }
  236. } else {
  237. if (build_mode == BUILD_MODE_TUNING) {
  238. GELOGE(GRAPH_PARAM_INVALID, "Build mode tuning must specify build step. Please check!");
  239. return GRAPH_PARAM_INVALID;
  240. }
  241. }
  242. return GRAPH_SUCCESS;
  243. }
  244. graphStatus Impl::Init(const std::map<std::string, std::string> &options) {
  245. // 1. check options
  246. graphStatus ret = CheckOptions(options);
  247. if (ret != GRAPH_SUCCESS) {
  248. GELOGE(ret, "User input options are illegal! Please check!");
  249. return ret;
  250. }
  251. std::string build_mode = (options_.find(BUILD_MODE) == options_.end() || options_[BUILD_MODE] == BUILD_MODE_NORMAL)
  252. ? "" : options_[BUILD_MODE];
  253. options_[BUILD_MODE] = build_mode;
  254. // set log level
  255. std::string log = options_.find(ge::ir_option::LOG_LEVEL) == options_.end()
  256. ? IR_OPTION_LOG_LEVEL_DEFAULT
  257. : options_[ge::ir_option::LOG_LEVEL];
  258. GE_CHK_BOOL_RET_STATUS_NOLOG(ge::CheckLogParamValidAndSetLogLevel(log) == 0, GRAPH_PARAM_INVALID);
  259. options_[ge::ir_option::LOG_LEVEL] = log;
  260. string input_shape = options_.find("input_shape") == options_.end() ? "" : options_["input_shape"];
  261. string input_format = options_.find("input_format") == options_.end() ? "" : options_["input_format"];
  262. string net_format = options_.find("net_format") == options_.end() ? "" : options_["net_format"];
  263. string dynamic_batch_size = options_.find(ge::ir_option::DYNAMIC_BATCH_SIZE) == options_.end()
  264. ? ""
  265. : options_[ge::ir_option::DYNAMIC_BATCH_SIZE];
  266. string dynamic_image_size = options_.find(ge::ir_option::DYNAMIC_IMAGE_SIZE) == options_.end()
  267. ? ""
  268. : options_[ge::ir_option::DYNAMIC_IMAGE_SIZE];
  269. string dynamic_dims =
  270. options_.find(ge::ir_option::DYNAMIC_DIMS) == options_.end() ? "" : options_[ge::ir_option::DYNAMIC_DIMS];
  271. auto status = CheckDynamicInputParamValid(dynamic_batch_size, dynamic_image_size, dynamic_dims, input_shape,
  272. input_format, is_dynamic_input_);
  273. if (status != ge::SUCCESS) {
  274. GELOGE(GRAPH_PARAM_INVALID, "Check dynamic input size failed!");
  275. return GRAPH_PARAM_INVALID;
  276. }
  277. GELOGD("User input dynamic_batch_size:%s, dynamic_image_size:%s, dynamic_dims:%s.", dynamic_batch_size.c_str(),
  278. dynamic_image_size.c_str(), dynamic_dims.c_str());
  279. omg_context_.dynamic_batch_size = dynamic_batch_size;
  280. omg_context_.dynamic_image_size = dynamic_image_size;
  281. omg_context_.dynamic_dims = dynamic_dims;
  282. // check output_type
  283. std::string output_type = options_.find(ge::ir_option::OUTPUT_TYPE) == options_.end()
  284. ? ""
  285. : options_[ge::ir_option::OUTPUT_TYPE];
  286. GE_CHK_BOOL_EXEC(ge::CheckOutputTypeParamValid(output_type) == ge::SUCCESS,
  287. return ge::GRAPH_PARAM_INVALID, "check output type failed!");
  288. // check insert_op_conf
  289. std::string insert_op_conf = options_.find(ge::ir_option::INSERT_OP_FILE) == options_.end()
  290. ? ""
  291. : options_[ge::ir_option::INSERT_OP_FILE];
  292. GE_CHK_BOOL_EXEC(ge::CheckInsertOpConfParamValid(std::string(insert_op_conf)) == ge::SUCCESS,
  293. return ge::GRAPH_PARAM_INVALID, "check insert op conf failed!");
  294. GE_CHK_BOOL_EXEC(insert_op_conf.empty() || dynamic_dims.empty(),
  295. return ge::GRAPH_PARAM_INVALID, "dynamic dims function does not support aipp");
  296. // for IR builder.Only support om mode, so here fixed;
  297. options_.insert(std::pair<string, string>(string(IR_OPTION_MODE), to_string(0)));
  298. options_.insert(std::pair<string, string>(string(IR_OPTION_TARGET), "mini"));
  299. options_.insert(std::pair<string, string>(string(ge::RUN_FLAG), to_string(0)));
  300. options_.insert(std::pair<string, string>(string(ge::TRAIN_FLAG), to_string(0)));
  301. options_.insert(std::pair<string, string>(string(ge::SAVE_ORIGINAL_MODEL), to_string(0)));
  302. // print ge option map
  303. ge::PrintOptionMap(options_, "ge option");
  304. SetRtSocVersion();
  305. UpdateThreadContext();
  306. // 3. init generator with options_
  307. ret = generator_.Initialize(options_, omg_context_);
  308. if (ret != GRAPH_SUCCESS) {
  309. GELOGE(ret, "generator Initialize failed!");
  310. return ret;
  311. }
  312. // 4.parse and init Context with input shape format and net format info
  313. return this->InitDomiOmgContext(input_shape, input_format, net_format, is_dynamic_input_);
  314. }
  315. void Impl::SetRtSocVersion() {
  316. const auto &global_options = GetMutableGlobalOptions();
  317. auto it = global_options.find(ge::SOC_VERSION);
  318. if (it != global_options.end()) {
  319. const char *soc_version = it->second.c_str();
  320. rtError_t rt_ret = rtSetSocVersion(soc_version);
  321. if (rt_ret != RT_ERROR_NONE) {
  322. GELOGW("Set soc version %s failed. ret:0x%X", soc_version, rt_ret);
  323. }
  324. GELOGI("Set soc version %s success.", soc_version);
  325. }
  326. }
  327. void Impl::UpdateThreadContext() {
  328. GetThreadLocalContext().SetGlobalOption(GetMutableGlobalOptions());
  329. GetThreadLocalContext().SetGraphOption(options_);
  330. }
  331. graphStatus Impl::CreateInputsForIRBuild(const ge::Graph &graph, vector<ge::GeTensor> &inputs) {
  332. auto compute_graph = ge::GraphUtils::GetComputeGraph(graph);
  333. GE_CHECK_NOTNULL(compute_graph);
  334. int64_t index = 0;
  335. for (ge::NodePtr &input_node : compute_graph->GetDirectNode()) {
  336. GE_CHECK_NOTNULL(input_node);
  337. ge::OpDescPtr op = input_node->GetOpDesc();
  338. GE_CHECK_NOTNULL(op);
  339. if (op->GetType() == DATA) {
  340. (void)AttrUtils::SetInt(op, ATTR_NAME_INDEX, index++);
  341. GELOGI("Data op inputDesc size: %zu", op->GetAllInputsDesc().size());
  342. ge::GeTensorDesc tensor = op->GetInputDesc(0);
  343. string data_op_name = op->GetName();
  344. GELOGI("Data op name: %s", data_op_name.c_str());
  345. ge::GeShape data_shape;
  346. auto iter = omg_context_.input_dims.find(data_op_name);
  347. if (iter != omg_context_.input_dims.end()) {
  348. data_shape = ge::GeShape(iter->second);
  349. GELOGI("Data op get shape from Context.");
  350. } else {
  351. data_shape = tensor.GetShape();
  352. GELOGI("Data op get shape from InputDesc in ge ir graph.");
  353. }
  354. // If user point input format, do work for all data ops; else do according to tensor_desc
  355. auto data_format = omg_context_.format != domi::DOMI_TENSOR_ND ?
  356. ge::TypeUtils::DomiFormatToFormat(omg_context_.format) : tensor.GetFormat();
  357. ge::DataType data_type = tensor.GetDataType();
  358. string data_type_str = ge::TypeUtils::DataTypeToSerialString(data_type);
  359. GELOGI("Data op get data type:%s from InputDesc in ge ir graph.", data_type_str.c_str());
  360. ge::GeTensor inputTensor;
  361. ge::GeTensorDesc desc(data_shape, ge::Format(data_format), data_type);
  362. inputTensor.SetTensorDesc(desc);
  363. inputs.push_back(inputTensor);
  364. }
  365. }
  366. GELOGD("CreateInputsForIRBuild, inputs size: %zu", inputs.size());
  367. return GRAPH_SUCCESS;
  368. }
  369. graphStatus Impl::BuildModel(const Graph &graph, const std::map<std::string, std::string> &options,
  370. ModelBufferData &model) {
  371. // 1. init GeGenerator with user optios
  372. graphStatus ret = Init(options);
  373. if (ret != GRAPH_SUCCESS) {
  374. GELOGE(ret, "Build ir model Init failed!");
  375. return ret;
  376. }
  377. // 2. construct input
  378. std::vector<GeTensor> inputs;
  379. if (!omg_context_.is_dynamic_input) { // if dynamic input , no need to creat inputs
  380. ret = CreateInputsForIRBuild(graph, inputs);
  381. if (ret != GRAPH_SUCCESS) {
  382. GELOGE(ret, "CreateInputsForIRBuild failed!");
  383. return ret;
  384. }
  385. }
  386. // 3. build IR model
  387. ret = generator_.GenerateOnlineModel(graph, inputs, model);
  388. if (ret != GRAPH_SUCCESS) {
  389. GELOGE(ret, "GenerateOnlineModel failed!");
  390. return ret;
  391. }
  392. return GRAPH_SUCCESS;
  393. }
  394. graphStatus Impl::InitDomiOmgContext(const string &input_shape, const string &input_format, const string &net_format,
  395. bool is_dynamic_input) {
  396. // Clear omgcontext data first
  397. omg_context_.input_dims.clear();
  398. omg_context_.user_input_dims.clear();
  399. omg_context_.is_dynamic_input = is_dynamic_input;
  400. // the default value is ND
  401. omg_context_.format = domi::DOMI_TENSOR_ND;
  402. if (!input_format.empty()) {
  403. auto iter = ge::input_format_str_to_geformat.find(input_format);
  404. if (iter != ge::input_format_str_to_geformat.end()) {
  405. omg_context_.format = iter->second;
  406. } else {
  407. GELOGE(GRAPH_PARAM_INVALID, "Input format %s not support , expect ND/NCHW/NHWC/CHWN/NC1HWC0/NHWC1C0.",
  408. input_format.c_str());
  409. return GRAPH_PARAM_INVALID;
  410. }
  411. }
  412. // Input is empty, do not process
  413. if (input_shape.empty()) {
  414. return GRAPH_SUCCESS;
  415. }
  416. if (!ParseInputShape(input_shape, omg_context_.input_dims, omg_context_.user_input_dims, is_dynamic_input)) {
  417. GELOGE(GRAPH_PARAM_INVALID, "Failed to parse input shape: %s", input_shape.c_str());
  418. return GRAPH_PARAM_INVALID;
  419. }
  420. return GRAPH_SUCCESS;
  421. }
  422. graphStatus aclgrphBuildModel(const ge::Graph &graph, const std::map<std::string, std::string> &build_options,
  423. ModelBufferData &model) {
  424. GELOGD("Enter aclmdlBuildModel process!");
  425. Impl builder;
  426. return builder.BuildModel(graph, build_options, model);
  427. }
  428. graphStatus aclgrphSaveModel(const string &output_file, const ModelBufferData &model) {
  429. GELOGD("Enter aclmdlSaveModel process!");
  430. if (model.data.get() == nullptr || model.length == 0) {
  431. GELOGE(GRAPH_PARAM_INVALID, "input model is illegal");
  432. return GRAPH_PARAM_INVALID;
  433. }
  434. return FileSaver::SaveToFile((output_file + ".om"), reinterpret_cast<void*>(model.data.get()),
  435. static_cast<uint32_t>(model.length));
  436. }
  437. graphStatus aclgrphGetIRVersion(int *major_version, int *minor_version, int *patch_version) {
  438. GELOGD("Enter aclgrphGetIRVersion process!");
  439. GE_CHECK_NOTNULL(major_version);
  440. GE_CHECK_NOTNULL(minor_version);
  441. GE_CHECK_NOTNULL(patch_version);
  442. *major_version = IR_MAJOR_VERSION;
  443. *minor_version = IR_MINOR_VERSION;
  444. *patch_version = IR_PATCH_VERSION;
  445. return GRAPH_SUCCESS;
  446. }
  447. graphStatus aclgrphInferShapeAndType(ge::Graph &graph) {
  448. auto compute_graph = GraphUtils::GetComputeGraph(graph);
  449. GE_CHECK_NOTNULL(compute_graph);
  450. auto root_graph = compute_graph->GetParentGraph();
  451. if (root_graph != nullptr) {
  452. GELOGE(GRAPH_PARAM_INVALID, "Input param should not be subgraph");
  453. return GRAPH_PARAM_INVALID;
  454. }
  455. auto ret = compute_graph->InferOriginFormat();
  456. if (ret != GRAPH_SUCCESS) {
  457. GELOGE(ret, "Acl InferOriginFormat failed.");
  458. return ret;
  459. }
  460. for (auto &node: compute_graph->GetAllNodes()) {
  461. graphStatus ret = ShapeRefiner::InferShapeAndType(node);
  462. if (ret == GRAPH_PARAM_INVALID) {
  463. GELOGW("Can not find infershape func.");
  464. continue;
  465. } else if (ret != GRAPH_SUCCESS) {
  466. GELOGE(ret, "Acl infershape failed.");
  467. return ret;
  468. }
  469. }
  470. return GRAPH_SUCCESS;
  471. }
  472. graphStatus aclgrphDumpGraph(const ge::Graph &graph, const char *file, const size_t len) {
  473. GE_CHECK_NOTNULL(file);
  474. if (len > PATH_MAX || len != strlen(file) || strlen(file) == 0) {
  475. GELOGE(GRAPH_PARAM_INVALID, "File path invalid.");
  476. return GRAPH_PARAM_INVALID;
  477. }
  478. auto compute_graph = GraphUtils::GetComputeGraph(graph);
  479. GE_CHECK_NOTNULL(compute_graph);
  480. string full_path(file, len);
  481. for (size_t i = 0; i < len; i++) {
  482. if (full_path[i] == '\\') {
  483. full_path.replace(i, 1, "/");
  484. }
  485. }
  486. string suffix;
  487. string file_path;
  488. int pos = full_path.rfind("/");
  489. if (pos != -1) {
  490. suffix = full_path.substr(pos + 1, -1);
  491. file_path = full_path.substr(0, pos);
  492. } else {
  493. suffix = full_path;
  494. file_path = "./";
  495. }
  496. if (suffix.empty()) {
  497. suffix = compute_graph->GetName();
  498. if (suffix.empty()) {
  499. suffix = "graph";
  500. }
  501. }
  502. char path[PATH_MAX] = {0};
  503. if (realpath(file_path.c_str(), path) == nullptr) {
  504. GELOGE(GRAPH_PARAM_INVALID, "Dump file path:%s is invalid.", file);
  505. return GRAPH_PARAM_INVALID;
  506. }
  507. GraphUtils::DumpGEGrph(compute_graph, string(path), suffix);
  508. GraphUtils::DumpGrphToOnnx(*compute_graph, string(path), suffix);
  509. uint64_t i = 0;
  510. for (const auto &sub_graph_func : compute_graph->GetAllSubgraphs()) {
  511. auto sub_graph_func_name = suffix + std::string("_sub_graph_") + std::to_string(i++);
  512. GraphUtils::DumpGEGrph(sub_graph_func, string(path), sub_graph_func_name);
  513. GraphUtils::DumpGrphToOnnx(*sub_graph_func, string(path), sub_graph_func_name);
  514. }
  515. return GRAPH_SUCCESS;
  516. }
  517. } // namespace ge

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