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.

launcher.py 5.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. # -*- coding: utf-8 -*-
  2. import functools
  3. import multiprocessing as mp
  4. import os
  5. import queue
  6. from .. import _exit
  7. from ..core._imperative_rt.core2 import full_sync
  8. from ..device import get_device_count
  9. from ..logger import get_logger
  10. from .group import _set_machine_ranks, group_barrier, init_process_group
  11. from .helper import _check_device_initialized
  12. from .server import Client, Server
  13. WARN_SUBPROCESS_EXIT_WITHOUT_RETURN = (
  14. "subprocess exited with code 0 but did not return a value"
  15. )
  16. def _run_wrapped(
  17. func,
  18. is_multimachine,
  19. master_ip,
  20. port,
  21. world_size,
  22. rank,
  23. dev,
  24. device_type,
  25. args,
  26. kwargs,
  27. backend,
  28. queue: mp.Queue,
  29. machine_ranks: list,
  30. ):
  31. r"""Init distributed process group and run wrapped function."""
  32. _check_device_initialized(device_type, dev)
  33. init_process_group(
  34. master_ip=master_ip,
  35. port=port,
  36. world_size=world_size,
  37. rank=rank,
  38. device=dev,
  39. backend=backend,
  40. device_type=device_type,
  41. )
  42. # set NCCL_LAUNCH_MODE to avoid deadlock
  43. os.environ["NCCL_LAUNCH_MODE"] = "PARALLEL"
  44. _set_machine_ranks(machine_ranks)
  45. if is_multimachine:
  46. group_barrier()
  47. ret = func(*args, **kwargs)
  48. queue.put((dev, ret))
  49. full_sync()
  50. if is_multimachine:
  51. group_barrier()
  52. _exit(0)
  53. class launcher:
  54. r"""Decorator for launching multiple processes in single-machine multi-gpu training.
  55. Args:
  56. func: the function you want to launch in distributed mode.
  57. n_gpus: how many devices each node.
  58. world_size: how many devices totally.
  59. rank_start: start number for rank.
  60. master_ip: ip address for master node (where the rank 0 is).
  61. port: server port for distributed server.
  62. backend: set default collective communication backend.
  63. """
  64. def __new__(cls, *args, **kwargs):
  65. if not args:
  66. return functools.partial(cls, **kwargs)
  67. return super().__new__(cls)
  68. def __init__(
  69. self,
  70. func,
  71. n_gpus=None,
  72. world_size=None,
  73. rank_start=0,
  74. master_ip="localhost",
  75. port=0,
  76. device_type="xpu",
  77. backend="nccl",
  78. ):
  79. self.func = func
  80. self.n_gpus = n_gpus if n_gpus is not None else get_device_count(device_type)
  81. self.world_size = world_size if world_size is not None else self.n_gpus
  82. self.rank_start = rank_start
  83. self.master_ip = master_ip
  84. self.port = port
  85. self.device_type = device_type
  86. self.backend = backend
  87. # master node create server
  88. if self.rank_start == 0:
  89. self.server = Server(self.port)
  90. self.port = self.server.py_server_port
  91. else:
  92. assert self.port != 0, "you have to assign a port for distributed server"
  93. def __call__(self, *args, **kwargs):
  94. procs = []
  95. queue = mp.Queue(self.n_gpus)
  96. results = [None] * self.n_gpus
  97. machine_ranks = [i + self.rank_start for i in range(self.n_gpus)]
  98. for dev in range(self.n_gpus):
  99. p = mp.Process(
  100. target=_run_wrapped,
  101. args=(
  102. self.func,
  103. self.world_size > self.n_gpus,
  104. self.master_ip,
  105. self.port,
  106. self.world_size,
  107. dev + self.rank_start,
  108. dev,
  109. self.device_type,
  110. args,
  111. kwargs,
  112. self.backend,
  113. queue,
  114. machine_ranks,
  115. ),
  116. )
  117. p.start()
  118. procs.append(p)
  119. devs = list(range(self.n_gpus))
  120. def terminate():
  121. for dev in devs:
  122. procs[dev].terminate()
  123. devs.clear()
  124. result_count = 0
  125. while len(devs) > 0:
  126. left = []
  127. # check all processes in one second
  128. time_to_wait = 1.0 / len(devs)
  129. for dev in devs:
  130. procs[dev].join(time_to_wait)
  131. code = procs[dev].exitcode
  132. # terminate processes if one of them has failed
  133. if code != 0 and code != None:
  134. terminate()
  135. assert (
  136. code == 0 or code == None
  137. ), "subprocess {} exit with code {}".format(dev + self.rank_start, code)
  138. if code == None:
  139. left.append(dev)
  140. # DO NOT delete it, multiprocess.Queue has small buffer
  141. # fetch data early to avoid dead lock
  142. if not queue.empty():
  143. result_count += 1
  144. dev, ret = queue.get_nowait()
  145. results[dev] = ret
  146. devs = left
  147. while not queue.empty():
  148. result_count += 1
  149. dev, ret = queue.get_nowait()
  150. results[dev] = ret
  151. if result_count < self.n_gpus:
  152. get_logger().warning(WARN_SUBPROCESS_EXIT_WITHOUT_RETURN)
  153. return results