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.0 kB

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

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