options.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. # mypy: allow-untyped-defs
  2. from typing import Optional, Union
  3. import torch
  4. from . import _is_tensorpipe_available, constants as rpc_contants
  5. DeviceType = Union[int, str, torch.device]
  6. __all__ = ["TensorPipeRpcBackendOptions"]
  7. def _to_device(device: DeviceType) -> torch.device:
  8. device = torch.device(device)
  9. if device.type != "cuda":
  10. raise ValueError(
  11. "`set_devices` expect a list of CUDA devices, but got "
  12. f"device type {device.type}."
  13. )
  14. return device
  15. def _to_device_map(
  16. device_map: dict[DeviceType, DeviceType],
  17. ) -> dict[torch.device, torch.device]:
  18. full_device_map: dict[torch.device, torch.device] = {}
  19. reverse_map: dict[torch.device, torch.device] = {}
  20. for k, v in device_map.items():
  21. k, v = torch.device(k), torch.device(v)
  22. if v in reverse_map:
  23. raise ValueError(
  24. "`device_map` only supports 1-to-1 mapping, "
  25. f"trying to map {k} and {reverse_map[v]} to {v}"
  26. )
  27. full_device_map[k] = v
  28. reverse_map[v] = k
  29. return full_device_map
  30. def _to_device_list(devices: list[DeviceType]) -> list[torch.device]:
  31. return list(map(_to_device, devices))
  32. if _is_tensorpipe_available: # type: ignore[has-type]
  33. from torch._C._distributed_rpc import _TensorPipeRpcBackendOptionsBase
  34. else:
  35. _TensorPipeRpcBackendOptionsBase = object # type: ignore[assignment, misc]
  36. class TensorPipeRpcBackendOptions(_TensorPipeRpcBackendOptionsBase):
  37. r"""
  38. The backend options for
  39. :class:`~torch.distributed.rpc.TensorPipeAgent`, derived from
  40. :class:`~torch.distributed.rpc.RpcBackendOptions`.
  41. Args:
  42. num_worker_threads (int, optional): The number of threads in the
  43. thread-pool used by
  44. :class:`~torch.distributed.rpc.TensorPipeAgent` to execute
  45. requests (default: 16).
  46. rpc_timeout (float, optional): The default timeout, in seconds,
  47. for RPC requests (default: 60 seconds). If the RPC has not
  48. completed in this timeframe, an exception indicating so will
  49. be raised. Callers can override this timeout for individual
  50. RPCs in :meth:`~torch.distributed.rpc.rpc_sync` and
  51. :meth:`~torch.distributed.rpc.rpc_async` if necessary.
  52. init_method (str, optional): The URL to initialize the distributed
  53. store used for rendezvous. It takes any value accepted for the
  54. same argument of :meth:`~torch.distributed.init_process_group`
  55. (default: ``env://``).
  56. device_maps (Dict[str, Dict], optional): Device placement mappings from
  57. this worker to the callee. Key is the callee worker name and value
  58. the dictionary (``Dict`` of ``int``, ``str``, or ``torch.device``)
  59. that maps this worker's devices to the callee worker's devices.
  60. (default: ``None``)
  61. devices (List[int, str, or ``torch.device``], optional): all local
  62. CUDA devices used by RPC agent. By Default, it will be initialized
  63. to all local devices from its own ``device_maps`` and corresponding
  64. devices from its peers' ``device_maps``. When processing CUDA RPC
  65. requests, the agent will properly synchronize CUDA streams for
  66. all devices in this ``List``.
  67. """
  68. def __init__(
  69. self,
  70. *,
  71. num_worker_threads: int = rpc_contants.DEFAULT_NUM_WORKER_THREADS,
  72. rpc_timeout: float = rpc_contants.DEFAULT_RPC_TIMEOUT_SEC,
  73. init_method: str = rpc_contants.DEFAULT_INIT_METHOD,
  74. device_maps: Optional[dict[str, dict[DeviceType, DeviceType]]] = None,
  75. devices: Optional[list[DeviceType]] = None,
  76. _transports: Optional[list] = None,
  77. _channels: Optional[list] = None,
  78. ):
  79. full_device_maps = (
  80. {}
  81. if device_maps is None
  82. else {k: _to_device_map(v) for k, v in device_maps.items()}
  83. )
  84. full_device_list = [] if devices is None else _to_device_list(devices)
  85. super().__init__(
  86. num_worker_threads,
  87. _transports,
  88. _channels,
  89. rpc_timeout,
  90. init_method,
  91. full_device_maps,
  92. full_device_list,
  93. )
  94. def set_device_map(self, to: str, device_map: dict[DeviceType, DeviceType]):
  95. r"""
  96. Set device mapping between each RPC caller and callee pair. This
  97. function can be called multiple times to incrementally add
  98. device placement configurations.
  99. Args:
  100. to (str): Callee name.
  101. device_map (Dict of int, str, or torch.device): Device placement
  102. mappings from this worker to the callee. This map must be
  103. invertible.
  104. Example:
  105. >>> # xdoctest: +SKIP("distributed")
  106. >>> # both workers
  107. >>> def add(x, y):
  108. >>> print(x) # tensor([1., 1.], device='cuda:1')
  109. >>> return x + y, (x + y).to(2)
  110. >>>
  111. >>> # on worker 0
  112. >>> options = TensorPipeRpcBackendOptions(
  113. >>> num_worker_threads=8,
  114. >>> device_maps={"worker1": {0: 1}}
  115. >>> # maps worker0's cuda:0 to worker1's cuda:1
  116. >>> )
  117. >>> options.set_device_map("worker1", {1: 2})
  118. >>> # maps worker0's cuda:1 to worker1's cuda:2
  119. >>>
  120. >>> rpc.init_rpc(
  121. >>> "worker0",
  122. >>> rank=0,
  123. >>> world_size=2,
  124. >>> backend=rpc.BackendType.TENSORPIPE,
  125. >>> rpc_backend_options=options
  126. >>> )
  127. >>>
  128. >>> x = torch.ones(2)
  129. >>> rets = rpc.rpc_sync("worker1", add, args=(x.to(0), 1))
  130. >>> # The first argument will be moved to cuda:1 on worker1. When
  131. >>> # sending the return value back, it will follow the invert of
  132. >>> # the device map, and hence will be moved back to cuda:0 and
  133. >>> # cuda:1 on worker0
  134. >>> print(rets[0]) # tensor([2., 2.], device='cuda:0')
  135. >>> print(rets[1]) # tensor([2., 2.], device='cuda:1')
  136. """
  137. full_device_map = _to_device_map(device_map)
  138. curr_device_maps = super().device_maps
  139. if to in curr_device_maps:
  140. for k, v in full_device_map.items():
  141. if k in curr_device_maps[to] and v != curr_device_maps[to][k]:
  142. raise ValueError(
  143. "`set_device_map` only supports 1-to-1 mapping, trying"
  144. f" to map {k} to {v} and {curr_device_maps[to][k]}"
  145. )
  146. super()._set_device_map(to, full_device_map)
  147. def set_devices(self, devices: list[DeviceType]):
  148. r"""
  149. Set local devices used by the TensorPipe RPC agent. When processing
  150. CUDA RPC requests, the TensorPipe RPC agent will properly synchronize
  151. CUDA streams for all devices in this ``List``.
  152. Args:
  153. devices (List of int, str, or torch.device): local devices used by
  154. the TensorPipe RPC agent.
  155. """
  156. self.devices = _to_device_list(devices)