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 30 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  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. includes the execution mode, execution backend and other feature switches.
  18. """
  19. import os
  20. import time
  21. import threading
  22. from collections import namedtuple
  23. from types import FunctionType
  24. from mindspore import log as logger
  25. from mindspore._c_expression import MSContext, ms_ctx_param
  26. from mindspore._checkparam import args_type_check
  27. from mindspore.parallel._auto_parallel_context import _set_auto_parallel_context, _get_auto_parallel_context, \
  28. _reset_auto_parallel_context
  29. from mindspore.parallel._ps_context import _set_ps_context, _get_ps_context, _reset_ps_context
  30. from .default_config import __device_target__, __package_name__
  31. __all__ = ['GRAPH_MODE', 'PYNATIVE_MODE', 'set_context', 'get_context', 'set_auto_parallel_context',
  32. 'get_auto_parallel_context', 'reset_auto_parallel_context', 'ParallelMode', 'set_ps_context',
  33. 'get_ps_context', 'reset_ps_context']
  34. GRAPH_MODE = 0
  35. PYNATIVE_MODE = 1
  36. # The max memory size of graph plus variable.
  37. _DEVICE_APP_MEMORY_SIZE = 31
  38. def _make_directory(path):
  39. """Make directory."""
  40. real_path = None
  41. if path is None or not isinstance(path, str) or path.strip() == "":
  42. raise ValueError(f"Input path `{path}` is invalid type")
  43. # convert the relative paths
  44. path = os.path.realpath(path)
  45. logger.debug("The absolute path is %r", path)
  46. # check whether the path is already existed and has written permissions
  47. if os.path.exists(path):
  48. real_path = path
  49. else:
  50. # All exceptions need to be caught because create directory maybe have some limit(permissions)
  51. logger.debug("The directory(%s) doesn't exist, will create it", path)
  52. try:
  53. os.makedirs(path)
  54. real_path = path
  55. except PermissionError as e:
  56. logger.error(f"No write permission on the directory `{path}, error = {e}")
  57. raise ValueError(f"No write permission on the directory `{path}`.")
  58. return real_path
  59. def _get_print_file_name(file_name):
  60. """Add timestamp suffix to file name. Rename the file name: file_name + "." + time(seconds)."""
  61. time_second = str(int(time.time()))
  62. file_name = file_name + "." + time_second
  63. if os.path.exists(file_name):
  64. ValueError("This file {} already exists.".format(file_name))
  65. return file_name
  66. class _ThreadLocalInfo(threading.local):
  67. """
  68. Thread local Info used for store thread local attributes.
  69. """
  70. def __init__(self):
  71. super(_ThreadLocalInfo, self).__init__()
  72. self._reserve_class_name_in_scope = True
  73. @property
  74. def reserve_class_name_in_scope(self):
  75. """Gets whether to save the network class name in the scope."""
  76. return self._reserve_class_name_in_scope
  77. @reserve_class_name_in_scope.setter
  78. def reserve_class_name_in_scope(self, reserve_class_name_in_scope):
  79. """Sets whether to save the network class name in the scope."""
  80. if not isinstance(reserve_class_name_in_scope, bool):
  81. raise ValueError(
  82. "Set reserve_class_name_in_scope value must be bool!")
  83. self._reserve_class_name_in_scope = reserve_class_name_in_scope
  84. _ContextRecord = namedtuple(
  85. "_ContextRecord", ["is_pynative_mode", "switch_context_fn"])
  86. class _ContextSwitchInfo(threading.local):
  87. """
  88. Record of context switch information.
  89. Args:
  90. is_pynative (bool): Whether to adopt the PyNative mode.
  91. """
  92. def __init__(self, is_pynative):
  93. super(_ContextSwitchInfo, self).__init__()
  94. self.context_stack = []
  95. if is_pynative:
  96. self.push(True, None)
  97. def push(self, is_pynative, switch_context_fn):
  98. """
  99. Push a context switch record onto the stack.
  100. Args:
  101. is_pynative (bool): Whether context switch to PyNative mode.
  102. switch_context_fn (Function): A callable that executes the context switch.
  103. """
  104. if isinstance(switch_context_fn, FunctionType):
  105. switch_context_fn()
  106. self.context_stack.append(
  107. _ContextRecord(is_pynative, switch_context_fn))
  108. def pop(self):
  109. self.context_stack.pop()
  110. class _Context:
  111. """
  112. _Context is the environment in which operations are executed
  113. Note:
  114. Create a context through instantiating Context object is not recommended.
  115. should use context() to get the context since Context is singleton.
  116. """
  117. _instance = None
  118. _instance_lock = threading.Lock()
  119. def __init__(self):
  120. self._thread_local_info = _ThreadLocalInfo()
  121. self._context_switches = _ContextSwitchInfo(True)
  122. self._context_handle = MSContext.get_instance()
  123. def __new__(cls, *args, **kwargs):
  124. if cls._instance is None:
  125. cls._instance_lock.acquire()
  126. cls._instance = object.__new__(cls)
  127. cls._instance_lock.release()
  128. return cls._instance
  129. def __getattribute__(self, attr):
  130. value = object.__getattribute__(self, attr)
  131. if attr == "_context_handle" and value is None:
  132. raise ValueError("Context handle is none in context!!!")
  133. return value
  134. def get_param(self, param):
  135. return self._context_handle.get_param(param)
  136. def set_param(self, param, value):
  137. self._context_handle.set_param(param, value)
  138. def set_mode(self, mode):
  139. """
  140. Switch between Graph mode and PyNative mode.
  141. Args:
  142. mode (int): GRAPH_MODE or PYNATIVE_MODE.
  143. """
  144. if mode == PYNATIVE_MODE:
  145. if self.enable_debug_runtime:
  146. self.set_backend_policy("vm")
  147. self._context_switches.push(True, None)
  148. elif mode == GRAPH_MODE:
  149. if self.enable_debug_runtime:
  150. self.set_backend_policy("ge")
  151. self._context_switches.push(False, None)
  152. else:
  153. raise ValueError(f'The execution mode {mode} is invalid!')
  154. self.set_param(ms_ctx_param.mode, mode)
  155. def set_backend_policy(self, policy):
  156. success = self._context_handle.set_backend_policy(policy)
  157. if not success:
  158. raise RuntimeError("Backend policy must be one of ge, vm, ms.")
  159. def set_save_graphs_path(self, save_graphs_path):
  160. self.set_param(ms_ctx_param.save_graphs_path, _make_directory(save_graphs_path))
  161. def set_device_target(self, target):
  162. valid_targets = ["CPU", "GPU", "Ascend", "Davinci"]
  163. if not target in valid_targets:
  164. raise ValueError(f"Target device name {target} is invalid! It must be one of {valid_targets}")
  165. if target == "Davinci":
  166. target = "Ascend"
  167. self.set_param(ms_ctx_param.device_target, target)
  168. if self.enable_debug_runtime and target == "CPU":
  169. self.set_backend_policy("vm")
  170. def set_device_id(self, device_id):
  171. if device_id < 0 or device_id > 4095:
  172. raise ValueError(f"Device id must be in [0, 4095], but got {device_id}")
  173. self.set_param(ms_ctx_param.device_id, device_id)
  174. def set_max_call_depth(self, max_call_depth):
  175. if max_call_depth <= 0:
  176. raise ValueError(f"Max call depth must be greater than 0, but got {max_call_depth}")
  177. self.set_param(ms_ctx_param.max_call_depth, max_call_depth)
  178. def set_profiling_options(self, option):
  179. options = ["training_trace", "task_trace",
  180. "task_trace:training_trace", "training_trace:task_trace", "op_trace"]
  181. if option not in options:
  182. raise ValueError("Profiling options must be in 'training_trace' 'task_trace' "
  183. "'task_trace:training_trace' 'training_trace:task_trace' or 'op_trace'.")
  184. self.set_param(ms_ctx_param.profiling_options, option)
  185. def set_variable_memory_max_size(self, variable_memory_max_size):
  186. """set values of variable_memory_max_size and graph_memory_max_size"""
  187. if not _check_input_format(variable_memory_max_size):
  188. raise ValueError("Context param variable_memory_max_size should be in correct format! Such as \"5GB\"")
  189. if int(variable_memory_max_size[:-2]) >= _DEVICE_APP_MEMORY_SIZE:
  190. raise ValueError("Context param variable_memory_max_size should be less than 31GB.")
  191. variable_memory_max_size_ = variable_memory_max_size[:-2] + " * 1024 * 1024 * 1024"
  192. graph_memory_max_size = _DEVICE_APP_MEMORY_SIZE - int(variable_memory_max_size[:-2])
  193. graph_memory_max_size_ = str(graph_memory_max_size) + " * 1024 * 1024 * 1024"
  194. self.set_param(ms_ctx_param.variable_memory_max_size, variable_memory_max_size_)
  195. # pylint: disable=protected-access
  196. self.set_param(ms_ctx_param._graph_memory_max_size, graph_memory_max_size_)
  197. def set_max_device_memory(self, max_device_memory):
  198. if not _check_input_format(max_device_memory):
  199. raise ValueError("Context param max_device_memory should be in correct format! Such as \"3.5GB\"")
  200. max_device_memory_value = float(max_device_memory[:-2])
  201. if max_device_memory_value == 0:
  202. raise ValueError("Context param max_device_memory should be in correct format! Such as \"3.5GB\"")
  203. self.set_param(ms_ctx_param.max_device_memory, max_device_memory_value)
  204. def set_print_file_path(self, file_path):
  205. """Add timestamp suffix to file name. Sets print file path."""
  206. print_file_path = os.path.realpath(file_path)
  207. if os.path.isdir(print_file_path):
  208. raise IOError("Print_file_path should be file path, but got {}.".format(file_path))
  209. if os.path.exists(print_file_path):
  210. _path, _file_name = os.path.split(print_file_path)
  211. path = _make_directory(_path)
  212. file_name = _get_print_file_name(_file_name)
  213. full_file_name = os.path.join(path, file_name)
  214. else:
  215. full_file_name = print_file_path
  216. self.set_param(ms_ctx_param.print_file_path, full_file_name)
  217. setters = {
  218. 'mode': set_mode,
  219. 'backend_policy': set_backend_policy,
  220. 'save_graphs_path': set_save_graphs_path,
  221. 'device_target': set_device_target,
  222. 'device_id': set_device_id,
  223. 'max_call_depth': set_max_call_depth,
  224. 'profiling_options': set_profiling_options,
  225. 'variable_memory_max_size': set_variable_memory_max_size,
  226. 'max_device_memory': set_max_device_memory,
  227. 'print_file_path': set_print_file_path
  228. }
  229. @property
  230. def reserve_class_name_in_scope(self):
  231. """Gets whether to save the network class name in the scope."""
  232. return self._thread_local_info.reserve_class_name_in_scope
  233. @reserve_class_name_in_scope.setter
  234. def reserve_class_name_in_scope(self, reserve_class_name_in_scope):
  235. """Sets whether to save the network class name in the scope."""
  236. self._thread_local_info.reserve_class_name_in_scope = reserve_class_name_in_scope
  237. @property
  238. def enable_ge(self):
  239. return self._context_handle.get_backend_policy() == 'ge'
  240. @property
  241. def enable_debug_runtime(self):
  242. return self._thread_local_info.debug_runtime
  243. @enable_debug_runtime.setter
  244. def enable_debug_runtime(self, enable):
  245. thread_info = self._thread_local_info
  246. thread_info.debug_runtime = enable
  247. def _check_input_format(x):
  248. import re
  249. pattern = r'[1-9][0-9]*(\.)?[0-9]*GB|0\.[0-9]*GB'
  250. result = re.match(pattern, x)
  251. return result is not None
  252. _k_context = None
  253. def _context():
  254. """
  255. Get the global _context, if context is not created, create a new one.
  256. Returns:
  257. _Context, the global context in PyNative mode.
  258. """
  259. global _k_context
  260. if _k_context is None:
  261. default_backend = 'debug'
  262. try:
  263. from mindspore import default_config
  264. default_backend = default_config.__backend__
  265. except ImportError:
  266. logger.error("import default config fail")
  267. _k_context = _Context()
  268. _k_context.enable_debug_runtime = False
  269. if default_backend == 'debug':
  270. _k_context.enable_debug_runtime = True
  271. default_backend = 'vm'
  272. _k_context.set_backend_policy(default_backend)
  273. return _k_context
  274. @args_type_check(device_num=int, global_rank=int, gradients_mean=bool, gradient_fp32_sync=bool, parallel_mode=str,
  275. auto_parallel_search_mode=str, parameter_broadcast=bool, strategy_ckpt_load_file=str,
  276. strategy_ckpt_save_file=str, full_batch=bool, enable_parallel_optimizer=bool,
  277. all_reduce_fusion_config=list)
  278. def set_auto_parallel_context(**kwargs):
  279. """
  280. Set auto parallel context.
  281. Note:
  282. Attribute name is required for setting attributes.
  283. If a program has tasks with different parallel modes, then before setting new parallel mode for the
  284. next task, interface mindspore.context.reset_auto_parallel_context() needs to be called to reset
  285. the configuration.
  286. Setting or changing parallel modes must be called before any creating Initializer, otherwise,
  287. RuntimeError may be raised when compiling the network.
  288. Args:
  289. device_num (int): Available device number, the value must be in [1, 4096]. Default: 1.
  290. global_rank (int): Global rank id, the value must be in [0, 4095]. Default: 0.
  291. gradients_mean (bool): Whether to perform mean operator after all-reduce of mirror.
  292. "stand_alone" does not support `gradients_mean`. Default: False.
  293. gradient_fp32_sync (bool): Gradients allreduce by fp32, even though gradients is fp16 if this flag is True..
  294. "stand_alone", "data_parallel" and "hybrid_parallel" do not support
  295. gradient_fp32_sync. Default: True.
  296. parallel_mode (str): There are five kinds of parallel modes, "stand_alone", "data_parallel",
  297. "hybrid_parallel", "semi_auto_parallel" and "auto_parallel". Default: "stand_alone".
  298. - stand_alone: Only one processor is working.
  299. - data_parallel: Distributes the data across different processors.
  300. - hybrid_parallel: Achieves data parallelism and model parallelism manually.
  301. - semi_auto_parallel: Achieves data parallelism and model parallelism by
  302. setting parallel strategies.
  303. - auto_parallel: Achieves parallelism automatically.
  304. auto_parallel_search_mode (str): There are two kinds of search modes, "recursive_programming"
  305. and "dynamic_programming". Default: "dynamic_programming".
  306. - recursive_programming: Recursive programming search mode.
  307. - dynamic_programming: Dynamic programming search mode.
  308. parameter_broadcast (bool): Whether to broadcast parameters before training.
  309. "stand_alone", "semi_auto_parallel" and "auto_parallel" do not support parameter
  310. broadcast. Default: False.
  311. strategy_ckpt_load_file (str): The path to load parallel strategy checkpoint. Default: ''
  312. strategy_ckpt_save_file (str): The path to save parallel strategy checkpoint. Default: ''
  313. full_batch (bool): Whether to load the whole batch on each device. Default: False.
  314. enable_parallel_optimizer (bool): This is a developing feature, which shards the weight update computation in
  315. data parallel training in the benefit of time and memory saving.
  316. all_reduce_fusion_config (list): Set allreduce fusion strategy by parameters indices. Only support ReduceOp.SUM
  317. and HCCL_WORLD_GROUP/NCCL_WORLD_GROUP.
  318. Raises:
  319. ValueError: If input key is not attribute in auto parallel context.
  320. Examples:
  321. >>> context.set_auto_parallel_context(device_num=8)
  322. >>> context.set_auto_parallel_context(global_rank=0)
  323. >>> context.set_auto_parallel_context(gradients_mean=True)
  324. >>> context.set_auto_parallel_context(gradient_fp32_sync=False)
  325. >>> context.set_auto_parallel_context(parallel_mode="auto_parallel")
  326. >>> context.set_auto_parallel_context(parameter_broadcast=False)
  327. >>> context.set_auto_parallel_context(strategy_ckpt_load_file="./strategy_stage1.ckpt")
  328. >>> context.set_auto_parallel_context(strategy_ckpt_save_file="./strategy_stage1.ckpt")
  329. """
  330. _set_auto_parallel_context(**kwargs)
  331. def get_auto_parallel_context(attr_key):
  332. """
  333. Gets auto parallel context attribute value according to the key.
  334. Args:
  335. attr_key (str): The key of the attribute.
  336. Returns:
  337. Returns attribute value according to the key.
  338. Raises:
  339. ValueError: If input key is not attribute in auto parallel context.
  340. """
  341. return _get_auto_parallel_context(attr_key)
  342. def reset_auto_parallel_context():
  343. """
  344. Reset auto parallel context attributes to the default values:
  345. - device_num: 1.
  346. - global_rank: 0.
  347. - gradients_mean: False.
  348. - gradient_fp32_sync: True.
  349. - parallel_mode: "stand_alone".
  350. - parameter_broadcast: False.
  351. - strategy_ckpt_load_file: "".
  352. - strategy_ckpt_save_file: "".
  353. - enable_parallel_optimizer: False.
  354. """
  355. _reset_auto_parallel_context()
  356. def _check_target_specific_cfgs(device, arg_key):
  357. """Checking whether a config is sutable for a specified device"""
  358. device_cfgs = {
  359. 'enable_auto_mixed_precision': ['Ascend'],
  360. 'enable_dump': ['Ascend'],
  361. 'enable_profiling': ['Ascend'],
  362. 'variable_memory_max_size': ['Ascend'],
  363. 'max_device_memory': ['GPU']
  364. }
  365. # configs not in map device_cfgs are supposed to be suitable for all devices
  366. if not arg_key in device_cfgs:
  367. return True
  368. supported_devices = device_cfgs[arg_key]
  369. if device in supported_devices:
  370. return True
  371. logger.warning(f"Config '{arg_key}' only supports devices in {supported_devices}, current device is '{device}'"
  372. ", ignore it.")
  373. return False
  374. @args_type_check(mode=int, precompile_only=bool, device_target=str, device_id=int, save_graphs=bool,
  375. save_graphs_path=str, enable_dump=bool,
  376. save_dump_path=str, enable_reduce_precision=bool, variable_memory_max_size=str,
  377. enable_profiling=bool, profiling_options=str, enable_auto_mixed_precision=bool,
  378. enable_graph_kernel=bool, check_bprop=bool, max_device_memory=str, print_file_path=str,
  379. enable_sparse=bool, max_call_depth=int)
  380. def set_context(**kwargs):
  381. """
  382. Sets context for running environment.
  383. Context should be configured before running your program. If there is no configuration,
  384. the "Ascend" device target will be used by default. GRAPH_MODE or
  385. PYNATIVE_MODE can be set by `mode` attribute and both modes support all backends, default
  386. mode is PYNATIVE_MODE.
  387. When the `save_graphs` attribute is set to True, attribute of `save_graphs_path` is used to set the
  388. intermediate compilation graph storage path. By default, the graphs are saved in the current directory.
  389. For other configurations and arguments, please refer to the corresponding module
  390. description, the configuration is optional and can be enabled when needed.
  391. Note:
  392. Attribute name is required for setting attributes.
  393. The mode is not recommended to be changed after net was initilized because the implementations of some
  394. operations are different in graph mode and pynative mode. Default: PYNATIVE_MODE.
  395. Some configurations are device specific, see the bellow table for details:
  396. =========================== =========================== =================
  397. Common(CPU/GPU/Asecend) Ascend GPU
  398. =========================== =========================== =================
  399. check_bprop enable_auto_mixed_precision max_device_memory
  400. device_id enable_dump
  401. device_target enable_profiling
  402. enable_graph_kernel variable_memory_max_size
  403. enable_reduce_precision
  404. enable_sparse
  405. mode
  406. print_file_path
  407. profiling_options
  408. reserve_class_name_in_scope
  409. save_dump_path
  410. save_graphs
  411. save_graphs_path
  412. =========================== =========================== =================
  413. Args:
  414. mode (int): Running in GRAPH_MODE(0) or PYNATIVE_MODE(1). Default: PYNATIVE_MODE(1).
  415. device_target (str): The target device to run, support "Ascend", "GPU", and "CPU". Default: "Ascend".
  416. device_id (int): ID of the target device, the value must be in [0, device_num_per_host-1],
  417. while device_num_per_host should be no more than 4096. Default: 0.
  418. save_graphs (bool): Whether to save graphs. Default: False.
  419. save_graphs_path (str): Path to save graphs. Default: "."
  420. enable_auto_mixed_precision (bool): Whether to enable auto mixed precision. Default: False.
  421. enable_graph_kernel (bool): Whether to enable composition of basic primitives. These primitives would be
  422. compiled into a fused kernel automatically. Default: False.
  423. reserve_class_name_in_scope (bool) : Whether to save the network class name in the scope. Default: True.
  424. enable_reduce_precision (bool): Whether to enable precision reduction. Default: True.
  425. enable_dump (bool): Whether to enable dump. Default: False.
  426. save_dump_path (str): When the program is executed on Ascend, operators can dump data in this path.
  427. The root dump path is configured in /home/HwHiAiUser/ide_daemon/ide_daemon.cfg.
  428. So the real dump path is "{configured root dump path}/{`save_dump_path`}". Default: ".".
  429. variable_memory_max_size (str): Set the maximum size of the variable memory max size. Default: "0GB".
  430. enable_profiling (bool): Whether to open profiling. Default: False.
  431. profiling_options (str): Set profiling collection options, operators can profiling data here.
  432. The values of profiling collection options are as follows, supporting the collection of multiple data.
  433. - training_trace: collect iterative trajectory data, that is, the training task and software information of
  434. the AI software stack, to achieve performance analysis of the training task, focusing on data
  435. enhancement, forward and backward calculation, gradient aggregation update and other related data.
  436. - task_trace: collect task trajectory data, that is, the hardware information of the HWTS/AICore of
  437. the Ascend 910 processor, and analyze the information of beginning and ending of the task.
  438. - op_trace: collect single operator performance data.
  439. The profiling can choose the combination of `training_trace`, `task_trace`,
  440. `training_trace` and `task_trace` combination, and eparated by colons;
  441. a single operator can choose `op_trace`, `op_trace` cannot be combined with
  442. `training_trace` and `task_trace`. Default: "training_trace".
  443. check_bprop (bool): Whether to check bprop. Default: False.
  444. max_device_memory (str): Sets the maximum memory available for devices.
  445. Currently, it is only supported on GPU. The format is "xxGB". Default: "1024GB".
  446. print_file_path (str): The path of saving print data. If this parameter is set, print data is saved to
  447. a file by default, and turns off printing to the screen. If the file already exists, add a timestamp
  448. suffix to the file. Default: ''.
  449. enable_sparse (bool): Whether to enable sparsity feature. Default: False.
  450. max_call_depth(int): Specify the maximum depth of function call. Default: 1000.
  451. Raises:
  452. ValueError: If input key is not an attribute in context.
  453. Examples:
  454. >>> context.set_context(mode=context.GRAPH_MODE)
  455. >>> context.set_context(mode=context.PYNATIVE_MODE)
  456. >>> context.set_context(device_target="Ascend")
  457. >>> context.set_context(device_id=0)
  458. >>> context.set_context(save_graphs=True, save_graphs_path="./model.ms")
  459. >>> context.set_context(enable_reduce_precision=True)
  460. >>> context.set_context(enable_dump=True, save_dump_path=".")
  461. >>> context.set_context(reserve_class_name_in_scope=True)
  462. >>> context.set_context(variable_memory_max_size="6GB")
  463. >>> context.set_context(mode=context.GRAPH_MODE,
  464. >>> device_target="Ascend",device_id=0, save_graphs=True,
  465. >>> save_graphs_path="/mindspore")
  466. >>> context.set_context(enable_profiling=True, profiling_options="training_trace")
  467. >>> context.set_context(max_device_memory="3.5GB")
  468. >>> context.set_context(print_file_path="print.pb")
  469. >>> context.set_context(max_call_depth=80)
  470. """
  471. ctx = _context()
  472. # set device target first
  473. if 'device_target' in kwargs:
  474. ctx.set_device_target(kwargs['device_target'])
  475. device = ctx.get_param(ms_ctx_param.device_target)
  476. if not device.lower() in __device_target__:
  477. raise ValueError(f"Error, package type {__package_name__} support device type {__device_target__}, "
  478. f"but got device target {device}")
  479. device = ctx.get_param(ms_ctx_param.device_target)
  480. for key, value in kwargs.items():
  481. if not _check_target_specific_cfgs(device, key):
  482. continue
  483. if hasattr(ctx, key):
  484. setattr(ctx, key, value)
  485. continue
  486. if key in ctx.setters:
  487. ctx.setters[key](ctx, value)
  488. continue
  489. # enum variables begining with '_' are for internal use
  490. if key in ms_ctx_param.__members__ and key[0] != '_':
  491. ctx.set_param(ms_ctx_param.__members__[key], value)
  492. continue
  493. raise ValueError("Set context keyword %s is not recognized!" % key)
  494. def get_context(attr_key):
  495. """
  496. Gets context attribute value according to the input key.
  497. Args:
  498. attr_key (str): The key of the attribute.
  499. Returns:
  500. Object, The value of given attribute key.
  501. Raises:
  502. ValueError: If input key is not an attribute in context.
  503. """
  504. ctx = _context()
  505. device = ctx.get_param(ms_ctx_param.device_target)
  506. _ = _check_target_specific_cfgs(device, attr_key)
  507. if hasattr(ctx, attr_key):
  508. return getattr(ctx, attr_key)
  509. # enum variables begining with '_' are for internal use
  510. if attr_key in ms_ctx_param.__members__ and attr_key[0] != '_':
  511. return ctx.get_param(ms_ctx_param.__members__[attr_key])
  512. raise ValueError("Get context keyword %s is not recognized!" % attr_key)
  513. class ParallelMode:
  514. """
  515. Parallel mode options.
  516. There are five kinds of parallel modes, "STAND_ALONE", "DATA_PARALLEL",
  517. "HYBRID_PARALLEL", "SEMI_AUTO_PARALLEL" and "AUTO_PARALLEL". Default: "STAND_ALONE".
  518. - STAND_ALONE: Only one processor is working.
  519. - DATA_PARALLEL: Distributes the data across different processors.
  520. - HYBRID_PARALLEL: Achieves data parallelism and model parallelism manually.
  521. - SEMI_AUTO_PARALLEL: Achieves data parallelism and model parallelism by setting parallel strategies.
  522. - AUTO_PARALLEL: Achieves parallelism automatically.
  523. MODE_LIST: The list of all supported parallel modes.
  524. """
  525. STAND_ALONE = "stand_alone"
  526. DATA_PARALLEL = "data_parallel"
  527. HYBRID_PARALLEL = "hybrid_parallel"
  528. SEMI_AUTO_PARALLEL = "semi_auto_parallel"
  529. AUTO_PARALLEL = "auto_parallel"
  530. MODE_LIST = [STAND_ALONE, DATA_PARALLEL, HYBRID_PARALLEL, SEMI_AUTO_PARALLEL, AUTO_PARALLEL]
  531. @args_type_check(enable_ps=bool)
  532. def set_ps_context(**kwargs):
  533. """
  534. Set parameter server training mode context.
  535. Note:
  536. Some other environment variables should also be set for parameter server training mode.
  537. These environment variables are listed below:
  538. MS_SERVER_NUM # Server number
  539. MS_WORKER_NUM # Worker number
  540. MS_SCHED_HOST # Scheduler IP address
  541. MS_SCHED_PORT # Scheduler port
  542. MS_ROLE # The role of this process:
  543. MS_SCHED represents the scheduler,
  544. MS_WORKER represents the worker,
  545. MS_PSERVER represents the Server
  546. Args:
  547. enable_ps (bool): Whether to enable parameter server training mode.
  548. Only after enable_ps is set True, the environment variables will be effective.
  549. Default: False.
  550. Raises:
  551. ValueError: If input key is not the attribute in parameter server training mode context.
  552. Examples:
  553. >>> context.set_ps_context(enable_ps=True)
  554. """
  555. _set_ps_context(**kwargs)
  556. def get_ps_context(attr_key):
  557. """
  558. Get parameter server training mode context attribute value according to the key.
  559. Args:
  560. attr_key (str): The key of the attribute.
  561. Returns:
  562. Returns attribute value according to the key.
  563. Raises:
  564. ValueError: If input key is not attribute in auto parallel context.
  565. """
  566. return _get_ps_context(attr_key)
  567. def reset_ps_context():
  568. """
  569. Reset parameter server training mode context attributes to the default values:
  570. - enable_ps: False.
  571. """
  572. _reset_ps_context()