steer-ml 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.
steer/__init__.py ADDED
@@ -0,0 +1,537 @@
1
+ """Steer SDK: live control of a PyTorch training loop.
2
+
3
+ import steer
4
+ steer.init(api_key="sk_...", server="http://localhost:8000", model=model, optimizer=opt, scheduler=sched)
5
+ lr = steer.param("lr", 3e-4, min=1e-6, max=1e-2)
6
+ for step, batch in enumerate(loader):
7
+ loss = train_step(batch)
8
+ steer.step(step, loss=loss) # safe point: apply changes, pause, checkpoint, guardrails
9
+
10
+ Training never depends on the server: if it is unreachable, Steer retries in the background.
11
+
12
+ OOM rescue: wrap the step in `with steer.oom_guard():` and register `steer.param("batch_size", ...)`; a CUDA
13
+ out-of-memory error then skips that step and halves batch_size instead of killing the run.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import atexit
18
+ import copy
19
+ import json
20
+ import logging
21
+ import math
22
+ import os
23
+ import queue
24
+ import random
25
+ import sys
26
+ import threading
27
+ import time
28
+ from collections import deque
29
+ from contextlib import contextmanager
30
+ from pathlib import Path
31
+ from typing import Annotated, Any
32
+
33
+ from pydantic import Field, TypeAdapter, ValidationError
34
+ from websockets.exceptions import InvalidStatus
35
+ from websockets.sync.client import connect
36
+
37
+ log = logging.getLogger("steer")
38
+ __all__ = ["init", "param", "step", "checkpoint", "finish", "oom_guard", "Param"]
39
+
40
+ METRICS_FLUSH_SECONDS = 1.0
41
+ SPIKE_WINDOW, SPIKE_MIN_POINTS = 50, 20
42
+ LR_KEYS = ("lr", "initial_lr", "max_lr", "min_lr")
43
+
44
+
45
+ class Param:
46
+ """A live-controllable value. Read `.value` each step; Steer updates it at safe points."""
47
+
48
+ def __init__(self, name: str, default: Any, min: float | None = None, max: float | None = None):
49
+ kind = type(default)
50
+ if kind not in (int, float, bool, str):
51
+ raise TypeError(f"steer.param {name!r}: default must be int, float, bool or str")
52
+ bounds = {} if kind in (bool, str) else {"ge": min, "le": max}
53
+ self._adapter = TypeAdapter(Annotated[kind, Field(**bounds)])
54
+ self.name = name
55
+ self.value = self._adapter.validate_python(default)
56
+ self.schema = self._adapter.json_schema()
57
+
58
+ def validate(self, value: Any) -> Any:
59
+ return self._adapter.validate_python(value)
60
+
61
+ def __repr__(self) -> str:
62
+ return f"Param({self.name}={self.value!r})"
63
+
64
+
65
+ class _Connection(threading.Thread):
66
+ """Background thread owning the WebSocket. Reconnects with backoff; buffers while offline."""
67
+
68
+ def __init__(self, run: _Run, url: str, api_key: str):
69
+ super().__init__(name="steer-connection", daemon=True)
70
+ self.owner, self.url, self.api_key = run, url, api_key
71
+ self.outbox: deque[dict] = deque(maxlen=10_000) # shortcut: oldest messages drop after long outages
72
+ self.commands: queue.Queue[dict] = queue.Queue()
73
+ self.connected = threading.Event()
74
+ self.stopping = threading.Event()
75
+ self.run_id: int | None = None
76
+
77
+ def send(self, msg: dict) -> None:
78
+ self.outbox.append(msg)
79
+
80
+ def dashboard_url(self) -> str:
81
+ return f"{self.url.replace('ws', 'http', 1).removesuffix('/ws/run')}/#/runs/{self.run_id}"
82
+
83
+ def run(self) -> None:
84
+ backoff = 1.0
85
+ while not self.stopping.is_set():
86
+ try:
87
+ with connect(self.url, additional_headers={"Authorization": f"Bearer {self.api_key}"},
88
+ open_timeout=10, close_timeout=2) as ws:
89
+ ws.send(json.dumps(self.owner.hello(self.run_id)))
90
+ first, self.run_id = self.run_id is None, json.loads(ws.recv(timeout=10))["run_id"]
91
+ if first: # print(), not log: most scripts never configure logging, so log.info would be hidden
92
+ print(f"steer: watch this run live at {self.dashboard_url()}", file=sys.stderr, flush=True)
93
+ self.connected.set()
94
+ backoff = 1.0
95
+ log.info("steer: connected, run %s", self.run_id)
96
+ self._pump(ws)
97
+ except InvalidStatus as e:
98
+ if e.response.status_code in (401, 403):
99
+ log.error("steer: server rejected the API key; continuing without Steer")
100
+ return
101
+ log.warning("steer: connection refused (%s); retrying in %.0fs", e, backoff)
102
+ except Exception as e: # network errors must never reach the training loop
103
+ log.warning("steer: disconnected (%s); retrying in %.0fs", e, backoff)
104
+ self.connected.clear()
105
+ if self.stopping.wait(backoff):
106
+ return
107
+ backoff = min(backoff * 2, 30.0)
108
+
109
+ def _pump(self, ws) -> None:
110
+ while True:
111
+ while self.outbox:
112
+ ws.send(json.dumps(self.outbox[0]))
113
+ self.outbox.popleft() # only drop after a successful send
114
+ if self.stopping.is_set():
115
+ return
116
+ try:
117
+ self.commands.put(json.loads(ws.recv(timeout=0.2)))
118
+ except TimeoutError:
119
+ pass
120
+
121
+
122
+ class _Run:
123
+ def __init__(self, *, api_key: str, server: str, run_name: str, model, optimizer, scheduler,
124
+ guardrails: bool, spike_factor: float, checkpoint_dir: str):
125
+ self.name, self.model, self.optimizer, self.scheduler = run_name, model, optimizer, scheduler
126
+ self.guardrails, self.spike_factor = guardrails, spike_factor
127
+ self.checkpoint_dir = Path(checkpoint_dir)
128
+ self.params: dict[str, Param] = {}
129
+ self.overrides_checked = False
130
+ self.step_num = 0
131
+ self.paused = False
132
+ self.status = "finished"
133
+ self._points: list[dict] = []
134
+ self._last_flush = time.monotonic()
135
+ self._losses: deque[float] = deque(maxlen=SPIKE_WINDOW)
136
+ self._probe: dict | None = None
137
+ self._offset = 0 # user steps consumed by probes; reported step = user step - offset
138
+ url = server.rstrip("/").replace("http", "ws", 1) + "/ws/run"
139
+ self.conn = _Connection(self, url, api_key)
140
+ self.conn.start()
141
+
142
+ # ----- messages -----
143
+ def hello(self, run_id: int | None) -> dict:
144
+ return {"type": "hello", "run_id": run_id, "name": self.name,
145
+ "model_family": type(self.model).__name__ if self.model is not None else None,
146
+ "optimizer": type(self.optimizer).__name__ if self.optimizer is not None else None,
147
+ "gpu_info": _gpu_info(),
148
+ "params": {n: {"value": p.value, "schema": p.schema} for n, p in self.params.items()}}
149
+
150
+ def event(self, kind: str, message: str, **data) -> None:
151
+ log.info("steer [%s] step %s: %s", kind, self.step_num, message)
152
+ self.conn.send({"type": "event", "step": self.step_num, "kind": kind, "message": message,
153
+ "data": data or None})
154
+
155
+ def flush_metrics(self) -> None:
156
+ if self._points:
157
+ self.conn.send({"type": "metrics", "step": self.step_num, "points": self._points})
158
+ self._points = []
159
+ if (p := self._probe) and p["points"]:
160
+ self.conn.send({"type": "probe_metrics", "probe_id": p["id"], "branch": len(p["branches"]),
161
+ "points": p["points"]})
162
+ p["points"] = []
163
+ self._last_flush = time.monotonic()
164
+
165
+ # ----- safe point -----
166
+ def step(self, step: int, metrics: dict[str, Any]) -> None:
167
+ values = {}
168
+ for name, value in metrics.items():
169
+ try:
170
+ values[name] = float(value)
171
+ except (TypeError, ValueError):
172
+ log.warning("steer: metric %r is not a number; skipped", name)
173
+ if self._probe is not None:
174
+ self._probe_step(step, values)
175
+ else:
176
+ self.step_num = step - self._offset
177
+ self._points += [{"step": self.step_num, "name": n, "value": v} for n, v in values.items()]
178
+ if self.guardrails and "loss" in values:
179
+ self._check_loss(values["loss"])
180
+ if time.monotonic() - self._last_flush >= METRICS_FLUSH_SECONDS:
181
+ self.flush_metrics()
182
+ self._drain_commands()
183
+ while self.paused:
184
+ self.flush_metrics()
185
+ try:
186
+ self._handle(self.conn.commands.get(timeout=0.5))
187
+ except queue.Empty:
188
+ pass
189
+
190
+ def _drain_commands(self) -> None:
191
+ while True:
192
+ try:
193
+ self._handle(self.conn.commands.get_nowait())
194
+ except queue.Empty:
195
+ return
196
+
197
+ def _handle(self, cmd: dict) -> None:
198
+ kind = cmd.get("type")
199
+ if kind == "probe":
200
+ return self._start_probe(cmd)
201
+ if self._probe is not None: # applied right after the probe, in arrival order
202
+ return self._probe["deferred"].append(cmd)
203
+ if kind == "set_param":
204
+ self._set_param(cmd)
205
+ elif kind == "pause" and not self.paused:
206
+ self.paused = True
207
+ self.event("paused", f"Paused by the {by} agent" if (by := cmd.get("author_agent")) else "Paused from dashboard")
208
+ elif kind == "resume" and self.paused:
209
+ self.paused = False
210
+ self.event("resumed", f"Resumed by the {by} agent" if (by := cmd.get("author_agent")) else "Resumed")
211
+ elif kind == "checkpoint":
212
+ self.checkpoint()
213
+
214
+ def _set_param(self, cmd: dict) -> None:
215
+ name = cmd.get("name")
216
+ p = self.params.get(name)
217
+ if p is None:
218
+ return self.event("rejected", f"Unknown parameter {name!r}")
219
+ try:
220
+ new = p.validate(cmd.get("value"))
221
+ except ValidationError as e:
222
+ return self.event("rejected", f"{name}: {e.errors()[0]['msg']}", param=name, value=cmd.get("value"))
223
+ old = self._assign(name, new)
224
+ self._losses.clear() # a deliberate change (e.g. a loss weight) moves the loss level; not a spike
225
+ self.conn.send({"type": "change_applied", "step": self.step_num, "name": name, "old": old, "new": new,
226
+ "author_user_id": cmd.get("author_user_id"), "author_agent": cmd.get("author_agent"),
227
+ "suggestion_id": cmd.get("suggestion_id")})
228
+
229
+ def _assign(self, name: str, new: Any) -> Any:
230
+ p = self.params[name]
231
+ old, p.value = p.value, new
232
+ self._apply_to_optimizer(name, old, new)
233
+ return old
234
+
235
+ def _apply_to_optimizer(self, name: str, old: Any, new: Any) -> None:
236
+ opt = self.optimizer
237
+ if opt is None:
238
+ return
239
+ if name == "lr" and old:
240
+ # Scale rather than overwrite, so a scheduler's shape (warmup, cosine...) is kept and its
241
+ # next step() doesn't silently undo the change.
242
+ factor = new / old
243
+ for g in opt.param_groups:
244
+ for key in LR_KEYS: # initial_lr/max_lr/min_lr are what LambdaLR, OneCycleLR etc. read
245
+ if key in g:
246
+ g[key] *= factor
247
+ if self.scheduler is not None and hasattr(self.scheduler, "base_lrs"):
248
+ self.scheduler.base_lrs = [b * factor for b in self.scheduler.base_lrs]
249
+ elif name in opt.defaults:
250
+ for g in opt.param_groups:
251
+ g[name] = new
252
+
253
+ # ----- speculative probing: try variants for a few steps from one snapshot, then rewind -----
254
+ def _start_probe(self, cmd: dict) -> None:
255
+ steps, variants = cmd.get("steps"), cmd.get("variants") or []
256
+ try:
257
+ if self.model is None or self.optimizer is None:
258
+ raise ValueError("probing needs model= and optimizer= in steer.init()")
259
+ if self._probe is not None:
260
+ raise ValueError("a probe is already running")
261
+ if not isinstance(steps, int) or steps < 1 or not variants:
262
+ raise ValueError("a probe needs steps >= 1 and at least one variant")
263
+ if unknown := {n for v in variants for n in v} - self.params.keys():
264
+ raise ValueError(f"Unknown parameter(s) {sorted(unknown)}")
265
+ variants = [{n: self.params[n].validate(x) for n, x in v.items()} for v in variants]
266
+ except ValueError as e: # pydantic's ValidationError is a ValueError
267
+ msg = e.errors()[0]["msg"] if isinstance(e, ValidationError) else str(e)
268
+ return self.conn.send({"type": "probe_result", "probe_id": cmd.get("probe_id"),
269
+ "step": self.step_num, "error": msg})
270
+ import torch
271
+
272
+ np = sys.modules.get("numpy")
273
+ snap = {"model": copy.deepcopy(self.model.state_dict()),
274
+ "optimizer": copy.deepcopy(self.optimizer.state_dict()),
275
+ "scheduler": copy.deepcopy(self.scheduler.state_dict()) if self.scheduler is not None else None,
276
+ "py_rng": random.getstate(), "torch_rng": torch.get_rng_state(),
277
+ "cuda_rng": torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None,
278
+ "np_rng": np.random.get_state() if np is not None else None,
279
+ "params": {n: p.value for n, p in self.params.items()}}
280
+ self._probe = {"id": cmd.get("probe_id"), "steps": steps, "variants": variants, "snap": snap,
281
+ "s0": self.step_num, "paused": self.paused, "deferred": [], "branches": [],
282
+ "points": [], "curve": [], "k": 0}
283
+ self.paused = False # a paused run still probes; the pause is re-established afterwards
284
+ self.conn.send({"type": "probe_started", "probe_id": self._probe["id"], "step": self.step_num,
285
+ "steps": steps, "variants": variants})
286
+ log.info("steer: probe %s started at step %s: %d variants x %d steps",
287
+ self._probe["id"], self.step_num, len(variants), steps)
288
+ self._begin_branch()
289
+
290
+ def _begin_branch(self) -> None:
291
+ p = self._probe
292
+ self._restore(p["snap"])
293
+ for name, value in p["variants"][len(p["branches"])].items():
294
+ self._assign(name, value)
295
+ p["curve"], p["k"] = [], 0
296
+
297
+ def _restore(self, snap: dict) -> None:
298
+ import torch
299
+
300
+ self.model.load_state_dict(snap["model"])
301
+ # load_state_dict may keep references to the tensors it's given, so never hand it the snapshot itself
302
+ self.optimizer.load_state_dict(copy.deepcopy(snap["optimizer"]))
303
+ if snap["scheduler"] is not None:
304
+ self.scheduler.load_state_dict(copy.deepcopy(snap["scheduler"]))
305
+ random.setstate(snap["py_rng"])
306
+ torch.set_rng_state(snap["torch_rng"])
307
+ if snap["cuda_rng"] is not None:
308
+ torch.cuda.set_rng_state_all(snap["cuda_rng"])
309
+ if snap["np_rng"] is not None:
310
+ sys.modules["numpy"].random.set_state(snap["np_rng"])
311
+ for name, value in snap["params"].items():
312
+ self.params[name].value = value
313
+
314
+ def _probe_step(self, step: int, values: dict[str, float]) -> None:
315
+ p = self._probe
316
+ k, p["k"] = p["k"], p["k"] + 1
317
+ loss_name = "loss" if "loss" in values else next((n for n in values if n.endswith("loss")), None)
318
+ if loss_name is not None:
319
+ p["curve"].append((k, values[loss_name]))
320
+ p["points"] += [{"step": k, "name": n, "value": v} for n, v in values.items() if math.isfinite(v)]
321
+ if p["k"] < p["steps"]:
322
+ return
323
+ self.flush_metrics() # before the branch index advances
324
+ p["branches"].append(_branch_result(p["variants"][len(p["branches"])], p["curve"]))
325
+ if len(p["branches"]) < len(p["variants"]):
326
+ return self._begin_branch()
327
+ self._restore(p["snap"])
328
+ self._probe, self._offset, self.paused = None, step - p["s0"], p["paused"]
329
+ scores = {i: b["score"] for i, b in enumerate(p["branches"]) if b["score"] is not None}
330
+ winner = min(scores, key=scores.get, default=None)
331
+ self.conn.send({"type": "probe_result", "probe_id": p["id"], "step": p["s0"],
332
+ "branches": p["branches"], "winner": winner})
333
+ log.info("steer: probe %s finished, winner %s", p["id"], winner)
334
+ for cmd in p["deferred"]:
335
+ self._handle(cmd)
336
+
337
+ def _check_loss(self, loss: float) -> None:
338
+ if not math.isfinite(loss):
339
+ return self._trip(f"Loss is {loss}", loss)
340
+ window = self._losses
341
+ if len(window) >= SPIKE_MIN_POINTS and loss > self.spike_factor * (sum(window) / len(window)):
342
+ return self._trip(f"Loss spiked to {loss:.4g} (>{self.spike_factor}x the recent mean "
343
+ f"{sum(window) / len(window):.4g})", loss)
344
+ window.append(loss)
345
+
346
+ def _trip(self, message: str, loss: float) -> None:
347
+ self._losses.clear() # re-baseline after a trip so one spike doesn't re-fire every step
348
+ path = self.checkpoint(announce=False)
349
+ connected = self.conn.connected.is_set()
350
+ if connected:
351
+ self.paused = True
352
+ suffix = "; paused, resume from the dashboard" if connected else "; not paused (server offline)"
353
+ self.event("guardrail", message + suffix, loss=loss if math.isfinite(loss) else str(loss),
354
+ checkpoint=str(path) if path else None)
355
+ self.flush_metrics()
356
+
357
+ def rescue_oom(self, halve: str) -> bool:
358
+ """After a CUDA out-of-memory error: free what we can and halve the `halve` param. False if it can't go lower."""
359
+ import torch
360
+
361
+ if self.optimizer is not None:
362
+ self.optimizer.zero_grad(set_to_none=True)
363
+ torch.cuda.empty_cache()
364
+ p = self.params.get(halve)
365
+ try:
366
+ new = p.validate(p.value // 2) if p is not None and type(p.value) is int and p.value > 1 else None
367
+ except ValidationError: # below the param's min
368
+ new = None
369
+ if new is None:
370
+ self.event("oom", f"Out of GPU memory, and {halve} can't be halved; stopping the run")
371
+ self.flush_metrics()
372
+ return False
373
+ old = self._assign(halve, new)
374
+ self.conn.send({"type": "change_applied", "step": self.step_num, "name": halve, "old": old, "new": new,
375
+ "author_agent": "oom_rescue"})
376
+ self.event("oom", f"Out of GPU memory: skipped the step and halved {halve} from {old} to {new}",
377
+ param=halve, old=old, new=new)
378
+ self.flush_metrics()
379
+ return True
380
+
381
+ def checkpoint(self, announce: bool = True) -> Path | None:
382
+ if self.model is None:
383
+ if announce:
384
+ self.event("info", "Checkpoint skipped: pass model= to steer.init()")
385
+ return None
386
+ import torch
387
+
388
+ self.checkpoint_dir.mkdir(parents=True, exist_ok=True)
389
+ path = self.checkpoint_dir / f"{self.name}-step{self.step_num}.pt"
390
+ state = {"step": self.step_num, "model": self.model.state_dict(),
391
+ "params": {n: p.value for n, p in self.params.items()}}
392
+ if self.optimizer is not None:
393
+ state["optimizer"] = self.optimizer.state_dict()
394
+ if self.scheduler is not None:
395
+ state["scheduler"] = self.scheduler.state_dict()
396
+ tmp = path.with_suffix(".tmp")
397
+ torch.save(state, tmp)
398
+ os.replace(tmp, path) # never leave a half-written checkpoint
399
+ if announce:
400
+ self.event("checkpoint", f"Saved {path}", path=str(path))
401
+ return path
402
+
403
+ def finish(self, status: str) -> None:
404
+ if (p := self._probe) is not None: # the loop ended mid-probe: don't leave the model in a branch's state
405
+ self._restore(p["snap"])
406
+ self._probe = None
407
+ self.flush_metrics()
408
+ self.conn.send({"type": "bye", "step": self.step_num, "status": status})
409
+ self.conn.stopping.set()
410
+ self.conn.join(timeout=5)
411
+
412
+
413
+ def _branch_result(params: dict, curve: list[tuple[int, float]]) -> dict:
414
+ losses = [loss for _, loss in curve]
415
+ diverged = any(not math.isfinite(x) for x in losses) or bool(losses) and losses[-1] > 3 * losses[0]
416
+ tail = losses[len(losses) // 2:]
417
+ finite = [[k, loss] for k, loss in curve if math.isfinite(loss)]
418
+ return {"params": params, "score": None if diverged or not tail else sum(tail) / len(tail),
419
+ "final_loss": losses[-1] if losses and math.isfinite(losses[-1]) else None,
420
+ "diverged": diverged, "curve": finite[::len(finite) // 100 + 1]}
421
+
422
+
423
+ def _gpu_info() -> dict | None:
424
+ torch = sys.modules.get("torch")
425
+ if torch is None or not torch.cuda.is_available():
426
+ return None
427
+ props = torch.cuda.get_device_properties(0)
428
+ return {"name": props.name, "memory_gb": round(props.total_memory / 2**30, 1),
429
+ "count": torch.cuda.device_count()}
430
+
431
+
432
+ _run: _Run | None = None
433
+
434
+
435
+ def init(api_key: str | None = None, server: str | None = None, run_name: str | None = None, *,
436
+ model=None, optimizer=None, scheduler=None, guardrails: bool = True, spike_factor: float = 3.0,
437
+ checkpoint_dir: str = "checkpoints") -> None:
438
+ """Connect this process to Steer. Pass model/optimizer/scheduler to enable checkpoints and lr control."""
439
+ global _run
440
+ if _run is not None:
441
+ raise RuntimeError("steer.init() was already called in this process")
442
+ api_key = api_key or os.getenv("STEER_API_KEY")
443
+ if not api_key:
444
+ raise ValueError("steer.init(): pass api_key= or set STEER_API_KEY")
445
+ _run = _Run(api_key=api_key, server=server or os.getenv("STEER_SERVER", "http://localhost:8000"),
446
+ run_name=run_name or time.strftime("run-%Y%m%d-%H%M%S"), model=model, optimizer=optimizer,
447
+ scheduler=scheduler, guardrails=guardrails, spike_factor=spike_factor,
448
+ checkpoint_dir=checkpoint_dir)
449
+ atexit.register(finish)
450
+ previous_hook = sys.excepthook
451
+
452
+ def _crash_hook(*exc_info):
453
+ finish("crashed")
454
+ previous_hook(*exc_info)
455
+
456
+ sys.excepthook = _crash_hook
457
+
458
+
459
+ def _require_run() -> _Run:
460
+ if _run is None:
461
+ raise RuntimeError("call steer.init() first")
462
+ return _run
463
+
464
+
465
+ def _overrides() -> dict:
466
+ """Param values for a re-run, from the STEER_OVERRIDES env var: a JSON object like {"lr": 0.001}."""
467
+ raw = os.getenv("STEER_OVERRIDES")
468
+ if not raw:
469
+ return {}
470
+ try:
471
+ out = json.loads(raw)
472
+ except json.JSONDecodeError as e:
473
+ raise ValueError(f"STEER_OVERRIDES is not valid JSON ({e}); expected something like {{\"lr\": 0.001}}") from None
474
+ if not isinstance(out, dict):
475
+ raise ValueError('STEER_OVERRIDES must be a JSON object, like {"lr": 0.001}')
476
+ return out
477
+
478
+
479
+ def param(name: str, default: Any, *, min: float | None = None, max: float | None = None) -> Param:
480
+ """Register a live-controllable parameter. Call before the training loop. STEER_OVERRIDES (a JSON object)
481
+ replaces `default` for a re-run, checked against the same bounds as a live change."""
482
+ run = _require_run()
483
+ p = run.params[name] = Param(name, default, min=min, max=max)
484
+ if name in (overrides := _overrides()):
485
+ try:
486
+ new = p.validate(overrides[name])
487
+ except ValidationError as e:
488
+ raise ValueError(f"STEER_OVERRIDES: bad value for {name!r}: {e.errors()[0]['msg']}") from None
489
+ run._assign(name, new) # same path as a live change, so the optimizer and scheduler follow
490
+ run.event("override", f"{name} = {new} (from STEER_OVERRIDES; the script's default is {default})")
491
+ if run.conn.connected.is_set():
492
+ run.conn.send(run.hello(run.conn.run_id)) # re-hello registers the new param on the server
493
+ return p
494
+
495
+
496
+ def step(step: int, **metrics: Any) -> None:
497
+ """The safe point. Logs metrics, applies queued changes, honours pause, runs guardrails."""
498
+ run = _require_run()
499
+ try:
500
+ if not run.overrides_checked: # by the first step every param is registered, so leftovers are typos
501
+ run.overrides_checked = True
502
+ if unknown := sorted(set(_overrides()) - set(run.params)):
503
+ run.event("override", f"STEER_OVERRIDES names params this script doesn't register: {', '.join(unknown)}")
504
+ run.step(step, metrics)
505
+ except Exception: # a bug in Steer must never kill the user's training
506
+ log.exception("steer: internal error in step(); training continues")
507
+
508
+
509
+ def checkpoint() -> Path | None:
510
+ return _require_run().checkpoint()
511
+
512
+
513
+ @contextmanager
514
+ def oom_guard(halve: str = "batch_size"):
515
+ """Wrap one training step. A CUDA out-of-memory error skips the step and halves the `halve` param (read its
516
+ .value when building the batch); if it can't be halved, the error is raised as usual."""
517
+ torch = sys.modules.get("torch")
518
+ oom = None
519
+ try:
520
+ yield
521
+ except Exception as e:
522
+ if torch is None or not isinstance(e, torch.cuda.OutOfMemoryError):
523
+ raise
524
+ oom = str(e)
525
+ # Outside the except block, so the traceback (and the tensors its frames hold) is gone before empty_cache().
526
+ if oom is not None and not _require_run().rescue_oom(halve):
527
+ raise torch.cuda.OutOfMemoryError(oom)
528
+
529
+
530
+ def finish(status: str = "finished") -> None:
531
+ global _run
532
+ run, _run = _run, None
533
+ if run is not None:
534
+ try:
535
+ run.finish(status)
536
+ except Exception:
537
+ log.exception("steer: error while finishing")
steer/__main__.py ADDED
@@ -0,0 +1,14 @@
1
+ """`steer mcp` (or `python -m steer mcp`): the only CLI command so far."""
2
+ import sys
3
+
4
+
5
+ def main() -> None:
6
+ if sys.argv[1:] != ["mcp"]:
7
+ raise SystemExit("usage: steer mcp")
8
+ from .mcp_server import main as mcp_main
9
+
10
+ mcp_main()
11
+
12
+
13
+ if __name__ == "__main__":
14
+ main()
steer/mcp_server.py ADDED
@@ -0,0 +1,136 @@
1
+ """`steer mcp`: Steer's runs as MCP tools, so Claude Code / Claude Desktop (or any MCP client) can babysit training.
2
+
3
+ pip install "steer-ml[mcp]"
4
+ claude mcp add steer -e STEER_SERVER=https://your-steer -e STEER_EMAIL=you@x.com -e STEER_PASSWORD=... -- steer mcp
5
+
6
+ It logs in as you and calls the same REST API as the dashboard, so your project role and every run's agent
7
+ policy apply unchanged.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ import shlex
14
+ from typing import Any
15
+
16
+ import httpx
17
+ from mcp.server import MCPServer
18
+ from mcp.server.mcpserver.exceptions import ToolError
19
+
20
+ TREND_POINTS = 200 # points per metric that run_status summarises
21
+
22
+
23
+ def login(server: str, email: str, password: str) -> httpx.Client:
24
+ http = httpx.Client(base_url=server.rstrip("/"), timeout=30)
25
+ http.post("/api/auth/login", json={"email": email, "password": password}).raise_for_status()
26
+ return http
27
+
28
+
29
+ def build(http: httpx.Client) -> MCPServer:
30
+ def call(method: str, path: str, body: Any = None) -> Any:
31
+ r = http.request(method, path, json=body)
32
+ if r.is_error: # the API's own message ("Run is not connected", "Requires controller role") is the useful part
33
+ raise ToolError(f"{r.status_code}: {r.json().get('detail', r.text) if r.content else r.reason_phrase}")
34
+ return r.json() if r.content else None
35
+
36
+ mcp = MCPServer("steer", instructions=(
37
+ "Steer controls live ML training runs. Start with list_runs, then run_status. Changes are applied at the "
38
+ "run's next safe point; the run's agents (Watchdog, Doctor, Experimenter, Scribe) keep working alongside you."))
39
+
40
+ @mcp.tool()
41
+ def list_runs() -> list[dict]:
42
+ """Every run in your projects: id, name, status, step, whether it's connected, and fixes agents made."""
43
+ out = []
44
+ for p in call("GET", "/api/projects"):
45
+ for r in call("GET", f"/api/projects/{p['id']}/runs"):
46
+ out.append({"project": p["name"], **{k: r[k] for k in (
47
+ "id", "name", "status", "live", "current_step", "model_family", "optimizer", "agent_fixes")}})
48
+ return out
49
+
50
+ @mcp.tool()
51
+ def run_status(run_id: int) -> dict:
52
+ """One run: status, live params with their bounds, agent policy, pending suggestions, and a summary of
53
+ each metric over its last 200 points (first, min, last)."""
54
+ run = call("GET", f"/api/runs/{run_id}")
55
+ start = max(-1, run["current_step"] - TREND_POINTS)
56
+ trends = {name: {"first": pts[0][1], "min": min(v for _, v in pts), "last": pts[-1][1],
57
+ "last_step": pts[-1][0]} for name, pts in call("GET", f"/api/runs/{run_id}/metrics?after_step={start}").items() if pts}
58
+ pending = [s for s in call("GET", f"/api/runs/{run_id}/suggestions") if s["status"] == "pending"]
59
+ return {**{k: run[k] for k in ("id", "name", "status", "live", "current_step", "model_family", "optimizer",
60
+ "policy", "params", "agent_fixes")},
61
+ "metrics": trends, "pending_suggestions": pending}
62
+
63
+ @mcp.tool()
64
+ def get_metrics(run_id: int, name: str = "loss", last: int = 500) -> list[list[float]]:
65
+ """[[step, value], ...] for one metric, at most 100 points evenly spread over the last `last` steps."""
66
+ run = call("GET", f"/api/runs/{run_id}")
67
+ pts = call("GET", f"/api/runs/{run_id}/metrics?after_step={run['current_step'] - last}").get(name, [])
68
+ return pts[::len(pts) // 100 + 1]
69
+
70
+ @mcp.tool()
71
+ def read_journal(run_id: int, last: int = 30) -> list[dict]:
72
+ """The run's journal: what the agents saw, thought and did, and events from the training process."""
73
+ return [{k: j[k] for k in ("step", "agent", "kind", "message")}
74
+ for j in call("GET", f"/api/runs/{run_id}/journal")[-last:]]
75
+
76
+ @mcp.tool()
77
+ def set_param(run_id: int, name: str, value: float | int | bool | str) -> str:
78
+ """Change a live parameter (e.g. lr, dropout). The training process validates it against its bounds."""
79
+ call("POST", f"/api/runs/{run_id}/commands", {"type": "set_param", "name": name, "value": value})
80
+ return f"Queued {name} = {value}; it applies at the next training step."
81
+
82
+ @mcp.tool()
83
+ def pause(run_id: int) -> str:
84
+ """Pause training at the next step."""
85
+ call("POST", f"/api/runs/{run_id}/commands", {"type": "pause"})
86
+ return "Pause queued."
87
+
88
+ @mcp.tool()
89
+ def resume(run_id: int) -> str:
90
+ """Resume a paused run."""
91
+ call("POST", f"/api/runs/{run_id}/commands", {"type": "resume"})
92
+ return "Resume queued."
93
+
94
+ @mcp.tool()
95
+ def probe(run_id: int, param: str, values: list[float]) -> str:
96
+ """Race up to 4 values of one param against the current setting for a few steps each from the same
97
+ checkpoint, then rewind; the winner is applied if the run's policy allows. See read_journal for the result."""
98
+ call("POST", f"/api/runs/{run_id}/probe", {"fixes": [{"param": param, "value": v} for v in values]})
99
+ return "The Experimenter will start the probe at the next step."
100
+
101
+ @mcp.tool()
102
+ def ask_doctor(run_id: int) -> str:
103
+ """Ask the Doctor agent to diagnose the run now; its diagnosis and fixes appear in read_journal."""
104
+ call("POST", f"/api/runs/{run_id}/ask")
105
+ return "The Doctor is looking at the run."
106
+
107
+ @mcp.tool()
108
+ def rerun_command(run_id: int, changes: dict[str, float | int | bool | str] | None = None) -> dict:
109
+ """Steer can't restart a training process itself. This returns the STEER_OVERRIDES value and the commands
110
+ that start the script again with the run's last param values plus `changes`; give them to the user to run
111
+ where they train. The SDK checks each value against its param's bounds at startup."""
112
+ params = {p["name"]: p["value"] for p in call("GET", f"/api/runs/{run_id}")["params"]}
113
+ if unknown := sorted(set(changes or {}) - set(params)):
114
+ raise ToolError(f"This run has no params named {', '.join(unknown)}; it has {', '.join(params) or 'none'}")
115
+ value = json.dumps(params | (changes or {}))
116
+ sh = shlex.quote(value)
117
+ return {"STEER_OVERRIDES": value, "terminal": f"STEER_OVERRIDES={sh} python train.py",
118
+ "slurm": f"STEER_OVERRIDES={sh} sbatch train.sh",
119
+ "notebook": f"import os\nos.environ['STEER_OVERRIDES'] = {value!r} # before steer.init",
120
+ "note": "Replace train.py / train.sh with the user's script."}
121
+
122
+ @mcp.tool()
123
+ def decide_suggestion(run_id: int, suggestion_id: int, apply: bool) -> dict:
124
+ """Apply (apply=true) or dismiss a pending agent suggestion."""
125
+ return call("POST", f"/api/runs/{run_id}/suggestions/{suggestion_id}/{'apply' if apply else 'dismiss'}")
126
+
127
+ return mcp
128
+
129
+
130
+ def main() -> None:
131
+ missing = [v for v in ("STEER_EMAIL", "STEER_PASSWORD") if not os.getenv(v)]
132
+ if missing:
133
+ raise SystemExit(f"steer mcp: set {' and '.join(missing)} (and STEER_SERVER)")
134
+ http = login(os.getenv("STEER_SERVER", "http://localhost:8000"), os.environ["STEER_EMAIL"],
135
+ os.environ["STEER_PASSWORD"])
136
+ build(http).run() # stdio
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.4
2
+ Name: steer-ml
3
+ Version: 0.1.0
4
+ Summary: Live control of ML training runs
5
+ Requires-Python: >=3.10
6
+ Requires-Dist: websockets>=13
7
+ Requires-Dist: pydantic>=2
8
+ Provides-Extra: torch
9
+ Requires-Dist: torch; extra == "torch"
10
+ Provides-Extra: mcp
11
+ Requires-Dist: mcp>=2; extra == "mcp"
12
+ Requires-Dist: httpx; extra == "mcp"
@@ -0,0 +1,8 @@
1
+ steer/__init__.py,sha256=VSRxOsbKU_ADcFn9QgQsJA1OebSB6_SrDzdUburnaSI,25158
2
+ steer/__main__.py,sha256=fyciBWEsUf4qZSyjS35eTV2iBiSBO1CecFHk496uvPs,286
3
+ steer/mcp_server.py,sha256=EsZ5fP3BiDRKUSQYNl7ifPbv9HtoVwW2GoSaXqQAg5g,7240
4
+ steer_ml-0.1.0.dist-info/METADATA,sha256=DQmSQRl6pa8K6ePNtWQlqiexTxMgnJw7R2sshS-lNiM,331
5
+ steer_ml-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ steer_ml-0.1.0.dist-info/entry_points.txt,sha256=JsCvm9ZP_8hZ0ykxZeCsVY6-6E0eTPeEL1hwuOiAqQw,46
7
+ steer_ml-0.1.0.dist-info/top_level.txt,sha256=8X0JAc_JTgG1kNGOqdw0DlNgwkKOy_aREe1KJiyVusE,6
8
+ steer_ml-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ steer = steer.__main__:main
@@ -0,0 +1 @@
1
+ steer