File size: 12,480 Bytes
6f2ed01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
#!/usr/bin/env python
"""AI Judge: semantic answer clustering, then correctness.   [GPU]  (protocol 3)

    python src/judge_run.py --model Llama-3.2-1B

Two passes, in the order protocol 3 mandates:

  Pass 1  REFERENCE-BLIND. The judge never sees the gold answer. It only groups
          responses that assert the same thing -- "Paris", "The answer is
          Paris.", "巴黎" -- and flags ABSTAIN / MULTIPLE / UNPARSEABLE.
          This is what BCS and BES are built on, and keeping gold out of it is
          what lets a confidently wrong model score BCS = 1.

  Pass 2  REFERENCE-AWARE. Gold, aliases, answer type and granularity are
          supplied, and each CLUSTER (not each response) is labelled. This only
          separates Stable Correct from Stable Wrong; it never reshapes a
          cluster.

The unit of judgement is the (fact, model) pair, per protocol 3.1: judging pairs
of responses independently would produce non-transitive verdicts, where a~b and
b~c but a!~c, and no consistent cluster assignment exists.

Cost control: responses are pre-grouped by normalised surface string before the
judge sees them. Exact post-normalisation identity is a strict subset of
semantic equivalence, so the judge can only ever merge those groups further,
never split them -- the clustering is unchanged, but a typical fact sends 3-6
distinct strings instead of 17 responses.
"""
import os, sys, json, time, argparse, re

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import mcommon as mc
sys.path.insert(0, mc.runner_dir())
from common import normalize                       # noqa: E402

BLIND = """You are clustering short answers to one factual question. You are NOT told the correct answer and must not guess it.

Question: {question}

Candidate answers:
{answers}

Work in two steps, exactly as follows.

Step 1. For each answer, extract ONLY the core entity or value it finally asserts. Strip restated question text, subject names, hedging, reasoning and trailing explanation. "Agriculture and Agri-Food Canada applies in Canada" asserts "Canada". "The answer is Paris." asserts "Paris".

Step 2. Group the answers whose EXTRACTED core is the same entity or value. Ignore wording, language, punctuation and capitalisation; translations of one another belong together, and a bare entity belongs with a full sentence asserting that same entity. Two answers go in different groups only when they name genuinely different entities.

Use these special groups where they apply:
- ABSTAIN: refuses, or says it does not know
- MULTIPLE: gives several conflicting answers without choosing
- UNPARSEABLE: no answer can be extracted

Reply with JSON only, where "meaning" is the extracted core from step 1:
{{"clusters":[{{"ids":[0,2],"meaning":"Paris","status":"ANSWER"}},{{"ids":[1],"meaning":"","status":"ABSTAIN"}}]}}
Every id from 0 to {last} must appear exactly once."""

AWARE = """Judge whether each proposed answer is correct for this question.

Question: {question}
Correct answer: {gold}
Also acceptable: {aliases}
Answer type: {atype} ({gran})

Proposed answers:
{answers}

Label each one:
- CORRECT: same entity/value as the correct answer, any wording or language
- INCORRECT: a different entity/value
- ABSTAIN: a refusal or "I don't know"
- AMBIGUOUS: could refer to the correct answer but is too vague to tell
- REVIEW_REQUIRED: cannot decide

Reply with JSON only: {{"labels":["CORRECT","INCORRECT"]}} with exactly {n} entries in order."""


def parse_json(text):
    """Judges emit prose around the JSON often enough that this must be robust."""
    m = re.search(r"\{.*\}", text, re.S)
    if not m:
        return None
    try:
        return json.loads(m.group(0))
    except json.JSONDecodeError:
        try:
            return json.loads(re.sub(r",\s*([}\]])", r"\1", m.group(0)))
        except json.JSONDecodeError:
            return None


def generate(model, tok, prompts, max_new, batch):
    outs = []
    for i in range(0, len(prompts), batch):
        chunk = prompts[i:i + batch]
        texts = [tok.apply_chat_template([{"role": "user", "content": p}],
                                         tokenize=False, add_generation_prompt=True)
                 for p in chunk]
        enc = tok(texts, return_tensors="pt", padding=True, truncation=True,
                  max_length=2048).to(0)
        with torch.no_grad():
            g = model.generate(**enc, max_new_tokens=max_new, do_sample=False,
                               num_beams=1, pad_token_id=tok.pad_token_id)
        outs += tok.batch_decode(g[:, enc["input_ids"].shape[1]:],
                                 skip_special_tokens=True)
    return outs


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--model", required=True, help="the model being judged")
    ap.add_argument("--judge", default=None)
    ap.add_argument("--batch", type=int, default=32)
    ap.add_argument("--limit", type=int, default=0, help="debug: first N facts")
    ap.add_argument("--sample", type=int, default=0,
                    help="judge a fixed random subset of facts instead of all 2,592")
    ap.add_argument("--sample-seed", type=int, default=20260101)
    ap.add_argument("--resume", action="store_true")
    args = ap.parse_args()

    judge_name = args.judge or mc.models_cfg()["auxiliary_models"]["judge"]["name"]
    if judge_name == args.model:
        raise SystemExit("the judge must not judge itself (MODEL_SELECTION_20 section 6)")

    fams = set(mc.cfg()["main_families"])
    gen_path = mc.generations(args.model)
    if not os.path.exists(gen_path):
        raise SystemExit(
            f"no generations for {args.model}: {gen_path}\n"
            f"run  python runner/eval_run.py --model {args.model}  first")

    qmeta = {r["query_id"]: r for r in mc.main_forward_queries()}
    by_fact = {}
    for r in mc.read_jsonl(gen_path):
        if r["condition_family"] not in fams or r["query_id"] not in qmeta:
            continue
        by_fact.setdefault(r["fact_id"], []).append(r)
    fact_ids = sorted(by_fact)
    if args.sample and args.sample < len(fact_ids):
        # Drawn from the FULL benchmark fact list with a fixed seed, not from
        # this model's own facts, so every model is judged on an identical
        # subset. Sampling per model would make BCS/BES incomparable, which is
        # exactly what protocol 1.3 forbids.
        import numpy as np
        allf = sorted(mc.facts())
        rng = np.random.default_rng(args.sample_seed)
        pick = set(np.array(allf)[rng.choice(len(allf), size=args.sample,
                                             replace=False)].tolist())
        fact_ids = [f for f in fact_ids if f in pick]
    if args.limit:
        fact_ids = fact_ids[:args.limit]

    dest = mc.out("metrics", "judge", f"{args.model}.jsonl")
    done = set()
    if args.resume and os.path.exists(dest):
        done = {r["fact_id"] for r in mc.read_jsonl(dest)}
        fact_ids = [f for f in fact_ids if f not in done]
    if not fact_ids:
        print(f"[{args.model}] judge already complete")
        return

    facts = mc.facts()
    # Pre-group by normalised surface: a strict subset of semantic equivalence,
    # so this changes cost and not the clustering the judge can express.
    tasks = []
    for fid in fact_ids:
        recs = by_fact[fid]
        groups = {}
        for r in recs:
            key = normalize(r["raw_response"].strip().split("\n")[0][:120])
            groups.setdefault(key, []).append(r["query_id"])
        surfaces = list(groups)
        display = [next(x["raw_response"].strip().split("\n")[0][:120]
                        for x in recs if normalize(
                            x["raw_response"].strip().split("\n")[0][:120]) == s) or "(empty)"
                   for s in surfaces]
        tasks.append({"fact_id": fid, "surfaces": surfaces, "display": display,
                      "groups": [groups[s] for s in surfaces],
                      "question": facts[fid]["qualification_question"]})

    path = mc.model_path(judge_name)
    tok = AutoTokenizer.from_pretrained(path)
    if tok.pad_token is None:
        tok.pad_token = tok.eos_token
    tok.padding_side = "left"
    judge = AutoModelForCausalLM.from_pretrained(
        path, dtype=torch.bfloat16, device_map={"": 0}).eval()

    t0 = time.time()
    out_f = open(dest, "a" if done else "w")
    for i in range(0, len(tasks), args.batch):
        chunk = tasks[i:i + args.batch]

        p1 = [BLIND.format(question=t["question"], last=len(t["display"]) - 1,
                           answers="\n".join(f"{j}. {d}" for j, d in enumerate(t["display"])))
              for t in chunk]
        r1 = generate(judge, tok, p1, 512, args.batch)

        for t, raw in zip(chunk, r1):
            js = parse_json(raw) or {}
            clusters, seen = [], set()
            for c in js.get("clusters", []):
                ids = [int(x) for x in c.get("ids", [])
                       if isinstance(x, (int, float)) and 0 <= int(x) < len(t["display"])
                       and int(x) not in seen]
                if not ids:
                    continue
                seen.update(ids)
                clusters.append({"ids": ids, "meaning": str(c.get("meaning", ""))[:80],
                                 "status": str(c.get("status", "ANSWER")).upper()})
            # Anything the judge dropped or mangled stays its own cluster rather
            # than vanishing: silently losing a response would change the BCS
            # denominator for that fact.
            for j in range(len(t["display"])):
                if j not in seen:
                    clusters.append({"ids": [j], "meaning": t["display"][j][:80],
                                     "status": "ANSWER", "recovered": True})
            t["clusters"] = clusters
            t["judge_raw_blind"] = raw[:400]

        p2, own = [], []
        for t in chunk:
            f = facts[t["fact_id"]]
            answer = [c["meaning"] or t["display"][c["ids"][0]] for c in t["clusters"]]
            p2.append(AWARE.format(
                question=t["question"], gold=f["object"]["canonical"],
                aliases=", ".join(f["object"]["aliases"][:10]),
                atype=f.get("answer_type", "entity"),
                gran=f.get("answer_granularity", "entity"),
                answers="\n".join(f"{j}. {a}" for j, a in enumerate(answer)),
                n=len(answer)))
            own.append(t)
        r2 = generate(judge, tok, p2, 256, args.batch)
        for t, raw in zip(own, r2):
            js = parse_json(raw) or {}
            labels = [str(x).upper() for x in js.get("labels", [])]
            for j, c in enumerate(t["clusters"]):
                lab = labels[j] if j < len(labels) else "REVIEW_REQUIRED"
                if c["status"] in ("ABSTAIN", "MULTIPLE", "UNPARSEABLE"):
                    lab = c["status"] if c["status"] == "ABSTAIN" else "REVIEW_REQUIRED"
                c["correctness"] = lab
            t["judge_raw_aware"] = raw[:400]

        for t in chunk:
            rows = []
            for k, c in enumerate(t["clusters"]):
                cid = f"C{k}" if c["status"] == "ANSWER" else c["status"]
                for j in c["ids"]:
                    for qid in t["groups"][j]:
                        rows.append({"query_id": qid,
                                     "condition_family": qmeta[qid]["condition_family"],
                                     "cluster_id": cid})
            out_f.write(json.dumps({
                "model": args.model, "judge": judge_name, "fact_id": t["fact_id"],
                "clusters": [{"cluster_id": f"C{k}" if c["status"] == "ANSWER"
                              else c["status"],
                              "canonical_meaning": c["meaning"],
                              "status": c["status"],
                              "correctness": c.get("correctness", "REVIEW_REQUIRED")}
                             for k, c in enumerate(t["clusters"])],
                "assignments": rows}, ensure_ascii=False) + "\n")
        out_f.flush()
        d = i + len(chunk)
        print(f"  {d}/{len(tasks)} facts  {d / max(time.time() - t0, 1e-9):.2f}/s",
              flush=True)
    out_f.close()
    print(f"[{args.model}] judged {len(tasks)} facts with {judge_name}  JUDGE_DONE",
          flush=True)


if __name__ == "__main__":
    main()