Coverage for scripts/cycle_retrain.py: 100%

326 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""A retrain anyone can run (V6.6.1): the same stages on this machine or on the training Codespace, resumable after a reboot, every stage logged. 

2 

3 python scripts/cycle_retrain.py --host local --procedure k06 # a machine with the RAM; builds its own data if it has none 

4 python scripts/cycle_retrain.py --host codespace --procedure k06 # drives the training Codespace from here, and stops it however the run ends 

5 python scripts/cycle_retrain.py --host local --smoke # every stage on a tiny synthetic panel: proves the plumbing on any machine 

6 

7A refit of a frozen procedure adds a vintage to its generation. A new procedure is a candidate: it goes through a research round first, and this script only writes its scores for that round. 

8""" 

9 

10from __future__ import annotations 

11 

12import argparse 

13import datetime 

14import hashlib 

15import json 

16import os 

17import shutil 

18import subprocess 

19import sys 

20import time as _time 

21import uuid 

22from collections.abc import Callable, Mapping, Sequence 

23from pathlib import Path 

24 

25ROOT = Path(__file__).resolve().parents[1] 

26sys.path.insert(0, str(ROOT)) 

27 

28from evaluation.research_cycle import ram_preflight, retrain_stages, stack_plan, stack_stages, validate_plan_flags # noqa: E402 

29from retraining import run_resume # noqa: E402 

30 

31CONTACT_ENV = "AQ_SEC_CONTACT" 

32STATE_ROOT = ROOT / "ml" / "cycle" 

33CODESPACE = "aq-Training-Ground-Fixed" 

34REMOTE_REPO = "/workspaces/Aether-quant" 

35# What a procedure trains. Adding one is a code change, visible in git: a retrain has no free-form command. 

36PROCEDURES: dict[str, dict] = { 

37 "k06": {"model": "gbm_monotone", "variant": "a", "seeds": "1,2,3", "feature_set": "fundamental", "train_start": "2011-07-01", "first_test_year": 2013, "purge_days": 31}, 

38 "k07": {"model": "mlp_multitask", "variant": "a", "seeds": "1,2,3,4,5", "feature_set": "fundamental", "train_start": "2011-07-01", "first_test_year": 2013, "purge_days": 31}, 

39 # V6.6.9: the model stack (`ml/`'s multitask, sequence and gating models) as one procedure. `stack` is the installed recipe, so a refit is a new vintage of 

40 # its generation (g0006); `stack_asof` (as-of labels, within-class ranked inputs) is a new procedure and only writes scores for a research round. 

41 "stack": {"kind": "stack", "mode": "expanding", "trainers": ["train.py", "train_multitask.py", "train_sequence.py", "train_gating.py"]}, 

42 "stack_asof": {"kind": "stack", "mode": "expanding", "asof_labels": True, "trainers": ["train.py", "train_multitask.py", "train_sequence.py", "train_gating.py"]}, 

43} 

44 

45 

46def _now() -> str: 

47 return datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0).isoformat() 

48 

49 

50def load_state(path: Path) -> dict: 

51 return json.loads(Path(path).read_text(encoding="utf-8")) if Path(path).exists() else {"done": {}} 

52 

53 

54def save_state(path: Path, state: Mapping) -> None: 

55 path = Path(path) 

56 path.parent.mkdir(parents=True, exist_ok=True) 

57 temporary = path.with_name(path.name + ".tmp") 

58 temporary.write_text(json.dumps(state, indent=1, sort_keys=True), encoding="utf-8", newline="\n") 

59 temporary.replace(path) 

60 

61 

62def run_stages(stages: Sequence[str], actions: Mapping[str, Callable[[], object]], *, state_path: Path, emit: Callable[[str], None] = print) -> dict: 

63 """Runs what isn't done yet, saving after each stage, so a reboot costs one stage at most. A failed stage stops the run: a later stage must not read a half-built result.""" 

64 state = load_state(state_path) 

65 for stage in stages: 

66 if stage in state["done"]: 

67 emit(f"{stage}: already done") 

68 continue 

69 emit(f"{stage}: running") 

70 result = actions[stage]() 

71 state["done"][stage] = {"at": _now(), "result": result if isinstance(result, (str, int, float, dict, list, type(None))) else str(result)} 

72 save_state(state_path, state) 

73 return state 

74 

75 

76def procedure_sha256(name: str, procedure: Mapping, trainer_source: bytes) -> str: 

77 """What makes two fits the same generation: the trainer's code and every setting, not the weights they produce.""" 

78 return hashlib.sha256(trainer_source + json.dumps({"name": name, **procedure}, sort_keys=True).encode("utf-8")).hexdigest() 

79 

80 

81def register_vintage(registry_path: Path, lifecycle_path: Path, procedure_sha: str, vintage: str, *, created_at: str) -> dict: 

82 """A refit of a frozen procedure is a new vintage of its generation (Problems #321): the vintage name goes on the generation whose `procedure_sha256` this is, with a hash-chained lifecycle 

83 row. A procedure no generation holds is a candidate and has no vintage to add: it goes through `aq cycle research` first. A vintage is added once.""" 

84 from dataclasses import replace 

85 

86 from evaluation.generation_registry import append_lifecycle, load_registry, save_registry 

87 

88 if not Path(registry_path).exists(): 

89 return {"added": False, "reason": "no registry"} 

90 registry = load_registry(Path(registry_path)) 

91 owner = next((generation for generation in registry.values() if generation.procedure_sha256 == procedure_sha), None) 

92 if owner is None: 

93 return {"added": False, "reason": "no generation holds this procedure: it is a candidate, and goes through a research round first"} 

94 if vintage in owner.vintages: 

95 return {"added": False, "generation": owner.id, "reason": "this vintage is already recorded"} 

96 registry[owner.id] = replace(owner, vintages=(*owner.vintages, vintage)) 

97 save_registry(Path(registry_path), registry) 

98 append_lifecycle(Path(lifecycle_path), event="vintage_added", created_at=created_at, payload={"generation": owner.id, "vintage": vintage, "procedure_sha256": procedure_sha}) 

99 return {"added": True, "generation": owner.id} 

100 

101 

102def sync_shell() -> str: 

103 """The PowerShell that runs scripts/codespace_sync.ps1: `pwsh` where it exists, else Windows PowerShell. Anywhere else the push script can't run, and that is said plainly.""" 

104 shell = shutil.which("pwsh") or shutil.which("powershell") 

105 if shell is None: 

106 raise RuntimeError("scripts/codespace_sync.ps1 needs PowerShell (pwsh or powershell on PATH); run the retrain on the Codespace itself with --host local --on-codespace") 

107 return shell 

108 

109 

110def trainer_command(python: str, name: str, procedure: Mapping, *, panel: str, out: str, score_end: str | None = None, year_cache: str | None = None) -> list[str]: 

111 """The cross-sectional trainer's command; `year_cache` keeps each test year's scores so a resumed walk-forward continues at its next year.""" 

112 command = [ 

113 python, "train_cross_sectional.py", "--panel", panel, "--model", str(procedure["model"]), "--variant", str(procedure["variant"]), "--seeds", str(procedure["seeds"]), 

114 "--feature-set", str(procedure["feature_set"]), "--train-start", str(procedure["train_start"]), "--first-test-year", str(procedure["first_test_year"]), "--purge-days", str(procedure["purge_days"]), "--out", out, 

115 ] 

116 command = [*command, "--score-end", score_end] if score_end else command 

117 return [*command, "--year-cache", year_cache] if year_cache else command 

118 

119 

120def _run_full(command: Sequence[str], *, cwd: Path = ROOT, runner: Callable = subprocess.run) -> str: 

121 """A failed step stops the run with what it said. The command is logged by name, and an environment value is never on it.""" 

122 result = runner(list(command), cwd=str(cwd), capture_output=True, text=True) 

123 if result.returncode != 0: 

124 raise RuntimeError(f"{command[0]} {' '.join(command[1:3])} exit {result.returncode}: {(result.stderr or result.stdout or '')[-800:]}") 

125 return result.stdout or "" 

126 

127 

128def _run(command: Sequence[str], *, cwd: Path = ROOT, runner: Callable = subprocess.run) -> str: 

129 return _run_full(command, cwd=cwd, runner=runner)[-400:] 

130 

131 

132def local_actions(name: str, procedure: Mapping, *, run_dir: Path, python: str = sys.executable, runner: Callable = subprocess.run) -> dict[str, Callable[[], object]]: 

133 panel = "data_wide/reference/panel_TA.parquet" 

134 scores = run_dir / f"{name}.csv" 

135 

136 def go(*command: str) -> str: 

137 return _run([python, *command], runner=runner) 

138 

139 def bootstrap() -> str: 

140 if not os.environ.get(CONTACT_ENV, "").strip(): 

141 raise RuntimeError(f"bootstrap_data builds EDGAR fundamentals, which SEC refuses without a contact: set {CONTACT_ENV} for this run (it is never stored)") 

142 go("scripts/build_wide_root.py") 

143 go("scripts/build_wide_info.py") 

144 return "built data_wide from public sources" 

145 

146 def refresh() -> str: 

147 return go("scripts/data_append_refresh.py", "--apply") 

148 

149 def build_panel() -> str: 

150 return go("scripts/v660_build_panel.py", "TA", "--out", panel) if not (ROOT / panel).exists() else "panel present" 

151 

152 def walk() -> str: 

153 return _run(trainer_command(python, name, procedure, panel=panel, out=str(scores), year_cache=str(run_dir / "years")), runner=runner) 

154 

155 def score() -> dict: 

156 if not scores.exists(): 

157 raise RuntimeError(f"{scores} was not written") 

158 return {"scores": str(scores.relative_to(ROOT)) if scores.is_relative_to(ROOT) else str(scores), "sha256": hashlib.sha256(scores.read_bytes()).hexdigest()} 

159 

160 def gate() -> str: 

161 return "a refit keeps its procedure's verdict; a new procedure needs `aq cycle research`: nothing is promoted here" 

162 

163 def register() -> dict: 

164 trainer = (ROOT / "train_cross_sectional.py").read_bytes() 

165 sha = procedure_sha256(name, procedure, trainer) 

166 recorded = register_vintage(ROOT / "ml" / "generations" / "registry.json", ROOT / "ml" / "generations" / "lifecycle.jsonl", sha, run_dir.name, created_at=_now()) 

167 return {"procedure": name, "procedure_sha256": sha, "vintage": run_dir.name, "registered": recorded} 

168 

169 def report() -> str: 

170 return str(run_dir) 

171 

172 return {"bootstrap_data": bootstrap, "refresh_data": refresh, "build_panel": build_panel, "walk_forward": walk, "score": score, "round": gate, "register": register, "report": report} 

173 

174 

175def stack_actions( 

176 name: str, procedure: Mapping, *, run_dir: Path, run_id: str, python: str = sys.executable, runner: Callable = subprocess.run, score_end: str | None = None, 

177 profile: str = "standard", resume_walk_forward: str | None = None, 

178) -> dict[str, Callable[[], object]]: 

179 """The model stack's stages (`evaluation.research_cycle.stack_plan`): each a command from the plan, or one of three that run here. The walk-forward's run id is read 

180 from its own output, so `scores` knows which windows to score.""" 

181 import re 

182 

183 from retraining.artifact_pins import snapshot_active, write_artifact_pins 

184 

185 plan = dict(stack_plan(procedure, run_id=run_id, python=python, score_end=score_end, profile=profile, resume_id=resume_walk_forward)) 

186 # a walk-forward stopped part way continues its own windows (V6.6.10): the scores stage reads that run 

187 found: dict[str, str] = {"walk_forward": resume_walk_forward} if resume_walk_forward else {} 

188 

189 def command_stage(stage: str) -> Callable[[], object]: 

190 def run() -> object: 

191 command = plan[stage] 

192 if command is None: 

193 return "skipped: pass --score-end, the last date the next round may read" 

194 if stage == "scores": 

195 command = [*command[:3], found["walk_forward"], *command[4:]] 

196 output = _run_full(command, runner=runner) 

197 if stage == "walk_forward": 

198 # the id is logged to stderr at the start and printed to stdout at the end ("Walk-forward run <id>: ..."); a resumed run knows it already 

199 match = re.search(r"(walk-forward-[0-9a-f][0-9a-f-]+)", output) 

200 if match is None and "walk_forward" not in found: 

201 raise RuntimeError("the walk-forward printed no run id; its windows cannot be found") 

202 if match is not None: 

203 found["walk_forward"] = match.group(1) 

204 return output[-400:] 

205 

206 return run 

207 

208 def snapshot() -> str: 

209 return str(snapshot_active(ROOT / "ml", ROOT / "ml" / "backups" / f"pre_retrain_{run_id}.zip")) 

210 

211 def pins() -> dict: 

212 return write_artifact_pins(ROOT / "ml" / "versions" / f"{run_id}_base", run_dir / "artifact_pins.json") 

213 

214 def register() -> dict: 

215 source = b"".join((ROOT / trainer).read_bytes() for trainer in procedure["trainers"]) 

216 sha = procedure_sha256(name, procedure, source) 

217 recorded = register_vintage(ROOT / "ml" / "generations" / "registry.json", ROOT / "ml" / "generations" / "lifecycle.jsonl", sha, run_id, created_at=_now()) 

218 return {"procedure": name, "procedure_sha256": sha, "vintage": run_id, "registered": recorded} 

219 

220 actions = {stage: command_stage(stage) for stage in stack_stages()} 

221 actions.update(snapshot_active=snapshot, pins=pins, register=register, report=lambda: str(run_dir)) 

222 return actions 

223 

224 

225def memory_estimate(dataset: Path, config_path: Path, *, schema: Path | None = None) -> dict: 

226 """Each memory profile's estimated peak for the sequence stage (the stack's largest) on this dataset, and this machine's RAM: what 

227 `--estimate` prints before anyone spends a night on a run that cannot fit.""" 

228 from evaluation.research_cycle import GIB, total_memory_bytes 

229 from retraining.slicing import PROFILES, estimate_peak_gb 

230 

231 if not dataset.exists(): 

232 return {"dataset": str(dataset), "error": "no dataset: build one first (train.py --dataset-only)"} 

233 with dataset.open("rb") as handle: 

234 columns = len(handle.readline().split(b",")) 

235 rows = sum(chunk.count(b"\n") for chunk in iter(lambda: handle.read(1 << 22), b"")) 

236 schema = schema or dataset.parents[1] / "feature_schema.json" 

237 features = len(json.loads(schema.read_text(encoding="utf-8"))["model_input_names"]) if schema.exists() else columns 

238 window = int(json.loads(config_path.read_text(encoding="utf-8"))["phase_v2"]["retraining"]["sequence_training"].get("window_size", 30)) 

239 total = total_memory_bytes() 

240 return { 

241 "dataset": str(dataset), "rows": rows, "columns": columns, "features": features, "window": window, 

242 "machine_gb": None if total is None else round(total / GIB, 1), 

243 "estimated_peak_gb": {name: estimate_peak_gb(rows, columns, features, window=window, profile=name) for name in PROFILES}, 

244 } 

245 

246 

247def smoke_panel(path: Path, *, seed: int = 3) -> None: 

248 """A tiny synthetic panel: three years, 40 names, a planted signal. Small enough for any machine.""" 

249 import numpy as np 

250 import pandas as pd 

251 

252 from train_cross_sectional import FUNDAMENTAL_SIGNS 

253 

254 rng = np.random.default_rng(seed) 

255 dates = [day.strftime("%Y-%m-%d") for day in pd.bdate_range("2012-01-02", "2014-12-31", freq="5B")] 

256 tickers = [f"T{index:02d}" for index in range(40)] 

257 rows = [] 

258 for date in dates: 

259 block = {name: rng.normal(size=len(tickers)) for name in FUNDAMENTAL_SIGNS} 

260 signal = sum(sign * block[name] for name, sign in FUNDAMENTAL_SIGNS.items()) / len(FUNDAMENTAL_SIGNS) 

261 label = signal + rng.normal(scale=0.3, size=len(tickers)) 

262 label = (pd.Series(label).rank(pct=True) - 0.5).to_numpy() 

263 rows.append(pd.DataFrame({"date": date, "ticker": tickers, "sector": "tech", "target_wide_20d": label, **block})) 

264 Path(path).parent.mkdir(parents=True, exist_ok=True) 

265 pd.concat(rows, ignore_index=True).to_parquet(path) 

266 

267 

268def smoke_actions(*, run_dir: Path, python: str = sys.executable, runner: Callable = subprocess.run) -> dict[str, Callable[[], object]]: 

269 """Every stage on the synthetic panel with the small tree model: no real data read, no download.""" 

270 panel = run_dir / "panel.parquet" 

271 scores = run_dir / "smoke.csv" 

272 procedure = {**PROCEDURES["k06"], "seeds": "1", "train_start": "2012-01-01", "first_test_year": 2014, "purge_days": 20} 

273 

274 def build() -> str: 

275 smoke_panel(panel) 

276 return str(panel.name) 

277 

278 def walk() -> str: 

279 return _run(trainer_command(python, "smoke", procedure, panel=str(panel), out=str(scores)), runner=runner) 

280 

281 def score() -> dict: 

282 import pandas as pd 

283 

284 frame = pd.read_csv(scores) 

285 if frame.empty or not frame["score"].notna().all(): 

286 raise RuntimeError("the smoke run wrote no usable scores") 

287 return {"rows": int(len(frame)), "sha256": hashlib.sha256(scores.read_bytes()).hexdigest()} 

288 

289 return { 

290 "bootstrap_data": lambda: "skipped: a synthetic panel", "refresh_data": lambda: "skipped: a synthetic panel", "build_panel": build, "walk_forward": walk, "score": score, 

291 "round": lambda: "skipped: a synthetic panel earns no verdict", "register": lambda: "skipped: a synthetic panel is no generation", "report": lambda: str(run_dir.name), 

292 } 

293 

294 

295def remote_command(name: str, *, run_id: str, smoke: bool = False, resume: bool = False) -> list[str]: 

296 """What runs over there: this same script, as a local run on that machine. The argv holds no quote or space, since Windows OpenSSH strips quotes from a command line. 

297 `resume` (V6.6.10): continue that machine's own run folder (its resume.json and walk_forward_run_id), so a stopped walk-forward keeps its windows.""" 

298 flags = ["--smoke"] if smoke else ["--procedure", name] 

299 return ["python3", f"{REMOTE_REPO}/scripts/cycle_retrain.py", "--host", "local", *flags, "--run-id", run_id, "--on-codespace", *(["--resume", run_id] if resume else [])] 

300 

301 

302def resolve_codespace(name: str, *, gh: Sequence[str] = ("gh", "codespace"), runner: Callable = subprocess.run) -> str: 

303 """`gh codespace ... -c` wants the generated name; the training Codespace is known by its display name.""" 

304 result = runner([*gh, "list", "--json", "name,displayName"], cwd=str(ROOT), capture_output=True, text=True) 

305 if result.returncode != 0: 

306 raise RuntimeError(f"gh codespace list exit {result.returncode}: {(result.stderr or '')[-300:]}") 

307 for entry in json.loads(result.stdout or "[]"): 

308 if name in (entry.get("name"), entry.get("displayName")): 

309 return str(entry["name"]) 

310 raise RuntimeError(f"no Codespace named or titled {name!r} (gh codespace list)") 

311 

312 

313def wait_until_reachable( 

314 codespace: str, *, gh: Sequence[str] = ("gh", "codespace"), runner: Callable = subprocess.run, sleep: Callable[[float], None] = _time.sleep, attempts: int = 40, pause_seconds: float = 15.0, 

315) -> None: 

316 """A Codespace stopped a moment ago answers nothing until it has shut down, and a push would then report only that it found no repo. `ssh` starts a stopped one.""" 

317 for _ in range(attempts): 

318 listed = runner([*gh, "list", "--json", "name,state"], cwd=str(ROOT), capture_output=True, text=True) 

319 states = {entry.get("name"): entry.get("state") for entry in json.loads(listed.stdout or "[]")} if listed.returncode == 0 else {} 

320 if states.get(codespace) in ("Available", "Shutdown"): 

321 probe = runner([*gh, "ssh", "-c", codespace, "--", "test", "-f", "/workspaces/Aether-quant/train.py"], cwd=str(ROOT), capture_output=True, text=True) 

322 if probe.returncode == 0: 

323 return 

324 sleep(pause_seconds) 

325 raise RuntimeError(f"{codespace} did not become reachable") 

326 

327 

328def drive_codespace( 

329 name: str, procedure: Mapping, *, run_id: str, smoke: bool, codespace: str = CODESPACE, runner: Callable = subprocess.run, emit: Callable[[str], None] = print, 

330 gh: Sequence[str] = ("gh", "codespace"), scratch: Path | None = None, sleep: Callable[[float], None] = _time.sleep, attempts: int = 6, resume: bool = False, 

331) -> dict: 

332 """Start, push the code, run, pull, and stop in a `finally`: a Codespace left running bills the owner, so stopping doesn't depend on the run going well.""" 

333 work = Path(scratch) if scratch else STATE_ROOT / f"retrain_{run_id}" 

334 work.mkdir(parents=True, exist_ok=True) 

335 codespace = resolve_codespace(codespace, gh=gh, runner=runner) 

336 try: 

337 wait_until_reachable(codespace, gh=gh, runner=runner, sleep=sleep) 

338 _run([sync_shell(), "-NoProfile", "-File", "scripts/codespace_sync.ps1", "-Mode", "push", "-CodeOnly", "-Codespace", codespace], runner=runner) 

339 emit("code pushed") 

340 # The VM reboots about hourly, which drops this session. Stages resume, so another attempt continues the run. 

341 for attempt in range(1, attempts + 1): 

342 try: 

343 # every attempt after the first (the VM rebooted mid-run) continues the run there, as `--resume` does 

344 emit(_run([*gh, "ssh", "-c", codespace, "--", *remote_command(name, run_id=run_id, smoke=smoke, resume=resume or attempt > 1)], runner=runner)) 

345 break 

346 except RuntimeError as error: 

347 if attempt == attempts: 

348 raise 

349 emit(f"attempt {attempt} ended: {str(error)[:200]}; resuming") 

350 wait_until_reachable(codespace, gh=gh, runner=runner, sleep=sleep) 

351 # `gh codespace cp` quotes a remote path, which Windows' scp reads literally, so the state comes back over ssh. 

352 state = _run_full([*gh, "ssh", "-c", codespace, "--", "cat", f"{REMOTE_REPO}/ml/cycle/retrain_{run_id}/state.json"], runner=runner) 

353 (work / "state.json").write_text(state, encoding="utf-8", newline="\n") 

354 pulled = load_state(work / "state.json") 

355 # the scores are the point of a retrain and they stayed on the Codespace: bring them back the same way, so a stopped Codespace loses nothing 

356 scores_file = (((pulled.get("done") or {}).get("score") or {}).get("result") or {}).get("scores") 

357 if scores_file: 

358 remote = scores_file if scores_file.startswith("/") else f"{REMOTE_REPO}/{scores_file}" 

359 text = _run_full([*gh, "ssh", "-c", codespace, "--", "cat", remote], runner=runner) 

360 (work / Path(scores_file).name).write_text(text, encoding="utf-8", newline="\n") 

361 emit(f"scores pulled: {work / Path(scores_file).name}") 

362 return {"ran": True, "state": pulled} 

363 finally: 

364 result = runner([*gh, "stop", "-c", codespace], cwd=str(ROOT), capture_output=True, text=True) 

365 emit(f"Codespace stop exit {result.returncode}") 

366 if result.returncode != 0: 

367 # It bills while it runs, so this must not pass quietly. 

368 print(f"THE CODESPACE {codespace} DID NOT STOP: gh codespace stop -c {codespace} ({(result.stderr or '')[-200:]})", file=sys.stderr) 

369 

370 

371RESUME_KEYS = ("host", "procedure", "smoke", "memory_profile", "score_end", "min_ram_gb") 

372 

373 

374def write_resume(run_dir: Path, args: argparse.Namespace, *, run_id: str) -> dict: 

375 """The run's resume record (V6.6.10): what `--resume` needs to continue it with the same settings, and where the snapshot 

376 of the installed models went. Written once when the run starts; the walk-forward adds its own run id beside it.""" 

377 record = {"run_id": run_id, **{key: getattr(args, key) for key in RESUME_KEYS}, "started": _now(), 

378 "snapshot": str(ROOT / "ml" / "backups" / f"pre_retrain_{run_id}.zip")} 

379 run_dir.mkdir(parents=True, exist_ok=True) 

380 (run_dir / "resume.json").write_text(json.dumps(record, indent=1), encoding="utf-8", newline="\n") 

381 return record 

382 

383 

384def find_resumable(state_root: Path, run_id: str | None = None) -> Path | None: 

385 """The run folder to continue: the named one, or the newest whose resume record exists and whose last stage has not run.""" 

386 return run_resume.find_resumable(state_root, "retrain_", run_id, last_step="report") 

387 

388 

389def resume_args(args: argparse.Namespace, *, state_root: Path) -> argparse.Namespace | None: 

390 """`--resume [RUN_ID]`: the stopped run's own settings, its run id and the walk-forward it had started; None when there is none.""" 

391 folder = find_resumable(state_root, None if args.resume == "latest" else args.resume) 

392 if folder is None: 

393 return None 

394 record = json.loads((folder / "resume.json").read_text(encoding="utf-8")) 

395 walk_forward = folder / "walk_forward_run_id" 

396 merged = argparse.Namespace(**{**vars(args), **{key: record.get(key) for key in RESUME_KEYS}, "run_id": record["run_id"]}) 

397 merged.resume_walk_forward = args.resume_walk_forward or (walk_forward.read_text(encoding="utf-8").strip() if walk_forward.exists() else None) 

398 return merged 

399 

400 

401def main(argv: list[str] | None = None) -> int: 

402 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) 

403 parser.add_argument("--host", choices=["local", "codespace"], default=None, help="required, except with --resume (the run's own) or --estimate") 

404 parser.add_argument("--procedure", default=None, choices=sorted(PROCEDURES)) 

405 parser.add_argument("--smoke", action="store_true") 

406 parser.add_argument("--run-id", default=None) 

407 parser.add_argument("--min-ram-gb", type=float, default=None, help="override the memory profile's minimum (standard 14, low 3.5)") 

408 parser.add_argument("--memory-profile", choices=["standard", "low"], default="standard", help="low: train the stack on a 4 GB machine, slower (V6.6.10)") 

409 parser.add_argument("--estimate", action="store_true", help="print each profile's estimated peak memory for the active dataset, and stop") 

410 parser.add_argument("--dry-run", action="store_true", help="print the stages and the preflight, and stop") 

411 parser.add_argument("--score-end", default=None, help="a stack run: the last date of the walk-forward scores (the next research round's window)") 

412 parser.add_argument("--resume-walk-forward", default=None, metavar="RUN_ID", help="a stack run: continue this walk-forward run's windows instead of starting a new one") 

413 parser.add_argument("--resume", nargs="?", const="latest", default=None, metavar="RUN_ID", 

414 help="continue a stopped run with its own settings (the newest unfinished one, or RUN_ID): finished stages are skipped, the walk-forward continues its windows, the sequence trainer its checkpoint") 

415 parser.add_argument("--list-runs", action="store_true", help="list every retrain and `aq train` run with a resume record: its finished stages and whether it can be resumed") 

416 parser.add_argument("--on-codespace", action="store_true", help=argparse.SUPPRESS) 

417 args = parser.parse_args(argv) 

418 if args.list_runs: 

419 print(run_resume.render_runs(run_resume.list_runs(STATE_ROOT, ["retrain_", "train_"], last_step="report"))) 

420 return 0 

421 if args.resume: 

422 resumed = resume_args(args, state_root=STATE_ROOT) 

423 if resumed is None and (args.procedure or args.smoke) and args.run_id: 

424 # a retry whose first attempt never got to write its record: the settings came along, so the run starts now 

425 print(f"no resume record for {args.run_id} yet: starting it") 

426 resumed = args 

427 elif resumed is None: 

428 print("nothing to resume: no unfinished run with a resume record under " + str(STATE_ROOT), file=sys.stderr) 

429 return 1 

430 args = resumed 

431 print(f"resuming {args.run_id}" + (f" (walk-forward {args.resume_walk_forward})" if args.resume_walk_forward else "")) 

432 if args.host is None and not args.estimate: 

433 parser.error("name a --host, or --resume a run") 

434 if args.estimate: 

435 print(json.dumps(memory_estimate(ROOT / "ml" / "datasets" / "full_dataset.csv", ROOT / "config.json"), indent=1)) 

436 return 0 

437 if not args.smoke and not args.procedure: 

438 parser.error("name a --procedure, or run --smoke") 

439 run_id = args.run_id or f"{datetime.datetime.now(datetime.timezone.utc):%Y%m%d}_{uuid.uuid4().hex[:6]}" 

440 run_dir = STATE_ROOT / f"retrain_{run_id}" 

441 state_path = run_dir / "state.json" 

442 chosen = PROCEDURES.get(args.procedure) if args.procedure else None 

443 is_stack = chosen is not None and chosen.get("kind") == "stack" 

444 name = args.procedure if is_stack else ("smoke" if args.smoke else args.procedure) 

445 procedure = chosen if is_stack else PROCEDURES.get(name, PROCEDURES["k06"]) 

446 preflight = ram_preflight(args.host, min_gb=args.min_ram_gb, profile=args.memory_profile) 

447 data_present = args.smoke or (ROOT / "data_wide" / "wide_manifest.json").exists() 

448 if args.smoke and args.procedure and is_stack: 

449 # a stack's plumbing is proved by its commands: every flag the plan passes is one its trainer lists 

450 problems = validate_plan_flags( 

451 stack_plan(procedure, run_id=run_id, python=sys.executable, score_end="2023-06-30", resume_id="walk-forward-smoke", profile=args.memory_profile), runner=subprocess.run, 

452 ) 

453 print(json.dumps({"run": run_id, "procedure": name, "stages": stack_stages(), "flag_problems": problems}, indent=1)) 

454 return 1 if problems else 0 

455 stages = stack_stages() if is_stack else retrain_stages(data_present=data_present) 

456 print(json.dumps({"run": run_id, "host": args.host, "procedure": name, "smoke": args.smoke, "memory_profile": args.memory_profile, "preflight": preflight, "stages": stages}, indent=1)) 

457 if args.dry_run: 

458 return 0 if (preflight["ok"] or args.smoke) else 2 

459 if args.host == "codespace": 

460 if not (run_dir / "resume.json").exists(): 

461 write_resume(run_dir, args, run_id=run_id) 

462 drive_codespace(name, procedure, run_id=run_id, smoke=args.smoke, resume=bool(args.resume)) 

463 return 0 

464 if not preflight["ok"] and not args.smoke and not args.on_codespace: 

465 print(f"refusing: {preflight['reason']}", file=sys.stderr) 

466 return 2 

467 run_dir.mkdir(parents=True, exist_ok=True) 

468 if not (run_dir / "resume.json").exists(): 

469 write_resume(run_dir, args, run_id=run_id) 

470 if is_stack: 

471 actions = stack_actions(name, procedure, run_dir=run_dir, run_id=run_id, score_end=args.score_end, profile=args.memory_profile, 

472 resume_walk_forward=args.resume_walk_forward) 

473 else: 

474 actions = smoke_actions(run_dir=run_dir) if args.smoke else local_actions(name, procedure, run_dir=run_dir) 

475 run_stages(stages, actions, state_path=state_path) 

476 print(f"done: {state_path}") 

477 return 0 

478 

479 

480if __name__ == "__main__": 

481 raise SystemExit(main())