euler-connector 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- euler_connector/__init__.py +39 -0
- euler_connector/_log.py +33 -0
- euler_connector/channel.py +119 -0
- euler_connector/connector.py +181 -0
- euler_connector/env.py +130 -0
- euler_connector/envelope.py +115 -0
- euler_connector/identity.py +59 -0
- euler_connector/integrations/__init__.py +1 -0
- euler_connector/integrations/tqdm.py +57 -0
- euler_connector/progress.py +268 -0
- euler_connector/py.typed +0 -0
- euler_connector/throttle.py +39 -0
- euler_connector/transports/__init__.py +17 -0
- euler_connector/transports/base.py +35 -0
- euler_connector/transports/callback.py +24 -0
- euler_connector/transports/file.py +74 -0
- euler_connector/transports/http.py +213 -0
- euler_connector/transports/memory.py +39 -0
- euler_connector-0.1.0.dist-info/METADATA +123 -0
- euler_connector-0.1.0.dist-info/RECORD +23 -0
- euler_connector-0.1.0.dist-info/WHEEL +5 -0
- euler_connector-0.1.0.dist-info/licenses/LICENSE +21 -0
- euler_connector-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""euler-connector — how the euler-* packages talk to euler-view.
|
|
2
|
+
|
|
3
|
+
One source of truth for the connection: the launch environment euler-view
|
|
4
|
+
sets, which process speaks for a job, the record envelope, and the
|
|
5
|
+
transports that carry records (a file on the shared filesystem everywhere;
|
|
6
|
+
HTTP where compute nodes reach the app). Domain modules build on it:
|
|
7
|
+
|
|
8
|
+
* ``euler_connector.progress`` — structured progress of a run (schema 1).
|
|
9
|
+
|
|
10
|
+
The protocol is in ``docs/protocol.md``.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from importlib.metadata import PackageNotFoundError as _PackageNotFoundError
|
|
14
|
+
from importlib.metadata import version as _version
|
|
15
|
+
|
|
16
|
+
try:
|
|
17
|
+
__version__ = _version("euler-connector")
|
|
18
|
+
except _PackageNotFoundError: # an unpacked source tree
|
|
19
|
+
__version__ = "0+unknown"
|
|
20
|
+
|
|
21
|
+
from .channel import StateChannel # noqa: E402
|
|
22
|
+
from .connector import Connector, connect, current, set_current # noqa: E402
|
|
23
|
+
from .env import LaunchEnvironment # noqa: E402
|
|
24
|
+
from .envelope import PROTOCOL_VERSION, Envelope, EnvelopeError # noqa: E402
|
|
25
|
+
from .identity import ProcessIdentity # noqa: E402
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"PROTOCOL_VERSION",
|
|
29
|
+
"Connector",
|
|
30
|
+
"Envelope",
|
|
31
|
+
"EnvelopeError",
|
|
32
|
+
"LaunchEnvironment",
|
|
33
|
+
"ProcessIdentity",
|
|
34
|
+
"StateChannel",
|
|
35
|
+
"__version__",
|
|
36
|
+
"connect",
|
|
37
|
+
"current",
|
|
38
|
+
"set_current",
|
|
39
|
+
]
|
euler_connector/_log.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Quiet, bounded diagnostics: the connector must never flood a job's log."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
from typing import Dict
|
|
9
|
+
|
|
10
|
+
logger = logging.getLogger("euler_connector")
|
|
11
|
+
|
|
12
|
+
_lock = threading.Lock()
|
|
13
|
+
_seen: Dict[str, float] = {}
|
|
14
|
+
#: The same message is repeated at most once per this many seconds.
|
|
15
|
+
REPEAT_AFTER_SEC = 300.0
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def warn_once(message: str, *, key: str = "", repeat_after: float = REPEAT_AFTER_SEC) -> None:
|
|
19
|
+
"""Log a warning, but the same ``key`` (default: the message) at most once per ``repeat_after`` seconds."""
|
|
20
|
+
marker = key or message
|
|
21
|
+
now = time.monotonic()
|
|
22
|
+
with _lock:
|
|
23
|
+
last = _seen.get(marker)
|
|
24
|
+
if last is not None and now - last < repeat_after:
|
|
25
|
+
return
|
|
26
|
+
_seen[marker] = now
|
|
27
|
+
logger.warning("euler-connector: %s", message)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def reset() -> None:
|
|
31
|
+
"""Forget what was logged (tests)."""
|
|
32
|
+
with _lock:
|
|
33
|
+
_seen.clear()
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Channels: named streams of records, each with its own payload schema.
|
|
2
|
+
|
|
3
|
+
A ``StateChannel`` carries a value whose *latest* state is what matters
|
|
4
|
+
(progress today; a status or a heartbeat later). Further kinds (an event
|
|
5
|
+
channel that keeps every record) can sit next to it on the same transports.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import threading
|
|
12
|
+
import time
|
|
13
|
+
from typing import Any, Callable, Hashable, Mapping, Optional, Sequence
|
|
14
|
+
|
|
15
|
+
from ._log import warn_once
|
|
16
|
+
from .envelope import Envelope, utc_timestamp, validate_channel_name
|
|
17
|
+
from .identity import ProcessIdentity
|
|
18
|
+
from .throttle import Throttle
|
|
19
|
+
from .transports.base import Transport
|
|
20
|
+
|
|
21
|
+
_UNSET = object()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class StateChannel:
|
|
25
|
+
"""The latest value of something, published to every transport, throttled.
|
|
26
|
+
|
|
27
|
+
``publish(data, key=…)`` sends ``data`` when the throttle allows: at most
|
|
28
|
+
one record per interval, and at once (after a short gap) when ``key``
|
|
29
|
+
changes, i.e. at a boundary such as the next task or epoch. A value the
|
|
30
|
+
throttle holds back is not lost: ``close()`` writes the last one.
|
|
31
|
+
|
|
32
|
+
Thread-safe. A no-op once closed and in a forked child (the parent owns
|
|
33
|
+
the transports).
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
name: str,
|
|
39
|
+
*,
|
|
40
|
+
schema: int,
|
|
41
|
+
transports: Sequence[Transport],
|
|
42
|
+
identity: ProcessIdentity,
|
|
43
|
+
launch_id: Optional[str],
|
|
44
|
+
interval: float,
|
|
45
|
+
clock: Callable[[], float] = time.monotonic,
|
|
46
|
+
) -> None:
|
|
47
|
+
self.name = validate_channel_name(name)
|
|
48
|
+
self.schema = schema
|
|
49
|
+
self._transports = list(transports)
|
|
50
|
+
self._identity = identity
|
|
51
|
+
self._launch_id = launch_id
|
|
52
|
+
self._throttle = Throttle(interval)
|
|
53
|
+
self._clock = clock
|
|
54
|
+
self._lock = threading.Lock()
|
|
55
|
+
self._seq = 0
|
|
56
|
+
self._key: Any = _UNSET
|
|
57
|
+
self._held: Optional[Mapping[str, Any]] = None
|
|
58
|
+
self._closed = False
|
|
59
|
+
self._pid = os.getpid()
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def enabled(self) -> bool:
|
|
63
|
+
return bool(self._transports) and not self._closed and os.getpid() == self._pid
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def interval(self) -> float:
|
|
67
|
+
return self._throttle.interval
|
|
68
|
+
|
|
69
|
+
def publish(self, data: Mapping[str, Any], *, key: Hashable = None, force: bool = False) -> bool:
|
|
70
|
+
"""Offer the channel's new value; True when it was written now."""
|
|
71
|
+
if not self.enabled:
|
|
72
|
+
return False
|
|
73
|
+
try:
|
|
74
|
+
with self._lock:
|
|
75
|
+
if self._closed:
|
|
76
|
+
return False
|
|
77
|
+
now = self._clock()
|
|
78
|
+
boundary = key != self._key
|
|
79
|
+
self._key = key
|
|
80
|
+
if not self._throttle.should_write(now, boundary=boundary, force=force):
|
|
81
|
+
self._held = data
|
|
82
|
+
return False
|
|
83
|
+
self._write(data, now)
|
|
84
|
+
return True
|
|
85
|
+
except Exception as error: # noqa: BLE001 - publishing never breaks the run
|
|
86
|
+
warn_once(f"{self.name}: cannot publish: {error}", key=f"publish:{self.name}")
|
|
87
|
+
return False
|
|
88
|
+
|
|
89
|
+
def close(self, final: Optional[Mapping[str, Any]] = None) -> None:
|
|
90
|
+
"""Write ``final`` (else the last value the throttle held back), then stop. Idempotent."""
|
|
91
|
+
if os.getpid() != self._pid:
|
|
92
|
+
return
|
|
93
|
+
with self._lock:
|
|
94
|
+
if self._closed:
|
|
95
|
+
return
|
|
96
|
+
data = final if final is not None else self._held
|
|
97
|
+
try:
|
|
98
|
+
if data is not None and self._transports:
|
|
99
|
+
self._write(data, self._clock())
|
|
100
|
+
except Exception as error: # noqa: BLE001
|
|
101
|
+
warn_once(f"{self.name}: cannot write the final record: {error}", key=f"close:{self.name}")
|
|
102
|
+
self._closed = True
|
|
103
|
+
|
|
104
|
+
def _write(self, data: Mapping[str, Any], now: float) -> None:
|
|
105
|
+
self._seq += 1
|
|
106
|
+
envelope = Envelope(
|
|
107
|
+
channel=self.name,
|
|
108
|
+
schema=self.schema,
|
|
109
|
+
seq=self._seq,
|
|
110
|
+
ts=utc_timestamp(),
|
|
111
|
+
data=dict(data),
|
|
112
|
+
launch_id=self._launch_id,
|
|
113
|
+
attempt=self._identity.attempt,
|
|
114
|
+
rank=self._identity.rank,
|
|
115
|
+
)
|
|
116
|
+
self._held = None
|
|
117
|
+
self._throttle.mark_written(now)
|
|
118
|
+
for transport in self._transports:
|
|
119
|
+
transport.publish(envelope)
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""The connector: one per process, the single way an euler-* package talks to euler-view.
|
|
2
|
+
|
|
3
|
+
It reads the launch environment once, knows which process speaks (only
|
|
4
|
+
rank 0 does), owns the transports and hands out channels. Packages use a
|
|
5
|
+
domain module on top (``euler_connector.progress``) rather than channels.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import atexit
|
|
11
|
+
import os
|
|
12
|
+
import threading
|
|
13
|
+
import time
|
|
14
|
+
from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence
|
|
15
|
+
|
|
16
|
+
from . import __version__
|
|
17
|
+
from .channel import StateChannel
|
|
18
|
+
from .env import LaunchEnvironment
|
|
19
|
+
from .identity import ProcessIdentity
|
|
20
|
+
from .transports.base import Transport
|
|
21
|
+
from .transports.file import FileTransport
|
|
22
|
+
from .transports.http import HttpTransport
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Connector:
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
*,
|
|
29
|
+
environment: LaunchEnvironment,
|
|
30
|
+
identity: ProcessIdentity,
|
|
31
|
+
transports: Sequence[Transport],
|
|
32
|
+
clock: Callable[[], float] = time.monotonic,
|
|
33
|
+
) -> None:
|
|
34
|
+
self.environment = environment
|
|
35
|
+
self.identity = identity
|
|
36
|
+
# Only the global rank 0 speaks for a job.
|
|
37
|
+
self._transports: List[Transport] = list(transports) if identity.is_primary else []
|
|
38
|
+
self._clock = clock
|
|
39
|
+
self._channels: Dict[str, StateChannel] = {}
|
|
40
|
+
self._lock = threading.Lock()
|
|
41
|
+
self._closed = False
|
|
42
|
+
self._pid = os.getpid()
|
|
43
|
+
|
|
44
|
+
@classmethod
|
|
45
|
+
def from_environment(
|
|
46
|
+
cls,
|
|
47
|
+
environ: Optional[Mapping[str, str]] = None,
|
|
48
|
+
*,
|
|
49
|
+
extra_transports: Sequence[Transport] = (),
|
|
50
|
+
) -> "Connector":
|
|
51
|
+
"""The transports the launch environment allows (none outside euler-view)."""
|
|
52
|
+
environment = LaunchEnvironment.from_environ(environ)
|
|
53
|
+
identity = ProcessIdentity.detect(environ)
|
|
54
|
+
transports: List[Transport] = []
|
|
55
|
+
if environment.mode != "off":
|
|
56
|
+
if environment.file_enabled and environment.connector_dir is not None:
|
|
57
|
+
transports.append(FileTransport(environment.connector_dir))
|
|
58
|
+
if environment.http_enabled and environment.base_url and environment.token:
|
|
59
|
+
transports.append(
|
|
60
|
+
HttpTransport(environment.base_url, environment.token, user_agent=f"euler-connector/{__version__}")
|
|
61
|
+
)
|
|
62
|
+
transports.extend(extra_transports)
|
|
63
|
+
return cls(environment=environment, identity=identity, transports=transports)
|
|
64
|
+
|
|
65
|
+
@classmethod
|
|
66
|
+
def disabled(cls) -> "Connector":
|
|
67
|
+
"""A connector that accepts every call and sends nothing."""
|
|
68
|
+
return cls(environment=LaunchEnvironment(mode="off"), identity=ProcessIdentity.detect(), transports=[])
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def enabled(self) -> bool:
|
|
72
|
+
return bool(self._transports) and not self._closed and os.getpid() == self._pid
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def launch_id(self) -> Optional[str]:
|
|
76
|
+
return self.environment.launch_id
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def transports(self) -> tuple:
|
|
80
|
+
return tuple(self._transports)
|
|
81
|
+
|
|
82
|
+
def state_channel(self, name: str, *, schema: int = 1, interval: Optional[float] = None) -> StateChannel:
|
|
83
|
+
"""The state channel ``name`` (one per name and process)."""
|
|
84
|
+
with self._lock:
|
|
85
|
+
channel = self._channels.get(name)
|
|
86
|
+
if channel is None:
|
|
87
|
+
channel = StateChannel(
|
|
88
|
+
name,
|
|
89
|
+
schema=schema,
|
|
90
|
+
transports=self._transports if self.enabled else [],
|
|
91
|
+
identity=self.identity,
|
|
92
|
+
launch_id=self.launch_id,
|
|
93
|
+
interval=self.environment.interval_sec if interval is None else interval,
|
|
94
|
+
clock=self._clock,
|
|
95
|
+
)
|
|
96
|
+
self._channels[name] = channel
|
|
97
|
+
elif channel.schema != schema:
|
|
98
|
+
raise ValueError(f"channel {name!r} is open with schema {channel.schema}, not {schema}")
|
|
99
|
+
return channel
|
|
100
|
+
|
|
101
|
+
def describe(self) -> Dict[str, Any]:
|
|
102
|
+
"""What this connector does (diagnostics; no secrets)."""
|
|
103
|
+
return {
|
|
104
|
+
"version": __version__,
|
|
105
|
+
"enabled": self.enabled,
|
|
106
|
+
"launchId": self.launch_id,
|
|
107
|
+
"rank": self.identity.rank,
|
|
108
|
+
"attempt": self.identity.attempt,
|
|
109
|
+
"mode": self.environment.mode,
|
|
110
|
+
"transports": [{"name": t.name, "healthy": t.healthy} for t in self._transports],
|
|
111
|
+
"channels": sorted(self._channels),
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
def close(self, timeout: float = 2.0) -> None:
|
|
115
|
+
"""Write every channel's last value and deliver what is left, waiting at most ``timeout`` seconds."""
|
|
116
|
+
if os.getpid() != self._pid:
|
|
117
|
+
return
|
|
118
|
+
with self._lock:
|
|
119
|
+
if self._closed:
|
|
120
|
+
return
|
|
121
|
+
channels = list(self._channels.values())
|
|
122
|
+
self._closed = True
|
|
123
|
+
for channel in channels:
|
|
124
|
+
channel.close()
|
|
125
|
+
deadline = self._clock() + max(0.0, timeout)
|
|
126
|
+
for transport in self._transports:
|
|
127
|
+
transport.close(max(0.0, deadline - self._clock()))
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
# ---------------------------------------------------------------------------
|
|
131
|
+
# The process's connector
|
|
132
|
+
|
|
133
|
+
_current: Optional[Connector] = None
|
|
134
|
+
_current_lock = threading.Lock()
|
|
135
|
+
#: True in a process forked from one that imported the connector (a DataLoader worker).
|
|
136
|
+
_forked_child = False
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def connect(environ: Optional[Mapping[str, str]] = None) -> Connector:
|
|
140
|
+
"""The process's connector, created from the environment on first use.
|
|
141
|
+
|
|
142
|
+
A forked child gets a disabled connector: its parent speaks for the job.
|
|
143
|
+
"""
|
|
144
|
+
global _current
|
|
145
|
+
with _current_lock:
|
|
146
|
+
if _current is None:
|
|
147
|
+
_current = Connector.disabled() if _forked_child else Connector.from_environment(environ)
|
|
148
|
+
return _current
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def current() -> Connector:
|
|
152
|
+
return connect()
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def set_current(connector: Optional[Connector]) -> Optional[Connector]:
|
|
156
|
+
"""Replace the process's connector (tests, applications that build their own); returns the previous one."""
|
|
157
|
+
global _current
|
|
158
|
+
with _current_lock:
|
|
159
|
+
previous, _current = _current, connector
|
|
160
|
+
return previous
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _close_current() -> None:
|
|
164
|
+
connector = _current
|
|
165
|
+
if connector is not None:
|
|
166
|
+
connector.close(timeout=2.0)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _after_fork_in_child() -> None:
|
|
170
|
+
# A forked child (a DataLoader worker) must not reuse the parent's
|
|
171
|
+
# transports or threads, nor build its own: it stays disabled. The lock
|
|
172
|
+
# is replaced, as another thread may have held it at the fork.
|
|
173
|
+
global _current, _current_lock, _forked_child
|
|
174
|
+
_forked_child = True
|
|
175
|
+
_current_lock = threading.Lock()
|
|
176
|
+
_current = Connector.disabled()
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
atexit.register(_close_current)
|
|
180
|
+
if hasattr(os, "register_at_fork"):
|
|
181
|
+
os.register_at_fork(after_in_child=_after_fork_in_child)
|
euler_connector/env.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""The launch environment euler-view sets for a job.
|
|
2
|
+
|
|
3
|
+
This is the contract between euler-view and every euler-* package: which
|
|
4
|
+
variables say where a process belongs and how it may reach euler-view
|
|
5
|
+
(``docs/protocol.md``). Nothing else in the package reads the environment.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Mapping, Optional
|
|
14
|
+
|
|
15
|
+
from ._log import warn_once
|
|
16
|
+
|
|
17
|
+
#: The launch this process belongs to (a UUID). Set by euler-view.
|
|
18
|
+
LAUNCH_ID = "EULER_LAUNCH_ID"
|
|
19
|
+
#: A directory on the shared filesystem for the file transport. Set by euler-view.
|
|
20
|
+
CONNECTOR_DIR = "EULER_CONNECTOR_DIR"
|
|
21
|
+
#: euler-view's base URL. Set only where compute nodes may reach the app.
|
|
22
|
+
BASE_URL = "EULER_VIEW_BASE_URL"
|
|
23
|
+
#: The launch's connector token, when not in ``<EULER_CONNECTOR_DIR>/token``.
|
|
24
|
+
TOKEN = "EULER_CONNECTOR_TOKEN"
|
|
25
|
+
#: A file holding the token (default: ``<EULER_CONNECTOR_DIR>/token``).
|
|
26
|
+
TOKEN_FILE = "EULER_CONNECTOR_TOKEN_FILE"
|
|
27
|
+
#: ``auto`` (default: every transport the environment allows), ``file``, ``http`` or ``off``.
|
|
28
|
+
MODE = "EULER_CONNECTOR_MODE"
|
|
29
|
+
#: Seconds between two records of one channel (default 10, at least 1).
|
|
30
|
+
INTERVAL = "EULER_CONNECTOR_INTERVAL"
|
|
31
|
+
|
|
32
|
+
#: Every variable of the contract, for documentation and tests.
|
|
33
|
+
VARIABLES = (LAUNCH_ID, CONNECTOR_DIR, BASE_URL, TOKEN, TOKEN_FILE, MODE, INTERVAL)
|
|
34
|
+
|
|
35
|
+
TOKEN_FILENAME = "token"
|
|
36
|
+
DEFAULT_INTERVAL_SEC = 10.0
|
|
37
|
+
MIN_INTERVAL_SEC = 1.0
|
|
38
|
+
MODES = ("auto", "file", "http", "off")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class LaunchEnvironment:
|
|
43
|
+
"""What euler-view told this process (all optional: outside euler-view nothing is set)."""
|
|
44
|
+
|
|
45
|
+
launch_id: Optional[str] = None
|
|
46
|
+
connector_dir: Optional[Path] = None
|
|
47
|
+
base_url: Optional[str] = None
|
|
48
|
+
token: Optional[str] = None
|
|
49
|
+
mode: str = "auto"
|
|
50
|
+
interval_sec: float = DEFAULT_INTERVAL_SEC
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def file_enabled(self) -> bool:
|
|
54
|
+
"""Records go to ``connector_dir`` (euler-view reads them over SSH)."""
|
|
55
|
+
return self.mode in ("auto", "file") and self.connector_dir is not None
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def http_enabled(self) -> bool:
|
|
59
|
+
"""Records go to euler-view over HTTP (the node reaches the app and holds a token)."""
|
|
60
|
+
return self.mode in ("auto", "http") and bool(self.base_url) and bool(self.token)
|
|
61
|
+
|
|
62
|
+
@classmethod
|
|
63
|
+
def from_environ(cls, environ: Optional[Mapping[str, str]] = None) -> "LaunchEnvironment":
|
|
64
|
+
env = os.environ if environ is None else environ
|
|
65
|
+
connector_dir = _path(env.get(CONNECTOR_DIR))
|
|
66
|
+
return cls(
|
|
67
|
+
launch_id=_text(env.get(LAUNCH_ID)),
|
|
68
|
+
connector_dir=connector_dir,
|
|
69
|
+
base_url=_base_url(env.get(BASE_URL)),
|
|
70
|
+
token=_token(env, connector_dir),
|
|
71
|
+
mode=_mode(env.get(MODE)),
|
|
72
|
+
interval_sec=_interval(env.get(INTERVAL)),
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _text(value: Optional[str]) -> Optional[str]:
|
|
77
|
+
if value is None:
|
|
78
|
+
return None
|
|
79
|
+
value = value.strip()
|
|
80
|
+
return value or None
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _path(value: Optional[str]) -> Optional[Path]:
|
|
84
|
+
text = _text(value)
|
|
85
|
+
return Path(text).expanduser() if text else None
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _base_url(value: Optional[str]) -> Optional[str]:
|
|
89
|
+
text = _text(value)
|
|
90
|
+
if not text:
|
|
91
|
+
return None
|
|
92
|
+
if not text.startswith(("http://", "https://")):
|
|
93
|
+
warn_once(f"{BASE_URL} must start with http:// or https://; ignoring {text!r}")
|
|
94
|
+
return None
|
|
95
|
+
return text.rstrip("/")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _token(env: Mapping[str, str], connector_dir: Optional[Path]) -> Optional[str]:
|
|
99
|
+
direct = _text(env.get(TOKEN))
|
|
100
|
+
if direct:
|
|
101
|
+
return direct
|
|
102
|
+
path = _path(env.get(TOKEN_FILE)) or (connector_dir / TOKEN_FILENAME if connector_dir else None)
|
|
103
|
+
if path is None:
|
|
104
|
+
return None
|
|
105
|
+
try:
|
|
106
|
+
return _text(path.read_text(encoding="utf-8"))
|
|
107
|
+
except FileNotFoundError:
|
|
108
|
+
return None
|
|
109
|
+
except OSError as error:
|
|
110
|
+
warn_once(f"cannot read the connector token at {path}: {error}")
|
|
111
|
+
return None
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _mode(value: Optional[str]) -> str:
|
|
115
|
+
text = (_text(value) or "auto").lower()
|
|
116
|
+
if text not in MODES:
|
|
117
|
+
warn_once(f"{MODE}={text!r} is not one of {', '.join(MODES)}; using auto")
|
|
118
|
+
return "auto"
|
|
119
|
+
return text
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _interval(value: Optional[str]) -> float:
|
|
123
|
+
text = _text(value)
|
|
124
|
+
if not text:
|
|
125
|
+
return DEFAULT_INTERVAL_SEC
|
|
126
|
+
try:
|
|
127
|
+
return max(MIN_INTERVAL_SEC, float(text))
|
|
128
|
+
except ValueError:
|
|
129
|
+
warn_once(f"{INTERVAL}={text!r} is not a number; using {DEFAULT_INTERVAL_SEC:g}")
|
|
130
|
+
return DEFAULT_INTERVAL_SEC
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""The envelope every record travels in (protocol version 1, ``docs/protocol.md``).
|
|
2
|
+
|
|
3
|
+
A channel (``progress`` today) owns the schema of ``data``; the envelope
|
|
4
|
+
says who wrote it, when, and in which order. Both transports carry the same
|
|
5
|
+
JSON: the file transport stores it, the HTTP transport posts it.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import dataclasses
|
|
11
|
+
import json
|
|
12
|
+
import math
|
|
13
|
+
import re
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from datetime import datetime, timezone
|
|
16
|
+
from pathlib import PurePath
|
|
17
|
+
from typing import Any, Dict, Mapping, Optional
|
|
18
|
+
|
|
19
|
+
PROTOCOL_VERSION = 1
|
|
20
|
+
#: Channel names: lowercase, start with a letter; dots group related channels (``run.metrics``).
|
|
21
|
+
CHANNEL_NAME = re.compile(r"^[a-z][a-z0-9_.-]{0,63}$")
|
|
22
|
+
#: One encoded envelope; a larger record is dropped (a channel holds a state, not a payload).
|
|
23
|
+
MAX_ENVELOPE_BYTES = 16 * 1024
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class EnvelopeError(ValueError):
|
|
27
|
+
"""An envelope that cannot be sent (bad channel name, too large, not JSON)."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def validate_channel_name(name: str) -> str:
|
|
31
|
+
if not isinstance(name, str) or not CHANNEL_NAME.match(name):
|
|
32
|
+
raise EnvelopeError(f"invalid channel name {name!r} (lowercase letters, digits, '_', '.', '-'; max 64)")
|
|
33
|
+
return name
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def utc_timestamp() -> str:
|
|
37
|
+
"""ISO-8601, UTC, milliseconds: ``2026-11-19T12:00:00.123Z``."""
|
|
38
|
+
return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class Envelope:
|
|
43
|
+
channel: str
|
|
44
|
+
#: Version of the channel's ``data`` schema.
|
|
45
|
+
schema: int
|
|
46
|
+
#: Increases with every envelope of one channel within one attempt.
|
|
47
|
+
seq: int
|
|
48
|
+
ts: str
|
|
49
|
+
data: Mapping[str, Any]
|
|
50
|
+
launch_id: Optional[str]
|
|
51
|
+
attempt: str
|
|
52
|
+
rank: int
|
|
53
|
+
|
|
54
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
55
|
+
return {
|
|
56
|
+
"v": PROTOCOL_VERSION,
|
|
57
|
+
"channel": self.channel,
|
|
58
|
+
"schema": self.schema,
|
|
59
|
+
"launchId": self.launch_id,
|
|
60
|
+
"attempt": self.attempt,
|
|
61
|
+
"rank": self.rank,
|
|
62
|
+
"seq": self.seq,
|
|
63
|
+
"ts": self.ts,
|
|
64
|
+
"data": dict(self.data),
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
def encode(self) -> str:
|
|
68
|
+
"""Compact JSON (NaN and infinities become null); raises ``EnvelopeError``
|
|
69
|
+
when it is not JSON or exceeds ``MAX_ENVELOPE_BYTES``."""
|
|
70
|
+
try:
|
|
71
|
+
text = json.dumps(
|
|
72
|
+
_finite_tree(self.to_dict()), separators=(",", ":"), default=json_default, allow_nan=False
|
|
73
|
+
)
|
|
74
|
+
except (TypeError, ValueError) as error:
|
|
75
|
+
raise EnvelopeError(f"{self.channel} record is not JSON: {error}") from error
|
|
76
|
+
if len(text.encode("utf-8")) > MAX_ENVELOPE_BYTES:
|
|
77
|
+
raise EnvelopeError(f"{self.channel} record is larger than {MAX_ENVELOPE_BYTES} bytes")
|
|
78
|
+
return text
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def json_default(value: Any) -> Any:
|
|
82
|
+
"""Make common scientific values JSON: numpy/torch scalars and arrays, paths, dataclasses."""
|
|
83
|
+
if hasattr(value, "item") and callable(value.item):
|
|
84
|
+
try:
|
|
85
|
+
return finite(value.item())
|
|
86
|
+
except (TypeError, ValueError):
|
|
87
|
+
pass
|
|
88
|
+
if hasattr(value, "tolist") and callable(value.tolist):
|
|
89
|
+
return value.tolist()
|
|
90
|
+
if isinstance(value, PurePath):
|
|
91
|
+
return str(value)
|
|
92
|
+
if dataclasses.is_dataclass(value) and not isinstance(value, type):
|
|
93
|
+
return dataclasses.asdict(value)
|
|
94
|
+
if isinstance(value, (set, frozenset, tuple)):
|
|
95
|
+
return list(value)
|
|
96
|
+
return str(value)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def finite(value: Any) -> Any:
|
|
100
|
+
"""``None`` for NaN and infinities (JSON has neither), the value otherwise."""
|
|
101
|
+
if isinstance(value, float) and (math.isnan(value) or math.isinf(value)):
|
|
102
|
+
return None
|
|
103
|
+
return value
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _finite_tree(value: Any, depth: int = 0) -> Any:
|
|
107
|
+
if depth > 32:
|
|
108
|
+
return None
|
|
109
|
+
if isinstance(value, float):
|
|
110
|
+
return finite(value)
|
|
111
|
+
if isinstance(value, dict):
|
|
112
|
+
return {key: _finite_tree(item, depth + 1) for key, item in value.items()}
|
|
113
|
+
if isinstance(value, (list, tuple)):
|
|
114
|
+
return [_finite_tree(item, depth + 1) for item in value]
|
|
115
|
+
return value
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Which process is speaking: its rank among the job's processes and its attempt."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import socket
|
|
7
|
+
import time
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import Mapping, Optional
|
|
10
|
+
|
|
11
|
+
#: Global-rank variables, most specific first (torchrun / accelerate, MPI, then SLURM's task id).
|
|
12
|
+
RANK_VARIABLES = ("RANK", "OMPI_COMM_WORLD_RANK", "PMI_RANK", "SLURM_PROCID")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class ProcessIdentity:
|
|
17
|
+
"""The speaking process.
|
|
18
|
+
|
|
19
|
+
``rank`` is the global rank (0 for a single process); only rank 0 speaks
|
|
20
|
+
for a job. ``attempt`` names one run of the process: a requeued or
|
|
21
|
+
restarted job is a new attempt, so its counters start over without
|
|
22
|
+
looking older than the previous attempt's.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
rank: int
|
|
26
|
+
attempt: str
|
|
27
|
+
pid: int
|
|
28
|
+
host: str
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def is_primary(self) -> bool:
|
|
32
|
+
return self.rank == 0
|
|
33
|
+
|
|
34
|
+
@classmethod
|
|
35
|
+
def detect(cls, environ: Optional[Mapping[str, str]] = None) -> "ProcessIdentity":
|
|
36
|
+
env = os.environ if environ is None else environ
|
|
37
|
+
pid = os.getpid()
|
|
38
|
+
host = socket.gethostname()
|
|
39
|
+
return cls(rank=global_rank(env), attempt=attempt_id(env, pid=pid, host=host), pid=pid, host=host)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def global_rank(environ: Optional[Mapping[str, str]] = None) -> int:
|
|
43
|
+
env = os.environ if environ is None else environ
|
|
44
|
+
for key in RANK_VARIABLES:
|
|
45
|
+
value = (env.get(key) or "").strip()
|
|
46
|
+
if value.isdigit():
|
|
47
|
+
return int(value)
|
|
48
|
+
return 0
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def attempt_id(environ: Optional[Mapping[str, str]] = None, *, pid: Optional[int] = None, host: Optional[str] = None) -> str:
|
|
52
|
+
"""``<job>.<step>.<restart>`` under SLURM, else ``<host>.<pid>.<start>``."""
|
|
53
|
+
env = os.environ if environ is None else environ
|
|
54
|
+
job = (env.get("SLURM_JOB_ID") or "").strip()
|
|
55
|
+
restart = (env.get("SLURM_RESTART_COUNT") or "0").strip() or "0"
|
|
56
|
+
if job:
|
|
57
|
+
step = (env.get("SLURM_STEP_ID") or "").strip()
|
|
58
|
+
return f"{job}.{step}.{restart}" if step else f"{job}.{restart}"
|
|
59
|
+
return f"{host or socket.gethostname()}.{pid if pid is not None else os.getpid()}.{int(time.time())}"
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Optional integrations with third-party libraries (imported only when used)."""
|