data_parallel.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. # mypy: allow-untyped-defs
  2. import operator
  3. import warnings
  4. from collections.abc import Sequence
  5. from itertools import chain
  6. from typing import Any, Generic, Optional, TypeVar, Union
  7. import torch
  8. from torch._utils import (
  9. _get_all_device_indices,
  10. _get_available_device_type,
  11. _get_device_index,
  12. _get_devices_properties,
  13. )
  14. from torch.nn.modules import Module
  15. from torch.nn.parallel.parallel_apply import parallel_apply
  16. from torch.nn.parallel.replicate import replicate
  17. from torch.nn.parallel.scatter_gather import gather, scatter_kwargs
  18. __all__ = ["DataParallel", "data_parallel"]
  19. def _check_balance(device_ids: Sequence[Union[int, torch.device]]) -> None:
  20. imbalance_warn = """
  21. There is an imbalance between your GPUs. You may want to exclude GPU {} which
  22. has less than 75% of the memory or cores of GPU {}. You can do so by setting
  23. the device_ids argument to DataParallel, or by setting the CUDA_VISIBLE_DEVICES
  24. environment variable."""
  25. device_ids = [_get_device_index(x, True) for x in device_ids]
  26. dev_props = _get_devices_properties(device_ids)
  27. def warn_imbalance(get_prop):
  28. values = [get_prop(props) for props in dev_props]
  29. min_pos, min_val = min(enumerate(values), key=operator.itemgetter(1))
  30. max_pos, max_val = max(enumerate(values), key=operator.itemgetter(1))
  31. if min_val / max_val < 0.75:
  32. warnings.warn(
  33. imbalance_warn.format(device_ids[min_pos], device_ids[max_pos])
  34. )
  35. return True
  36. return False
  37. if warn_imbalance(lambda props: props.total_memory):
  38. return
  39. if warn_imbalance(lambda props: props.multi_processor_count):
  40. return
  41. T = TypeVar("T", bound=Module)
  42. class DataParallel(Module, Generic[T]):
  43. r"""Implements data parallelism at the module level.
  44. This container parallelizes the application of the given :attr:`module` by
  45. splitting the input across the specified devices by chunking in the batch
  46. dimension (other objects will be copied once per device). In the forward
  47. pass, the module is replicated on each device, and each replica handles a
  48. portion of the input. During the backwards pass, gradients from each replica
  49. are summed into the original module.
  50. The batch size should be larger than the number of GPUs used.
  51. .. warning::
  52. It is recommended to use :class:`~torch.nn.parallel.DistributedDataParallel`,
  53. instead of this class, to do multi-GPU training, even if there is only a single
  54. node. See: :ref:`cuda-nn-ddp-instead` and :ref:`ddp`.
  55. Arbitrary positional and keyword inputs are allowed to be passed into
  56. DataParallel but some types are specially handled. tensors will be
  57. **scattered** on dim specified (default 0). tuple, list and dict types will
  58. be shallow copied. The other types will be shared among different threads
  59. and can be corrupted if written to in the model's forward pass.
  60. The parallelized :attr:`module` must have its parameters and buffers on
  61. ``device_ids[0]`` before running this :class:`~torch.nn.DataParallel`
  62. module.
  63. .. warning::
  64. In each forward, :attr:`module` is **replicated** on each device, so any
  65. updates to the running module in ``forward`` will be lost. For example,
  66. if :attr:`module` has a counter attribute that is incremented in each
  67. ``forward``, it will always stay at the initial value because the update
  68. is done on the replicas which are destroyed after ``forward``. However,
  69. :class:`~torch.nn.DataParallel` guarantees that the replica on
  70. ``device[0]`` will have its parameters and buffers sharing storage with
  71. the base parallelized :attr:`module`. So **in-place** updates to the
  72. parameters or buffers on ``device[0]`` will be recorded. E.g.,
  73. :class:`~torch.nn.BatchNorm2d` and :func:`~torch.nn.utils.spectral_norm`
  74. rely on this behavior to update the buffers.
  75. .. warning::
  76. Forward and backward hooks defined on :attr:`module` and its submodules
  77. will be invoked ``len(device_ids)`` times, each with inputs located on
  78. a particular device. Particularly, the hooks are only guaranteed to be
  79. executed in correct order with respect to operations on corresponding
  80. devices. For example, it is not guaranteed that hooks set via
  81. :meth:`~torch.nn.Module.register_forward_pre_hook` be executed before
  82. `all` ``len(device_ids)`` :meth:`~torch.nn.Module.forward` calls, but
  83. that each such hook be executed before the corresponding
  84. :meth:`~torch.nn.Module.forward` call of that device.
  85. .. warning::
  86. When :attr:`module` returns a scalar (i.e., 0-dimensional tensor) in
  87. :func:`forward`, this wrapper will return a vector of length equal to
  88. number of devices used in data parallelism, containing the result from
  89. each device.
  90. .. note::
  91. There is a subtlety in using the
  92. ``pack sequence -> recurrent network -> unpack sequence`` pattern in a
  93. :class:`~torch.nn.Module` wrapped in :class:`~torch.nn.DataParallel`.
  94. See :ref:`pack-rnn-unpack-with-data-parallelism` section in FAQ for
  95. details.
  96. Args:
  97. module (Module): module to be parallelized
  98. device_ids (list of int or torch.device): CUDA devices (default: all devices)
  99. output_device (int or torch.device): device location of output (default: device_ids[0])
  100. Attributes:
  101. module (Module): the module to be parallelized
  102. Example::
  103. >>> # xdoctest: +SKIP
  104. >>> net = torch.nn.DataParallel(model, device_ids=[0, 1, 2])
  105. >>> output = net(input_var) # input_var can be on any device, including CPU
  106. """
  107. # TODO: update notes/cuda.rst when this class handles 8+ GPUs well
  108. def __init__(
  109. self,
  110. module: T,
  111. device_ids: Optional[Sequence[Union[int, torch.device]]] = None,
  112. output_device: Optional[Union[int, torch.device]] = None,
  113. dim: int = 0,
  114. ) -> None:
  115. super().__init__()
  116. torch._C._log_api_usage_once("torch.nn.parallel.DataParallel")
  117. device_type = _get_available_device_type()
  118. if device_type is None or device_type == "mps":
  119. self.module = module
  120. self.device_ids = []
  121. return
  122. if device_ids is None:
  123. device_ids = _get_all_device_indices()
  124. if device_ids is None:
  125. raise RuntimeError("no available devices were found")
  126. if output_device is None:
  127. output_device = device_ids[0]
  128. self.dim = dim
  129. self.module = module
  130. self.device_ids = [_get_device_index(x, True) for x in device_ids]
  131. self.output_device = _get_device_index(output_device, True)
  132. self.src_device_obj = torch.device(device_type, self.device_ids[0])
  133. if device_type == "cuda":
  134. _check_balance(self.device_ids)
  135. if len(self.device_ids) == 1:
  136. self.module.to(self.src_device_obj)
  137. def forward(self, *inputs: Any, **kwargs: Any) -> Any:
  138. with torch.autograd.profiler.record_function("DataParallel.forward"):
  139. if not self.device_ids:
  140. return self.module(*inputs, **kwargs)
  141. for t in chain(self.module.parameters(), self.module.buffers()):
  142. if t.device != self.src_device_obj:
  143. raise RuntimeError(
  144. "module must have its parameters and buffers "
  145. f"on device {self.src_device_obj} (device_ids[0]) but found one of "
  146. f"them on device: {t.device}"
  147. )
  148. inputs, module_kwargs = self.scatter(inputs, kwargs, self.device_ids)
  149. # for forward function without any inputs, empty list and dict will be created
  150. # so the module can be executed on one device which is the first one in device_ids
  151. if not inputs and not module_kwargs:
  152. inputs = ((),)
  153. module_kwargs = ({},)
  154. if len(self.device_ids) == 1:
  155. return self.module(*inputs[0], **module_kwargs[0])
  156. replicas = self.replicate(self.module, self.device_ids[: len(inputs)])
  157. outputs = self.parallel_apply(replicas, inputs, module_kwargs)
  158. return self.gather(outputs, self.output_device)
  159. def replicate(
  160. self, module: T, device_ids: Sequence[Union[int, torch.device]]
  161. ) -> list[T]:
  162. return replicate(module, device_ids, not torch.is_grad_enabled())
  163. def scatter(
  164. self,
  165. inputs: tuple[Any, ...],
  166. kwargs: Optional[dict[str, Any]],
  167. device_ids: Sequence[Union[int, torch.device]],
  168. ) -> Any:
  169. return scatter_kwargs(inputs, kwargs, device_ids, dim=self.dim)
  170. def parallel_apply(
  171. self, replicas: Sequence[T], inputs: Sequence[Any], kwargs: Any
  172. ) -> list[Any]:
  173. return parallel_apply(
  174. replicas, inputs, kwargs, self.device_ids[: len(replicas)]
  175. )
  176. def gather(self, outputs: Any, output_device: Union[int, torch.device]) -> Any:
  177. return gather(outputs, output_device, dim=self.dim)
  178. def data_parallel(
  179. module: Module,
  180. inputs: Any,
  181. device_ids: Optional[Sequence[Union[int, torch.device]]] = None,
  182. output_device: Optional[Union[int, torch.device]] = None,
  183. dim: int = 0,
  184. module_kwargs: Optional[Any] = None,
  185. ) -> torch.Tensor:
  186. r"""Evaluate module(input) in parallel across the GPUs given in device_ids.
  187. This is the functional version of the DataParallel module.
  188. Args:
  189. module (Module): the module to evaluate in parallel
  190. inputs (Tensor): inputs to the module
  191. device_ids (list of int or torch.device): GPU ids on which to replicate module
  192. output_device (list of int or torch.device): GPU location of the output Use -1 to indicate the CPU.
  193. (default: device_ids[0])
  194. Returns:
  195. a Tensor containing the result of module(input) located on
  196. output_device
  197. """
  198. if not isinstance(inputs, tuple):
  199. inputs = (inputs,) if inputs is not None else ()
  200. device_type = _get_available_device_type()
  201. if device_type is None:
  202. raise RuntimeError("device type could not be determined")
  203. if device_ids is None:
  204. device_ids = _get_all_device_indices()
  205. if device_ids is None:
  206. raise RuntimeError("no available devices were found")
  207. if output_device is None:
  208. output_device = device_ids[0]
  209. device_ids = [_get_device_index(x, True) for x in device_ids]
  210. output_device = _get_device_index(output_device, True)
  211. src_device_obj = torch.device(device_type, device_ids[0])
  212. for t in chain(module.parameters(), module.buffers()):
  213. if t.device != src_device_obj:
  214. raise RuntimeError(
  215. "module must have its parameters and buffers "
  216. f"on device {src_device_obj} (device_ids[0]) but found one of "
  217. f"them on device: {t.device}"
  218. )
  219. inputs, module_kwargs = scatter_kwargs(inputs, module_kwargs, device_ids, dim)
  220. # for module without any inputs, empty list and dict will be created
  221. # so the module can be executed on one device which is the first one in device_ids
  222. if not inputs and not module_kwargs:
  223. inputs = ((),)
  224. module_kwargs = ({},)
  225. assert module_kwargs is not None
  226. if len(device_ids) == 1:
  227. return module(*inputs[0], **module_kwargs[0])
  228. used_device_ids = device_ids[: len(inputs)]
  229. replicas = replicate(module, used_device_ids)
  230. outputs = parallel_apply(replicas, inputs, module_kwargs, used_device_ids)
  231. return gather(outputs, output_device, dim)