"""Log and runtime recording for every run. python -m ml_porosity.runlog [-n NAME] [--note "..."] [--] [args...] python -m ml_porosity.runlog ls [-k 30] # most recent runs + runs in progress python -m ml_porosity.runlog reindex # rebuild logs/index.csv from the meta.json files Each run creates `logs/runs/_/` (root overridable via ML_POROSITY_LOGS): log.txt merged stdout + stderr, including child workers (ProcessPool); each line carries the elapsed time [h:mm:ss] meta.json command, cwd, git commit + dirty state + source hash, thread/GPU variables, device, start/end, wall/CPU time, peak RSS, peak VRAM of the process tree, exit code; written at start with status=running and appends one row to `logs/index.csv`. A `.py` file at the head of the command is run with the current python. For nested calls (RUNLOG_DIR already set, e.g. the individual steps of scripts/run_p2.sh), the child step is placed inside the parent run's directory, and the `parent` column of the index points to the parent run. """ from __future__ import annotations import argparse import csv import datetime as dt import fcntl import hashlib import json import os import platform import re import resource import shlex import signal import socket import subprocess import sys import threading import time from pathlib import Path from .paths import REPO_ROOT FIELDS = ["run_id", "parent", "name", "status", "exit_code", "start", "end", "wall_s", "wall", "device", "git", "dirty", "code_sha", "source", "cmd"] ENV_KEYS = ["CUDA_VISIBLE_DEVICES", "OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS", "NUMBA_NUM_THREADS", "PYTHONHASHSEED", "DEVICE", "WORKERS", "ML_POROSITY_OUTPUTS"] CODE_DIRS = ["ml_porosity", "scripts", "configs", "tests"] GPU_POLL_S = 15.0 def logs_dir() -> Path: env = os.environ.get("ML_POROSITY_LOGS") return Path(env) if env else REPO_ROOT / "logs" def now() -> dt.datetime: return dt.datetime.now().astimezone() def fmt_wall(s: float | None) -> str: if s is None: return "" h, r = divmod(int(round(s)), 3600) return f"{h}:{r // 60:02d}:{r % 60:02d}" def _out(cmd: list[str]) -> str: try: return subprocess.run(cmd, capture_output=True, text=True, timeout=20, cwd=REPO_ROOT).stdout.strip() except (OSError, subprocess.SubprocessError): return "" def git_state() -> dict: """Commit + working-tree state. Since uncommitted code may also be run, a content hash of the files in CODE_DIRS (tracked + untracked, excluding ignored files) is recorded to identify the exact code version run.""" st = _out(["git", "status", "--porcelain"]).splitlines() files = sorted(_out(["git", "ls-files", "-co", "--exclude-standard", *CODE_DIRS]).splitlines()) h = hashlib.sha256() for f in files: p = REPO_ROOT / f if p.is_file(): h.update(f.encode() + b"\0" + p.read_bytes() + b"\0") return {"commit": _out(["git", "rev-parse", "--short=12", "HEAD"]), "branch": _out(["git", "branch", "--show-current"]), "dirty": any(not s.startswith("??") for s in st), "n_modified": sum(not s.startswith("??") for s in st), "n_untracked": sum(s.startswith("??") for s in st), "code_sha256": h.hexdigest()[:16] if files else ""} def gpu_state() -> list[dict]: rows = _out(["nvidia-smi", "--query-gpu=index,memory.used,memory.total,utilization.gpu", "--format=csv,noheader,nounits"]) out = [] for r in rows.splitlines(): try: i, used, tot, util = (int(x) for x in r.split(",")) except ValueError: continue out.append({"index": i, "mem_used_mib": used, "mem_total_mib": tot, "util_pct": util}) return out def _group_pids(pgid: int) -> set[int]: pids = set() for d in Path("/proc").iterdir(): if d.name.isdigit(): try: if os.getpgid(int(d.name)) == pgid: pids.add(int(d.name)) except OSError: pass return pids class GpuSampler(threading.Thread): """Sample the VRAM of the process tree (same process group as the child process) every GPU_POLL_S seconds.""" def __init__(self, pgid: int): super().__init__(daemon=True) self.pgid, self.peak, self.stop = pgid, 0, threading.Event() def run(self) -> None: wait = 2.0 # early first sample so that short jobs still get a reading while not self.stop.wait(wait): wait = GPU_POLL_S rows = _out(["nvidia-smi", "--query-compute-apps=pid,used_memory", "--format=csv,noheader,nounits"]) if not rows: continue pids = _group_pids(self.pgid) tot = 0 for r in rows.splitlines(): try: pid, mem = (int(x) for x in r.split(",")) except ValueError: continue tot += mem if pid in pids else 0 self.peak = max(self.peak, tot) def default_name(cmd: list[str]) -> str: for a in cmd: m = re.search(r"(\d\d_\w+)\.py$", a) or re.search(r"(run_p\d+)\.sh$", a) if m: return m.group(1) if "pytest" in cmd: return "pytest" return re.sub(r"\W+", "_", Path(cmd[0]).stem) or "run" def device_of(cmd: list[str]) -> str: for i, a in enumerate(cmd): if a == "--device" and i + 1 < len(cmd): return cmd[i + 1] if a.startswith("--device="): return a.split("=", 1)[1] return os.environ.get("DEVICE", "") def write_json(path: Path, obj: dict) -> None: tmp = path.with_suffix(".tmp") tmp.write_text(json.dumps(obj, indent=1, ensure_ascii=False, default=str)) tmp.replace(path) def append_index(row: dict, root: Path | None = None) -> None: root = root or logs_dir() root.mkdir(parents=True, exist_ok=True) with open(root / "index.csv", "a+", newline="") as f: fcntl.flock(f, fcntl.LOCK_EX) # several concurrent runs may write to the index f.seek(0) new = not f.read(1) w = csv.DictWriter(f, FIELDS, extrasaction="ignore") if new: w.writeheader() w.writerow(row) fcntl.flock(f, fcntl.LOCK_UN) def index_row(meta: dict) -> dict: g = meta.get("git", {}) return {"run_id": meta["run_id"], "parent": meta.get("parent") or "", "name": meta["name"], "status": meta["status"], "exit_code": "" if meta.get("exit_code") is None else meta["exit_code"], "start": meta.get("start") or "", "end": meta.get("end") or "", "wall_s": "" if meta.get("wall_s") is None else round(meta["wall_s"], 1), "wall": fmt_wall(meta.get("wall_s")), "device": meta.get("device", ""), "git": g.get("commit", ""), "dirty": g.get("dirty", ""), "code_sha": g.get("code_sha256", ""), "source": meta.get("source", "runlog"), "cmd": " ⏎ ".join(meta["cmd"].splitlines())} def new_run_dir(name: str, start: dt.datetime) -> tuple[Path, str, str | None]: parent = os.environ.get("RUNLOG_DIR") if parent and Path(parent).is_dir(): k = sum(1 for p in Path(parent).iterdir() if p.is_dir()) + 1 while any(Path(parent).glob(f"{k:02d}_*")): k += 1 d = Path(parent) / f"{k:02d}_{name}" return d, f"{Path(parent).name}/{d.name}", os.environ.get("RUNLOG_ID") base = logs_dir() / "runs" / f"{start:%Y%m%d-%H%M%S}_{name}" d, k = base, 1 while d.exists(): # two runs started in the same second k += 1 d = base.with_name(f"{base.name}-{k}") return d, d.name, None class Tee: """Write the child process bytes to the terminal (verbatim) and to log.txt (prefixing each line with [h:mm:ss]).""" def __init__(self, path: Path, t0: float, stamp: bool): self.f, self.t0, self.stamp, self.bol, self.echo = open(path, "ab"), t0, stamp, True, True def write(self, b: bytes) -> None: if self.echo: try: sys.stdout.buffer.write(b) sys.stdout.buffer.flush() except (BrokenPipeError, ValueError): # terminal/pipe closed: keep writing to log.txt self.echo = False if self.stamp: parts = b.split(b"\n") out = [] for i, p in enumerate(parts): if self.bol and (p or i < len(parts) - 1): out.append(f"[{fmt_wall(time.time() - self.t0)}] ".encode()) self.bol = False out.append(p) if i < len(parts) - 1: out.append(b"\n") self.bol = True b = b"".join(out) self.f.write(b) self.f.flush() def note(self, s: str) -> None: self.f.write(f"# {s}\n".encode()) self.f.flush() def run(cmd: list[str], name: str | None, note: str, stamp: bool) -> int: if cmd and cmd[0].endswith(".py"): cmd = [sys.executable, *cmd] name = re.sub(r"[^\w.-]+", "_", name or default_name(cmd)) start = now() rdir, run_id, parent = new_run_dir(name, start) rdir.mkdir(parents=True) t0 = time.time() meta = {"run_id": run_id, "parent": parent, "name": name, "note": note, "status": "running", "exit_code": None, "cmd": shlex.join(cmd), "argv": cmd, "cwd": os.getcwd(), "start": start.isoformat(timespec="seconds"), "end": None, "wall_s": None, "device": device_of(cmd), "host": socket.gethostname(), "user": os.environ.get("USER", ""), "launcher_pid": os.getpid(), "python": platform.python_version(), "env": {k: os.environ[k] for k in ENV_KEYS if k in os.environ}, "git": git_state(), "gpu_start": gpu_state(), "source": "runlog"} write_json(rdir / "meta.json", meta) tee = Tee(rdir / "log.txt", t0, stamp) tee.note(f"{run_id} {meta['start']} {meta['cmd']}") env = os.environ | {"RUNLOG_DIR": str(rdir), "RUNLOG_ID": run_id, "PYTHONUNBUFFERED": "1"} try: child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, process_group=0) except OSError as e: tee.note(f"failed to launch: {e}") child = None got = [] def forward(sig, _frame): # Ctrl-C / kill: forward to the whole child process group and record it got.append(signal.Signals(sig).name) if child is not None: try: os.killpg(child.pid, sig) except OSError: pass for s in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP): signal.signal(s, forward) sampler = None if child is not None: sampler = GpuSampler(child.pid) sampler.start() fd = child.stdout.fileno() while True: try: b = os.read(fd, 65536) except InterruptedError: continue if not b: break tee.write(b) code = child.wait() sampler.stop.set() else: code = 127 ru = resource.getrusage(resource.RUSAGE_CHILDREN) wall = time.time() - t0 status = "ok" if code == 0 else ("interrupted" if got or code < 0 else "failed") meta |= {"status": status, "exit_code": code, "signals": got, "end": now().isoformat(timespec="seconds"), "wall_s": round(wall, 2), "wall": fmt_wall(wall), "cpu_user_s": round(ru.ru_utime, 1), "cpu_sys_s": round(ru.ru_stime, 1), "max_rss_mib": round(ru.ru_maxrss / 1024), "gpu_peak_mib": sampler.peak if sampler else None, "gpu_end": gpu_state()} write_json(rdir / "meta.json", meta) tee.note(f"{status} exit {code} wall {fmt_wall(wall)} ({wall:.1f} s)") append_index(index_row(meta)) print(f"[runlog] {status} exit {code} wall {fmt_wall(wall)} -> {rdir}", file=sys.stderr, flush=True) return code if code >= 0 else 128 - code def all_metas(root: Path) -> list[dict]: metas = [json.loads(m.read_text()) for m in [*(root / "runs").glob("*/meta.json"), *(root / "runs").glob("*/*/meta.json")]] return sorted(metas, key=lambda m: (m.get("start") or m.get("end") or "", m["run_id"])) def reindex() -> None: root = logs_dir() metas = [m for m in all_metas(root) if m.get("status") != "running"] (root / "index.csv").unlink(missing_ok=True) for m in metas: append_index(index_row(m), root) print(f"{len(metas)} rows -> {root / 'index.csv'}") def ls(k: int) -> None: root = logs_dir() rows = list(csv.DictReader(open(root / "index.csv"))) if (root / "index.csv").exists() else [] done = {r["run_id"] for r in rows} for meta in all_metas(root): if meta["run_id"] in done or meta.get("status") != "running": continue alive = Path(f"/proc/{meta.get('launcher_pid')}").exists() meta["status"] = "running" if alive else "lost" # launcher killed with -9 / machine rebooted start = dt.datetime.fromisoformat(meta["start"]) meta["wall_s"] = (now() - start).total_seconds() if alive else None rows.append(index_row(meta)) rows = rows[-k:] cols = ["run_id", "status", "exit_code", "start", "wall", "device", "cmd"] w = {c: min(60, max([len(c)] + [len(str(r[c])) for r in rows])) for c in cols} print(" ".join(c.ljust(w[c]) for c in cols)) for r in rows: print(" ".join(str(r[c])[:w[c]].ljust(w[c]) for c in cols)) def main(argv: list[str] | None = None) -> int: argv = sys.argv[1:] if argv is None else argv if argv[:1] == ["ls"]: ap = argparse.ArgumentParser(prog="python -m ml_porosity.runlog ls") ap.add_argument("-k", type=int, default=30) ls(ap.parse_args(argv[1:]).k) return 0 if argv == ["reindex"]: reindex() return 0 ap = argparse.ArgumentParser(prog="python -m ml_porosity.runlog", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("-n", "--name", help="run name (default: script name, e.g. 11_run_d2)") ap.add_argument("--note", default="", help="free-text note stored in meta.json") ap.add_argument("--no-stamp", action="store_true", help="do not prefix log.txt lines with [h:mm:ss]") ap.add_argument("cmd", nargs=argparse.REMAINDER) a = ap.parse_args(argv) cmd = a.cmd[1:] if a.cmd[:1] == ["--"] else a.cmd if not cmd: ap.error("missing command to run") return run(cmd, a.name, a.note, not a.no_stamp) if __name__ == "__main__": sys.exit(main())