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

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