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

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