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

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