tablinum-2 / code /grade.py
chadstthomas's picture
Tablinum-2: the Lite-Beam engram, release 2 (card, code, recipes, 9 released tables)
901f964 verified
Raw History Blame Contribute Delete
4.04 kB
"""grade.py RUN.jsonl [...] - grade engram_eval answers (10-19). Deterministic first: abstention phrases -> NOT_ATTEMPTED; normalised
gold contained in the answer (or the same number) -> CORRECT. Everything else goes to Beam with AA-Omniscience's own grader
template (qa/aa_grader_template.txt, A/B/C/D), the same judge for every arm, blind to the arm. Writes RUN.graded.jsonl (env GRADED renames) and prints
per arm: correct / incorrect / partial / not attempted and the Omniscience-style index 100*(C-I)/N. Env: PAR (8)."""
import sys, os, json, re, threading, urllib.request, concurrent.futures as cf
TPL = open("$ENGRAM_ROOT/qa/aa_grader_template.txt").read()
# 10-26: env JUDGE_URL / JUDGE_EFFORT / JUDGE_TAG let another local model judge (Qwen3.8 runs: Qwen judges, effort "low");
# defaults are Beam as before. graded_by records the judge.
U = os.environ.get("JUDGE_URL", "http://127.0.0.1:8080/v1/chat/completions")
JE, JT = os.environ.get("JUDGE_EFFORT", "minimal"), os.environ.get("JUDGE_TAG", "beam")
ABST = re.compile(r"\b(i don.?t know|not (?:certain|sure)|unsure|cannot (?:determine|verify|answer)|can.?t (?:determine|verify|answer)|insufficient|"
r"no (?:reliable|verified)|i (?:do not|don.?t) have|uncertain|unknown|need more context|without (?:verification|tools))", re.I)
norm = lambda s: re.sub(r"[^a-z0-9.]+", " ", s.lower()).strip()
num = lambda s: [float(x.replace(",", "")) for x in re.findall(r"-?\d[\d,]*\.?\d*", s)]
HEDGE = re.compile(r"\b(or|likely|probably|possibly|approximately|about|around|roughly|between|perhaps|maybe)\b|[~–]|\d\s*-\s*\d|\?", re.I)
def det(r): # 10-20: a rule CORRECT needs a short, unhedged answer; hedges, ranges and alternatives go to the judge
a, g = r["answer"], r["gold"]
if not a.strip() or r["finish"] in ("error", "length"):
return "NOT_ATTEMPTED"
if norm(a) == norm(g):
return "CORRECT"
if ABST.search(a):
return "NOT_ATTEMPTED" if len(a) < 400 and not (norm(g) and re.search(rf"(^| ){re.escape(norm(g))}( |$)", norm(a))) else None
if norm(g) and re.search(rf"(^| ){re.escape(norm(g))}( |$)", norm(a)) and len(a) <= len(g) + 30 and not HEDGE.search(a.replace(g, "")):
return "CORRECT"
return None
def judge(r):
body = {"model": "beam-1.0", "max_tokens": 2048, "temperature": 0, "chat_template_kwargs": {"reasoning_effort": JE},
"messages": [{"role": "user", "content": TPL.replace("{question}", r["q"]).replace("{target}", r["gold"]).replace("{predicted_answer}", r["answer"])}]}
d = json.load(urllib.request.urlopen(urllib.request.Request(U, json.dumps(body).encode(), {"Content-Type": "application/json"}), timeout=3600))
m = re.findall(r"\b([ABCD])\b", (d["choices"][0]["message"].get("content") or "").strip()[-20:])
return {"A": "CORRECT", "B": "INCORRECT", "C": "PARTIAL_ANSWER", "D": "NOT_ATTEMPTED"}.get(m[-1] if m else "", "INCORRECT")
for path in sys.argv[1:]:
out = path[:-6] + "." + os.environ.get("GRADED", "graded") + ".jsonl"; done = {}
if os.path.exists(out):
done = {(d["id"], d["arm"]): d for d in map(json.loads, open(out))}
rows = [r for r in map(json.loads, open(path)) if (r["id"], r["arm"]) not in done]; lock = threading.Lock()
def one(r):
g = det(r); r["grade"], r["graded_by"] = (g, "rule") if g else (judge(r), JT)
with lock:
with open(out, "a") as f:
f.write(json.dumps(r) + "\n")
done[(r["id"], r["arm"])] = r
with cf.ThreadPoolExecutor(int(os.environ.get("PAR", 8))) as ex:
list(ex.map(one, rows))
by = {}
for r in done.values():
by.setdefault(r["arm"], []).append(r["grade"])
for arm, gs in sorted(by.items()):
n = len(gs); c = gs.count("CORRECT"); i = gs.count("INCORRECT")
print(f"{os.path.basename(path)} {arm}: n={n} correct {c} incorrect {i} partial {gs.count('PARTIAL_ANSWER')} not-attempted {gs.count('NOT_ATTEMPTED')} "
f"| accuracy {100 * c / n:.1f}% index {100 * (c - i) / n:.1f}")