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.

_comm_helper.py 11 kB

5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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. """comm_helper"""
  16. from mindspore.parallel._ps_context import _is_role_pserver, _is_role_sched
  17. from ._hccl_management import load_lib as hccl_load_lib
  18. _HCCL_AVAILABLE = False
  19. _NCCL_AVAILABLE = False
  20. try:
  21. import mindspore._ms_mpi as mpi
  22. _NCCL_AVAILABLE = True
  23. except ImportError:
  24. _NCCL_AVAILABLE = False
  25. try:
  26. hccl_load_lib()
  27. _HCCL_AVAILABLE = True
  28. except RuntimeError:
  29. _HCCL_AVAILABLE = False
  30. if _HCCL_AVAILABLE:
  31. from . import _hccl_management as hccl
  32. else:
  33. try:
  34. import hccl_test.manage.api as hccl
  35. _HCCL_AVAILABLE = True
  36. except ImportError:
  37. _HCCL_AVAILABLE = False
  38. HCCL_WORLD_COMM_GROUP = "hccl_world_group"
  39. NCCL_WORLD_COMM_GROUP = "nccl_world_group"
  40. class Backend:
  41. """
  42. Class for available backends.
  43. Note:
  44. The backends' value should be string, e.g., "hccl".
  45. If backend is set to Backend.UNDEFINED, it will be seen as invaliad.
  46. Args:
  47. name (str): The name of backend.
  48. Raises:
  49. TypeError: If name is not a string.
  50. ValueError: If backend is invalid.
  51. Examples:
  52. >>> Backend("abc")
  53. >>> hccl = Backend("hccl")
  54. """
  55. UNDEFINED = "undefined"
  56. HCCL = "hccl"
  57. NCCL = "nccl"
  58. def __new__(cls, name):
  59. """Create instance object of Backend."""
  60. if not isinstance(name, str):
  61. raise TypeError("Backend name must be a string, but got {}".format(type(name)))
  62. value = getattr(Backend, name.upper(), Backend.UNDEFINED)
  63. if value == Backend.UNDEFINED:
  64. raise ValueError("Invalid backend: '{}'".format(name))
  65. return value
  66. def is_hccl_available():
  67. """
  68. Check hccl api is available.
  69. Returns:
  70. Boolean. Return whether hccl is available or not.
  71. """
  72. return _HCCL_AVAILABLE
  73. def is_nccl_available():
  74. """
  75. Check nccl api is available.
  76. Returns:
  77. Boolean. Return whether nccl is available or not.
  78. """
  79. return _NCCL_AVAILABLE
  80. def check_parameter_available(func):
  81. """
  82. Check parameter is available. If not available, raise Error.
  83. Args:
  84. func (Function): The function to be run.
  85. Raises:
  86. RuntimeError.
  87. Returns:
  88. Wrapper. If not available, raise Error.
  89. """
  90. def wrapper(*args, **kargs):
  91. if _is_role_pserver() or _is_role_sched():
  92. return func(*args, **kargs)
  93. group = None
  94. if "group" in kargs.keys():
  95. group = kargs.get("group")
  96. if group is not None and not isinstance(group, str):
  97. raise TypeError("Group should be str or None, "
  98. "but got group {}".format(type(group)))
  99. if "backend" in kargs.keys():
  100. backend = kargs.get("backend")
  101. if backend is Backend.HCCL and not is_hccl_available():
  102. raise RuntimeError("Distributed Communication doesn't have HCCL built in")
  103. if backend is Backend.NCCL and not is_nccl_available():
  104. raise RuntimeError("Distributed Communication doesn't have NCCL built in")
  105. if group is None:
  106. if backend is Backend.HCCL:
  107. group = HCCL_WORLD_COMM_GROUP
  108. elif backend is Backend.NCCL:
  109. group = NCCL_WORLD_COMM_GROUP
  110. return func(*args, **kargs)
  111. return wrapper
  112. @check_parameter_available
  113. def _get_rank_helper(group, backend):
  114. """
  115. The Helper to do get_rank_id.
  116. Args:
  117. group (str): The communication group.
  118. backend (str): The backend, like "hccl".
  119. Raises:
  120. ValueError: If backend is invalid.
  121. Returns:
  122. Integer. The local rank id of the calling process.
  123. """
  124. rank_id = None
  125. if _is_role_pserver() or _is_role_sched():
  126. rank_id = 0
  127. return rank_id
  128. if backend == Backend.HCCL:
  129. if group == HCCL_WORLD_COMM_GROUP:
  130. rank_id = hccl.get_rank_id()
  131. else:
  132. rank_id = hccl.get_rank_id(group)
  133. elif backend == Backend.NCCL:
  134. rank_id = mpi.get_rank_id(group)
  135. else:
  136. raise ValueError("Invalid backend: '{}'".format(backend))
  137. return rank_id
  138. @check_parameter_available
  139. def _get_local_rank_helper(group, backend):
  140. """
  141. The Helper to do get_local_rank_id.
  142. Args:
  143. group (str): The communication group.
  144. backend (str): The backend, like "hccl".
  145. Raises:
  146. ValueError: If backend is invalid.
  147. Returns:
  148. Integer. The local rank id of the calling process.
  149. """
  150. rank_id = None
  151. if backend == Backend.HCCL:
  152. if group == HCCL_WORLD_COMM_GROUP:
  153. rank_id = hccl.get_local_rank_id()
  154. else:
  155. rank_id = hccl.get_local_rank_id(group)
  156. elif backend == Backend.NCCL:
  157. raise RuntimeError("Nccl doesn't support get_local_rank_id now.")
  158. else:
  159. raise ValueError("Invalid backend: '{}'".format(backend))
  160. return rank_id
  161. @check_parameter_available
  162. def _get_size_helper(group, backend):
  163. """
  164. The Helper to do get_rank_size.
  165. Args:
  166. group (str): The communication group.
  167. backend (str): The backend, like "hccl".
  168. Raises:
  169. ValueError: If backend is invalid.
  170. Returns:
  171. Integer. The rank size of specified group.
  172. """
  173. size = None
  174. if _is_role_pserver() or _is_role_sched():
  175. size = 1
  176. return size
  177. if backend == Backend.HCCL:
  178. if group == HCCL_WORLD_COMM_GROUP:
  179. size = hccl.get_rank_size()
  180. else:
  181. size = hccl.get_rank_size(group)
  182. elif backend == Backend.NCCL:
  183. size = mpi.get_rank_size(group)
  184. else:
  185. raise ValueError("Invalid backend: '{}'".format(backend))
  186. return size
  187. @check_parameter_available
  188. def _get_local_size_helper(group, backend):
  189. """
  190. The Helper to do get_local_rank_size.
  191. Args:
  192. group (str): The communication group.
  193. backend (str): The backend, like "hccl".
  194. Raises:
  195. ValueError: If backend is invalid.
  196. Returns:
  197. Integer. The local rank size where the calling process is being within specified group.
  198. """
  199. size = None
  200. if backend == Backend.HCCL:
  201. if group == HCCL_WORLD_COMM_GROUP:
  202. size = hccl.get_local_rank_size()
  203. else:
  204. size = hccl.get_local_rank_size(group)
  205. elif backend == Backend.NCCL:
  206. raise RuntimeError("Nccl doesn't support get_local_rank_size now.")
  207. else:
  208. raise ValueError("Invalid backend: '{}'".format(backend))
  209. return size
  210. @check_parameter_available
  211. def _get_world_rank_from_group_rank_helper(group, group_rank_id, backend):
  212. """
  213. The Helper to do get_world_rank_from_group_rank.
  214. Args:
  215. group (str): The user communication group.
  216. group_rank_id (int): A rank id in user communication group.
  217. backend (str): The backend, like "hccl".
  218. Raises:
  219. TypeError: If group_rank_id is not int.
  220. ValueError: If group is "hccl_world_group" or backend is invalid.
  221. Returns:
  222. Integer. A rank id in world communication group.
  223. """
  224. world_rank_id = None
  225. if not isinstance(group_rank_id, int):
  226. raise TypeError("group_rank_id should be int, but got type {}".format(type(group_rank_id)))
  227. if backend == Backend.HCCL:
  228. if group == HCCL_WORLD_COMM_GROUP:
  229. raise ValueError("Group cannot be 'hccl_world_group'. ")
  230. world_rank_id = hccl.get_world_rank_from_group_rank(group, group_rank_id)
  231. elif backend == Backend.NCCL:
  232. raise RuntimeError("Nccl doesn't support get_world_rank_from_group_rank now.")
  233. else:
  234. raise ValueError("Invalid backend: '{}'".format(backend))
  235. return world_rank_id
  236. @check_parameter_available
  237. def _get_group_rank_from_world_rank_helper(world_rank_id, group, backend):
  238. """
  239. The Helper to do get_group_rank_from_world_rank.
  240. Args:
  241. world_rank_id (int): A rank id in world communication group.
  242. group (str): The user communication group.
  243. backend (str): The backend, like "hccl".
  244. Raises:
  245. TypeError: If world_rank_id is not int.
  246. ValueError: If group is 'hccl_world_group' or backend is invalid.
  247. Returns:
  248. Integer. A rank id in user communication group.
  249. """
  250. group_rank_id = None
  251. if not isinstance(world_rank_id, int):
  252. raise TypeError("world_rank_id should be int, but got type {}".format(type(world_rank_id)))
  253. if backend == Backend.HCCL:
  254. if group == HCCL_WORLD_COMM_GROUP:
  255. raise ValueError("Group cannot be 'hccl_world_group'. ")
  256. group_rank_id = hccl.get_group_rank_from_world_rank(world_rank_id, group)
  257. elif backend == Backend.NCCL:
  258. raise RuntimeError("Nccl doesn't support get_group_rank_from_world_rank now.")
  259. else:
  260. raise ValueError("Invalid backend: '{}'".format(backend))
  261. return group_rank_id
  262. @check_parameter_available
  263. def _create_group_helper(group, rank_ids, backend):
  264. """
  265. The Helper to do create_group.
  266. Args:
  267. group (str): The communication group.
  268. rank_ids (list): Rank ids in the group.
  269. backend (str): The backend, like "hccl".
  270. Raises:
  271. TypeError: If rank_ids is not a list.
  272. ValueError: If rank_ids size is not larger than 1 or rank_ids has duplicate data or backend is invalid.
  273. """
  274. if backend == Backend.HCCL:
  275. if not isinstance(rank_ids, list):
  276. raise TypeError("Rank_ids {} should be list".format(rank_ids))
  277. rank_size = len(rank_ids)
  278. if rank_size < 1:
  279. raise ValueError("Rank_ids size {} should be large than 0".format(rank_size))
  280. if len(rank_ids) - len(list(set(rank_ids))) > 0:
  281. raise ValueError("List rank_ids in Group {} has duplicate data!".format(group))
  282. hccl.create_group(group, rank_size, rank_ids)
  283. elif backend == Backend.NCCL:
  284. raise RuntimeError("Nccl doesn't support create_group now.")
  285. else:
  286. raise ValueError("Invalid backend: '{}'".format(backend))
  287. @check_parameter_available
  288. def _destroy_group_helper(group, backend):
  289. """
  290. The Helper to do destroy_group.
  291. Args:
  292. group (str): The user communication group.
  293. backend (str): The backend, like "hccl".
  294. Raises:
  295. ValueError: If group is "hccl_world_group" or backend is invalid.
  296. """
  297. if backend == Backend.HCCL:
  298. if group == HCCL_WORLD_COMM_GROUP:
  299. raise ValueError("The hccl_world_group does not support destruction.")
  300. hccl.destroy_group(group)
  301. elif backend == Backend.NCCL:
  302. raise RuntimeError("Nccl doesn't support destroy_group now.")
  303. else:
  304. raise ValueError("Invalid backend: '{}'".format(backend))