comm.py 10 KB

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