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.

context.py 25 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """
  16. The context of mindspore, used to configure the current execution environment,
  17. including execution mode, execution backend and other feature switches.
  18. """
  19. import os
  20. import threading
  21. from collections import namedtuple
  22. from types import FunctionType
  23. from mindspore import log as logger
  24. from mindspore._c_expression import MSContext
  25. from mindspore._checkparam import args_type_check
  26. from mindspore.parallel._auto_parallel_context import _set_auto_parallel_context, _get_auto_parallel_context, \
  27. _reset_auto_parallel_context
  28. from mindspore.parallel.mpi._mpi_config import _set_mpi_config, _get_mpi_config
  29. __all__ = ['GRAPH_MODE', 'PYNATIVE_MODE', 'set_context', 'get_context', 'set_auto_parallel_context',
  30. 'get_auto_parallel_context', 'reset_auto_parallel_context']
  31. GRAPH_MODE = 0
  32. PYNATIVE_MODE = 1
  33. # The max memory size of graph plus variable.
  34. _DEVICE_APP_MEMORY_SIZE = 31
  35. def _make_directory(path):
  36. """Make directory."""
  37. real_path = None
  38. if path is None or not isinstance(path, str) or path.strip() == "":
  39. raise ValueError(f"Input path `{path}` is invalid type")
  40. # convert the relative paths
  41. path = os.path.realpath(path)
  42. logger.debug("The absolute path is %r", path)
  43. # check whether the path is already existed and has written permissions
  44. if os.path.exists(path):
  45. real_path = path
  46. else:
  47. # All exceptions need to be caught because create directory maybe have some limit(permissions)
  48. logger.debug("The directory(%s) doesn't exist, will create it", path)
  49. try:
  50. os.makedirs(path)
  51. real_path = path
  52. except PermissionError as e:
  53. logger.error(f"No write permission on the directory `{path}, error = {e}")
  54. raise ValueError(f"No write permission on the directory `{path}`.")
  55. return real_path
  56. class _ThreadLocalInfo(threading.local):
  57. """
  58. Thread local Info used for store thread local attributes.
  59. """
  60. def __init__(self):
  61. super(_ThreadLocalInfo, self).__init__()
  62. self._reserve_class_name_in_scope = True
  63. @property
  64. def reserve_class_name_in_scope(self):
  65. """Gets whether to save the network class name in the scope."""
  66. return self._reserve_class_name_in_scope
  67. @reserve_class_name_in_scope.setter
  68. def reserve_class_name_in_scope(self, reserve_class_name_in_scope):
  69. """Sets whether to save the network class name in the scope."""
  70. if not isinstance(reserve_class_name_in_scope, bool):
  71. raise ValueError("Set reserve_class_name_in_scope value must be bool!")
  72. self._reserve_class_name_in_scope = reserve_class_name_in_scope
  73. _ContextRecord = namedtuple("_ContextRecord", ["is_pynative_mode", "switch_context_fn"])
  74. class _ContextSwitchInfo(threading.local):
  75. """
  76. Record of context switch information.
  77. Args:
  78. is_pynative (bool): Whether to adopt the PyNative mode.
  79. """
  80. def __init__(self, is_pynative):
  81. super(_ContextSwitchInfo, self).__init__()
  82. self.context_stack = []
  83. if is_pynative:
  84. self.push(True, None)
  85. def push(self, is_pynative, switch_context_fn):
  86. """
  87. Push a context switch record onto the stack.
  88. Args:
  89. is_pynative (bool): Whether context switch to PyNative mode.
  90. switch_context_fn (Function): A callable that executes the context switch.
  91. """
  92. if isinstance(switch_context_fn, FunctionType):
  93. switch_context_fn()
  94. self.context_stack.append(_ContextRecord(is_pynative, switch_context_fn))
  95. def pop(self):
  96. self.context_stack.pop()
  97. class _Context:
  98. """
  99. _Context is the environment in which operations are executed
  100. Note:
  101. Create a context through instantiating Context object is not recommended.
  102. should use context() to get the context since Context is singleton.
  103. """
  104. _instance = None
  105. _instance_lock = threading.Lock()
  106. def __init__(self):
  107. self._thread_local_info = _ThreadLocalInfo()
  108. self._context_switches = _ContextSwitchInfo(True)
  109. self._context_handle = MSContext.get_instance()
  110. def __new__(cls, *args, **kwargs):
  111. if cls._instance is None:
  112. cls._instance_lock.acquire()
  113. cls._instance = object.__new__(cls)
  114. cls._instance_lock.release()
  115. return cls._instance
  116. def __getattribute__(self, attr):
  117. value = object.__getattribute__(self, attr)
  118. if attr == "_context_handle" and value is None:
  119. raise ValueError("Context handle is none in context!!!")
  120. return value
  121. @property
  122. def mode(self):
  123. return self._context_handle.get_execution_mode()
  124. @mode.setter
  125. def mode(self, mode):
  126. """
  127. Switch between Graph mode and PyNative mode.
  128. Args:
  129. mode (int): GRAPH_MODE or PYNATIVE_MODE.
  130. """
  131. self._context_handle.set_execution_mode(mode)
  132. if mode == PYNATIVE_MODE:
  133. if self.enable_debug_runtime:
  134. self.set_backend_policy("vm")
  135. self._context_switches.push(True, None)
  136. else:
  137. if self.enable_debug_runtime:
  138. self.set_backend_policy("ge")
  139. self._context_switches.push(False, None)
  140. def set_backend_policy(self, policy):
  141. success = self._context_handle.set_backend_policy(policy)
  142. if not success:
  143. raise RuntimeError("Backend policy must be one of ge, vm, ms.")
  144. @property
  145. def precompile_only(self):
  146. return self._context_handle.get_precompile_only()
  147. @precompile_only.setter
  148. def precompile_only(self, precompile_only):
  149. self._context_handle.set_precompile_only(precompile_only)
  150. @property
  151. def save_graphs(self):
  152. return self._context_handle.get_save_graphs_flag()
  153. @save_graphs.setter
  154. def save_graphs(self, save_graphs_flag):
  155. self._context_handle.set_save_graphs_flag(save_graphs_flag)
  156. @property
  157. def save_graphs_path(self):
  158. return self._context_handle.get_save_graphs_path()
  159. @save_graphs_path.setter
  160. def save_graphs_path(self, save_graphs_path):
  161. self._context_handle.set_save_graphs_path(_make_directory(save_graphs_path))
  162. @property
  163. def device_target(self):
  164. return self._context_handle.get_device_target()
  165. @device_target.setter
  166. def device_target(self, target):
  167. success = self._context_handle.set_device_target(target)
  168. if not success:
  169. raise ValueError("Target device name is invalid!!!")
  170. @property
  171. def device_id(self):
  172. return self._context_handle.get_device_id()
  173. @device_id.setter
  174. def device_id(self, device_id):
  175. if device_id < 0 or device_id > 4095:
  176. raise ValueError("Device id must be in [0, 4095], but got {}".format(device_id))
  177. success = self._context_handle.set_device_id(device_id)
  178. if not success:
  179. raise RuntimeError("Device id set failed!!!")
  180. @property
  181. def save_ms_model(self):
  182. return self._context_handle.get_save_ms_model_flag()
  183. @save_ms_model.setter
  184. def save_ms_model(self, save_ms_model_flag):
  185. self._context_handle.set_save_ms_model_flag(save_ms_model_flag)
  186. @property
  187. def save_ms_model_path(self):
  188. return self._context_handle.get_save_ms_model_path()
  189. @save_ms_model_path.setter
  190. def save_ms_model_path(self, save_ms_model_path):
  191. self._context_handle.set_save_ms_model_path(save_ms_model_path)
  192. @property
  193. def enable_auto_mixed_precision(self):
  194. return self._context_handle.get_auto_mixed_precision_flag()
  195. @enable_auto_mixed_precision.setter
  196. def enable_auto_mixed_precision(self, enable_auto_mixed_precision):
  197. self._context_handle.set_auto_mixed_precision_flag(enable_auto_mixed_precision)
  198. @property
  199. def enable_reduce_precision(self):
  200. return self._context_handle.get_enable_reduce_precision_flag()
  201. @enable_reduce_precision.setter
  202. def enable_reduce_precision(self, enable_reduce_precision):
  203. self._context_handle.set_enable_reduce_precision_flag(enable_reduce_precision)
  204. @property
  205. def enable_dump(self):
  206. return self._context_handle.get_enable_dump()
  207. @enable_dump.setter
  208. def enable_dump(self, enable_dump):
  209. self._context_handle.set_enable_dump(enable_dump)
  210. @property
  211. def save_dump_path(self):
  212. return self._context_handle.get_save_dump_path()
  213. @save_dump_path.setter
  214. def save_dump_path(self, save_dump_path):
  215. self._context_handle.set_save_dump_path(save_dump_path)
  216. @property
  217. def enable_profiling(self):
  218. return self._context_handle.get_enable_profiling()
  219. @enable_profiling.setter
  220. def enable_profiling(self, flag):
  221. self._context_handle.set_enable_profiling(flag)
  222. @property
  223. def profiling_options(self):
  224. return self._context_handle.get_profiling_options()
  225. @profiling_options.setter
  226. def profiling_options(self, option):
  227. options = ["training_trace", "task_trace", "task_trace:training_trace", "training_trace:task_trace", "op_trace"]
  228. if option not in options:
  229. raise ValueError("Profiling options must be in 'training_trace' 'task_trace' "
  230. "'task_trace:training_trace' 'training_trace:task_trace' or 'op_trace'.")
  231. self._context_handle.set_profiling_options(option)
  232. @property
  233. def reserve_class_name_in_scope(self):
  234. """Gets whether to save the network class name in the scope."""
  235. return self._thread_local_info.reserve_class_name_in_scope
  236. @reserve_class_name_in_scope.setter
  237. def reserve_class_name_in_scope(self, reserve_class_name_in_scope):
  238. """Sets whether to save the network class name in the scope."""
  239. self._thread_local_info.reserve_class_name_in_scope = reserve_class_name_in_scope
  240. @property
  241. def variable_memory_max_size(self):
  242. return None
  243. @variable_memory_max_size.setter
  244. def variable_memory_max_size(self, variable_memory_max_size):
  245. if not check_input_format(variable_memory_max_size):
  246. raise ValueError("Context param variable_memory_max_size should be in correct format! Such as \"5GB\"")
  247. if int(variable_memory_max_size[:-2]) >= _DEVICE_APP_MEMORY_SIZE:
  248. raise ValueError("Context param variable_memory_max_size should be less than 31GB.")
  249. variable_memory_max_size_ = variable_memory_max_size[:-2] + " * 1024 * 1024 * 1024"
  250. graph_memory_max_size = _DEVICE_APP_MEMORY_SIZE - int(variable_memory_max_size[:-2])
  251. graph_memory_max_size_ = str(graph_memory_max_size) + " * 1024 * 1024 * 1024"
  252. self._context_handle.set_variable_memory_max_size(variable_memory_max_size_)
  253. self._context_handle.set_graph_memory_max_size(graph_memory_max_size_)
  254. @property
  255. def enable_ge(self):
  256. return self._context_handle.get_backend_policy() == 'ge'
  257. @property
  258. def enable_debug_runtime(self):
  259. return self._thread_local_info.debug_runtime
  260. @enable_debug_runtime.setter
  261. def enable_debug_runtime(self, enable):
  262. thread_info = self._thread_local_info
  263. thread_info.debug_runtime = enable
  264. @property
  265. def check_bprop(self):
  266. return self._context_handle.get_check_bprop_flag()
  267. @check_bprop.setter
  268. def check_bprop(self, check_bprop_flag):
  269. self._context_handle.set_check_bprop_flag(check_bprop_flag)
  270. @property
  271. def max_device_memory(self):
  272. return self._context_handle.get_max_device_memory()
  273. @max_device_memory.setter
  274. def max_device_memory(self, max_device_memory):
  275. if not check_input_format(max_device_memory):
  276. raise ValueError("Context param max_device_memory should be in correct format! Such as \"3.5GB\"")
  277. max_device_memory_value = float(max_device_memory[:-2])
  278. if max_device_memory_value == 0:
  279. raise ValueError("Context param max_device_memory should be in correct format! Such as \"3.5GB\"")
  280. self._context_handle.set_max_device_memory(max_device_memory_value)
  281. @property
  282. def print_file_path(self):
  283. return None
  284. @print_file_path.setter
  285. def print_file_path(self, file):
  286. self._context_handle.set_print_file_path(file)
  287. def check_input_format(x):
  288. import re
  289. pattern = r'[1-9][0-9]*(\.)?[0-9]*GB|0\.[0-9]*GB'
  290. result = re.match(pattern, x)
  291. return result is not None
  292. _k_context = None
  293. def _context():
  294. """
  295. Get the global _context, if context is not created, create a new one.
  296. Returns:
  297. _Context, the global context in PyNative mode.
  298. """
  299. global _k_context
  300. if _k_context is None:
  301. default_backend = 'debug'
  302. try:
  303. from mindspore import default_config
  304. default_backend = default_config.__backend__
  305. except ImportError:
  306. logger.error("import default config fail")
  307. _k_context = _Context()
  308. _k_context.enable_debug_runtime = False
  309. if default_backend == 'debug':
  310. _k_context.enable_debug_runtime = True
  311. default_backend = 'vm'
  312. _k_context.set_backend_policy(default_backend)
  313. return _k_context
  314. @args_type_check(device_num=int, global_rank=int, mirror_mean=bool, cast_before_mirror=bool, parallel_mode=str,
  315. auto_parallel_search_mode=str, parameter_broadcast=bool, strategy_ckpt_load_file=str,
  316. strategy_ckpt_save_file=str, full_batch=bool)
  317. def set_auto_parallel_context(**kwargs):
  318. """
  319. Set auto parallel context.
  320. Note:
  321. Attribute name is required for setting attributes.
  322. If a program has tasks with different parallel modes, then before setting new parallel mode for
  323. next task, interface mindspore.context.reset_auto_parallel_context() needs to be called to reset
  324. the configuration.
  325. Args:
  326. device_num (int): Available device number, the value must be in [1, 4096]. Default: 1.
  327. global_rank (int): Global rank id, the value must be in [0, 4095]. Default: 0.
  328. mirror_mean (bool): Whether to perform mean operator after all-reduce of mirror.
  329. "stand_alone" do not support mirror_mean. Default: False.
  330. cast_before_mirror (bool): Insert Mirror Op after the cast if this flag is True.
  331. "stand_alone", "data_parallel" and "hybrid_parallel" do not support
  332. cast_before_mirror. Default: True.
  333. parallel_mode (str): There are five kinds of parallel modes, "stand_alone", "data_parallel",
  334. "hybrid_parallel", "semi_auto_parallel" and "auto_parallel". Default: "stand_alone".
  335. - stand_alone: Only one processor working.
  336. - data_parallel: Distributing the data across different processors.
  337. - hybrid_parallel: Achieving data parallelism and model parallelism manually.
  338. - semi_auto_parallel: Achieving data parallelism and model parallelism by
  339. setting parallel strategies.
  340. - auto_parallel: Achieving parallelism automatically.
  341. auto_parallel_search_mode (str): There are two kinds of search modes, "recursive_programming"
  342. and "dynamic_programming". Default: "dynamic_programming".
  343. - recursive_programming: Recursive programming search mode.
  344. - dynamic_programming: Dynamic programming search mode.
  345. parameter_broadcast (bool): Indicating whether to broadcast parameters before training.
  346. "stand_alone", "semi_auto_parallel" and "auto_parallel" do not support parameter
  347. broadcast. Default: False.
  348. strategy_ckpt_load_file (str): The path to load parallel strategy checkpoint. Default: ''
  349. strategy_ckpt_save_file (str): The path to save parallel strategy checkpoint. Default: ''
  350. full_batch (bool): Whether to load the whole batch on each device. Default: False.
  351. Raises:
  352. ValueError: If input key is not attribute in auto parallel context.
  353. Examples:
  354. >>> context.set_auto_parallel_context(device_num=8)
  355. >>> context.set_auto_parallel_context(global_rank=0)
  356. >>> context.set_auto_parallel_context(mirror_mean=True)
  357. >>> context.set_auto_parallel_context(cast_before_mirror=False)
  358. >>> context.set_auto_parallel_context(parallel_mode="auto_parallel")
  359. >>> context.set_auto_parallel_context(parameter_broadcast=False)
  360. >>> context.set_auto_parallel_context(strategy_ckpt_load_file="./strategy_stage1.ckpt")
  361. >>> context.set_auto_parallel_context(strategy_ckpt_save_file="./strategy_stage1.ckpt")
  362. """
  363. _set_auto_parallel_context(**kwargs)
  364. def get_auto_parallel_context(attr_key):
  365. """
  366. Gets auto parallel context attribute value according to the key.
  367. Args:
  368. attr_key (str): The key of the attribute.
  369. Returns:
  370. Returns attribute value according to the key.
  371. Raises:
  372. ValueError: If input key is not attribute in auto parallel context.
  373. """
  374. return _get_auto_parallel_context(attr_key)
  375. def reset_auto_parallel_context():
  376. """
  377. Reset auto parallel context attributes to the default values:
  378. - device_num: 1.
  379. - global_rank: 0.
  380. - mirror_mean: False.
  381. - cast_before_mirror: True.
  382. - parallel_mode: "stand_alone".
  383. - parameter_broadcast: False.
  384. - strategy_ckpt_load_file: "".
  385. - strategy_ckpt_save_file: "".
  386. """
  387. _reset_auto_parallel_context()
  388. @args_type_check(mode=int, precompile_only=bool, device_target=str, device_id=int, save_graphs=bool,
  389. save_graphs_path=str, save_ms_model=bool, save_ms_model_path=str, enable_dump=bool,
  390. save_dump_path=str, enable_reduce_precision=bool, variable_memory_max_size=str,
  391. enable_profiling=bool, profiling_options=str, enable_auto_mixed_precision=bool,
  392. check_bprop=bool, max_device_memory=str, print_file_path=str)
  393. def set_context(**kwargs):
  394. """
  395. Sets context for running environment.
  396. Context should be configured before running your program. If there is no configuration,
  397. the "Ascend" device target will be used by default. GRAPH_MODE or
  398. PYNATIVE_MODE can be set by `mode` attribute and both modes support all backends, default
  399. mode is PYNATIVE_MODE.
  400. When the `save_graphs` attribute is set to True, attribute of `save_graphs_path` is used to set the
  401. intermediate compilation graph storage path. By default, the graphs are saved in the current directory.
  402. As for other configurations and arguments, please refer to the corresponding module
  403. description, the configuration is optional and can be enabled when needed.
  404. Note:
  405. Attribute name is required for setting attributes.
  406. Args:
  407. mode (int): Running in GRAPH_MODE(0) or PYNATIVE_MODE(1). Default: PYNATIVE_MODE.
  408. device_target (str): The target device to run, support "Ascend", "GPU", "CPU". Default: "Ascend".
  409. device_id (int): Id of target device, the value must be in [0, device_num_per_host-1],
  410. while device_num_per_host should no more than 4096. Default: 0.
  411. save_graphs (bool): Whether to save graphs. Default: False.
  412. save_ms_model (bool): Whether to save lite model converted by graph. Default: False.
  413. save_ms_model_path (str): Path to save converted lite model. Default: "."
  414. save_graphs_path (str): Path to save graphs. Default: "."
  415. enable_auto_mixed_precision (bool): Whether to enable auto mixed precision. Default: True.
  416. reserve_class_name_in_scope (bool) : Whether to save the network class name in the scope. Default: True.
  417. enable_reduce_precision (bool): Whether to enable precision reduction. Default: True.
  418. enable_dump (bool): Whether to enable dump. Default: False.
  419. save_dump_path (str): When the program is executed on Ascend, operators can dump data here.
  420. The root dump path is configured in /home/HwHiAiUser/ide_daemon/ide_daemon.cfg.
  421. So the real dump path is "{configured root dump path}/{`save_dump_path`}". Default: ".".
  422. variable_memory_max_size (str): Sets variable memory max size. Default: "5GB".
  423. enable_profiling (bool): Whether to open profiling. Default: False.
  424. profiling_options (str): Sets profiling collection options, operators can profiling data here.
  425. Profiling collection options, the values are as follows, supporting the collection of multiple data.
  426. - training_trace: collect iterative trajectory data, that is, the training task and software information of
  427. the AI software stack, to achieve performance analysis of the training task, focusing on data
  428. enhancement, forward and backward calculation, gradient aggregation update and other related data.
  429. - task_trace: collect task trajectory data, that is, the hardware information of the HWTS/AICore of
  430. the Ascend 910 processor, and analyze the information of start and end of the task.
  431. - op_trace: collect single operator performance data.
  432. The profiling can choose training_trace, task_trace, training_trace and task_trace combination and
  433. separated by colons; single operator can choose op_trace, op_trace cannot be combined with
  434. training_trace and task_trace. Default: "training_trace".
  435. check_bprop (bool): Whether to check bprop. Default: False.
  436. max_device_memory (str): Sets the maximum memory available for device, currently only supported on GPU.
  437. The format is "xxGB". Default: "1024GB".
  438. Raises:
  439. ValueError: If input key is not an attribute in context.
  440. Examples:
  441. >>> context.set_context(mode=context.GRAPH_MODE)
  442. >>> context.set_context(mode=context.PYNATIVE_MODE)
  443. >>> context.set_context(device_target="Ascend")
  444. >>> context.set_context(device_id=0)
  445. >>> context.set_context(save_graphs=True, save_graphs_path="./model.ms")
  446. >>> context.set_context(enable_reduce_precision=True)
  447. >>> context.set_context(save_ms_model=True, save_ms_model_path=".")
  448. >>> context.set_context(enable_dump=True, save_dump_path=".")
  449. >>> context.set_context(reserve_class_name_in_scope=True)
  450. >>> context.set_context(variable_memory_max_size="6GB")
  451. >>> context.set_context(mode=context.GRAPH_MODE,
  452. >>> device_target="Ascend",device_id=0, save_graphs=True,
  453. >>> save_graphs_path="/mindspore")
  454. >>> context.set_context(enable_profiling=True, profiling_options="training_trace")
  455. >>> context.set_context(max_device_memory="3.5GB")
  456. """
  457. for key, value in kwargs.items():
  458. if not hasattr(_context(), key):
  459. raise ValueError("Set context keyword %s is not recognized!" % key)
  460. setattr(_context(), key, value)
  461. def get_context(attr_key):
  462. """
  463. Gets context attribute value according to the input key.
  464. Args:
  465. attr_key (str): The key of the attribute.
  466. Returns:
  467. Object, The value of given attribute key.
  468. Raises:
  469. ValueError: If input key is not an attribute in context.
  470. """
  471. if not hasattr(_context(), attr_key):
  472. raise ValueError("Get context keyword %s is not recognized!" % attr_key)
  473. return getattr(_context(), attr_key)
  474. @args_type_check(enable_mpi=bool)
  475. def set_mpi_config(**kwargs):
  476. """
  477. Sets mpi config for running environment.
  478. mpi config should be configured before running your program. If there is no configuration,
  479. mpi moudle will be disabled by default.
  480. Note:
  481. Attribute name is required for setting attributes.
  482. Args:
  483. enable_mpi (bool): Whether to enable mpi. Default: False.
  484. Raises:
  485. ValueError: If input key is not an attribute in mpi config.
  486. Examples:
  487. >>> mpiconfig.set_mpi_config(enable_mpi=True)
  488. """
  489. _set_mpi_config(**kwargs)
  490. def get_mpi_config(attr_key):
  491. """
  492. Gets mpi config attribute value according to the input key.
  493. Args:
  494. attr_key (str): The key of the attribute.
  495. Returns:
  496. Object, The value of given attribute key.
  497. Raises:
  498. ValueError: If input key is not an attribute in context.
  499. """
  500. return _get_mpi_config(attr_key)