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_api.cc 30 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
4 years ago
5 years ago
5 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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 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
5 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
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  1. /**
  2. * Copyright 2019-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_api.h"
  17. #include <iostream>
  18. #include <malloc.h>
  19. #include "framework/common/debug/log.h"
  20. #include "framework/common/debug/ge_log.h"
  21. #include "common/ge/datatype_util.h"
  22. #include "proto/ge_api.pb.h"
  23. #include "graph/model_serialize.h"
  24. #include "graph/detail/model_serialize_imp.h"
  25. #include "graph/utils/tensor_adapter.h"
  26. #include "init/gelib.h"
  27. #include "session/session_manager.h"
  28. #include "graph/opsproto_manager.h"
  29. #include "graph/utils/type_utils.h"
  30. #include "graph/manager/util/rt_context_util.h"
  31. #include "common/ge_call_wrapper.h"
  32. #include "register/op_registry.h"
  33. #include "common/ge/tbe_plugin_manager.h"
  34. #include "common/util/error_manager/error_manager.h"
  35. #include "toolchain/plog.h"
  36. #include "ir_build/option_utils.h"
  37. using domi::OpRegistry;
  38. using std::map;
  39. using std::string;
  40. using std::vector;
  41. namespace {
  42. const int32_t kMaxStrLen = 128;
  43. } // namespace
  44. static bool g_ge_initialized = false;
  45. static std::mutex g_ge_release_mutex; // GEFinalize and ~Session use
  46. static std::shared_ptr<ge::SessionManager> g_session_manager;
  47. namespace ge {
  48. void GetOpsProtoPath(std::string &opsproto_path) {
  49. GELOGI("Enter get ops proto path schedule");
  50. const char *path_env = std::getenv("ASCEND_OPP_PATH");
  51. if (path_env != nullptr) {
  52. std::string path = path_env;
  53. opsproto_path = (path + "/op_proto/custom/" + ":") + (path + "/op_proto/built-in/");
  54. GELOGI("Get opsproto so path from env: %s", path.c_str());
  55. return;
  56. }
  57. std::string path_base = PluginManager::GetPath();
  58. GELOGI("path_base is %s", path_base.c_str());
  59. path_base = path_base.substr(0, path_base.rfind('/'));
  60. path_base = path_base.substr(0, path_base.rfind('/') + 1);
  61. opsproto_path = (path_base + "ops/op_proto/custom/" + ":") + (path_base + "ops/op_proto/built-in/");
  62. }
  63. Status CheckOptionsValid(const std::map<string, string> &options) {
  64. // check job_id is valid
  65. auto job_id_iter = options.find(OPTION_EXEC_JOB_ID);
  66. if (job_id_iter != options.end()) {
  67. if (job_id_iter->second.length() > kMaxStrLen) {
  68. GELOGE(PARAM_INVALID, "[Check][JobId]Failed, the job_id [%s] string length: %zu > max string length: %d",
  69. job_id_iter->second.c_str(), job_id_iter->second.length(), kMaxStrLen);
  70. REPORT_INPUT_ERROR("E10051", std::vector<std::string>({"id", "length"}),
  71. std::vector<std::string>({job_id_iter->second,
  72. std::to_string(kMaxStrLen)}));
  73. return FAILED;
  74. }
  75. }
  76. // check modify_mixlist is valid
  77. if (ge::CheckModifyMixlistParamValid(options) != ge::SUCCESS) {
  78. return FAILED;
  79. }
  80. return SUCCESS;
  81. }
  82. // Initialize GE, prepare for execution, call GELib::Initialize
  83. Status GEInitializeImpl(const std::map<string, string> &options) {
  84. ErrorManager::GetInstance().GenWorkStreamIdDefault();
  85. GELOGT(TRACE_INIT, "GEInitialize start");
  86. std::string path_base = ge::GELib::GetPath();
  87. auto ret = ErrorManager::GetInstance().Init(path_base);
  88. if (ret != SUCCESS) {
  89. GELOGE(GE_CLI_INIT_FAILED, "[Init][PathBase]Init failed when pass param path_base:%s", path_base.c_str());
  90. REPORT_CALL_ERROR("E19999", "Init failed when pass param path_base:%s", path_base.c_str());
  91. return ret;
  92. }
  93. // 0.check init status
  94. if (g_ge_initialized) {
  95. GELOGW("GEInitialize is called more than once");
  96. return SUCCESS;
  97. }
  98. ErrorManager::GetInstance().SetStage(error_message::kInitialize, error_message::kOpsProtoInit);
  99. // Load OpsProto lib plugin
  100. std::string opsproto_path;
  101. GetOpsProtoPath(opsproto_path);
  102. OpsProtoManager *manager = OpsProtoManager::Instance();
  103. std::map<string, string> option_tmp;
  104. option_tmp.emplace(std::pair<string, string>(string("ge.opsProtoLibPath"), opsproto_path));
  105. GE_TIMESTAMP_START(GEInitialize);
  106. bool is_proto_init = manager->Initialize(option_tmp);
  107. GE_TIMESTAMP_END(GEInitialize, "GEInitialize::ManagerInitialize");
  108. if (!is_proto_init) {
  109. GELOGE(GE_CLI_INIT_FAILED, "[Init][OpsProtoPath]Loading OpsProto lib plugin failed, OpsProtoPath:%s invalid.",
  110. opsproto_path.c_str());
  111. REPORT_CALL_ERROR("E19999", "Loading OpsProto lib plugin failed, OpsProtoPath:%s invalid", opsproto_path.c_str());
  112. return FAILED;
  113. }
  114. ErrorManager::GetInstance().SetStage(error_message::kInitialize, error_message::kOther);
  115. // check options is valid
  116. GE_TIMESTAMP_START(CheckOptionsValid);
  117. if (CheckOptionsValid(options) != SUCCESS) {
  118. return FAILED;
  119. }
  120. GE_TIMESTAMP_END(CheckOptionsValid, "GEInitialize::CheckOptionsValid");
  121. ErrorManager::GetInstance().SetStage(error_message::kInitialize, error_message::kOpsProtoInit);
  122. GE_TIMESTAMP_START(InitPreparation);
  123. TBEPluginManager::Instance().InitPreparation(options);
  124. GE_TIMESTAMP_END(InitPreparation, "GEInitialize::InitPreparation");
  125. // call Initialize
  126. GELOGT(TRACE_RUNNING, "Initializing environment");
  127. ErrorManager::GetInstance().SetStage(error_message::kInitialize, error_message::kOther);
  128. GE_TIMESTAMP_START(GELibInitialize);
  129. ret = ge::GELib::Initialize(options);
  130. GE_TIMESTAMP_END(GELibInitialize, "GEInitialize::GELibInitialize");
  131. if (ret != SUCCESS) {
  132. GELOGE(GE_CLI_INIT_FAILED, "[Init][GELib]Failed, error code = %u", ret);
  133. return FAILED;
  134. }
  135. ErrorManager::GetInstance().SetStage(error_message::kInitialize, error_message::kOther);
  136. GELOGI("sessionManager initial.");
  137. GE_TIMESTAMP_START(SessionManagerInitialize);
  138. g_session_manager = MakeShared<ge::SessionManager>();
  139. if (g_session_manager == nullptr) {
  140. GELOGE(GE_CLI_INIT_FAILED, "[Init][Create]SessionManager failed");
  141. return FAILED;
  142. }
  143. ret = g_session_manager->Initialize(options);
  144. GE_TIMESTAMP_END(SessionManagerInitialize, "InnerInitialize::SessionManagerInitialize");
  145. if (ret != SUCCESS) {
  146. GELOGE(ret, "[Init][SessionManager] GE session manager initial failed.");
  147. REPORT_CALL_ERROR("E19999", "SessionManager initialize failed.");
  148. return ret;
  149. }
  150. // 7.check return status, return
  151. if (!g_ge_initialized) {
  152. // Initialize success, first time calling initialize
  153. g_ge_initialized = true;
  154. }
  155. GELOGT(TRACE_STOP, "GEInitialize finished");
  156. return ret;
  157. }
  158. // Initialize GE, prepare for execution, call GELib::Initialize
  159. Status GEInitialize(const std::map<string, string> &options) {
  160. ErrorManager::GetInstance().SetStage(error_message::kInitialize, error_message::kOther);
  161. if (DlogReportInitialize() != SUCCESS) {
  162. GELOGW("Dlog report device log initialize failed.");
  163. }
  164. return GEInitializeImpl(options);
  165. }
  166. Status GEInitialize(const std::map<AscendString, AscendString> &options) {
  167. ErrorManager::GetInstance().SetStage(error_message::kInitialize, error_message::kOther);
  168. std::map<std::string, std::string> str_options;
  169. for (auto &option : options) {
  170. if (option.first.GetString() == nullptr || option.second.GetString() == nullptr) {
  171. GELOGE(FAILED, "[Check][Param]Options invalid, first or second option is nullptr.");
  172. REPORT_INNER_ERROR("E19999", "Check parameter's options invalid, the first or second option is nullptr.");
  173. return FAILED;
  174. }
  175. std::string key = option.first.GetString();
  176. std::string val = option.second.GetString();
  177. str_options[key] = val;
  178. }
  179. if (DlogReportInitialize() != SUCCESS) {
  180. GELOGW("Dlog report device log initialize failed.");
  181. }
  182. return GEInitializeImpl(str_options);
  183. }
  184. // GE finalize, releasing all resources
  185. Status GEFinalize() {
  186. std::lock_guard<std::mutex> lock(g_ge_release_mutex);
  187. // check init status
  188. if (!g_ge_initialized) {
  189. GELOGW("[FINAL][FINAL]GEFinalize is called before GEInitialize");
  190. return SUCCESS;
  191. }
  192. ErrorManager::GetInstance().SetStage(error_message::kFinalize, error_message::kFinalize);
  193. ErrorManager::GetInstance().GenWorkStreamIdDefault();
  194. GELOGT(TRACE_INIT, "GEFinalize start");
  195. GELOGI("SessionManager finalization.");
  196. if (g_session_manager != nullptr) {
  197. (void)g_session_manager->Finalize(); // always success.
  198. }
  199. // call Finalize
  200. Status ret = SUCCESS;
  201. Status middle_ret;
  202. GELOGT(TRACE_RUNNING, "Finalizing environment");
  203. std::shared_ptr<GELib> instancePtr = GELib::GetInstance();
  204. if (instancePtr != nullptr) {
  205. middle_ret = instancePtr->Finalize();
  206. GELOGI("GEFinalize finalize gelib ret=%u", middle_ret);
  207. if (middle_ret != SUCCESS) {
  208. ret = middle_ret;
  209. }
  210. }
  211. middle_ret = TBEPluginManager::Instance().Finalize();
  212. if (middle_ret != SUCCESS) {
  213. ret = middle_ret;
  214. }
  215. if (g_ge_initialized && ret == SUCCESS) {
  216. // Unified destruct rt_context
  217. RtContextUtil::GetInstance().DestroyAllRtContexts();
  218. g_ge_initialized = false;
  219. }
  220. // to avoid memory fragment, use malloc_trim to back free stack to system
  221. malloc_trim(0);
  222. if (DlogReportFinalize() != SUCCESS) {
  223. GELOGW("Dlog report device log finalize failed.");
  224. }
  225. GELOGT(TRACE_STOP, "GEFinalize finished");
  226. return ret;
  227. }
  228. std::string GEGetErrorMsg() {
  229. return ErrorManager::GetInstance().GetErrorMessage();
  230. }
  231. std::string GEGetWarningMsg() {
  232. return ErrorManager::GetInstance().GetWarningMessage();
  233. }
  234. // Initialize session,which calls innerSession
  235. Session::Session(const std::map<string, string> &options) {
  236. ErrorManager::GetInstance().SetStage(error_message::kInitialize, error_message::kOther);
  237. GELOGT(TRACE_INIT, "Start to construct session.");
  238. ErrorManager::GetInstance().GenWorkStreamIdDefault();
  239. // check init status
  240. sessionId_ = 0;
  241. if (!g_ge_initialized) {
  242. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  243. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  244. return;
  245. }
  246. GELOGT(TRACE_RUNNING, "Creating session");
  247. uint64_t session_id = 0;
  248. Status ret = g_session_manager->CreateSession(options, session_id);
  249. GELOGT(TRACE_RUNNING, "Session id is %lu", session_id);
  250. // check return status, return, update session id if success
  251. if (ret == SUCCESS) {
  252. sessionId_ = session_id;
  253. } else {
  254. GELOGE(ret, "[Construct][Session]Failed, error code:%u.", ret);
  255. return;
  256. }
  257. GELOGT(TRACE_STOP, "Session Constructor finished");
  258. }
  259. Session::Session(const std::map<AscendString, AscendString> &options) {
  260. ErrorManager::GetInstance().SetStage(error_message::kInitialize, error_message::kOther);
  261. GELOGT(TRACE_INIT, "Session Constructor start");
  262. ErrorManager::GetInstance().GenWorkStreamIdDefault();
  263. // check init status
  264. sessionId_ = 0;
  265. if (!g_ge_initialized) {
  266. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  267. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  268. return;
  269. }
  270. // call Initialize
  271. GELOGT(TRACE_RUNNING, "Creating session");
  272. std::map<std::string, std::string> str_options;
  273. for (auto &option : options) {
  274. if (option.first.GetString() == nullptr || option.second.GetString() == nullptr) {
  275. GELOGE(FAILED, "[Construct][Session]Failed, the first or second option is nullptr.");
  276. REPORT_INNER_ERROR("E19999", "Creating session's options invalid, the first or second option is nullptr.");
  277. return;
  278. }
  279. std::string key = option.first.GetString();
  280. std::string val = option.second.GetString();
  281. str_options[key] = val;
  282. }
  283. uint64_t session_id = 0;
  284. Status ret = g_session_manager->CreateSession(str_options, session_id);
  285. GELOGT(TRACE_RUNNING, "Session id is %lu", session_id);
  286. // check return status, return, update session id if success
  287. if (ret == SUCCESS) {
  288. sessionId_ = session_id;
  289. } else {
  290. GELOGE(ret, "[Construct][Session]Failed, error code:%u.", ret);
  291. REPORT_CALL_ERROR("E19999", "Construct session failed, error code:%u.", ret);
  292. return;
  293. }
  294. GELOGT(TRACE_STOP, "Session Constructor finished");
  295. }
  296. // session destructor
  297. Session::~Session() {
  298. ErrorManager::GetInstance().SetStage(error_message::kFinalize, error_message::kFinalize);
  299. GELOGT(TRACE_INIT, "Start to destruct session.");
  300. // 0.check init status
  301. if (!g_ge_initialized) {
  302. GELOGW("GE is not yet initialized or is finalized.");
  303. return;
  304. }
  305. Status ret = FAILED;
  306. std::lock_guard<std::mutex> lock(g_ge_release_mutex);
  307. try {
  308. uint64_t session_id = sessionId_;
  309. // call DestroySession
  310. GELOGT(TRACE_RUNNING, "Session id is %lu", session_id);
  311. GELOGT(TRACE_RUNNING, "Destroying session");
  312. ret = g_session_manager->DestroySession(session_id);
  313. } catch (google::protobuf::FatalException &e) {
  314. GELOGE(GE_CLI_SESS_DESTROY_FAILED, "[Destruct][Session]Failed because get fatalException.");
  315. REPORT_CALL_ERROR("E19999", "Destruct session failed, get fatal exception");
  316. }
  317. // check return status, return, update session id if success
  318. if (ret != SUCCESS) {
  319. GELOGE(ret, "[Destruct][Session]Failed, error code:%u.", ret);
  320. REPORT_CALL_ERROR("E19999", "Destruct session failed, error code:%u.", ret);
  321. }
  322. GELOGT(TRACE_STOP, "Session Destructor finished");
  323. }
  324. // Add Graph
  325. Status Session::AddGraph(uint32_t graph_id, const Graph &graph) {
  326. std::map<std::string, std::string> options;
  327. return AddGraph(graph_id, graph, options);
  328. }
  329. // Add Graph
  330. Status Session::AddGraph(uint32_t graph_id, const Graph &graph, const std::map<std::string, std::string> &options) {
  331. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  332. GELOGT(TRACE_INIT, "Start to add graph in Session. graph_id: %u, session_id: %lu.", graph_id, sessionId_);
  333. ErrorManager::GetInstance().GenWorkStreamIdBySessionGraph(sessionId_, graph_id);
  334. if (!g_ge_initialized) {
  335. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  336. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  337. return FAILED;
  338. }
  339. GELOGD("Adding graph to session");
  340. Status ret = g_session_manager->AddGraph(sessionId_, graph_id, graph, options);
  341. if (ret != SUCCESS) {
  342. GELOGE(ret, "[Add][Graph]Failed, error code:%u, session_id:%lu, graph_id:%u.", ret, sessionId_, graph_id);
  343. return FAILED;
  344. }
  345. GELOGD("AddGraph finished in Session.");
  346. return ret;
  347. }
  348. //Add Graph
  349. Status Session::AddGraph(uint32_t graph_id, const Graph &graph, const std::map<AscendString, AscendString> &options) {
  350. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  351. GELOGT(TRACE_INIT, "Start to add graph in Session. graph_id: %u, session_id: %lu.", graph_id, sessionId_);
  352. ErrorManager::GetInstance().GenWorkStreamIdBySessionGraph(sessionId_, graph_id);
  353. if (!g_ge_initialized) {
  354. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  355. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  356. return FAILED;
  357. }
  358. GELOGD("Adding graph to session");
  359. std::map<std::string, std::string> str_options;
  360. for (auto &option : options) {
  361. if (option.first.GetString() == nullptr || option.second.GetString() == nullptr) {
  362. GELOGE(FAILED, "[Add][Graph]Failed, the first or second option is nullptr.");
  363. REPORT_INNER_ERROR("E19999", "Add Graph Failed, the first or second option is nullptr.");
  364. return FAILED;
  365. }
  366. std::string key = option.first.GetString();
  367. std::string val = option.second.GetString();
  368. str_options[key] = val;
  369. }
  370. Status ret = g_session_manager->AddGraph(sessionId_, graph_id, graph, str_options);
  371. if (ret != SUCCESS) {
  372. GELOGE(ret, "[Add][Graph]Failed, error code:%u, session_id:%lu, graph_id:%u.", ret, sessionId_, graph_id);
  373. return FAILED;
  374. }
  375. GELOGD("AddGraph finished in Session.");
  376. return ret;
  377. }
  378. Status Session::AddGraphWithCopy(uint32_t graph_id, const Graph &graph) {
  379. std::map<AscendString, AscendString> options;
  380. return AddGraphWithCopy(graph_id, graph, options);
  381. }
  382. // Add Graph With Copy
  383. Status Session::AddGraphWithCopy(uint32_t graph_id, const Graph &graph,
  384. const std::map<AscendString, AscendString> &options) {
  385. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  386. GELOGT(TRACE_INIT, "Start to add graph in Session. graph_id: %u, session_id: %lu.", graph_id, sessionId_);
  387. ErrorManager::GetInstance().GenWorkStreamIdBySessionGraph(sessionId_, graph_id);
  388. if (!g_ge_initialized) {
  389. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  390. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  391. return FAILED;
  392. }
  393. std::map<std::string, std::string> str_options;
  394. for (auto it = options.begin(); it != options.end(); ++it) {
  395. str_options.insert({it->first.GetString(), it->second.GetString()});
  396. }
  397. GELOGD("Adding graph to session");
  398. Status ret = g_session_manager->AddGraphWithCopy(sessionId_, graph_id, graph, str_options);
  399. if (ret != SUCCESS) {
  400. GELOGE(ret, "[Add][Graph]Failed, error code:%u, session_id:%lu, graph_id:%u.", ret, sessionId_, graph_id);
  401. return FAILED;
  402. }
  403. GELOGD("AddGraph finished in Session.");
  404. return ret;
  405. }
  406. // Remove Graph
  407. Status Session::RemoveGraph(uint32_t graph_id) {
  408. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  409. GELOGT(TRACE_INIT, "Session RemoveGraph start");
  410. ErrorManager::GetInstance().GenWorkStreamIdBySessionGraph(sessionId_, graph_id);
  411. // call RemoveGraph
  412. if (!g_ge_initialized) {
  413. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  414. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  415. return FAILED;
  416. }
  417. GELOGT(TRACE_RUNNING, "Removing Graph from session");
  418. Status ret = g_session_manager->RemoveGraph(sessionId_, graph_id);
  419. // check return status, return
  420. if (ret != SUCCESS) {
  421. GELOGE(ret, "[Remove][Graph]Failed, error code:%u, session_id:%lu, graph_id:%u.", ret, sessionId_, graph_id);
  422. REPORT_CALL_ERROR("E19999", "Remove graph failed, error code:%u, session_id:%lu, graph_id:%u",
  423. ret, sessionId_, graph_id);
  424. return FAILED;
  425. }
  426. GELOGT(TRACE_STOP, "Session RemoveGraph finished");
  427. return ret;
  428. }
  429. // Print Output Result
  430. void PrintOutputResult(std::vector<Tensor> &outputs) {
  431. if (outputs.empty() || outputs[0].GetData() == nullptr) {
  432. GELOGW("outputs is empty or data is nullptr.");
  433. return;
  434. }
  435. size_t out_buf_size = outputs[0].GetSize();
  436. TensorDesc desc(outputs[0].GetTensorDesc());
  437. DataType data_type = desc.GetDataType();
  438. auto iter = CONST_OPDATA_TYPE_SIZE_MAP.find(data_type);
  439. if (iter == CONST_OPDATA_TYPE_SIZE_MAP.end()) {
  440. GELOGI("DataType %s has not defined size", TypeUtils::DataTypeToSerialString(data_type).c_str());
  441. return;
  442. }
  443. size_t length = CONST_OPDATA_TYPE_SIZE_MAP[data_type];
  444. for (size_t i = 0; i < 10 && i < (out_buf_size / length); ++i) { // take first 10 at most
  445. switch (data_type) {
  446. case DT_BOOL:
  447. case DT_INT8:
  448. case DT_UINT8:
  449. GELOGI("output data[%zu]=%d", i, *(reinterpret_cast<int8_t *>(outputs[0].GetData()) + i));
  450. break;
  451. case DT_INT16:
  452. case DT_UINT16:
  453. GELOGI("output data[%zu]=%d", i, *(reinterpret_cast<int16_t *>(outputs[0].GetData()) + i));
  454. break;
  455. case DT_INT32:
  456. case DT_UINT32:
  457. GELOGI("output data[%zu]=%d", i, *(reinterpret_cast<int32_t *>(outputs[0].GetData()) + i));
  458. break;
  459. case DT_INT64:
  460. case DT_UINT64:
  461. GELOGI("output data[%zu]=%ld", i, *(reinterpret_cast<int64_t *>(outputs[0].GetData()) + i));
  462. break;
  463. case DT_FLOAT:
  464. GELOGI("output data[%zu]=%f", i, *(reinterpret_cast<float *>(outputs[0].GetData()) + i));
  465. break;
  466. case DT_DOUBLE:
  467. GELOGI("output data[%zu]=%lf", i, *(reinterpret_cast<double *>(outputs[0].GetData()) + i));
  468. break;
  469. default:
  470. GELOGI("Output datatype %s is not supported.", TypeUtils::DataTypeToSerialString(data_type).c_str());
  471. return;
  472. }
  473. }
  474. }
  475. // Run Graph
  476. Status Session::RunGraph(uint32_t graph_id, const std::vector<Tensor> &inputs, std::vector<Tensor> &outputs) {
  477. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  478. GELOGT(TRACE_INIT, "Session RunGraph start");
  479. ErrorManager::GetInstance().GenWorkStreamIdBySessionGraph(sessionId_, graph_id);
  480. if (!g_ge_initialized) {
  481. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  482. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  483. return FAILED;
  484. }
  485. // call RunGraph
  486. GELOGT(TRACE_RUNNING, "Running Graph");
  487. Status ret = g_session_manager->RunGraph(sessionId_, graph_id, inputs, outputs);
  488. // check return status
  489. if (ret != SUCCESS) {
  490. GELOGE(ret, "[Run][Graph]Failed, error code:%u, session_id:%lu, graph_id:%u.", ret, sessionId_, graph_id);
  491. REPORT_CALL_ERROR("E19999", "Remove graph failed, error code:%u, session_id:%lu, graph_id:%u",
  492. ret, sessionId_, graph_id);
  493. return FAILED;
  494. }
  495. // print output
  496. if (outputs.size() > 0) {
  497. PrintOutputResult(outputs);
  498. }
  499. // return
  500. GELOGT(TRACE_STOP, "Session RunGraph finished");
  501. return ret;
  502. }
  503. // Run Graph with stream Asynchronously
  504. Status Session::RunGraphWithStreamAsync(uint32_t graph_id, void *stream, const std::vector<Tensor> &inputs,
  505. std::vector<Tensor> &outputs) {
  506. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  507. GELOGT(TRACE_INIT, "Start to run graph with stream async.");
  508. ErrorManager::GetInstance().GenWorkStreamIdBySessionGraph(sessionId_, graph_id);
  509. if (!g_ge_initialized) {
  510. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  511. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  512. return FAILED;
  513. }
  514. GELOGT(TRACE_RUNNING, "Run Graph Run graph with stream asyn.");
  515. Status ret = g_session_manager->RunGraphWithStreamAsync(sessionId_, graph_id, stream, inputs, outputs);
  516. if (ret != SUCCESS) {
  517. GELOGE(ret, "[Run][Graph]Run graph with stream asyn Failed,"
  518. "error code = %u, session id = %lu, graph id = %u, stream = %p.", ret, sessionId_, graph_id, stream);
  519. REPORT_CALL_ERROR("E19999", "[Run][Graph]Run graph with stream asyn failed, error code = %u, session id = %lu,"
  520. "graph id = %u, stream = %p.", ret, sessionId_, graph_id, stream);
  521. return FAILED;
  522. }
  523. GELOGT(TRACE_STOP, "Session run graph with stream async finished");
  524. return SUCCESS;
  525. }
  526. // Register Call Back
  527. Status Session::RegisterCallBackFunc(const std::string &key, const pCallBackFunc &callback) {
  528. ErrorManager::GetInstance().GenWorkStreamIdDefault();
  529. if (!g_ge_initialized) {
  530. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  531. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  532. return FAILED;
  533. }
  534. return g_session_manager->RegisterCallBackFunc(sessionId_, key, callback);
  535. }
  536. Status Session::RegisterCallBackFunc(const char *key, const session::pCallBackFunc &callback) {
  537. ErrorManager::GetInstance().GenWorkStreamIdDefault();
  538. if (!g_ge_initialized) {
  539. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  540. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  541. return FAILED;
  542. }
  543. std::string str_key;
  544. if (key != nullptr) {
  545. str_key = key;
  546. }
  547. return g_session_manager->RegisterCallBackFunc(sessionId_, str_key, callback);
  548. }
  549. // Build Graph
  550. Status Session::BuildGraph(uint32_t graph_id, const std::vector<InputTensorInfo> &inputs) {
  551. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  552. ErrorManager::GetInstance().GenWorkStreamIdBySessionGraph(sessionId_, graph_id);
  553. if (!g_ge_initialized) {
  554. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  555. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  556. return FAILED;
  557. }
  558. GELOGT(TRACE_RUNNING, "Building Graph");
  559. Status ret = g_session_manager->BuildGraph(sessionId_, graph_id, inputs);
  560. if (ret != SUCCESS) {
  561. GELOGE(ret, "[Build][Graph]Failed, error code:%u, session_id:%lu, graph_id:%u.", ret, sessionId_, graph_id);
  562. REPORT_CALL_ERROR("E19999", "Build graph failed , error code:%u, session_id:%lu, graph_id:%u",
  563. ret, sessionId_, graph_id);
  564. return FAILED;
  565. }
  566. return SUCCESS;
  567. }
  568. // Build Graph
  569. Status Session::BuildGraph(uint32_t graph_id, const std::vector<ge::Tensor> &inputs) {
  570. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  571. ErrorManager::GetInstance().GenWorkStreamIdBySessionGraph(sessionId_, graph_id);
  572. if (!g_ge_initialized) {
  573. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  574. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  575. return FAILED;
  576. }
  577. GELOGT(TRACE_RUNNING, "Building Graph");
  578. Status ret = g_session_manager->BuildGraph(sessionId_, graph_id, inputs);
  579. if (ret != SUCCESS) {
  580. GELOGE(ret, "[Build][Graph]Failed, error code:%u, session_id:%lu, graph_id:%u.", ret, sessionId_, graph_id);
  581. REPORT_CALL_ERROR("E19999", "Build graph failed , error code:%u, session_id:%lu, graph_id:%u",
  582. ret, sessionId_, graph_id);
  583. return FAILED;
  584. }
  585. return SUCCESS;
  586. }
  587. // Run Graph Asynchronously
  588. Status Session::RunGraphAsync(uint32_t graph_id, const std::vector<ge::Tensor> &inputs,
  589. RunAsyncCallback callback) {
  590. ErrorManager::GetInstance().SetStage(error_message::kModelExecute, error_message::kModelExecute);
  591. ErrorManager::GetInstance().GenWorkStreamIdBySessionGraph(sessionId_, graph_id);
  592. if (!g_ge_initialized) {
  593. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  594. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  595. return FAILED;
  596. }
  597. GELOGT(TRACE_RUNNING, "Run Graph Asynchronously");
  598. GELOGW(
  599. "The callback function will not be checked. Please ensure that the implementation of the function is trusted.");
  600. Status ret = g_session_manager->RunGraphAsync(sessionId_, graph_id, inputs, callback);
  601. if (ret != SUCCESS) {
  602. GELOGE(ret, "[Run][Graph]RunGraphAsync Failed, error code:%u, session_id:%lu, graph_id:%u.",
  603. ret, sessionId_, graph_id);
  604. REPORT_CALL_ERROR("E19999", "RunGraphAsync Failed, error code:%u, session_id:%lu, graph_id:%u",
  605. ret, sessionId_, graph_id);
  606. return FAILED;
  607. }
  608. return SUCCESS;
  609. }
  610. // Get Variables
  611. Status Session::GetVariables(const std::vector<std::string> &var_names, std::vector<Tensor> &var_values) {
  612. ErrorManager::GetInstance().SetStage(error_message::kModelExecute, error_message::kModelExecute);
  613. ErrorManager::GetInstance().GenWorkStreamIdDefault();
  614. if (!g_ge_initialized) {
  615. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  616. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  617. return FAILED;
  618. }
  619. GELOGT(TRACE_RUNNING, "Get Variables");
  620. Status ret = g_session_manager->GetVariables(sessionId_, var_names, var_values);
  621. if (ret != SUCCESS) {
  622. GELOGE(ret, "[Get][Variables]Failed, error code:%u, session_id:%lu.", ret, sessionId_);
  623. return FAILED;
  624. }
  625. return SUCCESS;
  626. }
  627. // Get Variables
  628. Status Session::GetVariables(const std::vector<AscendString> &var_names, std::vector<Tensor> &var_values) {
  629. ErrorManager::GetInstance().SetStage(error_message::kModelExecute, error_message::kModelExecute);
  630. ErrorManager::GetInstance().GenWorkStreamIdDefault();
  631. if (!g_ge_initialized) {
  632. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  633. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  634. return FAILED;
  635. }
  636. GELOGT(TRACE_RUNNING, "Get Variables");
  637. std::vector<ge::string> str_var_names;
  638. for (auto &var_name : var_names) {
  639. if (var_name.GetString() == nullptr) {
  640. GELOGE(FAILED, "[Get][Variable]Failed, variables' names are nullptr.");
  641. REPORT_INNER_ERROR("E19999", "GetVariables failed, variables' names are nullptr.");
  642. return FAILED;
  643. }
  644. str_var_names.emplace_back(var_name.GetString());
  645. }
  646. Status ret = g_session_manager->GetVariables(sessionId_, str_var_names, var_values);
  647. if (ret != SUCCESS) {
  648. GELOGE(ret, "[Get][Variables]Failed, error code:%u, session_id:%lu.", ret, sessionId_);
  649. REPORT_CALL_ERROR("E19999", "Get variables failed, error code:%u, session_id:%lu.", ret, sessionId_);
  650. return FAILED;
  651. }
  652. return SUCCESS;
  653. }
  654. bool Session::IsGraphNeedRebuild(uint32_t graph_id) {
  655. if (!g_ge_initialized) {
  656. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  657. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  658. return false;
  659. }
  660. return g_session_manager->IsGraphNeedRebuild(sessionId_, graph_id);
  661. }
  662. } // namespace ge

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