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.

group.py 6.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. from typing import List, Optional, Tuple
  10. from ..device import set_default_device, what_is_xpu
  11. from .server import Client, Server
  12. class StaticData:
  13. server = None
  14. client = None
  15. master_ip = None
  16. py_server_port = None
  17. mm_server_port = None
  18. world_size = None
  19. proc_rank = None
  20. device = None
  21. backend = None
  22. next_stream = None
  23. device_type = None
  24. _sd = None
  25. class Group:
  26. r"""
  27. Include ranked nodes running collective communication (See :mod:`~.functional.distributed`).
  28. By default collectives operate on the default group (also called ``WORLD``)
  29. and require all processes to enter the distributed function call.
  30. :param proc_ranks: rank list of the group, the first one is root rank.
  31. """
  32. def __init__(self, proc_ranks):
  33. if len(proc_ranks) == 0: # empty group
  34. self.proc_ranks = None
  35. self.stream = None
  36. else:
  37. self.reset(proc_ranks)
  38. def reset(self, proc_ranks):
  39. self.check(proc_ranks)
  40. self.proc_ranks = proc_ranks
  41. self.stream = _sd.next_stream
  42. _sd.next_stream += 1
  43. def check(self, proc_ranks):
  44. assert _sd is not None, "please call init_process_group first"
  45. for rank in proc_ranks:
  46. assert isinstance(rank, int)
  47. assert rank >= 0 and rank < _sd.world_size
  48. assert _sd.proc_rank in proc_ranks
  49. @property
  50. def size(self):
  51. assert len(self.proc_ranks) > 0, "invalid group"
  52. return len(self.proc_ranks)
  53. @property
  54. def key(self):
  55. assert len(self.proc_ranks) > 0, "invalid group"
  56. return ",".join(map(str, self.proc_ranks))
  57. @property
  58. def rank(self):
  59. assert len(self.proc_ranks) > 0, "invalid group"
  60. return self.proc_ranks.index(_sd.proc_rank)
  61. @property
  62. def comp_node(self):
  63. assert len(self.proc_ranks) > 0, "invalid group"
  64. return "{}{}:{}".format(_sd.device_type, _sd.device, self.stream)
  65. WORLD = Group([])
  66. _device2backend = {
  67. "gpu": "nccl",
  68. "cuda": "nccl",
  69. "rocm": "rccl",
  70. }
  71. _backends = {"nccl", "rccl", "ucx"}
  72. def init_process_group(
  73. master_ip: str,
  74. port: int,
  75. world_size: int,
  76. rank: int,
  77. device: int,
  78. backend: Optional[str] = None,
  79. device_type: str = "xpu",
  80. ) -> None:
  81. """
  82. Initialize the distributed process group and specify the device used in the current process
  83. :param master_ip: ip address of the master node.
  84. :param port: port available for all processes to communicate.
  85. :param world_size: total number of processes participating in the job.
  86. :param rank: rank of the current process.
  87. :param device: the GPU device id to bind this process to.
  88. :param backend: communicator backend, currently support 'nccl' and 'ucx'.
  89. """
  90. physical_device_type = what_is_xpu() if device_type == "xpu" else device_type
  91. backend = _device2backend[physical_device_type] if backend is None else backend
  92. if not isinstance(master_ip, str):
  93. raise TypeError("Expect type str but got {}".format(type(master_ip)))
  94. if not isinstance(port, int):
  95. raise TypeError("Expect type int but got {}".format(type(port)))
  96. if not isinstance(world_size, int):
  97. raise TypeError("Expect type int but got {}".format(type(world_size)))
  98. if not isinstance(rank, int):
  99. raise TypeError("Expect type int but got {}".format(type(rank)))
  100. if not isinstance(device, int):
  101. raise TypeError("Expect type int but got {}".format(type(backend)))
  102. if backend not in _backends:
  103. raise ValueError(
  104. "backend should be one of {} but got {}".format(_backends, backend)
  105. )
  106. if physical_device_type not in _device2backend:
  107. raise ValueError(
  108. "{} is not a valid distributed device type".format(device_type)
  109. )
  110. global _sd
  111. assert _sd is None, "init_process_group should be called only once"
  112. _sd = StaticData()
  113. assert world_size > 1
  114. assert rank >= 0 and rank < world_size
  115. assert port > 0
  116. _sd.client = Client(master_ip, port)
  117. _sd.master_ip = master_ip
  118. _sd.py_server_port = port
  119. _sd.mm_server_port = _sd.client.get_mm_server_port()
  120. _sd.world_size = world_size
  121. _sd.proc_rank = rank
  122. _sd.device = device
  123. _sd.backend = backend
  124. _sd.next_stream = 1
  125. _sd.device_type = device_type
  126. WORLD.reset(list(range(world_size)))
  127. set_default_device("{}{}".format(device_type, device))
  128. def is_distributed() -> bool:
  129. """Return True if the distributed process group has been initialized."""
  130. return _sd is not None
  131. def get_rank() -> int:
  132. """Get the rank of the current process."""
  133. return _sd.proc_rank if _sd is not None else 0
  134. def get_world_size() -> int:
  135. """Get the total number of processes participating in the job."""
  136. return _sd.world_size if _sd is not None else 1
  137. def get_backend() -> str:
  138. """Get the backend str."""
  139. assert _sd is not None, "please call init_process_group first"
  140. return _sd.backend if _sd is not None else None
  141. def get_py_server_addr() -> Tuple[str, int]:
  142. """Get master_ip and port of python XML RPC server."""
  143. assert _sd is not None, "please call init_process_group first"
  144. return _sd.master_ip, _sd.py_server_port
  145. def get_mm_server_addr() -> Tuple[str, int]:
  146. """Get master_ip and port of C++ mm_server."""
  147. assert _sd is not None, "please call init_process_group first"
  148. return _sd.master_ip, _sd.mm_server_port
  149. def get_client() -> Client:
  150. """Get client of python XML RPC server."""
  151. assert _sd is not None, "please call init_process_group first"
  152. return _sd.client
  153. def new_group(proc_ranks: List[int]) -> Group:
  154. """Build a subgroup containing certain ranks."""
  155. return Group(proc_ranks)
  156. def group_barrier(group: Group = WORLD) -> None:
  157. """Block until all ranks in the group reach this barrier."""
  158. # if running with single node, skip it
  159. if _sd is None:
  160. return
  161. assert isinstance(group, Group)
  162. _sd.client.group_barrier(group.key, group.size)

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台