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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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
  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. _sd = None
  24. class Group:
  25. r"""
  26. Include ranked nodes running collective communication (See :mod:`~.functional.distributed`).
  27. By default collectives operate on the default group (also called ``WORLD``)
  28. and require all processes to enter the distributed function call.
  29. :param proc_ranks: rank list of the group, the first one is root rank.
  30. """
  31. def __init__(self, proc_ranks):
  32. if len(proc_ranks) == 0: # empty group
  33. self.proc_ranks = None
  34. self.stream = None
  35. else:
  36. self.reset(proc_ranks)
  37. def reset(self, proc_ranks):
  38. self.check(proc_ranks)
  39. self.proc_ranks = proc_ranks
  40. self.stream = _sd.next_stream
  41. _sd.next_stream += 1
  42. def check(self, proc_ranks):
  43. assert _sd is not None, "please call init_process_group first"
  44. for rank in proc_ranks:
  45. assert isinstance(rank, int)
  46. assert rank >= 0 and rank < _sd.world_size
  47. assert _sd.proc_rank in proc_ranks
  48. @property
  49. def size(self):
  50. assert len(self.proc_ranks) > 0, "invalid group"
  51. return len(self.proc_ranks)
  52. @property
  53. def key(self):
  54. assert len(self.proc_ranks) > 0, "invalid group"
  55. return ",".join(map(str, self.proc_ranks))
  56. @property
  57. def rank(self):
  58. assert len(self.proc_ranks) > 0, "invalid group"
  59. return self.proc_ranks.index(_sd.proc_rank)
  60. @property
  61. def comp_node(self):
  62. assert len(self.proc_ranks) > 0, "invalid group"
  63. return "gpu{}:{}".format(_sd.device, self.stream)
  64. WORLD = Group([])
  65. def init_process_group(
  66. master_ip: str,
  67. port: int,
  68. world_size: int,
  69. rank: int,
  70. device: int,
  71. backend: Optional[str] = "nccl",
  72. ) -> None:
  73. """
  74. Initialize the distributed process group and specify the device used in the current process
  75. :param master_ip: ip address of the master node.
  76. :param port: port available for all processes to communicate.
  77. :param world_size: total number of processes participating in the job.
  78. :param rank: rank of the current process.
  79. :param device: the GPU device id to bind this process to.
  80. :param backend: communicator backend, currently support 'nccl' and 'ucx'.
  81. """
  82. if not isinstance(master_ip, str):
  83. raise TypeError("Expect type str but got {}".format(type(master_ip)))
  84. if not isinstance(port, int):
  85. raise TypeError("Expect type int but got {}".format(type(port)))
  86. if not isinstance(world_size, int):
  87. raise TypeError("Expect type int but got {}".format(type(world_size)))
  88. if not isinstance(rank, int):
  89. raise TypeError("Expect type int but got {}".format(type(rank)))
  90. if not isinstance(device, int):
  91. raise TypeError("Expect type int but got {}".format(type(backend)))
  92. if not isinstance(backend, str):
  93. raise TypeError("Expect type str but got {}".format(type(backend)))
  94. global _sd
  95. assert _sd is None, "init_process_group should be called only once"
  96. _sd = StaticData()
  97. assert world_size > 1
  98. assert rank >= 0 and rank < world_size
  99. assert port > 0
  100. _sd.client = Client(master_ip, port)
  101. _sd.master_ip = master_ip
  102. _sd.py_server_port = port
  103. _sd.mm_server_port = _sd.client.get_mm_server_port()
  104. _sd.world_size = world_size
  105. _sd.proc_rank = rank
  106. _sd.device = device
  107. _sd.backend = backend
  108. _sd.next_stream = 1
  109. WORLD.reset(list(range(world_size)))
  110. set_default_device("gpu{}".format(device))
  111. def is_distributed() -> bool:
  112. """Return True if the distributed process group has been initialized."""
  113. return _sd is not None
  114. def get_rank() -> int:
  115. """Get the rank of the current process."""
  116. return _sd.proc_rank if _sd is not None else 0
  117. def get_world_size() -> int:
  118. """Get the total number of processes participating in the job."""
  119. return _sd.world_size if _sd is not None else 1
  120. def get_backend() -> str:
  121. """Get the backend str."""
  122. assert _sd is not None, "please call init_process_group first"
  123. return _sd.backend if _sd is not None else None
  124. def get_py_server_addr() -> Tuple[str, int]:
  125. """Get master_ip and port of python XML RPC server."""
  126. assert _sd is not None, "please call init_process_group first"
  127. return _sd.master_ip, _sd.py_server_port
  128. def get_mm_server_addr() -> Tuple[str, int]:
  129. """Get master_ip and port of C++ mm_server."""
  130. assert _sd is not None, "please call init_process_group first"
  131. return _sd.master_ip, _sd.mm_server_port
  132. def get_client() -> Client:
  133. """Get client of python XML RPC server."""
  134. assert _sd is not None, "please call init_process_group first"
  135. return _sd.client
  136. def new_group(proc_ranks: List[int]) -> Group:
  137. """Build a subgroup containing certain ranks."""
  138. return Group(proc_ranks)
  139. def group_barrier(group: Optional[Group] = WORLD) -> None:
  140. """Block until all ranks in the group reach this barrier."""
  141. # if running with single node, skip it
  142. if _sd is None:
  143. return
  144. assert isinstance(group, Group)
  145. _sd.client.group_barrier(group.key, group.size)

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