ThatsNinja's picture
Sync gh-main from TheRock
241667d verified
Raw History Blame Contribute Delete
6.48 kB
"""Run manifest for immutable results preservation.
Records the full context of a training/eval run (git state, config, seed,
environment, dataset hashes, metrics) and emits ``manifest.json`` plus
``metrics.json`` under a uniquely-named run directory so results can be
reproduced and independently verified.
Pure stdlib only; torch is imported lazily (and optionally) inside
:meth:`RunManifest._collect_env`.
"""
from __future__ import annotations
import hashlib
import json
import platform
import re
import subprocess
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Optional
__all__ = ["RunManifest"]
_HASH_CHUNK_BYTES = 1 << 20 # 1 MiB
def _find_repo_root() -> Optional[Path]:
"""Walk up from this file until a ``.git`` dir or file is found."""
for parent in Path(__file__).resolve().parents:
if (parent / ".git").exists():
return parent
return None
def _git_output(args: list[str], cwd: Path) -> Optional[str]:
"""Run a git command, returning stripped stdout or None on any failure."""
try:
proc = subprocess.run(
["git", *args],
cwd=str(cwd),
capture_output=True,
text=True,
timeout=30,
check=False,
)
except (OSError, subprocess.SubprocessError):
return None
if proc.returncode != 0:
return None
return proc.stdout.strip() or None
def _slugify(name: str) -> str:
"""Lowercase, replace non-alphanumeric runs with single dashes."""
slug = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")
return slug or "run"
class RunManifest:
"""Accumulates provenance for a single run; ``finalize`` writes it out."""
def __init__(self) -> None:
self._config: dict[str, Any] = {}
self._seed: Optional[Any] = None
self._git_sha: Optional[str] = None
self._git_dirty: Optional[bool] = None
self._env: dict[str, Any] = {}
self._started_at: Optional[str] = None
self._start_monotonic: Optional[float] = None
self._metrics: Optional[dict[str, Any]] = None
self._artifact_hashes: dict[str, str] = {}
# ------------------------------------------------------------------
# Recording
# ------------------------------------------------------------------
def begin(self, config: dict) -> None:
"""Record config, git state, seed, environment and start time."""
self._config = dict(config)
self._seed = config.get("seed")
root = _find_repo_root()
if root is not None:
sha = _git_output(["rev-parse", "HEAD"], root)
self._git_sha = sha
if sha is not None:
status = _git_output(["status", "--porcelain"], root)
self._git_dirty = bool(status) if status is not None else None
else:
self._git_dirty = None
else:
self._git_sha = None
self._git_dirty = None
self._env = self._collect_env()
now = datetime.now(timezone.utc)
self._started_at = now.isoformat()
self._start_monotonic = time.monotonic()
def _collect_env(self) -> dict[str, Any]:
"""Python version plus optional torch/ROCm/GPU info (never raises)."""
env: dict[str, Any] = {"python_version": platform.python_version()}
try:
import torch # type: ignore[import-untyped]
except Exception:
return env
try:
env["torch_version"] = torch.__version__
hip = getattr(torch.version, "hip", None)
cuda = getattr(torch.version, "cuda", None)
if hip:
env["torch_hip_version"] = hip
if cuda:
env["torch_cuda_version"] = cuda
if torch.cuda.is_available():
env["gpu_name"] = torch.cuda.get_device_name(0)
except Exception:
pass
return env
def record_metrics(self, metrics: dict) -> None:
"""Store metrics; raises ``TypeError`` if not JSON-serializable."""
json.dumps(metrics) # validate serializability
self._metrics = dict(metrics)
def record_artifact_hash(self, path: Path) -> None:
"""Compute and store the SHA256 of ``path`` (keyed by file name)."""
sha256 = hashlib.sha256()
with Path(path).open("rb") as f:
while True:
chunk = f.read(_HASH_CHUNK_BYTES)
if not chunk:
break
sha256.update(chunk)
self._artifact_hashes[Path(path).name] = sha256.hexdigest()
# ------------------------------------------------------------------
# Emission
# ------------------------------------------------------------------
def _make_run_id(self) -> str:
timestamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
if "name" in self._config:
slug = _slugify(str(self._config["name"]))
else:
slug = "run"
sha_part = self._git_sha[:7] if self._git_sha else "nogit"
return f"{timestamp}__{slug}__{sha_part}"
def finalize(self, out_dir: Path) -> Path:
"""Create ``out_dir / run_id`` and write manifest + metrics files."""
if self._started_at is None or self._start_monotonic is None:
raise RuntimeError("begin() must be called before finalize()")
if self._metrics is None:
raise RuntimeError("record_metrics() must be called before finalize()")
run_id = self._make_run_id()
run_dir = Path(out_dir) / run_id
run_dir.mkdir(parents=True, exist_ok=True)
duration_s = time.monotonic() - self._start_monotonic
manifest: dict[str, Any] = {
"run_id": run_id,
"git_sha": self._git_sha,
"git_dirty": self._git_dirty,
"config": self._config,
"seed": self._seed,
"env": self._env,
"artifact_hashes": self._artifact_hashes,
"started_at": self._started_at,
"duration_s": duration_s,
}
(run_dir / "manifest.json").write_text(
json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8"
)
(run_dir / "metrics.json").write_text(
json.dumps(self._metrics, indent=2, sort_keys=True) + "\n", encoding="utf-8"
)
return run_dir