comm.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. # mypy: allow-untyped-defs
  2. import warnings
  3. import torch
  4. from torch._utils import (
  5. _flatten_dense_tensors,
  6. _get_device_index,
  7. _handle_complex,
  8. _reorder_tensors_as,
  9. _take_tensors,
  10. _unflatten_dense_tensors,
  11. )
  12. from torch.cuda import nccl
  13. def broadcast(tensor, devices=None, *, out=None):
  14. r"""Broadcasts a tensor to specified GPU devices.
  15. Args:
  16. tensor (Tensor): tensor to broadcast. Can be on CPU or GPU.
  17. devices (Iterable[torch.device, str or int], optional): an iterable of
  18. GPU devices, among which to broadcast.
  19. out (Sequence[Tensor], optional, keyword-only): the GPU tensors to
  20. store output results.
  21. .. note::
  22. Exactly one of :attr:`devices` and :attr:`out` must be specified.
  23. Returns:
  24. - If :attr:`devices` is specified,
  25. a tuple containing copies of :attr:`tensor`, placed on
  26. :attr:`devices`.
  27. - If :attr:`out` is specified,
  28. a tuple containing :attr:`out` tensors, each containing a copy of
  29. :attr:`tensor`.
  30. """
  31. tensor = _handle_complex(tensor)
  32. if not ((devices is None) ^ (out is None)):
  33. raise RuntimeError(
  34. f"Exactly one of 'devices' and 'out' must be specified, but got devices={devices} and out={out}"
  35. )
  36. if devices is not None:
  37. devices = [_get_device_index(d) for d in devices]
  38. return torch._C._broadcast(tensor, devices)
  39. else:
  40. return torch._C._broadcast_out(tensor, out)
  41. def broadcast_coalesced(tensors, devices, buffer_size=10485760):
  42. """Broadcast a sequence of tensors to the specified GPUs.
  43. Small tensors are first coalesced into a buffer to reduce the number of synchronizations.
  44. Args:
  45. tensors (sequence): tensors to broadcast. Must be on the same device,
  46. either CPU or GPU.
  47. devices (Iterable[torch.device, str or int]): an iterable of GPU
  48. devices, among which to broadcast.
  49. buffer_size (int): maximum size of the buffer used for coalescing
  50. Returns:
  51. A tuple containing copies of :attr:`tensor`, placed on :attr:`devices`.
  52. """
  53. devices = [_get_device_index(d) for d in devices]
  54. tensors = [_handle_complex(t) for t in tensors]
  55. return torch._C._broadcast_coalesced(tensors, devices, buffer_size)
  56. def reduce_add(inputs, destination=None):
  57. """Sum tensors from multiple GPUs.
  58. All inputs should have matching shapes, dtype, and layout. The output tensor
  59. will be of the same shape, dtype, and layout.
  60. Args:
  61. inputs (Iterable[Tensor]): an iterable of tensors to add.
  62. destination (int, optional): a device on which the output will be
  63. placed (default: current device).
  64. Returns:
  65. A tensor containing an elementwise sum of all inputs, placed on the
  66. :attr:`destination` device.
  67. """
  68. destination = _get_device_index(destination, optional=True)
  69. input_size = inputs[0].size()
  70. root_index = None # index of input tensor that already is on the correct device
  71. for i, inp in enumerate(inputs):
  72. assert inp.device.type != "cpu", "reduce_add expects all inputs to be on GPUs"
  73. if inp.get_device() == destination:
  74. root_index = i
  75. if inp.size() != input_size:
  76. got = "x".join(str(x) for x in inp.size())
  77. expected = "x".join(str(x) for x in input_size)
  78. raise ValueError(
  79. f"input {i} has invalid size: got {got}, but expected {expected}"
  80. )
  81. if root_index is None:
  82. raise RuntimeError(
  83. "reduce_add expects destination to be on the same GPU with one of the tensors"
  84. )
  85. if len(inputs) == 1:
  86. return inputs[0]
  87. if nccl.is_available(inputs):
  88. result = torch.empty_like(inputs[root_index])
  89. nccl.reduce(inputs, output=result, root=root_index)
  90. else:
  91. destination_device = torch.device(inputs[root_index].device.type, destination)
  92. nonroot = [t for i, t in enumerate(inputs) if i != root_index]
  93. # make a new tensor w/o clone
  94. result = inputs[root_index] + nonroot[0].to(
  95. device=destination_device, non_blocking=True
  96. )
  97. for other in nonroot[1:]:
  98. result.add_(other.to(device=destination_device, non_blocking=True))
  99. return result
  100. def reduce_add_coalesced(inputs, destination=None, buffer_size=10485760):
  101. """Sum tensors from multiple GPUs.
  102. Small tensors are first coalesced into a buffer to reduce the number
  103. of synchronizations.
  104. Args:
  105. inputs (Iterable[Iterable[Tensor]]): iterable of iterables that
  106. contain tensors from a single device.
  107. destination (int, optional): a device on which the output will be
  108. placed (default: current device).
  109. buffer_size (int): maximum size of the buffer used for coalescing
  110. Returns:
  111. A tuple of tensors containing an elementwise sum of each group of
  112. inputs, placed on the ``destination`` device.
  113. """
  114. # TODO: When `len(inputs) == 1` and all inputs are on `destination`, just
  115. # return `inputs`.
  116. dense_tensors: list[list] = [[] for _ in inputs] # shape (num_gpus, num_tensors)
  117. output = []
  118. ref_order = []
  119. # process sparse ones first since they may have different sizes on different gpus
  120. for tensor_at_gpus in zip(*inputs):
  121. if all(t.is_sparse for t in tensor_at_gpus):
  122. result = reduce_add(tensor_at_gpus, destination) # this will be sparse too
  123. output.append(result)
  124. ref_order.append(tensor_at_gpus[0])
  125. else:
  126. for coll, t in zip(dense_tensors, tensor_at_gpus):
  127. coll.append(t.to_dense() if t.is_sparse else t)
  128. ref_order.append(dense_tensors[0][-1])
  129. itrs = [_take_tensors(tensors, buffer_size) for tensors in dense_tensors]
  130. # now the dense ones, which have consistent sizes
  131. for chunks in zip(*itrs):
  132. flat_tensors = [
  133. _flatten_dense_tensors(chunk) for chunk in chunks
  134. ] # (num_gpus,)
  135. flat_result = reduce_add(flat_tensors, destination)
  136. for t in _unflatten_dense_tensors(flat_result, chunks[0]):
  137. # The unflattened tensors do not share storage, and we don't expose
  138. # base flat tensor anyways, so give them different version counters.
  139. # See NOTE [ Version Counter in comm.*_coalesced ]
  140. output.append(t.data)
  141. return tuple(_reorder_tensors_as(output, ref_order))
  142. def scatter(tensor, devices=None, chunk_sizes=None, dim=0, streams=None, *, out=None):
  143. """Scatters tensor across multiple GPUs.
  144. Args:
  145. tensor (Tensor): tensor to scatter. Can be on CPU or GPU.
  146. devices (Iterable[torch.device, str or int], optional): an iterable of
  147. GPU devices, among which to scatter.
  148. chunk_sizes (Iterable[int], optional): sizes of chunks to be placed on
  149. each device. It should match :attr:`devices` in length and sums to
  150. ``tensor.size(dim)``. If not specified, :attr:`tensor` will be divided
  151. into equal chunks.
  152. dim (int, optional): A dimension along which to chunk :attr:`tensor`.
  153. Default: ``0``.
  154. streams (Iterable[torch.cuda.Stream], optional): an iterable of Streams, among
  155. which to execute the scatter. If not specified, the default stream will
  156. be utilized.
  157. out (Sequence[Tensor], optional, keyword-only): the GPU tensors to
  158. store output results. Sizes of these tensors must match that of
  159. :attr:`tensor`, except for :attr:`dim`, where the total size must
  160. sum to ``tensor.size(dim)``.
  161. .. note::
  162. Exactly one of :attr:`devices` and :attr:`out` must be specified. When
  163. :attr:`out` is specified, :attr:`chunk_sizes` must not be specified and
  164. will be inferred from sizes of :attr:`out`.
  165. Returns:
  166. - If :attr:`devices` is specified,
  167. a tuple containing chunks of :attr:`tensor`, placed on
  168. :attr:`devices`.
  169. - If :attr:`out` is specified,
  170. a tuple containing :attr:`out` tensors, each containing a chunk of
  171. :attr:`tensor`.
  172. """
  173. tensor = _handle_complex(tensor)
  174. if out is None:
  175. devices = [_get_device_index(d) for d in devices]
  176. return tuple(torch._C._scatter(tensor, devices, chunk_sizes, dim, streams))
  177. else:
  178. if devices is not None:
  179. raise RuntimeError(
  180. f"'devices' must not be specified when 'out' is specified, but got devices={devices}"
  181. )
  182. if chunk_sizes is not None:
  183. raise RuntimeError(
  184. f"'chunk_sizes' must not be specified when 'out' is specified, but got chunk_sizes={chunk_sizes}"
  185. )
  186. return tuple(torch._C._scatter_out(tensor, out, dim, streams))
  187. def gather(tensors, dim=0, destination=None, *, out=None):
  188. r"""Gathers tensors from multiple GPU devices.
  189. Args:
  190. tensors (Iterable[Tensor]): an iterable of tensors to gather.
  191. Tensor sizes in all dimensions other than :attr:`dim` have to match.
  192. dim (int, optional): a dimension along which the tensors will be
  193. concatenated. Default: ``0``.
  194. destination (torch.device, str, or int, optional): the output device.
  195. Can be CPU or CUDA. Default: the current CUDA device.
  196. out (Tensor, optional, keyword-only): the tensor to store gather result.
  197. Its sizes must match those of :attr:`tensors`, except for :attr:`dim`,
  198. where the size must equal ``sum(tensor.size(dim) for tensor in tensors)``.
  199. Can be on CPU or CUDA.
  200. .. note::
  201. :attr:`destination` must not be specified when :attr:`out` is specified.
  202. Returns:
  203. - If :attr:`destination` is specified,
  204. a tensor located on :attr:`destination` device, that is a result of
  205. concatenating :attr:`tensors` along :attr:`dim`.
  206. - If :attr:`out` is specified,
  207. the :attr:`out` tensor, now containing results of concatenating
  208. :attr:`tensors` along :attr:`dim`.
  209. """
  210. tensors = [_handle_complex(t) for t in tensors]
  211. if out is None:
  212. if destination == -1:
  213. warnings.warn(
  214. "Using -1 to represent CPU tensor is deprecated. Please use a "
  215. 'device object or string instead, e.g., "cpu".',
  216. FutureWarning,
  217. stacklevel=2,
  218. )
  219. destination = _get_device_index(destination, allow_cpu=True, optional=True)
  220. return torch._C._gather(tensors, dim, destination)
  221. else:
  222. if destination is not None:
  223. raise RuntimeError(
  224. f"'destination' must not be specified when 'out' is specified, but got destination={destination}"
  225. )
  226. return torch._C._gather_out(tensors, out, dim)