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

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