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.

ms_context.cc 15 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. /**
  2. * Copyright 2019 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 "utils/context/ms_context.h"
  17. #include <thread>
  18. #include <atomic>
  19. #include <fstream>
  20. #include "./common.h"
  21. #include "utils/convert_utils.h"
  22. #include "utils/tensorprint_utils.h"
  23. #ifndef NO_DLIB
  24. #include "tdt/tsd_client.h"
  25. #include "tdt/tdt_host_interface.h"
  26. #include "tdt/data_common.h"
  27. #endif
  28. #ifdef ENABLE_GE
  29. #include "transform/df_graph_manager.h"
  30. #endif
  31. #include "ir/meta_tensor.h"
  32. namespace mindspore {
  33. #ifdef ENABLE_GE
  34. using mindspore::transform::DfGraphManager;
  35. #endif
  36. std::atomic<bool> thread_1_must_end(false);
  37. std::shared_ptr<MsContext> MsContext::inst_context_ = nullptr;
  38. std::map<std::string, MsBackendPolicy> MsContext::policy_map_ = {{"ge", kMsBackendGePrior},
  39. {"vm", kMsBackendVmOnly},
  40. {"ms", kMsBackendMsPrior},
  41. {"ge_only", kMsBackendGeOnly},
  42. {"vm_prior", kMsBackendVmPrior}};
  43. MsContext::MsContext(const std::string &policy, const std::string &target) {
  44. save_graphs_flag_ = false;
  45. save_graphs_path_ = ".";
  46. save_ms_model_flag_ = false;
  47. save_ms_model_path_ = "./model.ms";
  48. enable_dump_ = false;
  49. save_dump_path_ = ".";
  50. tsd_ref_ = 0;
  51. ge_ref_ = 0;
  52. is_multi_graph_sink_ = false;
  53. is_pynative_ge_init_ = false;
  54. enable_reduce_precision_ = true;
  55. auto env_device = common::GetEnv("DEVICE_ID");
  56. if (!env_device.empty()) {
  57. device_id_ = UlongToUint(std::stoul(env_device.c_str()));
  58. } else {
  59. device_id_ = 0;
  60. }
  61. backend_policy_ = policy_map_[policy];
  62. device_target_ = target;
  63. execution_mode_ = kPynativeMode;
  64. enable_task_sink_ = true;
  65. ir_fusion_flag_ = true;
  66. enable_hccl_ = false;
  67. enable_mem_reuse_ = true;
  68. enable_gpu_summary_ = true;
  69. precompile_only_ = false;
  70. auto_mixed_precision_flag_ = true;
  71. enable_pynative_infer_ = false;
  72. enable_dynamic_mem_pool_ = true;
  73. graph_memory_max_size_ = "0";
  74. variable_memory_max_size_ = "0";
  75. enable_loop_sink_ = target == kAscendDevice || target == kDavinciDevice;
  76. }
  77. std::shared_ptr<MsContext> MsContext::GetInstance() {
  78. if (inst_context_ == nullptr) {
  79. MS_LOG(DEBUG) << "Create new mindspore context";
  80. #ifdef ENABLE_GE
  81. inst_context_.reset(new (std::nothrow) MsContext("ge", kAscendDevice));
  82. #elif defined(ENABLE_D)
  83. inst_context_.reset(new (std::nothrow) MsContext("ms", kAscendDevice));
  84. #elif defined(ENABLE_GPU)
  85. inst_context_.reset(new (std::nothrow) MsContext("ms", kGPUDevice));
  86. #else
  87. inst_context_.reset(new (std::nothrow) MsContext("vm", kCPUDevice));
  88. #endif
  89. }
  90. return inst_context_;
  91. }
  92. bool MsContext::set_backend_policy(const std::string &policy) {
  93. if (policy_map_.find(policy) == policy_map_.end()) {
  94. MS_LOG(ERROR) << "invalid backend policy name: " << policy;
  95. return false;
  96. }
  97. backend_policy_ = policy_map_[policy];
  98. MS_LOG(INFO) << "ms set context backend policy:" << policy;
  99. return true;
  100. }
  101. std::string MsContext::backend_policy() const {
  102. auto res = std::find_if(
  103. policy_map_.begin(), policy_map_.end(),
  104. [&, this](const std::pair<std::string, MsBackendPolicy> &item) { return item.second == backend_policy_; });
  105. if (res != policy_map_.end()) {
  106. return res->first;
  107. }
  108. return "unknown";
  109. }
  110. void MsContext::set_execution_mode(int execution_mode) {
  111. if (execution_mode != kGraphMode && execution_mode != kPynativeMode) {
  112. MS_LOG(EXCEPTION) << "The execution mode is invalid!";
  113. }
  114. execution_mode_ = execution_mode;
  115. }
  116. bool MsContext::set_device_target(const std::string &target) {
  117. if (kTargetSet.find(target) == kTargetSet.end()) {
  118. MS_LOG(ERROR) << "invalid device target name: " << target;
  119. return false;
  120. }
  121. if (target == kDavinciDevice) {
  122. device_target_ = kAscendDevice;
  123. } else {
  124. device_target_ = target;
  125. }
  126. enable_loop_sink_ = device_target_ == kAscendDevice;
  127. MS_LOG(INFO) << "ms set context device target:" << target;
  128. return true;
  129. }
  130. bool MsContext::set_device_id(uint32_t device_id) {
  131. device_id_ = device_id;
  132. MS_LOG(INFO) << "ms set context device id:" << device_id;
  133. return true;
  134. }
  135. #ifndef NO_DLIB
  136. // Open tdt dataset
  137. bool MsContext::OpenTsd() {
  138. if (is_pynative_ge_init_) {
  139. return true;
  140. }
  141. if (tsd_ref_) {
  142. MS_LOG(DEBUG) << "TDT Dataset client is already opened.";
  143. tsd_ref_++;
  144. return true;
  145. }
  146. unsigned int device_id;
  147. unsigned int rank_size = 1;
  148. device_id = device_id_;
  149. auto rank_size_env = common::GetEnv("RANK_SIZE");
  150. if (rank_size_env.empty()) {
  151. MS_LOG(INFO) << "Should config rank size.";
  152. rank_size = 1;
  153. } else {
  154. int rank_env = std::stoi(rank_size_env);
  155. if (rank_env <= 0) {
  156. MS_LOG(EXCEPTION) << "Error rank size " << rank_env << ".";
  157. }
  158. rank_size = IntToUint(rank_env);
  159. }
  160. MS_LOG(INFO) << "Device id = " << device_id << ", rank size = " << rank_size << ".";
  161. TDT_StatusT status = tdt::TsdClient::GetInstance()->Open(device_id, rank_size);
  162. if (status != TDT_OK) {
  163. MS_LOG(EXCEPTION) << "Device " << device_id << " is occupied, open tsd failed, status = " << status << ".";
  164. return false;
  165. }
  166. tsd_ref_++;
  167. #ifdef ENABLE_TDTQUE
  168. int32_t initStatus = tdt::TdtHostInit(device_id);
  169. if (initStatus != TDT_OK_CODE) {
  170. MS_LOG(EXCEPTION) << "Init tsd failed, status = " << initStatus << ".";
  171. return false;
  172. }
  173. tdt_print_ = std::thread(TensorPrint());
  174. #endif
  175. MS_LOG(INFO) << "Open and init tsd successful, tsd reference = " << tsd_ref_ << ".";
  176. return true;
  177. }
  178. bool MsContext::CloseTsd(bool force) {
  179. if (tsd_ref_ == 0) {
  180. return true;
  181. }
  182. tsd_ref_--;
  183. if (force || tsd_ref_ == 0) {
  184. tsd_ref_ = 0;
  185. #ifdef ENABLE_TDTQUE
  186. int32_t stopStatus = tdt::TdtHostStop(KNpuLog);
  187. if (stopStatus != TDT_OK_CODE) {
  188. MS_LOG(EXCEPTION) << "Stop tsd failed, status = " << stopStatus << ".";
  189. return false;
  190. }
  191. py::gil_scoped_release gil_release;
  192. int32_t destroyStatus = tdt::TdtHostDestroy();
  193. if (destroyStatus != TDT_OK_CODE) {
  194. MS_LOG(EXCEPTION) << "Destroy tsd failed, status = " << destroyStatus << ".";
  195. return false;
  196. }
  197. try {
  198. if (tdt_print_.joinable()) {
  199. MS_LOG(INFO) << "join tdt host receive process";
  200. tdt_print_.join();
  201. }
  202. } catch (const std::exception &e) {
  203. MS_LOG(ERROR) << "tdt thread join failed: " << e.what();
  204. }
  205. #endif
  206. TDT_StatusT status = tdt::TsdClient::GetInstance()->Close();
  207. if (status != TDT_OK) {
  208. MS_LOG(EXCEPTION) << "Close tsd failed, status = " << status << ".";
  209. return false;
  210. }
  211. is_pynative_ge_init_ = false;
  212. MS_LOG(INFO) << "Destroy and close tsd successful, status = " << status << ".";
  213. } else {
  214. MS_LOG(DEBUG) << "TDT Dataset client is used, no need to close, tsd reference = " << tsd_ref_ << ".";
  215. }
  216. return true;
  217. }
  218. #else
  219. bool MsContext::OpenTsd() { return true; }
  220. bool MsContext::CloseTsd(bool) { return true; }
  221. #endif
  222. void MsContext::SetHcclOptions(std::map<std::string, std::string> *ge_options) const {
  223. auto env_table_file = common::GetEnv("RANK_TABLE_FILE");
  224. auto env_rank_id = common::GetEnv("RANK_ID");
  225. auto env_device_id = std::to_string(device_id_);
  226. if (!(env_table_file.empty() || env_rank_id.empty())) {
  227. MS_LOG(INFO) << "Initialize Ge for distribute parameter";
  228. MS_LOG(INFO) << "Use hccl, make sure hccl lib is set in OPTION_EXEC_EXTERN_PLUGIN_PATH.";
  229. auto env_hccl_flag = common::GetEnv("HCCL_FLAG");
  230. if (!env_hccl_flag.empty()) {
  231. (*ge_options)["ge.exec.hcclFlag"] = env_hccl_flag;
  232. }
  233. (*ge_options)["ge.exec.isUseHcom"] = "1";
  234. (*ge_options)["ge.exec.deviceId"] = env_device_id;
  235. (*ge_options)["ge.exec.rankId"] = env_rank_id;
  236. (*ge_options)["ge.exec.podName"] = env_rank_id;
  237. (*ge_options)["ge.exec.rankTableFile"] = env_table_file;
  238. (*ge_options)["ge.graphRunMode"] = "1";
  239. } else {
  240. // device id is still needed for non-distribute case
  241. (*ge_options)["ge.exec.deviceId"] = env_device_id;
  242. MS_LOG(INFO) << "No hccl mode. "
  243. "If use hccl, make sure [RANK_TABLE_FILE,RANK_ID,DEVICE_ID,DEPLOY_MODE] all be set in ENV.";
  244. }
  245. auto env_deploy_mode = common::GetEnv("DEPLOY_MODE");
  246. if (!env_deploy_mode.empty()) {
  247. (*ge_options)["ge.exec.deployMode"] = env_deploy_mode;
  248. } else {
  249. (*ge_options)["ge.exec.deployMode"] = "0";
  250. MS_LOG(WARNING) << "DEPLOY_MODE is not set in ENV. Now set to default value 0";
  251. }
  252. }
  253. void MsContext::GetGeOptions(std::map<std::string, std::string> *ge_options) const {
  254. #ifdef ENABLE_GE
  255. (*ge_options)["device_id"] = "0";
  256. (*ge_options)["ge.exec.enableDump"] = std::to_string(enable_dump_);
  257. (*ge_options)["ge.exec.dumpPath"] = save_dump_path_;
  258. // only not supported in ge
  259. auto tbe_plugin_path = common::GetEnv("ME_TBE_PLUGIN_PATH");
  260. if (!tbe_plugin_path.empty()) {
  261. char real_path[PATH_MAX] = {0};
  262. if (nullptr == realpath(tbe_plugin_path.c_str(), real_path)) {
  263. MS_LOG(ERROR) << "Ms tbe plugin Path error, " << tbe_plugin_path;
  264. } else {
  265. tbe_plugin_path = real_path;
  266. (*ge_options)["ge.TBE_plugin_path"] = tbe_plugin_path;
  267. }
  268. } else {
  269. MS_LOG(ERROR) << "Set TBE plugin path failed!";
  270. }
  271. (*ge_options)["rank_table_file"] = "";
  272. auto env_ddk_version = common::GetEnv("DDK_VERSION");
  273. if (!env_ddk_version.empty()) {
  274. (*ge_options)["ge.DDK_version"] = env_ddk_version;
  275. } else {
  276. (*ge_options)["ge.DDK_version"] = "1.60.T17.B830";
  277. }
  278. (*ge_options)["graphType"] = "1";
  279. if (graph_memory_max_size_ != "0") {
  280. (*ge_options)["ge.graphMemoryMaxSize"] = graph_memory_max_size_;
  281. }
  282. if (variable_memory_max_size_ != "0") {
  283. (*ge_options)["ge.variableMemoryMaxSize"] = variable_memory_max_size_;
  284. }
  285. #if ENABLE_TRAIN == 1
  286. (*ge_options)["ge.graphRunMode"] = "1";
  287. #endif
  288. SetDisableReuseMemoryFlag(ge_options);
  289. SetHcclOptions(ge_options);
  290. auto env_job_id = common::GetEnv("JOB_ID");
  291. if (!env_job_id.empty()) {
  292. (*ge_options)["ge.exec.jobId"] = env_job_id;
  293. } else {
  294. (*ge_options)["ge.exec.jobId"] = "0";
  295. MS_LOG(WARNING) << "JOB_ID is not set in ENV. Now set to default value 0";
  296. }
  297. auto env_fe_flag = common::GetEnv("FE_FLAG");
  298. if (!env_fe_flag.empty()) {
  299. (*ge_options)["ge.feFlag"] = env_fe_flag;
  300. MS_LOG(INFO) << "Use FE, make sure fe lib is set in OPTION_EXEC_EXTERN_PLUGIN_PATH.";
  301. }
  302. auto env_aicpu_flag = common::GetEnv("AICPU_FLAG");
  303. if (!env_aicpu_flag.empty()) {
  304. (*ge_options)["ge.aicpuFlag"] = env_aicpu_flag;
  305. MS_LOG(INFO) << "Use AICPU, make sure aicpu lib is set in OPTION_EXEC_EXTERN_PLUGIN_PATH.";
  306. }
  307. // all libs are set in same env variable "OPTION_EXEC_EXTERN_PLUGIN_PATH", such as FE, HCCL, AICPU, etc
  308. auto load_path = common::GetEnv("OPTION_EXEC_EXTERN_PLUGIN_PATH");
  309. if (!load_path.empty()) {
  310. char real_path[PATH_MAX] = {0};
  311. if (realpath(load_path.c_str(), real_path)) {
  312. load_path = real_path;
  313. (*ge_options)["ge.soLoadPath"] = load_path;
  314. }
  315. } else {
  316. MS_LOG(ERROR) << "Set lib load path failed!";
  317. }
  318. auto proto_lib_path = common::GetEnv("OPTION_PROTO_LIB_PATH");
  319. if (!proto_lib_path.empty()) {
  320. char real_path[PATH_MAX] = {0};
  321. if (realpath(proto_lib_path.c_str(), real_path)) {
  322. proto_lib_path = real_path;
  323. (*ge_options)["ge.opsProtoLibPath"] = proto_lib_path;
  324. }
  325. } else {
  326. MS_LOG(ERROR) << "Set proto lib path failed!";
  327. }
  328. // Enable auto mixed precision according to the context options
  329. (*ge_options)["ge.exec.auto_mix_precision"] = std::to_string(auto_mixed_precision_flag_);
  330. // Disable the global variable acc, only enable it whlie adding training graph in pipeline
  331. (*ge_options)["ge.exec.variable_acc"] = "0";
  332. #endif
  333. }
  334. void MsContext::SetDisableReuseMemoryFlag(std::map<std::string, std::string> *ge_options) const {
  335. auto env_disable_reuse_memory = common::GetEnv("DISABLE_REUSE_MEMORY");
  336. if (!env_disable_reuse_memory.empty()) {
  337. (*ge_options)["ge.exec.disableReuseMemory"] = env_disable_reuse_memory;
  338. } else {
  339. (*ge_options)["ge.exec.disableReuseMemory"] = "0";
  340. MS_LOG(WARNING) << "DISABLE_REUSE_MEMORY is not set in ENV. Now set to default value 0";
  341. }
  342. }
  343. bool MsContext::InitGe() {
  344. #ifdef ENABLE_GE
  345. if (is_pynative_ge_init_) {
  346. return true;
  347. }
  348. if (ge_ref_) {
  349. ge_ref_++;
  350. return true;
  351. }
  352. std::map<std::string, std::string> ge_options;
  353. GetGeOptions(&ge_options);
  354. {
  355. // Release GIL before calling into (potentially long-running) C++ code
  356. py::gil_scoped_release release;
  357. if (ge::GEInitialize(ge_options) != ge::GRAPH_SUCCESS) {
  358. MS_LOG(EXCEPTION) << "Initialize GE failed!";
  359. }
  360. }
  361. ge_ref_++;
  362. MS_LOG(INFO) << "Init ge successful, ge reference = " << ge_ref_ << ".";
  363. #endif
  364. return true;
  365. }
  366. bool MsContext::FinalizeGe(bool force) {
  367. #ifdef ENABLE_GE
  368. if (ge_ref_ == 0) {
  369. return true;
  370. }
  371. ge_ref_--;
  372. if (force || ge_ref_ == 0) {
  373. ge_ref_ = 0;
  374. try {
  375. DfGraphManager::GetInstance().DeleteGraphRunner();
  376. DfGraphManager::GetInstance().DeleteGeSession();
  377. } catch (const std::exception &e) {
  378. MS_LOG(ERROR) << "Error occurred when deleting GE graph runner and session fail. Error: " << e.what();
  379. } catch (...) {
  380. std::string exName(abi::__cxa_current_exception_type()->name());
  381. MS_LOG(ERROR) << "Error occurred when deleting GE graph runner and session fail. Exception name: " << exName;
  382. }
  383. if (ge::GEFinalize() != ge::GRAPH_SUCCESS) {
  384. MS_LOG(WARNING) << "Finalize GE failed!";
  385. }
  386. is_pynative_ge_init_ = false;
  387. } else {
  388. MS_LOG(INFO) << "Ge is used, no need to finalize, tsd reference = " << ge_ref_ << ".";
  389. }
  390. #endif
  391. return true;
  392. }
  393. bool MsContext::PynativeInitGe() {
  394. if (is_pynative_ge_init_ || ge_ref_ || tsd_ref_) {
  395. return true;
  396. }
  397. (void)OpenTsd();
  398. (void)InitGe();
  399. is_pynative_ge_init_ = true;
  400. return true;
  401. }
  402. bool MsContext::IsTsdOpened() {
  403. if (tsd_ref_ > 0) {
  404. return true;
  405. }
  406. return false;
  407. }
  408. bool MsContext::IsGeInited() {
  409. if (ge_ref_ > 0) {
  410. return true;
  411. }
  412. return false;
  413. }
  414. } // namespace mindspore