File size: 17,335 Bytes
41a0653
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
#!/usr/bin/env python3
"""Portable teacher-vs-prune eval kit for GLM-5.3-Flash (any OpenAI-compatible endpoint: our Thor CUDA server,
vLLM, or a hosted API). The SAME script, prompts, item ids, seed and generation config run
against both models, so every suite is a paired comparison.

  gen    : python glm_eval.py gen --suite ifbench --url http://127.0.0.1:8080 --expect-model ID --out results/ARM
  grade  : python glm_eval.py grade --suite ifbench --out results/ARM
  compare: python glm_eval.py compare --suite ifbench --a results/TEACHER --b results/PRUNE

Suites: gpqa (GPQA-Diamond, 198), ifbench (IFBench test, 300), humanevalplus (164), mmlupro (seeded subset of
MMLU-Pro test), aime26 (30). Item order is fixed (seeded), so partial runs of two arms pair on the same prefix.
Generation config is pinned and written into every record. Resumable: done ids are skipped.
Truncation = finish_reason length OR completion_tokens >= max_tokens (some servers report 'stop' on the cap).
"""
from __future__ import annotations

import argparse, csv, glob, hashlib, json, math, os, random, re, subprocess, sys, tempfile, threading, time, urllib.request
from pathlib import Path

HERE = Path(__file__).resolve().parent
DATA = HERE / "data"
VERSION = "glm_eval 1.0 (2026-11-14)"

# ----------------------------------------------------------------------------------------------- items
MC_TMPL = ("Answer the following multiple choice question. The last line of your response should be of the following "
           "format: 'Answer: $LETTER' (without quotes) where LETTER is one of {letters}. Think step by step before "
           "answering.\n\n{q}\n\n{opts}")


def items_gpqa():
    rows = list(csv.DictReader(open(DATA / "gpqa" / "gpqa_diamond.csv", encoding="utf-8")))
    out = []
    for i, r in enumerate(rows):
        ch = [r["Correct Answer"], r["Incorrect Answer 1"], r["Incorrect Answer 2"], r["Incorrect Answer 3"]]
        perm = list(range(4)); random.Random(f"gpqa-{i}").shuffle(perm)
        opts = [ch[j].strip() for j in perm]
        gold = "ABCD"[perm.index(0)]
        out.append({"id": f"gpqa-{i}", "prompt": MC_TMPL.format(letters="ABCD", q=r["Question"].strip(),
                    opts="\n".join(f"{'ABCD'[k]}) {o}" for k, o in enumerate(opts))), "gold": gold})
    return out


def items_mmlupro(n_default=500):
    import pandas as pd
    d = pd.read_parquet(DATA / "mmlupro" / "data" / "test-00000-of-00001.parquet")
    idx = list(range(len(d))); random.Random(0).shuffle(idx)
    out = []
    for i in idx:
        r = d.iloc[i]; opts = list(r["options"]); L = "ABCDEFGHIJ"[:len(opts)]
        out.append({"id": f"mmlupro-{int(r['question_id'])}", "prompt": MC_TMPL.format(letters=",".join(L), q=r["question"].strip(),
                    opts="\n".join(f"{L[k]}) {o}" for k, o in enumerate(opts))), "gold": r["answer"], "category": r["category"]})
    return out


def items_aime26():
    import pandas as pd
    d = pd.read_parquet(DATA / "aime26" / "data" / "train-00000-of-00001.parquet")
    return [{"id": f"aime26-{int(r['problem_idx'])}", "prompt": r["problem"].strip() +
             "\n\nPlease reason step by step, and put your final answer within \\boxed{}.", "gold": str(r["answer"]).strip()}
            for _, r in d.iterrows()]


def items_humanevalplus():
    out = []
    for l in open(DATA / "humanevalplus" / "test.jsonl"):
        r = json.loads(l)
        out.append({"id": r["task_id"].replace("/", "-"), "prompt": "Complete the following Python function. Reply with the "
                    "complete function (including the signature and any imports it needs) in a single ```python code block.\n\n"
                    f"```python\n{r['prompt']}```", "entry_point": r["entry_point"], "test": r["test"], "src_prompt": r["prompt"]})
    return out


def _clean(v):
    if isinstance(v, float) and v.is_integer(): return int(v)
    if hasattr(v, "tolist"): return [_clean(x) for x in v.tolist()]
    if isinstance(v, (list, tuple)): return [_clean(x) for x in v]
    return v


def items_ifbench():
    import pandas as pd
    d = pd.read_parquet(DATA / "ifbench" / "data" / "train-00000-of-00001.parquet")
    out = []
    for _, r in d.iterrows():
        kw = [{k: _clean(v) for k, v in dict(x).items() if v is not None and not (isinstance(v, float) and math.isnan(v))} for x in r["kwargs"]]
        out.append({"id": f"ifbench-{r['key']}", "prompt": r["prompt"], "instruction_id_list": list(r["instruction_id_list"]),
                    "kwargs": kw, "key": str(r["key"])})
    return out


SUITES = {"gpqa": items_gpqa, "mmlupro": items_mmlupro, "aime26": items_aime26, "humanevalplus": items_humanevalplus,
          "ifbench": items_ifbench}

# ----------------------------------------------------------------------------------------------- client
def http(url, body=None, timeout=60):
    req = urllib.request.Request(url, data=None if body is None else json.dumps(body).encode(),
                                 headers={"Content-Type": "application/json", **({"Authorization": "Bearer " + os.environ["EVAL_API_KEY"]}
                                                                                if os.environ.get("EVAL_API_KEY") else {})})
    with urllib.request.urlopen(req, timeout=timeout) as r:
        return json.loads(r.read())


def gen_cfg(a):
    return {"temperature": a.temperature, "top_p": a.top_p, "max_tokens": a.max_tokens, "seed": a.seed,
            "reasoning_effort": a.effort}


def chat(a, prompt):
    g = gen_cfg(a)
    body = {"model": a.expect_model, "messages": [{"role": "user", "content": prompt}], "stream": False,
            "temperature": g["temperature"], "top_p": g["top_p"], "max_tokens": g["max_tokens"], "seed": g["seed"]}
    if a.effort:  # GLM template levels: low / high / max ("" = template default = max)
        body["reasoning_effort"] = a.effort
        if not a.no_template_kwargs:
            body["chat_template_kwargs"] = {"reasoning_effort": a.effort}
    if a.extra_body:
        body.update(json.loads(a.extra_body))
    t0 = time.time()
    out = http(a.chat_url or (a.url.rstrip("/") + "/v1/chat/completions"), body, timeout=a.timeout)
    out["_latency_s"] = round(time.time() - t0, 2)
    return out


def cmd_gen(a):
    items = SUITES[a.suite]()
    if a.n: items = items[:a.n]
    out = Path(a.out); out.mkdir(parents=True, exist_ok=True)
    f = out / f"{a.suite}.jsonl"
    done = set()
    if f.exists():
        for l in open(f):
            r = json.loads(l)
            if r.get("type") == "item": done.add(r["id"])
    if not a.no_model_check:
        models = [m["id"] for m in http(a.url.rstrip("/") + "/v1/models")["data"]]
        if a.expect_model not in models:
            sys.exit(f"served models {models} do not include --expect-model {a.expect_model}")
    ids_sha = hashlib.sha256("\n".join(i["id"] for i in items).encode()).hexdigest()[:16]
    with open(f, "a") as w:
        w.write(json.dumps({"type": "header", "version": VERSION, "suite": a.suite, "n": len(items), "item_ids_sha16": ids_sha,
                            "model": a.expect_model, "url": a.url, "gen": gen_cfg(a), "ts": time.strftime("%Y-%m-%dT%H:%M:%S%z")}) + "\n")
        w.flush()
        if a.deadline:
            dl = time.mktime(time.strptime(a.deadline, "%Y-%m-%dT%H:%M"))
        todo = [it for it in items if it["id"] not in done]
        lock = threading.Lock()

        def put(obj):
            with lock:
                w.write(json.dumps(obj) + "\n"); w.flush()

        def spent():
            usd = 0.0
            for fp in glob.glob(a.budget_glob):
                for l in open(fp):
                    try: r = json.loads(l)
                    except ValueError: continue
                    if r.get("type") == "item":
                        u = r.get("usage") or {}
                        usd += (u.get("prompt_tokens") or 0) * a.price_in / 1e6 + (u.get("completion_tokens") or 0) * a.price_out / 1e6
            return usd

        def one(it):
            if a.deadline and time.time() > dl:
                return "deadline"
            if a.budget_usd:
                with lock:
                    if spent() >= a.budget_usd:
                        return "budget"
            try:
                r = chat(a, it["prompt"])
            except Exception as e:
                put({"type": "error", "id": it["id"], "err": str(e)[:300]}); return None
            if r.get("model") not in (None, a.expect_model) and not a.allow_model_alias:
                put({"type": "abort", "why": f"response model {r.get('model')}"}); return "abort"
            ch = r["choices"][0]; msg = ch.get("message") or {}
            u = r.get("usage") or {}
            ctok = u.get("completion_tokens") or 0
            put({"type": "item", "id": it["id"], "model": r.get("model"), "content": msg.get("content") or "",
                 "reasoning": msg.get("reasoning_content") or msg.get("reasoning") or "", "finish_reason": ch.get("finish_reason"),
                 "usage": u, "truncated": ch.get("finish_reason") == "length" or ctok >= a.max_tokens,
                 "latency_s": r["_latency_s"], "gen": gen_cfg(a)})
            return None

        if a.workers <= 1:
            for it in todo:
                st = one(it)
                if st == "abort": sys.exit(2)
                if st in ("deadline", "budget"): put({"type": "stop", "why": st, "ts": time.time()}); break
        else:
            from concurrent.futures import ThreadPoolExecutor
            with ThreadPoolExecutor(a.workers) as ex:
                sts = list(ex.map(one, todo))
            if "abort" in sts: sys.exit(2)
            for why in ("deadline", "budget"):
                if why in sts: put({"type": "stop", "why": why, "ts": time.time()})


# ----------------------------------------------------------------------------------------------- grading
def last_letter(text, letters):
    m = re.findall(r"(?i)answer\s*[::]\s*\**\(?([A-J])\)?", text)
    if m and m[-1].upper() in letters: return m[-1].upper()
    m = re.findall(r"(?i)answer is\s*\(?([A-J])\)?", text)
    if m and m[-1].upper() in letters: return m[-1].upper()
    return None


def boxed(text):
    i = text.rfind("\\boxed{")
    if i < 0: return None
    j, depth = i + 7, 1
    while j < len(text) and depth:
        depth += {"{": 1, "}": -1}.get(text[j], 0); j += 1
    return text[i + 7:j - 1].strip()


def norm_int(s):
    if s is None: return None
    s = re.sub(r"[\s,$]|\\text\{[^}]*\}|\\!|\^\\circ|\\%", "", s)
    m = re.fullmatch(r"0*(\d+)", s)
    return str(int(m.group(1))) if m else s


def extract_code(text, entry):
    blocks = re.findall(r"```(?:python|py)?\s*\n(.*?)```", text, re.S)
    for b in reversed(blocks):
        if f"def {entry}" in b: return b
    return blocks[-1] if blocks else text


def run_humaneval(code, test, entry, timeout=60):
    prog = code + "\n\n" + test + f"\n\ncheck({entry})\n"
    with tempfile.TemporaryDirectory() as d:
        p = Path(d) / "t.py"; p.write_text(prog)
        try:
            r = subprocess.run([sys.executable, "-I", str(p)], cwd=d, capture_output=True, timeout=timeout, text=True,
                               preexec_fn=lambda: __import__("resource").setrlimit(__import__("resource").RLIMIT_AS, (4 << 30, 4 << 30)))
            return r.returncode == 0, r.stderr[-300:]
        except subprocess.TimeoutExpired:
            return False, "timeout"


def load_items(path):
    items = {}
    for l in open(path):
        r = json.loads(l)
        if r.get("type") == "item": items[r["id"]] = r
    return items


def cmd_grade(a):
    out = Path(a.out); gen = load_items(out / f"{a.suite}.jsonl")
    src = {i["id"]: i for i in SUITES[a.suite]()}
    res = {}
    if a.suite == "ifbench":
        sys.path.insert(0, str(HERE / "IFBench"))
        os.environ.setdefault("NLTK_DATA", str(HERE / "nltk_data"))
        import evaluation_lib as E
        for iid, g in gen.items():
            s = src[iid]
            inp = E.InputExample(key=s["key"], instruction_id_list=s["instruction_id_list"], prompt=s["prompt"], kwargs=s["kwargs"])
            st = E.test_instruction_following_strict(inp, {s["prompt"]: g["content"]})
            lo = E.test_instruction_following_loose(inp, {s["prompt"]: g["content"]})
            res[iid] = {"pass": bool(st.follow_all_instructions), "loose": bool(lo.follow_all_instructions),
                        "inst_strict": [bool(x) for x in st.follow_instruction_list], "truncated": g["truncated"]}
    else:
        for iid, g in gen.items():
            s = src[iid]; c = g["content"]
            if a.suite in ("gpqa", "mmlupro"):
                pred = last_letter(c, "ABCDEFGHIJ"); ok = pred == s["gold"]
            elif a.suite == "aime26":
                pred = norm_int(boxed(c)); ok = pred == norm_int(s["gold"])
            elif a.suite == "humanevalplus":
                ok, pred = run_humaneval(extract_code(c, s["entry_point"]), s["test"], s["entry_point"])
            res[iid] = {"pass": bool(ok), "pred": pred if not isinstance(pred, str) or len(pred) < 300 else pred[:300],
                        "truncated": g["truncated"], "empty_content": not c.strip()}
    n = len(res); k = sum(r["pass"] for r in res.values())
    tr = sum(r["truncated"] for r in res.values())
    toks = [gen[i]["usage"].get("completion_tokens", 0) for i in res]
    summ = {"suite": a.suite, "n": n, "pass": k, "acc": k / n if n else None, "ci95": wilson(k, n), "truncated": tr,
            "mean_completion_tokens": sum(toks) / n if n else None,
            **({"loose_acc": sum(r["loose"] for r in res.values()) / n,
                "inst_strict_acc": sum(sum(r["inst_strict"]) for r in res.values()) / max(1, sum(len(r["inst_strict"]) for r in res.values()))}
               if a.suite == "ifbench" else {})}
    json.dump({"summary": summ, "items": res}, open(out / f"{a.suite}.graded.json", "w"), indent=1)
    print(json.dumps(summ))


def wilson(k, n, z=1.96):
    if not n: return None
    p = k / n; d = 1 + z * z / n; c = (p + z * z / (2 * n)) / d; h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
    return [round(c - h, 4), round(c + h, 4)]


def cmd_compare(a):
    A = json.load(open(Path(a.a) / f"{a.suite}.graded.json"))["items"]
    B = json.load(open(Path(a.b) / f"{a.suite}.graded.json"))["items"]
    ids = sorted(set(A) & set(B))
    pa = [A[i]["pass"] for i in ids]; pb = [B[i]["pass"] for i in ids]
    b_ = sum(x and not y for x, y in zip(pa, pb)); c_ = sum(y and not x for x, y in zip(pa, pb))
    nn = b_ + c_; kk = min(b_, c_)
    p = min(1.0, 2 * sum(math.comb(nn, i) for i in range(kk + 1)) / 2 ** nn) if nn else 1.0
    na, nb = sum(pa), sum(pb)
    print(json.dumps({"suite": a.suite, "paired_n": len(ids), "a": a.a, "b": a.b, "a_pass": na, "b_pass": nb,
                      "retention_b_over_a": nb / na if na else None, "a_only": b_, "b_only": c_, "mcnemar_p": p}))


def main():
    ap = argparse.ArgumentParser(); sp = ap.add_subparsers(dest="cmd", required=True)
    g = sp.add_parser("gen"); g.add_argument("--suite", required=True, choices=SUITES); g.add_argument("--url", required=True)
    g.add_argument("--expect-model", required=True); g.add_argument("--out", required=True); g.add_argument("--n", type=int, default=0)
    g.add_argument("--effort", default="high"); g.add_argument("--temperature", type=float, default=1.0)
    g.add_argument("--top-p", type=float, default=0.95); g.add_argument("--max-tokens", type=int, default=24576)
    g.add_argument("--seed", type=int, default=0); g.add_argument("--timeout", type=float, default=7200)
    g.add_argument("--deadline", default=None, help="local time YYYY-MM-DDTHH:MM; stop starting new items after it")
    g.add_argument("--chat-url", default=None, help="full chat-completions URL for hosted APIs (overrides URL/v1/chat/completions)")
    g.add_argument("--no-model-check", action="store_true", help="skip the /v1/models identity check (hosted APIs)")
    g.add_argument("--extra-body", default=None, help="JSON merged into every request body (provider-specific fields)")
    g.add_argument("--budget-usd", type=float, default=0.0, help="stop starting items once the spend over --budget-glob reaches this")
    g.add_argument("--budget-glob", default="", help="glob of result jsonl files whose usage counts toward the budget")
    g.add_argument("--price-in", type=float, default=0.0, help="USD per 1M prompt tokens")
    g.add_argument("--price-out", type=float, default=0.0, help="USD per 1M completion tokens")
    g.add_argument("--no-template-kwargs", action="store_true", help="send reasoning_effort only as a top-level field (hosted APIs)")
    g.add_argument("--workers", type=int, default=1, help="concurrent requests (vLLM batches them); 1 = sequential")
    g.add_argument("--allow-model-alias", action="store_true", help="hosted APIs may echo a different model string")
    gr = sp.add_parser("grade"); gr.add_argument("--suite", required=True, choices=SUITES); gr.add_argument("--out", required=True)
    c = sp.add_parser("compare"); c.add_argument("--suite", required=True, choices=SUITES); c.add_argument("--a", required=True); c.add_argument("--b", required=True)
    a = ap.parse_args()
    {"gen": cmd_gen, "grade": cmd_grade, "compare": cmd_compare}[a.cmd](a)


if __name__ == "__main__":
    main()