rendezvous.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. # mypy: allow-untyped-defs
  2. try:
  3. from urllib.parse import urlparse, urlunparse
  4. except ImportError as e:
  5. raise ImportError(
  6. "urllib cannot be found, urlparse from python2 is no longer supported."
  7. ) from e
  8. import numbers
  9. import os
  10. import sys
  11. from datetime import timedelta
  12. from typing import Dict, Optional, Callable, Iterator, Tuple
  13. from torch.distributed import FileStore, PrefixStore, Store, TCPStore
  14. from .constants import default_pg_timeout
  15. _rendezvous_handlers: Dict[str, Callable[..., Iterator[Tuple[Store, int, int]]]] = {}
  16. __all__ = ["register_rendezvous_handler", "rendezvous"]
  17. def register_rendezvous_handler(scheme, handler):
  18. """
  19. Register a new rendezvous handler.
  20. Before we can run collective algorithms, participating processes
  21. need to find each other and exchange information to be able to
  22. communicate. We call this process rendezvous.
  23. The outcome of the rendezvous process is a triplet containing a
  24. shared key/value store, the rank of the process, and the total
  25. number of participating processes.
  26. If none of the bundled rendezvous methods apply to your execution
  27. environment you can opt to register your own rendezvous handler.
  28. Pick a unique name and use the URL scheme to identify it when
  29. calling the `rendezvous()` function.
  30. Args:
  31. scheme (str): URL scheme to identify your rendezvous handler.
  32. handler (function): Handler that is invoked when the
  33. `rendezvous()` function is called with a URL that uses
  34. the corresponding scheme. It must be a generator function
  35. that yields the triplet.
  36. """
  37. global _rendezvous_handlers
  38. if scheme in _rendezvous_handlers:
  39. raise RuntimeError(
  40. f"Rendezvous handler for {scheme}:// already registered"
  41. )
  42. _rendezvous_handlers[scheme] = handler
  43. # Query will have format "rank=0&world_size=1" and is
  44. # converted into {"rank": 0, "world_size": 1}
  45. def _query_to_dict(query: str) -> Dict[str, str]:
  46. return {pair[0]: pair[1] for pair in (pair.split("=") for pair in filter(None, query.split("&")))}
  47. def _get_use_libuv_from_query_dict(query_dict: Dict[str, str]) -> bool:
  48. # libuv is the default backend for TCPStore. To enable the non-libuv backend,
  49. # user can explicitly specify ``use_libuv=0`` in the URL parameter.
  50. return query_dict.get("use_libuv", os.environ.get("USE_LIBUV", "1")) == "1"
  51. def _rendezvous_helper(url: str, rank: int, world_size_opt: Optional[int], **kwargs):
  52. result = urlparse(url)
  53. if world_size_opt is None:
  54. world_size = -1
  55. if result.scheme == "env":
  56. rank = int(os.environ.get("RANK", rank))
  57. # If the world_size env variable is not present then it is a dynamic group
  58. world_size = int(os.environ.get("WORLD_SIZE", world_size))
  59. else:
  60. world_size = world_size_opt
  61. if rank != -1 or world_size != -1 or world_size_opt is None:
  62. query_dict = _query_to_dict(result.query)
  63. assert (
  64. "rank" not in query_dict and "world_size" not in query_dict
  65. ), f"The url: {url} has node-specific arguments(rank, world_size) already."
  66. if rank != -1:
  67. query_dict["rank"] = str(rank)
  68. if world_size != -1 or world_size_opt is None:
  69. query_dict["world_size"] = str(world_size)
  70. result = result._replace(
  71. query=f"{'&'.join([f'{k}={v}' for k, v in query_dict.items()])}"
  72. )
  73. url = urlunparse(result)
  74. if result.scheme not in _rendezvous_handlers:
  75. raise RuntimeError(f"No rendezvous handler for {result.scheme}://")
  76. return _rendezvous_handlers[result.scheme](url, **kwargs)
  77. def rendezvous(url: str, rank: int = -1, world_size: int = -1, **kwargs):
  78. if not isinstance(url, (str, bytes)):
  79. raise RuntimeError(f"`url` must be a string. {type(url)}: {url}")
  80. if not isinstance(rank, numbers.Integral):
  81. raise RuntimeError(f"`rank` must be an integer. {rank}")
  82. if not isinstance(world_size, numbers.Integral):
  83. raise RuntimeError(f"`world_size` must be an integer. {world_size}")
  84. return _rendezvous_helper(url, rank, world_size, **kwargs)
  85. def _create_store_from_options(backend_options, rank):
  86. store, _, _ = next(_rendezvous_helper(backend_options.init_method, rank, None))
  87. return store
  88. def _rendezvous_error(msg):
  89. return ValueError("Error initializing torch.distributed using " + msg)
  90. def _file_rendezvous_handler(url: str, **kwargs):
  91. def _error(msg):
  92. return _rendezvous_error("file:// rendezvous: " + msg)
  93. result = urlparse(url)
  94. path = result.path
  95. if sys.platform == "win32":
  96. import urllib.request
  97. full_path = result.netloc + result.path
  98. path = urllib.request.url2pathname(full_path)
  99. if path:
  100. # Normalizing an empty string produces ".", which is not expected.
  101. path = os.path.normpath(path)
  102. if not path:
  103. raise _error("path missing")
  104. query_dict = _query_to_dict(result.query)
  105. if "rank" not in query_dict:
  106. raise _error("rank parameter missing")
  107. if "world_size" not in query_dict:
  108. raise _error("world size parameter missing")
  109. rank = int(query_dict["rank"])
  110. world_size = int(query_dict["world_size"])
  111. store = FileStore(path, world_size)
  112. yield (store, rank, world_size)
  113. # If this configuration is invalidated, there is nothing we can do about it
  114. raise RuntimeError("Unable to perform rerendezvous using file:// method")
  115. def _torchelastic_use_agent_store() -> bool:
  116. return os.environ.get("TORCHELASTIC_USE_AGENT_STORE", None) == str(True)
  117. def _create_c10d_store(hostname, port, rank, world_size, timeout, use_libuv=True) -> Store:
  118. """
  119. Smartly creates a c10d Store object on ``rank`` based on whether we need to re-use agent store.
  120. The TCPStore server is assumed to be hosted
  121. on ``hostname:port``.
  122. By default, the TCPStore server uses the asynchronous implementation
  123. ``LibUVStoreDaemon`` which utilizes libuv.
  124. If ``torchelastic_use_agent_store()`` is ``True``, then it is assumed that
  125. the agent leader (node rank 0) hosts the TCPStore server (for which the
  126. endpoint is specified by the given ``hostname:port``). Hence
  127. ALL ranks will create and return a TCPStore client (e.g. ``start_daemon=False``).
  128. If ``torchelastic_use_agent_store()`` is ``False``, then rank 0 will host
  129. the TCPStore (with multi-tenancy) and it is assumed that rank 0's hostname
  130. and port are correctly passed via ``hostname`` and ``port``. All
  131. non-zero ranks will create and return a TCPStore client.
  132. """
  133. # check if port is uint16_t
  134. if not 0 <= port < 2**16:
  135. raise ValueError(f"port must have value from 0 to 65535 but was {port}.")
  136. if _torchelastic_use_agent_store():
  137. attempt = os.environ["TORCHELASTIC_RESTART_COUNT"]
  138. tcp_store = TCPStore(hostname, port, world_size, False, timeout)
  139. return PrefixStore(f"/worker/attempt_{attempt}", tcp_store)
  140. else:
  141. start_daemon = rank == 0
  142. return TCPStore(
  143. hostname, port, world_size, start_daemon, timeout, multi_tenant=True, use_libuv=use_libuv
  144. )
  145. def _tcp_rendezvous_handler(
  146. url: str, timeout: timedelta = default_pg_timeout, **kwargs
  147. ):
  148. def _error(msg):
  149. return _rendezvous_error("tcp:// rendezvous: " + msg)
  150. result = urlparse(url)
  151. if not result.port:
  152. raise _error("port number missing")
  153. query_dict = _query_to_dict(result.query)
  154. if "rank" not in query_dict:
  155. raise _error("rank parameter missing")
  156. if "world_size" not in query_dict:
  157. raise _error("world size parameter missing")
  158. rank = int(query_dict["rank"])
  159. world_size = int(query_dict["world_size"])
  160. use_libuv = _get_use_libuv_from_query_dict(query_dict)
  161. assert result.hostname is not None
  162. store = _create_c10d_store(result.hostname, result.port, rank, world_size, timeout, use_libuv)
  163. yield (store, rank, world_size)
  164. # If this configuration is invalidated, there is nothing we can do about it
  165. raise RuntimeError("Unable to perform re-rendezvous using tcp:// method")
  166. def _env_rendezvous_handler(
  167. url: str, timeout: timedelta = default_pg_timeout, **kwargs
  168. ):
  169. def _error(msg):
  170. return _rendezvous_error("env:// rendezvous: " + msg)
  171. def _env_error(var):
  172. return _error(f"environment variable {var} expected, but not set")
  173. def _get_env_or_raise(env_var: str) -> str:
  174. env_val = os.environ.get(env_var, None)
  175. if not env_val:
  176. raise _env_error(env_var)
  177. else:
  178. return env_val
  179. result = urlparse(url)
  180. query_dict = _query_to_dict(result.query)
  181. rank: int
  182. world_size: int
  183. master_port: int
  184. master_addr: str
  185. if "rank" in query_dict:
  186. rank = int(query_dict["rank"])
  187. else:
  188. rank = int(_get_env_or_raise("RANK"))
  189. if "world_size" in query_dict:
  190. world_size = int(query_dict["world_size"])
  191. else:
  192. world_size = int(_get_env_or_raise("WORLD_SIZE"))
  193. master_addr = _get_env_or_raise("MASTER_ADDR")
  194. master_port = int(_get_env_or_raise("MASTER_PORT"))
  195. use_libuv = _get_use_libuv_from_query_dict(query_dict)
  196. store = _create_c10d_store(master_addr, master_port, rank, world_size, timeout, use_libuv)
  197. yield (store, rank, world_size)
  198. # If this configuration is invalidated, there is nothing we can do about it
  199. raise RuntimeError("Unable to perform re-rendezvous using env:// method")
  200. register_rendezvous_handler("tcp", _tcp_rendezvous_handler)
  201. register_rendezvous_handler("env", _env_rendezvous_handler)
  202. register_rendezvous_handler("file", _file_rendezvous_handler)