File size: 6,479 Bytes
241667d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
"""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