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

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