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

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

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