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
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
4 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  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. // call Finalize
  196. Status ret = SUCCESS;
  197. Status middle_ret;
  198. GELOGT(TRACE_RUNNING, "Finalizing environment");
  199. std::shared_ptr<GELib> instancePtr = ge::GELib::GetInstance();
  200. if (instancePtr == nullptr || !instancePtr->InitFlag()) {
  201. GELOGW("GEFinalize Failed: GE not initialized.");
  202. ret = GE_CLI_GE_NOT_INITIALIZED;
  203. }
  204. if (ret != GE_CLI_GE_NOT_INITIALIZED) {
  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. GELOGI("SessionManager finalization.");
  212. if (g_session_manager != nullptr) {
  213. (void)g_session_manager->Finalize(); // always success.
  214. }
  215. middle_ret = TBEPluginManager::Instance().Finalize();
  216. if (middle_ret != SUCCESS) {
  217. ret = middle_ret;
  218. }
  219. if (g_ge_initialized && ret == SUCCESS) {
  220. // Unified destruct rt_context
  221. RtContextUtil::GetInstance().DestroyAllRtContexts();
  222. g_ge_initialized = false;
  223. }
  224. // to avoid memory fragment, use malloc_trim to back free stack to system
  225. malloc_trim(0);
  226. if (DlogReportFinalize() != SUCCESS) {
  227. GELOGW("Dlog report device log finalize failed.");
  228. }
  229. GELOGT(TRACE_STOP, "GEFinalize finished");
  230. return ret;
  231. }
  232. std::string GEGetErrorMsg() {
  233. return ErrorManager::GetInstance().GetErrorMessage();
  234. }
  235. std::string GEGetWarningMsg() {
  236. return ErrorManager::GetInstance().GetWarningMessage();
  237. }
  238. // Initialize session,which calls innerSession
  239. Session::Session(const std::map<string, string> &options) {
  240. ErrorManager::GetInstance().SetStage(error_message::kInitialize, error_message::kOther);
  241. GELOGT(TRACE_INIT, "Start to construct session.");
  242. ErrorManager::GetInstance().GenWorkStreamIdDefault();
  243. // check init status
  244. sessionId_ = 0;
  245. if (!g_ge_initialized) {
  246. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  247. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  248. return;
  249. }
  250. GELOGT(TRACE_RUNNING, "Creating session");
  251. uint64_t session_id = 0;
  252. Status ret = g_session_manager->CreateSession(options, session_id);
  253. GELOGT(TRACE_RUNNING, "Session id is %lu", session_id);
  254. // check return status, return, update session id if success
  255. if (ret == SUCCESS) {
  256. sessionId_ = session_id;
  257. } else {
  258. GELOGE(ret, "[Construct][Session]Failed, error code:%u.", ret);
  259. return;
  260. }
  261. GELOGT(TRACE_STOP, "Session Constructor finished");
  262. }
  263. Session::Session(const std::map<AscendString, AscendString> &options) {
  264. ErrorManager::GetInstance().SetStage(error_message::kInitialize, error_message::kOther);
  265. GELOGT(TRACE_INIT, "Session Constructor start");
  266. ErrorManager::GetInstance().GenWorkStreamIdDefault();
  267. // check init status
  268. sessionId_ = 0;
  269. if (!g_ge_initialized) {
  270. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  271. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  272. return;
  273. }
  274. // call Initialize
  275. GELOGT(TRACE_RUNNING, "Creating session");
  276. std::map<std::string, std::string> str_options;
  277. for (auto &option : options) {
  278. if (option.first.GetString() == nullptr || option.second.GetString() == nullptr) {
  279. GELOGE(FAILED, "[Construct][Session]Failed, the first or second option is nullptr.");
  280. REPORT_INNER_ERROR("E19999", "Creating session's options invalid, the first or second option is nullptr.");
  281. return;
  282. }
  283. std::string key = option.first.GetString();
  284. std::string val = option.second.GetString();
  285. str_options[key] = val;
  286. }
  287. uint64_t session_id = 0;
  288. Status ret = g_session_manager->CreateSession(str_options, session_id);
  289. GELOGT(TRACE_RUNNING, "Session id is %lu", session_id);
  290. // check return status, return, update session id if success
  291. if (ret == SUCCESS) {
  292. sessionId_ = session_id;
  293. } else {
  294. GELOGE(ret, "[Construct][Session]Failed, error code:%u.", ret);
  295. REPORT_CALL_ERROR("E19999", "Construct session failed, error code:%u.", ret);
  296. return;
  297. }
  298. GELOGT(TRACE_STOP, "Session Constructor finished");
  299. }
  300. // session destructor
  301. Session::~Session() {
  302. ErrorManager::GetInstance().SetStage(error_message::kFinalize, error_message::kFinalize);
  303. GELOGT(TRACE_INIT, "Start to destruct session.");
  304. // 0.check init status
  305. if (!g_ge_initialized) {
  306. GELOGW("GE is not yet initialized or is finalized.");
  307. return;
  308. }
  309. Status ret = FAILED;
  310. std::lock_guard<std::mutex> lock(g_ge_release_mutex);
  311. try {
  312. uint64_t session_id = sessionId_;
  313. // call DestroySession
  314. GELOGT(TRACE_RUNNING, "Session id is %lu", session_id);
  315. GELOGT(TRACE_RUNNING, "Destroying session");
  316. ret = g_session_manager->DestroySession(session_id);
  317. } catch (google::protobuf::FatalException &e) {
  318. GELOGE(GE_CLI_SESS_DESTROY_FAILED, "[Destruct][Session]Failed because get fatalException.");
  319. REPORT_CALL_ERROR("E19999", "Destruct session failed, get fatal exception");
  320. }
  321. // check return status, return, update session id if success
  322. if (ret != SUCCESS) {
  323. GELOGE(ret, "[Destruct][Session]Failed, error code:%u.", ret);
  324. REPORT_CALL_ERROR("E19999", "Destruct session failed, error code:%u.", ret);
  325. }
  326. GELOGT(TRACE_STOP, "Session Destructor finished");
  327. }
  328. // Add Graph
  329. Status Session::AddGraph(uint32_t graph_id, const Graph &graph) {
  330. std::map<std::string, std::string> options;
  331. return AddGraph(graph_id, graph, options);
  332. }
  333. // Add Graph
  334. Status Session::AddGraph(uint32_t graph_id, const Graph &graph, const std::map<std::string, std::string> &options) {
  335. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  336. GELOGT(TRACE_INIT, "Start to add graph in Session. graph_id: %u, session_id: %lu.", graph_id, sessionId_);
  337. ErrorManager::GetInstance().GenWorkStreamIdBySessionGraph(sessionId_, graph_id);
  338. if (!g_ge_initialized) {
  339. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  340. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  341. return FAILED;
  342. }
  343. GELOGD("Adding graph to session");
  344. Status ret = g_session_manager->AddGraph(sessionId_, graph_id, graph, options);
  345. if (ret != SUCCESS) {
  346. GELOGE(ret, "[Add][Graph]Failed, error code:%u, session_id:%lu, graph_id:%u.", ret, sessionId_, graph_id);
  347. return FAILED;
  348. }
  349. GELOGD("AddGraph finished in Session.");
  350. return ret;
  351. }
  352. //Add Graph
  353. Status Session::AddGraph(uint32_t graph_id, const Graph &graph, const std::map<AscendString, AscendString> &options) {
  354. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  355. GELOGT(TRACE_INIT, "Start to add graph in Session. graph_id: %u, session_id: %lu.", graph_id, sessionId_);
  356. ErrorManager::GetInstance().GenWorkStreamIdBySessionGraph(sessionId_, graph_id);
  357. if (!g_ge_initialized) {
  358. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  359. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  360. return FAILED;
  361. }
  362. GELOGD("Adding graph to session");
  363. std::map<std::string, std::string> str_options;
  364. for (auto &option : options) {
  365. if (option.first.GetString() == nullptr || option.second.GetString() == nullptr) {
  366. GELOGE(FAILED, "[Add][Graph]Failed, the first or second option is nullptr.");
  367. REPORT_INNER_ERROR("E19999", "Add Graph Failed, the first or second option is nullptr.");
  368. return FAILED;
  369. }
  370. std::string key = option.first.GetString();
  371. std::string val = option.second.GetString();
  372. str_options[key] = val;
  373. }
  374. Status ret = g_session_manager->AddGraph(sessionId_, graph_id, graph, str_options);
  375. if (ret != SUCCESS) {
  376. GELOGE(ret, "[Add][Graph]Failed, error code:%u, session_id:%lu, graph_id:%u.", ret, sessionId_, graph_id);
  377. return FAILED;
  378. }
  379. GELOGD("AddGraph finished in Session.");
  380. return ret;
  381. }
  382. Status Session::AddGraphWithCopy(uint32_t graph_id, const Graph &graph) {
  383. std::map<AscendString, AscendString> options;
  384. return AddGraphWithCopy(graph_id, graph, options);
  385. }
  386. // Add Graph With Copy
  387. Status Session::AddGraphWithCopy(uint32_t graph_id, const Graph &graph,
  388. const std::map<AscendString, AscendString> &options) {
  389. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  390. GELOGT(TRACE_INIT, "Start to add graph in Session. graph_id: %u, session_id: %lu.", graph_id, sessionId_);
  391. ErrorManager::GetInstance().GenWorkStreamIdBySessionGraph(sessionId_, graph_id);
  392. if (!g_ge_initialized) {
  393. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  394. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  395. return FAILED;
  396. }
  397. std::map<std::string, std::string> str_options;
  398. for (auto it = options.begin(); it != options.end(); ++it) {
  399. str_options.insert({it->first.GetString(), it->second.GetString()});
  400. }
  401. GELOGD("Adding graph to session");
  402. Status ret = g_session_manager->AddGraphWithCopy(sessionId_, graph_id, graph, str_options);
  403. if (ret != SUCCESS) {
  404. GELOGE(ret, "[Add][Graph]Failed, error code:%u, session_id:%lu, graph_id:%u.", ret, sessionId_, graph_id);
  405. return FAILED;
  406. }
  407. GELOGD("AddGraph finished in Session.");
  408. return ret;
  409. }
  410. // Remove Graph
  411. Status Session::RemoveGraph(uint32_t graph_id) {
  412. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  413. GELOGT(TRACE_INIT, "Session RemoveGraph start");
  414. ErrorManager::GetInstance().GenWorkStreamIdBySessionGraph(sessionId_, graph_id);
  415. // call RemoveGraph
  416. if (!g_ge_initialized) {
  417. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  418. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  419. return FAILED;
  420. }
  421. GELOGT(TRACE_RUNNING, "Removing Graph from session");
  422. Status ret = g_session_manager->RemoveGraph(sessionId_, graph_id);
  423. // check return status, return
  424. if (ret != SUCCESS) {
  425. GELOGE(ret, "[Remove][Graph]Failed, error code:%u, session_id:%lu, graph_id:%u.", ret, sessionId_, graph_id);
  426. REPORT_CALL_ERROR("E19999", "Remove graph failed, error code:%u, session_id:%lu, graph_id:%u",
  427. ret, sessionId_, graph_id);
  428. return FAILED;
  429. }
  430. GELOGT(TRACE_STOP, "Session RemoveGraph finished");
  431. return ret;
  432. }
  433. // Print Output Result
  434. void PrintOutputResult(std::vector<Tensor> &outputs) {
  435. if (outputs.empty() || outputs[0].GetData() == nullptr) {
  436. GELOGW("outputs is empty or data is nullptr.");
  437. return;
  438. }
  439. size_t out_buf_size = outputs[0].GetSize();
  440. TensorDesc desc(outputs[0].GetTensorDesc());
  441. DataType data_type = desc.GetDataType();
  442. auto iter = CONST_OPDATA_TYPE_SIZE_MAP.find(data_type);
  443. if (iter == CONST_OPDATA_TYPE_SIZE_MAP.end()) {
  444. GELOGI("DataType %s has not defined size", TypeUtils::DataTypeToSerialString(data_type).c_str());
  445. return;
  446. }
  447. size_t length = CONST_OPDATA_TYPE_SIZE_MAP[data_type];
  448. for (size_t i = 0; i < 10 && i < (out_buf_size / length); ++i) { // take first 10 at most
  449. switch (data_type) {
  450. case DT_BOOL:
  451. case DT_INT8:
  452. case DT_UINT8:
  453. GELOGI("output data[%zu]=%d", i, *(reinterpret_cast<int8_t *>(outputs[0].GetData()) + i));
  454. break;
  455. case DT_INT16:
  456. case DT_UINT16:
  457. GELOGI("output data[%zu]=%d", i, *(reinterpret_cast<int16_t *>(outputs[0].GetData()) + i));
  458. break;
  459. case DT_INT32:
  460. case DT_UINT32:
  461. GELOGI("output data[%zu]=%d", i, *(reinterpret_cast<int32_t *>(outputs[0].GetData()) + i));
  462. break;
  463. case DT_INT64:
  464. case DT_UINT64:
  465. GELOGI("output data[%zu]=%ld", i, *(reinterpret_cast<int64_t *>(outputs[0].GetData()) + i));
  466. break;
  467. case DT_FLOAT:
  468. GELOGI("output data[%zu]=%f", i, *(reinterpret_cast<float *>(outputs[0].GetData()) + i));
  469. break;
  470. case DT_DOUBLE:
  471. GELOGI("output data[%zu]=%lf", i, *(reinterpret_cast<double *>(outputs[0].GetData()) + i));
  472. break;
  473. default:
  474. GELOGI("Output datatype %s is not supported.", TypeUtils::DataTypeToSerialString(data_type).c_str());
  475. return;
  476. }
  477. }
  478. }
  479. // Run Graph
  480. Status Session::RunGraph(uint32_t graph_id, const std::vector<Tensor> &inputs, std::vector<Tensor> &outputs) {
  481. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  482. GELOGT(TRACE_INIT, "Session RunGraph start");
  483. ErrorManager::GetInstance().GenWorkStreamIdBySessionGraph(sessionId_, graph_id);
  484. if (!g_ge_initialized) {
  485. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  486. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  487. return FAILED;
  488. }
  489. // call RunGraph
  490. GELOGT(TRACE_RUNNING, "Running Graph");
  491. Status ret = g_session_manager->RunGraph(sessionId_, graph_id, inputs, outputs);
  492. // check return status
  493. if (ret != SUCCESS) {
  494. GELOGE(ret, "[Run][Graph]Failed, error code:%u, session_id:%lu, graph_id:%u.", ret, sessionId_, graph_id);
  495. REPORT_CALL_ERROR("E19999", "Remove graph failed, error code:%u, session_id:%lu, graph_id:%u",
  496. ret, sessionId_, graph_id);
  497. return FAILED;
  498. }
  499. // print output
  500. if (outputs.size() > 0) {
  501. PrintOutputResult(outputs);
  502. }
  503. // return
  504. GELOGT(TRACE_STOP, "Session RunGraph finished");
  505. return ret;
  506. }
  507. // Run Graph with stream Asynchronously
  508. Status Session::RunGraphWithStreamAsync(uint32_t graph_id, void *stream, const std::vector<Tensor> &inputs,
  509. std::vector<Tensor> &outputs) {
  510. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  511. GELOGT(TRACE_INIT, "Start to run graph with stream async.");
  512. ErrorManager::GetInstance().GenWorkStreamIdBySessionGraph(sessionId_, graph_id);
  513. if (!g_ge_initialized) {
  514. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  515. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  516. return FAILED;
  517. }
  518. GELOGT(TRACE_RUNNING, "Run Graph Run graph with stream asyn.");
  519. Status ret = g_session_manager->RunGraphWithStreamAsync(sessionId_, graph_id, stream, inputs, outputs);
  520. if (ret != SUCCESS) {
  521. GELOGE(ret, "[Run][Graph]Run graph with stream asyn Failed,"
  522. "error code = %u, session id = %lu, graph id = %u, stream = %p.", ret, sessionId_, graph_id, stream);
  523. REPORT_CALL_ERROR("E19999", "[Run][Graph]Run graph with stream asyn failed, error code = %u, session id = %lu,"
  524. "graph id = %u, stream = %p.", ret, sessionId_, graph_id, stream);
  525. return FAILED;
  526. }
  527. GELOGT(TRACE_STOP, "Session run graph with stream async finished");
  528. return SUCCESS;
  529. }
  530. // Register Call Back
  531. Status Session::RegisterCallBackFunc(const std::string &key, const pCallBackFunc &callback) {
  532. ErrorManager::GetInstance().GenWorkStreamIdDefault();
  533. if (!g_ge_initialized) {
  534. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  535. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  536. return FAILED;
  537. }
  538. return g_session_manager->RegisterCallBackFunc(sessionId_, key, callback);
  539. }
  540. Status Session::RegisterCallBackFunc(const char *key, const session::pCallBackFunc &callback) {
  541. ErrorManager::GetInstance().GenWorkStreamIdDefault();
  542. if (!g_ge_initialized) {
  543. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  544. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  545. return FAILED;
  546. }
  547. std::string str_key;
  548. if (key != nullptr) {
  549. str_key = key;
  550. }
  551. return g_session_manager->RegisterCallBackFunc(sessionId_, str_key, callback);
  552. }
  553. // Build Graph
  554. Status Session::BuildGraph(uint32_t graph_id, const std::vector<InputTensorInfo> &inputs) {
  555. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  556. ErrorManager::GetInstance().GenWorkStreamIdBySessionGraph(sessionId_, graph_id);
  557. if (!g_ge_initialized) {
  558. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  559. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  560. return FAILED;
  561. }
  562. GELOGT(TRACE_RUNNING, "Building Graph");
  563. Status ret = g_session_manager->BuildGraph(sessionId_, graph_id, inputs);
  564. if (ret != SUCCESS) {
  565. GELOGE(ret, "[Build][Graph]Failed, error code:%u, session_id:%lu, graph_id:%u.", ret, sessionId_, graph_id);
  566. REPORT_CALL_ERROR("E19999", "Build graph failed , error code:%u, session_id:%lu, graph_id:%u",
  567. ret, sessionId_, graph_id);
  568. return FAILED;
  569. }
  570. return SUCCESS;
  571. }
  572. // Build Graph
  573. Status Session::BuildGraph(uint32_t graph_id, const std::vector<ge::Tensor> &inputs) {
  574. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  575. ErrorManager::GetInstance().GenWorkStreamIdBySessionGraph(sessionId_, graph_id);
  576. if (!g_ge_initialized) {
  577. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  578. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  579. return FAILED;
  580. }
  581. GELOGT(TRACE_RUNNING, "Building Graph");
  582. Status ret = g_session_manager->BuildGraph(sessionId_, graph_id, inputs);
  583. if (ret != SUCCESS) {
  584. GELOGE(ret, "[Build][Graph]Failed, error code:%u, session_id:%lu, graph_id:%u.", ret, sessionId_, graph_id);
  585. REPORT_CALL_ERROR("E19999", "Build graph failed , error code:%u, session_id:%lu, graph_id:%u",
  586. ret, sessionId_, graph_id);
  587. return FAILED;
  588. }
  589. return SUCCESS;
  590. }
  591. // Run Graph Asynchronously
  592. Status Session::RunGraphAsync(uint32_t graph_id, const std::vector<ge::Tensor> &inputs,
  593. RunAsyncCallback callback) {
  594. ErrorManager::GetInstance().SetStage(error_message::kModelExecute, error_message::kModelExecute);
  595. ErrorManager::GetInstance().GenWorkStreamIdBySessionGraph(sessionId_, graph_id);
  596. if (!g_ge_initialized) {
  597. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  598. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  599. return FAILED;
  600. }
  601. GELOGT(TRACE_RUNNING, "Run Graph Asynchronously");
  602. GELOGW(
  603. "The callback function will not be checked. Please ensure that the implementation of the function is trusted.");
  604. Status ret = g_session_manager->RunGraphAsync(sessionId_, graph_id, inputs, callback);
  605. if (ret != SUCCESS) {
  606. GELOGE(ret, "[Run][Graph]RunGraphAsync Failed, error code:%u, session_id:%lu, graph_id:%u.",
  607. ret, sessionId_, graph_id);
  608. REPORT_CALL_ERROR("E19999", "RunGraphAsync Failed, error code:%u, session_id:%lu, graph_id:%u",
  609. ret, sessionId_, graph_id);
  610. return FAILED;
  611. }
  612. return SUCCESS;
  613. }
  614. // Get Variables
  615. Status Session::GetVariables(const std::vector<std::string> &var_names, std::vector<Tensor> &var_values) {
  616. ErrorManager::GetInstance().SetStage(error_message::kModelExecute, error_message::kModelExecute);
  617. ErrorManager::GetInstance().GenWorkStreamIdDefault();
  618. if (!g_ge_initialized) {
  619. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  620. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  621. return FAILED;
  622. }
  623. GELOGT(TRACE_RUNNING, "Get Variables");
  624. Status ret = g_session_manager->GetVariables(sessionId_, var_names, var_values);
  625. if (ret != SUCCESS) {
  626. GELOGE(ret, "[Get][Variables]Failed, error code:%u, session_id:%lu.", ret, sessionId_);
  627. return FAILED;
  628. }
  629. return SUCCESS;
  630. }
  631. // Get Variables
  632. Status Session::GetVariables(const std::vector<AscendString> &var_names, std::vector<Tensor> &var_values) {
  633. ErrorManager::GetInstance().SetStage(error_message::kModelExecute, error_message::kModelExecute);
  634. ErrorManager::GetInstance().GenWorkStreamIdDefault();
  635. if (!g_ge_initialized) {
  636. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  637. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  638. return FAILED;
  639. }
  640. GELOGT(TRACE_RUNNING, "Get Variables");
  641. std::vector<ge::string> str_var_names;
  642. for (auto &var_name : var_names) {
  643. if (var_name.GetString() == nullptr) {
  644. GELOGE(FAILED, "[Get][Variable]Failed, variables' names are nullptr.");
  645. REPORT_INNER_ERROR("E19999", "GetVariables failed, variables' names are nullptr.");
  646. return FAILED;
  647. }
  648. str_var_names.emplace_back(var_name.GetString());
  649. }
  650. Status ret = g_session_manager->GetVariables(sessionId_, str_var_names, var_values);
  651. if (ret != SUCCESS) {
  652. GELOGE(ret, "[Get][Variables]Failed, error code:%u, session_id:%lu.", ret, sessionId_);
  653. REPORT_CALL_ERROR("E19999", "Get variables failed, error code:%u, session_id:%lu.", ret, sessionId_);
  654. return FAILED;
  655. }
  656. return SUCCESS;
  657. }
  658. bool Session::IsGraphNeedRebuild(uint32_t graph_id) {
  659. if (!g_ge_initialized) {
  660. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Construct][Session]Failed because lack GEInitialize call before.");
  661. REPORT_INNER_ERROR("E19999", "Creating session failed because lack GEInitialize call before.");
  662. return false;
  663. }
  664. return g_session_manager->IsGraphNeedRebuild(sessionId_, graph_id);
  665. }
  666. } // namespace ge

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