options.py 6.8 KB

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