__init__.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. from datetime import timedelta
  2. import logging
  3. import os
  4. import threading
  5. import warnings
  6. from typing import Generator, Tuple
  7. from urllib.parse import urlparse
  8. import torch
  9. import torch.distributed as dist
  10. logger = logging.getLogger(__name__)
  11. _init_counter = 0
  12. _init_counter_lock = threading.Lock()
  13. __all__ = ["is_available"]
  14. def is_available():
  15. return hasattr(torch._C, "_rpc_init")
  16. if is_available() and not torch._C._rpc_init():
  17. raise RuntimeError("Failed to initialize torch.distributed.rpc")
  18. if is_available():
  19. from torch._C._distributed_c10d import Store
  20. from torch._C._distributed_rpc import (
  21. _disable_jit_rref_pickle,
  22. _enable_jit_rref_pickle,
  23. _disable_server_process_global_profiler,
  24. _enable_server_process_global_profiler,
  25. _set_and_start_rpc_agent,
  26. _reset_current_rpc_agent,
  27. _delete_all_user_and_unforked_owner_rrefs,
  28. _destroy_rref_context,
  29. _set_profiler_node_id,
  30. _is_current_rpc_agent_set,
  31. _rref_context_get_debug_info,
  32. _cleanup_python_rpc_handler,
  33. _invoke_rpc_builtin,
  34. _invoke_rpc_python_udf,
  35. _invoke_rpc_torchscript,
  36. _invoke_remote_builtin,
  37. _invoke_remote_python_udf,
  38. _invoke_remote_torchscript,
  39. _set_rpc_timeout,
  40. _get_current_rpc_agent,
  41. get_rpc_timeout,
  42. enable_gil_profiling,
  43. RpcBackendOptions,
  44. _TensorPipeRpcBackendOptionsBase,
  45. RpcAgent,
  46. PyRRef,
  47. TensorPipeAgent,
  48. RemoteProfilerManager,
  49. WorkerInfo,
  50. _DEFAULT_INIT_METHOD,
  51. _DEFAULT_NUM_WORKER_THREADS,
  52. _UNSET_RPC_TIMEOUT,
  53. _DEFAULT_RPC_TIMEOUT_SEC,
  54. ) # noqa: F401
  55. from . import api, backend_registry, functions
  56. from .api import * # noqa: F401,F403
  57. import numbers
  58. import torch.distributed.autograd as dist_autograd
  59. from .backend_registry import BackendType
  60. from .options import TensorPipeRpcBackendOptions # noqa: F401
  61. from .server_process_global_profiler import (
  62. _server_process_global_profile,
  63. )
  64. rendezvous_iterator: Generator[Tuple[Store, int, int], None, None]
  65. __all__ += ["init_rpc", "BackendType", "TensorPipeRpcBackendOptions"]
  66. __all__ = __all__ + api.__all__ + backend_registry.__all__
  67. def init_rpc(
  68. name,
  69. backend=None,
  70. rank=-1,
  71. world_size=None,
  72. rpc_backend_options=None,
  73. ):
  74. r"""
  75. Initializes RPC primitives such as the local RPC agent
  76. and distributed autograd, which immediately makes the current
  77. process ready to send and receive RPCs.
  78. Args:
  79. name (str): a globally unique name of this node. (e.g.,
  80. ``Trainer3``, ``ParameterServer2``, ``Master``, ``Worker1``)
  81. Name can only contain number, alphabet, underscore, colon,
  82. and/or dash, and must be shorter than 128 characters.
  83. backend (BackendType, optional): The type of RPC backend
  84. implementation. Supported values is
  85. ``BackendType.TENSORPIPE`` (the default).
  86. See :ref:`rpc-backends` for more information.
  87. rank (int): a globally unique id/rank of this node.
  88. world_size (int): The number of workers in the group.
  89. rpc_backend_options (RpcBackendOptions, optional): The options
  90. passed to the RpcAgent constructor. It must be an agent-specific
  91. subclass of :class:`~torch.distributed.rpc.RpcBackendOptions`
  92. and contains agent-specific initialization configurations. By
  93. default, for all agents, it sets the default timeout to 60
  94. seconds and performs the rendezvous with an underlying process
  95. group initialized using ``init_method = "env://"``,
  96. meaning that environment variables ``MASTER_ADDR`` and
  97. ``MASTER_PORT`` need to be set properly. See
  98. :ref:`rpc-backends` for more information and find which options
  99. are available.
  100. """
  101. torch._C._log_api_usage_once("torch.distributed.init_rpc")
  102. if backend is not None and not isinstance(
  103. backend, backend_registry.BackendType
  104. ):
  105. raise TypeError("Argument backend must be a member of BackendType")
  106. if rpc_backend_options is not None and not isinstance(
  107. rpc_backend_options, RpcBackendOptions
  108. ):
  109. raise TypeError(
  110. "Argument rpc_backend_options must be an instance of RpcBackendOptions"
  111. )
  112. # Try to detect the backend from the options
  113. if backend is None and rpc_backend_options is not None:
  114. for candidate_backend in BackendType:
  115. if isinstance(
  116. rpc_backend_options,
  117. type(
  118. backend_registry.construct_rpc_backend_options(
  119. candidate_backend
  120. )
  121. ),
  122. ):
  123. backend = candidate_backend
  124. break
  125. else:
  126. raise TypeError(
  127. f"Could not infer backend for options {rpc_backend_options}"
  128. )
  129. # Ignore type error because mypy doesn't handle dynamically generated type objects (#4865)
  130. if backend != BackendType.TENSORPIPE: # type: ignore[attr-defined]
  131. logger.warning(
  132. f"RPC was initialized with no explicit backend but with options " # type: ignore[attr-defined]
  133. f"corresponding to {backend}, hence that backend will be used "
  134. f"instead of the default {BackendType.TENSORPIPE}. To silence this "
  135. f"warning pass `backend={backend}` explicitly."
  136. )
  137. if backend is None:
  138. backend = BackendType.TENSORPIPE # type: ignore[attr-defined]
  139. if rpc_backend_options is None:
  140. # default construct a set of RPC backend options.
  141. rpc_backend_options = backend_registry.construct_rpc_backend_options(
  142. backend
  143. )
  144. # Create store, performs rendezvous for static RPC group.
  145. if not world_size:
  146. # If world_size is not set in construction and also not set in environment variables
  147. # The store will be created for the dynamic group setting
  148. store = dist._create_store_from_options(rpc_backend_options, rank)
  149. else:
  150. # This rendezvous state sometimes is destroyed before all processes
  151. # finishing handshaking. To avoid that issue, we make it global to
  152. # keep it alive.
  153. global rendezvous_iterator
  154. rendezvous_iterator = dist.rendezvous(
  155. rpc_backend_options.init_method, rank=rank, world_size=world_size
  156. )
  157. store, _, _ = next(rendezvous_iterator)
  158. # Use same timeout as RPC.
  159. store.set_timeout(timedelta(seconds=rpc_backend_options.rpc_timeout))
  160. # Use a PrefixStore to distinguish multiple invocations.
  161. with _init_counter_lock:
  162. global _init_counter
  163. store = dist.PrefixStore(str("rpc_prefix_{}".format(_init_counter)), store)
  164. _init_counter += 1
  165. # Initialize autograd before RPC since _init_rpc_backend guarantees all
  166. # processes sync via the store. If we initialize autograd after RPC,
  167. # there could be a race where some nodes might have initialized autograd
  168. # and others might not have. As a result, a node calling
  169. # torch.distributed.autograd.backward() would run into errors since
  170. # other nodes might not have been initialized.
  171. dist_autograd._init(rank)
  172. _set_profiler_node_id(rank)
  173. # Initialize RPC.
  174. _init_rpc_backend(backend, store, name, rank, world_size, rpc_backend_options)
  175. def _validate_rpc_args(backend, store, name, rank, world_size, rpc_backend_options):
  176. type_mapping = {
  177. backend: backend_registry.BackendType,
  178. store: dist.Store,
  179. name: str,
  180. rank: numbers.Integral,
  181. # world_size can be None for a dynamic group
  182. world_size: (numbers.Integral, type(None)),
  183. rpc_backend_options: RpcBackendOptions,
  184. }
  185. for arg, arg_type in type_mapping.items():
  186. if not isinstance(arg, arg_type): # type: ignore[arg-type]
  187. raise RuntimeError(
  188. "Argument {} must be of type {} but got type {}".format(
  189. arg, arg_type, type(arg)
  190. )
  191. )
  192. def _init_rpc_backend(
  193. backend=BackendType.TENSORPIPE, # type: ignore[attr-defined]
  194. store=None,
  195. name=None,
  196. rank=-1,
  197. world_size=None,
  198. rpc_backend_options=None,
  199. ):
  200. _validate_rpc_args(backend, store, name, rank, world_size, rpc_backend_options)
  201. if _is_current_rpc_agent_set():
  202. raise RuntimeError("RPC is already initialized")
  203. # Initialize RPC.
  204. rpc_agent = backend_registry.init_backend(
  205. backend,
  206. store=store,
  207. name=name,
  208. rank=rank,
  209. world_size=world_size,
  210. rpc_backend_options=rpc_backend_options,
  211. )
  212. api._init_rpc_states(rpc_agent)
  213. @api._require_initialized
  214. def _get_debug_info():
  215. info = _rref_context_get_debug_info()
  216. info.update(api._get_current_rpc_agent().get_debug_info())
  217. info.update(dist_autograd._get_debug_info())
  218. return info