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

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