computeharbor-worker 0.2.4__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.
- computeharbor_worker/__init__.py +43 -0
- computeharbor_worker/batch_inference.py +303 -0
- computeharbor_worker/checkpoint.py +230 -0
- computeharbor_worker/client.py +262 -0
- computeharbor_worker/daemon.py +171 -0
- computeharbor_worker/models.py +62 -0
- computeharbor_worker/preemption.py +117 -0
- computeharbor_worker/storage.py +239 -0
- computeharbor_worker/supervisor.py +159 -0
- computeharbor_worker/trainer.py +305 -0
- computeharbor_worker-0.2.4.dist-info/METADATA +213 -0
- computeharbor_worker-0.2.4.dist-info/RECORD +16 -0
- computeharbor_worker-0.2.4.dist-info/WHEEL +5 -0
- computeharbor_worker-0.2.4.dist-info/entry_points.txt +4 -0
- computeharbor_worker-0.2.4.dist-info/licenses/LICENSE +21 -0
- computeharbor_worker-0.2.4.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import time
|
|
6
|
+
import urllib.error
|
|
7
|
+
import urllib.request
|
|
8
|
+
from datetime import UTC, datetime
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
_TRANSIENT_STATUS_CODES = frozenset({429, 500, 502, 503, 504})
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _is_transient_http_status(status_code: int) -> bool:
|
|
15
|
+
return status_code in _TRANSIENT_STATUS_CODES or 500 <= status_code < 600
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _parse_retry_after(exc: urllib.error.HTTPError) -> float | None:
|
|
19
|
+
if exc.headers is None:
|
|
20
|
+
return None
|
|
21
|
+
raw = exc.headers.get("Retry-After")
|
|
22
|
+
if raw is None:
|
|
23
|
+
return None
|
|
24
|
+
try:
|
|
25
|
+
delay = float(str(raw).strip())
|
|
26
|
+
except ValueError:
|
|
27
|
+
return None
|
|
28
|
+
return max(0.0, delay)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class ControlPlaneError(RuntimeError):
|
|
32
|
+
"""Raised when the ComputeHarbor control plane returns an HTTP error."""
|
|
33
|
+
|
|
34
|
+
def __init__(self, status_code: int, message: str) -> None:
|
|
35
|
+
self.status_code = status_code
|
|
36
|
+
self.message = message
|
|
37
|
+
super().__init__(f"Control plane HTTP {status_code}: {message}")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class ControlPlaneClient:
|
|
41
|
+
"""Stdlib HTTP/JSON client for the ComputeHarbor Go control plane."""
|
|
42
|
+
|
|
43
|
+
def __init__(
|
|
44
|
+
self,
|
|
45
|
+
base_url: str,
|
|
46
|
+
org_id: str,
|
|
47
|
+
timeout_sec: float = 5.0,
|
|
48
|
+
max_retries: int = 3,
|
|
49
|
+
backoff_base_sec: float = 0.05,
|
|
50
|
+
api_key: str | None = None,
|
|
51
|
+
) -> None:
|
|
52
|
+
if max_retries < 0:
|
|
53
|
+
raise ValueError("max_retries must be >= 0")
|
|
54
|
+
if backoff_base_sec < 0:
|
|
55
|
+
raise ValueError("backoff_base_sec must be >= 0")
|
|
56
|
+
self.base_url = base_url.rstrip("/")
|
|
57
|
+
self.org_id = org_id
|
|
58
|
+
self.timeout_sec = timeout_sec
|
|
59
|
+
self.max_retries = max_retries
|
|
60
|
+
self.backoff_base_sec = backoff_base_sec
|
|
61
|
+
self.api_key: str | None = (
|
|
62
|
+
api_key if api_key is not None else os.environ.get("COMPUTEHARBOR_API_KEY")
|
|
63
|
+
)
|
|
64
|
+
self.last_request_id: str | None = None
|
|
65
|
+
|
|
66
|
+
def _request(
|
|
67
|
+
self,
|
|
68
|
+
method: str,
|
|
69
|
+
path: str,
|
|
70
|
+
*,
|
|
71
|
+
payload: dict[str, Any] | None = None,
|
|
72
|
+
include_org_header: bool = True,
|
|
73
|
+
request_id: str | None = None,
|
|
74
|
+
) -> dict[str, Any]:
|
|
75
|
+
url = f"{self.base_url}{path}"
|
|
76
|
+
data: bytes | None = None
|
|
77
|
+
headers: dict[str, str] = {"Accept": "application/json"}
|
|
78
|
+
if self.api_key:
|
|
79
|
+
headers["Authorization"] = f"Bearer {self.api_key}"
|
|
80
|
+
if include_org_header:
|
|
81
|
+
headers["X-Org-ID"] = self.org_id
|
|
82
|
+
if request_id:
|
|
83
|
+
headers["X-Request-ID"] = request_id
|
|
84
|
+
if payload is not None:
|
|
85
|
+
data = json.dumps(payload).encode("utf-8")
|
|
86
|
+
headers["Content-Type"] = "application/json"
|
|
87
|
+
|
|
88
|
+
raw = ""
|
|
89
|
+
for attempt in range(self.max_retries + 1):
|
|
90
|
+
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
|
91
|
+
try:
|
|
92
|
+
with urllib.request.urlopen(req, timeout=self.timeout_sec) as resp:
|
|
93
|
+
self.last_request_id = (
|
|
94
|
+
resp.headers.get("X-Request-ID") if resp.headers is not None else None
|
|
95
|
+
)
|
|
96
|
+
raw = resp.read().decode("utf-8")
|
|
97
|
+
break
|
|
98
|
+
except urllib.error.HTTPError as exc:
|
|
99
|
+
if exc.headers is not None:
|
|
100
|
+
err_request_id = exc.headers.get("X-Request-ID")
|
|
101
|
+
if err_request_id is not None:
|
|
102
|
+
self.last_request_id = err_request_id
|
|
103
|
+
err_body = exc.read().decode("utf-8", errors="replace")
|
|
104
|
+
try:
|
|
105
|
+
parsed = json.loads(err_body)
|
|
106
|
+
msg = (
|
|
107
|
+
str(parsed.get("error", err_body))
|
|
108
|
+
if isinstance(parsed, dict)
|
|
109
|
+
else err_body
|
|
110
|
+
)
|
|
111
|
+
except json.JSONDecodeError:
|
|
112
|
+
msg = err_body
|
|
113
|
+
|
|
114
|
+
if not _is_transient_http_status(exc.code) or attempt >= self.max_retries:
|
|
115
|
+
raise ControlPlaneError(exc.code, msg) from exc
|
|
116
|
+
|
|
117
|
+
retry_after = _parse_retry_after(exc)
|
|
118
|
+
delay = (
|
|
119
|
+
retry_after
|
|
120
|
+
if retry_after is not None
|
|
121
|
+
else self.backoff_base_sec * (2**attempt)
|
|
122
|
+
)
|
|
123
|
+
if delay > 0:
|
|
124
|
+
time.sleep(delay)
|
|
125
|
+
except urllib.error.URLError:
|
|
126
|
+
if attempt >= self.max_retries:
|
|
127
|
+
raise
|
|
128
|
+
delay = self.backoff_base_sec * (2**attempt)
|
|
129
|
+
if delay > 0:
|
|
130
|
+
time.sleep(delay)
|
|
131
|
+
|
|
132
|
+
if not raw:
|
|
133
|
+
return {}
|
|
134
|
+
decoded = json.loads(raw)
|
|
135
|
+
if not isinstance(decoded, dict):
|
|
136
|
+
raise TypeError(
|
|
137
|
+
f"Expected JSON object response from {path}, got {type(decoded).__name__}"
|
|
138
|
+
)
|
|
139
|
+
return decoded
|
|
140
|
+
|
|
141
|
+
def healthz(self) -> dict[str, Any]:
|
|
142
|
+
"""Check control plane liveness via GET /healthz."""
|
|
143
|
+
return self._request("GET", "/healthz", include_org_header=False)
|
|
144
|
+
|
|
145
|
+
def readyz(self) -> dict[str, Any]:
|
|
146
|
+
"""Check control plane readiness via GET /readyz."""
|
|
147
|
+
return self._request("GET", "/readyz", include_org_header=False)
|
|
148
|
+
|
|
149
|
+
def submit_job(
|
|
150
|
+
self,
|
|
151
|
+
job_id: str,
|
|
152
|
+
gpu: str,
|
|
153
|
+
target_steps: int,
|
|
154
|
+
max_preemptions: int,
|
|
155
|
+
) -> dict[str, Any]:
|
|
156
|
+
"""Submit a new training job lease to the control plane."""
|
|
157
|
+
return self._request(
|
|
158
|
+
"POST",
|
|
159
|
+
"/v1/jobs",
|
|
160
|
+
payload={
|
|
161
|
+
"job_id": job_id,
|
|
162
|
+
"org_id": self.org_id,
|
|
163
|
+
"gpu": gpu,
|
|
164
|
+
"target_steps": target_steps,
|
|
165
|
+
"max_preemptions": max_preemptions,
|
|
166
|
+
},
|
|
167
|
+
include_org_header=False,
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
def assign_worker(self, job_id: str, worker_node_id: str) -> dict[str, Any]:
|
|
171
|
+
"""Assign a worker node to a queued or migrating job."""
|
|
172
|
+
return self._request(
|
|
173
|
+
"POST",
|
|
174
|
+
f"/v1/jobs/{job_id}/assign",
|
|
175
|
+
payload={"worker_node_id": worker_node_id},
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
def heartbeat(self, job_id: str, worker_node_id: str) -> dict[str, Any]:
|
|
179
|
+
"""Report a worker heartbeat for an active job lease."""
|
|
180
|
+
return self._request(
|
|
181
|
+
"POST",
|
|
182
|
+
f"/v1/jobs/{job_id}/heartbeat",
|
|
183
|
+
payload={"worker_node_id": worker_node_id},
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
def notify_sigterm(self, job_id: str) -> dict[str, Any]:
|
|
187
|
+
"""Notify the control plane that the active worker received SIGTERM."""
|
|
188
|
+
return self._request("POST", f"/v1/jobs/{job_id}/sigterm")
|
|
189
|
+
|
|
190
|
+
def commit_checkpoint(
|
|
191
|
+
self,
|
|
192
|
+
job_id: str,
|
|
193
|
+
step: int,
|
|
194
|
+
epoch: int,
|
|
195
|
+
loss: float,
|
|
196
|
+
safetensors_uri: str,
|
|
197
|
+
manifest_uri: str,
|
|
198
|
+
flush_latency_ms: int | float,
|
|
199
|
+
) -> dict[str, Any]:
|
|
200
|
+
"""Commit a flushed checkpoint reference for a job."""
|
|
201
|
+
flushed_at = datetime.now(UTC).isoformat().replace("+00:00", "Z")
|
|
202
|
+
return self._request(
|
|
203
|
+
"POST",
|
|
204
|
+
f"/v1/jobs/{job_id}/checkpoint",
|
|
205
|
+
payload={
|
|
206
|
+
"step": step,
|
|
207
|
+
"epoch": epoch,
|
|
208
|
+
"loss": loss,
|
|
209
|
+
"safetensors_uri": safetensors_uri,
|
|
210
|
+
"manifest_uri": manifest_uri,
|
|
211
|
+
"flushed_at": flushed_at,
|
|
212
|
+
"flush_latency_ms": int(round(flush_latency_ms)),
|
|
213
|
+
},
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
def get_job(self, job_id: str) -> dict[str, Any]:
|
|
217
|
+
"""Fetch current lease state for a job."""
|
|
218
|
+
return self._request("GET", f"/v1/jobs/{job_id}")
|
|
219
|
+
|
|
220
|
+
def schedule(
|
|
221
|
+
self,
|
|
222
|
+
*,
|
|
223
|
+
min_vram_gb: int,
|
|
224
|
+
gpu_count: int,
|
|
225
|
+
active_hours: float,
|
|
226
|
+
fee_fraction: float = 0.12,
|
|
227
|
+
exclude_gpus: list[str] | None = None,
|
|
228
|
+
) -> dict[str, Any]:
|
|
229
|
+
"""Select the best eligible spot GPU pool via POST /v1/schedule."""
|
|
230
|
+
payload: dict[str, Any] = {
|
|
231
|
+
"min_vram_gb": min_vram_gb,
|
|
232
|
+
"gpu_count": gpu_count,
|
|
233
|
+
"active_hours": active_hours,
|
|
234
|
+
"fee_fraction": fee_fraction,
|
|
235
|
+
}
|
|
236
|
+
if exclude_gpus is not None:
|
|
237
|
+
payload["exclude_gpus"] = exclude_gpus
|
|
238
|
+
return self._request(
|
|
239
|
+
"POST",
|
|
240
|
+
"/v1/schedule",
|
|
241
|
+
payload=payload,
|
|
242
|
+
include_org_header=False,
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
def barrier(
|
|
246
|
+
self,
|
|
247
|
+
job_id: str,
|
|
248
|
+
*,
|
|
249
|
+
world_size: int,
|
|
250
|
+
rank: int,
|
|
251
|
+
step: int,
|
|
252
|
+
) -> dict[str, Any]:
|
|
253
|
+
"""Coordinate a distributed ring-barrier step via POST /v1/jobs/{id}/barrier."""
|
|
254
|
+
return self._request(
|
|
255
|
+
"POST",
|
|
256
|
+
f"/v1/jobs/{job_id}/barrier",
|
|
257
|
+
payload={
|
|
258
|
+
"world_size": world_size,
|
|
259
|
+
"rank": rank,
|
|
260
|
+
"step": step,
|
|
261
|
+
},
|
|
262
|
+
)
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import os
|
|
5
|
+
import signal
|
|
6
|
+
import sys
|
|
7
|
+
import threading
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from computeharbor_worker.client import ControlPlaneClient, ControlPlaneError
|
|
11
|
+
from computeharbor_worker.models import LoRAConfig
|
|
12
|
+
from computeharbor_worker.preemption import MetadataPreemptionWatcher, MetadataProvider
|
|
13
|
+
from computeharbor_worker.storage import CheckpointStore, LocalMirrorObjectStore
|
|
14
|
+
from computeharbor_worker.trainer import LoRATrainer, RunResult
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _heartbeat_loop(
|
|
18
|
+
client: ControlPlaneClient,
|
|
19
|
+
job_id: str,
|
|
20
|
+
worker_node_id: str,
|
|
21
|
+
interval_sec: float,
|
|
22
|
+
stop_event: threading.Event,
|
|
23
|
+
) -> None:
|
|
24
|
+
"""Send periodic worker heartbeats until stop_event is signaled."""
|
|
25
|
+
while not stop_event.wait(interval_sec):
|
|
26
|
+
try:
|
|
27
|
+
client.heartbeat(job_id, worker_node_id)
|
|
28
|
+
except (ControlPlaneError, OSError):
|
|
29
|
+
if stop_event.is_set():
|
|
30
|
+
return
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def run_worker_daemon(
|
|
34
|
+
*,
|
|
35
|
+
client: ControlPlaneClient,
|
|
36
|
+
job_id: str,
|
|
37
|
+
worker_node_id: str,
|
|
38
|
+
checkpoint_dir: Path | str,
|
|
39
|
+
target_steps: int,
|
|
40
|
+
heartbeat_interval_sec: float = 0.5,
|
|
41
|
+
step_delay_sec: float = 0.0,
|
|
42
|
+
ready_file: Path | None = None,
|
|
43
|
+
remote_store: CheckpointStore | None = None,
|
|
44
|
+
config: LoRAConfig | None = None,
|
|
45
|
+
metadata_provider: MetadataProvider | None = None,
|
|
46
|
+
metadata_url: str | None = None,
|
|
47
|
+
metadata_poll_sec: float = 0.5,
|
|
48
|
+
max_checkpoints: int = 5,
|
|
49
|
+
api_key: str | None = None,
|
|
50
|
+
) -> RunResult:
|
|
51
|
+
"""Assign this worker to a job, stream heartbeats, train, and commit checkpoints."""
|
|
52
|
+
if api_key is not None:
|
|
53
|
+
client.api_key = api_key
|
|
54
|
+
ckpt_dir = Path(checkpoint_dir)
|
|
55
|
+
client.assign_worker(job_id, worker_node_id)
|
|
56
|
+
|
|
57
|
+
stop_event = threading.Event()
|
|
58
|
+
hb_thread = threading.Thread(
|
|
59
|
+
target=_heartbeat_loop,
|
|
60
|
+
args=(client, job_id, worker_node_id, heartbeat_interval_sec, stop_event),
|
|
61
|
+
name=f"heartbeat-{job_id}-{worker_node_id}",
|
|
62
|
+
daemon=True,
|
|
63
|
+
)
|
|
64
|
+
hb_thread.start()
|
|
65
|
+
|
|
66
|
+
watcher: MetadataPreemptionWatcher | None = None
|
|
67
|
+
if metadata_provider is not None:
|
|
68
|
+
watcher = MetadataPreemptionWatcher(
|
|
69
|
+
provider=metadata_provider,
|
|
70
|
+
metadata_url=metadata_url,
|
|
71
|
+
poll_interval_sec=metadata_poll_sec,
|
|
72
|
+
on_preempt=lambda: os.kill(os.getpid(), signal.SIGTERM),
|
|
73
|
+
)
|
|
74
|
+
watcher.start()
|
|
75
|
+
|
|
76
|
+
try:
|
|
77
|
+
trainer = LoRATrainer(
|
|
78
|
+
job_id=job_id,
|
|
79
|
+
config=config or LoRAConfig(),
|
|
80
|
+
checkpoint_dir=ckpt_dir,
|
|
81
|
+
remote_store=remote_store,
|
|
82
|
+
max_checkpoints=max_checkpoints,
|
|
83
|
+
)
|
|
84
|
+
result = trainer.train(
|
|
85
|
+
target_steps=target_steps,
|
|
86
|
+
step_delay_sec=step_delay_sec,
|
|
87
|
+
ready_file=ready_file,
|
|
88
|
+
)
|
|
89
|
+
finally:
|
|
90
|
+
if watcher is not None:
|
|
91
|
+
watcher.stop()
|
|
92
|
+
stop_event.set()
|
|
93
|
+
hb_thread.join(timeout=max(1.0, heartbeat_interval_sec * 2.0))
|
|
94
|
+
|
|
95
|
+
if result.summary.preempted:
|
|
96
|
+
client.notify_sigterm(job_id)
|
|
97
|
+
|
|
98
|
+
safetensors_name = str(result.summary.checkpoint_metadata.get("safetensors_filename", ""))
|
|
99
|
+
epoch = (
|
|
100
|
+
result.manifest.epoch
|
|
101
|
+
if result.manifest is not None
|
|
102
|
+
else result.summary.completed_step // 10
|
|
103
|
+
)
|
|
104
|
+
loss = result.summary.loss_history[-1] if result.summary.loss_history else 0.0
|
|
105
|
+
client.commit_checkpoint(
|
|
106
|
+
job_id=job_id,
|
|
107
|
+
step=result.summary.completed_step,
|
|
108
|
+
epoch=epoch,
|
|
109
|
+
loss=loss,
|
|
110
|
+
safetensors_uri=f"file://{ckpt_dir / safetensors_name}",
|
|
111
|
+
manifest_uri=f"file://{ckpt_dir / 'latest.json'}",
|
|
112
|
+
flush_latency_ms=int(round(result.summary.flush_duration_ms)),
|
|
113
|
+
)
|
|
114
|
+
return result
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def main(argv: list[str] | None = None) -> int:
|
|
118
|
+
"""CLI entrypoint for running the ComputeHarbor spot worker daemon."""
|
|
119
|
+
parser = argparse.ArgumentParser(description="ComputeHarbor Spot LoRA Worker Daemon")
|
|
120
|
+
parser.add_argument("--control-plane-url", required=True)
|
|
121
|
+
parser.add_argument("--org-id", required=True)
|
|
122
|
+
parser.add_argument("--job-id", required=True)
|
|
123
|
+
parser.add_argument("--worker-node-id", required=True)
|
|
124
|
+
parser.add_argument("--checkpoint-dir", required=True)
|
|
125
|
+
parser.add_argument("--target-steps", type=int, default=30)
|
|
126
|
+
parser.add_argument("--heartbeat-interval-sec", type=float, default=0.5)
|
|
127
|
+
parser.add_argument("--step-delay-sec", type=float, default=0.0)
|
|
128
|
+
parser.add_argument("--ready-file", default="")
|
|
129
|
+
parser.add_argument("--summary-out", default="")
|
|
130
|
+
parser.add_argument("--remote-store-dir", default="")
|
|
131
|
+
parser.add_argument("--metadata-provider", choices=["gcp", "aws"], default=None)
|
|
132
|
+
parser.add_argument("--metadata-url", default=None)
|
|
133
|
+
parser.add_argument("--metadata-poll-sec", type=float, default=0.5)
|
|
134
|
+
parser.add_argument("--max-checkpoints", type=int, default=5)
|
|
135
|
+
parser.add_argument("--api-key", default=None)
|
|
136
|
+
args = parser.parse_args(argv)
|
|
137
|
+
|
|
138
|
+
remote_store: CheckpointStore | None = (
|
|
139
|
+
LocalMirrorObjectStore(Path(args.remote_store_dir)) if args.remote_store_dir else None
|
|
140
|
+
)
|
|
141
|
+
client = ControlPlaneClient(
|
|
142
|
+
base_url=args.control_plane_url,
|
|
143
|
+
org_id=args.org_id,
|
|
144
|
+
api_key=args.api_key,
|
|
145
|
+
)
|
|
146
|
+
ready_path = Path(args.ready_file) if args.ready_file else None
|
|
147
|
+
result = run_worker_daemon(
|
|
148
|
+
client=client,
|
|
149
|
+
job_id=args.job_id,
|
|
150
|
+
worker_node_id=args.worker_node_id,
|
|
151
|
+
checkpoint_dir=Path(args.checkpoint_dir),
|
|
152
|
+
target_steps=args.target_steps,
|
|
153
|
+
heartbeat_interval_sec=args.heartbeat_interval_sec,
|
|
154
|
+
step_delay_sec=args.step_delay_sec,
|
|
155
|
+
ready_file=ready_path,
|
|
156
|
+
remote_store=remote_store,
|
|
157
|
+
metadata_provider=args.metadata_provider,
|
|
158
|
+
metadata_url=args.metadata_url,
|
|
159
|
+
metadata_poll_sec=args.metadata_poll_sec,
|
|
160
|
+
max_checkpoints=args.max_checkpoints,
|
|
161
|
+
)
|
|
162
|
+
output_json = result.summary.model_dump_json(indent=2)
|
|
163
|
+
if args.summary_out:
|
|
164
|
+
Path(args.summary_out).write_text(output_json, encoding="utf-8")
|
|
165
|
+
else:
|
|
166
|
+
sys.stdout.write(output_json + "\n")
|
|
167
|
+
return 0
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
if __name__ == "__main__":
|
|
171
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from datetime import UTC, datetime
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class LoRAConfig(BaseModel):
|
|
10
|
+
model_config = ConfigDict(frozen=True, extra="forbid")
|
|
11
|
+
|
|
12
|
+
in_features: int = Field(default=64, gt=0)
|
|
13
|
+
out_features: int = Field(default=64, gt=0)
|
|
14
|
+
rank: int = Field(default=8, gt=0)
|
|
15
|
+
alpha: float = Field(default=16.0, gt=0.0)
|
|
16
|
+
learning_rate: float = Field(default=5e-3, gt=0.0)
|
|
17
|
+
weight_decay: float = Field(default=1e-2, ge=0.0)
|
|
18
|
+
beta1: float = Field(default=0.9, gt=0.0, lt=1.0)
|
|
19
|
+
beta2: float = Field(default=0.999, gt=0.0, lt=1.0)
|
|
20
|
+
eps: float = Field(default=1e-8, gt=0.0)
|
|
21
|
+
batch_size: int = Field(default=16, gt=0)
|
|
22
|
+
base_seed: int = Field(default=42, ge=0)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class RNGStatePayload(BaseModel):
|
|
26
|
+
model_config = ConfigDict(frozen=True, extra="forbid")
|
|
27
|
+
|
|
28
|
+
python_random_state_json: str
|
|
29
|
+
numpy_bit_generator_state_json: str
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class CheckpointManifest(BaseModel):
|
|
33
|
+
model_config = ConfigDict(frozen=True, extra="forbid")
|
|
34
|
+
|
|
35
|
+
job_id: str = Field(min_length=1)
|
|
36
|
+
step: int = Field(ge=0)
|
|
37
|
+
epoch: int = Field(ge=0)
|
|
38
|
+
loss_history: list[float]
|
|
39
|
+
safetensors_filename: str = Field(min_length=1)
|
|
40
|
+
payload_sha256: str = Field(min_length=64, max_length=64)
|
|
41
|
+
flush_duration_ms: float = Field(ge=0.0)
|
|
42
|
+
preempted: bool = False
|
|
43
|
+
remote_uri: str | None = None
|
|
44
|
+
remote_upload_ms: float = Field(default=0.0, ge=0.0)
|
|
45
|
+
created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
|
46
|
+
lora_config: LoRAConfig
|
|
47
|
+
rng_state: RNGStatePayload
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class TrainingRunSummary(BaseModel):
|
|
51
|
+
model_config = ConfigDict(frozen=True, extra="forbid")
|
|
52
|
+
|
|
53
|
+
job_id: str
|
|
54
|
+
start_step: int
|
|
55
|
+
completed_step: int
|
|
56
|
+
target_steps: int
|
|
57
|
+
preempted: bool
|
|
58
|
+
flush_duration_ms: float
|
|
59
|
+
loss_history: list[float]
|
|
60
|
+
adapter_a_sha256: str
|
|
61
|
+
adapter_b_sha256: str
|
|
62
|
+
checkpoint_metadata: dict[str, Any] = Field(default_factory=dict)
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import threading
|
|
5
|
+
import urllib.error
|
|
6
|
+
import urllib.request
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from typing import Literal
|
|
9
|
+
|
|
10
|
+
MetadataProvider = Literal["gcp", "aws"]
|
|
11
|
+
|
|
12
|
+
GCP_DEFAULT_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/preempted"
|
|
13
|
+
AWS_DEFAULT_METADATA_URL = "http://169.254.169.254/latest/meta-data/spot/instance-action"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class MetadataPreemptionWatcher:
|
|
17
|
+
"""Polls GCP or AWS instance metadata endpoints for spot preemption notices."""
|
|
18
|
+
|
|
19
|
+
def __init__(
|
|
20
|
+
self,
|
|
21
|
+
provider: MetadataProvider,
|
|
22
|
+
metadata_url: str | None = None,
|
|
23
|
+
poll_interval_sec: float = 0.5,
|
|
24
|
+
timeout_sec: float = 0.5,
|
|
25
|
+
on_preempt: Callable[[], None] | None = None,
|
|
26
|
+
) -> None:
|
|
27
|
+
if provider not in ("gcp", "aws"):
|
|
28
|
+
raise ValueError(f"Unsupported metadata provider: {provider!r}")
|
|
29
|
+
self.provider: MetadataProvider = provider
|
|
30
|
+
self.metadata_url: str = metadata_url or (
|
|
31
|
+
GCP_DEFAULT_METADATA_URL if provider == "gcp" else AWS_DEFAULT_METADATA_URL
|
|
32
|
+
)
|
|
33
|
+
self.poll_interval_sec = poll_interval_sec
|
|
34
|
+
self.timeout_sec = timeout_sec
|
|
35
|
+
self._on_preempt = on_preempt
|
|
36
|
+
|
|
37
|
+
self._preempt_event = threading.Event()
|
|
38
|
+
self._stop_event = threading.Event()
|
|
39
|
+
self._lock = threading.Lock()
|
|
40
|
+
self._thread: threading.Thread | None = None
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def preempted(self) -> bool:
|
|
44
|
+
"""Return True if a preemption notice has been observed."""
|
|
45
|
+
return self._preempt_event.is_set()
|
|
46
|
+
|
|
47
|
+
def wait(self, timeout: float | None = None) -> bool:
|
|
48
|
+
"""Block until preemption is detected or timeout expires."""
|
|
49
|
+
return self._preempt_event.wait(timeout=timeout)
|
|
50
|
+
|
|
51
|
+
def check_once(self) -> bool:
|
|
52
|
+
"""Poll the metadata endpoint once and return True if preemption is signaled."""
|
|
53
|
+
headers: dict[str, str] = {}
|
|
54
|
+
if self.provider == "gcp":
|
|
55
|
+
headers["Metadata-Flavor"] = "Google"
|
|
56
|
+
|
|
57
|
+
req = urllib.request.Request(self.metadata_url, headers=headers, method="GET")
|
|
58
|
+
try:
|
|
59
|
+
with urllib.request.urlopen(req, timeout=self.timeout_sec) as resp:
|
|
60
|
+
status = getattr(resp, "status", 200)
|
|
61
|
+
if status != 200:
|
|
62
|
+
return False
|
|
63
|
+
body = resp.read().decode("utf-8", errors="replace")
|
|
64
|
+
except (urllib.error.HTTPError, urllib.error.URLError, TimeoutError, OSError):
|
|
65
|
+
return False
|
|
66
|
+
|
|
67
|
+
detected = self._is_preempted_response(body)
|
|
68
|
+
if not detected:
|
|
69
|
+
return False
|
|
70
|
+
|
|
71
|
+
should_notify = False
|
|
72
|
+
with self._lock:
|
|
73
|
+
if not self._preempt_event.is_set():
|
|
74
|
+
self._preempt_event.set()
|
|
75
|
+
should_notify = True
|
|
76
|
+
|
|
77
|
+
if should_notify and self._on_preempt is not None:
|
|
78
|
+
self._on_preempt()
|
|
79
|
+
return True
|
|
80
|
+
|
|
81
|
+
def _is_preempted_response(self, body: str) -> bool:
|
|
82
|
+
if self.provider == "gcp":
|
|
83
|
+
return body.strip().upper() == "TRUE"
|
|
84
|
+
stripped = body.strip()
|
|
85
|
+
if not stripped:
|
|
86
|
+
return False
|
|
87
|
+
try:
|
|
88
|
+
parsed = json.loads(stripped)
|
|
89
|
+
except json.JSONDecodeError:
|
|
90
|
+
return False
|
|
91
|
+
return isinstance(parsed, dict) and "action" in parsed
|
|
92
|
+
|
|
93
|
+
def _poll_loop(self) -> None:
|
|
94
|
+
while not self._stop_event.is_set():
|
|
95
|
+
if self.check_once():
|
|
96
|
+
return
|
|
97
|
+
self._stop_event.wait(self.poll_interval_sec)
|
|
98
|
+
|
|
99
|
+
def start(self) -> None:
|
|
100
|
+
"""Start background polling in a daemon thread."""
|
|
101
|
+
with self._lock:
|
|
102
|
+
if self._thread is not None and self._thread.is_alive():
|
|
103
|
+
return
|
|
104
|
+
self._stop_event.clear()
|
|
105
|
+
self._thread = threading.Thread(
|
|
106
|
+
target=self._poll_loop,
|
|
107
|
+
name=f"metadata-preempt-{self.provider}",
|
|
108
|
+
daemon=True,
|
|
109
|
+
)
|
|
110
|
+
self._thread.start()
|
|
111
|
+
|
|
112
|
+
def stop(self) -> None:
|
|
113
|
+
"""Stop background polling and wait for the watcher thread to exit."""
|
|
114
|
+
self._stop_event.set()
|
|
115
|
+
thread = self._thread
|
|
116
|
+
if thread is not None and thread.is_alive() and threading.current_thread() is not thread:
|
|
117
|
+
thread.join(timeout=max(1.0, self.timeout_sec + self.poll_interval_sec))
|