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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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. from mindspore.parallel._dp_allreduce_fusion import _set_fusion_strategy_by_idx, _set_fusion_strategy_by_size
  19. from mindspore._c_expression import AutoParallelContext
  20. from mindspore._checkparam import args_type_check
  21. _MAX_GROUP_NAME_LEN = 127
  22. class _AutoParallelContext:
  23. """
  24. _AutoParallelContext is the environment in which operations are executed
  25. Note:
  26. Create a context through instantiating Context object is not recommended.
  27. Should use auto_parallel_context() to get the context since Context is singleton.
  28. """
  29. _instance = None
  30. _instance_lock = threading.Lock()
  31. def __init__(self):
  32. self._context_handle = AutoParallelContext.get_instance()
  33. def __new__(cls):
  34. if cls._instance is None:
  35. cls._instance_lock.acquire()
  36. cls._instance = object.__new__(cls)
  37. cls._instance_lock.release()
  38. return cls._instance
  39. def check_context_handle(self):
  40. """
  41. Check context handle.
  42. Raises:
  43. ValueError: If the context handle is none.
  44. """
  45. if self._context_handle is None:
  46. raise ValueError("Context handle is none in context!!!")
  47. def set_device_num(self, device_num):
  48. """
  49. Set device num for auto parallel.
  50. Args:
  51. device_num (int): The device number.
  52. Raises:
  53. ValueError: If the device num is not in [1, 4096].
  54. """
  55. self.check_context_handle()
  56. if device_num < 1 or device_num > 4096:
  57. raise ValueError("Device num must be in [1, 4096], but got {}".format(device_num))
  58. self._context_handle.set_device_num(device_num)
  59. def get_device_num(self):
  60. """Get device num."""
  61. self.check_context_handle()
  62. return self._context_handle.get_device_num()
  63. def set_global_rank(self, global_rank):
  64. """
  65. Set global rank for auto parallel.
  66. Args:
  67. global_rank (int): The rank id of current rank.
  68. Raises:
  69. ValueError: If the global rank is not in [1, 4096].
  70. """
  71. self.check_context_handle()
  72. if global_rank < 0 or global_rank > 4095:
  73. raise ValueError("Global rank must be in [0, 4095], but got {}".format(global_rank))
  74. self._context_handle.set_global_rank(global_rank)
  75. def get_global_rank(self):
  76. """Get current rank id."""
  77. self.check_context_handle()
  78. return self._context_handle.get_global_rank()
  79. def set_mirror_mean(self, mirror_mean):
  80. """
  81. Set mirror_mean flag.
  82. Note:
  83. If mirror_mean is true, it will insert a div operator after parameter gradients allreduce.
  84. Args:
  85. mirror_mean (bool): The mirror_mean flag.
  86. """
  87. self.check_context_handle()
  88. self._context_handle.set_mirror_mean(mirror_mean)
  89. def get_mirror_mean(self):
  90. """Get mirror_mean flag."""
  91. self.check_context_handle()
  92. return self._context_handle.get_mirror_mean()
  93. def set_cast_before_mirror(self, cast_before_mirror):
  94. """
  95. Set cast_before_mirror.
  96. Note:
  97. If cast_before_mirror is true,
  98. it will convert tensor type from fp16 to fp32 before parameter gradients allreduce.
  99. Args:
  100. cast_before_mirror (bool): The cast_before_mirror flag.
  101. """
  102. self.check_context_handle()
  103. self._context_handle.set_cast_before_mirror(cast_before_mirror)
  104. def get_cast_before_mirror(self):
  105. """Get cast_before_mirror flag."""
  106. self.check_context_handle()
  107. return self._context_handle.get_cast_before_mirror()
  108. def set_loss_repeated_mean(self, loss_repeated_mean):
  109. """
  110. Set loss_repeated_mean flag.
  111. Note:
  112. If loss_repeated_mean is true,
  113. Distributed automatic differentiation will perform a mean operator
  114. in backward in the case of repeated calculations.
  115. Args:
  116. loss_repeated_mean (bool): The loss_repeated_mean flag.
  117. """
  118. self.check_context_handle()
  119. self._context_handle.set_loss_repeated_mean(loss_repeated_mean)
  120. def get_loss_repeated_mean(self):
  121. """Get loss_repeated_mean flag."""
  122. self.check_context_handle()
  123. return self._context_handle.get_loss_repeated_mean()
  124. def set_communication_backend(self, communication_backend):
  125. """
  126. Set communication backend.
  127. Args:
  128. communication_backend (str): The communication backend.
  129. """
  130. self.check_context_handle()
  131. self._context_handle.set_communication_backend(communication_backend)
  132. def get_communication_backend(self):
  133. """Get communication backend."""
  134. self.check_context_handle()
  135. return self._context_handle.get_communication_backend()
  136. def set_parallel_mode(self, parallel_mode):
  137. """
  138. Set parallel mode for auto parallel.
  139. Args:
  140. parallel_mode (str): The parallel mode of auto parallel.
  141. Raises:
  142. ValueError: If parallel mode is not supported.
  143. """
  144. self.check_context_handle()
  145. ret = self._context_handle.set_parallel_mode(parallel_mode)
  146. if ret is False:
  147. raise ValueError("Parallel mode does not support {}".format(parallel_mode))
  148. def get_parallel_mode(self):
  149. """Get parallel mode."""
  150. self.check_context_handle()
  151. return self._context_handle.get_parallel_mode()
  152. def set_strategy_search_mode(self, strategy_search_mode):
  153. self.check_context_handle()
  154. ret = self._context_handle.set_strategy_search_mode(strategy_search_mode)
  155. if ret is False:
  156. raise ValueError("Strategy search mode does not support {}".format(strategy_search_mode))
  157. def get_strategy_search_mode(self):
  158. self.check_context_handle()
  159. return self._context_handle.get_strategy_search_mode()
  160. def set_parameter_broadcast(self, parameter_broadcast):
  161. """
  162. Set parameter broadcast.
  163. Args:
  164. parameter_broadcast (bool): Parameter broadcast or not.
  165. """
  166. self.check_context_handle()
  167. self._context_handle.set_parameter_broadcast(parameter_broadcast)
  168. def get_parameter_broadcast(self):
  169. """Get parameter broadcast flag."""
  170. self.check_context_handle()
  171. return self._context_handle.get_parameter_broadcast()
  172. def set_strategy_ckpt_load_file(self, strategy_ckpt_load_file):
  173. """
  174. Set strategy checkpoint load path.
  175. Args:
  176. strategy_ckpt_load_file (bool): Path to load parallel strategy checkpoint.
  177. """
  178. self.check_context_handle()
  179. self._context_handle.set_strategy_ckpt_load_file(strategy_ckpt_load_file)
  180. def get_strategy_ckpt_load_file(self):
  181. """Get strategy checkpoint load path."""
  182. self.check_context_handle()
  183. return self._context_handle.get_strategy_ckpt_load_file()
  184. def set_strategy_ckpt_save_file(self, strategy_ckpt_save_file):
  185. """
  186. Set strategy checkpoint save path.
  187. Args:
  188. strategy_ckpt_save_file (bool): Path to save parallel strategy checkpoint.
  189. """
  190. self.check_context_handle()
  191. self._context_handle.set_strategy_ckpt_save_file(strategy_ckpt_save_file)
  192. def get_strategy_ckpt_save_file(self):
  193. """Get strategy checkpoint save path."""
  194. self.check_context_handle()
  195. return self._context_handle.get_strategy_ckpt_save_file()
  196. def get_parameter_broadcast_is_set(self):
  197. """Get parameter broadcast is set or not."""
  198. self.check_context_handle()
  199. return self._context_handle.get_parameter_broadcast_is_set()
  200. def set_all_reduce_fusion_split_indices(self, indices, group="hccl_world_groupsum1"):
  201. """
  202. Set allreduce fusion strategy by parameters indices.
  203. Args:
  204. indices (list): Indices list.
  205. group (str): The hccl communication group.
  206. Raises:
  207. TypeError: If type of indices item is not int.
  208. TypeError: If group is not a python str.
  209. """
  210. self.check_context_handle()
  211. if isinstance(indices, (list)):
  212. for index in indices:
  213. if not isinstance(index, int):
  214. raise TypeError('indices has invalid value')
  215. else:
  216. raise TypeError('indices must be a python list')
  217. if isinstance(group, (str)):
  218. group_len = len(group)
  219. if group_len > _MAX_GROUP_NAME_LEN:
  220. raise ValueError('Group name len is out of range {_MAX_GROUP_NAME_LEN}')
  221. else:
  222. raise TypeError('Group must be a python str')
  223. self._context_handle.set_all_reduce_fusion_split_indices(indices, group)
  224. if context.get_context("device_target") == "Ascend":
  225. if group == "":
  226. _set_fusion_strategy_by_idx(indices)
  227. else:
  228. _set_fusion_strategy_by_idx(indices, group)
  229. def get_all_reduce_fusion_split_indices(self, group="hccl_world_groupsum1"):
  230. """
  231. Get allreduce fusion split indices.
  232. Args:
  233. group (str): The hccl communication group.
  234. Returns:
  235. Return split sizes list according to the group.
  236. Raises:
  237. TypeError: If group is not a python str.
  238. """
  239. self.check_context_handle()
  240. if isinstance(group, (str)):
  241. group_len = len(group)
  242. if group_len > _MAX_GROUP_NAME_LEN:
  243. raise ValueError('Group name len is out of range {_MAX_GROUP_NAME_LEN}')
  244. else:
  245. raise TypeError('Group must be a python str')
  246. return self._context_handle.get_all_reduce_fusion_split_indices(group)
  247. def set_all_reduce_fusion_split_sizes(self, sizes, group="hccl_world_groupsum1"):
  248. """
  249. Set allreduce fusion strategy by parameters data sizes.
  250. Args:
  251. sizes (list): Sizes list.
  252. group (str): The hccl communication group.
  253. Raises:
  254. TypeError: If type of sizes item is not int.
  255. TypeError: If group is not a python str.
  256. """
  257. self.check_context_handle()
  258. if isinstance(sizes, (list)):
  259. for size in sizes:
  260. if not isinstance(size, int):
  261. raise TypeError('sizes has invalid value')
  262. else:
  263. raise TypeError('sizes must be a python list')
  264. if isinstance(group, (str)):
  265. group_len = len(group)
  266. if group_len > _MAX_GROUP_NAME_LEN:
  267. raise ValueError('Group name len is out of range {_MAX_GROUP_NAME_LEN}')
  268. else:
  269. raise TypeError('Group must be a python str')
  270. self._context_handle.set_all_reduce_fusion_split_sizes(sizes, group)
  271. if context.get_context("device_target") == "Ascend":
  272. if group == "":
  273. _set_fusion_strategy_by_size(sizes)
  274. else:
  275. _set_fusion_strategy_by_size(sizes, group)
  276. def get_all_reduce_fusion_split_sizes(self, group="hccl_world_groupsum1"):
  277. """
  278. Get allreduce fusion split sizes.
  279. Args:
  280. group (str): The hccl communication group.
  281. Returns:
  282. Return split sizes list according to the group.
  283. Raises:
  284. TypeError: If group is not a python str.
  285. """
  286. self.check_context_handle()
  287. if isinstance(group, (str)):
  288. group_len = len(group)
  289. if group_len > _MAX_GROUP_NAME_LEN:
  290. raise ValueError('Group name len is out of range {_MAX_GROUP_NAME_LEN}')
  291. else:
  292. raise TypeError('Group must be a python str')
  293. return self._context_handle.get_all_reduce_fusion_split_sizes(group)
  294. def set_enable_all_reduce_fusion(self, enable_all_reduce_fusion):
  295. """
  296. Set enable/disable all reduce fusion.
  297. Args:
  298. enable_all_reduce_fusion (bool): Enable/disable all reduce fusion.
  299. """
  300. self.check_context_handle()
  301. if not isinstance(enable_all_reduce_fusion, bool):
  302. raise TypeError('enable_all_reduce_fusion is invalid type')
  303. self._context_handle.set_enable_all_reduce_fusion(enable_all_reduce_fusion)
  304. def get_enable_all_reduce_fusion(self):
  305. """Get all reduce fusion flag."""
  306. self.check_context_handle()
  307. return self._context_handle.get_enable_all_reduce_fusion()
  308. def get_device_num_is_set(self):
  309. """Get device number is set or not."""
  310. self.check_context_handle()
  311. return self._context_handle.get_device_num_is_set()
  312. def get_global_rank_is_set(self):
  313. """Get global rank is set or not."""
  314. self.check_context_handle()
  315. return self._context_handle.get_global_rank_is_set()
  316. def reset(self):
  317. """Reset all settings."""
  318. self.check_context_handle()
  319. self._context_handle.reset()
  320. _auto_parallel_context = None
  321. def auto_parallel_context():
  322. """
  323. Get the global _auto_parallel_context, if it is not created, create a new one.
  324. Returns:
  325. _AutoParallelContext, the global auto parallel context.
  326. """
  327. global _auto_parallel_context
  328. if _auto_parallel_context is None:
  329. _auto_parallel_context = _AutoParallelContext()
  330. return _auto_parallel_context
  331. _set_auto_parallel_context_func_map = {
  332. "device_num": auto_parallel_context().set_device_num,
  333. "global_rank": auto_parallel_context().set_global_rank,
  334. "mirror_mean": auto_parallel_context().set_mirror_mean,
  335. "cast_before_mirror": auto_parallel_context().set_cast_before_mirror,
  336. "loss_repeated_mean": auto_parallel_context().set_loss_repeated_mean,
  337. "parallel_mode": auto_parallel_context().set_parallel_mode,
  338. "parameter_broadcast": auto_parallel_context().set_parameter_broadcast,
  339. "strategy_ckpt_load_file": auto_parallel_context().set_strategy_ckpt_load_file,
  340. "strategy_ckpt_save_file": auto_parallel_context().set_strategy_ckpt_save_file}
  341. _get_auto_parallel_context_func_map = {
  342. "device_num": auto_parallel_context().get_device_num,
  343. "global_rank": auto_parallel_context().get_global_rank,
  344. "mirror_mean": auto_parallel_context().get_mirror_mean,
  345. "cast_before_mirror": auto_parallel_context().get_cast_before_mirror,
  346. "loss_repeated_mean": auto_parallel_context().get_loss_repeated_mean,
  347. "parallel_mode": auto_parallel_context().get_parallel_mode,
  348. "parameter_broadcast": auto_parallel_context().get_parameter_broadcast,
  349. "strategy_ckpt_load_file": auto_parallel_context().get_strategy_ckpt_load_file,
  350. "strategy_ckpt_save_file": auto_parallel_context().get_strategy_ckpt_save_file}
  351. @args_type_check(device_num=int, global_rank=int, mirror_mean=bool, cast_before_mirror=bool,
  352. loss_repeated_mean=bool, parallel_mode=str, parameter_broadcast=bool,
  353. strategy_ckpt_load_file=str, strategy_ckpt_save_file=str)
  354. def _set_auto_parallel_context(**kwargs):
  355. """
  356. Set auto parallel context.
  357. Note:
  358. Attribute name is required for setting attributes.
  359. Args:
  360. device_num (int): Available device number, the value must be in [1, 4096]. Default: 1.
  361. global_rank (int): Global rank id, the value must be in [0, 4095]. Default: 0.
  362. mirror_mean (bool): Whether to perform mean operator after all-reduce of mirror. Default: False.
  363. loss_repeated_mean (bool): Whether to perform mean operator in backward in the case of repeated
  364. calculations. Default: True.
  365. cast_before_mirror (bool): Insert Mirror Op after the cast if this flag is True. Default: True.
  366. parallel_mode (str): There are five kinds of parallel modes, "stand_alone", "data_parallel",
  367. "hybrid_parallel", "semi_auto_parallel" and "auto_parallel". Default: "stand_alone".
  368. - stand_alone: Only one processor working.
  369. - data_parallel: Distributing the data across different processors.
  370. - hybrid_parallel: Achieving data parallelism and model parallelism manually.
  371. - semi_auto_parallel: Achieving data parallelism and model parallelism by
  372. setting parallel strategies.
  373. - auto_parallel: Achieving parallelism automatically.
  374. parameter_broadcast (bool): Indicating whether to broadcast parameters before training.
  375. "stand_alone", "semi_auto_parallel" and "auto_parallel" do not support parameter
  376. broadcast. Default: False.
  377. strategy_ckpt_load_file (str): The path to load parallel strategy checkpoint. Default: ''
  378. strategy_ckpt_save_file (str): The path to save parallel strategy checkpoint. Default: ''
  379. Raises:
  380. ValueError: If input key is not attribute in auto parallel context.
  381. """
  382. for key, value in kwargs.items():
  383. if key not in _set_auto_parallel_context_func_map:
  384. raise ValueError("Set context keyword %s is not recognized!" % key)
  385. set_func = _set_auto_parallel_context_func_map[key]
  386. set_func(value)
  387. def _get_auto_parallel_context(attr_key):
  388. """
  389. Get auto parallel context attribute value according to the key.
  390. Args:
  391. attr_key (str): The key of the attribute.
  392. Returns:
  393. Return attribute value according to the key.
  394. Raises:
  395. ValueError: If input key is not attribute in auto parallel context.
  396. """
  397. if attr_key not in _get_auto_parallel_context_func_map:
  398. raise ValueError("Get context keyword %s is not recognized!" % attr_key)
  399. get_func = _get_auto_parallel_context_func_map[attr_key]
  400. return get_func()
  401. def _reset_auto_parallel_context():
  402. """
  403. Reset auto parallel context attributes to the default values:
  404. - device_num: 1.
  405. - global_rank: 0.
  406. - mirror_mean: False.
  407. - cast_before_mirror: True.
  408. - parallel_mode: "stand_alone".
  409. - parameter_broadcast: False.
  410. - strategy_ckpt_load_file: ""
  411. - strategy_ckpt_save_file: ""
  412. """
  413. auto_parallel_context().reset()