File size: 7,747 Bytes
eeab540
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Score a closed-set Hub benchmark with a d3 decision model over /v1/systemone.

Each item becomes one System One request with a single `choice` question; the
predicted answer is the argmax of the returned option probabilities.
"""

import argparse
import ast
import base64
import concurrent.futures as cf
import hashlib
import io
import json
import random
import time
import urllib.request
from pathlib import Path

import pyarrow.parquet as pq

DATA = Path(__file__).parent / "data"
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"


def as_list(v):
    return list(v) if not isinstance(v, str) else ast.literal_eval(v)


def evasion(seed):
    rows = pq.read_table(DATA / "EvasionBench/evasionbench_17k_eva4b_labels_dedup.parquet").to_pylist()
    for r in rows:
        labels = as_list(r["choices"])
        yield {
            "id": r["uid"],
            "state": f"Question: {r['question']}\n\nAnswer: {r['answer']}",
            "instructions": "You are a financial analyst. Detect evasive answers in financial Q&A: how directly does the answer address the question?",
            "options": {lab: None for lab in labels},
            "gold": r["eva4b_label"],
        }


def mmlu_pro(seed):
    rows = pq.read_table(DATA / "MMLU-Pro/data/test-00000-of-00001.parquet").to_pylist()
    for r in rows:
        opts = as_list(r["options"])
        yield {
            "id": str(r["question_id"]),
            "state": r["question"],
            "instructions": "Which option correctly answers the question?",
            "options": {LETTERS[i]: o for i, o in enumerate(opts)},
            "gold": r["answer"],
            "group": r["category"],
        }


def lexam_mcq4(seed):
    rows = pq.read_table(DATA / "LEXam/mcq_4_choices/test-00000-of-00001.parquet").to_pylist()
    for r in rows:
        opts = as_list(r["choices"])
        yield {
            "id": r["id"],
            "state": r["question"],
            "instructions": "Which option correctly answers the question?",
            "options": {LETTERS[i]: o for i, o in enumerate(opts)},
            "gold": LETTERS[int(r["gold"])],
            "group": r["language"],
        }


REENCODE = False  # set by --reencode-images for servers that reject >8 MB or MPO images


def _img(v):
    b = v["bytes"] if isinstance(v, dict) else v
    head = b[:12]
    if REENCODE and (len(b) > 7_500_000 or b"MPF\x00" in b[:65536]):
        from PIL import Image
        im = Image.open(io.BytesIO(b))
        im.seek(0)
        im = im.convert("RGB")
        scale = min(1.0, (1_638_400 / (im.width * im.height)) ** 0.5)
        if scale < 1:
            im = im.resize((round(im.width * scale), round(im.height * scale)), Image.BICUBIC)
        buf = io.BytesIO()
        im.save(buf, "PNG")
        b, head = buf.getvalue(), b"\x89PNG"
    mime = "image/png" if head.startswith(b"\x89PNG") else "image/webp" if head[8:12] == b"WEBP" else "image/jpeg"
    return f"data:{mime};base64,{base64.b64encode(b).decode()}"


def mmmu_pro(config):
    def gen(seed):
        files = sorted((DATA / "MMMU_Pro" / config).glob("test-*.parquet"))
        for f in files:
            for batch in pq.ParquetFile(f).iter_batches(batch_size=64):
                for r in batch.to_pylist():
                    opts = as_list(r["options"])
                    if config == "vision":
                        images, state = [_img(r["image"])], "Answer the multiple-choice question shown in the image."
                    else:
                        images = [_img(r[f"image_{i}"]) for i in range(1, 8) if r.get(f"image_{i}")]
                        state = r["question"]
                    yield {
                        "id": r["id"],
                        "state": state,
                        "images": images,
                        "instructions": "Which option correctly answers the question?",
                        "options": {LETTERS[i]: o for i, o in enumerate(opts)},
                        "gold": r["answer"],
                        "group": r.get("subject"),
                    }
    return gen


BENCH = {
    "evasion_bench": evasion,
    "mmlu_pro": mmlu_pro,
    "lexam_mcq4": lexam_mcq4,
    "mmmu_pro_standard_10": mmmu_pro("standard (10 options)"),
    "mmmu_pro_standard_4": mmmu_pro("standard (4 options)"),
    "mmmu_pro_vision": mmmu_pro("vision"),
}


def ask(endpoint, model, item, timeout):
    body = {
        "model": model,
        "state": item["state"],
        "questions": {"answer": {"type": "choice", "instructions": item["instructions"], "criteria": item["options"]}},
    }
    if item.get("images"):
        body["images"] = item["images"]
    req = urllib.request.Request(f"{endpoint}/v1/systemone", json.dumps(body).encode(), {"Content-Type": "application/json"})
    t0 = time.monotonic()
    for attempt in range(3):
        try:
            with urllib.request.urlopen(req, timeout=timeout) as resp:
                ans = json.load(resp)["answers"]["answer"]
            probs = ans["probabilities"]
            return {"pred": max(probs, key=probs.get), "probs": probs, "latency_s": time.monotonic() - t0}
        except Exception as e:  # noqa: BLE001 - recorded per item
            err = f"{type(e).__name__}: {getattr(e, 'read', lambda: b'')()[:300]!r} {e}"
            time.sleep(1 + attempt)
    return {"error": err, "latency_s": time.monotonic() - t0}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--bench", required=True, choices=BENCH)
    ap.add_argument("--model", required=True)
    ap.add_argument("--endpoint", default="http://127.0.0.1:8000")
    ap.add_argument("--out", required=True)
    ap.add_argument("--limit", type=int)
    ap.add_argument("--seed", type=int, default=0)
    ap.add_argument("--concurrency", type=int, default=16)
    ap.add_argument("--timeout", type=float, default=300)
    ap.add_argument("--reencode-images", action="store_true")
    a = ap.parse_args()
    global REENCODE
    REENCODE = a.reencode_images

    items = list(BENCH[a.bench](a.seed))
    if a.limit:
        items = random.Random(a.seed).sample(items, min(a.limit, len(items)))
    out = Path(a.out)
    out.parent.mkdir(parents=True, exist_ok=True)
    done = {}
    if out.exists():
        for line in out.open():
            r = json.loads(line)
            if "error" not in r:
                done[r["id"]] = r
    todo = [it for it in items if it["id"] not in done]
    print(f"{a.bench} {a.model}: {len(items)} items, {len(done)} cached, {len(todo)} to run", flush=True)
    with out.open("a") as f, cf.ThreadPoolExecutor(a.concurrency) as pool:
        futs = {pool.submit(ask, a.endpoint, a.model, it, a.timeout): it for it in todo}
        for n, fut in enumerate(cf.as_completed(futs), 1):
            it = futs[fut]
            r = {"id": it["id"], "gold": it["gold"], "group": it.get("group"), **fut.result()}
            f.write(json.dumps(r) + "\n")
            done[it["id"]] = r
            if n % 500 == 0:
                print(f"  {n}/{len(todo)}", flush=True)

    ids = {it["id"] for it in items}
    rows = [done[i] for i in ids if i in done]
    ok = [r for r in rows if "error" not in r]
    correct = sum(r["pred"] == r["gold"] for r in ok)
    lat = sorted(r["latency_s"] for r in ok)
    summary = {
        "bench": a.bench, "model": a.model, "n": len(items), "answered": len(ok),
        "errors": len(items) - len(ok), "correct": correct,
        "accuracy": correct / len(items),
        "latency_p50_s": lat[len(lat) // 2] if lat else None,
        "results_sha256": hashlib.sha256(out.read_bytes()).hexdigest(),
    }
    print(json.dumps(summary), flush=True)
    out.with_suffix(".summary.json").write_text(json.dumps(summary, indent=1))


if __name__ == "__main__":
    main()