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.

_auto_parallel_context.py 33 kB

5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  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. """Context of auto parallel"""
  16. import threading
  17. import mindspore.context as context
  18. import mindspore.log as logger
  19. from mindspore.parallel._dp_allreduce_fusion import _set_fusion_strategy_by_idx, _set_fusion_strategy_by_size
  20. from mindspore.parallel._ps_context import _is_role_pserver
  21. from mindspore._c_expression import AutoParallelContext
  22. from mindspore._checkparam import args_type_check, Validator
  23. _MAX_GROUP_NAME_LEN = 127
  24. _DEFAULT_HCCL_FUSION_GROUP_NAME = "hccl_world_groupsum1"
  25. _DEFAULT_NCCL_FUSION_GROUP_NAME = "nccl_world_groupsum1"
  26. class _AutoParallelContext:
  27. """
  28. _AutoParallelContext is the environment in which operations are executed
  29. Note:
  30. Create a context through instantiating Context object is not recommended.
  31. Should use auto_parallel_context() to get the context since Context is singleton.
  32. """
  33. _instance = None
  34. _instance_lock = threading.Lock()
  35. def __init__(self):
  36. self._context_handle = AutoParallelContext.get_instance()
  37. def __new__(cls):
  38. if cls._instance is None:
  39. cls._instance_lock.acquire()
  40. cls._instance = object.__new__(cls)
  41. cls._instance_lock.release()
  42. return cls._instance
  43. def check_context_handle(self):
  44. """
  45. Check context handle.
  46. Raises:
  47. ValueError: If the context handle is none.
  48. """
  49. if self._context_handle is None:
  50. raise ValueError("Context handle is none in context!!!")
  51. def set_device_num(self, device_num):
  52. """
  53. Set device num for auto parallel.
  54. Args:
  55. device_num (int): The device number.
  56. Raises:
  57. ValueError: If the device num is not in [1, 4096].
  58. """
  59. self.check_context_handle()
  60. if device_num < 1 or device_num > 4096:
  61. raise ValueError("Device num must be in [1, 4096], but got {}".format(device_num))
  62. self._context_handle.set_device_num(device_num)
  63. def get_device_num(self):
  64. """Get device num."""
  65. self.check_context_handle()
  66. return self._context_handle.get_device_num()
  67. def set_global_rank(self, global_rank):
  68. """
  69. Set global rank for auto parallel.
  70. Args:
  71. global_rank (int): The rank id of current rank.
  72. Raises:
  73. ValueError: If the global rank is not in [1, 4096].
  74. """
  75. self.check_context_handle()
  76. if global_rank < 0 or global_rank > 4095:
  77. raise ValueError("Global rank must be in [0, 4095], but got {}".format(global_rank))
  78. self._context_handle.set_global_rank(global_rank)
  79. def get_global_rank(self):
  80. """Get current rank id."""
  81. self.check_context_handle()
  82. return self._context_handle.get_global_rank()
  83. def set_pipeline_stages(self, stages):
  84. """Set the stages of the pipeline"""
  85. if isinstance(stages, bool):
  86. raise TypeError("The type of pipeline_stage_num must be int, but got bool.")
  87. if not isinstance(stages, int):
  88. raise TypeError("The type of pipeline_stage_num must be int.")
  89. if stages < 1:
  90. raise ValueError("pipeline_stage_num can't be less than 1.")
  91. self.check_context_handle()
  92. self._context_handle.set_pipeline_stage_split_num(stages)
  93. def get_pipeline_stages(self):
  94. """Get the stages of the pipeline"""
  95. self.check_context_handle()
  96. return self._context_handle.get_pipeline_stage_split_num()
  97. def set_gradients_mean(self, gradients_mean):
  98. """
  99. Set gradients_mean flag.
  100. Note:
  101. If gradients_mean is true, it will insert a div operator after parameter gradients allreduce.
  102. Args:
  103. gradients_mean (bool): The gradients_mean flag.
  104. """
  105. self.check_context_handle()
  106. self._context_handle.set_gradients_mean(gradients_mean)
  107. def get_gradients_mean(self):
  108. """Get gradients_mean flag."""
  109. self.check_context_handle()
  110. return self._context_handle.get_gradients_mean()
  111. def set_gradient_fp32_sync(self, gradient_fp32_sync):
  112. """
  113. Set gradient_fp32_sync.
  114. Note:
  115. If gradient_fp32_sync is true,
  116. it will convert tensor type from fp16 to fp32 before parameter gradients allreduce.
  117. Args:
  118. gradient_fp32_sync (bool): The gradient_fp32_sync flag.
  119. """
  120. self.check_context_handle()
  121. self._context_handle.set_gradient_fp32_sync(gradient_fp32_sync)
  122. def get_gradient_fp32_sync(self):
  123. """Get gradient_fp32_sync flag."""
  124. self.check_context_handle()
  125. return self._context_handle.get_gradient_fp32_sync()
  126. def set_loss_repeated_mean(self, loss_repeated_mean):
  127. """
  128. Set loss_repeated_mean flag.
  129. Note:
  130. If loss_repeated_mean is true,
  131. Distributed automatic differentiation will perform a mean operator
  132. in backward in the case of repeated calculations.
  133. Args:
  134. loss_repeated_mean (bool): The loss_repeated_mean flag.
  135. """
  136. self.check_context_handle()
  137. self._context_handle.set_loss_repeated_mean(loss_repeated_mean)
  138. def get_loss_repeated_mean(self):
  139. """Get loss_repeated_mean flag."""
  140. self.check_context_handle()
  141. return self._context_handle.get_loss_repeated_mean()
  142. def set_parallel_mode(self, parallel_mode):
  143. """
  144. Set parallel mode for auto parallel.
  145. Args:
  146. parallel_mode (str): The parallel mode of auto parallel.
  147. Raises:
  148. ValueError: If parallel mode is not supported.
  149. """
  150. self.check_context_handle()
  151. ret = self._context_handle.set_parallel_mode(parallel_mode)
  152. if ret is False:
  153. raise ValueError("Parallel mode does not support {}".format(parallel_mode))
  154. def get_parallel_mode(self):
  155. """Get parallel mode."""
  156. self.check_context_handle()
  157. if _is_role_pserver():
  158. return context.ParallelMode.STAND_ALONE
  159. return self._context_handle.get_parallel_mode()
  160. def set_strategy_search_mode(self, auto_parallel_search_mode):
  161. """
  162. Set search mode of strategy.
  163. Args:
  164. auto_parallel_search_mode (str): The search mode of strategy.
  165. """
  166. self.check_context_handle()
  167. ret = self._context_handle.set_strategy_search_mode(auto_parallel_search_mode)
  168. if ret is False:
  169. raise ValueError("Strategy search mode does not support {}".format(auto_parallel_search_mode))
  170. def get_strategy_search_mode(self):
  171. """Get search mode of strategy."""
  172. self.check_context_handle()
  173. return self._context_handle.get_strategy_search_mode()
  174. def set_parameter_broadcast(self, parameter_broadcast):
  175. """
  176. Set parameter broadcast.
  177. Args:
  178. parameter_broadcast (bool): Parameter broadcast or not.
  179. """
  180. self.check_context_handle()
  181. self._context_handle.set_parameter_broadcast(parameter_broadcast)
  182. def get_parameter_broadcast(self):
  183. """Get parameter broadcast flag."""
  184. self.check_context_handle()
  185. return self._context_handle.get_parameter_broadcast()
  186. def set_strategy_ckpt_load_file(self, strategy_ckpt_load_file):
  187. """
  188. Set strategy checkpoint load path.
  189. Args:
  190. strategy_ckpt_load_file (bool): Path to load parallel strategy checkpoint.
  191. """
  192. self.check_context_handle()
  193. self._context_handle.set_strategy_ckpt_load_file(strategy_ckpt_load_file)
  194. def get_strategy_ckpt_load_file(self):
  195. """Get strategy checkpoint load path."""
  196. self.check_context_handle()
  197. return self._context_handle.get_strategy_ckpt_load_file()
  198. def set_full_batch(self, full_batch):
  199. """
  200. Set whether load full batch on each device.
  201. Args:
  202. full_batch (bool): True if load full batch on each device.
  203. """
  204. self.check_context_handle()
  205. self._context_handle.set_full_batch(full_batch)
  206. def get_full_batch(self):
  207. """Get whether load full batch on each device."""
  208. self.check_context_handle()
  209. if _is_role_pserver():
  210. return False
  211. return self._context_handle.get_full_batch()
  212. def set_dataset_strategy(self, dataset_strategy):
  213. """
  214. Set dataset sharding strategy.
  215. Args:
  216. dataset_strategy (tuple(tuple)): The dataset sharding strategy.
  217. """
  218. self.check_context_handle()
  219. if not isinstance(dataset_strategy, tuple):
  220. raise TypeError(f'strategy must be tuple type, but got:{type(dataset_strategy)}')
  221. for ele in dataset_strategy:
  222. if not isinstance(ele, tuple):
  223. raise TypeError(f'The element of strategy must be tuple type, but got:{type(ele)}')
  224. for dim in ele:
  225. if not isinstance(dim, int):
  226. raise TypeError(f'The dim of each strategy value must be int type, but got:{type(dim)}')
  227. self._context_handle.set_dataset_strategy(dataset_strategy)
  228. def get_dataset_strategy(self):
  229. """Get dataset sharding strategy."""
  230. self.check_context_handle()
  231. if _is_role_pserver():
  232. return False
  233. return self._context_handle.get_dataset_strategy()
  234. def set_grad_accumulation_step(self, grad_accumulation_step):
  235. """
  236. Set grad accumulation step.
  237. Args:
  238. grad_accumulation_step (int): The grad accumulation step.
  239. """
  240. self.check_context_handle()
  241. Validator.check_positive_int(grad_accumulation_step)
  242. self._context_handle.set_grad_accumulation_step(grad_accumulation_step)
  243. def get_grad_accumulation_step(self):
  244. """Get grad accumulation step."""
  245. self.check_context_handle()
  246. return self._context_handle.get_grad_accumulation_step()
  247. def set_strategy_ckpt_save_file(self, strategy_ckpt_save_file):
  248. """
  249. Set strategy checkpoint save path.
  250. Args:
  251. strategy_ckpt_save_file (bool): Path to save parallel strategy checkpoint.
  252. """
  253. self.check_context_handle()
  254. import os
  255. dir_path = os.path.dirname(strategy_ckpt_save_file)
  256. if dir_path and not os.path.exists(dir_path):
  257. os.makedirs(dir_path)
  258. self._context_handle.set_strategy_ckpt_save_file(strategy_ckpt_save_file)
  259. def get_strategy_ckpt_save_file(self):
  260. """Get strategy checkpoint save path."""
  261. self.check_context_handle()
  262. return self._context_handle.get_strategy_ckpt_save_file()
  263. def set_group_ckpt_save_file(self, group_ckpt_save_file):
  264. """Set group checkpoint save path."""
  265. self.check_context_handle()
  266. import os
  267. dir_path = os.path.dirname(group_ckpt_save_file)
  268. if dir_path and not os.path.exists(dir_path):
  269. os.makedirs(dir_path)
  270. self._context_handle.set_group_ckpt_save_file(group_ckpt_save_file)
  271. def get_parameter_broadcast_is_set(self):
  272. """Get parameter broadcast is set or not."""
  273. self.check_context_handle()
  274. return self._context_handle.get_parameter_broadcast_is_set()
  275. def set_all_reduce_fusion_split_indices(self, indices, group=""):
  276. """
  277. Set allreduce fusion strategy by parameters indices.
  278. Args:
  279. indices (list): Indices list.
  280. group (str): The communication group of hccl/nccl.
  281. Raises:
  282. TypeError: If type of indices item is not int.
  283. TypeError: If group is not a python str.
  284. """
  285. self.check_context_handle()
  286. if not indices:
  287. raise ValueError('indices can not be empty')
  288. if isinstance(indices, (list)):
  289. for index in indices:
  290. if not isinstance(index, int):
  291. raise TypeError('indices has invalid value')
  292. else:
  293. raise TypeError('indices must be a python list')
  294. if len(set(indices)) != len(indices):
  295. raise ValueError('indices has duplicate elements')
  296. if sorted(indices) != indices:
  297. raise ValueError('elements in indices must be sorted in ascending order')
  298. new_group = self._check_and_default_group(group)
  299. self._context_handle.set_all_reduce_fusion_split_indices(indices, new_group)
  300. if context.get_context("device_target") == "Ascend" and context.get_context("enable_ge"):
  301. _set_fusion_strategy_by_idx(indices)
  302. def get_all_reduce_fusion_split_indices(self, group=""):
  303. """
  304. Get allreduce fusion split indices.
  305. Args:
  306. group (str): The communication group of hccl/nccl.
  307. Returns:
  308. Return split sizes list according to the group.
  309. Raises:
  310. TypeError: If group is not a python str.
  311. """
  312. self.check_context_handle()
  313. new_group = self._check_and_default_group(group)
  314. return self._context_handle.get_all_reduce_fusion_split_indices(new_group)
  315. def set_all_reduce_fusion_split_sizes(self, sizes, group=""):
  316. """
  317. Set allreduce fusion strategy by parameters data sizes.
  318. Args:
  319. sizes (list): Sizes list.
  320. group (str): The communication group of hccl/nccl.
  321. Raises:
  322. TypeError: If type of sizes item is not int.
  323. TypeError: If group is not a python str.
  324. """
  325. self.check_context_handle()
  326. if isinstance(sizes, (list)):
  327. for size in sizes:
  328. if not isinstance(size, int):
  329. raise TypeError('sizes has invalid value')
  330. else:
  331. raise TypeError('sizes must be a python list')
  332. new_group = self._check_and_default_group(group)
  333. self._context_handle.set_all_reduce_fusion_split_sizes(sizes, new_group)
  334. if context.get_context("device_target") == "Ascend":
  335. _set_fusion_strategy_by_size(sizes)
  336. def get_all_reduce_fusion_split_sizes(self, group=""):
  337. """
  338. Get allreduce fusion split sizes.
  339. Args:
  340. group (str): The communication group of hccl/nccl.
  341. Returns:
  342. Return split sizes list according to the group.
  343. Raises:
  344. TypeError: If group is not a python str.
  345. """
  346. self.check_context_handle()
  347. new_group = self._check_and_default_group(group)
  348. return self._context_handle.get_all_reduce_fusion_split_sizes(new_group)
  349. def set_enable_all_reduce_fusion(self, enable_all_reduce_fusion):
  350. """
  351. Set enable/disable all reduce fusion.
  352. Args:
  353. enable_all_reduce_fusion (bool): Enable/disable all reduce fusion.
  354. """
  355. self.check_context_handle()
  356. if not isinstance(enable_all_reduce_fusion, bool):
  357. raise TypeError('enable_all_reduce_fusion is invalid type')
  358. self._context_handle.set_enable_all_reduce_fusion(enable_all_reduce_fusion)
  359. def get_enable_all_reduce_fusion(self):
  360. """Get all reduce fusion flag."""
  361. self.check_context_handle()
  362. return self._context_handle.get_enable_all_reduce_fusion()
  363. def get_device_num_is_set(self):
  364. """Get device number is set or not."""
  365. self.check_context_handle()
  366. return self._context_handle.get_device_num_is_set()
  367. def get_global_rank_is_set(self):
  368. """Get global rank is set or not."""
  369. self.check_context_handle()
  370. return self._context_handle.get_global_rank_is_set()
  371. def set_enable_parallel_optimizer(self, enable_parallel_optimizer):
  372. """
  373. Set enable/disable parallel optimizer.
  374. Args:
  375. set_enable_parallel_optimizer (bool): Enable/disable parallel optimizer.
  376. """
  377. self.check_context_handle()
  378. if not isinstance(enable_parallel_optimizer, bool):
  379. raise TypeError('enable_parallel_optimizer is invalid type')
  380. self._context_handle.set_enable_parallel_optimizer(enable_parallel_optimizer)
  381. def get_enable_parallel_optimizer(self):
  382. """Get parallel optimizer flag."""
  383. self.check_context_handle()
  384. return self._context_handle.get_enable_parallel_optimizer()
  385. def set_sharding_propagation(self, sharding_propagation):
  386. """
  387. Set the value of sharding strategy propagation in AUTO_PARALLEL mode. If True, the strategy-configured operators
  388. will propagate the strategies to other operators with minimum redistribution cost; otherwise, the algorithm
  389. will search the desired strategies.
  390. Default: False.
  391. Args:
  392. sharding_propagation (bool): Enable/disable strategy propagation.
  393. """
  394. self.check_context_handle()
  395. if not isinstance(sharding_propagation, bool):
  396. raise TypeError("'sharding_propagation' is an invalid type.")
  397. self._context_handle.set_sharding_propagation(sharding_propagation)
  398. def get_sharding_propagation(self):
  399. """Get the value of sharding strategy propagation."""
  400. self.check_context_handle()
  401. return self._context_handle.get_sharding_propagation()
  402. def set_enable_alltoall(self, enable_a2a):
  403. """
  404. Set the value of enabling AllToAll. If False, AllGather and Split are used to circumvent AllToAll.
  405. Default: False.
  406. Args:
  407. enable_a2a (bool): Enable/disable AllToAll.
  408. """
  409. self.check_context_handle()
  410. if not isinstance(enable_a2a, bool):
  411. raise TypeError("'enable_a2a' is an invalid type.")
  412. self._context_handle.set_enable_alltoall(enable_a2a)
  413. def get_enable_alltoall(self):
  414. """Get the value of enabling AllToAll."""
  415. self.check_context_handle()
  416. return self._context_handle.get_enable_alltoall()
  417. def set_communi_parallel_mode(self, communi_parallel_mode):
  418. """
  419. Set communication parallel mode.
  420. Args:
  421. communi_parallel_mode (str): The communication parallel mode.
  422. Raises:
  423. ValueError: If parallel mode is not supported.
  424. """
  425. self.check_context_handle()
  426. ret = self._context_handle.set_communi_parallel_mode(communi_parallel_mode)
  427. if ret is False:
  428. raise ValueError("Communication parallel mode does not support {}".format(communi_parallel_mode))
  429. def get_communi_parallel_mode(self):
  430. """Get communication parallel mode."""
  431. self.check_context_handle()
  432. return self._context_handle.get_communi_parallel_mode()
  433. def set_optimizer_weight_shard_size(self, optimizer_weight_shard_size):
  434. """
  435. Set optimizer_weight_shard_size.
  436. Args:
  437. optimizer_weight_shard_size (int): Opt shard group size when not globally use parallel
  438. optimizer across devices.
  439. """
  440. self.check_context_handle()
  441. if not isinstance(optimizer_weight_shard_size, int):
  442. raise TypeError('optimizer_weight_shard_size is invalid type')
  443. if optimizer_weight_shard_size <= 1:
  444. logger.warning("The setting 'optimizer_weight_shard_size' is invalid. "
  445. "Please use the integer larger than 1.")
  446. return
  447. self._context_handle.set_optimizer_weight_shard_size(optimizer_weight_shard_size)
  448. def get_optimizer_weight_shard_size(self):
  449. """Get optimizer_weight_shard_size."""
  450. self.check_context_handle()
  451. return self._context_handle.get_optimizer_weight_shard_size()
  452. def set_optimizer_weight_shard_aggregated_save(self, optimizer_weight_shard_aggregated_save):
  453. """
  454. Set optimizer_weight_shard_aggregated_save.
  455. Args:
  456. optimizer_weight_shard_aggregated_save (bool): Whether to integrated save weight shard when
  457. enable parallel optimizer.
  458. """
  459. self.check_context_handle()
  460. if not isinstance(optimizer_weight_shard_aggregated_save, bool):
  461. raise TypeError('optimizer_weight_shard_aggregated_save is invalid type')
  462. self._context_handle.set_optimizer_weight_shard_aggregated_save(optimizer_weight_shard_aggregated_save)
  463. def get_optimizer_weight_shard_aggregated_save(self):
  464. """Get optimizer_weight_shard_size."""
  465. self.check_context_handle()
  466. return self._context_handle.get_optimizer_weight_shard_aggregated_save()
  467. def reset(self):
  468. """Reset all settings."""
  469. self.check_context_handle()
  470. self._context_handle.reset()
  471. def _check_and_default_group(self, group):
  472. """Validate the given group, if group is empty, returns a default fusion group"""
  473. if isinstance(group, (str)):
  474. group_len = len(group)
  475. if group_len > _MAX_GROUP_NAME_LEN:
  476. raise ValueError('Group name len is out of range {_MAX_GROUP_NAME_LEN}')
  477. else:
  478. raise TypeError('Group must be a python str')
  479. if group == "":
  480. if context.get_context("device_target") == "Ascend":
  481. group = _DEFAULT_HCCL_FUSION_GROUP_NAME
  482. else:
  483. group = _DEFAULT_NCCL_FUSION_GROUP_NAME
  484. return group
  485. _auto_parallel_context = None
  486. def auto_parallel_context():
  487. """
  488. Get the global _auto_parallel_context, if it is not created, create a new one.
  489. Returns:
  490. _AutoParallelContext, the global auto parallel context.
  491. """
  492. global _auto_parallel_context
  493. if _auto_parallel_context is None:
  494. _auto_parallel_context = _AutoParallelContext()
  495. return _auto_parallel_context
  496. _set_auto_parallel_context_func_map = {
  497. "device_num": auto_parallel_context().set_device_num,
  498. "global_rank": auto_parallel_context().set_global_rank,
  499. "gradients_mean": auto_parallel_context().set_gradients_mean,
  500. "gradient_fp32_sync": auto_parallel_context().set_gradient_fp32_sync,
  501. "loss_repeated_mean": auto_parallel_context().set_loss_repeated_mean,
  502. "pipeline_stages": auto_parallel_context().set_pipeline_stages,
  503. "parallel_mode": auto_parallel_context().set_parallel_mode,
  504. "auto_parallel_search_mode": auto_parallel_context().set_strategy_search_mode,
  505. "parameter_broadcast": auto_parallel_context().set_parameter_broadcast,
  506. "strategy_ckpt_load_file": auto_parallel_context().set_strategy_ckpt_load_file,
  507. "strategy_ckpt_save_file": auto_parallel_context().set_strategy_ckpt_save_file,
  508. "group_ckpt_save_file": auto_parallel_context().set_group_ckpt_save_file,
  509. "full_batch": auto_parallel_context().set_full_batch,
  510. "dataset_strategy": auto_parallel_context().set_dataset_strategy,
  511. "enable_parallel_optimizer": auto_parallel_context().set_enable_parallel_optimizer,
  512. "grad_accumulation_step": auto_parallel_context().set_grad_accumulation_step,
  513. "all_reduce_fusion_config": auto_parallel_context().set_all_reduce_fusion_split_indices,
  514. "communi_parallel_mode": auto_parallel_context().set_communi_parallel_mode,
  515. "optimizer_weight_shard_size": auto_parallel_context().set_optimizer_weight_shard_size,
  516. "optimizer_weight_shard_aggregated_save": auto_parallel_context().set_optimizer_weight_shard_aggregated_save,
  517. "sharding_propagation": auto_parallel_context().set_sharding_propagation,
  518. "enable_alltoall": auto_parallel_context().set_enable_alltoall}
  519. _get_auto_parallel_context_func_map = {
  520. "device_num": auto_parallel_context().get_device_num,
  521. "global_rank": auto_parallel_context().get_global_rank,
  522. "gradients_mean": auto_parallel_context().get_gradients_mean,
  523. "gradient_fp32_sync": auto_parallel_context().get_gradient_fp32_sync,
  524. "loss_repeated_mean": auto_parallel_context().get_loss_repeated_mean,
  525. "pipeline_stages": auto_parallel_context().get_pipeline_stages,
  526. "parallel_mode": auto_parallel_context().get_parallel_mode,
  527. "auto_parallel_search_mode": auto_parallel_context().get_strategy_search_mode,
  528. "parameter_broadcast": auto_parallel_context().get_parameter_broadcast,
  529. "strategy_ckpt_load_file": auto_parallel_context().get_strategy_ckpt_load_file,
  530. "strategy_ckpt_save_file": auto_parallel_context().get_strategy_ckpt_save_file,
  531. "full_batch": auto_parallel_context().get_full_batch,
  532. "dataset_strategy": auto_parallel_context().get_dataset_strategy,
  533. "enable_parallel_optimizer": auto_parallel_context().get_enable_parallel_optimizer,
  534. "grad_accumulation_step": auto_parallel_context().get_grad_accumulation_step,
  535. "all_reduce_fusion_config": auto_parallel_context().get_all_reduce_fusion_split_indices,
  536. "communi_parallel_mode": auto_parallel_context().get_communi_parallel_mode,
  537. "optimizer_weight_shard_size": auto_parallel_context().get_optimizer_weight_shard_size,
  538. "optimizer_weight_shard_aggregated_save": auto_parallel_context().get_optimizer_weight_shard_aggregated_save,
  539. "sharding_propagation": auto_parallel_context().get_sharding_propagation,
  540. "enable_alltoall": auto_parallel_context().get_enable_alltoall}
  541. @args_type_check(device_num=int, global_rank=int, gradients_mean=bool, gradient_fp32_sync=bool,
  542. loss_repeated_mean=bool, parallel_mode=str, auto_parallel_search_mode=str,
  543. parameter_broadcast=bool, strategy_ckpt_load_file=str,
  544. strategy_ckpt_save_file=str, full_batch=bool, dataset_strategy=tuple, enable_parallel_optimizer=bool,
  545. grad_accumulation_step=int, all_reduce_fusion_config=list, group_ckpt_save_file=str,
  546. communi_parallel_mode=str, optimizer_weight_shard_size=int,
  547. optimizer_weight_shard_aggregated_save=bool,
  548. sharding_propagation=bool, enable_alltoall=bool)
  549. def _set_auto_parallel_context(**kwargs):
  550. """
  551. Set auto parallel context.
  552. Note:
  553. Attribute name is required for setting attributes.
  554. Args:
  555. device_num (int): Available device number, the value must be in [1, 4096]. Default: 1.
  556. global_rank (int): Global rank id, the value must be in [0, 4095]. Default: 0.
  557. gradients_mean (bool): Whether to perform mean operator after all-reduce of mirror. Default: False.
  558. loss_repeated_mean (bool): Whether to perform mean operator in backward in the case of repeated
  559. calculations. Default: True.
  560. gradient_fp32_sync (bool): Gradients allreduce by fp32 even though gradients is fp16 if this flag is True.
  561. Default: True.
  562. parallel_mode (str): There are five kinds of parallel modes, "stand_alone", "data_parallel",
  563. "hybrid_parallel", "semi_auto_parallel" and "auto_parallel". Default: "stand_alone".
  564. - stand_alone: Only one processor working.
  565. - data_parallel: Distributing the data across different processors.
  566. - hybrid_parallel: Achieving data parallelism and model parallelism manually.
  567. - semi_auto_parallel: Achieving data parallelism and model parallelism by
  568. setting parallel strategies.
  569. - auto_parallel: Achieving parallelism automatically.
  570. auto_parallel_search_mode (str): There are two kinds of search modes, "recursive_programming"
  571. and "dynamic_programming". Default: "dynamic_programming".
  572. - recursive_programming: Recursive programming search mode.
  573. - dynamic_programming: Dynamic programming search mode.
  574. parameter_broadcast (bool): Indicating whether to broadcast parameters before training.
  575. "stand_alone", "semi_auto_parallel" and "auto_parallel" do not support parameter
  576. broadcast. Default: False.
  577. strategy_ckpt_load_file (str): The path to load parallel strategy checkpoint. Default: ''
  578. strategy_ckpt_save_file (str): The path to save parallel strategy checkpoint. Default: ''
  579. group_ckpt_save_file (str): The path to save parallel group checkpoint. Default: ''
  580. full_batch (bool): Whether to load the whole batch on each device. Default: False.
  581. dataset_strategy (tuplr): Dataset sharding strategy. Default: ().
  582. enable_parallel_optimizer (bool): Enable using optimizer segmentation or not. Default: False.
  583. all_reduce_fusion_config (list): Set allreduce fusion strategy by parameters indices.
  584. pipeline_stages (int): Set the stage information for pipeline parallel. This indicates how
  585. the devices are distributed alone the pipeline. The total devices will be divided into
  586. 'pipeline_stags' stages. This currently could only be used when
  587. parallel mode semi_auto_parallel is enabled. Default: 0
  588. communi_parallel_mode (str): There are tree kinds of communication parallel modes, "all_group_parallel",
  589. "same_server_group_parallel" and "no_group_parallel". Default: "all_group_parallel".
  590. - all_group_parallel: All communication groups are in parallel.
  591. - same_server_group_parallel: Only the communication groups within the same server are parallel.
  592. - no_group_parallel: All communication groups are not parallel.
  593. optimizer_weight_shard_size (int): Set optimizer shard group size when not fully use parallel optimizer.
  594. It should be larger than one and less than or equal with the data parallel size.
  595. Default: -1, which means fully use parallel optimizer in data parallel dimension.
  596. optimizer_weight_shard_aggregated_save (bool): Whether to integrated save weight shard when enable parallel
  597. optimizer. Default: False.
  598. sharding_propagation (bool): Set the value of sharding strategy propagation in AUTO_PARALLEL mode. If True,
  599. the strategy-configured operators will propagate the strategies to other
  600. operators with minimum redistribution cost; otherwise, the algorithm will
  601. search the desired strategies. Default: False.
  602. enable_alltoall (bool): Set the value of enabling AllToAll. If False, AllGather and Split are used to
  603. circumvent AllToAll. Default: False.
  604. Raises:
  605. ValueError: If input key is not attribute in auto parallel context.
  606. """
  607. for key, value in kwargs.items():
  608. if key not in _set_auto_parallel_context_func_map:
  609. raise ValueError("Set context keyword %s is not recognized!" % key)
  610. set_func = _set_auto_parallel_context_func_map[key]
  611. set_func(value)
  612. def _get_auto_parallel_context(attr_key):
  613. """
  614. Get auto parallel context attribute value according to the key.
  615. Args:
  616. attr_key (str): The key of the attribute.
  617. Returns:
  618. Return attribute value according to the key.
  619. Raises:
  620. ValueError: If input key is not attribute in auto parallel context.
  621. """
  622. if attr_key not in _get_auto_parallel_context_func_map:
  623. raise ValueError("Get context keyword %s is not recognized!" % attr_key)
  624. get_func = _get_auto_parallel_context_func_map[attr_key]
  625. return get_func()
  626. def _reset_auto_parallel_context():
  627. """
  628. Reset auto parallel context attributes to the default values:
  629. - device_num: 1.
  630. - global_rank: 0.
  631. - gradients_mean: False.
  632. - gradient_fp32_sync: True.
  633. - parallel_mode: "stand_alone".
  634. - parameter_broadcast: False.
  635. - strategy_ckpt_load_file: ""
  636. - strategy_ckpt_save_file: ""
  637. - enable_parallel_optimizer: False
  638. - auto_parallel_search_mode: dynamic_programming
  639. - pipeline_stages: 0
  640. """
  641. auto_parallel_context().reset()