File size: 3,792 Bytes
676defa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
63
64
65
#!/usr/bin/env python3
"""LLM-judge factual correctness for the multi-tool set (semantic/factual
correctness rather than lexical overlap).

    python3 mt_judge.py --pred preds_mt/X.jsonl --name X --provider glm --judge glm-5.3 [--concurrency 10]

The judge sees the question, the GOLD backend outputs (so answers built from wrongly
routed calls are judged against what the correct analyses say), the reference answer
and the candidate, and returns a 0-1 score. Wording and style are not scored.
Output: scores/mt/judge/<name>.judge_<judge>.jsonl  {question_hash, score, reasoning}
"""
import argparse, json, os, sys, time, statistics as st
from concurrent.futures import ThreadPoolExecutor, as_completed
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import mt_qa
SYS = ("You are an expert hardware-design reviewer grading answers about a Verilog module. You are given the "
       "question, the outputs of the EDA analyses relevant to it (ground truth), a reference answer, and a "
       "candidate answer. Score the candidate's factual correctness and completeness for the question on a "
       "scale from 0.0 to 1.0, using the analysis outputs as ground truth:\n"
       "1.0 = every stated fact agrees with the analysis outputs and every part of the question is answered;\n"
       "deduct for wrong or invented values, claims not supported by the outputs, and parts of the question left "
       "unanswered. The candidate may use different but correct facts than the reference. Do not score wording, "
       "length or style.\n"
       'Return only JSON: {"score": <float>, "reasoning": "<one sentence>"}')
def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--pred", required=True); ap.add_argument("--name", required=True)
    ap.add_argument("--ref", default="splits/mt/test.jsonl")
    ap.add_argument("--provider", choices=["glm", "claude-cli"], required=True); ap.add_argument("--judge", required=True)
    ap.add_argument("--concurrency", type=int, default=8)
    a = ap.parse_args()
    mt_qa.SYS = SYS
    ref = {json.loads(l)["question_hash"]: json.loads(l) for l in open(a.ref)}
    preds = {json.loads(l)["question_hash"]: json.loads(l).get("prediction", "") for l in open(a.pred)}
    os.makedirs("scores/mt/judge", exist_ok=True)
    out = f"scores/mt/judge/{a.name}.judge_{a.judge}.jsonl"
    done = set()
    if os.path.exists(out):
        for l in open(out): done.add(json.loads(l)["question_hash"])
    todo = [h for h in ref if h not in done]
    ask = (lambda u: mt_qa.ask_glm(a.judge, u)) if a.provider == "glm" else (lambda u: mt_qa.ask_cli(a.judge, u))
    def work(h):
        r = ref[h]
        u = (f"Question:\n{r['question']}\n\nAnalysis outputs (ground truth):\n{r['tool_result']}\n\n"
             f"Reference answer:\n{r['answer']}\n\nCandidate answer:\n{preds.get(h, '')}")
        for _ in range(4):
            try:
                t = ask(u)
                if "```" in t: t = t.split("```")[1].removeprefix("json")
                d = json.loads(t[t.find("{"): t.rfind("}") + 1])
                s = float(d["score"])
                return {"question_hash": h, "score": max(0.0, min(1.0, s)), "reasoning": str(d.get("reasoning", ""))[:300]}
            except Exception:
                time.sleep(3)
        return None
    n = ok = 0
    with ThreadPoolExecutor(a.concurrency) as ex, open(out, "a") as f:
        for fu in as_completed([ex.submit(work, h) for h in todo]):
            r = fu.result(); n += 1
            if r: f.write(json.dumps(r) + "\n"); f.flush(); ok += 1
    sc = [json.loads(l)["score"] for l in open(out)]
    print(json.dumps({"name": a.name, "judge": a.judge, "n": len(sc), "missing": len(ref) - len(sc), "mean": round(100 * st.mean(sc), 1)}))
if __name__ == "__main__":
    main()