The platform for continuously improving AI agents.
"""Live changes to a running training run: what a change may be, the limits that bound it,
and the file through which the worker hands changes to the training process."""
import json
import math
import os
from pathlib import Path
# A release whose trainer applies live changes carries this version in its identity.
VERSION = 1
# The worker reads the platform's requested changes from this Modal Dict, keyed by run id.
STORE = "overmind-training-controls"
# Applied by the training process at a step boundary. Stopping cancels the run instead.
DELIVERED = ("set_learning_rate", "set_clip_norm", "checkpoint", "restore_checkpoint", "finish")
OPERATIONS = (*DELIVERED, "stop")
DEFAULT_LIMITS = {
"max_seconds": 86400,
"max_cost_usd": 25,
"max_reviews": 12,
"max_interventions": 4,
"learning_rate": [1e-7, 0.01],
"clip_norm": [0.1, 2],
}
def _number(value, name, low, high):
if type(value) not in {int, float} or not math.isfinite(value) or not low <= value <= high:
raise ValueError(f"{name} must be a number between {low:g} and {high:g}")
return value
def _range(value, name, high):
if (
not isinstance(value, list)
or len(value) != 2
or _number(value[0], name, 0, high) <= 0
or _number(value[1], name, 0, high) < value[0]
):
raise ValueError(f"{name} must be a [low, high] range above 0 and at most {high:g}")
return [value[0], value[1]]
def limits(value):
"""The complete, validated execution limits; absent fields take the defaults."""
if value is None:
value = {}
if not isinstance(value, dict) or set(value) - set(DEFAULT_LIMITS):
raise ValueError(f"Execution limits take only {', '.join(DEFAULT_LIMITS)}")
merged = {**DEFAULT_LIMITS, **value}
for name, high in (("max_seconds", 86400), ("max_reviews", 100), ("max_interventions", 100)):
if type(merged[name]) is not int or not 1 <= merged[name] <= high:
raise ValueError(f"{name} must be a whole number between 1 and {high}")
_number(merged["max_cost_usd"], "max_cost_usd", 0.01, 1_000_000)
merged["learning_rate"] = _range(merged["learning_rate"], "learning_rate", 1)
merged["clip_norm"] = _range(merged["clip_norm"], "clip_norm", 100)
return merged
def arguments(operation, values, bounds, checkpoint_steps=()):
"""The arguments of one change, checked against the run's limits."""
if operation not in OPERATIONS:
raise ValueError(f"Unknown training change {operation!r}")
values = values or {}
if operation in {"set_learning_rate", "set_clip_norm"}:
name = "learning_rate" if operation == "set_learning_rate" else "clip_norm"
if set(values) != {"value"}:
raise ValueError(f"{operation} takes one value")
low, high = bounds[name]
return {"value": _number(values["value"], name.replace("_", " "), low, high)}
if operation == "restore_checkpoint":
if set(values) != {"step"} or type(values["step"]) is not int:
raise ValueError("restore_checkpoint takes the step of a retained checkpoint")
if values["step"] not in checkpoint_steps:
raise ValueError(f"No retained checkpoint at step {values['step']}")
return {"step": values["step"]}
if values:
raise ValueError(f"{operation} takes no arguments")
return {}
class Inbox:
"""The training process's side: changes the worker wrote to a local file, each taken
once. The file is local to the container, so reading it at every step costs nothing."""
def __init__(self, path=None):
path = path or os.environ.get("TRAINING_CONTROL_FILE")
self.path = Path(path) if path else None
self.seen = set()
def take(self):
if self.path is None or not self.path.exists():
return []
try:
commands = json.loads(self.path.read_text())
except (OSError, ValueError):
return []
fresh = [command for command in commands if command["id"] not in self.seen]
self.seen.update(command["id"] for command in fresh)
return fresh
def write_inbox(path, commands):
"""The worker's side: replace the inbox in one rename, so a reader never sees half."""
path = Path(path)
temporary = path.with_suffix(".tmp")
temporary.write_text(json.dumps(commands))
temporary.replace(path)