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 14 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
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
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
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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 "common/debug/log.h"
  19. #include "framework/common/debug/ge_log.h"
  20. #include "common/ge/datatype_util.h"
  21. #include "proto/ge_api.pb.h"
  22. #include "graph/model_serialize.h"
  23. #include "graph/detail/model_serialize_imp.h"
  24. #include "graph/utils/tensor_adapter.h"
  25. #include "init/gelib.h"
  26. #include "session/session_manager.h"
  27. #include "graph/opsproto_manager.h"
  28. #include "graph/utils/type_utils.h"
  29. #include "graph/manager/util/rt_context_util.h"
  30. #include "graph/common/ge_call_wrapper.h"
  31. #include "register/op_registry.h"
  32. #include "common/ge/tbe_plugin_manager.h"
  33. using domi::OpRegistry;
  34. using std::map;
  35. using std::string;
  36. using std::vector;
  37. namespace {
  38. const int32_t kMaxStrLen = 128;
  39. } // namespace
  40. static bool g_ge_initialized = false;
  41. static std::mutex g_ge_release_mutex; // GEFinalize and ~Session use
  42. namespace ge {
  43. void GetOpsProtoPath(std::string &opsproto_path) {
  44. GELOGI("Enter get ops proto path schedule");
  45. const char *path_env = std::getenv("ASCEND_OPP_PATH");
  46. if (path_env != nullptr) {
  47. std::string path = path_env;
  48. opsproto_path = (path + "/op_proto/custom/" + ":") + (path + "/op_proto/built-in/");
  49. GELOGI("Get opsproto so path from env: %s", path.c_str());
  50. return;
  51. }
  52. std::string path_base = PluginManager::GetPath();
  53. GELOGI("path_base is %s", path_base.c_str());
  54. path_base = path_base.substr(0, path_base.rfind('/'));
  55. path_base = path_base.substr(0, path_base.rfind('/') + 1);
  56. opsproto_path = (path_base + "ops/op_proto/custom/" + ":") + (path_base + "ops/op_proto/built-in/");
  57. }
  58. Status CheckOptionsValid(const std::map<string, string> &options) {
  59. // check job_id is valid
  60. auto job_id_iter = options.find(OPTION_EXEC_JOB_ID);
  61. if (job_id_iter != options.end()) {
  62. if (job_id_iter->second.length() > kMaxStrLen) {
  63. GELOGE(PARAM_INVALID, "CheckOptionsValid job_id failed, string len > %d", kMaxStrLen);
  64. return FAILED;
  65. }
  66. }
  67. return SUCCESS;
  68. }
  69. // Initialize GE, prepare for execution, call GELib::Initialize
  70. Status GEInitialize(const std::map<string, string> &options) {
  71. GELOGT(TRACE_INIT, "GEInitialize start");
  72. // 0.check init status
  73. if (g_ge_initialized) {
  74. GELOGW("GEInitialize is called more than once");
  75. return SUCCESS;
  76. }
  77. // Load OpsProto lib plugin
  78. std::string opsproto_path;
  79. GetOpsProtoPath(opsproto_path);
  80. OpsProtoManager *manager = OpsProtoManager::Instance();
  81. std::map<string, string> option_tmp;
  82. option_tmp.emplace(std::pair<string, string>(string("ge.opsProtoLibPath"), opsproto_path));
  83. GE_TIMESTAMP_START(GEInitialize);
  84. bool is_proto_init = manager->Initialize(option_tmp);
  85. GE_TIMESTAMP_END(GEInitialize, "GEInitialize::ManagerInitialize");
  86. if (!is_proto_init) {
  87. GELOGE(GE_CLI_INIT_FAILED, "geInitialize failed, ops proto path is invalid.");
  88. return FAILED;
  89. }
  90. // check options is valid
  91. GE_TIMESTAMP_START(CheckOptionsValid);
  92. if (CheckOptionsValid(options) != SUCCESS) {
  93. return FAILED;
  94. }
  95. GE_TIMESTAMP_END(CheckOptionsValid, "GEInitialize::CheckOptionsValid");
  96. GE_TIMESTAMP_START(InitPreparation);
  97. TBEPluginManager::Instance().InitPreparation(options);
  98. GE_TIMESTAMP_END(InitPreparation, "GEInitialize::InitPreparation");
  99. // call Initialize
  100. GELOGT(TRACE_RUNNING, "Initializing environment");
  101. GE_TIMESTAMP_START(GELibInitialize);
  102. Status ret = ge::GELib::Initialize(options);
  103. GE_TIMESTAMP_END(GELibInitialize, "GEInitialize::GELibInitialize");
  104. if (ret != SUCCESS) {
  105. GELOGE(GE_CLI_INIT_FAILED, "geInitialize failed, error code = %u", ret);
  106. return FAILED;
  107. }
  108. // 7.check return status, return
  109. if (!g_ge_initialized) {
  110. // Initialize success, first time calling initialize
  111. g_ge_initialized = true;
  112. }
  113. GELOGT(TRACE_STOP, "GEInitialize finished");
  114. return ret;
  115. }
  116. // GE finalize, releasing all resources
  117. Status GEFinalize() {
  118. GELOGT(TRACE_INIT, "GEFinalize start");
  119. // check init status
  120. if (!g_ge_initialized) {
  121. GELOGW("GEFinalize is called before GEInitialize");
  122. return SUCCESS;
  123. }
  124. std::lock_guard<std::mutex> lock(g_ge_release_mutex);
  125. // call Finalize
  126. Status ret = SUCCESS;
  127. Status middle_ret;
  128. GELOGT(TRACE_RUNNING, "Finalizing environment");
  129. std::shared_ptr<GELib> instancePtr = ge::GELib::GetInstance();
  130. if (instancePtr == nullptr || !instancePtr->InitFlag()) {
  131. GELOGW("GEFinalize Failed: GE not initialized.");
  132. ret = GE_CLI_GE_NOT_INITIALIZED;
  133. }
  134. if (ret != GE_CLI_GE_NOT_INITIALIZED) {
  135. middle_ret = instancePtr->Finalize();
  136. GELOGI("GEFinalize finalize gelib ret=%u", middle_ret);
  137. if (middle_ret != SUCCESS) {
  138. ret = middle_ret;
  139. }
  140. }
  141. middle_ret = TBEPluginManager::Instance().Finalize();
  142. if (middle_ret != SUCCESS) {
  143. ret = middle_ret;
  144. }
  145. if (g_ge_initialized && ret == SUCCESS) {
  146. // Unified destruct rt_context
  147. RtContextUtil::GetInstance().DestroyAllRtContexts();
  148. g_ge_initialized = false;
  149. }
  150. GELOGT(TRACE_STOP, "GEFinalize finished");
  151. return ret;
  152. }
  153. // Initialize session,which calls innerSession
  154. Session::Session(const std::map<string, string> &options) {
  155. GELOGT(TRACE_INIT, "Session Constructor start");
  156. // check init status
  157. sessionId_ = 0;
  158. if (!g_ge_initialized) {
  159. GELOGE(GE_CLI_GE_NOT_INITIALIZED);
  160. return;
  161. }
  162. // call Initialize
  163. std::shared_ptr<GELib> instance_ptr = ge::GELib::GetInstance();
  164. if (instance_ptr == nullptr || !instance_ptr->InitFlag()) {
  165. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "Session Constructor failed");
  166. return;
  167. }
  168. GELOGT(TRACE_RUNNING, "Creating session");
  169. uint64_t session_id = 0;
  170. Status ret = instance_ptr->SessionManagerObj().CreateSession(options, session_id);
  171. GELOGT(TRACE_RUNNING, "Session id is %lu", session_id);
  172. // check return status, return, update session id if success
  173. if (ret == SUCCESS) {
  174. sessionId_ = session_id;
  175. } else {
  176. GELOGE(ret, "Session constructor failed, session Id not initialized");
  177. return;
  178. }
  179. GELOGT(TRACE_STOP, "Session Constructor finished");
  180. }
  181. // session destructor
  182. Session::~Session() {
  183. GELOGT(TRACE_INIT, "Session Destructor start");
  184. // 0.check init status
  185. if (!g_ge_initialized) {
  186. GELOGW("GE is not yet initialized or is finalized.");
  187. return;
  188. }
  189. Status ret = FAILED;
  190. std::lock_guard<std::mutex> lock(g_ge_release_mutex);
  191. try {
  192. uint64_t session_id = sessionId_;
  193. // call DestroySession
  194. std::shared_ptr<GELib> instance_ptr = ge::GELib::GetInstance();
  195. if (instance_ptr == nullptr || !instance_ptr->InitFlag()) {
  196. GELOGW("GE is not yet initialized or is finalized.");
  197. return;
  198. }
  199. GELOGT(TRACE_RUNNING, "Session id is %lu", session_id);
  200. GELOGT(TRACE_RUNNING, "Destroying session");
  201. ret = instance_ptr->SessionManagerObj().DestroySession(session_id);
  202. } catch (google::protobuf::FatalException &e) {
  203. GELOGE(GE_CLI_SESS_DESTROY_FAILED, "SessionDestructor throws FatalException");
  204. }
  205. // check return status, return, update session id if success
  206. if (ret != SUCCESS) {
  207. GELOGE(ret, "Session Destructor failed");
  208. }
  209. GELOGT(TRACE_STOP, "Session Destructor finished");
  210. }
  211. Status Session::AddGraph(uint32_t graph_id, const Graph &graph) {
  212. std::map<std::string, std::string> options;
  213. return AddGraph(graph_id, graph, options);
  214. }
  215. Status Session::AddGraph(uint32_t graph_id, const Graph &graph, const std::map<std::string, std::string> &options) {
  216. GELOGT(TRACE_INIT, "Start to add graph in Session. graph_id: %u, session_id: %lu.", graph_id, sessionId_);
  217. std::shared_ptr<GELib> instance_ptr = ge::GELib::GetInstance();
  218. if (instance_ptr == nullptr || !instance_ptr->InitFlag()) {
  219. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "AddGraph failed in Session.");
  220. return FAILED;
  221. }
  222. GELOGD("Adding graph to session");
  223. Status ret = instance_ptr->SessionManagerObj().AddGraph(sessionId_, graph_id, graph, options);
  224. if (ret != SUCCESS) {
  225. GELOGE(ret, "AddGraph failed in Session.");
  226. return FAILED;
  227. }
  228. GELOGD("AddGraph finished in Session.");
  229. return ret;
  230. }
  231. Status Session::RemoveGraph(uint32_t graph_id) {
  232. GELOGT(TRACE_INIT, "Session RemoveGraph start");
  233. // call RemoveGraph
  234. std::shared_ptr<GELib> instance_ptr = ge::GELib::GetInstance();
  235. if (!instance_ptr || !instance_ptr->InitFlag()) {
  236. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "Session RemoveGraph failed");
  237. return FAILED;
  238. }
  239. GELOGT(TRACE_RUNNING, "Removing Graph from session");
  240. Status ret = instance_ptr->SessionManagerObj().RemoveGraph(sessionId_, graph_id);
  241. // check return status, return
  242. if (ret != SUCCESS) {
  243. GELOGE(ret, "session RemoveGraph failed");
  244. return FAILED;
  245. }
  246. GELOGT(TRACE_STOP, "Session RemoveGraph finished");
  247. return ret;
  248. }
  249. void PrintOutputResult(std::vector<Tensor> &outputs) {
  250. if (outputs.empty() || outputs[0].GetData() == nullptr) {
  251. GELOGW("outputs is empty or data is nullptr.");
  252. return;
  253. }
  254. size_t out_buf_size = outputs[0].GetSize();
  255. TensorDesc desc(outputs[0].GetTensorDesc());
  256. DataType data_type = desc.GetDataType();
  257. auto iter = CONST_OPDATA_TYPE_SIZE_MAP.find(data_type);
  258. if (iter == CONST_OPDATA_TYPE_SIZE_MAP.end()) {
  259. GELOGI("DataType %s has not defined size", TypeUtils::DataTypeToSerialString(data_type).c_str());
  260. return;
  261. }
  262. size_t length = CONST_OPDATA_TYPE_SIZE_MAP[data_type];
  263. for (size_t i = 0; i < 10 && i < (out_buf_size / length); ++i) { // take first 10 at most
  264. switch (data_type) {
  265. case DT_BOOL:
  266. case DT_INT8:
  267. case DT_UINT8:
  268. GELOGI("output data[%zu]=%d", i, *(reinterpret_cast<int8_t *>(outputs[0].GetData()) + i));
  269. break;
  270. case DT_INT16:
  271. case DT_UINT16:
  272. GELOGI("output data[%zu]=%d", i, *(reinterpret_cast<int16_t *>(outputs[0].GetData()) + i));
  273. break;
  274. case DT_INT32:
  275. case DT_UINT32:
  276. GELOGI("output data[%zu]=%d", i, *(reinterpret_cast<int32_t *>(outputs[0].GetData()) + i));
  277. break;
  278. case DT_INT64:
  279. case DT_UINT64:
  280. GELOGI("output data[%zu]=%ld", i, *(reinterpret_cast<int64_t *>(outputs[0].GetData()) + i));
  281. break;
  282. case DT_FLOAT:
  283. GELOGI("output data[%zu]=%f", i, *(reinterpret_cast<float *>(outputs[0].GetData()) + i));
  284. break;
  285. case DT_DOUBLE:
  286. GELOGI("output data[%zu]=%lf", i, *(reinterpret_cast<double *>(outputs[0].GetData()) + i));
  287. break;
  288. default:
  289. GELOGI("Output datatype %s is not supported.", TypeUtils::DataTypeToSerialString(data_type).c_str());
  290. return;
  291. }
  292. }
  293. }
  294. Status Session::RunGraph(uint32_t graph_id, const std::vector<Tensor> &inputs, std::vector<Tensor> &outputs) {
  295. GELOGT(TRACE_INIT, "Session RunGraph start");
  296. std::vector<Tensor> graph_inputs = inputs;
  297. // call RunGraph
  298. std::shared_ptr<GELib> instance_ptr = ge::GELib::GetInstance();
  299. if (instance_ptr == nullptr || !instance_ptr->InitFlag()) {
  300. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "Session RunGraph failed");
  301. return FAILED;
  302. }
  303. GELOGT(TRACE_RUNNING, "Running Graph");
  304. Status ret = instance_ptr->SessionManagerObj().RunGraph(sessionId_, graph_id, graph_inputs, outputs);
  305. // check return status
  306. if (ret != SUCCESS) {
  307. GELOGE(ret, "Session RunGraph failed");
  308. return FAILED;
  309. }
  310. // print output
  311. if (outputs.size() > 0) {
  312. PrintOutputResult(outputs);
  313. }
  314. // return
  315. GELOGT(TRACE_STOP, "Session RunGraph finished");
  316. return ret;
  317. }
  318. Status Session::RegisterCallBackFunc(const std::string &key, const pCallBackFunc &callback) {
  319. return ge::GELib::GetInstance()->SessionManagerObj().RegisterCallBackFunc(sessionId_, key, callback);
  320. }
  321. Status Session::BuildGraph(uint32_t graph_id, const std::vector<InputTensorInfo> &inputs) {
  322. std::shared_ptr<GELib> instance_ptr = ge::GELib::GetInstance();
  323. if (instance_ptr == nullptr || !instance_ptr->InitFlag()) {
  324. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "SessionConstructor failed");
  325. return FAILED;
  326. }
  327. GELOGT(TRACE_RUNNING, "Building Graph");
  328. Status ret = instance_ptr->SessionManagerObj().BuildGraph(sessionId_, graph_id, inputs);
  329. if (ret != SUCCESS) {
  330. GELOGE(ret, "Session BuildGraph failed");
  331. return FAILED;
  332. }
  333. return SUCCESS;
  334. }
  335. Status Session::RunGraphAsync(uint32_t graph_id, const std::vector<InputTensorInfo> &inputs,
  336. RunAsyncCallback callback) {
  337. std::shared_ptr<GELib> instance_ptr = ge::GELib::GetInstance();
  338. if (instance_ptr == nullptr || !instance_ptr->InitFlag()) {
  339. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "SessionConstructor failed");
  340. return FAILED;
  341. }
  342. GELOGT(TRACE_RUNNING, "Run Graph Asynchronously");
  343. GELOGW(
  344. "The callback function will not be checked. Please ensure that the implementation of the function is trusted.");
  345. Status ret = ge::GELib::GetInstance()->SessionManagerObj().RunGraphAsync(sessionId_, graph_id, inputs, callback);
  346. if (ret != SUCCESS) {
  347. GELOGE(ret, "SessionManager RunGraphAsync failed");
  348. return FAILED;
  349. }
  350. return SUCCESS;
  351. }
  352. Status Session::GetVariables(const std::vector<std::string> &var_names, std::vector<Tensor> &var_values) {
  353. auto instance_ptr = ge::GELib::GetInstance();
  354. if (instance_ptr == nullptr || !instance_ptr->InitFlag()) {
  355. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "SessionConstructor failed");
  356. return FAILED;
  357. }
  358. GELOGT(TRACE_RUNNING, "Get Variables");
  359. Status ret = ge::GELib::GetInstance()->SessionManagerObj().GetVariables(sessionId_, var_names, var_values);
  360. if (ret != SUCCESS) {
  361. GELOGE(ret, "SessionManager RunGraphAsync failed");
  362. return FAILED;
  363. }
  364. return SUCCESS;
  365. }
  366. bool Session::IsGraphNeedRebuild(uint32_t graph_id) {
  367. return ge::GELib::GetInstance()->SessionManagerObj().IsGraphNeedRebuild(sessionId_, graph_id);
  368. }
  369. } // namespace ge

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