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.

distributed.py 8.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2020 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 Optional, Tuple
  10. from ..core._imperative_rt.ops import CollectiveCommMode
  11. from ..core.autodiff.builtin_op_utils import builtin_op_get_backward_fn
  12. from ..core.autodiff.grad import (
  13. Tracer,
  14. check_backward_allow_noinput,
  15. get_grad_managers,
  16. get_op_has_grad_fn,
  17. tracer_apply,
  18. )
  19. from ..core.ops.builtin import CollectiveComm, Copy, RemoteRecv, RemoteSend
  20. from ..core.tensor.core import apply
  21. from ..core.tensor.tensor import Tensor
  22. from ..device import get_default_device
  23. from ..distributed.group import (
  24. WORLD,
  25. Group,
  26. get_backend,
  27. get_client,
  28. get_mm_server_addr,
  29. get_rank,
  30. )
  31. from ..tensor import tensor
  32. __all__ = [
  33. "reduce_sum",
  34. "broadcast",
  35. "all_gather",
  36. "reduce_scatter_sum",
  37. "all_reduce_sum",
  38. "all_reduce_max",
  39. "all_reduce_min",
  40. "gather",
  41. "scatter",
  42. "all_to_all",
  43. "remote_send",
  44. "remote_recv",
  45. ]
  46. @apply.register()
  47. def _(op: RemoteSend, *args: Tensor):
  48. ret = apply.super(op, *args)
  49. # set extra information
  50. tracer_set = dict()
  51. for k in set().union(*(i._extra_data for i in args if isinstance(i, Tensor))):
  52. tracer_set[k.name] = True
  53. # check tracer_set in remote_recv
  54. get_client().set_remote_tracer(op.key, tracer_set)
  55. return ret
  56. @builtin_op_get_backward_fn.register(RemoteSend)
  57. def _(op: RemoteSend, inputs, outputs, input_requires_grad):
  58. def backward(*args):
  59. return [
  60. remote_recv(
  61. op.rank_to, inputs[0].shape, inputs[0].dtype, str(inputs[0].device)
  62. )
  63. ]
  64. return backward, [True]
  65. @get_op_has_grad_fn.register(RemoteSend)
  66. def _(op: RemoteSend):
  67. def has_grad(opnode, reached):
  68. return get_client().check_is_grad(op.key)
  69. return has_grad
  70. @check_backward_allow_noinput.register(RemoteSend)
  71. def _(op: RemoteSend):
  72. return True
  73. @builtin_op_get_backward_fn.register(RemoteRecv)
  74. def _(op: RemoteRecv, inputs, outputs, input_requires_grad):
  75. def backward(*output_grads):
  76. return [remote_send(output_grads[0], op.rank_from)]
  77. return backward, [True]
  78. @get_op_has_grad_fn.register(RemoteRecv)
  79. def _(op: RemoteRecv):
  80. def has_grad(opnode, reached):
  81. ret = False
  82. for v in opnode.outputs:
  83. if v() in reached:
  84. ret = True
  85. break
  86. get_client().set_is_grad(op.key, ret)
  87. return ret
  88. return has_grad
  89. def collective_comm(inp, mode, group, device):
  90. """Helper function for applying collective communication functions"""
  91. assert isinstance(group, Group)
  92. if group is None:
  93. return inp
  94. op = CollectiveComm()
  95. op.key = group.key
  96. op.nr_devices = group.size
  97. op.rank = group.rank
  98. op.is_root = op.rank == 0
  99. op.local_grad = False
  100. op.addr, op.port = get_mm_server_addr()
  101. op.mode = mode
  102. op.dtype = inp.dtype
  103. op.backend = get_backend()
  104. op.comp_node = device
  105. return apply(op, inp)[0]
  106. def reduce_sum(
  107. inp: Tensor, group: Optional[Group] = WORLD, device: Optional[str] = ""
  108. ) -> Tensor:
  109. """Create reduce_sum operator for collective communication
  110. :param inp: input tensor
  111. :param group: communication group
  112. :param device: execute placement
  113. """
  114. mode = CollectiveCommMode.REDUCE_SUM
  115. return collective_comm(inp, mode, group, device)
  116. def broadcast(
  117. inp: Tensor, group: Optional[Group] = WORLD, device: Optional[str] = ""
  118. ) -> Tensor:
  119. """Create broadcast operator for collective communication
  120. :param inp: input tensor
  121. :param group: communication group
  122. :param device: execute placement
  123. """
  124. mode = CollectiveCommMode.BROADCAST
  125. return collective_comm(inp, mode, group, device)
  126. def all_gather(
  127. inp: Tensor, group: Optional[Group] = WORLD, device: Optional[str] = ""
  128. ) -> Tensor:
  129. """Create all_gather operator for collective communication
  130. :param inp: input tensor
  131. :param group: communication group
  132. :param device: execute placement
  133. """
  134. mode = CollectiveCommMode.ALL_GATHER
  135. return collective_comm(inp, mode, group, device)
  136. def reduce_scatter_sum(
  137. inp: Tensor, group: Optional[Group] = WORLD, device: Optional[str] = ""
  138. ) -> Tensor:
  139. """Create reduce_scatter_sum operator for collective communication
  140. :param inp: input tensor
  141. :param group: communication group
  142. :param device: execute placement
  143. """
  144. mode = CollectiveCommMode.REDUCE_SCATTER_SUM
  145. return collective_comm(inp, mode, group, device)
  146. def all_reduce_sum(
  147. inp: Tensor, group: Optional[Group] = WORLD, device: Optional[str] = ""
  148. ) -> Tensor:
  149. """Create all_reduce_sum operator for collective communication
  150. :param inp: input tensor
  151. :param group: communication group
  152. :param device: execute placement
  153. """
  154. mode = CollectiveCommMode.ALL_REDUCE_SUM
  155. return collective_comm(inp, mode, group, device)
  156. def all_reduce_max(
  157. inp: Tensor, group: Optional[Group] = WORLD, device: Optional[str] = ""
  158. ) -> Tensor:
  159. """Create all_reduce_max operator for collective communication
  160. :param inp: input tensor
  161. :param group: communication group
  162. :param device: execute placement
  163. """
  164. mode = CollectiveCommMode.ALL_REDUCE_MAX
  165. return collective_comm(inp, mode, group, device)
  166. def all_reduce_min(
  167. inp: Tensor, group: Optional[Group] = WORLD, device: Optional[str] = ""
  168. ) -> Tensor:
  169. """Create all_reduce_min operator for collective communication
  170. :param inp: input tensor
  171. :param group: communication group
  172. :param device: execute placement
  173. """
  174. mode = CollectiveCommMode.ALL_REDUCE_MIN
  175. return collective_comm(inp, mode, group, device)
  176. def gather(
  177. inp: Tensor, group: Optional[Group] = WORLD, device: Optional[str] = ""
  178. ) -> Tensor:
  179. """Create gather operator for collective communication
  180. :param inp: input tensor
  181. :param group: communication group
  182. :param device: execute placement
  183. """
  184. mode = CollectiveCommMode.GATHER
  185. return collective_comm(inp, mode, group, device)
  186. def scatter(
  187. inp: Tensor, group: Optional[Group] = WORLD, device: Optional[str] = ""
  188. ) -> Tensor:
  189. """Create scatter operator for collective communication
  190. :param inp: input tensor
  191. :param group: communication group
  192. :param device: execute placement
  193. """
  194. mode = CollectiveCommMode.SCATTER
  195. return collective_comm(inp, mode, group, device)
  196. def all_to_all(
  197. inp: Tensor, group: Optional[Group] = WORLD, device: Optional[str] = ""
  198. ) -> Tensor:
  199. """Create all_to_all operator for collective communication
  200. :param inp: input tensor
  201. :param group: communication group
  202. :param device: execute placement
  203. """
  204. mode = CollectiveCommMode.ALL_TO_ALL
  205. return collective_comm(inp, mode, group, device)
  206. def remote_send(inp: Tensor, dest_rank: int) -> Tensor:
  207. """Send a Tensor to a remote process
  208. :param inp: tensor to send
  209. :param dest_rank: destination process rank
  210. """
  211. op = RemoteSend()
  212. op.key = "{}->{}".format(get_rank(), dest_rank)
  213. op.addr, op.port = get_mm_server_addr()
  214. op.rank_to = dest_rank
  215. return apply(op, inp)[0]
  216. def remote_recv(
  217. src_rank: int, shape: Tuple[int], dtype: type, device: Optional[str] = None
  218. ) -> Tensor:
  219. """Receive a Tensor from a remote process
  220. :param src_rank: source process rank
  221. :param shape: the shape of the tensor to receive
  222. :param dtype: the data type of the tensor to receive
  223. :param device: the device to place the received tensor,
  224. if None, use default device
  225. """
  226. key = "{}->{}".format(src_rank, get_rank())
  227. if device is None:
  228. device = get_default_device()
  229. # dummpy input
  230. inp = tensor([0])
  231. tracer_set = get_client().check_remote_tracer(key)
  232. for grad_manager in get_grad_managers():
  233. if grad_manager.name in tracer_set:
  234. grad_manager.wrt(inp)
  235. op = RemoteRecv()
  236. op.key = key
  237. op.cn = device
  238. op.shape = shape
  239. op.dtype = dtype
  240. op.addr, op.port = get_mm_server_addr()
  241. op.rank_from = src_rank
  242. return apply(op, inp)[0]

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