Download scripts/verify_openjev_final.py from raspbfox/nanberry-decision-checkpoints: direct link, hf CLI and curl.
- Browser
- Download file 6.74 kB
-
https://huggingface.co/raspbfox/nanberry-decision-checkpoints/resolve/main/scripts/verify_openjev_final.py
- Command line
-
hf download hf://raspbfox/nanberry-decision-checkpoints/scripts/verify_openjev_final.py
-
curl -L -o verify_openjev_final.py https://huggingface.co/raspbfox/nanberry-decision-checkpoints/resolve/main/scripts/verify_openjev_final.py
6.74 kB
| """CPU-only final-checkpoint and paired evaluation verification; no model inference.""" | |
| import argparse | |
| import hashlib | |
| import json | |
| import math | |
| from pathlib import Path | |
| from statistics import fmean | |
| import torch | |
| def read_json(path): | |
| try: | |
| return json.loads(path.read_text()) | |
| except (OSError, json.JSONDecodeError) as exc: | |
| raise RuntimeError(f"Invalid evidence: {path}") from exc | |
| def sha(path): | |
| with path.open("rb") as stream: | |
| return hashlib.file_digest(stream, "sha256").hexdigest() | |
| def row_metrics(row): | |
| p, q = row["probabilities"], row["target"] | |
| assert len(p) == len(q) >= 2 | |
| for values in (p, q): | |
| assert all(math.isfinite(x) and 0 <= x <= 1 for x in values) | |
| assert abs(sum(values)-1) < 1e-6 | |
| assert all(a > 0 or b == 0 for a, b in zip(p, q, strict=True)), "CE lost to probability underflow" | |
| ce = -sum(b*math.log(a) for a, b in zip(p, q, strict=True) if b) | |
| brier = sum((a-b)**2 for a, b in zip(p, q, strict=True)) | |
| hard = max(q) == 1.0 | |
| correct = hard and max(range(len(p)), key=p.__getitem__) == q.index(1.0) | |
| return ce, brier, hard, bool(correct) | |
| def aggregate(rows): | |
| assert rows | |
| values = [row_metrics(r) for r in rows] | |
| ce, brier = fmean(v[0] for v in values), fmean(v[1] for v in values) | |
| hard_n, correct = sum(v[2] for v in values), sum(v[3] for v in values) | |
| return {"n":len(rows), "ce":ce, "brier":brier, "ce_plus_brier":ce+brier, | |
| "hard_n":hard_n, "hard_correct":correct, | |
| "hard_accuracy":correct/hard_n if hard_n else None} | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1]) | |
| args = parser.parse_args() | |
| root = args.root | |
| run = root / "runs/nanberry-openjev-v11-epoch1" | |
| report = read_json(run / "report.json") | |
| audit = read_json(run / "shuffle-audit.json") | |
| cfg = read_json(run / "config.json") | |
| assert report["completed"] and not report["probe"] | |
| assert report["steps"] == report["total_steps"] == audit["batches"] == 34795 | |
| assert report["examples_seen"] == report["expected_train_rows"] == audit["unique_rows"] == audit["rows"] == 147139 | |
| assert audit["data"]["truncated"] == 0 | |
| assert report["tokens"] == audit["data"]["useful_tokens"] == 44994196 | |
| checkpoint = run / "latest.pt" | |
| saved = torch.load(checkpoint, map_location="cpu", weights_only=True, mmap=True) | |
| assert saved["status"] == "trained" and saved["cursor"] == report["steps"] | |
| assert saved["config"] == cfg and saved["order_sha256"] == audit["order_sha256"] | |
| assert saved["tokens"] == report["tokens"] and len(saved["curve"]) == report["steps"] | |
| assert all(math.isfinite(x) for x in saved["curve"]) | |
| parent_path = root / cfg["parent_checkpoint"] | |
| assert sha(parent_path) == cfg["parent_payload_sha256"] | |
| parent = torch.load(parent_path, map_location="cpu", weights_only=True, mmap=True) | |
| assert parent["source_checkpoint_sha256"] == cfg["parent_source_sha256"] | |
| assert saved["trainable"].keys() == parent["trainable"].keys() | |
| changed = 0 | |
| for name, tensor in saved["trainable"].items(): | |
| assert tensor.shape == parent["trainable"][name].shape and torch.isfinite(tensor).all() | |
| changed += not torch.equal(tensor, parent["trainable"][name]) | |
| assert changed > 0 | |
| panels = {} | |
| for split, expected in {"validation":256,"test":200,"ood":200,"retention-manual":200,"retention-procedural":101}.items(): | |
| pair = {phase:read_json(run/f"{phase}-{split}.json") for phase in ("parent","final")} | |
| a, b = pair["parent"]["records"], pair["final"]["records"] | |
| assert len(a) == len(b) == len({r["id"] for r in a}) == expected | |
| assert [(r["id"],r["target"],r["kind"],r["source"]) for r in a] == [(r["id"],r["target"],r["kind"],r["source"]) for r in b] | |
| metrics = {phase:aggregate(data["records"]) for phase,data in pair.items()} | |
| for phase in pair: | |
| assert abs(metrics[phase]["ce_plus_brier"]-pair[phase]["ce_plus_brier"]) < 2e-5 | |
| initial = phase == "parent" | |
| expected_loss = (report["initial_val" if initial else "final_val"] if split == "validation" | |
| else report["initial_extra" if initial else "final_extra"][split]) | |
| assert pair[phase]["ce_plus_brier"] == expected_loss | |
| metrics["loss_change_percent"] = 100*(metrics["final"]["ce_plus_brier"]/metrics["parent"]["ce_plus_brier"]-1) | |
| metrics["by_kind"] = {kind:{phase:aggregate([r for r in data["records"] if r["kind"]==kind]) for phase,data in pair.items()} for kind in sorted({r["kind"] for r in a})} | |
| metrics["by_source"] = {source:{phase:aggregate([r for r in data["records"] if r["source"]==source]) for phase,data in pair.items()} for source in sorted({r["source"] for r in a})} | |
| metrics["by_target_type"] = {label:{phase:aggregate([r for r in data["records"] if (max(r["target"])==1)==hard]) for phase,data in pair.items()} for label,hard in (("hard",True),("soft",False)) if any((max(r["target"])==1)==hard for r in a)} | |
| metrics["hard_paired_changes"] = {"improved":sum(not row_metrics(x)[3] and row_metrics(y)[3] for x,y in zip(a,b,strict=True) if row_metrics(x)[2]),"regressed":sum(row_metrics(x)[3] and not row_metrics(y)[3] for x,y in zip(a,b,strict=True) if row_metrics(x)[2])} | |
| panels[split] = metrics | |
| digest = sha(checkpoint) | |
| archive = run / f"checkpoint-00034795-{digest[:12]}.pt" | |
| if not archive.exists(): | |
| archive.hardlink_to(checkpoint) | |
| assert sha(archive) == digest | |
| result = {"passed":True,"checkpoint":str(archive.relative_to(root)),"sha256":digest, | |
| "bytes":archive.stat().st_size,"trainable_tensors":len(saved["trainable"]), | |
| "changed_tensors":changed,"report":report,"panels":panels, | |
| "baseline":"Immediate procedural+480 parent; NOT untouched 5090 checkpoint", | |
| "limits":["Small fixed panels, not full splits","Retention panels previously consumed during development","Descriptive differences, no independence-adjusted significance claim","No fresh original-5090 or Jev comparison"]} | |
| (run/"final-verification.json").write_text(json.dumps(result,indent=2,allow_nan=False)+"\n") | |
| print(json.dumps({"passed":True,"sha256":digest,"checkpoint":result["checkpoint"],"panels":{k:{x:v[x] for x in ("parent","final","loss_change_percent","hard_paired_changes","by_target_type")} for k,v in panels.items()}},indent=2)) | |
| if __name__ == "__main__": | |
| assert row_metrics({"probabilities":[0.25,0.75],"target":[0,1]})[2:] == (True,True) | |
| assert aggregate([{"probabilities":[0.5,0.5],"target":[0.5,0.5]}])["hard_n"] == 0 | |
| main() | |