round4-sft-eval / scripts /score_diversify_ab.py
Aelien's picture
SFT eval: frozen 657-problem holdout + shardable checker-aware eval framework
0721659 verified
Raw History Blame Contribute Delete
5.71 kB
#!/usr/bin/env python3
"""Score the divergence A/B: unique full-pass solution density per problem, stay-close vs diversify.
Input: each arm's run_squeeze_evolve output JSONL (outputs/ab_diversify/<arm>_out.jsonl), records
{id, question, candidates:[response,...]}. With loops=2 + update=replace, `candidates` is the FINAL
(loop-1) recombination population. We grade every candidate's extracted code on the FULL codeforces
system tests (pool test_cases via lcb_exec_harness, cached + timeout-retry), dedup the full-pass set by
whitespace-normalized code per problem, and report unique-full-pass / problem (the metric the divergence
operator targets) plus raw, dedup ratio, and coverage. Diversify should beat stay-close on unique density.
"""
from __future__ import annotations
import argparse
import json
import re
import sys
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
_S = Path(__file__).resolve().parent
sys.path.insert(0, str(_S))
from lcb_grading import GradingCache, run_harness_cached # noqa: E402
HARNESS = _S / "lcb_exec_harness.py"
_CODE = re.compile(r"```(?:python|py)?\s*\n?(.*?)```", re.DOTALL)
_LIKE = re.compile(r"\b(def|import|class|for|while|print|input|return)\b|=")
def extract_code(t): # same heuristic as build_cstrip_sft.extract_code
bs = [b.strip() for b in _CODE.findall(t or "")]
if bs:
for b in reversed(bs):
if _LIKE.search(b):
return b
return bs[-1]
return t.strip() if t and _LIKE.search(t) else None
def _norm(c):
return re.sub(r"\s+", " ", c).strip() if c else ""
def grade_arm(path, pool, cache, workers, tle):
recs = [json.loads(l) for l in open(path)]
per = {}
jobs = []
for r in recs:
pid = r["id"]
s = pool.get(pid)
if not s:
continue
tj = s if isinstance(s, str) else json.dumps(s)
n = len(json.loads(tj)["inputs"])
tl = float(json.loads(tj).get("time_limit", tle))
per[pid] = {"n_cand": 0, "hashes": []}
for cand in (r.get("candidates") or []):
per[pid]["n_cand"] += 1
jobs.append((pid, extract_code(cand), tj, n, tl))
def run(j):
pid, code, tj, n, tl = j
if not code:
return pid, None
v = run_harness_cached(HARNESS, code, tj, n, tl=tl, cache=cache)
return pid, (_norm(code) if (v and v.get("passed")) else None)
with ThreadPoolExecutor(max_workers=workers) as ex:
for pid, h in ex.map(run, jobs):
if h:
per[pid]["hashes"].append(h)
return per
def metrics(per):
probs = list(per)
n = len(probs)
raw = sum(len(per[p]["hashes"]) for p in probs)
uniq = sum(len(set(per[p]["hashes"])) for p in probs)
cov = sum(1 for p in probs if per[p]["hashes"])
return {
"problems": n,
"raw_fullpass": raw,
"unique_fullpass": uniq,
"unique_per_problem": round(uniq / max(1, n), 3),
"raw_per_problem": round(raw / max(1, n), 3),
"dedup_ratio": round(uniq / max(1, raw), 3),
"coverage_problems": cov,
"unique_per_solved_problem": round(uniq / max(1, cov), 3),
}
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--stayclose", default="outputs/ab_diversify/stayclose_out.jsonl")
ap.add_argument("--diversify", default="outputs/ab_diversify/diversify_out.jsonl")
ap.add_argument("--canonical", default="outputs/ab_diversify/canonical_out.jsonl")
ap.add_argument("--canonical-fb", default="outputs/ab_diversify/canonical_fb_out.jsonl")
ap.add_argument("--pool", default="data/openthoughts114k_codeforces_stdin_clean.jsonl")
ap.add_argument("--out", default="outputs/ab_diversify/ab_summary.json")
ap.add_argument("--workers", type=int, default=64)
ap.add_argument("--tle", type=float, default=6.0)
a = ap.parse_args()
pool = {}
for l in open(a.pool):
r = json.loads(l)
pool[r["seed_id"]] = r["test_cases"]
cache = GradingCache("outputs/grading_cache/ab_diversify.jsonl")
res = {}
for arm, path in (("canonical", a.canonical), ("canonical_fb", a.canonical_fb),
("stayclose", a.stayclose), ("diversify", a.diversify)):
if not Path(path).exists():
print(f"WARN: {path} missing — skipping {arm}")
continue
per = grade_arm(path, pool, cache, a.workers, a.tle)
res[arm] = metrics(per)
print(f"{arm}: {json.dumps(res[arm])}", flush=True)
present = {k: res[k] for k in ("canonical", "canonical_fb", "stayclose", "diversify") if k in res}
if len(present) >= 2:
res["compare_unique_per_problem"] = {k: v["unique_per_problem"] for k, v in present.items()}
res["compare_dedup_ratio"] = {k: v["dedup_ratio"] for k, v in present.items()}
res["compare_coverage"] = {k: v["coverage_problems"] for k, v in present.items()}
def _d(x, y):
if x in present and y in present:
return round(present[x]["unique_per_problem"] - present[y]["unique_per_problem"], 3)
return None
res["delta_unique_per_problem"] = {
"diversify_minus_stayclose": _d("diversify", "stayclose"),
"stayclose_minus_canonical_fb": _d("stayclose", "canonical_fb"),
"diversify_minus_canonical_fb": _d("diversify", "canonical_fb"),
"canonical_fb_minus_canonical": _d("canonical_fb", "canonical"),
}
Path(a.out).parent.mkdir(parents=True, exist_ok=True)
Path(a.out).write_text(json.dumps(res, indent=2))
print(json.dumps(res, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())