#!/usr/bin/env python3 """Keep a training run going across restarts: run in chunks, auto-`--resume`. This wraps the normal trainer. Each "chunk" runs `PPOTrainer` (with resume) up to a slightly higher iteration target; when it finishes the chunk, the wrapper bumps the target and runs again — indefinitely, or until `--max-iterations`. It reuses the run's saved hyperparameters (runs//config.json), so settings are preserved exactly. Robustness: - Each chunk runs in a **child process**, so a crash in one chunk doesn't kill the loop (it retries a few times, then gives up). - The dashboard **Stop** button is honored: if a chunk exits because of a stop request (status.json state == "stopped"), the wrapper halts instead of relaunching. Pause is handled inside the trainer (it idles), so the wrapper isn't involved. Examples: # Continue an existing run forever (e.g. v2), in 500-iter chunks: python3 scripts/train_forever.py --run-name v2 --chunk 500 # Continue, but cap the total at 20000 iterations: python3 scripts/train_forever.py --run-name v2 --chunk 500 --max-iterations 20000 """ import argparse import json import multiprocessing as mp import os import sys import time sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from koehandel.training.metrics import run_paths # noqa: E402 from koehandel.training.ppo import PPOConfig, PPOTrainer # noqa: E402 _PPO_FIELDS = set(PPOConfig.__dataclass_fields__.keys()) def _run_chunk(config_dict: dict, target: int) -> None: """Child-process entrypoint: run the trainer up to `target` iterations (resuming).""" cfg = PPOConfig(**{k: v for k, v in config_dict.items() if k in _PPO_FIELDS}) cfg.iterations = target cfg.resume = True PPOTrainer(cfg).train() def _read_status(paths) -> dict: try: with open(paths.status_path) as f: return json.load(f) except (OSError, json.JSONDecodeError, AttributeError): return {} def _control_command(paths) -> str: try: with open(os.path.join(paths.root, "control.json")) as f: return json.load(f).get("command", "run") except (OSError, json.JSONDecodeError): return "run" def _current_iteration(paths) -> int: path = os.path.join(paths.root, "status.json") try: with open(path) as f: return int(json.load(f).get("iteration", 0)) except (OSError, json.JSONDecodeError, ValueError): return 0 def main(): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--run-name", required=True, help="existing run under runs/") p.add_argument("--chunk", type=int, default=500, help="iterations per chunk") p.add_argument("--max-iterations", type=int, default=0, help="overall cap (0 = run indefinitely)") p.add_argument("--max-retries", type=int, default=3, help="consecutive crash retries before giving up") args = p.parse_args() paths = run_paths(args.run_name) config_file = os.path.join(paths.root, "config.json") if not os.path.isfile(config_file): sys.exit(f"No config.json in runs/{args.run_name}/. Start the run once with " f"scripts/train.py first, then use this wrapper to keep it going.") with open(config_file) as f: config_dict = json.load(f) ctx = mp.get_context("spawn") # safe with torch retries = 0 round_n = 0 print(f"[forever] continuing run '{args.run_name}' in chunks of {args.chunk}" + (f", cap {args.max_iterations}" if args.max_iterations else ", no cap"), flush=True) while True: # Honor a Stop clicked between chunks (a chunk's own startup would clear it). if _control_command(paths) == "stop": print("[forever] stop command present; not launching another chunk.", flush=True) break done = _current_iteration(paths) if args.max_iterations and done >= args.max_iterations: print(f"[forever] reached cap ({done} >= {args.max_iterations}); done.", flush=True) break target = done + args.chunk if args.max_iterations: target = min(target, args.max_iterations) round_n += 1 print(f"[forever] round {round_n}: training {done} -> {target} ...", flush=True) proc = ctx.Process(target=_run_chunk, args=(config_dict, target)) proc.start() proc.join() state = _read_status(paths).get("state", "unknown") new_done = _current_iteration(paths) if proc.exitcode != 0 and state != "stopped": retries += 1 print(f"[forever] chunk crashed (exit {proc.exitcode}); retry {retries}/{args.max_retries}", flush=True) if retries >= args.max_retries: print("[forever] too many crashes; giving up.", flush=True) break time.sleep(3) continue retries = 0 if state == "stopped": print(f"[forever] run was stopped (via dashboard/signal) at iter {new_done}; " f"not relaunching.", flush=True) break if new_done <= done: print(f"[forever] no progress made ({done} -> {new_done}); stopping to avoid a loop.", flush=True) break print("[forever] exiting.", flush=True) if __name__ == "__main__": main()