rendezvous.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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 collections.abc import Callable, Iterator
  12. from datetime import timedelta
  13. from torch.distributed import FileStore, 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(f"Rendezvous handler for {scheme}:// already registered")
  40. _rendezvous_handlers[scheme] = handler
  41. # Query will have format "rank=0&world_size=1" and is
  42. # converted into {"rank": 0, "world_size": 1}
  43. def _query_to_dict(query: str) -> dict[str, str]:
  44. return {
  45. pair[0]: pair[1]
  46. for pair in (pair.split("=") for pair in filter(None, query.split("&")))
  47. }
  48. def _get_use_libuv_from_query_dict(query_dict: dict[str, str]) -> bool:
  49. # libuv is the default backend for TCPStore. To enable the non-libuv backend,
  50. # user can explicitly specify ``use_libuv=0`` in the URL parameter.
  51. if sys.platform == "win32":
  52. # PyTorch is built without libuv support on windows, so default to 0
  53. return query_dict.get("use_libuv", os.environ.get("USE_LIBUV", "0")) == "1"
  54. return query_dict.get("use_libuv", os.environ.get("USE_LIBUV", "1")) == "1"
  55. def _rendezvous_helper(url: str, rank: int, world_size_opt: int | None, **kwargs):
  56. result = urlparse(url)
  57. if world_size_opt is None:
  58. world_size = -1
  59. if result.scheme == "env":
  60. rank = int(os.environ.get("RANK", rank))
  61. # If the world_size env variable is not present then it is a dynamic group
  62. world_size = int(os.environ.get("WORLD_SIZE", world_size))
  63. else:
  64. world_size = world_size_opt
  65. if rank != -1 or world_size != -1 or world_size_opt is None:
  66. query_dict = _query_to_dict(result.query)
  67. if "rank" in query_dict or "world_size" in query_dict:
  68. raise AssertionError(
  69. f"The url: {url} has node-specific arguments(rank, world_size) already."
  70. )
  71. if rank != -1:
  72. query_dict["rank"] = str(rank)
  73. if world_size != -1 or world_size_opt is None:
  74. query_dict["world_size"] = str(world_size)
  75. result = result._replace(
  76. query=f"{'&'.join([f'{k}={v}' for k, v in query_dict.items()])}"
  77. )
  78. # pyrefly: ignore [bad-assignment]
  79. url = urlunparse(result)
  80. if result.scheme not in _rendezvous_handlers:
  81. raise RuntimeError(f"No rendezvous handler for {result.scheme}://")
  82. return _rendezvous_handlers[result.scheme](url, **kwargs)
  83. def rendezvous(url: str, rank: int = -1, world_size: int = -1, **kwargs):
  84. if not isinstance(url, (str, bytes)):
  85. raise RuntimeError(f"`url` must be a string. {type(url)}: {url}")
  86. if not isinstance(rank, numbers.Integral):
  87. raise RuntimeError(f"`rank` must be an integer. {rank}")
  88. if not isinstance(world_size, numbers.Integral):
  89. raise RuntimeError(f"`world_size` must be an integer. {world_size}")
  90. return _rendezvous_helper(url, rank, world_size, **kwargs)
  91. def _create_store_from_options(backend_options, rank):
  92. store, _, _ = next(_rendezvous_helper(backend_options.init_method, rank, None))
  93. return store
  94. def _rendezvous_error(msg):
  95. return ValueError("Error initializing torch.distributed using " + msg)
  96. def _file_rendezvous_handler(url: str, **kwargs):
  97. def _error(msg):
  98. return _rendezvous_error("file:// rendezvous: " + msg)
  99. result = urlparse(url)
  100. path = result.path
  101. if sys.platform == "win32":
  102. import urllib.request
  103. full_path = result.netloc + result.path
  104. path = urllib.request.url2pathname(full_path)
  105. if path:
  106. # Normalizing an empty string produces ".", which is not expected.
  107. path = os.path.normpath(path)
  108. if not path:
  109. raise _error("path missing")
  110. query_dict = _query_to_dict(result.query)
  111. if "rank" not in query_dict:
  112. raise _error("rank parameter missing")
  113. if "world_size" not in query_dict:
  114. raise _error("world size parameter missing")
  115. rank = int(query_dict["rank"])
  116. world_size = int(query_dict["world_size"])
  117. store = FileStore(path, world_size)
  118. yield (store, rank, world_size)
  119. # If this configuration is invalidated, there is nothing we can do about it
  120. raise RuntimeError("Unable to perform rerendezvous using file:// method")
  121. def _torchelastic_use_agent_store() -> bool:
  122. return os.environ.get("TORCHELASTIC_USE_AGENT_STORE", None) == str(True)
  123. def _create_c10d_store(
  124. hostname, port, rank, world_size, timeout, use_libuv=True
  125. ) -> Store:
  126. """
  127. Smartly creates a c10d Store object on ``rank`` based on whether we need to reuse agent store.
  128. The TCPStore server is assumed to be hosted
  129. on ``hostname:port``.
  130. By default, the TCPStore server uses the asynchronous implementation
  131. ``LibUVStoreDaemon`` which utilizes libuv.
  132. If ``torchelastic_use_agent_store()`` is ``True``, then it is assumed that
  133. the agent leader (node rank 0) hosts the TCPStore server (for which the
  134. endpoint is specified by the given ``hostname:port``). Hence
  135. ALL ranks will create and return a TCPStore client (e.g. ``start_daemon=False``).
  136. If ``torchelastic_use_agent_store()`` is ``False``, then rank 0 will host
  137. the TCPStore (with multi-tenancy) and it is assumed that rank 0's hostname
  138. and port are correctly passed via ``hostname`` and ``port``. All
  139. non-zero ranks will create and return a TCPStore client.
  140. """
  141. # check if port is uint16_t
  142. if not 0 <= port < 2**16:
  143. raise ValueError(f"port must have value from 0 to 65535 but was {port}.")
  144. if _torchelastic_use_agent_store():
  145. # We create a new TCPStore for every retry so no need to add prefix for each attempt.
  146. return TCPStore(
  147. host_name=hostname,
  148. port=port,
  149. world_size=world_size,
  150. is_master=False,
  151. timeout=timeout,
  152. )
  153. else:
  154. start_daemon = rank == 0
  155. return TCPStore(
  156. host_name=hostname,
  157. port=port,
  158. world_size=world_size,
  159. is_master=start_daemon,
  160. timeout=timeout,
  161. multi_tenant=True,
  162. use_libuv=use_libuv,
  163. )
  164. def _tcp_rendezvous_handler(
  165. url: str, timeout: timedelta = default_pg_timeout, **kwargs
  166. ):
  167. def _error(msg):
  168. return _rendezvous_error("tcp:// rendezvous: " + msg)
  169. result = urlparse(url)
  170. if result.port is None:
  171. raise _error("port number missing")
  172. query_dict = _query_to_dict(result.query)
  173. if "rank" not in query_dict:
  174. raise _error("rank parameter missing")
  175. if "world_size" not in query_dict:
  176. raise _error("world size parameter missing")
  177. rank = int(query_dict["rank"])
  178. world_size = int(query_dict["world_size"])
  179. use_libuv = _get_use_libuv_from_query_dict(query_dict)
  180. if result.hostname is None:
  181. raise AssertionError("hostname cannot be None")
  182. store = _create_c10d_store(
  183. result.hostname, result.port, rank, world_size, timeout, use_libuv
  184. )
  185. yield (store, rank, world_size)
  186. # If this configuration is invalidated, there is nothing we can do about it
  187. raise RuntimeError("Unable to perform re-rendezvous using tcp:// method")
  188. def _env_rendezvous_handler(
  189. url: str, timeout: timedelta = default_pg_timeout, **kwargs
  190. ):
  191. def _error(msg):
  192. return _rendezvous_error("env:// rendezvous: " + msg)
  193. def _env_error(var):
  194. return _error(f"environment variable {var} expected, but not set")
  195. def _get_env_or_raise(env_var: str) -> str:
  196. env_val = os.environ.get(env_var, None)
  197. if not env_val:
  198. raise _env_error(env_var)
  199. else:
  200. return env_val
  201. result = urlparse(url)
  202. query_dict = _query_to_dict(result.query)
  203. rank: int
  204. world_size: int
  205. master_port: int
  206. master_addr: str
  207. if "rank" in query_dict:
  208. rank = int(query_dict["rank"])
  209. else:
  210. rank = int(_get_env_or_raise("RANK"))
  211. if "world_size" in query_dict:
  212. world_size = int(query_dict["world_size"])
  213. else:
  214. world_size = int(_get_env_or_raise("WORLD_SIZE"))
  215. master_addr = _get_env_or_raise("MASTER_ADDR")
  216. master_port = int(_get_env_or_raise("MASTER_PORT"))
  217. use_libuv = _get_use_libuv_from_query_dict(query_dict)
  218. store = _create_c10d_store(
  219. master_addr, master_port, rank, world_size, timeout, use_libuv
  220. )
  221. yield (store, rank, world_size)
  222. # If this configuration is invalidated, there is nothing we can do about it
  223. raise RuntimeError("Unable to perform re-rendezvous using env:// method")
  224. register_rendezvous_handler("tcp", _tcp_rendezvous_handler)
  225. register_rendezvous_handler("env", _env_rendezvous_handler)
  226. register_rendezvous_handler("file", _file_rendezvous_handler)