File size: 4,040 Bytes
901f964
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
"""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}")