albedo_training / score_local.py
cryptoDev23's picture
SN97 training set: 41,463 rows + runbook, analysis, local scorer
7e7bd6a verified
Raw History Blame Contribute Delete
4.19 kB
"""Score locally generated trajectories without a judge or an API key.
python3 score_local.py --build-index # once
/root/.venv-tok/bin/python score_local.py --trajectories mine.jsonl
Input is JSONL with `sample_id` and either `messages` (role/content) or `turns`.
Questions are looked up from the harvested artifacts, so the sample must be one
that appeared in a real eval run - there are 19,811 of them in `questions.json`.
Read the accuracy notes in README before trusting a number: this resolves a
2.5-point margin only at 500+ paired samples, and it is exact only for loops.
"""
from __future__ import annotations
import argparse
import json
import pickle
import statistics
import sys
from collections import defaultdict
from pathlib import Path
ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT.parents[1] / "albedo" / "src"))
from build_local_scorer import featurize, side_context # noqa: E402
QUESTIONS = ROOT / "questions.json"
SCORER = ROOT / "local_scorer.pkl"
def build_index() -> None:
index = [r for r in json.loads((ROOT / "index.json").read_text())
if "SCORING_RESULTS" in (r.get("files") or {})]
out: dict[str, list] = {}
for rec in index:
path = ROOT / "raw" / rec["files"]["SCORING_RESULTS"]
for line in path.read_text(errors="replace").splitlines():
if not line.strip():
continue
o = json.loads(line)
if o.get("scored") and o["sample_id"] not in out:
out[o["sample_id"]] = o.get("questions") or []
QUESTIONS.write_text(json.dumps(out))
print(f"indexed {len(out):,} samples -> {QUESTIONS.name} "
f"({QUESTIONS.stat().st_size / 1e6:,.0f} MB)")
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--build-index", action="store_true")
ap.add_argument("--trajectories")
ap.add_argument("--out", default="local_scores.jsonl")
args = ap.parse_args()
if args.build_index:
build_index()
return 0
if not args.trajectories:
ap.error("--trajectories required (or --build-index)")
import numpy as np
questions = json.loads(QUESTIONS.read_text())
bundle = pickle.load(SCORER.open("rb"))
model = bundle["model"]
scores, missing, looped = [], 0, 0
with open(args.out, "w") as fh:
for line in open(args.trajectories):
if not line.strip():
continue
rec = json.loads(line)
qs = questions.get(rec.get("sample_id"))
if not qs:
missing += 1
continue
turns = rec.get("messages") or rec.get("turns") or []
ctx = side_context(turns)
X = np.asarray([featurize(q, ctx, len(qs)) for q in qs], dtype=np.float32)
w = np.asarray([float(q.get("weight", 1) or 1) for q in qs], dtype=np.float32)
p = model.predict_proba(X)[:, 1]
score = 0.0 if ctx["looped"] else float((p * w).sum() / w.sum())
looped += int(ctx["looped"])
scores.append(score)
fh.write(json.dumps({
"sample_id": rec["sample_id"], "predicted_score": round(score, 4),
"looped": bool(ctx["looped"]), "n_turns": int(ctx["n_turns"]),
"flag_catastrophic": score < 0.35,
}) + "\n")
if not scores:
print("no scorable trajectories - are the sample_ids from real eval runs?")
return 1
n = len(scores)
print(f"scored {n:,} trajectories (skipped {missing:,} with unknown sample_id)")
print(f" mean predicted score : {statistics.mean(scores):.4f}")
print(f" LOOPED (exact, pre-eval kills these): {looped:,} ({100 * looped / n:.1f}%)")
print(f" flagged catastrophic (<0.35, ~82% precision): "
f"{sum(1 for s in scores if s < 0.35):,}")
print(f" 95% CI on the mean: +/-{1.96 * 0.207 / (n ** 0.5):.4f}"
f"{' (resolves a 0.025 margin)' if 1.96 * 0.207 / (n ** 0.5) < 0.025 else ' (TOO NOISY - use 500+ samples)'}")
print(f"\nwrote {args.out}")
return 0
if __name__ == "__main__":
sys.exit(main())