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

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