"""Thread-safe training progress for the FastAPI /train dashboard.""" from __future__ import annotations import json import os import threading from dataclasses import dataclass, field from datetime import datetime, timezone from pathlib import Path from typing import Any, Callable @dataclass class UnitProgress: """One train job: a single (architecture, seed, fold) run.""" arch: str seed: int fold: int run_tag: str status: str = "queued" # queued | running | done | skipped | error epoch: int = 0 epochs: int = 0 loss: float | None = None val_acc: float | None = None best_acc: float | None = None message: str = "" error: str | None = None @dataclass class SuiteProgress: running: bool = False started_at: str | None = None finished_at: str | None = None total_units: int = 0 completed_units: int = 0 units: list[UnitProgress] = field(default_factory=list) log_tail: list[str] = field(default_factory=list) _lock: threading.Lock = field(default_factory=threading.Lock, repr=False) def to_api_dict(self) -> dict[str, Any]: with self._lock: return { "running": self.running, "started_at": self.started_at, "finished_at": self.finished_at, "total_units": self.total_units, "completed_units": self.completed_units, "units": [ { "arch": u.arch, "seed": u.seed, "fold": u.fold, "run_tag": u.run_tag, "status": u.status, "epoch": u.epoch, "epochs": u.epochs, "loss": u.loss, "val_acc": u.val_acc, "best_acc": u.best_acc, "message": u.message, "error": u.error, } for u in self.units ], "log_tail": list(self.log_tail), } def reset_for_new_run(self, unit_specs: list[tuple[str, int, int, str]]) -> None: """*unit_specs*: list of (arch, seed, fold_idx, run_tag).""" with self._lock: self.units = [ UnitProgress(arch=a, seed=s, fold=f, run_tag=tag) for a, s, f, tag in unit_specs ] self.total_units = len(self.units) self.completed_units = 0 self.log_tail = [] def mark_suite_start(self, started_at: str) -> None: with self._lock: self.running = True self.started_at = started_at self.finished_at = None self.completed_units = 0 def mark_suite_end(self, finished_at: str) -> None: with self._lock: self.running = False self.finished_at = finished_at def _find_unit(self, arch: str, seed: int, fold: int) -> UnitProgress | None: for u in self.units: if u.arch == arch and u.seed == seed and u.fold == fold: return u return None def unit_start(self, arch: str, seed: int, fold: int, epochs: int) -> None: with self._lock: u = self._find_unit(arch, seed, fold) if u: u.status = "running" u.epochs = epochs u.message = "Training…" def unit_epoch( self, arch: str, seed: int, fold: int, epoch: int, epochs: int, *, loss: float | None = None, val_acc: float | None = None, best_acc: float | None = None, ) -> None: with self._lock: u = self._find_unit(arch, seed, fold) if u: u.epoch = epoch u.epochs = epochs if loss is not None: u.loss = round(loss, 5) if val_acc is not None: u.val_acc = round(val_acc, 4) if best_acc is not None: u.best_acc = round(best_acc, 4) u.message = f"Epoch {epoch}/{epochs}" def unit_skip(self, arch: str, seed: int, fold: int) -> None: with self._lock: u = self._find_unit(arch, seed, fold) if u: u.status = "skipped" u.message = "Already completed (resume)" self.completed_units += 1 def unit_done(self, arch: str, seed: int, fold: int, message: str = "") -> None: with self._lock: u = self._find_unit(arch, seed, fold) if u: u.status = "done" u.epoch = u.epochs u.message = message or "Finished" self.completed_units += 1 def unit_error(self, arch: str, seed: int, fold: int, err: str) -> None: with self._lock: u = self._find_unit(arch, seed, fold) if u: u.status = "error" u.error = err[:2000] u.message = "Failed" self.completed_units += 1 def append_log(self, line: str, max_lines: int = 120) -> None: line = line.rstrip() if not line: return with self._lock: self.log_tail.append(line) if len(self.log_tail) > max_lines: self.log_tail = self.log_tail[-max_lines:] def should_write_progress_json() -> bool: """When true, each run writes ``experiments/.../progress.json`` (for GCS + local dashboard sync).""" v = (os.environ.get("EXCEL_CHUNKER_WRITE_PROGRESS_JSON") or "1").strip().lower() return v not in ("0", "false", "no", "off") def write_unit_progress_file( exp_dir: Path, *, arch: str, seed: int, fold: int, run_tag: str, status: str, epoch: int = 0, epochs: int = 0, loss: float | None = None, val_acc: float | None = None, best_acc: float | None = None, message: str = "", error: str | None = None, ) -> None: """Atomic write of per-unit progress (read by local app from GCS or local disk).""" exp_dir.mkdir(parents=True, exist_ok=True) data: dict[str, Any] = { "arch": arch, "seed": seed, "fold": fold, "run_tag": run_tag, "status": status, "epoch": epoch, "epochs": epochs, "loss": round(float(loss), 5) if loss is not None else None, "val_acc": round(float(val_acc), 4) if val_acc is not None else None, "best_acc": round(float(best_acc), 4) if best_acc is not None else None, "message": message, "error": (error[:2000] if error else None), "updated_at": datetime.now(timezone.utc).isoformat(), } path = exp_dir / "progress.json" tmp = exp_dir / ".progress.json.tmp" tmp.write_text(json.dumps(data, indent=2), encoding="utf-8") tmp.replace(path) def build_unit_plan( architectures: list[str], seeds: list[int], fold_indices: list[int], ) -> list[tuple[str, int, int, str]]: """Cartesian product in the same order as ``run_experiments`` loops.""" out: list[tuple[str, int, int, str]] = [] for seed in seeds: for fold_idx in fold_indices: for arch in architectures: tag = f"{arch}_s{seed}_f{fold_idx}" out.append((arch, seed, fold_idx, tag)) return out