api.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. #!/usr/bin/env python3
  2. # mypy: allow-untyped-defs
  3. # Copyright (c) Facebook, Inc. and its affiliates.
  4. # All rights reserved.
  5. #
  6. # This source code is licensed under the BSD-style license found in the
  7. # LICENSE file in the root directory of this source tree.
  8. import sys
  9. import uuid
  10. from dataclasses import dataclass, field
  11. from typing import Any, Callable, Dict, List, Optional, Tuple, Union
  12. import torch.distributed.elastic.rendezvous.registry as rdzv_registry
  13. from torch.distributed.elastic import events, metrics
  14. from torch.distributed.elastic.agent.server.api import WorkerSpec
  15. from torch.distributed.elastic.agent.server.local_elastic_agent import LocalElasticAgent
  16. from torch.distributed.elastic.multiprocessing import DefaultLogsSpecs, LogsSpecs, SignalException
  17. from torch.distributed.elastic.multiprocessing.errors import ChildFailedError
  18. from torch.distributed.elastic.rendezvous import RendezvousParameters
  19. from torch.distributed.elastic.rendezvous.utils import parse_rendezvous_endpoint
  20. from torch.distributed.elastic.utils.logging import get_logger
  21. __all__ = ['LaunchConfig', 'elastic_launch', 'launch_agent']
  22. logger = get_logger(__name__)
  23. @dataclass
  24. class LaunchConfig:
  25. """
  26. Creates a rendezvous config.
  27. Args:
  28. min_nodes: Minimum amount of nodes that the user function will
  29. be launched on. Elastic agent ensures that the user
  30. function start only when the min_nodes amount enters
  31. the rendezvous.
  32. max_nodes: Maximum amount of nodes that the user function
  33. will be launched on.
  34. nproc_per_node: On each node the elastic agent will launch
  35. this amount of workers that will execute user
  36. defined function.
  37. rdzv_backend: rdzv_backend to use in the rendezvous (zeus-adapter, etcd).
  38. rdzv_endpoint: The endpoint of the rdzv sync. storage.
  39. rdzv_configs: Key, value pair that specifies rendezvous specific configuration.
  40. rdzv_timeout: Legacy argument that specifies timeout for the rendezvous. It is going
  41. to be removed in future versions, see the note below. The default timeout is 900 seconds.
  42. run_id: The unique run id of the job (if not passed a unique one will be
  43. deduced from run environment - flow workflow id in flow - or auto generated).
  44. role: User defined role of the worker (defaults to "trainer").
  45. max_restarts: The maximum amount of restarts that elastic agent will conduct
  46. on workers before failure.
  47. monitor_interval: The interval in seconds that is used by the elastic_agent
  48. as a period of monitoring workers.
  49. start_method: The method is used by the elastic agent to start the
  50. workers (spawn, fork, forkserver).
  51. metrics_cfg: configuration to initialize metrics.
  52. local_addr: address of the local node if any. If not set, a lookup on the local
  53. machine's FQDN will be performed.
  54. local_ranks_filter: ranks for which to show logs in console. If not set, show from all.
  55. ..note:
  56. `rdzv_timeout` is a legacy argument that will be removed in future.
  57. Set the timeout via `rdzv_configs['timeout']`
  58. """
  59. min_nodes: int
  60. max_nodes: int
  61. nproc_per_node: int
  62. logs_specs: Optional[LogsSpecs] = None
  63. run_id: str = ""
  64. role: str = "default_role"
  65. rdzv_endpoint: str = ""
  66. rdzv_backend: str = "etcd"
  67. rdzv_configs: Dict[str, Any] = field(default_factory=dict)
  68. rdzv_timeout: int = -1
  69. max_restarts: int = 3
  70. monitor_interval: float = 0.1
  71. start_method: str = "spawn"
  72. log_line_prefix_template: Optional[str] = None
  73. metrics_cfg: Dict[str, str] = field(default_factory=dict)
  74. local_addr: Optional[str] = None
  75. def __post_init__(self):
  76. default_timeout = 900
  77. if self.rdzv_timeout != -1:
  78. self.rdzv_configs["timeout"] = self.rdzv_timeout
  79. elif "timeout" not in self.rdzv_configs:
  80. self.rdzv_configs["timeout"] = default_timeout
  81. # Post-processing to enable refactoring to introduce logs_specs due to non-torchrun API usage
  82. if self.logs_specs is None:
  83. self.logs_specs = DefaultLogsSpecs()
  84. class elastic_launch:
  85. """
  86. Launches an torchelastic agent on the container that invoked the entrypoint.
  87. 1. Pass the ``entrypoint`` arguments as non ``kwargs`` (e.g. no named parameters)/
  88. ``entrypoint`` can be a function or a command.
  89. 2. The return value is a map of each worker's output mapped
  90. by their respective global rank.
  91. Usage
  92. ::
  93. def worker_fn(foo):
  94. # ...
  95. def main():
  96. # entrypoint is a function.
  97. outputs = elastic_launch(LaunchConfig, worker_fn)(foo)
  98. # return rank 0's output
  99. return outputs[0]
  100. # entrypoint is a command and ``script.py`` is the python module.
  101. outputs = elastic_launch(LaunchConfig, "script.py")(args)
  102. outputs = elastic_launch(LaunchConfig, "python")("script.py")
  103. """
  104. def __init__(
  105. self,
  106. config: LaunchConfig,
  107. entrypoint: Union[Callable, str, None],
  108. ):
  109. self._config = config
  110. self._entrypoint = entrypoint
  111. def __call__(self, *args):
  112. return launch_agent(self._config, self._entrypoint, list(args))
  113. def _get_entrypoint_name(
  114. entrypoint: Union[Callable, str, None], args: List[Any]
  115. ) -> str:
  116. """Retrieve entrypoint name with the rule:
  117. 1. If entrypoint is a function, use ``entrypoint.__qualname__``.
  118. 2. If entrypoint is a string, check its value:
  119. 2.1 if entrypoint equals to ``sys.executable`` (like "python"), use the first element from ``args``
  120. which does not start with hifen letter (for example, "-u" will be skipped).
  121. 2.2 otherwise, use ``entrypoint`` value.
  122. 3. Otherwise, return empty string.
  123. """
  124. if isinstance(entrypoint, Callable): # type: ignore[arg-type]
  125. return entrypoint.__name__ # type: ignore[union-attr]
  126. elif isinstance(entrypoint, str):
  127. if entrypoint == sys.executable:
  128. return next((arg for arg in args if arg[0] != "-"), "")
  129. else:
  130. return entrypoint
  131. else:
  132. return ""
  133. def _get_addr_and_port(
  134. rdzv_parameters: RendezvousParameters,
  135. ) -> Tuple[Optional[str], Optional[int]]:
  136. if rdzv_parameters.backend != "static":
  137. return (None, None)
  138. endpoint = rdzv_parameters.endpoint
  139. endpoint = endpoint.strip()
  140. if not endpoint:
  141. raise ValueError(
  142. "Endpoint is missing in endpoint. Try to add --master-addr and --master-port"
  143. )
  144. master_addr, master_port = parse_rendezvous_endpoint(endpoint, default_port=-1)
  145. if master_port == -1:
  146. raise ValueError(
  147. f"port is missing in endpoint: {endpoint}. Try to specify --master-port"
  148. )
  149. return (master_addr, master_port)
  150. def launch_agent(
  151. config: LaunchConfig,
  152. entrypoint: Union[Callable, str, None],
  153. args: List[Any],
  154. ) -> Dict[int, Any]:
  155. if not config.run_id:
  156. run_id = str(uuid.uuid4().int)
  157. logger.warning("config has no run_id, generated a random run_id: %s", run_id)
  158. config.run_id = run_id
  159. entrypoint_name = _get_entrypoint_name(entrypoint, args)
  160. logger.info(
  161. "Starting elastic_operator with launch configs:\n"
  162. " entrypoint : %(entrypoint)s\n"
  163. " min_nodes : %(min_nodes)s\n"
  164. " max_nodes : %(max_nodes)s\n"
  165. " nproc_per_node : %(nproc_per_node)s\n"
  166. " run_id : %(run_id)s\n"
  167. " rdzv_backend : %(rdzv_backend)s\n"
  168. " rdzv_endpoint : %(rdzv_endpoint)s\n"
  169. " rdzv_configs : %(rdzv_configs)s\n"
  170. " max_restarts : %(max_restarts)s\n"
  171. " monitor_interval : %(monitor_interval)s\n"
  172. " log_dir : %(log_dir)s\n"
  173. " metrics_cfg : %(metrics_cfg)s\n",
  174. {
  175. "entrypoint": entrypoint_name,
  176. "min_nodes": config.min_nodes,
  177. "max_nodes": config.max_nodes,
  178. "nproc_per_node": config.nproc_per_node,
  179. "run_id": config.run_id,
  180. "rdzv_backend": config.rdzv_backend,
  181. "rdzv_endpoint": config.rdzv_endpoint,
  182. "rdzv_configs": config.rdzv_configs,
  183. "max_restarts": config.max_restarts,
  184. "monitor_interval": config.monitor_interval,
  185. "log_dir": config.logs_specs.root_log_dir, # type: ignore[union-attr]
  186. "metrics_cfg": config.metrics_cfg
  187. }
  188. )
  189. rdzv_parameters = RendezvousParameters(
  190. backend=config.rdzv_backend,
  191. endpoint=config.rdzv_endpoint,
  192. run_id=config.run_id,
  193. min_nodes=config.min_nodes,
  194. max_nodes=config.max_nodes,
  195. local_addr=config.local_addr,
  196. **config.rdzv_configs,
  197. )
  198. master_addr, master_port = _get_addr_and_port(rdzv_parameters)
  199. spec = WorkerSpec(
  200. role=config.role,
  201. local_world_size=config.nproc_per_node,
  202. entrypoint=entrypoint,
  203. args=tuple(args),
  204. rdzv_handler=rdzv_registry.get_rendezvous_handler(rdzv_parameters),
  205. max_restarts=config.max_restarts,
  206. monitor_interval=config.monitor_interval,
  207. master_addr=master_addr,
  208. master_port=master_port,
  209. local_addr=config.local_addr,
  210. )
  211. agent = LocalElasticAgent(
  212. spec=spec,
  213. logs_specs=config.logs_specs, # type: ignore[arg-type]
  214. start_method=config.start_method,
  215. log_line_prefix_template=config.log_line_prefix_template,
  216. )
  217. shutdown_rdzv = True
  218. try:
  219. metrics.initialize_metrics(metrics.MetricsConfig(config.metrics_cfg))
  220. result = agent.run()
  221. # records that agent.run() has succeeded NOT that workers have succeeded
  222. events.record(agent.get_event_succeeded())
  223. if result.is_failed():
  224. # ChildFailedError is treated specially by @record
  225. # if the error files for the failed children exist
  226. # @record will copy the first error (root cause)
  227. # to the error file of the launcher process.
  228. raise ChildFailedError(
  229. name=entrypoint_name,
  230. failures=result.failures,
  231. )
  232. return result.return_values
  233. except ChildFailedError:
  234. raise
  235. except SignalException:
  236. # when the agent dies with a signal do NOT shutdown the rdzv_handler
  237. # since this closes the rendezvous on this rdzv_id permanently and
  238. # prevents any additional scaling events
  239. shutdown_rdzv = False
  240. events.record(agent.get_event_failed())
  241. raise
  242. except Exception:
  243. events.record(agent.get_event_failed())
  244. raise
  245. finally:
  246. if shutdown_rdzv:
  247. spec.rdzv_handler.shutdown()