api.py 12 KB

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