sequential-router-v2 / code /scripts_seqroute /selftest_evaluators.py
divy123's picture
Add files using upload-large-folder tool
8ad880b verified
Raw History Blame Contribute Delete
3.61 kB
"""Evaluator self-test: a gold-derived 'perfect' answer must score Q=10 and a junk answer ~0 for every evaluator type."""
import json
import sys
from collections import deque
import pandas as pd
sys.path.insert(0, "src"); sys.path.insert(0, ".")
from llmroute.seqroute.evaluate import evaluate_row
df = pd.read_parquet("/mnt/localssd/seqroute1m/queries/queries_20k.parquet")
def bw_plan(p):
mv = []
for s in p["init"]:
for b in reversed(s):
mv.append(f"move {b} to table")
for s in p["goal"]:
for i in range(1, len(s)):
mv.append(f"move {s[i]} to {s[i - 1]}")
return json.dumps(mv)
def hanoi_plan(p):
pegs = list(p["init"])
start = tuple(tuple(p["init"][x]) for x in pegs)
goal = tuple(tuple(p["goal"][x]) for x in pegs)
prev, q = {start: None}, deque([start])
while q:
s = q.popleft()
if s == goal:
break
for i in range(3):
if not s[i]:
continue
d = s[i][-1]
for j in range(3):
if i != j and (not s[j] or s[j][-1] > d):
t = list(map(list, s)); t[i].pop(); t[j].append(d)
t = tuple(map(tuple, t))
if t not in prev:
prev[t] = (s, [d, pegs[i], pegs[j]]); q.append(t)
mv, s = [], goal
while prev.get(s):
s, m = prev[s]; mv.append(m)
return json.dumps(mv[::-1])
def perfect(r):
ev, pl = r.evaluator_type, json.loads(r.payload)
if ev == "math_exact":
return f"Final answer: \\boxed{{{pl['gold']}}}"
if ev == "mc_exact":
return f"Reasoning...\nFinal answer: {pl['gold']}"
if ev == "unit_tests":
if pl["kind"] == "humaneval":
ref = r.reference
return f"```python\n{pl['func_prompt'] if not ref.lstrip().startswith(('def', 'from', 'import')) else ''}{ref}\n```"
return f"```python\n{r.reference}\n```" if r.reference else None
if ev == "extraction_f1":
return r.reference
if ev == "exact_str":
return f"Final answer: ({pl['gold']})" if pl["kind"] == "letter" else f"Final answer: **{pl['gold']}**"
if ev in ("label_exact",):
return pl["gold"]
if ev == "json_slots":
return "```json\n" + r.reference + "\n```"
if ev == "qa_f1":
return r.reference
if ev == "plan_blocksworld":
return "Final answer: " + bw_plan(pl)
if ev == "plan_hanoi":
return "Final answer: " + hanoi_plan(pl) if pl["n_disks"] <= 5 else None
if ev == "sudoku":
return "Final answer:\n" + "\n".join("".join(map(str, row)) for row in pl["solution"])
return None
bad = 0
for ev, g in df.groupby("evaluator_type"):
if ev in ("judge_summ", "comet", "simplification"):
continue
res = []
for r in g.sample(min(40, len(g)), random_state=0).itertuples():
pa = perfect(r)
pl = json.loads(r.payload)
wrong = evaluate_row(ev, r.prompt, pl, "I am not sure. Final answer: zzz qq", None, "stop")
if pa is None:
res.append((None, wrong["Q"])); continue
right = evaluate_row(ev, r.prompt, pl, pa, None, "stop")
res.append((right["Q"], wrong["Q"]))
rights = [a for a, b in res if a is not None]
print(f"{ev:18s} n={len(res)} perfect-mean={sum(rights) / max(len(rights), 1):.2f} (n={len(rights)}, min={min(rights) if rights else None}) wrong-mean={sum(b for a, b in res) / len(res):.2f}", flush=True)
for a, b in res:
if a is not None and a < 9.99:
bad += 1
print("imperfect gold cases:", bad)