api.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. # mypy: allow-untyped-defs
  2. # Copyright (c) Facebook, Inc. and its affiliates.
  3. # All rights reserved.
  4. #
  5. # This source code is licensed under the BSD-style license found in the
  6. # LICENSE file in the root directory of this source tree.
  7. import socket
  8. from abc import ABC, abstractmethod
  9. from dataclasses import dataclass
  10. from typing import Any, Callable, ClassVar, Optional
  11. from torch.distributed import Store
  12. from torch.distributed.elastic.utils.distributed import get_free_port
  13. __all__ = [
  14. "RendezvousClosedError",
  15. "RendezvousConnectionError",
  16. "RendezvousError",
  17. "RendezvousGracefulExitError",
  18. "RendezvousHandler",
  19. "RendezvousHandlerCreator",
  20. "RendezvousHandlerRegistry",
  21. "RendezvousInfo",
  22. "RendezvousParameters",
  23. "RendezvousStateError",
  24. "RendezvousStoreInfo",
  25. "RendezvousTimeoutError",
  26. "rendezvous_handler_registry",
  27. ]
  28. class RendezvousError(Exception):
  29. """Represents the base type for rendezvous errors."""
  30. class RendezvousClosedError(RendezvousError):
  31. """Raised when a rendezvous is closed."""
  32. class RendezvousTimeoutError(RendezvousError):
  33. """Raised when a rendezvous did not complete on time."""
  34. class RendezvousConnectionError(RendezvousError):
  35. """Raised when the connection to a rendezvous backend has failed."""
  36. class RendezvousStateError(RendezvousError):
  37. """Raised when the state of a rendezvous is corrupt."""
  38. class RendezvousGracefulExitError(RendezvousError):
  39. """Raised when node wasn't not included in rendezvous and gracefully exits.
  40. Exception is a mechanism to exit the stack, however does not mean a failure.
  41. """
  42. @dataclass
  43. class RendezvousStoreInfo:
  44. """Store address and port that can be used to bootstrap trainer distributed comms"""
  45. MASTER_ADDR_KEY: ClassVar[str] = "MASTER_ADDR"
  46. MASTER_PORT_KEY: ClassVar[str] = "MASTER_PORT"
  47. master_addr: str
  48. master_port: int
  49. @staticmethod
  50. def build(
  51. rank: int,
  52. store: Store,
  53. local_addr: Optional[str],
  54. server_port: Optional[int] = None,
  55. ) -> "RendezvousStoreInfo":
  56. """Factory method, finds unused new port on rank0 host and addr/port info with all ranks.
  57. If master_addr/master_port is knowns (useful when sharing existing tcp store server) use the constructor.
  58. Args:
  59. rank: rank of the current node
  60. store: store to use for rendezvous
  61. local_addr: address of the current node, if not provided will be resolved from hostname
  62. server_port: port of the TCPStore server, when the TCPStore is shared.
  63. """
  64. # TODO swap to collectives comms API
  65. if rank == 0:
  66. addr = local_addr or socket.getfqdn()
  67. # When TCPStore is not shared, we fallback to get_free_port.
  68. port = server_port or get_free_port()
  69. store.set(
  70. RendezvousStoreInfo.MASTER_ADDR_KEY,
  71. addr.encode(encoding="UTF-8"), # type: ignore[arg-type]
  72. )
  73. store.set(
  74. RendezvousStoreInfo.MASTER_PORT_KEY,
  75. str(port).encode(encoding="UTF-8"), # type: ignore[arg-type]
  76. )
  77. addr = store.get(RendezvousStoreInfo.MASTER_ADDR_KEY).decode(encoding="UTF-8")
  78. port = int(
  79. store.get(RendezvousStoreInfo.MASTER_PORT_KEY).decode(encoding="UTF-8")
  80. )
  81. return RendezvousStoreInfo(master_addr=addr, master_port=port)
  82. class RendezvousInfo:
  83. """Holds the information about the rendezvous."""
  84. def __init__(
  85. self,
  86. store: Store,
  87. rank: int,
  88. world_size: int,
  89. bootstrap_store_info: RendezvousStoreInfo,
  90. ):
  91. self._store = store
  92. self._rank = rank
  93. self._world_size = world_size
  94. self._bootstrap_store_info = bootstrap_store_info
  95. @property
  96. def store(self) -> Store:
  97. """Store used by torchelastic control plane"""
  98. return self._store
  99. @property
  100. def rank(self) -> int:
  101. """Rank within a group"""
  102. return self._rank
  103. @property
  104. def world_size(self) -> int:
  105. """Global group size"""
  106. return self._world_size
  107. @property
  108. def bootstrap_store_info(self) -> Optional[RendezvousStoreInfo]:
  109. """Store information that can used by trainer code to bootstrap distributed comms."""
  110. return self._bootstrap_store_info
  111. class RendezvousHandler(ABC):
  112. """Main rendezvous interface.
  113. Note:
  114. Distributed Torch users normally **do not** need to implement their own
  115. ``RendezvousHandler``. An implementation based on C10d Store is already
  116. provided, and is recommended for most users.
  117. """
  118. @abstractmethod
  119. def get_backend(self) -> str:
  120. """Return the name of the rendezvous backend."""
  121. @property
  122. def use_agent_store(self) -> bool:
  123. """Indicates that store reference returned by :py:meth:`next_rendezvous` can be shared with user
  124. applications and will be available during application lifecycle.
  125. Rendezvous handler impl will share store details as instance of :py:class:`RendezvousStoreInfo`.
  126. Applications as a convention use `MASTER_ADDR`/`MASTER_PORT` env variables to lookup the store.
  127. """
  128. return False
  129. @abstractmethod
  130. def next_rendezvous(self) -> RendezvousInfo:
  131. """Main entry-point into the rendezvous barrier.
  132. Blocks until the rendezvous is complete and the current process is
  133. included in the formed worker group, or a timeout occurs, or the
  134. rendezvous was marked closed.
  135. Returns:
  136. Instance of :py:class:`RendezvousInfo`.
  137. Raises:
  138. RendezvousClosedError:
  139. The rendezvous is closed.
  140. RendezvousConnectionError:
  141. The connection to the rendezvous backend has failed.
  142. RendezvousStateError:
  143. The rendezvous state is corrupt.
  144. RendezvousTimeoutError:
  145. The rendezvous did not complete on time.
  146. """
  147. @abstractmethod
  148. def is_closed(self) -> bool:
  149. """Check whether the rendezvous has been closed.
  150. A closed rendezvous means all future attempts to re-rendezvous within
  151. same job will fail.
  152. ``is_closed()`` and :py:meth:`set_closed` have semantics of eventual
  153. propagation and should not be used for synchronization. The intention is
  154. that if at least one node decides the job is finished, it will close the
  155. rendezvous, and other nodes will soon observe this and stop running as
  156. well.
  157. """
  158. @abstractmethod
  159. def set_closed(self):
  160. """Mark the rendezvous as closed."""
  161. @abstractmethod
  162. def num_nodes_waiting(self) -> int:
  163. """Return the number of nodes who arrived late at the rendezvous
  164. barrier, hence were not included in the current worker group.
  165. Callers should periodically call this method to check whether new
  166. nodes are waiting to join the job and if so admit them by calling
  167. :py:meth:`next_rendezvous()` (re-rendezvous).
  168. """
  169. @abstractmethod
  170. def get_run_id(self) -> str:
  171. """Return the run id of the rendezvous.
  172. The run id is a user-defined id that uniquely identifies an instance of
  173. a distributed application. It typically maps to a job id and is used to
  174. allow nodes to join the correct distributed application.
  175. """
  176. @abstractmethod
  177. def shutdown(self) -> bool:
  178. """Close all resources that were open for the rendezvous.
  179. Example::
  180. rdzv_handler = ...
  181. try:
  182. store, rank, world_size = rdzv_handler.next_rendezvous()
  183. finally:
  184. rdzv_handler.shutdown()
  185. """
  186. class RendezvousParameters:
  187. """Hold the parameters to construct a :py:class:`RendezvousHandler`.
  188. Args:
  189. backend:
  190. The name of the backend to use to handle the rendezvous.
  191. endpoint:
  192. The endpoint of the rendezvous, usually in form <hostname>[:<port>].
  193. run_id:
  194. The id of the rendezvous.
  195. min_nodes:
  196. The minimum number of nodes to admit to the rendezvous.
  197. max_nodes:
  198. The maximum number of nodes to admit to the rendezvous.
  199. local_addr:
  200. The address of the local node.
  201. **kwargs:
  202. Additional parameters for the specified backend.
  203. """
  204. def __init__(
  205. self,
  206. backend: str,
  207. endpoint: str,
  208. run_id: str,
  209. min_nodes: int,
  210. max_nodes: int,
  211. local_addr: Optional[str] = None,
  212. **kwargs,
  213. ):
  214. if not backend:
  215. raise ValueError("The rendezvous backend name must be a non-empty string.")
  216. if min_nodes < 1:
  217. raise ValueError(
  218. f"The minimum number of rendezvous nodes ({min_nodes}) must be greater than zero."
  219. )
  220. if max_nodes < min_nodes:
  221. raise ValueError(
  222. f"The maximum number of rendezvous nodes ({max_nodes}) must be greater than or "
  223. f"equal to the minimum number of rendezvous nodes ({min_nodes})."
  224. )
  225. self.backend = backend
  226. self.endpoint = endpoint
  227. self.run_id = run_id
  228. self.min_nodes = min_nodes
  229. self.max_nodes = max_nodes
  230. self.config = kwargs
  231. self.local_addr = local_addr
  232. def get(self, key: str, default: Any = None) -> Any:
  233. """Return the value for ``key`` if ``key`` exists, else ``default``."""
  234. return self.config.get(key, default)
  235. def get_as_bool(self, key: str, default: Optional[bool] = None) -> Optional[bool]:
  236. """Return the value for ``key`` as a ``bool``."""
  237. value = self.get(key, default)
  238. if value is None or isinstance(value, bool):
  239. return value
  240. if isinstance(value, int):
  241. if value == 1:
  242. return True
  243. if value == 0:
  244. return False
  245. elif isinstance(value, str):
  246. if value.lower() in ["1", "true", "t", "yes", "y"]:
  247. return True
  248. if value.lower() in ["0", "false", "f", "no", "n"]:
  249. return False
  250. raise ValueError(
  251. f"The rendezvous configuration option '{key}' does not represent a valid boolean value."
  252. )
  253. def get_as_int(self, key: str, default: Optional[int] = None) -> Optional[int]:
  254. """Return the value for ``key`` as an ``int``."""
  255. value = self.get(key, default)
  256. if value is None:
  257. return value
  258. try:
  259. return int(value)
  260. except ValueError as e:
  261. raise ValueError(
  262. f"The rendezvous configuration option '{key}' does not represent a valid integer "
  263. "value."
  264. ) from e
  265. RendezvousHandlerCreator = Callable[[RendezvousParameters], RendezvousHandler]
  266. class RendezvousHandlerRegistry:
  267. """Represent a registry of :py:class:`RendezvousHandler` backends."""
  268. _registry: dict[str, RendezvousHandlerCreator]
  269. def __init__(self) -> None:
  270. self._registry = {}
  271. def register(self, backend: str, creator: RendezvousHandlerCreator) -> None:
  272. """Register a new rendezvous backend.
  273. Args:
  274. backend:
  275. The name of the backend.
  276. creator:
  277. The callback to invoke to construct the
  278. :py:class:`RendezvousHandler`.
  279. """
  280. if not backend:
  281. raise ValueError("The rendezvous backend name must be a non-empty string.")
  282. current_creator: Optional[RendezvousHandlerCreator]
  283. try:
  284. current_creator = self._registry[backend]
  285. except KeyError:
  286. current_creator = None
  287. if current_creator is not None and current_creator != creator:
  288. raise ValueError(
  289. f"The rendezvous backend '{backend}' cannot be registered with '{creator}' as it "
  290. f"is already registered with '{current_creator}'."
  291. )
  292. self._registry[backend] = creator
  293. def create_handler(self, params: RendezvousParameters) -> RendezvousHandler:
  294. """Create a new :py:class:`RendezvousHandler`."""
  295. try:
  296. creator = self._registry[params.backend]
  297. except KeyError as e:
  298. raise ValueError(
  299. f"The rendezvous backend '{params.backend}' is not registered. Did you forget "
  300. f"to call `{self.register.__name__}`?"
  301. ) from e
  302. handler = creator(params)
  303. # Do some sanity check.
  304. if handler.get_backend() != params.backend:
  305. raise RuntimeError(
  306. f"The rendezvous backend '{handler.get_backend()}' does not match the requested "
  307. f"backend '{params.backend}'."
  308. )
  309. return handler
  310. # The default global registry instance used by launcher scripts to instantiate
  311. # rendezvous handlers.
  312. rendezvous_handler_registry = RendezvousHandlerRegistry()