ADAPT-Chase commited on
Commit
bf0e42d
·
verified ·
1 Parent(s): 6125f5d

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/__pycache__/__init__.cpython-312.pyc +0 -0
  3. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/__pycache__/control_plane.cpython-312.pyc +0 -0
  4. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/agent/__pycache__/__init__.cpython-312.pyc +0 -0
  5. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/agent/server/__init__.py +41 -0
  6. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/agent/server/__pycache__/__init__.cpython-312.pyc +0 -0
  7. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/agent/server/__pycache__/api.cpython-312.pyc +0 -0
  8. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/agent/server/__pycache__/health_check_server.cpython-312.pyc +0 -0
  9. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/agent/server/__pycache__/local_elastic_agent.cpython-312.pyc +0 -0
  10. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/agent/server/api.py +957 -0
  11. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/agent/server/health_check_server.py +65 -0
  12. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/agent/server/local_elastic_agent.py +417 -0
  13. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/events/__pycache__/__init__.cpython-312.pyc +0 -0
  14. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/events/__pycache__/api.cpython-312.pyc +0 -0
  15. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/events/__pycache__/handlers.cpython-312.pyc +0 -0
  16. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/metrics/__pycache__/__init__.cpython-312.pyc +0 -0
  17. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/metrics/__pycache__/api.cpython-312.pyc +0 -0
  18. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/__pycache__/__init__.cpython-312.pyc +0 -0
  19. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/__pycache__/api.cpython-312.pyc +0 -0
  20. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/__pycache__/redirects.cpython-312.pyc +0 -0
  21. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/__pycache__/tail_log.cpython-312.pyc +0 -0
  22. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/errors/__init__.py +383 -0
  23. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/errors/__pycache__/__init__.cpython-312.pyc +0 -0
  24. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/errors/__pycache__/error_handler.cpython-312.pyc +0 -0
  25. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/errors/__pycache__/handlers.cpython-312.pyc +0 -0
  26. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/errors/error_handler.py +166 -0
  27. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/errors/handlers.py +18 -0
  28. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/__init__.py +16 -0
  29. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/__pycache__/__init__.cpython-312.pyc +0 -0
  30. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/__pycache__/handlers.cpython-312.pyc +0 -0
  31. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/__pycache__/subprocess_handler.cpython-312.pyc +0 -0
  32. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/handlers.py +30 -0
  33. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/subprocess_handler.py +78 -0
  34. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/__pycache__/__init__.cpython-312.pyc +0 -0
  35. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/__pycache__/_etcd_stub.cpython-312.pyc +0 -0
  36. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/__pycache__/api.cpython-312.pyc +0 -0
  37. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/__pycache__/c10d_rendezvous_backend.cpython-312.pyc +0 -0
  38. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/__pycache__/dynamic_rendezvous.cpython-312.pyc +0 -0
  39. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/__pycache__/etcd_rendezvous.cpython-312.pyc +0 -0
  40. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/__pycache__/etcd_rendezvous_backend.cpython-312.pyc +0 -0
  41. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/__pycache__/etcd_server.cpython-312.pyc +0 -0
  42. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/__pycache__/etcd_store.cpython-312.pyc +0 -0
  43. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/__pycache__/registry.cpython-312.pyc +0 -0
  44. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/__pycache__/static_tcp_rendezvous.cpython-312.pyc +0 -0
  45. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/__pycache__/utils.cpython-312.pyc +0 -0
  46. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/etcd_rendezvous.py +1081 -0
  47. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/etcd_rendezvous_backend.py +215 -0
  48. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/etcd_server.py +248 -0
  49. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/etcd_store.py +216 -0
  50. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/registry.py +100 -0
.gitattributes CHANGED
@@ -4481,3 +4481,4 @@ tool_server/.venv/lib/python3.12/site-packages/torch/_refs/__pycache__/__init__.
4481
  tool_server/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/fake_tensor.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
4482
  tool_server/.venv/lib/python3.12/site-packages/torch/backends/_nnapi/__pycache__/serializer.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
4483
  tool_server/.venv/lib/python3.12/site-packages/torch/distributed/__pycache__/distributed_c10d.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
 
 
4481
  tool_server/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/fake_tensor.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
4482
  tool_server/.venv/lib/python3.12/site-packages/torch/backends/_nnapi/__pycache__/serializer.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
4483
  tool_server/.venv/lib/python3.12/site-packages/torch/distributed/__pycache__/distributed_c10d.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
4484
+ tool_server/.venv/lib/python3.12/site-packages/torch/distributed/fsdp/__pycache__/_flat_param.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (3.63 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/__pycache__/control_plane.cpython-312.pyc ADDED
Binary file (1.88 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/agent/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (201 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/agent/server/__init__.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
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
+
9
+ """
10
+ The elastic agent is the control plane of torchelastic.
11
+
12
+ It is a process that launches and manages underlying worker processes.
13
+ The agent is responsible for:
14
+
15
+ 1. Working with distributed torch: the workers are started with all the
16
+ necessary information to successfully and trivially call
17
+ ``torch.distributed.init_process_group()``.
18
+
19
+ 2. Fault tolerance: monitors workers and upon detecting worker failures
20
+ or unhealthiness, tears down all workers and restarts everyone.
21
+
22
+ 3. Elasticity: Reacts to membership changes and restarts workers with the new
23
+ members.
24
+
25
+ The simplest agents are deployed per node and works with local processes.
26
+ A more advanced agent can launch and manage workers remotely. Agents can
27
+ be completely decentralized, making decisions based on the workers it manages.
28
+ Or can be coordinated, communicating to other agents (that manage workers
29
+ in the same job) to make a collective decision.
30
+ """
31
+
32
+ from .api import ( # noqa: F401
33
+ ElasticAgent,
34
+ RunResult,
35
+ SimpleElasticAgent,
36
+ Worker,
37
+ WorkerGroup,
38
+ WorkerSpec,
39
+ WorkerState,
40
+ )
41
+ from .local_elastic_agent import TORCHELASTIC_ENABLE_FILE_TIMER, TORCHELASTIC_TIMER_FILE
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/agent/server/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (1.45 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/agent/server/__pycache__/api.cpython-312.pyc ADDED
Binary file (43.1 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/agent/server/__pycache__/health_check_server.cpython-312.pyc ADDED
Binary file (2.35 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/agent/server/__pycache__/local_elastic_agent.cpython-312.pyc ADDED
Binary file (18.3 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/agent/server/api.py ADDED
@@ -0,0 +1,957 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
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
+
9
+ import abc
10
+ import json
11
+ import os
12
+ import signal
13
+ import socket
14
+ import time
15
+ import traceback
16
+ import warnings
17
+ from collections import defaultdict
18
+ from contextlib import contextmanager
19
+ from dataclasses import dataclass, field
20
+ from enum import Enum
21
+ from typing import Any, Callable, Optional, Union
22
+
23
+ import torch.distributed.elastic.rendezvous as rdzv
24
+ import torch.distributed.elastic.utils.store as store_util
25
+ from torch.distributed.elastic.events import Event, EventSource, record
26
+ from torch.distributed.elastic.metrics import prof, put_metric
27
+ from torch.distributed.elastic.multiprocessing import ProcessFailure, SignalException
28
+ from torch.distributed.elastic.rendezvous import RendezvousGracefulExitError
29
+ from torch.distributed.elastic.utils.logging import get_logger
30
+
31
+
32
+ __all__ = [
33
+ "WorkerSpec",
34
+ "Worker",
35
+ "WorkerState",
36
+ "WorkerGroup",
37
+ "RunResult",
38
+ "ElasticAgent",
39
+ "SimpleElasticAgent",
40
+ ]
41
+ _TERMINAL_STATE_SYNC_ID = "torchelastic/agent/terminal_state"
42
+
43
+ DEFAULT_ROLE = "default"
44
+ logger = get_logger(__name__)
45
+
46
+
47
+ @dataclass
48
+ class WorkerSpec:
49
+ """Blueprint information about a particular type of worker.
50
+
51
+ For a given role, there must only exist a single worker spec.
52
+ Worker spec is expected to be homogeneous across all nodes (machine),
53
+ that is each node runs the same number of workers for a particular spec.
54
+
55
+ Args:
56
+ role: user-defined role for the workers with this spec
57
+ local_world_size: number local workers to run
58
+ fn: (deprecated use entrypoint instead)
59
+ entrypoint: worker function or command
60
+ args: arguments to pass to ``entrypoint``
61
+ rdzv_handler: handles rdzv for this set of workers
62
+ max_restarts: number of max retries for the workers
63
+ monitor_interval: monitor status of workers every ``n`` seconds
64
+ master_port: fixed port to run the c10d store on rank 0
65
+ if not specified then will chose a random free port
66
+ master_addr: fixed master_addr to run the c10d store on rank 0
67
+ if not specified then will chose hostname on agent rank 0
68
+ redirects: redirect std streams to a file,
69
+ selectively redirect for a particular
70
+ local rank by passing a map
71
+ tee: tees the specified std stream(s) to console + file,
72
+ selectively tee for a particular local rank by passing a map,
73
+ takes precedence over ``redirects`` settings.
74
+
75
+ """
76
+
77
+ role: str
78
+ local_world_size: int
79
+ rdzv_handler: rdzv.RendezvousHandler
80
+ fn: Optional[Callable] = None
81
+ # TODO @kiuk - make entrypoint a required field
82
+ entrypoint: Union[Callable, str, None] = None
83
+ args: tuple = ()
84
+ max_restarts: int = 3
85
+ monitor_interval: float = 0.1
86
+ master_port: Optional[int] = None
87
+ master_addr: Optional[str] = None
88
+ local_addr: Optional[str] = None
89
+
90
+ def __post_init__(self):
91
+ assert self.local_world_size > 0
92
+ assert self.monitor_interval > 0
93
+
94
+ if self.fn:
95
+ warnings.warn(
96
+ "WorkerSpec.fn will be deprecated,"
97
+ " please use WorkerSpec.entrypoint instead",
98
+ category=DeprecationWarning,
99
+ )
100
+ self.entrypoint = self.fn
101
+ assert self.entrypoint
102
+
103
+ def get_entrypoint_name(self):
104
+ """Get the entry point name.
105
+
106
+ If the entrypoint is a function (e.g. ``Callable``) returns its ``__qualname__``
107
+ else if the entrypoint is a binary (e.g. ``str``), returns the binary name.
108
+ """
109
+ if isinstance(self.entrypoint, str):
110
+ return os.path.basename(self.entrypoint)
111
+ else:
112
+ assert self.entrypoint is not None
113
+ return self.entrypoint.__qualname__
114
+
115
+
116
+ class Worker:
117
+ """A worker instance.
118
+
119
+ Contrast this with ``WorkerSpec`` that represents the specifications of a
120
+ worker. A ``Worker`` is created from a ``WorkerSpec``. A ``Worker`` is to
121
+ a ``WorkerSpec`` as an object is to a class.
122
+
123
+ The ``id`` of the worker is interpreted
124
+ by the specific implementation of ``ElasticAgent``. For a local
125
+ agent, it could be the ``pid (int)`` of the worker, for a remote
126
+ agent it could be encoded as ``host:port (string)``.
127
+
128
+ Args:
129
+ id (Any): uniquely identifies a worker (interpreted by the agent)
130
+ local_rank (int): local rank of the worker
131
+ global_rank (int): global rank of the worker
132
+ role_rank (int): rank of the worker across all workers that have the same role
133
+ world_size (int): number of workers (globally)
134
+ role_world_size (int): number of workers that have the same role
135
+ """
136
+
137
+ __slots__ = [
138
+ "id",
139
+ "local_rank",
140
+ "global_rank",
141
+ "role_rank",
142
+ "world_size",
143
+ "role_world_size",
144
+ ]
145
+
146
+ def __init__(
147
+ self,
148
+ local_rank: int,
149
+ global_rank: int = -1,
150
+ role_rank: int = -1,
151
+ world_size: int = -1,
152
+ role_world_size: int = -1,
153
+ ):
154
+ # unique identifier for this worker
155
+ self.id: Any = None
156
+
157
+ # rank of the worker among workers with the same role being monitored
158
+ # by the same ``agent`` instance.
159
+ self.local_rank: int = local_rank
160
+
161
+ # rank of the worker among all the workers across all roles
162
+ # across all ``agent`` instances.
163
+ # Global rank is not stable between re-rendezvous.
164
+ self.global_rank: int = global_rank
165
+
166
+ # rank of the worker among all the workers with the same role
167
+ # across all ``agent`` instances.
168
+ # Role rank is not stable between re-rendezvous.
169
+ self.role_rank: int = role_rank
170
+
171
+ # total number of workers (globally). Due to elasticity
172
+ # the world size may change between re-rendezvous.
173
+ self.world_size: int = world_size
174
+
175
+ # total number of workers that share the same role. Due to elasticity
176
+ # the role world size may change between re-rendezvous.
177
+ self.role_world_size: int = role_world_size
178
+
179
+ def __str__(self):
180
+ return (
181
+ f"local_rank={self.local_rank},global_rank={self.global_rank}"
182
+ f",role_rank={self.role_rank},world_size={self.world_size}"
183
+ f",role_world_size={self.role_world_size}"
184
+ )
185
+
186
+ def __repr__(self):
187
+ return str(self)
188
+
189
+
190
+ class WorkerState(str, Enum):
191
+ """A state of the ``WorkerGroup``.
192
+
193
+ Workers in a worker group change state as a unit. If a single worker
194
+ in a worker group fails the entire set is considered failed::
195
+
196
+ UNKNOWN - agent lost track of worker group state, unrecoverable
197
+ INIT - worker group object created not yet started
198
+ HEALTHY - workers running and healthy
199
+ UNHEALTHY - workers running and unhealthy
200
+ STOPPED - workers stopped (interrupted) by the agent
201
+ SUCCEEDED - workers finished running (exit 0)
202
+ FAILED - workers failed to successfully finish (exit !0)
203
+
204
+
205
+ A worker group starts from an initial ``INIT`` state,
206
+ then progresses to ``HEALTHY`` or ``UNHEALTHY`` states,
207
+ and finally reaches a terminal ``SUCCEEDED`` or ``FAILED`` state.
208
+
209
+ Worker groups can be interrupted and temporarily put into ``STOPPED`` state
210
+ by the agent. Workers in ``STOPPED`` state are scheduled to be restarted
211
+ in the near future by the agent. Some examples of workers being put into
212
+ ``STOPPED`` state are:
213
+
214
+ 1. Worker group failure|unhealthy observed
215
+ 2. Membership change detected
216
+
217
+ When actions (start, stop, rdzv, retry, etc) on worker group fails
218
+ and results in the action being partially applied to the worker group
219
+ the state will be ``UNKNOWN``. Typically this happens on uncaught/unhandled
220
+ exceptions during state change events on the agent. The agent is not
221
+ expected to recover worker groups in ``UNKNOWN`` state and is better off
222
+ self terminating and allowing the job manager to retry the node.
223
+ """
224
+
225
+ UNKNOWN = "UNKNOWN"
226
+ INIT = "INIT"
227
+ HEALTHY = "HEALTHY"
228
+ UNHEALTHY = "UNHEALTHY"
229
+ STOPPED = "STOPPED"
230
+ SUCCEEDED = "SUCCEEDED"
231
+ FAILED = "FAILED"
232
+
233
+ @staticmethod
234
+ def is_running(state: "WorkerState") -> bool:
235
+ """Return the state of the Worker.
236
+
237
+ Returns:
238
+ True if the worker state represents workers still running
239
+ (e.g. that the process exists but not necessarily healthy).
240
+ """
241
+ return state in {WorkerState.HEALTHY, WorkerState.UNHEALTHY}
242
+
243
+
244
+ class WorkerGroup:
245
+ """A set of ``Worker`` instances.
246
+
247
+ The class defines a set of ``Worker`` instances for the given ``WorkerSpec`` managed by ``ElasticAgent``. Whether the worker
248
+ group contains cross instance workers or not depends on the implementation of the agent.
249
+ """
250
+
251
+ __slots__ = [
252
+ "spec",
253
+ "workers",
254
+ "store",
255
+ "group_rank",
256
+ "group_world_size",
257
+ "state",
258
+ "master_addr",
259
+ "master_port",
260
+ ]
261
+
262
+ def __init__(self, spec: WorkerSpec):
263
+ self.spec = spec
264
+ self.workers = [Worker(local_rank=i) for i in range(self.spec.local_world_size)]
265
+
266
+ # assigned after rdzv
267
+ self.store = None
268
+ self.group_rank = None
269
+ self.group_world_size = None
270
+ self.master_addr = None
271
+ self.master_port = None
272
+
273
+ self.state = WorkerState.INIT
274
+
275
+
276
+ class _RoleInstanceInfo:
277
+ """The class is used by the agent to exchange the information with other agents.
278
+
279
+ The information is used to determine the rank of the workers that agent
280
+ manages in heterogeneous environments, where different agents can have
281
+ different number of workers.
282
+ """
283
+
284
+ __slots__ = ["role", "rank", "local_world_size"]
285
+
286
+ def __init__(self, role: str, rank: int, local_world_size: int):
287
+ r"""Initialize the agent class instance.
288
+
289
+ Args:
290
+ role (str): user-defined role for the workers with this spec
291
+ rank (int): the rank of the agent
292
+ local_world_size (int): number of local workers to run
293
+ """
294
+ self.role = role
295
+ self.rank = rank
296
+ self.local_world_size = local_world_size
297
+
298
+ def serialize(self) -> bytes:
299
+ dict_data = {
300
+ "role": self.role,
301
+ "rank": self.rank,
302
+ "local_world_size": self.local_world_size,
303
+ }
304
+ return json.dumps(dict_data).encode(encoding="UTF-8")
305
+
306
+ @staticmethod
307
+ def deserialize(data: bytes):
308
+ dict_data = json.loads(data.decode(encoding="UTF-8"))
309
+ return _RoleInstanceInfo(
310
+ dict_data["role"], dict_data["rank"], dict_data["local_world_size"]
311
+ )
312
+
313
+ @staticmethod
314
+ def compare(obj1, obj2) -> int:
315
+ if obj1.role == obj2.role:
316
+ return obj1.rank - obj2.rank
317
+ elif obj1.role > obj2.role:
318
+ return 1
319
+ else:
320
+ return -1
321
+
322
+ @staticmethod
323
+ def find_role_boundaries(roles_infos: list, role: str) -> tuple[int, int]:
324
+ start_idx, end_idx = -1, -1
325
+ for idx, role_info in enumerate(roles_infos):
326
+ if role_info.role == role:
327
+ if start_idx == -1:
328
+ start_idx = idx
329
+ end_idx = idx
330
+ return (start_idx, end_idx)
331
+
332
+
333
+ @dataclass
334
+ class RunResult:
335
+ """Return results of the worker executions.
336
+
337
+ Run results follow an "all-or-nothing" policy where the run is successful if and
338
+ only if ALL local workers managed by this agent complete successfully.
339
+
340
+ If the result is successful (e.g. ``is_failed() = False``) then the ``return_values``
341
+ field contains the outputs (return values) of the workers managed by THIS agent mapped
342
+ by their GLOBAL ranks. That is ``result.return_values[0]`` is the return value of
343
+ global rank 0.
344
+
345
+ .. note:: ``return_values`` are only meaningful for when the worker entrypoint
346
+ is a function. Workers specified as a binary entrypoint do not canonically
347
+ have a return value and the ``return_values`` field is meaningless and
348
+ may be empty.
349
+
350
+ If ``is_failed()`` returns ``True`` then the ``failures`` field contains the
351
+ failure information, again, mapped by the GLOBAL rank of the worker that failed.
352
+
353
+ The keys in ``return_values`` and ``failures`` are mutually exclusive, that is,
354
+ a worker's final state can only be one of: succeeded, failed. Workers intentionally
355
+ terminated by the agent according to the agent's restart policy, are not represented
356
+ in either ``return_values`` nor ``failures``.
357
+ """
358
+
359
+ state: WorkerState
360
+ return_values: dict[int, Any] = field(default_factory=dict)
361
+ failures: dict[int, ProcessFailure] = field(default_factory=dict)
362
+
363
+ def is_failed(self) -> bool:
364
+ return self.state == WorkerState.FAILED
365
+
366
+
367
+ def _get_fq_hostname() -> str:
368
+ return socket.getfqdn(socket.gethostname())
369
+
370
+
371
+ class ElasticAgent(abc.ABC):
372
+ """An agent process responsible for managing one or more worker processes.
373
+
374
+ The worker processes are assumed to be regular distributed PyTorch scripts.
375
+ When the worker process is created by the agent, the agent provides the
376
+ necessary information for the worker processes to properly initialize
377
+ a torch process group.
378
+
379
+ The exact deployment topology and ratio of agent-to-worker is dependent
380
+ on the specific implementation of the agent and the user's job placement
381
+ preferences. For instance, to run a distributed training job on GPU with
382
+ 8 trainers (one per GPU) one can:
383
+
384
+ 1. Use 8 x single GPU instances, place an agent per instance, managing
385
+ 1 worker per agent.
386
+ 2. Use 4 x double GPU instances, place an agent per instance, managing
387
+ 2 workers per agent.
388
+ 3. Use 2 x quad GPU instances, place an agent per instance, managing
389
+ 4 workers per agent.
390
+ 4. Use 1 x 8 GPU instance, place an agent per instance, managing
391
+ 8 workers per agent.
392
+
393
+ Usage
394
+ ::
395
+
396
+ group_result = agent.run()
397
+ if group_result.is_failed():
398
+ # workers failed
399
+ failure = group_result.failures[0]
400
+ logger.exception("worker 0 failed with exit code : %s", failure.exit_code)
401
+ else:
402
+ return group_result.return_values[0] # return rank 0's results
403
+
404
+ """
405
+
406
+ @abc.abstractmethod
407
+ def run(self, role: str = DEFAULT_ROLE) -> RunResult:
408
+ """Run the agent.
409
+
410
+ Supports retrying the worker group on failures up to ``max_restarts``.
411
+
412
+ Returns:
413
+ The result of the execution, containing the return values or
414
+ failure details for each worker mapped by the worker's global rank.
415
+
416
+ Raises:
417
+ Exception - any other failures NOT related to worker process
418
+ """
419
+ raise NotImplementedError
420
+
421
+ @abc.abstractmethod
422
+ def get_worker_group(self, role: str = DEFAULT_ROLE) -> WorkerGroup:
423
+ """Return the ``WorkerGroup`` for the given ``role``.
424
+
425
+ Note that the worker group is a mutable object and hence in a
426
+ multi-threaded/process environment it may change state.
427
+ Implementors are encouraged (but not required) to return
428
+ a defensive read-only copy.
429
+ """
430
+ raise NotImplementedError
431
+
432
+
433
+ class SimpleElasticAgent(ElasticAgent):
434
+ """An ``ElasticAgent`` that manages one particular type of worker role.
435
+
436
+ An ``ElasticAgent`` that manages workers (``WorkerGroup``) for a single ``WorkerSpec``
437
+ such as one particular type of worker role.
438
+ """
439
+
440
+ def __init__(self, spec: WorkerSpec, exit_barrier_timeout: float = 300):
441
+ self._worker_group = WorkerGroup(spec)
442
+ self._remaining_restarts = self._worker_group.spec.max_restarts
443
+ self._store = None
444
+ self._exit_barrier_timeout = exit_barrier_timeout
445
+ self._total_execution_time = 0
446
+
447
+ def get_worker_group(self, role: str = DEFAULT_ROLE) -> WorkerGroup:
448
+ return self._worker_group
449
+
450
+ @abc.abstractmethod
451
+ def _start_workers(self, worker_group: WorkerGroup) -> dict[int, Any]:
452
+ r"""Start ``worker_group.spec.local_world_size`` number of workers.
453
+
454
+ This is according to worker spec for the worker group .
455
+ Returns a map of ``local_rank`` to worker ``id``.
456
+ """
457
+ raise NotImplementedError
458
+
459
+ @abc.abstractmethod
460
+ def _stop_workers(
461
+ self, worker_group: WorkerGroup, is_restart: bool = False
462
+ ) -> None:
463
+ r"""Stop all workers in the given worker group.
464
+
465
+ Implementors must deal with workers in all states defined by
466
+ ``WorkerState``. That is, it must gracefully handle stopping
467
+ non-existent workers, unhealthy (stuck) workers, etc.
468
+ """
469
+ raise NotImplementedError
470
+
471
+ @abc.abstractmethod
472
+ def _monitor_workers(self, worker_group: WorkerGroup) -> RunResult:
473
+ r"""Check on the workers for the ``worker_group``.
474
+
475
+ This function also returns the new state of the worker group.
476
+ """
477
+ raise NotImplementedError
478
+
479
+ @abc.abstractmethod
480
+ def _shutdown(
481
+ self, death_sig: signal.Signals = signal.SIGTERM, is_restart: bool = False
482
+ ) -> None:
483
+ """Clean up any resources that were allocated during the agent's work.
484
+
485
+ Args:
486
+ death_sig: Signal to send to the child process, SIGTERM is default
487
+ """
488
+ raise NotImplementedError
489
+
490
+ @prof
491
+ def _rendezvous(self, worker_group: WorkerGroup) -> None:
492
+ r"""Run rendezvous for the workers specified by the worker spec.
493
+
494
+ Assigns workers a new global rank and world size.
495
+ Updates the rendezvous store for the worker group.
496
+ """
497
+ spec = worker_group.spec
498
+
499
+ with self.record_duration("RENDEZVOUS"):
500
+ rdzv_info = spec.rdzv_handler.next_rendezvous()
501
+ store = rdzv_info.store
502
+ group_rank = rdzv_info.rank
503
+ group_world_size = rdzv_info.world_size
504
+
505
+ # master_addr/master_port could be explicitly overriden
506
+ # TODO: BC - specific to static rdzv and can be simplifed further
507
+ master_addr = spec.master_addr or rdzv_info.bootstrap_store_info.master_addr
508
+ master_port = spec.master_port or rdzv_info.bootstrap_store_info.master_port
509
+
510
+ self._store = store
511
+
512
+ with self.record_duration("ASSIGN_WORKER_RANKS"):
513
+ workers = self._assign_worker_ranks(
514
+ store, group_rank, group_world_size, spec
515
+ )
516
+ worker_group.workers = workers
517
+ worker_group.store = store
518
+ worker_group.group_rank = group_rank
519
+ worker_group.group_world_size = group_world_size
520
+ worker_group.master_addr = master_addr
521
+ worker_group.master_port = master_port
522
+
523
+ restart_count = spec.max_restarts - self._remaining_restarts
524
+
525
+ logger.info(
526
+ "[%(role)s] Rendezvous complete for workers. Result:\n"
527
+ " restart_count=%(restart_count)s\n"
528
+ " master_addr=%(master_addr)s\n"
529
+ " master_port=%(master_port)s\n"
530
+ " group_rank=%(group_rank)s\n"
531
+ " group_world_size=%(group_world_size)s\n"
532
+ " local_ranks=%(local_ranks)s\n"
533
+ " role_ranks=%(role_ranks)s\n"
534
+ " global_ranks=%(global_ranks)s\n"
535
+ " role_world_sizes=%(role_world_sizes)s\n"
536
+ " global_world_sizes=%(global_world_sizes)s\n",
537
+ {
538
+ "role": spec.role,
539
+ "restart_count": restart_count,
540
+ "master_addr": master_addr,
541
+ "master_port": master_port,
542
+ "group_rank": group_rank,
543
+ "group_world_size": group_world_size,
544
+ "local_ranks": [worker.local_rank for worker in workers],
545
+ "role_ranks": [worker.role_rank for worker in workers],
546
+ "global_ranks": [worker.global_rank for worker in workers],
547
+ "role_world_sizes": [worker.role_world_size for worker in workers],
548
+ "global_world_sizes": [worker.world_size for worker in workers],
549
+ },
550
+ )
551
+
552
+ # pyre-fixme[56]: Pyre was not able to infer the type of the decorator
553
+ # `torch.distributed.elastic.metrics.prof`.
554
+ @prof
555
+ def _assign_worker_ranks(
556
+ self, store, group_rank: int, group_world_size: int, spec: WorkerSpec
557
+ ) -> list[Worker]:
558
+ """Determine proper ranks for worker processes.
559
+
560
+ Fast Path: when all workers have the same role and world size. We calculate
561
+ the global rank to be group_rank * group_world_size + local_rank. And the
562
+ `role_world_size` is the same as `global_world_size`. No TCP store is used in
563
+ this case. This is only enabled when users set the environment variable
564
+ `TORCH_ELASTIC_WORKER_IDENTICAL` to 1.
565
+
566
+ Time complexity: each worker O(1), overall O(1)
567
+
568
+ Slow Path: when workers have different roles and world sizes. We use the
569
+ the following algorithm:
570
+
571
+ 1. Each agent writes its configuration(group_rank, group_world_size
572
+ , num_workers) to the common store.
573
+ 2. The rank 0 agent reads all the role_info from the store and
574
+ determines each agents worker ranks.
575
+ 3. Determine the global rank: the global rank of the workers is computed
576
+ by cumulative sum of the local_world_size for all workers in front of it.
577
+ For efficiency reasons each worker is assigned a base global rank
578
+ such that it's workers are in the range [base_global_rank,
579
+ base_global_rank + local_world_size).
580
+ 4. Determine the role rank: The role rank is determined using the algorithms
581
+ in the point 3 with the exception that the ranks are calculated with
582
+ respect to the role name.
583
+ 5. The rank 0 agent writes the assigned ranks to the store.
584
+ 6. Each agent reads the assigned ranks from the store.
585
+
586
+ Time complexity: each worker O(1), rank0 O(n), overall O(n)
587
+ """
588
+
589
+ if os.environ.get("TORCH_ELASTIC_WORKER_IDENTICAL", "0") == "1":
590
+ global_world_size = group_world_size * spec.local_world_size
591
+ base_global_rank = group_rank * spec.local_world_size
592
+ base_role_rank = base_global_rank
593
+ role_world_size = global_world_size
594
+ else:
595
+ ROLE_INFO_PREFIX = "torchelastic/role_info/"
596
+ ASSIGNED_RANKS_PREFIX = "torchelastic/assigned_ranks/"
597
+
598
+ agent_role_info = _RoleInstanceInfo(
599
+ spec.role, group_rank, spec.local_world_size
600
+ )
601
+ store.set(f"{ROLE_INFO_PREFIX}{group_rank}", agent_role_info.serialize())
602
+
603
+ # tcp store is collocated with rank 0 so we can use it to do extra compute to reduce overall # of operations.
604
+ if group_rank == 0:
605
+ role_infos_bytes = store.multi_get(
606
+ [f"torchelastic/role_info/{i}" for i in range(group_world_size)]
607
+ )
608
+ role_infos = [
609
+ _RoleInstanceInfo.deserialize(info_bytes)
610
+ for info_bytes in role_infos_bytes
611
+ ]
612
+
613
+ role_sizes = defaultdict(lambda: 0)
614
+ global_size = 0
615
+ for role_info in role_infos:
616
+ role_sizes[role_info.role] += role_info.local_world_size
617
+ global_size += role_info.local_world_size
618
+
619
+ base_global_rank = 0
620
+ role_ranks = defaultdict(lambda: 0)
621
+
622
+ keys = []
623
+ values = []
624
+ for i, role_info in enumerate(role_infos):
625
+ keys.append(f"{ASSIGNED_RANKS_PREFIX}{i}")
626
+ values.append(
627
+ json.dumps(
628
+ [
629
+ base_global_rank,
630
+ global_size,
631
+ role_ranks[role_info.role],
632
+ role_sizes[role_info.role],
633
+ ]
634
+ )
635
+ )
636
+
637
+ base_global_rank += role_info.local_world_size
638
+ role_ranks[role_info.role] += role_info.local_world_size
639
+
640
+ store.multi_set(keys, values)
641
+
642
+ # get will block until the data is available in the store.
643
+ (
644
+ base_global_rank,
645
+ global_world_size,
646
+ base_role_rank,
647
+ role_world_size,
648
+ ) = json.loads(store.get(f"{ASSIGNED_RANKS_PREFIX}{group_rank}"))
649
+
650
+ workers = []
651
+ for local_rank in range(spec.local_world_size):
652
+ worker = Worker(
653
+ local_rank=local_rank,
654
+ global_rank=base_global_rank + local_rank,
655
+ role_rank=base_role_rank + local_rank,
656
+ world_size=global_world_size,
657
+ role_world_size=role_world_size,
658
+ )
659
+ workers.append(worker)
660
+ return workers
661
+
662
+ # pyre-fixme[56]: Pyre was not able to infer the type of the decorator
663
+ # `torch.distributed.elastic.metrics.prof`.
664
+ @prof
665
+ def _initialize_workers(self, worker_group: WorkerGroup) -> None:
666
+ r"""Start a fresh set of workers for the worker_group.
667
+
668
+ Essentially, a rendezvous followed by a ``start_workers``.
669
+ The caller should first call ``_stop_workers()`` to stop running workers
670
+ prior to calling this method.
671
+
672
+ Optimistically sets the state of the worker group that
673
+ just started as ``HEALTHY`` and delegates the actual monitoring
674
+ of state to ``_monitor_workers()`` method
675
+ """
676
+ role = worker_group.spec.role
677
+ logger.info("[%s] Rendezvous'ing worker group", role)
678
+
679
+ # TODO after stopping workers, wait at least monitor_interval*2 for
680
+ # workers on different nodes to fail on a collective op before waiting
681
+ # on the rdzv barrier, this way we ensure that nodes enter rdzv
682
+ # at around the same time and reduce false positive rdzv timeout errors
683
+ self._rendezvous(worker_group)
684
+
685
+ logger.info("[%s] Starting worker group", role)
686
+ worker_ids = self._start_workers(worker_group)
687
+ for local_rank, w_id in worker_ids.items():
688
+ worker = worker_group.workers[local_rank]
689
+ worker.id = w_id
690
+
691
+ worker_group.state = WorkerState.HEALTHY
692
+
693
+ # pyre-fixme[56]: Pyre was not able to infer the type of the decorator
694
+ # `torch.distributed.elastic.metrics.prof`.
695
+ @prof
696
+ def _restart_workers(self, worker_group: WorkerGroup) -> None:
697
+ """Restart (stops, rendezvous, starts) all local workers in the group."""
698
+ role = worker_group.spec.role
699
+ logger.info("[%s] Stopping worker group", role)
700
+ self._stop_workers(worker_group, is_restart=True)
701
+ worker_group.state = WorkerState.STOPPED
702
+ self._initialize_workers(worker_group)
703
+
704
+ # pyre-fixme[56]: Pyre was not able to infer the type of the decorator
705
+ # `torch.distributed.elastic.metrics.prof`.
706
+ @prof
707
+ def run(self, role: str = DEFAULT_ROLE) -> RunResult:
708
+ start_time = time.monotonic()
709
+ shutdown_called: bool = False
710
+ try:
711
+ result = self._invoke_run(role)
712
+ self._total_execution_time = int(time.monotonic() - start_time)
713
+ self._record_metrics(result)
714
+ self._record_worker_events(result)
715
+ return result
716
+ except RendezvousGracefulExitError as e:
717
+ logger.info("Rendezvous gracefully exited: %s", e)
718
+ except SignalException as e:
719
+ logger.warning("Received %s death signal, shutting down workers", e.sigval)
720
+ self._shutdown(e.sigval)
721
+ shutdown_called = True
722
+ raise
723
+ finally:
724
+ if not shutdown_called:
725
+ self._shutdown()
726
+ # record the execution time in case there were any exceptions during run.
727
+ self._total_execution_time = int(time.monotonic() - start_time)
728
+
729
+ def get_event_failed(self) -> Event:
730
+ return self._construct_event(
731
+ state="FAILED",
732
+ source=EventSource.AGENT,
733
+ raw_error=traceback.format_exc(),
734
+ )
735
+
736
+ def get_event_succeeded(self) -> Event:
737
+ return self._construct_event(
738
+ state="SUCCEEDED",
739
+ source=EventSource.AGENT,
740
+ )
741
+
742
+ def _record_worker_events(self, result: RunResult) -> None:
743
+ for worker in self._worker_group.workers:
744
+ failure = result.failures.get(worker.global_rank)
745
+ state: str = self._get_worker_state(worker, result)
746
+ raw_error = json.dumps(failure.error_file_data) if failure else None
747
+ record(self._construct_event(state, EventSource.WORKER, worker, raw_error))
748
+
749
+ def _get_worker_state(self, worker: Worker, result: RunResult) -> str:
750
+ failure = result.failures.get(worker.global_rank)
751
+ if result.state in {WorkerState.UNHEALTHY, WorkerState.FAILED} and not failure:
752
+ # The worker got terminated by the torchelastic agent via SIGTERM signal
753
+ return "TERMINATED"
754
+ elif failure or worker.global_rank in result.return_values:
755
+ return result.state.value
756
+ else:
757
+ raise ValueError(f"Unknown worker: {worker.global_rank}")
758
+
759
+ @contextmanager
760
+ def record_duration(self, state: str):
761
+ start_time = time.perf_counter()
762
+ try:
763
+ yield
764
+ finally:
765
+ end_time = time.perf_counter()
766
+ duration_ms = (end_time - start_time) * 1000
767
+ record(
768
+ self._construct_event(
769
+ state=state, source=EventSource.AGENT, duration_ms=duration_ms
770
+ )
771
+ )
772
+
773
+ def _construct_event(
774
+ self,
775
+ state: str,
776
+ source: EventSource,
777
+ worker: Optional[Worker] = None,
778
+ raw_error: Optional[str] = None,
779
+ duration_ms: Optional[float] = None,
780
+ ) -> Event:
781
+ wg = self._worker_group
782
+ spec = wg.spec
783
+ md = {
784
+ "group_world_size": wg.group_world_size,
785
+ "entry_point": spec.get_entrypoint_name(),
786
+ }
787
+ if worker:
788
+ md["local_rank"] = (worker.local_rank,)
789
+ md["role_rank"] = (worker.role_rank,)
790
+ md["role_world_size"] = (worker.role_world_size,)
791
+ global_rank = worker.global_rank
792
+ worker_id = str(worker.id)
793
+ else:
794
+ global_rank = None
795
+ worker_id = None
796
+ md_str = json.dumps(md)
797
+ metadata = {
798
+ "run_id": spec.rdzv_handler.get_run_id(),
799
+ "global_rank": global_rank,
800
+ "group_rank": wg.group_rank,
801
+ "worker_id": worker_id,
802
+ "role": spec.role,
803
+ "hostname": _get_fq_hostname(),
804
+ "state": state,
805
+ "total_run_time": self._total_execution_time,
806
+ "rdzv_backend": spec.rdzv_handler.get_backend(),
807
+ "raw_error": raw_error,
808
+ "metadata": md_str,
809
+ "agent_restarts": spec.max_restarts - self._remaining_restarts,
810
+ "duration_ms": duration_ms,
811
+ }
812
+ return Event(
813
+ f"torchelastic.worker.status.{state}", source=source, metadata=metadata
814
+ )
815
+
816
+ def _record_metrics(self, group_results: RunResult):
817
+ is_failed = group_results.is_failed()
818
+ self._record_flakiness_metric(is_failed)
819
+ spec = self._worker_group.spec
820
+ restarts_happened = self._remaining_restarts != spec.max_restarts
821
+ put_metric(f"workers.{spec.role}.run_total", 1)
822
+ self._record_metric_with_condition(
823
+ "run_success_with_retries", not is_failed and restarts_happened
824
+ )
825
+ self._record_metric_with_condition(
826
+ "run_success_no_retries", not is_failed and not restarts_happened
827
+ )
828
+ self._record_metric_with_condition(
829
+ "run_failed_with_retries", is_failed and restarts_happened
830
+ )
831
+ self._record_metric_with_condition(
832
+ "run_failed_no_retries", is_failed and not restarts_happened
833
+ )
834
+
835
+ def _record_metric_with_condition(self, metric_name, condition):
836
+ spec = self._worker_group.spec
837
+ if condition:
838
+ put_metric(f"workers.{spec.role}.{metric_name}", 1)
839
+ else:
840
+ put_metric(f"workers.{spec.role}.{metric_name}", 0)
841
+
842
+ def _record_flakiness_metric(self, is_failed: bool = False):
843
+ if is_failed:
844
+ flakiness = 100.0
845
+ else:
846
+ spec = self._worker_group.spec
847
+ flakiness = 100.0 - 100.0 * (self._remaining_restarts + 1) / (
848
+ spec.max_restarts + 1
849
+ )
850
+ spec = self._worker_group.spec
851
+
852
+ put_metric(f"workers.{spec.role}.flakiness", int(flakiness))
853
+
854
+ def _invoke_run(self, role: str = DEFAULT_ROLE) -> RunResult:
855
+ # NOTE: currently only works for a single role
856
+
857
+ spec = self._worker_group.spec
858
+ role = spec.role
859
+
860
+ logger.info(
861
+ "[%s] starting workers for entrypoint: %s", role, spec.get_entrypoint_name()
862
+ )
863
+
864
+ self._initialize_workers(self._worker_group)
865
+ monitor_interval = spec.monitor_interval
866
+ rdzv_handler = spec.rdzv_handler
867
+
868
+ while True:
869
+ assert self._worker_group.state != WorkerState.INIT
870
+ time.sleep(monitor_interval)
871
+ run_result = self._monitor_workers(self._worker_group)
872
+ state = run_result.state
873
+ self._worker_group.state = state
874
+
875
+ put_metric(f"workers.{role}.remaining_restarts", self._remaining_restarts)
876
+ put_metric(f"workers.{role}.{state.name.lower()}", 1)
877
+
878
+ if state == WorkerState.SUCCEEDED:
879
+ logger.info(
880
+ "[%s] worker group successfully finished."
881
+ " Waiting %s seconds for other agents to finish.",
882
+ role,
883
+ self._exit_barrier_timeout,
884
+ )
885
+ self._exit_barrier()
886
+ return run_result
887
+ elif state in {WorkerState.UNHEALTHY, WorkerState.FAILED}:
888
+ if self._remaining_restarts > 0:
889
+ logger.info(
890
+ "[%s] Worker group %s. "
891
+ "%s/%s attempts left;"
892
+ " will restart worker group",
893
+ role,
894
+ state.name,
895
+ self._remaining_restarts,
896
+ spec.max_restarts,
897
+ )
898
+ self._remaining_restarts -= 1
899
+ self._restart_workers(self._worker_group)
900
+ else:
901
+ self._stop_workers(self._worker_group)
902
+ self._worker_group.state = WorkerState.FAILED
903
+ return run_result
904
+ elif state == WorkerState.HEALTHY:
905
+ # membership changes do not count as retries
906
+ num_nodes_waiting = rdzv_handler.num_nodes_waiting()
907
+ group_rank = self._worker_group.group_rank
908
+ if num_nodes_waiting > 0:
909
+ logger.info(
910
+ "[%s] Detected %s "
911
+ "new nodes from group_rank=%s; "
912
+ "will restart worker group",
913
+ role,
914
+ num_nodes_waiting,
915
+ group_rank,
916
+ )
917
+ self._restart_workers(self._worker_group)
918
+ else:
919
+ raise Exception( # noqa: TRY002
920
+ f"[{role}] Worker group in {state.name} state"
921
+ )
922
+
923
+ def _exit_barrier(self):
924
+ """
925
+ Define a barrier that keeps the agent process alive until all workers finish.
926
+
927
+ Wait for ``exit_barrier_timeout`` seconds for all agents to finish
928
+ executing their local workers (either successfully or not). This
929
+ acts as a safety guard against user scripts that terminate at different
930
+ times.
931
+ """
932
+ logger.info(
933
+ "Local worker group finished (%s). "
934
+ "Waiting %s seconds for other agents to finish",
935
+ self._worker_group.state,
936
+ self._exit_barrier_timeout,
937
+ )
938
+ start = time.time()
939
+ try:
940
+ store_util.barrier(
941
+ store=self._store,
942
+ world_size=self._worker_group.group_world_size,
943
+ key_prefix=_TERMINAL_STATE_SYNC_ID,
944
+ barrier_timeout=self._exit_barrier_timeout,
945
+ )
946
+ logger.info(
947
+ "Done waiting for other agents. Elapsed: %s seconds",
948
+ time.time() - start,
949
+ )
950
+ except SignalException as e:
951
+ logger.warning("Got termination signal: %s", e.sigval)
952
+ raise
953
+ except Exception:
954
+ logger.exception(
955
+ "Error waiting on exit barrier. Elapsed: %s seconds",
956
+ time.time() - start,
957
+ )
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/agent/server/health_check_server.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
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
+
9
+ from typing import Callable
10
+
11
+ from torch.distributed.elastic.utils.logging import get_logger
12
+
13
+
14
+ log = get_logger(__name__)
15
+
16
+ __all__ = ["HealthCheckServer", "create_healthcheck_server"]
17
+
18
+
19
+ class HealthCheckServer:
20
+ """
21
+ Interface for health check monitoring server, which can be extended
22
+ by starting tcp/http server on the specified port.
23
+
24
+ Args:
25
+
26
+ alive_callback: Callable[[], int], callback to last progress time of agent
27
+
28
+ port: int, port number to start tcp/http server
29
+
30
+ timeout: int, timeout seconds to decide agent is alive/dead
31
+ """
32
+
33
+ _alive_callback: Callable[[], int]
34
+ _port: int
35
+ _timeout: int
36
+
37
+ def __init__(
38
+ self, alive_callback: Callable[[], int], port: int, timeout: int
39
+ ) -> None:
40
+ self._alive_callback = alive_callback
41
+ self._port = port
42
+ self._timeout = timeout
43
+
44
+ def start(self) -> None:
45
+ """
46
+ Unsupported functionality for Pytorch, doesn't start any health check server
47
+ """
48
+ log.warning("No health check server started")
49
+
50
+ def stop(self) -> None:
51
+ """
52
+ Function to stop health check server
53
+ """
54
+ log.info("Stopping noop health check server.")
55
+
56
+
57
+ def create_healthcheck_server(
58
+ alive_callback: Callable[[], int],
59
+ port: int,
60
+ timeout: int,
61
+ ) -> HealthCheckServer:
62
+ """
63
+ creates health check server object
64
+ """
65
+ return HealthCheckServer(alive_callback, port, timeout)
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/agent/server/local_elastic_agent.py ADDED
@@ -0,0 +1,417 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # mypy: allow-untyped-defs
3
+
4
+ # Copyright (c) Facebook, Inc. and its affiliates.
5
+ # All rights reserved.
6
+ #
7
+ # This source code is licensed under the BSD-style license found in the
8
+ # LICENSE file in the root directory of this source tree.
9
+
10
+
11
+ import json
12
+ import os
13
+ import signal
14
+ import socket
15
+ import time
16
+ import uuid
17
+ from string import Template
18
+ from typing import Any, Optional, TYPE_CHECKING
19
+
20
+ import torch.distributed.elastic.timer as timer
21
+ from torch.distributed.elastic import events
22
+ from torch.distributed.elastic.agent.server.api import (
23
+ RunResult,
24
+ SimpleElasticAgent,
25
+ WorkerGroup,
26
+ WorkerSpec,
27
+ WorkerState,
28
+ )
29
+ from torch.distributed.elastic.agent.server.health_check_server import (
30
+ create_healthcheck_server,
31
+ HealthCheckServer,
32
+ )
33
+ from torch.distributed.elastic.metrics.api import prof
34
+ from torch.distributed.elastic.multiprocessing import (
35
+ LogsSpecs,
36
+ PContext,
37
+ start_processes,
38
+ )
39
+ from torch.distributed.elastic.utils import macros
40
+ from torch.distributed.elastic.utils.logging import get_logger
41
+
42
+
43
+ if TYPE_CHECKING:
44
+ from torch.distributed.elastic.events.api import EventMetadataValue
45
+
46
+ logger = get_logger(__name__)
47
+
48
+ __all__ = [
49
+ "LocalElasticAgent",
50
+ "TORCHELASTIC_ENABLE_FILE_TIMER",
51
+ "TORCHELASTIC_TIMER_FILE",
52
+ "TORCHELASTIC_HEALTH_CHECK_PORT",
53
+ ]
54
+
55
+ TORCHELASTIC_ENABLE_FILE_TIMER = "TORCHELASTIC_ENABLE_FILE_TIMER"
56
+ TORCHELASTIC_HEALTH_CHECK_PORT = "TORCHELASTIC_HEALTH_CHECK_PORT"
57
+ TORCHELASTIC_TIMER_FILE = "TORCHELASTIC_TIMER_FILE"
58
+
59
+
60
+ class LocalElasticAgent(SimpleElasticAgent):
61
+ """An implementation of :py:class:`torchelastic.agent.server.ElasticAgent` that handles host-local workers.
62
+
63
+ This agent is deployed per host and is configured to spawn ``n`` workers.
64
+ When using GPUs, ``n`` maps to the number of GPUs available on the host.
65
+
66
+ The local agent does not communicate to other local agents deployed on
67
+ other hosts, even if the workers may communicate inter-host. The worker id
68
+ is interpreted to be a local process. The agent starts and stops all worker
69
+ processes as a single unit.
70
+
71
+
72
+ The worker function and argument passed to the worker function must be
73
+ python multiprocessing compatible. To pass multiprocessing data structures
74
+ to the workers you may create the data structure in the same multiprocessing
75
+ context as the specified ``start_method`` and pass it as a function argument.
76
+
77
+ The ``exit_barrier_timeout`` specifies the amount of time (in seconds) to wait
78
+ for other agents to finish. This acts as a safety net to handle cases where
79
+ workers finish at different times, to prevent agents from viewing workers
80
+ that finished early as a scale-down event. It is strongly advised that the
81
+ user code deal with ensuring that workers are terminated in a synchronous
82
+ manner rather than relying on the exit_barrier_timeout.
83
+
84
+ A named pipe based watchdog can be enabled in ```LocalElasticAgent``` if an
85
+ environment variable ``TORCHELASTIC_ENABLE_FILE_TIMER`` with value 1 has
86
+ been defined in the ```LocalElasticAgent``` process.
87
+ Optionally, another environment variable ```TORCHELASTIC_TIMER_FILE```
88
+ can be set with a unique file name for the named pipe. If the environment
89
+ variable ```TORCHELASTIC_TIMER_FILE``` is not set, ```LocalElasticAgent```
90
+ will internally create a unique file name and set it to the environment
91
+ variable ```TORCHELASTIC_TIMER_FILE```, and this environment variable will
92
+ be propagated to the worker processes to allow them to connect to the same
93
+ named pipe that ```LocalElasticAgent``` uses.
94
+
95
+ Logs are written to the specified log directory. Each log line will be by default
96
+ prefixed by ``[${role_name}${local_rank}]:`` (e.g. ``[trainer0]: foobar``).
97
+ Log prefixes can be customized by passing a `template string
98
+ <https://docs.python.org/3/library/string.html#template-strings>`_ as the
99
+ ``log_line_prefix_template`` argument.
100
+ The following macros (identifiers) are substituted at runtime:
101
+ ``${role_name}, ${local_rank}, ${rank}``. For example, to prefix each log line with
102
+ global rank instead of the local rank, set ``log_line_prefix_template = "[${rank}]:``.
103
+
104
+
105
+ Example launching function
106
+
107
+ ::
108
+
109
+ def trainer(args) -> str:
110
+ return "do train"
111
+
112
+ def main():
113
+ start_method="spawn"
114
+ shared_queue= multiprocessing.get_context(start_method).Queue()
115
+ spec = WorkerSpec(
116
+ role="trainer",
117
+ local_world_size=nproc_per_process,
118
+ entrypoint=trainer,
119
+ args=("foobar",),
120
+ ...<OTHER_PARAMS...>)
121
+ agent = LocalElasticAgent(spec, start_method)
122
+ results = agent.run()
123
+
124
+ if results.is_failed():
125
+ print("trainer failed")
126
+ else:
127
+ print(f"rank 0 return value: {results.return_values[0]}")
128
+ # prints -> rank 0 return value: do train
129
+
130
+ Example launching binary
131
+
132
+ ::
133
+
134
+ def main():
135
+ spec = WorkerSpec(
136
+ role="trainer",
137
+ local_world_size=nproc_per_process,
138
+ entrypoint="/usr/local/bin/trainer",
139
+ args=("--trainer-args", "foobar"),
140
+ ...<OTHER_PARAMS...>)
141
+ agent = LocalElasticAgent(spec)
142
+ results = agent.run()
143
+
144
+ if not results.is_failed():
145
+ print("binary launches do not have return values")
146
+
147
+ """
148
+
149
+ def __init__(
150
+ self,
151
+ spec: WorkerSpec,
152
+ logs_specs: LogsSpecs,
153
+ start_method="spawn",
154
+ exit_barrier_timeout: float = 300,
155
+ log_line_prefix_template: Optional[str] = None,
156
+ ):
157
+ super().__init__(spec, exit_barrier_timeout)
158
+ self._start_method = start_method
159
+ self._pcontext: Optional[PContext] = None
160
+ self._rdzv_handler = spec.rdzv_handler
161
+ self._log_line_prefix_template = log_line_prefix_template
162
+ self._worker_watchdog: Optional[timer.FileTimerServer] = None
163
+ self._logs_specs = logs_specs
164
+ self._health_check_server: Optional[HealthCheckServer] = None
165
+
166
+ def _setup_local_watchdog(self, envs: dict[int, dict[str, str]]) -> None:
167
+ enable_watchdog_env_name = TORCHELASTIC_ENABLE_FILE_TIMER
168
+ watchdog_enabled = os.getenv(enable_watchdog_env_name)
169
+ watchdog_file_env_name = TORCHELASTIC_TIMER_FILE
170
+ watchdog_file_path = os.getenv(watchdog_file_env_name)
171
+ if watchdog_enabled is not None and str(watchdog_enabled) == "1":
172
+ if watchdog_file_path is None:
173
+ watchdog_file_path = "/tmp/watchdog_timer_" + str(uuid.uuid4())
174
+ logger.info("Starting a FileTimerServer with %s ...", watchdog_file_path)
175
+ if not envs:
176
+ logger.warning(
177
+ "Empty envs variables, using empty run_id for FileTimerServer"
178
+ )
179
+ run_id = ""
180
+ else:
181
+ run_id = envs[0]["TORCHELASTIC_RUN_ID"]
182
+ self._worker_watchdog = timer.FileTimerServer(
183
+ file_path=watchdog_file_path,
184
+ run_id=run_id,
185
+ max_interval=0.1,
186
+ daemon=True,
187
+ log_event=self._log_watchdog_event,
188
+ )
189
+ self._worker_watchdog.start()
190
+ logger.info("FileTimerServer started")
191
+ else:
192
+ logger.info(
193
+ "Environment variable '%s' not found. Do not start FileTimerServer.",
194
+ enable_watchdog_env_name,
195
+ )
196
+ # Propagate the watchdog file env to worker processes
197
+ if watchdog_file_path is not None:
198
+ for worker_env in envs.values():
199
+ worker_env[watchdog_file_env_name] = watchdog_file_path
200
+
201
+ @staticmethod
202
+ def _get_current_time_secs() -> int:
203
+ return int(time.time())
204
+
205
+ def _setup_healthcheck(self) -> None:
206
+ healthcheck_port_env_name = TORCHELASTIC_HEALTH_CHECK_PORT
207
+ healthcheck_port = os.getenv(healthcheck_port_env_name)
208
+ if healthcheck_port is not None:
209
+ logger.info(
210
+ "Found healthcheck port %s: %s",
211
+ healthcheck_port_env_name,
212
+ healthcheck_port,
213
+ )
214
+ if self._worker_watchdog is None:
215
+ logger.info(
216
+ "FileTimerServer doesn't exist, using current time as dummy callback"
217
+ )
218
+ alive_callback = LocalElasticAgent._get_current_time_secs
219
+ else:
220
+ alive_callback = self._worker_watchdog.get_last_progress_time
221
+
222
+ try:
223
+ healthcheck_port_as_int = int(healthcheck_port)
224
+ self._health_check_server = create_healthcheck_server(
225
+ alive_callback=alive_callback,
226
+ port=healthcheck_port_as_int,
227
+ timeout=60,
228
+ )
229
+ self._health_check_server.start()
230
+ except ValueError:
231
+ logger.info(
232
+ "Invalid healthcheck port value: '%s', expecting integer. Not starting healthcheck server.",
233
+ healthcheck_port,
234
+ )
235
+ else:
236
+ logger.info(
237
+ "Environment variable '%s' not found. Do not start health check.",
238
+ healthcheck_port_env_name,
239
+ )
240
+
241
+ def _get_fq_hostname(self) -> str:
242
+ return socket.getfqdn(socket.gethostname())
243
+
244
+ def _log_watchdog_event(
245
+ self,
246
+ name: str,
247
+ request: Optional[timer.FileTimerRequest],
248
+ ) -> None:
249
+ wg = self._worker_group
250
+ spec = wg.spec
251
+ md = {"watchdog_event": name}
252
+ if request is not None:
253
+ md["worker_pid"] = str(request.worker_pid)
254
+ md["scope_id"] = request.scope_id
255
+ md["expiration_time"] = str(request.expiration_time)
256
+ md["signal"] = str(request.signal)
257
+ md_str = json.dumps(md)
258
+ state = "RUNNING"
259
+ metadata: dict[str, EventMetadataValue] = {
260
+ "run_id": spec.rdzv_handler.get_run_id(),
261
+ "global_rank": None,
262
+ "group_rank": wg.group_rank,
263
+ "worker_id": None,
264
+ "role": spec.role,
265
+ "hostname": self._get_fq_hostname(),
266
+ "state": state,
267
+ "total_run_time": self._total_execution_time,
268
+ "rdzv_backend": spec.rdzv_handler.get_backend(),
269
+ "raw_error": None,
270
+ "metadata": md_str,
271
+ "agent_restarts": spec.max_restarts - self._remaining_restarts,
272
+ }
273
+ # Note: The 'metadata' field of the Event is converted to a TorchelasticStatusLogEntry later.
274
+ # The 'name' field of the Event is NOT used in the TorchelasticStatusLogEntry.
275
+ event = events.Event(
276
+ name=name, source=events.EventSource.AGENT, metadata=metadata
277
+ )
278
+ events.record(event)
279
+
280
+ # pyre-fixme[56]: Pyre was not able to infer the type of the decorator
281
+ # `torch.distributed.elastic.metrics.prof`.
282
+ @prof
283
+ def _stop_workers(
284
+ self, worker_group: WorkerGroup, is_restart: bool = False
285
+ ) -> None:
286
+ self._shutdown(is_restart=is_restart)
287
+
288
+ # pyre-fixme[56]: Pyre was not able to infer the type of the decorator
289
+ # `torch.distributed.elastic.metrics.prof`.
290
+ @prof
291
+ def _start_workers(self, worker_group: WorkerGroup) -> dict[int, Any]:
292
+ spec = worker_group.spec
293
+ store = worker_group.store
294
+ assert store is not None
295
+ restart_count = spec.max_restarts - self._remaining_restarts
296
+
297
+ use_agent_store: bool = spec.rdzv_handler.use_agent_store
298
+ logger.info("use_agent_store: %s", use_agent_store)
299
+
300
+ args: dict[int, tuple] = {}
301
+ envs: dict[int, dict[str, str]] = {}
302
+ log_line_prefixes: Optional[dict[int, str]] = (
303
+ {} if self._log_line_prefix_template else None
304
+ )
305
+ for worker in worker_group.workers:
306
+ local_rank = worker.local_rank
307
+ worker_env = {
308
+ "LOCAL_RANK": str(local_rank),
309
+ "RANK": str(worker.global_rank),
310
+ "GROUP_RANK": str(worker_group.group_rank),
311
+ "ROLE_RANK": str(worker.role_rank),
312
+ "ROLE_NAME": spec.role,
313
+ "LOCAL_WORLD_SIZE": str(spec.local_world_size),
314
+ "WORLD_SIZE": str(worker.world_size),
315
+ "GROUP_WORLD_SIZE": str(worker_group.group_world_size),
316
+ "ROLE_WORLD_SIZE": str(worker.role_world_size),
317
+ "MASTER_ADDR": worker_group.master_addr,
318
+ "MASTER_PORT": str(worker_group.master_port),
319
+ "TORCHELASTIC_RESTART_COUNT": str(restart_count),
320
+ "TORCHELASTIC_MAX_RESTARTS": str(spec.max_restarts),
321
+ "TORCHELASTIC_RUN_ID": spec.rdzv_handler.get_run_id(),
322
+ "TORCHELASTIC_USE_AGENT_STORE": str(use_agent_store),
323
+ "TORCH_NCCL_ASYNC_ERROR_HANDLING": os.getenv(
324
+ "TORCH_NCCL_ASYNC_ERROR_HANDLING", str(1)
325
+ ),
326
+ }
327
+ if "OMP_NUM_THREADS" in os.environ:
328
+ worker_env["OMP_NUM_THREADS"] = os.environ["OMP_NUM_THREADS"]
329
+
330
+ if self._log_line_prefix_template:
331
+ log_line_prefix = Template(
332
+ self._log_line_prefix_template
333
+ ).safe_substitute(
334
+ role_name=spec.role,
335
+ rank=worker.global_rank,
336
+ local_rank=local_rank,
337
+ )
338
+ log_line_prefixes[local_rank] = log_line_prefix
339
+
340
+ envs[local_rank] = worker_env
341
+ worker_args = list(spec.args)
342
+ worker_args = macros.substitute(worker_args, str(local_rank))
343
+ args[local_rank] = tuple(worker_args)
344
+
345
+ self._setup_local_watchdog(envs=envs)
346
+ self._setup_healthcheck()
347
+
348
+ assert spec.entrypoint is not None
349
+ assert self._logs_specs is not None
350
+ self._pcontext = start_processes(
351
+ name=spec.role,
352
+ entrypoint=spec.entrypoint,
353
+ args=args,
354
+ envs=envs,
355
+ logs_specs=self._logs_specs,
356
+ log_line_prefixes=log_line_prefixes,
357
+ start_method=self._start_method,
358
+ )
359
+
360
+ return self._pcontext.pids()
361
+
362
+ def _shutdown(
363
+ self, death_sig: signal.Signals = signal.SIGTERM, is_restart: bool = False
364
+ ) -> None:
365
+ if self._worker_watchdog is not None:
366
+ self._worker_watchdog.stop()
367
+ self._worker_watchdog = None
368
+ if self._health_check_server is not None:
369
+ self._health_check_server.stop()
370
+ self._health_check_server = None
371
+ if self._pcontext:
372
+ self._pcontext.close(death_sig)
373
+ if not is_restart and self._rdzv_handler:
374
+ self._rdzv_handler.shutdown()
375
+
376
+ # pyre-fixme[56]: Pyre was not able to infer the type of the decorator
377
+ # `torch.distributed.elastic.metrics.prof`.
378
+ @prof
379
+ def _monitor_workers(self, worker_group: WorkerGroup) -> RunResult:
380
+ role = worker_group.spec.role
381
+ worker_pids = {w.id for w in worker_group.workers}
382
+ assert self._pcontext is not None
383
+ pc_pids = set(self._pcontext.pids().values())
384
+ if worker_pids != pc_pids:
385
+ logger.error(
386
+ "[%s] worker pids do not match process_context pids."
387
+ " Expected: %s, actual: %s",
388
+ role,
389
+ worker_pids,
390
+ pc_pids,
391
+ )
392
+ return RunResult(state=WorkerState.UNKNOWN)
393
+
394
+ result = self._pcontext.wait(0)
395
+ if result:
396
+ if result.is_failed():
397
+ # map local rank failure to global rank
398
+ worker_failures = {}
399
+ for local_rank, failure in result.failures.items():
400
+ worker = worker_group.workers[local_rank]
401
+ worker_failures[worker.global_rank] = failure
402
+ return RunResult(
403
+ state=WorkerState.FAILED,
404
+ failures=worker_failures,
405
+ )
406
+ else:
407
+ # copy ret_val_queue into a map with a global ranks
408
+ workers_ret_vals = {}
409
+ for local_rank, ret_val in result.return_values.items():
410
+ worker = worker_group.workers[local_rank]
411
+ workers_ret_vals[worker.global_rank] = ret_val
412
+ return RunResult(
413
+ state=WorkerState.SUCCEEDED,
414
+ return_values=workers_ret_vals,
415
+ )
416
+ else:
417
+ return RunResult(state=WorkerState.HEALTHY)
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/events/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (5.77 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/events/__pycache__/api.cpython-312.pyc ADDED
Binary file (4.81 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/events/__pycache__/handlers.cpython-312.pyc ADDED
Binary file (785 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/metrics/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (5.02 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/metrics/__pycache__/api.cpython-312.pyc ADDED
Binary file (8.21 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (7.32 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/__pycache__/api.cpython-312.pyc ADDED
Binary file (39.9 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/__pycache__/redirects.cpython-312.pyc ADDED
Binary file (4.01 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/__pycache__/tail_log.cpython-312.pyc ADDED
Binary file (6.22 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/errors/__init__.py ADDED
@@ -0,0 +1,383 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # mypy: allow-untyped-defs
3
+
4
+ # Copyright (c) Facebook, Inc. and its affiliates.
5
+ # All rights reserved.
6
+ #
7
+ # This source code is licensed under the BSD-style license found in the
8
+ # LICENSE file in the root directory of this source tree.
9
+
10
+ """
11
+ Each host in a distributed PyTorch job runs with a single TorchElastic agent,
12
+ and multiple workers (as children processes of the TorchElastic agent).
13
+ Since the workers are user-provided (your PyTorch script/job), TorchElastic
14
+ has a way to propagate errors on the trainers through the agent and up to the
15
+ scheduler, which ultimately informs the end-user about the state of the job
16
+ and applies any retry policies.
17
+
18
+ TorchElastic categorizes errors into 3 categories:
19
+
20
+ +----------------+----------------+--------------------------------------------------------------+
21
+ | Category | Sub-Category | Description |
22
+ +================+================+==============================================================+
23
+ | User Error | Input Error | invalid inputs to TorchElastic APIs (e.g. min > max nodes) |
24
+ | +----------------+--------------------------------------------------------------+
25
+ | | Worker Failure | any failures on the worker child process |
26
+ +----------------+----------------+--------------------------------------------------------------+
27
+ | Platform Error | n/a | failures caused by the agent |
28
+ +----------------+----------------+--------------------------------------------------------------+
29
+ | Infra Error | n/a | failures outside the domain of the agent and workers |
30
+ | | | (e.g. host failures) |
31
+ +----------------+----------------+--------------------------------------------------------------+
32
+
33
+ All errors other than "Worker Failure" are either raised canonically from the
34
+ agent process or implicitly or explicitly crash the agent process. So the
35
+ standard language (python) provided exception handling strategies apply.
36
+
37
+ Worker Failures are special because the exception/failure originates on a different
38
+ process from the agent so the error needs to be propagated inter-process
39
+ (e.g. the agent cannot simply ``try-catch`` an exception raised on the worker process).
40
+
41
+ TorchElastic agents use :func:`torch.distributed.elastic.multiprocessing.start_processes`
42
+ to launch the workers which has a simple file based inter-process error propagation
43
+ built-in.
44
+
45
+ Any function or binary entrypoint decorated with :func:`record`
46
+ will write uncaught exceptions (with the trace information) to a file specified by the
47
+ environment variable ``TORCHELASTIC_ERROR_FILE``. The parent process (e.g. agent)
48
+ sets this env var on each child it launches, then aggregates the error files for all
49
+ children, and propagates the one with the **smallest** timestamp (e.g. the **first** error).
50
+ """
51
+
52
+ import json
53
+ import os
54
+ import signal
55
+ import socket
56
+ import time
57
+ from dataclasses import dataclass, field
58
+ from datetime import datetime
59
+ from functools import wraps
60
+ from string import Template
61
+ from typing import Any, Callable, Optional, TypeVar
62
+
63
+ from torch.distributed.elastic.utils.logging import get_logger
64
+
65
+ from .error_handler import ErrorHandler # noqa: F401
66
+ from .handlers import get_error_handler # noqa: F401
67
+
68
+
69
+ __all__ = [
70
+ "ProcessFailure",
71
+ "ChildFailedError",
72
+ "record",
73
+ "ErrorHandler",
74
+ "get_error_handler",
75
+ ]
76
+
77
+ logger = get_logger(__name__)
78
+
79
+
80
+ JSON = dict
81
+
82
+ _EMPTY_ERROR_DATA = {"message": "<NONE>"}
83
+ _NOT_AVAILABLE = "<N/A>"
84
+
85
+ T = TypeVar("T")
86
+
87
+
88
+ @dataclass
89
+ class ProcessFailure:
90
+ """
91
+ Represent the failed process result. When the worker process fails, it may record failure root cause into the file.
92
+
93
+ Tries to read the failure timestamp from the provided ``error_file``,
94
+ if the ``error_file`` does not exist, the timestamp is the current
95
+ timestamp (seconds since epoch).
96
+
97
+ The ``message`` field is a concise explanation of the failure. If
98
+ the error file exists then the message is obtained from the error file.
99
+ Otherwise one is generated based on the failure signature.
100
+
101
+ .. note:: It is assumed that the ``error_file`` is written by
102
+ ``torch.distributed.elastic.multiprocessing.errors.error_handler.ErrorHandler``.
103
+ Otherwise the behavior is undefined.
104
+
105
+ """
106
+
107
+ local_rank: int
108
+ pid: int
109
+ exitcode: int
110
+ error_file: str
111
+ error_file_data: JSON = field(init=False)
112
+ message: str = field(init=False)
113
+ timestamp: int = field(init=False)
114
+
115
+ def __post_init__(self):
116
+ self.error_file_data = _EMPTY_ERROR_DATA
117
+ if os.path.isfile(self.error_file):
118
+ try:
119
+ with open(self.error_file) as fp:
120
+ self.error_file_data = json.load(fp)
121
+ logger.debug(
122
+ "User process failed with error data: %s",
123
+ json.dumps(self.error_file_data, indent=2),
124
+ )
125
+ self.message, self.timestamp = self._get_error_data(
126
+ self.error_file_data
127
+ )
128
+ except Exception:
129
+ logger.exception("Failed to parse reply file: %s", self.error_file)
130
+ raise
131
+ else:
132
+ self._set_no_reply_file()
133
+
134
+ # make up an informative message if not already present
135
+ if not self.message:
136
+ # signals typically do not generate an error file message
137
+ if self.exitcode < 0:
138
+ self.message = (
139
+ f"Signal {-self.exitcode} ({self.signal_name()})"
140
+ f" received by PID {self.pid}"
141
+ )
142
+ else:
143
+ self.message = "To enable traceback see: https://pytorch.org/docs/stable/elastic/errors.html"
144
+
145
+ def _get_error_data(self, error_file_data: dict[str, Any]) -> tuple[str, int]:
146
+ message = error_file_data["message"]
147
+ if isinstance(message, str):
148
+ timestamp = int(error_file_data.get("timestamp", 0))
149
+ else:
150
+ timestamp = int(message["extraInfo"]["timestamp"])
151
+ return (message, timestamp)
152
+
153
+ def _set_no_reply_file(self):
154
+ self.error_file = _NOT_AVAILABLE
155
+ self.error_file_data = _EMPTY_ERROR_DATA
156
+ self.message = ""
157
+ self.timestamp = int(time.time())
158
+
159
+ def signal_name(self) -> str:
160
+ if self.exitcode < 0:
161
+ # We don't want to kill the parent process trying to find the signal name.
162
+ # if the signal doesn't map to a known name, use not available.
163
+ try:
164
+ return signal.Signals(-self.exitcode).name
165
+ except Exception:
166
+ return _NOT_AVAILABLE
167
+ else:
168
+ return _NOT_AVAILABLE
169
+
170
+ def timestamp_isoformat(self):
171
+ """Return timestamp in ISO format (YYYY-MM-DD_HH:MM:SS)."""
172
+ return datetime.fromtimestamp(self.timestamp).isoformat(sep="_")
173
+
174
+
175
+ GlobalRank = int
176
+
177
+ _FAILURE_FORMAT_TEMPLATE = """[${idx}]:
178
+ time : ${time}
179
+ host : ${hostname}
180
+ rank : ${rank} (local_rank: ${local_rank})
181
+ exitcode : ${exitcode} (pid: ${pid})
182
+ error_file: ${error_file}
183
+ traceback : ${message}"""
184
+
185
+ # extra new lines before and after are intentional
186
+ _MSG_FORMAT_TEMPLATE = """
187
+ ${boarder}
188
+ ${title}
189
+ ${section}
190
+ Failures:
191
+ ${other_failures}
192
+ ${section}
193
+ Root Cause (first observed failure):
194
+ ${root_failure}
195
+ ${boarder}"""
196
+
197
+
198
+ class ChildFailedError(Exception):
199
+ """
200
+ Special exception type that can be raised from a function annotated with the
201
+ ``@record`` decorator to have the child process' (root exception) propagate
202
+ up the stack as-is (e.g. without being wrapped in the parent's traceback).
203
+
204
+ Useful in cases where the parent is a simple nanny process
205
+ and the child (worker) processes are actually doing meaningful compute.
206
+ In this case, errors typically occur on the child process as the parent
207
+ is not doing anything non-trivial, and child errors should be propagated
208
+ to the scheduler for accurate root cause diagnostics.
209
+
210
+ .. note:: The propagation relies on error files rather than exception handling to
211
+ support both function and binary launches.
212
+
213
+ Example:
214
+ ::
215
+
216
+ # process tree on a host (container)
217
+ 0: scheduler-init-process:
218
+ |- 1: torchelastic_agent:
219
+ |- 2: trainer_0 (ok)
220
+ |- 3: trainer_1 (fail) -> error.json
221
+ |- ...
222
+ |- n+2: trainer_n (ok)
223
+ |- n+3: other processes
224
+ |- ...
225
+
226
+ In the example above, trainer 1's failure (written into error.json) is
227
+ the root cause and should be reported to the scheduler's init process.
228
+ The torchelastic agent raises a ``ChildFailedError("trainer", {1: "trainer_1/error.json"})``
229
+ upon detecting trainer 1's failure which would propagate the contents
230
+ of trainer 1's error file to the scheduler's init process.
231
+ """
232
+
233
+ def __init__(self, name: str, failures: dict[GlobalRank, ProcessFailure]):
234
+ self.name = name
235
+ self.failures = failures
236
+ assert (
237
+ self.failures
238
+ ) # does not make sense to create a ChildFaileError with no failures
239
+ super().__init__(self.format_msg())
240
+
241
+ def get_first_failure(self) -> tuple[GlobalRank, ProcessFailure]:
242
+ rank = min(self.failures.keys(), key=lambda r: self.failures[r].timestamp)
243
+ return rank, self.failures[rank]
244
+
245
+ def format_msg(self, boarder_delim="=", section_delim="-"):
246
+ title = f"{self.name} FAILED"
247
+ root_rank, _root_failure = self.get_first_failure()
248
+
249
+ root_failure_fmt: str = ""
250
+ other_failures_fmt: list[str] = []
251
+ width = len(title)
252
+ for idx, (rank, failure) in enumerate(self.failures.items()):
253
+ fmt, w = self._format_failure(idx, rank, failure)
254
+ width = max(width, w)
255
+ if rank == root_rank:
256
+ root_failure_fmt = fmt
257
+ else:
258
+ other_failures_fmt.append(fmt)
259
+
260
+ # upper boundary on width
261
+ width = min(width, 60)
262
+
263
+ return Template(_MSG_FORMAT_TEMPLATE).substitute(
264
+ boarder=boarder_delim * width,
265
+ title=title,
266
+ section=section_delim * width,
267
+ root_failure=root_failure_fmt,
268
+ other_failures="\n".join(other_failures_fmt or [" <NO_OTHER_FAILURES>"]),
269
+ )
270
+
271
+ def _format_failure(
272
+ self, idx: int, rank: int, failure: ProcessFailure
273
+ ) -> tuple[str, int]:
274
+ # failure.message is either a str (when the failure does not generate a traceback - e.g. signals)
275
+ # or a dict (json) of the form
276
+ # {"message": $ERROR_MSG, "extraInfo": {"py_callstack": $TRACEBACK, timestamp: $TS}}
277
+ # so the display logic is:
278
+ # 1. if failure.message is not a dict (it is a str) just show it as is
279
+ # 2. else try to get the traceback (py_callstack)
280
+ # 3. if the traceback is not there, use the message
281
+ # 4. if the message is not there show <N/A>
282
+ msg = failure.message
283
+ if isinstance(failure.message, dict):
284
+ msg = (
285
+ failure.message.get("extraInfo", {})
286
+ .get("py_callstack", failure.message.get("message", "<N/A>"))
287
+ .replace("\n", "\n ") # to properly indent the traceback
288
+ )
289
+
290
+ fmt = Template(_FAILURE_FORMAT_TEMPLATE).substitute(
291
+ idx=idx,
292
+ time=failure.timestamp_isoformat(),
293
+ hostname=socket.getfqdn(),
294
+ rank=rank,
295
+ local_rank=failure.local_rank,
296
+ exitcode=failure.exitcode,
297
+ pid=failure.pid,
298
+ error_file=failure.error_file,
299
+ message=msg,
300
+ )
301
+ width = 0
302
+ for line in fmt.split("\n"):
303
+ width = max(width, len(line))
304
+ return fmt, width
305
+
306
+
307
+ def record(
308
+ fn: Callable[..., T], error_handler: Optional[ErrorHandler] = None
309
+ ) -> Callable[..., T]:
310
+ """
311
+ Syntactic sugar to record errors/exceptions that happened in the decorated
312
+ function using the provided ``error_handler``.
313
+
314
+ Using this decorator is equivalent to:
315
+
316
+ ::
317
+
318
+ error_handler = get_error_handler()
319
+ error_handler.initialize()
320
+ try:
321
+ foobar()
322
+ except ChildFailedError as e:
323
+ _, failure = e.get_first_failure()
324
+ error_handler.dump_error_file(failure.error_file, failure.exitcode)
325
+ raise
326
+ except Exception as e:
327
+ error_handler.record_exception(e)
328
+ raise
329
+
330
+ .. important:: use this decorator once per process at the top level method,
331
+ typically this is the main method.
332
+
333
+ Example
334
+
335
+ ::
336
+
337
+ @record
338
+ def main():
339
+ pass
340
+
341
+
342
+ if __name__ == "__main__":
343
+ main()
344
+
345
+ """
346
+ if not error_handler:
347
+ error_handler = get_error_handler()
348
+
349
+ def wrap(f):
350
+ @wraps(f)
351
+ def wrapper(*args, **kwargs):
352
+ assert error_handler is not None # assertion for mypy type checker
353
+ error_handler.initialize()
354
+ try:
355
+ return f(*args, **kwargs)
356
+ except SystemExit as se:
357
+ # For run_path based entrypoints, SystemExit with code = 0 will never exit.
358
+ # Handling it here by returning a value:
359
+ if se.code == 0:
360
+ return None
361
+ else:
362
+ raise
363
+ except ChildFailedError as e:
364
+ rank, failure = e.get_first_failure()
365
+ if failure.error_file != _NOT_AVAILABLE:
366
+ error_handler.dump_error_file(failure.error_file, failure.exitcode)
367
+ else:
368
+ logger.info(
369
+ (
370
+ "local_rank %s FAILED with no error file."
371
+ " Decorate your entrypoint fn with @record for traceback info."
372
+ " See: https://pytorch.org/docs/stable/elastic/errors.html",
373
+ rank,
374
+ )
375
+ )
376
+ raise
377
+ except Exception as e:
378
+ error_handler.record_exception(e)
379
+ raise
380
+
381
+ return wrapper
382
+
383
+ return wrap(fn)
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/errors/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (16.3 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/errors/__pycache__/error_handler.cpython-312.pyc ADDED
Binary file (7.3 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/errors/__pycache__/handlers.cpython-312.pyc ADDED
Binary file (509 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/errors/error_handler.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # mypy: allow-untyped-defs
3
+
4
+ # Copyright (c) Facebook, Inc. and its affiliates.
5
+ # All rights reserved.
6
+ #
7
+ # This source code is licensed under the BSD-style license found in the
8
+ # LICENSE file in the root directory of this source tree.
9
+ import faulthandler
10
+ import json
11
+ import logging
12
+ import os
13
+ import time
14
+ import traceback
15
+ import warnings
16
+ from typing import Any, Optional
17
+
18
+
19
+ __all__ = ["ErrorHandler"]
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ class ErrorHandler:
25
+ """
26
+ Write the provided exception object along with some other metadata about
27
+ the error in a structured way in JSON format to an error file specified by the
28
+ environment variable: ``TORCHELASTIC_ERROR_FILE``. If this environment
29
+ variable is not set, then simply logs the contents of what would have been
30
+ written to the error file.
31
+
32
+ This handler may be subclassed to customize the handling of the error.
33
+ Subclasses should override ``initialize()`` and ``record_exception()``.
34
+ """
35
+
36
+ def _get_error_file_path(self) -> Optional[str]:
37
+ """
38
+ Return the error file path.
39
+
40
+ May return ``None`` to have the structured error be logged only.
41
+ """
42
+ return os.environ.get("TORCHELASTIC_ERROR_FILE", None)
43
+
44
+ def initialize(self) -> None:
45
+ """
46
+ Call prior to running code that we wish to capture errors/exceptions.
47
+
48
+ Typically registers signal/fault handlers. Users can override this
49
+ function to add custom initialization/registrations that aid in
50
+ propagation/information of errors/signals/exceptions/faults.
51
+ """
52
+ try:
53
+ faulthandler.enable(all_threads=True)
54
+ except Exception as e:
55
+ warnings.warn(f"Unable to enable fault handler. {type(e).__name__}: {e}")
56
+
57
+ def _write_error_file(self, file_path: str, error_msg: str) -> None:
58
+ """Write error message to the file."""
59
+ try:
60
+ with open(file_path, "w") as fp:
61
+ fp.write(error_msg)
62
+ except Exception as e:
63
+ warnings.warn(f"Unable to write error to file. {type(e).__name__}: {e}")
64
+
65
+ def record_exception(self, e: BaseException) -> None:
66
+ """
67
+ Write a structured information about the exception into an error file in JSON format.
68
+
69
+ If the error file cannot be determined, then logs the content
70
+ that would have been written to the error file.
71
+ """
72
+ file = self._get_error_file_path()
73
+ if file:
74
+ data = {
75
+ "message": {
76
+ "message": f"{type(e).__name__}: {e}",
77
+ "extraInfo": {
78
+ "py_callstack": traceback.format_exc(),
79
+ "timestamp": str(int(time.time())),
80
+ },
81
+ }
82
+ }
83
+ with open(file, "w") as fp:
84
+ json.dump(data, fp)
85
+
86
+ def override_error_code_in_rootcause_data(
87
+ self,
88
+ rootcause_error_file: str,
89
+ rootcause_error: dict[str, Any],
90
+ error_code: int = 0,
91
+ ):
92
+ """Modify the rootcause_error read from the file, to correctly set the exit code."""
93
+ if "message" not in rootcause_error:
94
+ logger.warning(
95
+ "child error file (%s) does not have field `message`. \n"
96
+ "cannot override error code: %s",
97
+ rootcause_error_file,
98
+ error_code,
99
+ )
100
+ elif isinstance(rootcause_error["message"], str):
101
+ logger.warning(
102
+ "child error file (%s) has a new message format. \n"
103
+ "skipping error code override",
104
+ rootcause_error_file,
105
+ )
106
+ else:
107
+ rootcause_error["message"]["errorCode"] = error_code
108
+
109
+ def dump_error_file(self, rootcause_error_file: str, error_code: int = 0):
110
+ """Dump parent error file from child process's root cause error and error code."""
111
+ with open(rootcause_error_file) as fp:
112
+ rootcause_error = json.load(fp)
113
+ # Override error code since the child process cannot capture the error code if it
114
+ # is terminated by signals like SIGSEGV.
115
+ if error_code:
116
+ self.override_error_code_in_rootcause_data(
117
+ rootcause_error_file, rootcause_error, error_code
118
+ )
119
+ logger.debug(
120
+ "child error file (%s) contents:\n%s",
121
+ rootcause_error_file,
122
+ json.dumps(rootcause_error, indent=2),
123
+ )
124
+
125
+ my_error_file = self._get_error_file_path()
126
+ if my_error_file:
127
+ # Guard against existing error files
128
+ # This can happen when the child is created using multiprocessing
129
+ # and the same env var (TORCHELASTIC_ERROR_FILE) is used on the
130
+ # parent and child to specify the error files (respectively)
131
+ # because the env vars on the child is set in the wrapper function
132
+ # and by default the child inherits the parent's env vars, if the child
133
+ # process receives a signal before the wrapper function kicks in
134
+ # and the signal handler writes to the error file, then the child
135
+ # will write to the parent's error file. In this case just log the
136
+ # original error file contents and overwrite the error file.
137
+ self._rm(my_error_file)
138
+ self._write_error_file(my_error_file, json.dumps(rootcause_error))
139
+ logger.info("dumped error file to parent's %s", my_error_file)
140
+ else:
141
+ logger.error(
142
+ "no error file defined for parent, to copy child error file (%s)",
143
+ rootcause_error_file,
144
+ )
145
+
146
+ def _rm(self, my_error_file):
147
+ if os.path.isfile(my_error_file):
148
+ # Log the contents of the original file.
149
+ with open(my_error_file) as fp:
150
+ try:
151
+ original = json.dumps(json.load(fp), indent=2)
152
+ logger.warning(
153
+ "%s already exists"
154
+ " and will be overwritten."
155
+ " Original contents:\n%s",
156
+ my_error_file,
157
+ original,
158
+ )
159
+ except json.decoder.JSONDecodeError:
160
+ logger.warning(
161
+ "%s already exists"
162
+ " and will be overwritten."
163
+ " Unable to load original contents:\n",
164
+ my_error_file,
165
+ )
166
+ os.remove(my_error_file)
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/errors/handlers.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
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
+ # Multiprocessing error-reporting module
9
+
10
+
11
+ from torch.distributed.elastic.multiprocessing.errors.error_handler import ErrorHandler
12
+
13
+
14
+ __all__ = ["get_error_handler"]
15
+
16
+
17
+ def get_error_handler() -> ErrorHandler:
18
+ return ErrorHandler()
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
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
+ from torch.distributed.elastic.multiprocessing.subprocess_handler.handlers import (
9
+ get_subprocess_handler,
10
+ )
11
+ from torch.distributed.elastic.multiprocessing.subprocess_handler.subprocess_handler import (
12
+ SubprocessHandler,
13
+ )
14
+
15
+
16
+ __all__ = ["SubprocessHandler", "get_subprocess_handler"]
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (515 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/__pycache__/handlers.cpython-312.pyc ADDED
Binary file (802 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/__pycache__/subprocess_handler.cpython-312.pyc ADDED
Binary file (3.32 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/handlers.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from torch.distributed.elastic.multiprocessing.subprocess_handler.subprocess_handler import (
8
+ SubprocessHandler,
9
+ )
10
+
11
+
12
+ __all__ = ["get_subprocess_handler"]
13
+
14
+
15
+ def get_subprocess_handler(
16
+ entrypoint: str,
17
+ args: tuple,
18
+ env: dict[str, str],
19
+ stdout: str,
20
+ stderr: str,
21
+ local_rank_id: int,
22
+ ) -> SubprocessHandler:
23
+ return SubprocessHandler(
24
+ entrypoint=entrypoint,
25
+ args=args,
26
+ env=env,
27
+ stdout=stdout,
28
+ stderr=stderr,
29
+ local_rank_id=local_rank_id,
30
+ )
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/subprocess_handler.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
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 os
9
+ import signal
10
+ import subprocess
11
+ import sys
12
+ from typing import Any, Optional
13
+
14
+
15
+ __all__ = ["SubprocessHandler"]
16
+
17
+ IS_WINDOWS = sys.platform == "win32"
18
+
19
+
20
+ def _get_default_signal() -> signal.Signals:
21
+ """Get the default termination signal. SIGTERM for unix, CTRL_C_EVENT for windows."""
22
+ if IS_WINDOWS:
23
+ return signal.CTRL_C_EVENT # type: ignore[attr-defined] # noqa: F821
24
+ else:
25
+ return signal.SIGTERM
26
+
27
+
28
+ class SubprocessHandler:
29
+ """
30
+ Convenience wrapper around python's ``subprocess.Popen``. Keeps track of
31
+ meta-objects associated to the process (e.g. stdout and stderr redirect fds).
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ entrypoint: str,
37
+ args: tuple,
38
+ env: dict[str, str],
39
+ stdout: Optional[str],
40
+ stderr: Optional[str],
41
+ local_rank_id: int,
42
+ ):
43
+ self._stdout = open(stdout, "w") if stdout else None
44
+ self._stderr = open(stderr, "w") if stderr else None
45
+ # inherit parent environment vars
46
+ env_vars = os.environ.copy()
47
+ env_vars.update(env)
48
+
49
+ args_str = (entrypoint, *[str(e) for e in args])
50
+ self.local_rank_id = local_rank_id
51
+ self.proc: subprocess.Popen = self._popen(args_str, env_vars)
52
+
53
+ def _popen(self, args: tuple, env: dict[str, str]) -> subprocess.Popen:
54
+ kwargs: dict[str, Any] = {}
55
+ if not IS_WINDOWS:
56
+ kwargs["start_new_session"] = True
57
+ return subprocess.Popen(
58
+ # pyre-fixme[6]: Expected `Union[typing.Sequence[Union[_PathLike[bytes],
59
+ # _PathLike[str], bytes, str]], bytes, str]` for 1st param but got
60
+ # `Tuple[str, *Tuple[Any, ...]]`.
61
+ args=args,
62
+ env=env,
63
+ stdout=self._stdout,
64
+ stderr=self._stderr,
65
+ **kwargs,
66
+ )
67
+
68
+ def close(self, death_sig: Optional[signal.Signals] = None) -> None:
69
+ if not death_sig:
70
+ death_sig = _get_default_signal()
71
+ if IS_WINDOWS:
72
+ self.proc.send_signal(death_sig)
73
+ else:
74
+ os.killpg(self.proc.pid, death_sig)
75
+ if self._stdout:
76
+ self._stdout.close()
77
+ if self._stderr:
78
+ self._stderr.close()
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (6.06 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/__pycache__/_etcd_stub.cpython-312.pyc ADDED
Binary file (3.98 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/__pycache__/api.cpython-312.pyc ADDED
Binary file (16.3 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/__pycache__/c10d_rendezvous_backend.cpython-312.pyc ADDED
Binary file (10.6 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/__pycache__/dynamic_rendezvous.cpython-312.pyc ADDED
Binary file (63.2 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/__pycache__/etcd_rendezvous.cpython-312.pyc ADDED
Binary file (41.5 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/__pycache__/etcd_rendezvous_backend.cpython-312.pyc ADDED
Binary file (8.95 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/__pycache__/etcd_server.cpython-312.pyc ADDED
Binary file (11.3 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/__pycache__/etcd_store.cpython-312.pyc ADDED
Binary file (8.48 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/__pycache__/registry.cpython-312.pyc ADDED
Binary file (3.82 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/__pycache__/static_tcp_rendezvous.cpython-312.pyc ADDED
Binary file (5.04 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/__pycache__/utils.cpython-312.pyc ADDED
Binary file (10.1 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/etcd_rendezvous.py ADDED
@@ -0,0 +1,1081 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # mypy: allow-untyped-defs
3
+
4
+ # Copyright (c) Facebook, Inc. and its affiliates.
5
+ # All rights reserved.
6
+ #
7
+ # This source code is licensed under the BSD-style license found in the
8
+ # LICENSE file in the root directory of this source tree.
9
+
10
+ import json
11
+ import logging
12
+ import sys
13
+ import threading
14
+ import time
15
+ from typing import Optional
16
+
17
+
18
+ try:
19
+ import etcd # type: ignore[import]
20
+ except ModuleNotFoundError:
21
+ from . import _etcd_stub as etcd
22
+
23
+ from torch.distributed.elastic.rendezvous import (
24
+ RendezvousClosedError,
25
+ RendezvousError,
26
+ RendezvousHandler,
27
+ RendezvousInfo,
28
+ RendezvousParameters,
29
+ RendezvousStoreInfo,
30
+ RendezvousTimeoutError,
31
+ )
32
+
33
+ from .etcd_store import cas_delay, EtcdStore
34
+ from .utils import parse_rendezvous_endpoint
35
+
36
+
37
+ __all__ = [
38
+ "EtcdRendezvousRetryableFailure",
39
+ "EtcdRendezvousRetryImmediately",
40
+ "EtcdRendezvousHandler",
41
+ "EtcdRendezvous",
42
+ "create_rdzv_handler",
43
+ ]
44
+
45
+ _log_fmt = logging.Formatter("%(levelname)s %(asctime)s %(message)s")
46
+ _log_handler = logging.StreamHandler(sys.stderr)
47
+ _log_handler.setFormatter(_log_fmt)
48
+
49
+ logger = logging.getLogger(__name__)
50
+ logger.propagate = False
51
+ logger.setLevel(logging.INFO)
52
+ logger.addHandler(_log_handler)
53
+
54
+
55
+ # Retryable failure exception means the we were too late to make
56
+ # a desired state transition (e.g. because of a race condition),
57
+ # and should now restart from the beginning.
58
+ # A small delay is recommended to avoid spamming Etcd.
59
+ class EtcdRendezvousRetryableFailure(Exception):
60
+ pass
61
+
62
+
63
+ # Similar to retryable failure, but the new state we observed suggests we
64
+ # can re-try immediately, i.e. without a need for "safety delay".
65
+ class EtcdRendezvousRetryImmediately(Exception):
66
+ pass
67
+
68
+
69
+ # Default timeout for the rendezvous.
70
+ _DEFAULT_TIMEOUT: int = 600 # 10 minutes
71
+
72
+ # Additional waiting time after reaching the minimum number of nodes
73
+ # in case the rendezvous is elastic (min != max).
74
+ _DEFAULT_LAST_CALL_TIMEOUT: int = 30 # 30 seconds
75
+
76
+ # Various constants used internally in EtcdRendezvous
77
+ CONST_ETCD_SETUP_TTL = 5
78
+ CONST_ETCD_FROZEN_TTL = 10
79
+ CONST_ETCD_JOINABLE_EPHEMERAL_TTL = 10
80
+
81
+ # Ephemeral node TTL for worker's keep-alive key:
82
+ CONST_WORKER_KEEPALIVE_TTL = 10
83
+
84
+ # TTL for the ephemeral run_id-specific directory. All rendezvous state data
85
+ # for a specific run_id (job instance) is contained within directory.
86
+ # Its only role is to clean-up rendezvous data from old runs (for the case when
87
+ # etcd server is persistent), and has no affect on correctness, but should be
88
+ # larger than any timeouts that a worker process is expected to survive:
89
+ CONST_RUNID_SUBROOT_TTL = 7200 # 2 hours
90
+
91
+
92
+ class EtcdRendezvousHandler(RendezvousHandler):
93
+ """
94
+ Implements a
95
+ :py:class:`torch.distributed.elastic.rendezvous.RendezvousHandler` interface
96
+ backed by
97
+ :py:class:`torch.distributed.elastic.rendezvous.etcd_rendezvous.EtcdRendezvous`.
98
+ ``EtcdRendezvousHandler`` uses a URL to configure the type of rendezvous to
99
+ use and to pass implementation specific configurations to the rendezvous
100
+ module. The basic etcd rendezvous configuration URL looks like the following
101
+ ::
102
+
103
+ etcd://<etcd_address>:<port>/<job_id>?min_workers=<min_workers>&max_workers=<max_workers> # noqa: W605
104
+
105
+ -- example --
106
+
107
+ etcd://localhost:2379/1234?min_workers=1&max_workers=3
108
+
109
+ The URL above is interpreted as follows:
110
+
111
+ 1. Use the rendezvous handler that is registered with the ``etcd``
112
+ scheme
113
+ 2. The ``etcd`` endpoint to use is ``localhost:2379``
114
+ 3. ``job_id == 1234`` is used as the prefix in etcd (this allows one to
115
+ share a common etcd server for multiple jobs so long as the
116
+ ``job_ids`` are guaranteed to be unique). Note that the job id can be
117
+ any string (e.g. does not need to be a number) as long as it is
118
+ unique.
119
+ 4. ``min_workers=1`` and ``max_workers=3`` specifies a range for
120
+ membership size - Torch Distributed Elastic starts running the job as
121
+ long as the cluster size is greater than or equal to ``min_workers``
122
+ and admits up to ``max_workers`` into the cluster.
123
+
124
+ Below are a full list of the parameters that can be passed to etcd
125
+ rendezvous:
126
+
127
+ +--------------------------------------------+--------------------------+
128
+ | Parameter | Description |
129
+ +============================================+==========================+
130
+ | min_workers | minimum number of |
131
+ | | workers for the |
132
+ | | rendezvous to be valid |
133
+ +--------------------------------------------+--------------------------+
134
+ | max_workers | maximum number of |
135
+ | | workers to admit |
136
+ +--------------------------------------------+--------------------------+
137
+ | timeout | total timeout within |
138
+ | | which next_rendezvous is |
139
+ | | expected to succeed |
140
+ | | (default 600s) |
141
+ +--------------------------------------------+--------------------------+
142
+ | last_call_timeout | additional wait amount |
143
+ | | ("last call") after min |
144
+ | | number of workers has |
145
+ | | been reached (defaults |
146
+ | | to 30s) |
147
+ +--------------------------------------------+--------------------------+
148
+ | etcd_prefix | path prefix (from etcd |
149
+ | | root), inside which all |
150
+ | | etcd nodes will be |
151
+ | | created (defaults to |
152
+ | | ``/torchelastic/p2p``) |
153
+ +--------------------------------------------+--------------------------+
154
+ """
155
+
156
+ def __init__(self, rdzv_impl: "EtcdRendezvous", local_addr: Optional[str]):
157
+ """
158
+ Args:
159
+ rdzv_impl: the implementation of the rendezvous
160
+ local_addr: the local address of the current node
161
+ """
162
+
163
+ self._rdzv_impl = rdzv_impl
164
+ self._local_addr = local_addr
165
+
166
+ def __del__(self):
167
+ # TODO: look into using weakref here instead.
168
+ del self._rdzv_impl
169
+
170
+ def get_backend(self) -> str:
171
+ return "etcd"
172
+
173
+ def next_rendezvous(self):
174
+ rdzv_version, rank, world_size = self._rdzv_impl.rendezvous_barrier()
175
+
176
+ logger.info("Creating EtcdStore as the c10d::Store implementation")
177
+ store = self._rdzv_impl.setup_kv_store(rdzv_version)
178
+
179
+ bootstrap_store_info = RendezvousStoreInfo.build(
180
+ rank, store, local_addr=self._local_addr
181
+ )
182
+ return RendezvousInfo(store, rank, world_size, bootstrap_store_info)
183
+
184
+ def is_closed(self):
185
+ try:
186
+ _, state = self._rdzv_impl.get_rdzv_state()
187
+ return state["status"] == "closed"
188
+ except etcd.EtcdKeyNotFound:
189
+ # No rendezvous state, so it cannot be closed.
190
+ return False
191
+
192
+ def set_closed(self):
193
+ self._rdzv_impl.set_closed()
194
+
195
+ def num_nodes_waiting(self):
196
+ try:
197
+ _, state = self._rdzv_impl.get_rdzv_state()
198
+ if state["status"] == "final":
199
+ return state["num_workers_waiting"]
200
+ except etcd.EtcdKeyNotFound:
201
+ pass
202
+ return 0
203
+
204
+ def get_run_id(self) -> str:
205
+ return self._rdzv_impl._run_id
206
+
207
+ def shutdown(self) -> bool:
208
+ try:
209
+ self.set_closed()
210
+ return True
211
+ except BaseException as e:
212
+ logger.warning("Shutdown failed. Error occurred: %s", str(e))
213
+ return False
214
+
215
+
216
+ # TODO: we should probably handle a few additional errors,
217
+ # like EtcdLeaderElectionInProgress and EtcdWatcherCleared. These are
218
+ # only relevant for multi-node Etcd ensemble. A simple retry would work,
219
+ # but is verbose to add everywhere. Consider wrapping the client calls
220
+ # into auto-retry for these errors?
221
+ #
222
+ class EtcdRendezvous:
223
+ """A rendezvous implementation that uses `etcd <https://etcd.io/>`__ as the backend store."""
224
+
225
+ def __init__(
226
+ self,
227
+ client,
228
+ prefix,
229
+ run_id,
230
+ num_min_workers,
231
+ num_max_workers,
232
+ timeout,
233
+ last_call_timeout,
234
+ ):
235
+ self.client = client
236
+ logger.info("Etcd machines: %s", self.client.machines)
237
+
238
+ self._prefix = prefix
239
+ self._run_id = run_id
240
+ self._num_min_workers = num_min_workers
241
+ self._num_max_workers = num_max_workers
242
+ self._timeout = timeout
243
+ self._last_call_timeout = last_call_timeout
244
+
245
+ # For cleaning up TTL refresher threads (for ephemeral keys)
246
+ self._lease_run_id_stop = None
247
+ self._lease_this_rank_stop = None
248
+
249
+ if not self._prefix.endswith("/"):
250
+ self._prefix += "/"
251
+
252
+ # Setup a permanent prefix dir, if didn't exist
253
+ if self._prefix != "/":
254
+ self.create_path_if_not_exists(self._prefix)
255
+
256
+ # Lease a "sub-root" node specific to this job instance (run_id)
257
+ self.create_path_if_not_exists(self.get_path(""), ttl=CONST_RUNID_SUBROOT_TTL)
258
+ self._lease_run_id_stop = self.setup_lease_renewal(
259
+ self.get_path(""), ttl=CONST_RUNID_SUBROOT_TTL
260
+ )
261
+
262
+ # Subdir for all rendezvous work
263
+ self.create_path_if_not_exists(self.get_path("/rdzv"))
264
+
265
+ # Create a rendezvous version counter, if doesn't exist
266
+ try:
267
+ self.client.write(
268
+ key=self.get_path("/rdzv/version_counter"), value="0", prevExist=False
269
+ )
270
+ except etcd.EtcdAlreadyExist:
271
+ pass
272
+
273
+ def __del__(self):
274
+ # TODO: look into using weakref here instead.
275
+ if self._lease_run_id_stop is not None:
276
+ self._lease_run_id_stop.set()
277
+
278
+ if self._lease_this_rank_stop is not None:
279
+ self._lease_this_rank_stop.set()
280
+
281
+ def rendezvous_barrier(self):
282
+ """
283
+ Main entry point for next rendezvous.
284
+
285
+ This method is blocking until rendezvous succeeds or a timeout occurs.
286
+
287
+ Returns:
288
+ ``(rdzv_version, rank, world_size)``
289
+
290
+ Raises:
291
+ RendezvousTimeoutError - timeout waiting for rendezvous
292
+ RendezvousClosedError - rendezvous is or was closed while waiting
293
+ RendezvousError - other persistent errors that
294
+ render the rendezvous non-retryable
295
+ """
296
+ self._rendezvous_deadline = time.time() + self._timeout
297
+ while True:
298
+ if time.time() > self._rendezvous_deadline:
299
+ raise RendezvousTimeoutError
300
+
301
+ logger.info("Attempting to join next rendezvous")
302
+ try:
303
+ # Dis-own our lease in the previous rendezvous, if exists
304
+ if self._lease_this_rank_stop is not None:
305
+ self._lease_this_rank_stop.set()
306
+
307
+ return self.init_phase()
308
+
309
+ except EtcdRendezvousRetryImmediately:
310
+ # The type of failure suggests we can retry without delay
311
+ pass
312
+
313
+ except EtcdRendezvousRetryableFailure:
314
+ # In case of retryable failure, wait a small delay
315
+ # to avoid spamming etcd
316
+ time.sleep(1)
317
+
318
+ except RendezvousTimeoutError:
319
+ logger.info("Rendezvous timeout occurred in EtcdRendezvousHandler")
320
+ raise
321
+
322
+ except RendezvousClosedError:
323
+ logger.info(
324
+ "Rendezvous for run_id=%s was observed to be closed", self._run_id
325
+ )
326
+ raise
327
+
328
+ except RendezvousError:
329
+ raise
330
+
331
+ except Exception as e:
332
+ # In case of a general exception, wait a small delay
333
+ # to avoid spamming etcd
334
+ # FIXME: there are a few things that fall under this like
335
+ # etcd.EtcdKeyNotFound, etc, which could be handled more explicitly.
336
+ logger.info("Rendezvous attempt failed, will retry. Reason: %s", e)
337
+ time.sleep(1)
338
+
339
+ def init_phase(self):
340
+ """
341
+ Initially, the rendezvous state is expected to be one of:
342
+
343
+ 1. empty (non-existent) - in this case we try to create a new one.
344
+ 2. joinable - we try to join it.
345
+ 3. final - we announce ourselves as waiting, and go into monitoring mode
346
+
347
+ Any other state is considered transitional, and will be retried after
348
+ a short delay.
349
+
350
+ Returns:
351
+ ``(rdzv_version, rank, world_size)``
352
+
353
+ Raises:
354
+ RendezvousClosedError - current rendezvous was/is closed
355
+ EtcdRendezvousRetryableFailure - observed some intermediate
356
+ state, which is best handled by retrying later
357
+ """
358
+ try:
359
+ active_version = self.try_create_rendezvous()
360
+ state = json.loads(active_version.value)
361
+ logger.info("New rendezvous state created: %s", state)
362
+ except etcd.EtcdAlreadyExist:
363
+ active_version, state = self.get_rdzv_state()
364
+ # Note: it is possible for above query to fail (etcd.EtcdKeyNotFound),
365
+ # but this is ok for us - just means we'll restart from beginning.
366
+ logger.info("Observed existing rendezvous state: %s", state)
367
+
368
+ if state["status"] == "closed":
369
+ raise RendezvousClosedError
370
+
371
+ if state["status"] == "joinable":
372
+ return self.join_phase(state["version"])
373
+
374
+ if state["status"] == "final":
375
+ self.handle_existing_rendezvous(state["version"])
376
+ raise EtcdRendezvousRetryImmediately
377
+
378
+ self.try_wait_for_state_change(etcd_index=active_version.etcd_index + 1)
379
+ raise EtcdRendezvousRetryableFailure
380
+
381
+ def join_phase(self, expected_version):
382
+ """
383
+ We observed a rendezvous state in 'joinable' state, and attempt to join this
384
+ particular version, and then wait for all other peers to join.
385
+ """
386
+ # Failure to join will propagate an exception, causing a re-entry.
387
+ active_version, this_rank = self.join_rendezvous(expected_version)
388
+ state = json.loads(active_version.value)
389
+ logger.info(
390
+ "Joined rendezvous version %s as rank %s. Full state: %s",
391
+ state["version"],
392
+ this_rank,
393
+ state,
394
+ )
395
+
396
+ # If this worker was first to reach num_min_workers requirement,
397
+ # and rendezvous is still joinable (therefore it is elastic),
398
+ # then this worker will be responsible for waiting out the "last call"
399
+ # timeout and closing (i.e. transitioning to 'frozen') the rendezvous
400
+ # afterwards.
401
+ # As a safety against a potential failure of this worker (during the
402
+ # last call timeout), the rendezvous state is made ephemeral
403
+ # when min_num_workers is reached.
404
+
405
+ if this_rank == self._num_min_workers - 1 and state["status"] == "joinable":
406
+ logger.info("Rank %s is responsible for join last call.", this_rank)
407
+ last_call_deadline = time.time() + self._last_call_timeout
408
+ self.handle_join_last_call(expected_version, last_call_deadline)
409
+ logger.info("Rank %s finished join last call.", this_rank)
410
+
411
+ # Wait for rendezvous state to be frozen, which means a fixed set of peers
412
+ logger.info("Waiting for remaining peers.")
413
+ active_version = self.wait_for_peers(expected_version)
414
+ state = json.loads(active_version.value)
415
+
416
+ assert state["version"] == expected_version, (
417
+ "Logic error: failed to observe version mismatch"
418
+ )
419
+
420
+ return self.confirm_phase(expected_version, this_rank)
421
+
422
+ def confirm_phase(self, expected_version, this_rank):
423
+ """
424
+ Once the rendezvous state transitions from 'joinable' to 'frozen',
425
+ we have every participant confirm their membership and setup per-member
426
+ keep-alive TTL keys, and then wait for all other participants to confirm,
427
+ which would then successfully conclude this rendezvous.
428
+ """
429
+ logger.info("All peers arrived. Confirming membership.")
430
+ self.confirm_membership(expected_version, this_rank)
431
+
432
+ logger.info("Waiting for confirmations from all peers.")
433
+ active_version = self.wait_for_final(expected_version)
434
+ state = json.loads(active_version.value)
435
+
436
+ logger.info(
437
+ "Rendezvous version %s is complete. Final state: %s",
438
+ state["version"],
439
+ state,
440
+ )
441
+
442
+ # Rendezvous version number; our rank in it; world size
443
+ return state["version"], this_rank, len(state["participants"])
444
+
445
+ def handle_existing_rendezvous(self, expected_version):
446
+ """
447
+ Handle the case when there's an existing (state 'final) rendezvous already
448
+ in place, and we have to announce ourselves waiting, and wait until
449
+ the next rendezvous opportunity.
450
+ """
451
+ # If state is 'final' -> increment num_workers_waiting
452
+ # Then, observe state changes:
453
+ # 1. if it's no longer final -> bail out and re-try
454
+ # 2. if keep alives are missing, destroy it and bail out.
455
+ active_state = self.announce_self_waiting(expected_version)
456
+ logger.info(
457
+ "Added self to waiting list. Rendezvous full state: %s", active_state.value
458
+ )
459
+
460
+ self.wait_for_rendezvous_to_free(expected_version)
461
+ logger.info(
462
+ "Previously existing rendezvous state changed. Will re-try joining."
463
+ )
464
+
465
+ def try_create_rendezvous(self):
466
+ """
467
+ Create new rendezvous state or raise an exception that indicates an unexpected state (e.g. already exists).
468
+
469
+ Raises:
470
+ RendezvousError - on unexpected state
471
+ """
472
+ # Initially active_version is ephemeral - this is to handle the
473
+ # possibility that might fail to complete the setup transaction,
474
+ # i.e. the transition "setup" -> "joinable".
475
+ active_version = self.client.write(
476
+ key=self.get_path("/rdzv/active_version"),
477
+ value=json.dumps({"status": "setup"}),
478
+ prevExist=False,
479
+ ttl=CONST_ETCD_SETUP_TTL,
480
+ )
481
+
482
+ try:
483
+ version_counter = self.client.get(self.get_path("/rdzv/version_counter"))
484
+ version_counter.value = str(int(version_counter.value) + 1)
485
+ self.client.update(version_counter)
486
+ except (etcd.EtcdKeyNotFound, etcd.EtcdCompareFailed) as e:
487
+ raise RendezvousError(
488
+ "Unexpected state of EtcdRendezvousHandler, worker needs to die."
489
+ ) from e
490
+
491
+ # Any failure below results in declaring a retryable rendezvous failure.
492
+ # The ephemeral /rdzv/active_version will expire and someone can then
493
+ # re-try the setup process.
494
+
495
+ # Create directory node for participant data
496
+ self.client.write(
497
+ key=self.get_path(f"/rdzv/v_{version_counter.value}"),
498
+ value=None,
499
+ dir=True,
500
+ prevExist=False,
501
+ )
502
+
503
+ # Publish rendezvous version and signal it is ready-to-be-joined.
504
+ # If rendezvous was set closed just before this, a retry will happen,
505
+ # where the closed condition will be handled.
506
+ return self.client.test_and_set(
507
+ key=self.get_path("/rdzv/active_version"),
508
+ value=json.dumps(
509
+ {
510
+ "status": "joinable",
511
+ "version": version_counter.value,
512
+ "participants": [],
513
+ }
514
+ ),
515
+ prev_value=active_version.value,
516
+ )
517
+
518
+ def join_rendezvous(self, expected_version):
519
+ """Helper method for the join phase."""
520
+ # Use compare-and-swap to add self to rendezvous state:
521
+ while True:
522
+ cas_delay()
523
+ active_version, state = self.get_rdzv_state()
524
+
525
+ if state["status"] != "joinable":
526
+ raise EtcdRendezvousRetryableFailure(
527
+ "Rendezvous state became non-joinable before we could join. "
528
+ "Must join next one."
529
+ )
530
+
531
+ if state["version"] != expected_version:
532
+ raise EtcdRendezvousRetryImmediately(
533
+ "Rendezvous version changed. Must try join the new one."
534
+ )
535
+
536
+ assert len(state["participants"]) < self._num_max_workers, (
537
+ "Logic error: joinable rendezvous should always have space left"
538
+ )
539
+
540
+ this_rank = len(state["participants"])
541
+ state["participants"].append(this_rank)
542
+
543
+ # When reaching min workers, or changing state to frozen, we'll set
544
+ # the active_version node to be ephemeral.
545
+ set_ttl: Optional[int] = None
546
+ if len(state["participants"]) == self._num_max_workers:
547
+ state["status"] = "frozen"
548
+ state["keep_alives"] = []
549
+ set_ttl = CONST_ETCD_FROZEN_TTL
550
+ elif len(state["participants"]) >= self._num_min_workers:
551
+ set_ttl = CONST_ETCD_JOINABLE_EPHEMERAL_TTL
552
+
553
+ try:
554
+ # Compare-and-swap.
555
+ active_version = self.client.test_and_set(
556
+ key=self.get_path("/rdzv/active_version"),
557
+ value=json.dumps(state),
558
+ prev_value=active_version.value,
559
+ ttl=set_ttl,
560
+ )
561
+ # We succeeded joining.
562
+ return active_version, this_rank
563
+
564
+ except etcd.EtcdCompareFailed:
565
+ logger.info("Join rendezvous CAS unsuccessful, retrying")
566
+
567
+ def wait_for_peers(self, expected_version):
568
+ """Helper method for the join phase."""
569
+ active_version, state = self.get_rdzv_state()
570
+ while True:
571
+ if state["status"] == "frozen" and state["version"] == expected_version:
572
+ # Success, all peers arrived.
573
+ return active_version
574
+
575
+ elif state["status"] == "joinable" and state["version"] == expected_version:
576
+ # Continue waiting for any interesting events.
577
+ active_version, state = self.try_wait_for_state_change(
578
+ etcd_index=active_version.etcd_index + 1
579
+ )
580
+
581
+ else:
582
+ # No valid transition possible at this point
583
+ raise EtcdRendezvousRetryableFailure(
584
+ "Rendezvous state transition no longer possible. Must re-enter."
585
+ )
586
+
587
+ def confirm_membership(self, expected_version, this_rank):
588
+ """Helper method for the confirm phase."""
589
+ # Compare-and-swap loop
590
+ while True:
591
+ cas_delay()
592
+ active_version, state = self.get_rdzv_state()
593
+
594
+ if state["status"] != "frozen":
595
+ raise EtcdRendezvousRetryImmediately(
596
+ "Rendezvous no longer frozen, before we confirmed. "
597
+ "Must join next one"
598
+ )
599
+ if state["version"] != expected_version:
600
+ raise EtcdRendezvousRetryImmediately(
601
+ "Rendezvous version changed. Must try join the new one."
602
+ )
603
+
604
+ this_lease_key = self.get_path(
605
+ f"/rdzv/v_{expected_version}/rank_{this_rank}"
606
+ )
607
+ self.client.set(this_lease_key, value=None, ttl=CONST_WORKER_KEEPALIVE_TTL)
608
+
609
+ state["keep_alives"].append(this_lease_key)
610
+ if len(state["keep_alives"]) == len(state["participants"]):
611
+ # Everyone confirmed (this rank is last to do so)
612
+ state["status"] = "final"
613
+ state["num_workers_waiting"] = 0
614
+ finalize = True
615
+ else:
616
+ finalize = False
617
+
618
+ try:
619
+ # Compare-and-swap. If new state is still frozen, keep it ephemeral.
620
+ active_version = self.client.test_and_set(
621
+ key=self.get_path("/rdzv/active_version"),
622
+ value=json.dumps(state),
623
+ prev_value=active_version.value,
624
+ ttl=None if finalize else CONST_ETCD_FROZEN_TTL,
625
+ )
626
+
627
+ self._lease_this_rank_stop = self.setup_lease_renewal(
628
+ this_lease_key, ttl=CONST_WORKER_KEEPALIVE_TTL
629
+ )
630
+ return active_version
631
+
632
+ except etcd.EtcdCompareFailed:
633
+ logger.info("Confirm membership CAS unsuccessful, retrying")
634
+
635
+ def wait_for_final(self, expected_version):
636
+ """Helper method for the confirm phase."""
637
+ active_version, state = self.get_rdzv_state()
638
+ while True:
639
+ if state["status"] == "final" and state["version"] == expected_version:
640
+ # Success. This rendezvous is final, and we accept it.
641
+ return active_version
642
+
643
+ elif state["status"] == "frozen" and state["version"] == expected_version:
644
+ # Continue waiting for any interesting events.
645
+ active_version, state = self.try_wait_for_state_change(
646
+ etcd_index=active_version.etcd_index + 1
647
+ )
648
+
649
+ else:
650
+ # No valid transition possible at this point
651
+ raise EtcdRendezvousRetryableFailure(
652
+ "Rendezvous state transition no longer possible. Must re-enter."
653
+ )
654
+
655
+ def announce_self_waiting(self, expected_version):
656
+ """
657
+ Announce this worker is waiting (via num_workers_waiting counter) to join next
658
+ rendezvous, but only if state and version match.
659
+ """
660
+ while True:
661
+ cas_delay()
662
+ active_version, state = self.get_rdzv_state()
663
+
664
+ if state["status"] != "final" or state["version"] != expected_version:
665
+ raise EtcdRendezvousRetryImmediately
666
+
667
+ # Increment counter to signal an additional waiting worker.
668
+ state["num_workers_waiting"] += 1
669
+
670
+ try:
671
+ active_version = self.client.test_and_set(
672
+ key=self.get_path("/rdzv/active_version"),
673
+ value=json.dumps(state),
674
+ prev_value=active_version.value,
675
+ )
676
+ return active_version
677
+
678
+ except etcd.EtcdCompareFailed:
679
+ logger.info("Announce self as waiting CAS unsuccessful, retrying")
680
+
681
+ def wait_for_rendezvous_to_free(self, expected_version):
682
+ """
683
+ When there's an existing valid rendezvous in state 'final', we have to wait until the next opportunity to join.
684
+
685
+ Such opportunity may come from:
686
+
687
+ 1. rendezvous state changed by someone else, in which case we unblock and retry.
688
+ 2. rendezvous becomes invalid because at least one member failed to renew their
689
+ leased keep_alive node. We detect this, and destroy the rendezvous.
690
+ """
691
+ active_version, state = self.get_rdzv_state()
692
+ while True:
693
+ if state["status"] != "final" or state["version"] != expected_version:
694
+ return
695
+
696
+ # Check if current rendezvous state is valid, in the sense that all
697
+ # its members are alive (renewing their lease).
698
+ # If not, try destroy this rendezvous, so a new one can be created.
699
+ alive_members = self.client.get(
700
+ self.get_path(f"/rdzv/v_{expected_version}")
701
+ )
702
+ keep_alive_keys = [ch.key for ch in alive_members.children]
703
+
704
+ for key in state["keep_alives"]:
705
+ if key not in keep_alive_keys:
706
+ # This participant didn't renew their lease. We'll declare this
707
+ # rendezvous version as dead (but only if it hadn't changed)
708
+ logger.info("Keep-alive key %s is not renewed.", key)
709
+ logger.info(
710
+ "Rendezvous version %s is incomplete. ", expected_version
711
+ )
712
+ logger.info("Attempting to destroy it.")
713
+
714
+ # Compare-and-delete operation. Throws if compare failed,
715
+ # which means rendezvous was already destroyed/re-created/closed,
716
+ # and we can try to re-enter the barrier.
717
+ self.client.delete(
718
+ key=self.get_path("/rdzv/active_version"),
719
+ prevValue=active_version.value,
720
+ )
721
+
722
+ logger.info(
723
+ "Destroyed rendezvous version %s successfully.",
724
+ expected_version,
725
+ )
726
+
727
+ # We can return (and retry) immediately
728
+ return
729
+
730
+ # Existing rendezvous seems valid, no reason to destroy it.
731
+ # We just have to wait until something changes and re-check.
732
+ try:
733
+ overall_timeout = (
734
+ max(self._rendezvous_deadline - time.time(), 0.0) + 1.0
735
+ )
736
+ self.client.watch(
737
+ key=self.get_path("/rdzv"),
738
+ index=active_version.etcd_index + 1,
739
+ recursive=True,
740
+ timeout=overall_timeout,
741
+ )
742
+ except (etcd.EtcdEventIndexCleared, etcd.EtcdWatchTimedOut):
743
+ pass
744
+
745
+ if time.time() > self._rendezvous_deadline:
746
+ raise RendezvousTimeoutError
747
+ active_version, state = self.get_rdzv_state()
748
+
749
+ def handle_join_last_call(self, expected_version, deadline):
750
+ """
751
+ After we reach min number of workers, one particular worker takes on the
752
+ responsibility of waiting an additional timeout before closing the join window.
753
+ If the worker responsible for this fails, the rendezvous will be destroyed due
754
+ to expiring TTL, and the other participants will re-rendezvous.
755
+
756
+ Here we expect to see state <joinable, expected_version>
757
+ Exit gracefully if either:
758
+
759
+ 1. state becomes <frozen, expected_version>
760
+ 2. timeout happens (reaching deadline), in which case
761
+ we try the transition to <frozen, expected_version>
762
+
763
+ Exit with exception otherwise.
764
+ """
765
+ active_version, state = self.get_rdzv_state()
766
+ while True:
767
+ if state["status"] == "frozen" and state["version"] == expected_version:
768
+ # Worker set became frozen before last-call timeout. This is possible
769
+ # when num_max_workers is reached before the timeout.
770
+ return
771
+
772
+ if state["status"] != "joinable" or state["version"] != expected_version:
773
+ raise EtcdRendezvousRetryableFailure(
774
+ "Rendezvous state transition no longer possible. Must re-enter."
775
+ )
776
+
777
+ # If timeout occurred, attempt a state transition (joinable -> frozen)
778
+ if time.time() >= deadline:
779
+ state["status"] = "frozen"
780
+ state["keep_alives"] = []
781
+ try:
782
+ active_version = self.client.test_and_set(
783
+ key=self.get_path("/rdzv/active_version"),
784
+ value=json.dumps(state),
785
+ prev_value=active_version.value,
786
+ ttl=CONST_ETCD_FROZEN_TTL,
787
+ )
788
+ # We successfully made this rendezvous frozen.
789
+ return
790
+ except etcd.EtcdCompareFailed:
791
+ logger.info(
792
+ "Join last-call transition CAS unsuccessful. Will retry"
793
+ )
794
+ cas_delay()
795
+ active_version, state = self.get_rdzv_state()
796
+ continue
797
+
798
+ # Timeout did not occur, so we must refresh TTL, and wait for
799
+ # further changes. Note: we only want TTL to be refreshed if
800
+ # state is still joinable, hence we use CAS for that here,
801
+ # even though we don't change any of the data.
802
+ try:
803
+ active_version = self.client.test_and_set(
804
+ key=self.get_path("/rdzv/active_version"),
805
+ value=active_version.value,
806
+ prev_value=active_version.value,
807
+ ttl=CONST_ETCD_JOINABLE_EPHEMERAL_TTL,
808
+ )
809
+
810
+ # Minimize "oversleeping":
811
+ timeout = min(
812
+ CONST_ETCD_JOINABLE_EPHEMERAL_TTL / 2,
813
+ deadline - time.time() + 1.0, # Oversleeping by 1s is ok.
814
+ )
815
+ active_version, state = self.try_wait_for_state_change(
816
+ etcd_index=active_version.etcd_index + 1, timeout=timeout
817
+ )
818
+ except etcd.EtcdCompareFailed:
819
+ logger.info("Join last-call TTL refresh CAS unsuccessful, will retry")
820
+ cas_delay()
821
+ active_version, state = self.get_rdzv_state()
822
+
823
+ def set_closed(self):
824
+ """
825
+ Mark rendezvous 'closed' for current run_id, which is used to signal other
826
+ participants to not attempt to perform (re-)rendezvous. This is useful
827
+ when one of the workers decides the job is complete.
828
+ """
829
+ while True:
830
+ active_version, state = self.get_rdzv_state()
831
+
832
+ if state["status"] == "closed":
833
+ # Already closed by someone else.
834
+ return
835
+
836
+ state["status"] = "closed"
837
+ try:
838
+ self.client.test_and_set(
839
+ key=self.get_path("/rdzv/active_version"),
840
+ value=json.dumps(state),
841
+ prev_value=active_version.value,
842
+ )
843
+ return
844
+
845
+ except etcd.EtcdCompareFailed:
846
+ logger.info("Set closed CAS unsuccessful, retrying")
847
+ cas_delay()
848
+
849
+ def get_rdzv_state(self):
850
+ active_version = self.client.get(key=self.get_path("/rdzv/active_version"))
851
+ return active_version, json.loads(active_version.value)
852
+
853
+ def try_wait_for_state_change(self, etcd_index, timeout=None):
854
+ # Don't sleep past the overall deadline (at least more than by 1s)
855
+ overall_timeout = max(self._rendezvous_deadline - time.time(), 0.0) + 1.0
856
+ timeout = overall_timeout if timeout is None else min(timeout, overall_timeout)
857
+
858
+ try:
859
+ self.client.watch(
860
+ self.get_path("/rdzv/active_version"), index=etcd_index, timeout=timeout
861
+ )
862
+ except (etcd.EtcdEventIndexCleared, etcd.EtcdWatchTimedOut):
863
+ pass
864
+
865
+ if time.time() > self._rendezvous_deadline:
866
+ raise RendezvousTimeoutError
867
+
868
+ # Unfortunately, we have to do another fetch in order to get last etcd_index.
869
+ return self.get_rdzv_state()
870
+
871
+ def get_path(self, path):
872
+ if not path.startswith("/"):
873
+ path = "/" + path
874
+
875
+ return f"{self._prefix}run_{self._run_id}{path}"
876
+
877
+ def create_path_if_not_exists(self, full_path, ttl=None):
878
+ try:
879
+ self.client.write(
880
+ key=full_path, value=None, dir=True, prevExist=False, ttl=ttl
881
+ )
882
+ except etcd.EtcdAlreadyExist:
883
+ pass
884
+
885
+ def setup_lease_renewal(self, full_path, ttl):
886
+ # NOTE: For ephemeral key TTL renewal (~lease) to work correctly,
887
+ # make sure you don't call any long-blocking methods that do not
888
+ # release the Python's GIL! An example of this is calling a pybind11
889
+ # extension function that is blocking / long-running, but is not
890
+ # doing a scoped release of the GIL.
891
+ def lease_worker(client, path, ttl, stop_event):
892
+ while True:
893
+ try:
894
+ client.refresh(path, ttl=ttl)
895
+ except etcd.EtcdKeyNotFound:
896
+ break
897
+ except ConnectionRefusedError:
898
+ # This error usually occurs during test when the server already got terminated but the
899
+ # python garbage collector have not yet invoked the __del__ method.
900
+ break
901
+
902
+ if stop_event.wait(timeout=ttl / 2):
903
+ break
904
+
905
+ lease_stop_event = threading.Event()
906
+ lease_thread = threading.Thread(
907
+ target=lease_worker, args=(self.client, full_path, ttl, lease_stop_event)
908
+ )
909
+
910
+ lease_thread.daemon = True
911
+ lease_thread.start()
912
+
913
+ return lease_stop_event
914
+
915
+ def store_extra_data(self, rdzv_version, key, value):
916
+ node = self.get_path(f"/rdzv/v_{rdzv_version}/extra_data")
917
+ try:
918
+ # If first time we are storing anything:
919
+ extra_data = self.client.write(
920
+ key=node, value=json.dumps({key: value}), prevExist=False
921
+ )
922
+ return
923
+ except etcd.EtcdAlreadyExist:
924
+ pass
925
+
926
+ # CAS loop, to make sure we don't lose concurrent stores.
927
+ while True:
928
+ # We never delete extra_data. Failure here should be fatal, no special handling.
929
+ extra_data = self.client.get(node)
930
+
931
+ new_extra_data_value = json.loads(extra_data.value)
932
+ new_extra_data_value[key] = value
933
+
934
+ try:
935
+ extra_data = self.client.test_and_set(
936
+ key=node,
937
+ value=json.dumps(new_extra_data_value),
938
+ prev_value=extra_data.value,
939
+ )
940
+ return
941
+ except etcd.EtcdCompareFailed:
942
+ logger.info("Store extra_data CAS unsuccessful, retrying")
943
+ time.sleep(0.1)
944
+
945
+ def load_extra_data(self, rdzv_version, key, timeout=None):
946
+ # 'extra_data' node itself, and the directory it is located in:
947
+ node = self.get_path(f"/rdzv/v_{rdzv_version}/extra_data")
948
+ node_dir = self.get_path(f"/rdzv/v_{rdzv_version}")
949
+
950
+ # TODO: implement timeout
951
+ # https://github.com/pytorch/elastic/issues/12
952
+ while True:
953
+ # Combined wait for the node itself, and the key inside it.
954
+ root = self.client.get(node_dir)
955
+
956
+ # Find the extra_data node, if it exists
957
+ extra_data = [n for n in root.children if n.key == node]
958
+ assert len(extra_data) <= 1
959
+
960
+ # Node for extra_data exists, check the desired key inside it.
961
+ if len(extra_data) == 1:
962
+ extra_data_dict = json.loads(extra_data[0].value)
963
+ if key in extra_data_dict:
964
+ return extra_data_dict[key]
965
+
966
+ # The 'extra_data' node doesn't exist, or they key isn't published yet.
967
+ # Wait for interesting events on the extra_data node and retry.
968
+ try:
969
+ self.client.watch(node, index=root.etcd_index + 1)
970
+ except (etcd.EtcdEventIndexCleared, etcd.EtcdWatchTimedOut):
971
+ pass
972
+
973
+ def setup_kv_store(self, rdzv_version):
974
+ store_path = self.get_path(f"/rdzv/v_{rdzv_version}/kv")
975
+ self.create_path_if_not_exists(store_path)
976
+ return EtcdStore(etcd_client=self.client, etcd_store_prefix=store_path)
977
+
978
+
979
+ def _create_etcd_client(params: RendezvousParameters) -> etcd.Client:
980
+ """Create a new ``etcd.Client`` from the specified ``RendezvousParameters``."""
981
+ hostname, port = parse_rendezvous_endpoint(params.endpoint, 2379)
982
+
983
+ # The communication protocol
984
+ protocol = params.config.get("protocol")
985
+ if protocol is None:
986
+ protocol = "http"
987
+ else:
988
+ if protocol != "http" and protocol != "https":
989
+ raise ValueError("The etcd protocol must be HTTP or HTTPS.")
990
+
991
+ # The SSL client certificate
992
+ ssl_cert = params.config.get("cert")
993
+ if ssl_cert is not None:
994
+ cert_key = params.config.get("key")
995
+ if cert_key is not None:
996
+ # The etcd client expects the certificate key as the second element
997
+ # of the `cert` tuple.
998
+ ssl_cert = (ssl_cert, cert_key)
999
+
1000
+ # The root certificate
1001
+ ca_cert = params.config.get("cacert")
1002
+
1003
+ return etcd.Client(
1004
+ hostname,
1005
+ port,
1006
+ protocol=protocol,
1007
+ cert=ssl_cert,
1008
+ ca_cert=ca_cert,
1009
+ allow_reconnect=True,
1010
+ )
1011
+
1012
+
1013
+ # Handler for torch.distributed "static" registration
1014
+ def create_rdzv_handler(params: RendezvousParameters) -> RendezvousHandler:
1015
+ """
1016
+ Usage:
1017
+
1018
+ ::
1019
+
1020
+ rdzv_params = RendezvousParameters(
1021
+ backend="etcd",
1022
+ endpoint="192.168.0.42:2379",
1023
+ run_id="123",
1024
+ min_nodes=4,
1025
+ max_nodes=8,
1026
+ timeout=300,
1027
+ last_call_timeout=30,
1028
+ etcd_prefix="custom_prefix",
1029
+ protocol="https",
1030
+ cacert="/etc/kubernetes/certs/ca.crt",
1031
+ cert="/etc/kubernetes/certs/client.crt",
1032
+ key="/etc/kubernetes/certs/client.key")
1033
+ # -- or --
1034
+ rdzv_params = RendezvousParameters(
1035
+ backend="etcd",
1036
+ endpoint="192.168.0.42:2379",
1037
+ run_id="123",
1038
+ min_nodes=4,
1039
+ max_nodes=8)
1040
+
1041
+ etcd_rdzv_handler = create_etcd_rendezvous_handler(rdzv_params)
1042
+
1043
+
1044
+ Where:
1045
+ run_id - unique id for this training job instance,
1046
+ min_nodes - min number of workers expected to join the rendezvous,
1047
+ max_nodes - max number of workers allowed to join the rendezvous,
1048
+ defaults to min_workers is not specified.
1049
+ timeout - total timeout within which next_rendezvous is expected to
1050
+ succeed; a RendezvousTimeoutError is raised otherwise;
1051
+ Defaults is 600 (10 minutes).
1052
+ last_call_timeout - additional wait amount ("last call") after
1053
+ min number of workers has been reached.
1054
+ Defaults to 30 seconds.
1055
+ etcd_prefix - path prefix (from etcd root), inside which all
1056
+ etcd nodes will be created.
1057
+ Default is "/torchelastic/p2p".
1058
+ protocol - http (default) or https to access etcd.
1059
+ cacert - CA cert to access etcd, only makes sense with https.
1060
+ cert - client cert to access etcd, only makes sense with https.
1061
+ key - client key to access etcd, only makes sense with https.
1062
+ """
1063
+ client = _create_etcd_client(params)
1064
+
1065
+ etcd_prefix = params.get("etcd_prefix", "/torchelastic/p2p")
1066
+
1067
+ rdzv = EtcdRendezvous(
1068
+ client=client,
1069
+ prefix=etcd_prefix,
1070
+ run_id=params.run_id,
1071
+ num_min_workers=params.min_nodes,
1072
+ num_max_workers=params.max_nodes,
1073
+ timeout=params.get_as_int("timeout", _DEFAULT_TIMEOUT),
1074
+ last_call_timeout=params.get_as_int(
1075
+ "last_call_timeout", _DEFAULT_LAST_CALL_TIMEOUT
1076
+ ),
1077
+ )
1078
+ return EtcdRendezvousHandler(
1079
+ rdzv_impl=rdzv,
1080
+ local_addr=params.local_addr,
1081
+ )
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/etcd_rendezvous_backend.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
8
+ import binascii
9
+ from base64 import b64decode, b64encode
10
+ from typing import cast, Optional
11
+
12
+ import urllib3.exceptions # type: ignore[import]
13
+
14
+
15
+ try:
16
+ import etcd # type: ignore[import]
17
+ except ModuleNotFoundError:
18
+ from . import _etcd_stub as etcd
19
+
20
+ from torch.distributed import Store
21
+
22
+ from .api import RendezvousConnectionError, RendezvousParameters, RendezvousStateError
23
+ from .dynamic_rendezvous import RendezvousBackend, Token
24
+ from .etcd_store import EtcdStore
25
+ from .utils import parse_rendezvous_endpoint
26
+
27
+
28
+ class EtcdRendezvousBackend(RendezvousBackend):
29
+ """Represents an etcd-based rendezvous backend.
30
+
31
+ Args:
32
+ client:
33
+ The ``etcd.Client`` instance to use to communicate with etcd.
34
+ run_id:
35
+ The run id of the rendezvous.
36
+ key_prefix:
37
+ The path under which to store the rendezvous state in etcd.
38
+ ttl:
39
+ The TTL of the rendezvous state. If not specified, defaults to two hours.
40
+ """
41
+
42
+ _DEFAULT_TTL = 7200 # 2 hours
43
+
44
+ _client: etcd.Client
45
+ _key: str
46
+ _ttl: int
47
+
48
+ def __init__(
49
+ self,
50
+ client: etcd.Client,
51
+ run_id: str,
52
+ key_prefix: Optional[str] = None,
53
+ ttl: Optional[int] = None,
54
+ ) -> None:
55
+ if not run_id:
56
+ raise ValueError("The run id must be a non-empty string.")
57
+
58
+ self._client = client
59
+
60
+ if key_prefix:
61
+ self._key = key_prefix + "/" + run_id
62
+ else:
63
+ self._key = run_id
64
+
65
+ if ttl and ttl > 0:
66
+ self._ttl = ttl
67
+ else:
68
+ self._ttl = self._DEFAULT_TTL
69
+
70
+ @property
71
+ def name(self) -> str:
72
+ """See base class."""
73
+ return "etcd-v2"
74
+
75
+ def get_state(self) -> Optional[tuple[bytes, Token]]:
76
+ """See base class."""
77
+ try:
78
+ result = self._client.read(self._key)
79
+ except etcd.EtcdKeyNotFound:
80
+ return None
81
+ except (etcd.EtcdException, urllib3.exceptions.TimeoutError) as exc:
82
+ raise RendezvousConnectionError(
83
+ "The connection to etcd has failed. See inner exception for details."
84
+ ) from exc
85
+
86
+ return self._decode_state(result)
87
+
88
+ def set_state(
89
+ self, state: bytes, token: Optional[Token] = None
90
+ ) -> Optional[tuple[bytes, Token, bool]]:
91
+ """See base class."""
92
+ base64_state = b64encode(state).decode()
93
+
94
+ kwargs = {}
95
+
96
+ def get_state():
97
+ result = self.get_state()
98
+ if result is not None:
99
+ tmp = *result, False
100
+ # Python 3.6 does not support tuple unpacking in return
101
+ # statements.
102
+ return tmp
103
+ return None
104
+
105
+ if token:
106
+ try:
107
+ token = int(token)
108
+ except ValueError:
109
+ return get_state()
110
+
111
+ if token:
112
+ kwargs["prevIndex"] = token
113
+ else:
114
+ kwargs["prevExist"] = False
115
+
116
+ try:
117
+ result = self._client.write(self._key, base64_state, self._ttl, **kwargs)
118
+ except (etcd.EtcdAlreadyExist, etcd.EtcdCompareFailed):
119
+ result = None
120
+ except (etcd.EtcdException, urllib3.exceptions.TimeoutError) as exc:
121
+ raise RendezvousConnectionError(
122
+ "The connection to etcd has failed. See inner exception for details."
123
+ ) from exc
124
+
125
+ if result is None:
126
+ return get_state()
127
+
128
+ tmp = *self._decode_state(result), True
129
+ return tmp
130
+
131
+ def _decode_state(self, result: etcd.EtcdResult) -> tuple[bytes, Token]:
132
+ base64_state = result.value.encode()
133
+
134
+ try:
135
+ state = b64decode(base64_state)
136
+ except binascii.Error as exc:
137
+ raise RendezvousStateError(
138
+ "The state object is corrupt. See inner exception for details."
139
+ ) from exc
140
+
141
+ return state, result.modifiedIndex
142
+
143
+
144
+ def _create_etcd_client(params: RendezvousParameters) -> etcd.Client:
145
+ host, port = parse_rendezvous_endpoint(params.endpoint, default_port=2379)
146
+
147
+ # The timeout
148
+ read_timeout = cast(int, params.get_as_int("read_timeout", 60))
149
+ if read_timeout <= 0:
150
+ raise ValueError("The read timeout must be a positive integer.")
151
+
152
+ # The communication protocol
153
+ protocol = params.get("protocol", "http").strip().lower()
154
+ if protocol != "http" and protocol != "https":
155
+ raise ValueError("The protocol must be HTTP or HTTPS.")
156
+
157
+ # The SSL client certificate
158
+ ssl_cert = params.get("ssl_cert")
159
+ if ssl_cert:
160
+ ssl_cert_key = params.get("ssl_cert_key")
161
+ if ssl_cert_key:
162
+ # The etcd client expects the certificate key as the second element
163
+ # of the `cert` tuple.
164
+ ssl_cert = (ssl_cert, ssl_cert_key)
165
+
166
+ # The root certificate
167
+ ca_cert = params.get("ca_cert")
168
+
169
+ try:
170
+ return etcd.Client(
171
+ host,
172
+ port,
173
+ read_timeout=read_timeout,
174
+ protocol=protocol,
175
+ cert=ssl_cert,
176
+ ca_cert=ca_cert,
177
+ allow_reconnect=True,
178
+ )
179
+ except (etcd.EtcdException, urllib3.exceptions.TimeoutError) as exc:
180
+ raise RendezvousConnectionError(
181
+ "The connection to etcd has failed. See inner exception for details."
182
+ ) from exc
183
+
184
+
185
+ def create_backend(params: RendezvousParameters) -> tuple[EtcdRendezvousBackend, Store]:
186
+ """Create a new :py:class:`EtcdRendezvousBackend` from the specified parameters.
187
+
188
+ +--------------+-----------------------------------------------------------+
189
+ | Parameter | Description |
190
+ +==============+===========================================================+
191
+ | read_timeout | The read timeout, in seconds, for etcd operations. |
192
+ | | Defaults to 60 seconds. |
193
+ +--------------+-----------------------------------------------------------+
194
+ | protocol | The protocol to use to communicate with etcd. Valid |
195
+ | | values are "http" and "https". Defaults to "http". |
196
+ +--------------+-----------------------------------------------------------+
197
+ | ssl_cert | The path to the SSL client certificate to use along with |
198
+ | | HTTPS. Defaults to ``None``. |
199
+ +--------------+-----------------------------------------------------------+
200
+ | ssl_cert_key | The path to the private key of the SSL client certificate |
201
+ | | to use along with HTTPS. Defaults to ``None``. |
202
+ +--------------+-----------------------------------------------------------+
203
+ | ca_cert | The path to the rool SSL authority certificate. Defaults |
204
+ | | to ``None``. |
205
+ +--------------+-----------------------------------------------------------+
206
+ """
207
+ client = _create_etcd_client(params)
208
+
209
+ backend = EtcdRendezvousBackend(
210
+ client, params.run_id, key_prefix="/torch/elastic/rendezvous"
211
+ )
212
+
213
+ store = EtcdStore(client, "/torch/elastic/store")
214
+
215
+ return backend, store
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/etcd_server.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # mypy: allow-untyped-defs
3
+
4
+ # Copyright (c) Facebook, Inc. and its affiliates.
5
+ # All rights reserved.
6
+ #
7
+ # This source code is licensed under the BSD-style license found in the
8
+ # LICENSE file in the root directory of this source tree.
9
+ import atexit
10
+ import logging
11
+ import os
12
+ import shlex
13
+ import shutil
14
+ import socket
15
+ import subprocess
16
+ import tempfile
17
+ import time
18
+ from typing import Optional, TextIO, Union
19
+
20
+
21
+ try:
22
+ import etcd # type: ignore[import]
23
+ except ModuleNotFoundError:
24
+ pass
25
+
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+
30
+ def find_free_port():
31
+ """
32
+ Find a free port and binds a temporary socket to it so that the port can be "reserved" until used.
33
+
34
+ .. note:: the returned socket must be closed before using the port,
35
+ otherwise a ``address already in use`` error will happen.
36
+ The socket should be held and closed as close to the
37
+ consumer of the port as possible since otherwise, there
38
+ is a greater chance of race-condition where a different
39
+ process may see the port as being free and take it.
40
+
41
+ Returns: a socket binded to the reserved free port
42
+
43
+ Usage::
44
+
45
+ sock = find_free_port()
46
+ port = sock.getsockname()[1]
47
+ sock.close()
48
+ use_port(port)
49
+ """
50
+ addrs = socket.getaddrinfo(
51
+ host="localhost", port=None, family=socket.AF_UNSPEC, type=socket.SOCK_STREAM
52
+ )
53
+
54
+ for addr in addrs:
55
+ family, type, proto, _, _ = addr
56
+ try:
57
+ s = socket.socket(family, type, proto)
58
+ s.bind(("localhost", 0))
59
+ s.listen(0)
60
+ return s
61
+ except OSError as e:
62
+ s.close() # type: ignore[possibly-undefined]
63
+ print(f"Socket creation attempt failed: {e}")
64
+ raise RuntimeError("Failed to create a socket")
65
+
66
+
67
+ def stop_etcd(subprocess, data_dir: Optional[str] = None):
68
+ if subprocess and subprocess.poll() is None:
69
+ logger.info("stopping etcd server")
70
+ subprocess.terminate()
71
+ subprocess.wait()
72
+
73
+ if data_dir:
74
+ logger.info("deleting etcd data dir: %s", data_dir)
75
+ shutil.rmtree(data_dir, ignore_errors=True)
76
+
77
+
78
+ class EtcdServer:
79
+ """
80
+ .. note:: tested on etcd server v3.4.3.
81
+
82
+ Starts and stops a local standalone etcd server on a random free
83
+ port. Useful for single node, multi-worker launches or testing,
84
+ where a sidecar etcd server is more convenient than having to
85
+ separately setup an etcd server.
86
+
87
+ This class registers a termination handler to shutdown the etcd
88
+ subprocess on exit. This termination handler is NOT a substitute for
89
+ calling the ``stop()`` method.
90
+
91
+ The following fallback mechanism is used to find the etcd binary:
92
+
93
+ 1. Uses env var TORCHELASTIC_ETCD_BINARY_PATH
94
+ 2. Uses ``<this file root>/bin/etcd`` if one exists
95
+ 3. Uses ``etcd`` from ``PATH``
96
+
97
+ Usage
98
+ ::
99
+
100
+ server = EtcdServer("/usr/bin/etcd", 2379, "/tmp/default.etcd")
101
+ server.start()
102
+ client = server.get_client()
103
+ # use client
104
+ server.stop()
105
+
106
+ Args:
107
+ etcd_binary_path: path of etcd server binary (see above for fallback path)
108
+ """
109
+
110
+ def __init__(self, data_dir: Optional[str] = None):
111
+ self._port = -1
112
+ self._host = "localhost"
113
+
114
+ root = os.path.dirname(__file__)
115
+ default_etcd_bin = os.path.join(root, "bin/etcd")
116
+ self._etcd_binary_path = os.environ.get(
117
+ "TORCHELASTIC_ETCD_BINARY_PATH", default_etcd_bin
118
+ )
119
+ if not os.path.isfile(self._etcd_binary_path):
120
+ self._etcd_binary_path = "etcd"
121
+
122
+ self._base_data_dir = (
123
+ data_dir if data_dir else tempfile.mkdtemp(prefix="torchelastic_etcd_data")
124
+ )
125
+ self._etcd_cmd = None
126
+ self._etcd_proc: Optional[subprocess.Popen] = None
127
+
128
+ def _get_etcd_server_process(self) -> subprocess.Popen:
129
+ if not self._etcd_proc:
130
+ raise RuntimeError(
131
+ "No etcd server process started. Call etcd_server.start() first"
132
+ )
133
+ else:
134
+ return self._etcd_proc
135
+
136
+ def get_port(self) -> int:
137
+ """Return the port the server is running on."""
138
+ return self._port
139
+
140
+ def get_host(self) -> str:
141
+ """Return the host the server is running on."""
142
+ return self._host
143
+
144
+ def get_endpoint(self) -> str:
145
+ """Return the etcd server endpoint (host:port)."""
146
+ return f"{self._host}:{self._port}"
147
+
148
+ def start(
149
+ self,
150
+ timeout: int = 60,
151
+ num_retries: int = 3,
152
+ stderr: Union[int, TextIO, None] = None,
153
+ ) -> None:
154
+ """
155
+ Start the server, and waits for it to be ready. When this function returns the sever is ready to take requests.
156
+
157
+ Args:
158
+ timeout: time (in seconds) to wait for the server to be ready
159
+ before giving up.
160
+ num_retries: number of retries to start the server. Each retry
161
+ will wait for max ``timeout`` before considering it as failed.
162
+ stderr: the standard error file handle. Valid values are
163
+ `subprocess.PIPE`, `subprocess.DEVNULL`, an existing file
164
+ descriptor (a positive integer), an existing file object, and
165
+ `None`.
166
+
167
+ Raises:
168
+ TimeoutError: if the server is not ready within the specified timeout
169
+ """
170
+ curr_retries = 0
171
+ while True:
172
+ try:
173
+ data_dir = os.path.join(self._base_data_dir, str(curr_retries))
174
+ os.makedirs(data_dir, exist_ok=True)
175
+ return self._start(data_dir, timeout, stderr)
176
+ except Exception as e:
177
+ curr_retries += 1
178
+ stop_etcd(self._etcd_proc)
179
+ logger.warning(
180
+ "Failed to start etcd server, got error: %s, retrying", str(e)
181
+ )
182
+ if curr_retries >= num_retries:
183
+ shutil.rmtree(self._base_data_dir, ignore_errors=True)
184
+ raise
185
+ atexit.register(stop_etcd, self._etcd_proc, self._base_data_dir)
186
+
187
+ def _start(
188
+ self, data_dir: str, timeout: int = 60, stderr: Union[int, TextIO, None] = None
189
+ ) -> None:
190
+ sock = find_free_port()
191
+ sock_peer = find_free_port()
192
+ self._port = sock.getsockname()[1]
193
+ peer_port = sock_peer.getsockname()[1]
194
+
195
+ etcd_cmd = shlex.split(
196
+ " ".join(
197
+ [
198
+ self._etcd_binary_path,
199
+ "--enable-v2",
200
+ "--data-dir",
201
+ data_dir,
202
+ "--listen-client-urls",
203
+ f"http://{self._host}:{self._port}",
204
+ "--advertise-client-urls",
205
+ f"http://{self._host}:{self._port}",
206
+ "--listen-peer-urls",
207
+ f"http://{self._host}:{peer_port}",
208
+ ]
209
+ )
210
+ )
211
+
212
+ logger.info("Starting etcd server: [%s]", etcd_cmd)
213
+
214
+ sock.close()
215
+ sock_peer.close()
216
+ self._etcd_proc = subprocess.Popen(etcd_cmd, close_fds=True, stderr=stderr)
217
+ self._wait_for_ready(timeout)
218
+
219
+ def get_client(self):
220
+ """Return an etcd client object that can be used to make requests to this server."""
221
+ return etcd.Client(
222
+ host=self._host, port=self._port, version_prefix="/v2", read_timeout=10
223
+ )
224
+
225
+ def _wait_for_ready(self, timeout: int = 60) -> None:
226
+ client = etcd.Client(
227
+ host=f"{self._host}", port=self._port, version_prefix="/v2", read_timeout=5
228
+ )
229
+ max_time = time.time() + timeout
230
+
231
+ while time.time() < max_time:
232
+ if self._get_etcd_server_process().poll() is not None:
233
+ # etcd server process finished
234
+ exitcode = self._get_etcd_server_process().returncode
235
+ raise RuntimeError(
236
+ f"Etcd server process exited with the code: {exitcode}"
237
+ )
238
+ try:
239
+ logger.info("etcd server ready. version: %s", client.version)
240
+ return
241
+ except Exception:
242
+ time.sleep(1)
243
+ raise TimeoutError("Timed out waiting for etcd server to be ready!")
244
+
245
+ def stop(self) -> None:
246
+ """Stop the server and cleans up auto generated resources (e.g. data dir)."""
247
+ logger.info("EtcdServer stop method called")
248
+ stop_etcd(self._etcd_proc, self._base_data_dir)
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/etcd_store.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
8
+ import datetime
9
+ import random
10
+ import time
11
+ from base64 import b64decode, b64encode
12
+ from typing import Optional
13
+
14
+ # pyre-ignore[21]: Could not find name `Store` in `torch.distributed`.
15
+ from torch.distributed import Store
16
+
17
+
18
+ try:
19
+ import etcd # type: ignore[import]
20
+ except ModuleNotFoundError:
21
+ from . import _etcd_stub as etcd
22
+
23
+
24
+ # Delay (sleep) for a small random amount to reduce CAS failures.
25
+ # This does not affect correctness, but will reduce requests to etcd server.
26
+ def cas_delay():
27
+ time.sleep(random.uniform(0, 0.1))
28
+
29
+
30
+ # pyre-fixme[11]: Annotation `Store` is not defined as a type.
31
+ class EtcdStore(Store):
32
+ """
33
+ Implement a c10 Store interface by piggybacking on the rendezvous etcd instance.
34
+
35
+ This is the store object returned by ``EtcdRendezvous``.
36
+ """
37
+
38
+ def __init__(
39
+ self,
40
+ etcd_client,
41
+ etcd_store_prefix,
42
+ # Default timeout same as in c10d/Store.hpp
43
+ timeout: Optional[datetime.timedelta] = None,
44
+ ):
45
+ super().__init__() # required for pybind trampoline.
46
+
47
+ self.client = etcd_client
48
+ self.prefix = etcd_store_prefix
49
+
50
+ if timeout is not None:
51
+ self.set_timeout(timeout)
52
+
53
+ if not self.prefix.endswith("/"):
54
+ self.prefix += "/"
55
+
56
+ def set(self, key, value):
57
+ """
58
+ Write a key/value pair into ``EtcdStore``.
59
+
60
+ Both key and value may be either Python ``str`` or ``bytes``.
61
+ """
62
+ self.client.set(key=self.prefix + self._encode(key), value=self._encode(value))
63
+
64
+ def get(self, key) -> bytes:
65
+ """
66
+ Get a value by key, possibly doing a blocking wait.
67
+
68
+ If key is not immediately present, will do a blocking wait
69
+ for at most ``timeout`` duration or until the key is published.
70
+
71
+
72
+ Returns:
73
+ value ``(bytes)``
74
+
75
+ Raises:
76
+ LookupError - If key still not published after timeout
77
+ """
78
+ b64_key = self.prefix + self._encode(key)
79
+ kvs = self._try_wait_get([b64_key])
80
+
81
+ if kvs is None:
82
+ raise LookupError(f"Key {key} not found in EtcdStore")
83
+
84
+ return self._decode(kvs[b64_key])
85
+
86
+ def add(self, key, num: int) -> int:
87
+ """
88
+ Atomically increment a value by an integer amount.
89
+
90
+ The integer is represented as a string using base 10. If key is not present,
91
+ a default value of ``0`` will be assumed.
92
+
93
+ Returns:
94
+ the new (incremented) value
95
+
96
+
97
+ """
98
+ b64_key = self._encode(key)
99
+ # c10d Store assumes value is an integer represented as a decimal string
100
+ try:
101
+ # Assume default value "0", if this key didn't yet:
102
+ node = self.client.write(
103
+ key=self.prefix + b64_key,
104
+ value=self._encode(str(num)), # i.e. 0 + num
105
+ prevExist=False,
106
+ )
107
+ return int(self._decode(node.value))
108
+ except etcd.EtcdAlreadyExist:
109
+ pass
110
+
111
+ while True:
112
+ # Note: c10d Store does not have a method to delete keys, so we
113
+ # can be sure it's still there.
114
+ node = self.client.get(key=self.prefix + b64_key)
115
+ new_value = self._encode(str(int(self._decode(node.value)) + num))
116
+ try:
117
+ node = self.client.test_and_set(
118
+ key=node.key, value=new_value, prev_value=node.value
119
+ )
120
+ return int(self._decode(node.value))
121
+ except etcd.EtcdCompareFailed:
122
+ cas_delay()
123
+
124
+ def wait(self, keys, override_timeout: Optional[datetime.timedelta] = None):
125
+ """
126
+ Wait until all of the keys are published, or until timeout.
127
+
128
+ Raises:
129
+ LookupError - if timeout occurs
130
+ """
131
+ b64_keys = [self.prefix + self._encode(key) for key in keys]
132
+ kvs = self._try_wait_get(b64_keys, override_timeout)
133
+ if kvs is None:
134
+ raise LookupError("Timeout while waiting for keys in EtcdStore")
135
+ # No return value on success
136
+
137
+ def check(self, keys) -> bool:
138
+ """Check if all of the keys are immediately present (without waiting)."""
139
+ b64_keys = [self.prefix + self._encode(key) for key in keys]
140
+ kvs = self._try_wait_get(
141
+ b64_keys,
142
+ override_timeout=datetime.timedelta(microseconds=1), # as if no wait
143
+ )
144
+ return kvs is not None
145
+
146
+ #
147
+ # Encode key/value data in base64, so we can store arbitrary binary data
148
+ # in EtcdStore. Input can be `str` or `bytes`.
149
+ # In case of `str`, utf-8 encoding is assumed.
150
+ #
151
+ def _encode(self, value) -> str:
152
+ if type(value) == bytes:
153
+ return b64encode(value).decode()
154
+ elif type(value) == str:
155
+ return b64encode(value.encode()).decode()
156
+ raise ValueError("Value must be of type str or bytes")
157
+
158
+ #
159
+ # Decode a base64 string (of type `str` or `bytes`).
160
+ # Return type is `bytes`, which is more convenient with the Store interface.
161
+ #
162
+ def _decode(self, value) -> bytes:
163
+ if type(value) == bytes:
164
+ return b64decode(value)
165
+ elif type(value) == str:
166
+ return b64decode(value.encode())
167
+ raise ValueError("Value must be of type str or bytes")
168
+
169
+ #
170
+ # Get all of the (base64-encoded) etcd keys at once, or wait until all the keys
171
+ # are published or timeout occurs.
172
+ # This is a helper method for the public interface methods.
173
+ #
174
+ # On success, a dictionary of {etcd key -> etcd value} is returned.
175
+ # On timeout, None is returned.
176
+ #
177
+ def _try_wait_get(self, b64_keys, override_timeout=None):
178
+ timeout = self.timeout if override_timeout is None else override_timeout # type: ignore[attr-defined]
179
+ deadline = time.time() + timeout.total_seconds()
180
+
181
+ while True:
182
+ # Read whole directory (of keys), filter only the ones waited for
183
+ all_nodes = None
184
+ try:
185
+ all_nodes = self.client.get(key=self.prefix)
186
+ req_nodes = {
187
+ node.key: node.value
188
+ for node in all_nodes.children
189
+ if node.key in b64_keys
190
+ }
191
+
192
+ if len(req_nodes) == len(b64_keys):
193
+ # All keys are available
194
+ return req_nodes
195
+ except etcd.EtcdKeyNotFound:
196
+ pass
197
+
198
+ watch_timeout = deadline - time.time()
199
+ if watch_timeout <= 0:
200
+ return None
201
+
202
+ try:
203
+ index = all_nodes.etcd_index + 1 if all_nodes else 0
204
+ self.client.watch(
205
+ key=self.prefix,
206
+ recursive=True,
207
+ timeout=watch_timeout,
208
+ index=index,
209
+ )
210
+ except etcd.EtcdWatchTimedOut:
211
+ if time.time() >= deadline:
212
+ return None
213
+ else:
214
+ continue
215
+ except etcd.EtcdEventIndexCleared:
216
+ continue
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/registry.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import logging
8
+ import sys
9
+
10
+ from .api import (
11
+ rendezvous_handler_registry as handler_registry,
12
+ RendezvousHandler,
13
+ RendezvousParameters,
14
+ )
15
+ from .dynamic_rendezvous import create_handler
16
+
17
+
18
+ if sys.version_info < (3, 10):
19
+ from importlib_metadata import entry_points
20
+ else:
21
+ from importlib.metadata import entry_points
22
+
23
+ log = logging.getLogger(__name__)
24
+
25
+ __all__ = ["get_rendezvous_handler"]
26
+
27
+
28
+ def _create_static_handler(params: RendezvousParameters) -> RendezvousHandler:
29
+ from . import static_tcp_rendezvous
30
+
31
+ return static_tcp_rendezvous.create_rdzv_handler(params)
32
+
33
+
34
+ def _create_etcd_handler(params: RendezvousParameters) -> RendezvousHandler:
35
+ from . import etcd_rendezvous
36
+
37
+ return etcd_rendezvous.create_rdzv_handler(params)
38
+
39
+
40
+ def _create_etcd_v2_handler(params: RendezvousParameters) -> RendezvousHandler:
41
+ from .etcd_rendezvous_backend import create_backend
42
+
43
+ backend, store = create_backend(params)
44
+
45
+ return create_handler(store, backend, params)
46
+
47
+
48
+ def _create_c10d_handler(params: RendezvousParameters) -> RendezvousHandler:
49
+ from .c10d_rendezvous_backend import create_backend
50
+
51
+ backend, store = create_backend(params)
52
+
53
+ return create_handler(store, backend, params)
54
+
55
+
56
+ def _register_default_handlers() -> None:
57
+ handler_registry.register("etcd", _create_etcd_handler)
58
+ handler_registry.register("etcd-v2", _create_etcd_v2_handler)
59
+ handler_registry.register("c10d", _create_c10d_handler)
60
+ handler_registry.register("static", _create_static_handler)
61
+
62
+
63
+ def _register_out_of_tree_handlers() -> None:
64
+ discovered_handler_generators = entry_points(group="torchrun.handlers")
65
+
66
+ for handler_generator in discovered_handler_generators:
67
+ try:
68
+ get_handler = discovered_handler_generators[handler_generator.name].load()
69
+ handler_registry.register(handler_generator.name, get_handler())
70
+ except Exception:
71
+ log.warning(
72
+ "Exception while registering out of tree plugin %s: ",
73
+ handler_generator.name,
74
+ exc_info=True,
75
+ )
76
+
77
+
78
+ def get_rendezvous_handler(params: RendezvousParameters) -> RendezvousHandler:
79
+ """
80
+ Obtain a reference to a :py:class`RendezvousHandler`.
81
+
82
+ Custom rendezvous handlers can be registered by
83
+
84
+ ::
85
+
86
+ from torch.distributed.elastic.rendezvous import rendezvous_handler_registry
87
+ from torch.distributed.elastic.rendezvous.registry import get_rendezvous_handler
88
+
89
+
90
+ def create_my_rdzv(params: RendezvousParameters):
91
+ return MyCustomRdzv(params)
92
+
93
+
94
+ rendezvous_handler_registry.register("my_rdzv_backend_name", create_my_rdzv)
95
+
96
+ my_rdzv_handler = get_rendezvous_handler(
97
+ "my_rdzv_backend_name", RendezvousParameters
98
+ )
99
+ """
100
+ return handler_registry.create_handler(params)