okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-142c-small into f-142407ea8192

main
14.0 KiB293 linesraw
1#!/usr/bin/env python3
2"""Re-run the 2026-10-08 RTX 4070/IQ2_XS benchmark from provenance.json.
3
4Standard-library only. No network, download, model redistribution, or automatic
5publication. Run "check" (SHA-256) *separately* from "run" to avoid warming the
6OS file cache immediately before a timed measurement.
7"""
8from __future__ import annotations
9
10import argparse
11import hashlib
12import json
13import os
14from pathlib import Path
15import re
16import statistics
17import subprocess
18import sys
19from datetime import datetime, timezone
20
21MANIFEST = Path(__file__).with_name("provenance.json")
22SOURCE_COMMIT = "9ec3806058cf32ab27a55e4377daf7cf0d087dec"
23PATH_OPTIONS = {"--pack", "--native", "--ple-gguf", "--mtp",
24                "--expert-profile", "--tokens-file"}
25DECODE_RE = re.compile(
26    r"^decode\s+(\d+) tokens in\s+([\d.]+) ms\s+->\s+([\d.]+) tok/s",
27    re.MULTILINE,
28)
29
30
31def sha256(path: Path) -> str:
32    h = hashlib.sha256()
33    with path.open("rb") as stream:
34        for block in iter(lambda: stream.read(8 * 1024 * 1024), b""):
35            h.update(block)
36    return h.hexdigest().upper()
37
38
39def git_head(directory: Path) -> str | None:
40    try:
41        p = subprocess.run(["git", "-C", str(directory), "rev-parse", "HEAD"],
42                           capture_output=True, text=True, check=True)
43        return p.stdout.strip()
44    except (OSError, subprocess.CalledProcessError):
45        return None
46
47
48def checked_path(root: Path, rel: str) -> Path:
49    candidate = (root / rel).resolve()
50    if not candidate.is_relative_to(root.resolve()):
51        raise ValueError("Manifest path escapes data root: " + rel)
52    return candidate
53
54
55def expected_files(manifest: dict) -> list[dict]:
56    rows = []
57    for entry in manifest["model"]["native_shards"]:
58        rows.append({"role": "model", **entry})
59    rows.extend(manifest["artifacts"])
60    return rows
61
62
63def verify(manifest: dict, data_root: Path, engine: Path, source: Path | None,
64           mode: str, permit_different_binary: bool,
65           overrides: dict[str, Path]) -> tuple[list[str], list[str]]:
66    problems, warnings = [], []
67    head = git_head(source) if source else None
68    if source:
69        if head is None:
70            problems.append(f"Cannot determine Git HEAD in source directory: {source}")
71        elif head.lower() != SOURCE_COMMIT:
72            problems.append(f"Wrong source HEAD: {head}; expected {SOURCE_COMMIT}")
73        try:
74            dirty = subprocess.run(
75                ["git", "-C", str(source), "status", "--porcelain"],
76                capture_output=True, text=True, check=True,
77            ).stdout.strip()
78            if dirty:
79                warnings.append("Source working tree has uncommitted changes")
80        except (OSError, subprocess.CalledProcessError):
81            warnings.append("Cannot check whether source tree is clean")
82    else:
83        warnings.append("Source Git checkout not verified (provide --source-root)")
84    if not engine.is_file():
85        problems.append(f"Engine executable missing: {engine}")
86    else:
87        expected = manifest["source"]
88        if engine.stat().st_size != expected["binary_bytes"]:
89            msg = (f"Engine size mismatch: {engine.stat().st_size} vs "
90                   f"{expected['binary_bytes']} bytes")
91            (warnings if permit_different_binary else problems).append(msg)
92        digest = sha256(engine)
93        if digest != expected["binary_sha256"].upper():
94            msg = f"Engine binary SHA-256 mismatch: {digest}"
95            (warnings if permit_different_binary else problems).append(msg)
96    for item in expected_files(manifest):
97        if ((item["path"] == "profiles/learned-heart.bin" and "--expert-profile" in overrides) or
98            (item["path"] == "prompts/neuro.tokens" and "--tokens-file" in overrides)):
99            continue  # Local profile/prompt are checked separately, without matching historical SHA.
100        target = checked_path(data_root, item["path"])
101        if not target.is_file():
102            problems.append(f"MISSING [{item['role']}]: {target}")
103            continue
104        if target.stat().st_size != item["bytes"]:
105            problems.append(f"SIZE MISMATCH [{item['role']}]: {target}")
106            continue
107        if mode == "sha256" and sha256(target) != item["sha256"].upper():
108            problems.append(f"SHA256 MISMATCH [{item['role']}]: {target}")
109    for flag, target in overrides.items():
110        if not target.is_file():
111            problems.append(f"OVERRIDE MISSING [{flag}]: {target}")
112    if "--tokens-file" in overrides and overrides["--tokens-file"].is_file():
113        content = overrides["--tokens-file"].read_text(encoding="utf-8")
114        if not re.fullmatch(r"[\d+,\s-]+", content):
115            problems.append("User prompt must be pretokenized integer IDs (comma/whitespace-separated)")
116        else:
117            count = len(re.findall(r"[-+]?\d+", content))
118            target_count = int(manifest["primary_command"]["actual_prompt_tokens"])
119            if count != target_count:
120                problems.append(f"Prompt length {count} differs from {target_count} historical input tokens")
121    if mode == "size":
122        warnings.append("Data file SHA-256 was NOT checked; only sizes were compared")
123    if overrides:
124        warnings.append("Comparable-workload reproduction: custom prompt/profile; NOT an exact historical replay")
125    return problems, warnings
126
127
128def make_command(manifest: dict, data_root: Path, engine: Path,
129                 overrides: dict[str, Path]) -> list[str]:
130    original = manifest["primary_command"]["args"]
131    command = [str(engine)]
132    path_value = None
133    for arg in original:
134        if path_value is not None:
135            command.append(str(overrides[path_value] if path_value in overrides else
136                               checked_path(data_root, arg)))
137            path_value = None
138        else:
139            command.append(arg)
140            path_value = arg if arg in PATH_OPTIONS else None
141    if path_value:
142        raise ValueError("Path flag at end of provenance argument vector")
143    return command
144
145
146def gpu_snapshot(path: Path) -> None:
147    try:
148        p = subprocess.run(
149            ["nvidia-smi", "--query-gpu=timestamp,name,memory.total,memory.used,"
150             "memory.free,driver_version", "--format=csv"],
151            capture_output=True, text=True, timeout=20,
152        )
153        path.write_text(p.stdout if p.returncode == 0 else p.stderr,
154                        encoding="utf-8")
155    except (OSError, subprocess.TimeoutExpired) as exc:
156        path.write_text(str(exc), encoding="utf-8")
157
158
159def run_benchmark(manifest: dict, data_root: Path, engine: Path,
160                  output: Path, repetitions: int, source: Path | None,
161                  validation_mode: str, allow_binary_mismatch: bool,
162                  overrides: dict[str, Path]) -> None:
163    output.mkdir(parents=True, exist_ok=False)
164    command = make_command(manifest, data_root, engine, overrides)
165    env = os.environ.copy()
166    env.update(manifest["primary_command"]["environment"])
167    # The source installer records CUDA runtime DLL directories in BUILD.json.
168    # A bare strata.exe launch requires those directories on PATH on Windows.
169    build_json = engine.parent / "BUILD.json"
170    dll_dirs = []
171    if build_json.is_file():
172        build = json.loads(build_json.read_text(encoding="utf-8"))
173        dll_dirs = [str(Path(d)) for key in ("lib_dirs", "cuda_dirs")
174                    for d in (build.get(key) or []) if Path(d).is_dir()]
175    if dll_dirs:
176        env["PATH"] = os.pathsep.join(dll_dirs + [env.get("PATH", "")])
177    result_rows = []
178    expected_tokens = int(manifest["primary_command"]["output_tokens"])
179    for index in range(1, repetitions + 1):
180        folder = output / f"run-{index:02d}"
181        folder.mkdir()
182        # Do not publish raw stdout: the engine prints the full prompt and
183        # output token IDs, potentially encoding private text.
184        (folder / "command.json").write_text(
185            json.dumps({"argv": command,
186                        "environment_overrides": manifest["primary_command"]["environment"],
187                        "cuda_library_paths_from_BUILD_json": dll_dirs,
188                        "started_utc": datetime.now(timezone.utc).isoformat()},
189                       indent=2), encoding="utf-8")
190        gpu_snapshot(folder / "gpu-before.csv")
191        with (
192            (folder / "stdout.log").open("w", encoding="utf-8") as stdout,
193            (folder / "stderr.log").open("w", encoding="utf-8") as stderr,
194        ):
195            proc = subprocess.run(command, cwd=data_root, env=env,
196                                  stdout=stdout, stderr=stderr, check=False)
197        gpu_snapshot(folder / "gpu-after.csv")
198        output_text = (folder / "stdout.log").read_text(encoding="utf-8")
199        matches = DECODE_RE.findall(output_text)
200        row = {"run": index, "exit_code": proc.returncode,
201               "accepted_decode_tok_s": None, "output_tokens": None,
202               "decode_ms": None, "valid": False}
203        if proc.returncode == 0 and len(matches) == 1:
204            tokens, ms, rate = matches[0]
205            row.update({"output_tokens": int(tokens), "decode_ms": float(ms),
206                        "accepted_decode_tok_s": float(rate),
207                        "valid": int(tokens) == expected_tokens})
208        (folder / "summary.json").write_text(json.dumps(row, indent=2),
209                                               encoding="utf-8")
210        result_rows.append(row)
211        print(f"run {index}/{repetitions}: {row}", flush=True)
212    success = [r["accepted_decode_tok_s"] for r in result_rows if r["valid"]]
213    report = {
214        "source_commit_required": SOURCE_COMMIT,
215        "source_git_head_observed": git_head(source) if source else None,
216        "binary_sha256_expected": manifest["source"]["binary_sha256"],
217        "binary_sha256_observed": sha256(engine),
218        "binary_mismatch_explicitly_allowed": allow_binary_mismatch,
219        "data_validation_mode": validation_mode,
220        "environment_overrides": manifest["primary_command"]["environment"],
221        "cuda_library_paths_from_BUILD_json": dll_dirs,
222        "comparison_type": "comparable user-supplied workload (not historical exact)" if overrides else
223                           "historical inputs if all file hashes match",
224        "prompt_file_sha256": sha256(overrides["--tokens-file"]) if "--tokens-file" in overrides else
225                              sha256(checked_path(data_root, "prompts/neuro.tokens")),
226        "profile_sha256": sha256(overrides["--expert-profile"]) if "--expert-profile" in overrides else
227                          sha256(checked_path(data_root, "profiles/learned-heart.bin")),
228        "prompt_tokens": int(manifest["primary_command"]["actual_prompt_tokens"]),
229        "results": result_rows,
230        "valid_runs": len(success),
231        "median_accepted_decode_tok_s": statistics.median(success) if success else None,
232        "mean_accepted_decode_tok_s": statistics.mean(success) if success else None,
233        "min_accepted_decode_tok_s": min(success) if success else None,
234        "max_accepted_decode_tok_s": max(success) if success else None,
235        "historical_primary_median": manifest["run_sets"]["primary_e4_s24"]["median_tok_s"],
236        "note": "GPU snapshots are before/after, NOT an in-run peak VRAM measurement",
237    }
238    (output / "report.json").write_text(json.dumps(report, indent=2),
239                                        encoding="utf-8")
240    print(json.dumps({k: v for k, v in report.items() if k != "results"}, indent=2))
241    if len(success) != repetitions:
242        raise SystemExit("One or more runs failed or produced the wrong output token count")
243
244
245def main() -> int:
246    p = argparse.ArgumentParser(description=__doc__)
247    p.add_argument("action", choices=["check", "run"])
248    p.add_argument("--data-root", type=Path, required=True,
249                   help="Folder containing models/, packs/, mtp/, profiles/, prompts/")
250    p.add_argument("--engine", type=Path, required=True,
251                   help="Path to the compiled strata.exe executable")
252    p.add_argument("--source-root", type=Path,
253                   help="The pinned Git checkout to verify with git rev-parse HEAD")
254    p.add_argument("--hash-mode", choices=["sha256", "size"],
255                   help="Defaults to sha256 for check, size for run (avoid pre-run cache warming)")
256    p.add_argument("--allow-binary-mismatch", action="store_true",
257                   help="Run a rebuild that differs in bytes; not a byte-identical engine reproduction")
258    p.add_argument("--profile", type=Path,
259                   help="Locally generated expert profile; no historical profile download required")
260    p.add_argument("--prompt-file", type=Path,
261                   help="Your own pretokenized, 28,912-token prompt; historical prompt not required")
262    p.add_argument("--runs", type=int, default=5)
263    p.add_argument("--out", type=Path, help="New output directory for raw logs (never overwritten)")
264    args = p.parse_args()
265    if args.action == "run" and (not args.out or args.runs < 1):
266        p.error("run requires --out and --runs >= 1")
267    data_root, engine = args.data_root.resolve(), args.engine.resolve()
268    manifest = json.loads(MANIFEST.read_text(encoding="utf-8"))
269    mode = args.hash_mode or ("sha256" if args.action == "check" else "size")
270    overrides = {}
271    if args.profile:
272        overrides["--expert-profile"] = args.profile.resolve()
273    if args.prompt_file:
274        overrides["--tokens-file"] = args.prompt_file.resolve()
275    problems, warnings = verify(manifest, data_root, engine,
276                                 args.source_root.resolve() if args.source_root else None,
277                                 mode, args.allow_binary_mismatch, overrides)
278    for line in warnings:
279        print("WARNING:", line, file=sys.stderr)
280    if problems:
281        for line in problems:
282            print("ERROR:", line, file=sys.stderr)
283        return 2
284    print(f"Preflight OK ({mode} data validation)")
285    if args.action == "run":
286        run_benchmark(manifest, data_root, engine, args.out.resolve(), args.runs,
287                      args.source_root.resolve() if args.source_root else None,
288                      mode, args.allow_binary_mismatch, overrides)
289    return 0
290
291
292if __name__ == "__main__":
293    raise SystemExit(main())