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

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

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