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

5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 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
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  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. // check modify_mixlist
  129. std::string modify_mixlist = global_options.find(ge::ir_option::MODIFY_MIXLIST) ==
  130. global_options.end()
  131. ? ""
  132. : global_options[ge::ir_option::MODIFY_MIXLIST];
  133. if (ge::CheckModifyMixlistParamValid(precision_mode, modify_mixlist) != ge::SUCCESS) {
  134. return ge::GRAPH_PARAM_INVALID;
  135. }
  136. global_options[ge::ir_option::MODIFY_MIXLIST] = modify_mixlist;
  137. return GRAPH_SUCCESS;
  138. }
  139. static void GetOpsProtoPath(string &opsproto_path) {
  140. GELOGI("Start to get ops proto path schedule.");
  141. const char *path_env = std::getenv("ASCEND_OPP_PATH");
  142. if (path_env != nullptr) {
  143. string path = path_env;
  144. string file_path = RealPath(path.c_str());
  145. if (file_path.empty()) {
  146. GELOGE(FAILED, "[Check][Path] %s is invalid.", path.c_str());
  147. return;
  148. }
  149. opsproto_path = (path + "/op_proto/custom/" + ":") + (path + "/op_proto/built-in/");
  150. GELOGI("Get opsproto so path from env : %s", path.c_str());
  151. return;
  152. }
  153. string path_base = PluginManager::GetPath();
  154. GELOGI("path_base is %s", path_base.c_str());
  155. path_base = path_base.substr(0, path_base.rfind('/'));
  156. path_base = path_base.substr(0, path_base.rfind('/') + 1);
  157. opsproto_path = (path_base + "ops/op_proto/custom/" + ":") + (path_base + "ops/op_proto/built-in/");
  158. }
  159. static void LoadOpsProto() {
  160. string opsproto_path;
  161. GetOpsProtoPath(opsproto_path);
  162. GELOGI("Get opsproto path is %s", opsproto_path.c_str());
  163. OpsProtoManager *manager = OpsProtoManager::Instance();
  164. map<string, string> option_tmp;
  165. option_tmp.emplace(std::pair<string, string>(string("ge.opsProtoLibPath"), opsproto_path));
  166. (void)manager->Initialize(option_tmp);
  167. }
  168. graphStatus aclgrphBuildInitializeImpl(std::map<std::string, std::string> &global_options) {
  169. GELOGD("Enter aclgrphInitialize start!");
  170. // check global options
  171. if (CheckGlobalOptions(global_options) != GRAPH_SUCCESS) {
  172. GELOGE(GRAPH_PARAM_INVALID, "[Check][Global Options] falied!");
  173. return GRAPH_PARAM_INVALID;
  174. }
  175. // print global option map
  176. ge::PrintOptionMap(global_options, "global option");
  177. LoadOpsProto();
  178. std::shared_ptr<ge::GELib> instance_ptr = ge::GELib::GetInstance();
  179. if (instance_ptr == nullptr || !instance_ptr->InitFlag()) {
  180. GELOGI("aclgrphInitialize start!");
  181. auto ret = ge::GELib::Initialize(global_options);
  182. if (ret != ge::SUCCESS) {
  183. GELOGE(ret, "[Init][GELib] failed!");
  184. return GRAPH_FAILED;
  185. }
  186. }
  187. GELOGW("gelib has been initialized!");
  188. std::string path_base = ge::GELib::GetPath();
  189. int ret = ErrorManager::GetInstance().Init(path_base);
  190. if (ret != 0) {
  191. DOMI_LOGE("ErrorManager init fail !");
  192. return GRAPH_FAILED;
  193. }
  194. return GRAPH_SUCCESS;
  195. }
  196. graphStatus aclgrphBuildInitialize(std::map<std::string, std::string> global_options) {
  197. ErrorManager::GetInstance().SetStage(error_message::kInitialize, error_message::kOther);
  198. return aclgrphBuildInitializeImpl(global_options);
  199. }
  200. graphStatus aclgrphBuildInitialize(std::map<AscendString, AscendString> &global_options) {
  201. ErrorManager::GetInstance().SetStage(error_message::kInitialize, error_message::kOther);
  202. std::map<std::string, std::string> tmp_global_options;
  203. for (auto &option : global_options) {
  204. if (option.first.GetString() == nullptr || option.second.GetString() == nullptr) {
  205. GELOGE(GRAPH_FAILED, "[Check][Options]AclgrphBuildInitialize option is nullptr.");
  206. return GRAPH_FAILED;
  207. }
  208. std::string key = option.first.GetString();
  209. std::string val = option.second.GetString();
  210. tmp_global_options[key] = val;
  211. }
  212. return aclgrphBuildInitializeImpl(tmp_global_options);
  213. }
  214. void aclgrphBuildFinalize() {
  215. ErrorManager::GetInstance().SetStage(error_message::kFinalize, error_message::kFinalize);
  216. if (ge::GELib::GetInstance() != nullptr && ge::GELib::GetInstance()->InitFlag()) {
  217. (void)ge::GELib::GetInstance()->Finalize();
  218. return;
  219. }
  220. GELOGW("[Notice] gelib has not been initialized!do nothing!");
  221. }
  222. class Impl {
  223. public:
  224. Impl() {
  225. omg_context_ = domi::GetContext();
  226. omg_context_.format = domi::DOMI_TENSOR_ND;
  227. omg_context_.input_nodes_format_map.clear();
  228. omg_context_.output_formats.clear();
  229. omg_context_.user_input_dims.clear();
  230. omg_context_.input_dims.clear();
  231. omg_context_.op_conf_map.clear();
  232. omg_context_.out_nodes_map.clear();
  233. omg_context_.user_out_nodes.clear();
  234. omg_context_.net_format = domi::DOMI_TENSOR_RESERVED;
  235. omg_context_.type = domi::FRAMEWORK_RESERVED;
  236. omg_context_.run_mode = ONLY_PRE_CHECK;
  237. omg_context_.train_flag = false;
  238. omg_context_.output_type.clear();
  239. omg_context_.is_dynamic_input = false;
  240. omg_context_.dynamic_batch_size.clear();
  241. omg_context_.dynamic_image_size.clear();
  242. omg_context_.dynamic_dims.clear();
  243. omg_context_.user_attr_index_valid = false;
  244. };
  245. ~Impl() { (void)generator_.Finalize(); };
  246. graphStatus CheckBuildModeAndBuildStep();
  247. graphStatus GetSupportedOptions(const std::map<std::string, std::string> &in,
  248. std::map<std::string, std::string> &out);
  249. graphStatus CheckOptions(const std::map<std::string, std::string> &options);
  250. graphStatus CreateInputsForIRBuild(const ge::Graph &graph, vector<ge::GeTensor> &inputs);
  251. graphStatus UpdateDataOpAttr(const Graph &graph);
  252. graphStatus CheckDataOpAttrIndexValid(const Graph &graph, const std::string &input_shape_range);
  253. graphStatus Init(const Graph &graph, const std::map<std::string, std::string> &options);
  254. graphStatus BuildModel(const Graph &graph, const std::map<std::string, std::string> &options,
  255. ModelBufferData &ge_models);
  256. graphStatus InitDomiOmgContext(const string &input_shape, const string &input_format, bool is_dynamic_input);
  257. graphStatus GetInputShapeRange(const string &input_shape_range,
  258. std::map<string, std::vector<std::pair<int64_t, int64_t>>> &name_shape_range_map,
  259. std::vector<std::vector<std::pair<int64_t, int64_t>>> &index_shape_range_map);
  260. static graphStatus InferShapePrepare(const ComputeGraphPtr &compute_graph);
  261. bool GetUsrAttrIndexValidFlag();
  262. bool IsAttrIndexSetByUser(const ComputeGraphPtr &compute_graph, size_t &data_num, vector<int64_t> &attr_index);
  263. void SetRtSocVersion();
  264. void UpdateThreadContext();
  265. void LoadOpsProto();
  266. std::string GetParam(const std::string &param);
  267. public:
  268. ge::GeGenerator generator_;
  269. std::map<std::string, std::string> options_;
  270. bool is_dynamic_input_ = false;
  271. OmgContext omg_context_;
  272. };
  273. graphStatus Impl::InferShapePrepare(const ComputeGraphPtr &compute_graph) {
  274. GE_CHECK_NOTNULL(compute_graph);
  275. PassManager prepare_infershape;
  276. prepare_infershape.AddPass("PrepareNetoutput", new(std::nothrow) NetOutputPass);
  277. prepare_infershape.AddPass("PrepareSubGraphReflection", new (std::nothrow) DataPass);
  278. auto ret = prepare_infershape.Run(compute_graph);
  279. if ((ret != SUCCESS) && (ret != NOT_CHANGED)) {
  280. GELOGE(ret, "[Prepair][InferShape] failed, ret:%d", ret);
  281. return ret;
  282. }
  283. GELOGD("Prepair for infershape success!");
  284. return GRAPH_SUCCESS;
  285. }
  286. bool Impl::GetUsrAttrIndexValidFlag() {
  287. return omg_context_.user_attr_index_valid;
  288. }
  289. bool Impl::IsAttrIndexSetByUser(const ComputeGraphPtr &compute_graph,
  290. size_t &data_num,
  291. vector<int64_t> &attr_index) {
  292. bool all_zero_flag = true;
  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. data_num++;
  299. GeAttrValue::INT index = 0;
  300. if (AttrUtils::GetInt(op, ATTR_NAME_INDEX, index)) {
  301. if (index != 0) {
  302. all_zero_flag = false;
  303. }
  304. attr_index.push_back(index);
  305. } else {
  306. GELOGW("[Get][AttrIndex] Get index[%ld] failed for op[%s].", index, op->GetName().c_str());
  307. }
  308. }
  309. }
  310. if (data_num > 1 && attr_index.size() == data_num && all_zero_flag) {
  311. GELOGI("Attr indexes are not set by user.");
  312. return false;
  313. }
  314. return true;
  315. }
  316. graphStatus Impl::GetInputShapeRange(const string &input_shape_range,
  317. std::map<string, std::vector<std::pair<int64_t, int64_t>>> &name_shape_range_map,
  318. std::vector<std::vector<std::pair<int64_t, int64_t>>> &index_shape_range_map) {
  319. if (input_shape_range.empty()) {
  320. GELOGI("Input shape range is empty.");
  321. return GRAPH_SUCCESS;
  322. }
  323. Status ret = GRAPH_PARAM_INVALID;
  324. if (input_shape_range.find(":") != string::npos) {
  325. ret = ParseInputShapeRange(input_shape_range, name_shape_range_map);
  326. } else {
  327. ret = ParseInputShapeRange(input_shape_range, index_shape_range_map);
  328. }
  329. if (ret != SUCCESS) {
  330. GELOGE(GRAPH_PARAM_INVALID, "[Parse][InputShapeRange] parse shape range[%s] failed.", input_shape_range.c_str());
  331. return GRAPH_PARAM_INVALID;
  332. }
  333. return GRAPH_SUCCESS;
  334. }
  335. graphStatus Impl::CheckDataOpAttrIndexValid(const Graph &graph, const std::string &input_shape_range) {
  336. auto compute_graph = ge::GraphUtils::GetComputeGraph(graph);
  337. GE_CHECK_NOTNULL(compute_graph);
  338. // when set input shape range by index, user must set data attr index, eg. "[1, 3, 3, -1],[1, 3~5, 6, -1]"
  339. bool index_input_shape_range_flag = !input_shape_range.empty() && (input_shape_range.find(":") == string::npos);
  340. size_t data_num = 0;
  341. vector<int64_t> attr_index;
  342. if (!IsAttrIndexSetByUser(compute_graph, data_num, attr_index)) {
  343. if (index_input_shape_range_flag) {
  344. std::string situation = "Data op index";
  345. std::string reason = "it must be set by user, total data op num[" + std::to_string(data_num) + "], "
  346. "when set input shape range by index.";
  347. REPORT_INPUT_ERROR("E19025", std::vector<std::string>({"situation", "reason"}),
  348. std::vector<std::string>({situation, reason}));
  349. GELOGE(GRAPH_FAILED, "[Check][AttrIndex] Data op index is not set, total data op num[%ld], "
  350. "when set input shape range by index.", data_num);
  351. return GRAPH_FAILED;
  352. }
  353. return GRAPH_SUCCESS;
  354. }
  355. omg_context_.user_attr_index_valid = true;
  356. for (size_t i = 0; i < data_num; ++i) {
  357. if (std::find(attr_index.begin(), attr_index.end(), i) == attr_index.end()) {
  358. omg_context_.user_attr_index_valid = false;
  359. if (index_input_shape_range_flag) {
  360. std::string situation = "Data op index[" + std::to_string(i) + "]";
  361. std::string reason = "it must be set by user, total data op num[" + std::to_string(data_num) + "], "
  362. "when set input shape range by index";
  363. REPORT_INPUT_ERROR("E19025", std::vector<std::string>({"situation", "reason"}),
  364. std::vector<std::string>({situation, reason}));
  365. GELOGE(GRAPH_FAILED, "[Check][AttrIndex] Attr index [%ld] is not set, total data op num[%ld], "
  366. "when set input shape range by index", i, data_num);
  367. return GRAPH_FAILED;
  368. } else {
  369. GELOGW("[Check][AttrIndex] Attr index [%ld] is not set, total data op num[%ld].", i, data_num);
  370. }
  371. }
  372. }
  373. GELOGI("Data op attr indexes are set by user and valid.");
  374. return GRAPH_SUCCESS;
  375. }
  376. graphStatus Impl::UpdateDataOpAttr(const Graph &graph) {
  377. GELOGD("Enter Update Data Attr Process!");
  378. std::string input_shape = (options_.find(kInputShape) == options_.end()) ? "" : options_[kInputShape];
  379. std::string input_shape_range = (options_.find(kInputShapeRange) == options_.end()) ? "" : options_[kInputShapeRange];
  380. graphStatus ret = CheckDataOpAttrIndexValid(graph, input_shape_range);
  381. if (ret != GRAPH_SUCCESS) {
  382. GELOGE(GRAPH_FAILED, "[Check][DataOpAttrIndex] fail, shape range[%s].", input_shape_range.c_str());
  383. return GRAPH_FAILED;
  384. }
  385. map<string, vector<int64_t>> shape_map;
  386. vector<pair<string, vector<int64_t>>> user_shape_map;
  387. if (!input_shape.empty()) {
  388. GE_CHK_BOOL_EXEC(ParseInputShape(input_shape, shape_map, user_shape_map, true),
  389. return GRAPH_PARAM_INVALID, "[Parse][InputShape] failed!");
  390. }
  391. std::map<string, std::vector<std::pair<int64_t, int64_t>>> name_shape_range_map;
  392. std::vector<std::vector<std::pair<int64_t, int64_t>>> index_shape_range_map;
  393. auto compute_graph = ge::GraphUtils::GetComputeGraph(graph);
  394. GE_CHECK_NOTNULL(compute_graph);
  395. ret = GetInputShapeRange(input_shape_range, name_shape_range_map, index_shape_range_map);
  396. if (ret != GRAPH_SUCCESS) {
  397. GELOGE(GRAPH_FAILED, "[Get][InputShapeRange] fail, shape range[%s].", input_shape_range.c_str());
  398. return GRAPH_FAILED;
  399. }
  400. for (ge::NodePtr &input_node : compute_graph->GetDirectNode()) {
  401. GE_CHECK_NOTNULL(input_node);
  402. ge::OpDescPtr op = input_node->GetOpDesc();
  403. GE_CHECK_NOTNULL(op);
  404. if (op->GetType() == DATA) {
  405. if (UpdateDataOpShape(op, shape_map) != SUCCESS) {
  406. GELOGE(GRAPH_FAILED, "[Update][DataOpShape] fail for op:%s.", op->GetName().c_str());
  407. return GRAPH_FAILED;
  408. }
  409. if (UpdateDataOpShapeRange(op, name_shape_range_map) != SUCCESS) {
  410. GELOGE(GRAPH_FAILED, "[Update][DataOpShapeRange] fail for op:%s.", op->GetName().c_str());
  411. return GRAPH_FAILED;
  412. }
  413. if (UpdateDataOpShapeRange(op, index_shape_range_map) != SUCCESS) {
  414. GELOGE(GRAPH_FAILED, "[Update][DataOpShapeRange] fail for op:%s.", op->GetName().c_str());
  415. return GRAPH_FAILED;
  416. }
  417. }
  418. }
  419. return GRAPH_SUCCESS;
  420. }
  421. graphStatus Impl::CheckBuildModeAndBuildStep() {
  422. std::string build_mode;
  423. auto it = options_.find(BUILD_MODE);
  424. if (it != options_.end() && !(it->second.empty())) {
  425. if (build_mode_options.find(it->second) == build_mode_options.end()) {
  426. REPORT_INPUT_ERROR("E10001", std::vector<std::string>({"parameter", "value", "reason"}),
  427. std::vector<std::string>({BUILD_MODE, it->second, "value is unsupported. Please check!"}));
  428. GELOGE(GRAPH_PARAM_INVALID, "[Check][BuildMode]:%s is unsupported. Please check!", it->second.c_str());
  429. return GRAPH_PARAM_INVALID;
  430. }
  431. build_mode = it->second;
  432. }
  433. it = options_.find(BUILD_STEP);
  434. if (it != options_.end() && !(it->second.empty())) {
  435. if (build_step_options.find(it->second) == build_step_options.end()) {
  436. REPORT_INPUT_ERROR("E10001", std::vector<std::string>({"parameter", "value", "reason"}),
  437. std::vector<std::string>({BUILD_STEP, it->second, "value is unsupported. Please check!"}));
  438. GELOGE(GRAPH_PARAM_INVALID, "[Check][BuildStep]:%s is unsupported. Please check!", it->second.c_str());
  439. return GRAPH_PARAM_INVALID;
  440. }
  441. } else {
  442. if (build_mode == BUILD_MODE_TUNING) {
  443. REPORT_INPUT_ERROR("E10001", std::vector<std::string>({"parameter", "value", "reason"}),
  444. std::vector<std::string>({BUILD_MODE, it->second, "tuning must specify build step. Please check!"}));
  445. GELOGE(GRAPH_PARAM_INVALID, "[Check][BuildMode] tuning must specify build step. Please check!");
  446. return GRAPH_PARAM_INVALID;
  447. }
  448. }
  449. return GRAPH_SUCCESS;
  450. }
  451. graphStatus Impl::GetSupportedOptions(const std::map<std::string, std::string> &in,
  452. std::map<std::string, std::string> &out) {
  453. for (auto &ele : in) {
  454. auto it = ge::ir_option::ir_builder_suppported_options.find(ele.first);
  455. if (it == ge::ir_option::ir_builder_suppported_options.end()) {
  456. auto it_lx_fusion = ir_builder_supported_options_for_lx_fusion.find(ele.first);
  457. if (it_lx_fusion == ir_builder_supported_options_for_lx_fusion.end()) {
  458. GELOGE(GRAPH_PARAM_INVALID, "[Check][Options] unsupported option(%s), Please check!",
  459. ele.first.c_str());
  460. return GRAPH_PARAM_INVALID;
  461. }
  462. }
  463. out.insert(ele);
  464. }
  465. return GRAPH_SUCCESS;
  466. }
  467. graphStatus Impl::CheckOptions(const std::map<std::string, std::string> &options) {
  468. auto ret = GetSupportedOptions(options, options_);
  469. if (ret != GRAPH_SUCCESS) {
  470. return ret;
  471. }
  472. // Check options build_mode and build_step.
  473. ret = CheckBuildModeAndBuildStep();
  474. if (ret != GRAPH_SUCCESS) {
  475. return ret;
  476. }
  477. // Check option EXEC_DISABLE_REUSED_MEMORY
  478. auto it = options_.find(ge::ir_option::EXEC_DISABLE_REUSED_MEMORY);
  479. if (it != options_.end() && (CheckDisableReuseMemoryParamValid(it->second) != GRAPH_SUCCESS)) {
  480. return GRAPH_PARAM_INVALID;
  481. }
  482. // Check option modify_mixlist
  483. if (ge::CheckModifyMixlistParamValid(options_) != GRAPH_SUCCESS) {
  484. return GRAPH_PARAM_INVALID;
  485. }
  486. // Check option OP_PRECISION_MODE
  487. it = options_.find(ge::ir_option::OP_PRECISION_MODE);
  488. if (it != options_.end() && !it->second.empty() && !ge::CheckInputPathValid(it->second)) {
  489. REPORT_INPUT_ERROR("E10001", std::vector<std::string>({"parameter", "value", "reason"}),
  490. std::vector<std::string>({ge::ir_option::OP_PRECISION_MODE, it->second, "path is not found"}));
  491. GELOGE(GRAPH_PARAM_INVALID, "[Check][OP_PRECISION_MODE] %s not found", it->second.c_str());
  492. return GRAPH_PARAM_INVALID;
  493. }
  494. if (it != options_.end()) {
  495. GELOGI("Option set successfully, option_key=%s, option_value=%s",
  496. ge::ir_option::OP_PRECISION_MODE, it->second.c_str());
  497. }
  498. // Check Input Format
  499. if (options_.find(kInputFormat) != options_.end()) {
  500. return CheckInputFormat(options_[kInputFormat]);
  501. }
  502. return GRAPH_SUCCESS;
  503. }
  504. std::string Impl::GetParam(const std::string &param) {
  505. return options_.find(param) == options_.end() ? "" : options_[param];
  506. }
  507. graphStatus Impl::Init(const Graph &graph, const std::map<std::string, std::string> &options) {
  508. // 1. check options
  509. graphStatus ret = CheckOptions(options);
  510. if (ret != GRAPH_SUCCESS) {
  511. GELOGE(ret, "[Check][Options] options are illegal! Please check!");
  512. return ret;
  513. }
  514. ret = UpdateDataOpAttr(graph);
  515. if (ret != GRAPH_SUCCESS) {
  516. return ret;
  517. }
  518. std::string build_mode = (options_.find(BUILD_MODE) == options_.end() || options_[BUILD_MODE] == BUILD_MODE_NORMAL)
  519. ? "" : options_[BUILD_MODE];
  520. options_[BUILD_MODE] = build_mode;
  521. // set log level
  522. std::string log = options_.find(ge::ir_option::LOG_LEVEL) == options_.end()
  523. ? IR_OPTION_LOG_LEVEL_DEFAULT
  524. : options_[ge::ir_option::LOG_LEVEL];
  525. GE_CHK_BOOL_RET_STATUS_NOLOG(ge::CheckLogParamValidAndSetLogLevel(log) == 0, GRAPH_PARAM_INVALID);
  526. options_[ge::ir_option::LOG_LEVEL] = log;
  527. string input_shape = GetParam(ge::ir_option::INPUT_SHAPE);
  528. string input_format = GetParam(ge::ir_option::INPUT_FORMAT);
  529. string dynamic_batch_size = GetParam(ge::ir_option::DYNAMIC_BATCH_SIZE);
  530. string dynamic_image_size = GetParam(ge::ir_option::DYNAMIC_IMAGE_SIZE);
  531. string dynamic_dims = GetParam(ge::ir_option::DYNAMIC_DIMS);
  532. string input_shape_range = GetParam(ge::INPUT_SHAPE_RANGE);
  533. auto status = CheckDynamicInputParamValid(dynamic_batch_size, dynamic_image_size, dynamic_dims, input_shape,
  534. input_shape_range, input_format, is_dynamic_input_);
  535. if (status != ge::SUCCESS) {
  536. GELOGE(GRAPH_PARAM_INVALID, "[Check][DynamicInput] failed!");
  537. return GRAPH_PARAM_INVALID;
  538. }
  539. GELOGD("User input dynamic_batch_size:%s, dynamic_image_size:%s, dynamic_dims:%s.", dynamic_batch_size.c_str(),
  540. dynamic_image_size.c_str(), dynamic_dims.c_str());
  541. omg_context_.dynamic_batch_size = dynamic_batch_size;
  542. omg_context_.dynamic_image_size = dynamic_image_size;
  543. omg_context_.dynamic_dims = dynamic_dims;
  544. // check output_type
  545. std::string output_type = GetParam(ge::ir_option::OUTPUT_TYPE);
  546. GE_CHK_BOOL_EXEC(ge::CheckOutputTypeParamValid(output_type) == ge::SUCCESS,
  547. return ge::GRAPH_PARAM_INVALID, "[Check][OutputType] failed!");
  548. // check insert_op_conf
  549. std::string insert_op_conf = GetParam(ge::ir_option::INSERT_OP_FILE);
  550. GE_CHK_BOOL_EXEC(ge::CheckInsertOpConfParamValid(std::string(insert_op_conf)) == ge::SUCCESS,
  551. return ge::GRAPH_PARAM_INVALID, "[Check][InsertOpConf] failed!");
  552. GE_CHK_BOOL_EXEC(insert_op_conf.empty() || dynamic_dims.empty(),
  553. return ge::GRAPH_PARAM_INVALID, "[Check][Data]dynamic dims function does not support aipp");
  554. // for IR builder.Only support om mode, so here fixed;
  555. options_.insert(std::pair<string, string>(string(IR_OPTION_MODE), to_string(0)));
  556. options_.insert(std::pair<string, string>(string(IR_OPTION_TARGET), "mini"));
  557. options_.insert(std::pair<string, string>(string(ge::RUN_FLAG), to_string(0)));
  558. options_.insert(std::pair<string, string>(string(ge::TRAIN_FLAG), to_string(0)));
  559. options_.insert(std::pair<string, string>(string(ge::SAVE_ORIGINAL_MODEL), to_string(0)));
  560. // print ge option map
  561. ge::PrintOptionMap(options_, "ge option");
  562. SetRtSocVersion();
  563. UpdateThreadContext();
  564. // 3. init generator with options_
  565. ret = generator_.Initialize(options_, omg_context_);
  566. if (ret != GRAPH_SUCCESS) {
  567. GELOGE(ret, "[Init][Generator]failed!");
  568. return ret;
  569. }
  570. // 4.parse and init Context with input shape format and net format info
  571. return this->InitDomiOmgContext(input_shape, input_format, is_dynamic_input_);
  572. }
  573. void Impl::SetRtSocVersion() {
  574. const auto &global_options = GetMutableGlobalOptions();
  575. auto it = global_options.find(ge::SOC_VERSION);
  576. if (it != global_options.end()) {
  577. const char *soc_version = it->second.c_str();
  578. rtError_t rt_ret = rtSetSocVersion(soc_version);
  579. if (rt_ret != RT_ERROR_NONE) {
  580. GELOGW("Set soc version %s failed. ret:0x%X", soc_version, rt_ret);
  581. }
  582. GELOGD("Set soc version %s success.", soc_version);
  583. }
  584. }
  585. void Impl::UpdateThreadContext() {
  586. GetThreadLocalContext().SetGlobalOption(GetMutableGlobalOptions());
  587. GetThreadLocalContext().SetGraphOption(options_);
  588. }
  589. graphStatus Impl::CreateInputsForIRBuild(const ge::Graph &graph, vector<ge::GeTensor> &inputs) {
  590. auto compute_graph = ge::GraphUtils::GetComputeGraph(graph);
  591. GE_CHECK_NOTNULL(compute_graph);
  592. int64_t index = 0;
  593. for (ge::NodePtr &input_node : compute_graph->GetDirectNode()) {
  594. GE_CHECK_NOTNULL(input_node);
  595. ge::OpDescPtr op = input_node->GetOpDesc();
  596. GE_CHECK_NOTNULL(op);
  597. if (op->GetType() == DATA) {
  598. if (!GetUsrAttrIndexValidFlag()) {
  599. (void)AttrUtils::SetInt(op, ATTR_NAME_INDEX, index++);
  600. }
  601. GELOGD("Data op inputDesc size: %zu", op->GetAllInputsDesc().size());
  602. ge::GeTensorDesc tensor = op->GetInputDesc(0);
  603. string data_op_name = op->GetName();
  604. GELOGD("Data op name: %s", data_op_name.c_str());
  605. ge::GeShape data_shape;
  606. auto iter = omg_context_.input_dims.find(data_op_name);
  607. if (iter != omg_context_.input_dims.end()) {
  608. data_shape = ge::GeShape(iter->second);
  609. GELOGD("Data op get shape from Context.");
  610. } else {
  611. data_shape = tensor.GetShape();
  612. GELOGD("Data op get shape from InputDesc in ge ir graph.");
  613. }
  614. // If user point input format, do work for all data ops; else do according to tensor_desc
  615. auto data_format = omg_context_.format != domi::DOMI_TENSOR_ND ?
  616. ge::TypeUtils::DomiFormatToFormat(omg_context_.format) : tensor.GetFormat();
  617. ge::DataType data_type = tensor.GetDataType();
  618. string data_type_str = ge::TypeUtils::DataTypeToSerialString(data_type);
  619. GELOGD("Data op get data type:%s from InputDesc in ge ir graph.", data_type_str.c_str());
  620. std::vector<std::pair<int64_t, int64_t>> shape_range;
  621. if (tensor.GetShapeRange(shape_range) != GRAPH_SUCCESS) {
  622. GELOGE(FAILED, "[Creat][Input] Data op [%s] get shape range failed.", data_op_name.c_str());
  623. return FAILED;
  624. }
  625. ge::GeTensor inputTensor;
  626. ge::GeTensorDesc desc(data_shape, ge::Format(data_format), data_type);
  627. if (desc.SetShapeRange(shape_range) != GRAPH_SUCCESS) {
  628. GELOGE(FAILED, "[Creat][Input] Data op [%s] set shape range failed.", data_op_name.c_str());
  629. return FAILED;
  630. }
  631. inputTensor.SetTensorDesc(desc);
  632. inputs.push_back(inputTensor);
  633. }
  634. }
  635. GELOGD("CreateInputsForIRBuild, inputs size: %zu", inputs.size());
  636. return GRAPH_SUCCESS;
  637. }
  638. graphStatus Impl::BuildModel(const Graph &graph, const std::map<std::string, std::string> &options,
  639. ModelBufferData &model) {
  640. // 1. init GeGenerator with user optios
  641. graphStatus ret = Init(graph, options);
  642. if (ret != GRAPH_SUCCESS) {
  643. GELOGE(ret, "[Init][GeGenerator]Build ir model Init failed!");
  644. return ret;
  645. }
  646. // 2. construct input
  647. std::vector<GeTensor> inputs;
  648. if (!omg_context_.is_dynamic_input) { // if dynamic input , no need to creat inputs
  649. ret = CreateInputsForIRBuild(graph, inputs);
  650. if (ret != GRAPH_SUCCESS) {
  651. GELOGE(ret, "[Create][InputsForIRBuild] failed!");
  652. return ret;
  653. }
  654. }
  655. // 3. build IR model
  656. ret = generator_.GenerateOnlineModel(graph, inputs, model);
  657. if (ret != GRAPH_SUCCESS) {
  658. GELOGE(ret, "[Generate][OnlineModel] failed!");
  659. return ret;
  660. }
  661. return GRAPH_SUCCESS;
  662. }
  663. graphStatus Impl::InitDomiOmgContext(const string &input_shape, const string &input_format, bool is_dynamic_input) {
  664. // Clear omgcontext data first
  665. omg_context_.input_dims.clear();
  666. omg_context_.user_input_dims.clear();
  667. omg_context_.is_dynamic_input = is_dynamic_input;
  668. // the default value is ND
  669. omg_context_.format = domi::DOMI_TENSOR_ND;
  670. if (!input_format.empty()) {
  671. auto iter = ge::input_format_str_to_geformat.find(input_format);
  672. if (iter != ge::input_format_str_to_geformat.end()) {
  673. omg_context_.format = iter->second;
  674. } else {
  675. GELOGE(GRAPH_PARAM_INVALID,
  676. "[Check][Param:InputForamt] %s not support , expect ND/NCHW/NHWC/CHWN/NC1HWC0/NHWC1C0.",
  677. input_format.c_str());
  678. return GRAPH_PARAM_INVALID;
  679. }
  680. }
  681. // Input is empty, do not process
  682. if (input_shape.empty()) {
  683. return GRAPH_SUCCESS;
  684. }
  685. if (!ParseInputShape(input_shape, omg_context_.input_dims, omg_context_.user_input_dims, is_dynamic_input)) {
  686. GELOGE(GRAPH_PARAM_INVALID, "[Parse][InputShape:InputShape] Failed, shape: %s", input_shape.c_str());
  687. return GRAPH_PARAM_INVALID;
  688. }
  689. return GRAPH_SUCCESS;
  690. }
  691. graphStatus aclgrphBuildModel(const ge::Graph &graph, const std::map<std::string, std::string> &build_options,
  692. ModelBufferData &model) {
  693. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  694. GELOGD("Enter aclmdlBuildModel process!");
  695. Impl builder;
  696. return builder.BuildModel(graph, build_options, model);
  697. }
  698. graphStatus aclgrphBuildModel(const ge::Graph &graph, const std::map<AscendString, AscendString> &build_options,
  699. ModelBufferData &model) {
  700. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  701. GELOGD("Enter aclmdlBuildModel process!");
  702. std::map<std::string, std::string> tmp_build_options;
  703. for (auto &option : build_options) {
  704. if (option.first.GetString() == nullptr || option.second.GetString() == nullptr) {
  705. GELOGE(GRAPH_FAILED, "[Check][Options]AclgrphBuildInitialize option is nullptr.");
  706. return GRAPH_FAILED;
  707. }
  708. std::string key = option.first.GetString();
  709. std::string val = option.second.GetString();
  710. tmp_build_options[key] = val;
  711. }
  712. Impl builder;
  713. return builder.BuildModel(graph, tmp_build_options, model);
  714. }
  715. graphStatus aclgrphSaveModel(const string &output_file, const ModelBufferData &model) {
  716. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  717. GELOGD("Enter aclmdlSaveModel process!");
  718. if (model.data.get() == nullptr || model.length == 0) {
  719. GELOGE(GRAPH_PARAM_INVALID, "[Check][ModelBufferData] model is illegal");
  720. return GRAPH_PARAM_INVALID;
  721. }
  722. return FileSaver::SaveToFile((output_file + ".om"), reinterpret_cast<void *>(model.data.get()),
  723. static_cast<uint32_t>(model.length));
  724. }
  725. graphStatus aclgrphSaveModel(const char *output_file, const ModelBufferData &model) {
  726. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  727. GELOGD("Enter aclmdlSaveModel process!");
  728. if (model.data.get() == nullptr || model.length == 0) {
  729. GELOGE(GRAPH_PARAM_INVALID, "[Check][ModelBufferData]model is illegal");
  730. return GRAPH_PARAM_INVALID;
  731. }
  732. if (output_file == nullptr) {
  733. GELOGE(GRAPH_PARAM_INVALID, "[Check][OutputFile]file is nullptr.");
  734. return GRAPH_PARAM_INVALID;
  735. }
  736. std::string str_output_file = output_file;
  737. return FileSaver::SaveToFile((str_output_file + ".om"), reinterpret_cast<void *>(model.data.get()),
  738. static_cast<uint32_t>(model.length));
  739. }
  740. graphStatus aclgrphGetIRVersion(int *major_version, int *minor_version, int *patch_version) {
  741. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  742. GELOGD("Enter aclgrphGetIRVersion process!");
  743. GE_CHECK_NOTNULL(major_version);
  744. GE_CHECK_NOTNULL(minor_version);
  745. GE_CHECK_NOTNULL(patch_version);
  746. *major_version = IR_MAJOR_VERSION;
  747. *minor_version = IR_MINOR_VERSION;
  748. *patch_version = IR_PATCH_VERSION;
  749. return GRAPH_SUCCESS;
  750. }
  751. graphStatus aclgrphDumpGraph(const ge::Graph &graph, const char *file, const size_t len) {
  752. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  753. GE_CHECK_NOTNULL(file);
  754. if (len > PATH_MAX || len != strlen(file) || strlen(file) == 0) {
  755. GELOGE(GRAPH_PARAM_INVALID, "[Check][FilePath]file invalid.");
  756. return GRAPH_PARAM_INVALID;
  757. }
  758. auto compute_graph = GraphUtils::GetComputeGraph(graph);
  759. GE_CHECK_NOTNULL(compute_graph);
  760. string full_path(file, len);
  761. for (size_t i = 0; i < len; i++) {
  762. if (full_path[i] == '\\') {
  763. full_path.replace(i, 1, "/");
  764. }
  765. }
  766. string suffix;
  767. string file_path;
  768. int pos = full_path.rfind("/");
  769. if (pos != -1) {
  770. suffix = full_path.substr(pos + 1, -1);
  771. file_path = full_path.substr(0, pos);
  772. } else {
  773. suffix = full_path;
  774. file_path = "./";
  775. }
  776. if (suffix.empty()) {
  777. suffix = compute_graph->GetName();
  778. if (suffix.empty()) {
  779. suffix = "graph";
  780. }
  781. }
  782. char path[PATH_MAX] = {0};
  783. if (realpath(file_path.c_str(), path) == nullptr) {
  784. GELOGE(GRAPH_PARAM_INVALID, "[Check][DumpFile] path:%s is invalid.", file);
  785. return GRAPH_PARAM_INVALID;
  786. }
  787. GraphUtils::DumpGEGrph(compute_graph, string(path), suffix);
  788. GraphUtils::DumpGrphToOnnx(*compute_graph, string(path), suffix);
  789. uint64_t i = 0;
  790. for (const auto &sub_graph_func : compute_graph->GetAllSubgraphs()) {
  791. auto sub_graph_func_name = suffix + std::string("_sub_graph_") + std::to_string(i++);
  792. GraphUtils::DumpGEGrph(sub_graph_func, string(path), sub_graph_func_name);
  793. GraphUtils::DumpGrphToOnnx(*sub_graph_func, string(path), sub_graph_func_name);
  794. }
  795. return GRAPH_SUCCESS;
  796. }
  797. graphStatus aclgrphGenerateForOp(const AscendString &op_type, const vector<TensorDesc> &inputs,
  798. const vector<TensorDesc> &outputs, Graph &graph) {
  799. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  800. auto op_type_str = std::string(op_type.GetString());
  801. auto op_name = op_type_str + "_" + std::to_string(ge::GetCurrentTimestamp());
  802. auto op_desc = ge::MakeShared<ge::OpDesc>(op_name, op_type_str);
  803. GE_CHECK_NOTNULL(op_desc);
  804. // convert input tensordesc to getensor
  805. std::vector<ge::GeTensor> input_tensors;
  806. for (const auto &input : inputs) {
  807. ge::GeTensorDesc tensor_desc(ge::GeShape(input.GetShape().GetDims()), input.GetFormat(), input.GetDataType());
  808. tensor_desc.SetOriginFormat(input.GetFormat());
  809. ge::TensorUtils::SetRealDimCnt(tensor_desc, static_cast<uint32_t>(input.GetShape().GetDims().size()));
  810. ge::TensorUtils::SetInputTensor(tensor_desc, true);
  811. ge::TensorUtils::SetOutputTensor(tensor_desc, false);
  812. if (op_desc->AddInputDesc(tensor_desc) != ge::GRAPH_SUCCESS) {
  813. GELOGE(ge::FAILED, "[Add][InputDesc] fail.");
  814. return ge::FAILED;
  815. }
  816. input_tensors.emplace_back(tensor_desc);
  817. }
  818. // convert output tensordesc to getensor
  819. std::vector<ge::GeTensor> output_tensors;
  820. for (const auto &output : outputs) {
  821. ge::GeTensorDesc tensor_desc(ge::GeShape(output.GetShape().GetDims()), output.GetFormat(), output.GetDataType());
  822. tensor_desc.SetOriginFormat(output.GetFormat());
  823. ge::TensorUtils::SetRealDimCnt(tensor_desc, static_cast<uint32_t>(output.GetShape().GetDims().size()));
  824. ge::TensorUtils::SetInputTensor(tensor_desc, false);
  825. ge::TensorUtils::SetOutputTensor(tensor_desc, true);
  826. (void)op_desc->AddOutputDesc(tensor_desc);
  827. output_tensors.emplace_back(tensor_desc);
  828. }
  829. // call api to get graph
  830. ge::GeGenerator generator;
  831. std::string graph_name = ge::CurrentTimeInStr() + "_graph";
  832. if (generator.BuildSingleOpGraph(op_desc, input_tensors, output_tensors, graph_name, graph) != ge::SUCCESS) {
  833. GELOGE(GRAPH_FAILED, "[Make][Graph] fail.");
  834. return GRAPH_FAILED;
  835. }
  836. return GRAPH_SUCCESS;
  837. }
  838. static std::string AttrTypeToSerialString(aclgrphAttrType attr_type) {
  839. auto it = kAttrTypeToStringMap.find(attr_type);
  840. if (it != kAttrTypeToStringMap.end()) {
  841. return it->second;
  842. } else {
  843. REPORT_INNER_ERROR("E19999", "attr_type:%u is not support", attr_type);
  844. GELOGE(GRAPH_FAILED, "[Check][AclgrphAttrType] attr_type not support %u", attr_type);
  845. return "UNDEFINED";
  846. }
  847. }
  848. graphStatus aclgrphSetOpAttr(Graph &graph, aclgrphAttrType attr_type, const char *cfg_path) {
  849. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  850. auto compute_graph = GraphUtils::GetComputeGraph(graph);
  851. GE_CHECK_NOTNULL(compute_graph);
  852. if (cfg_path == nullptr) {
  853. return GRAPH_SUCCESS;
  854. }
  855. auto iter = kAttrTypeFuncMap.find(attr_type);
  856. if (iter == kAttrTypeFuncMap.end()) {
  857. GELOGE(GRAPH_FAILED, "[Check][AclgrphAttrType]%s is not support", AttrTypeToSerialString(attr_type).c_str());
  858. return GRAPH_FAILED;
  859. }
  860. std::string path = cfg_path;
  861. return iter->second(compute_graph, path);
  862. }
  863. } // namespace ge

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