File size: 18,590 Bytes
dbd598d
 
5493f13
 
dbd598d
5493f13
dbd598d
5493f13
 
 
 
 
dbd598d
 
 
5493f13
 
dbd598d
 
 
5493f13
dbd598d
 
5493f13
dbd598d
 
5493f13
 
 
 
dbd598d
 
 
 
 
 
 
 
 
 
 
 
5493f13
 
 
dbd598d
 
5493f13
 
 
dbd598d
 
 
5493f13
 
 
 
dbd598d
 
 
 
 
 
 
 
 
 
 
5493f13
dbd598d
5493f13
 
 
 
 
dbd598d
 
5493f13
dbd598d
 
 
5493f13
dbd598d
 
5493f13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbd598d
 
 
 
5493f13
dbd598d
 
 
 
 
 
5493f13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbd598d
5493f13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbd598d
5493f13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbd598d
 
 
 
 
 
5493f13
 
dbd598d
 
 
 
 
 
 
 
 
 
 
 
5493f13
 
 
dbd598d
 
 
 
 
 
 
5493f13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbd598d
 
 
 
 
 
 
 
5493f13
dbd598d
5493f13
dbd598d
5493f13
 
dbd598d
 
 
 
5493f13
dbd598d
5493f13
 
 
 
 
 
 
 
 
 
 
 
dbd598d
 
5493f13
 
 
 
 
 
 
 
 
dbd598d
 
 
 
 
 
5493f13
 
 
 
 
 
 
 
 
 
 
 
 
 
dbd598d
5493f13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbd598d
5493f13
dbd598d
5493f13
 
 
 
 
 
 
 
 
 
 
 
 
 
dbd598d
 
 
5493f13
 
 
 
dbd598d
 
 
 
 
5493f13
 
dbd598d
5493f13
dbd598d
5493f13
 
 
dbd598d
5493f13
dbd598d
 
 
 
 
 
 
5493f13
dbd598d
 
5493f13
dbd598d
5493f13
 
 
dbd598d
 
 
 
 
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
#!/usr/bin/env python3
"""
Sampling Config Benchmark (code / fix bug / toán, mức dễ-trung bình)
====================================================================
Tìm cấu hình sampling tốt nhất (temperature, top_p, top_k, repetition_penalty)
cho một model, chấm hoàn toàn tự động:

  code : HumanEval + MBPP (chạy unit test)
  fix  : HumanEvalFix (sửa code lỗi, chạy unit test)
  math : GSM8K + MATH-500 (chỉ level 1-3)

Chạy với server tương thích OpenAI API (vLLM, SGLang, llama.cpp server, ...):

  vllm serve Qwen/Qwen3-8B --port 8000
  python benchmark.py --model Qwen/Qwen3-8B --base-url http://localhost:8000/v1

CẢNH BÁO: script chạy code do model sinh ra. Hãy chạy trong Docker/VM/máy cô lập.
"""
import argparse
import asyncio
import hashlib
import itertools
import json
import os
import random
import re
import signal
import sys
import tempfile
from asyncio.subprocess import DEVNULL
from pathlib import Path

import numpy as np
from datasets import load_dataset
from openai import AsyncOpenAI

GRID = {
    "temperature": [0.0, 0.3, 0.6, 0.8, 1.0, 1.2],
    "top_p": [0.8, 0.9, 0.95, 1.0],
    "top_k": [0, 20, 40, 100],  # 0 = tắt
    "repetition_penalty": [1.0, 1.05, 1.1],
}
CATS = ["code", "fix", "math"]
SUBTASKS = {"humaneval": "code", "mbpp": "code", "humanevalfix": "fix", "gsm8k": "math", "math500": "math"}
EXEC_SEM = None


# ----------------------------------------------------------------------------
# Configs
# ----------------------------------------------------------------------------
def make_configs(mode, n_random, seed):
    keys = list(GRID)
    seen, out = set(), []
    for v in itertools.product(*GRID.values()):
        c = dict(zip(keys, v))
        if c["temperature"] == 0:  # greedy: top_p/top_k vô nghĩa
            c["top_p"], c["top_k"] = 1.0, 0
        k = json.dumps(c, sort_keys=True)
        if k not in seen:
            seen.add(k)
            out.append(c)
    if mode == "random":
        random.Random(seed).shuffle(out)
        out = out[:n_random]
    return out


# ----------------------------------------------------------------------------
# Datasets
# ----------------------------------------------------------------------------
CODE_REPLY = "Reply with the complete code in a single ```python code block."


def imports_of(code):
    return "\n".join(l for l in code.splitlines() if re.match(r"^(import|from)\s+\S", l))


def load_items(subtasks, n, seed):
    rng = random.Random(seed)
    items = []

    def pick(ds):
        idx = list(range(len(ds)))
        rng.shuffle(idx)
        return [ds[i] for i in idx[:n]]

    if "humaneval" in subtasks:
        for r in pick(load_dataset("openai/openai_humaneval", split="test")):
            items.append(dict(
                id=f"he-{r['task_id']}", cat="code", task="humaneval", kind="exec", entry=r["entry_point"],
                pre=r["prompt"], post=r["test"] + f"\ncheck({r['entry_point']})",
                prompt=f"Complete the following Python function.\n\n```python\n{r['prompt']}\n```\n\n{CODE_REPLY}"))
    if "mbpp" in subtasks:
        for r in pick(load_dataset("google-research-datasets/mbpp", "sanitized", split="test")):
            m = re.search(r"def\s+(\w+)", r["code"])
            tests = "\n".join(r["test_list"])
            items.append(dict(
                id=f"mbpp-{r['task_id']}", cat="code", task="mbpp", kind="exec", entry=m.group(1) if m else "",
                pre="\n".join(r["test_imports"]), post=tests,
                prompt=f"{r['prompt']}\n\nYour code must pass these tests:\n```python\n{tests}\n```\n\n{CODE_REPLY}"))
    if "humanevalfix" in subtasks:
        for r in pick(load_dataset("bigcode/humanevalpack", "python", split="test")):
            buggy = r["prompt"] + r["buggy_solution"]
            items.append(dict(
                id=f"hef-{r['task_id']}", cat="fix", task="humanevalfix", kind="exec", entry=r["entry_point"],
                pre=imports_of(buggy), post=r["test"] + f"\ncheck({r['entry_point']})",
                prompt=("The following Python code contains a bug and fails its unit tests. "
                        f"Find and fix the bug.\n\n```python\n{buggy}\n```\n\n"
                        "Reply with the complete fixed code (including any helper functions) in a single ```python code block.")))
    if "gsm8k" in subtasks:
        for r in pick(load_dataset("openai/gsm8k", "main", split="test")):
            items.append(dict(
                id="gsm8k-" + hashlib.md5(r["question"].encode()).hexdigest()[:10], cat="math", task="gsm8k", kind="math",
                gold=r["answer"].split("####")[-1].strip().replace(",", ""),
                prompt=r["question"] + "\n\nSolve step by step. Put the final answer in \\boxed{}."))
    if "math500" in subtasks:
        ds = load_dataset("HuggingFaceH4/MATH-500", split="test").filter(lambda r: r["level"] <= 3)
        for r in pick(ds):
            items.append(dict(
                id=f"math-{r['unique_id']}", cat="math", task="math500", kind="math", gold=r["answer"],
                prompt=r["problem"] + "\n\nSolve step by step. Put the final answer in \\boxed{}."))
    return items


# ----------------------------------------------------------------------------
# Scoring: math
# ----------------------------------------------------------------------------
def strip_think(t):
    t = re.sub(r"<think>.*?</think>", "", t, flags=re.S)
    return t.split("</think>")[-1].strip()


def last_boxed(s):
    i = s.rfind("\\boxed")
    j = s.find("{", i) if i >= 0 else -1
    if j < 0:
        return None
    depth = 0
    for k in range(j, len(s)):
        if s[k] == "{":
            depth += 1
        elif s[k] == "}":
            depth -= 1
            if depth == 0:
                return s[j + 1:k]
    return None


def norm(a):
    a = re.sub(r"\\text\{([^}]*)\}", r"\1", a.strip())
    for t in ["\\left", "\\right", "\\!", "\\,", "\\;", "\\ ", "$", "\\%", "%", "^\\circ", "^{\\circ}", "\\displaystyle"]:
        a = a.replace(t, "")
    a = a.replace("dfrac", "frac").replace("tfrac", "frac").replace(" ", "").rstrip(".")
    if re.fullmatch(r"-?[\d,]+(\.\d+)?", a):
        a = a.replace(",", "")
    return a


def to_num(a):
    try:
        m = re.fullmatch(r"(-?)\\frac\{(-?[\d.]+)\}\{(-?[\d.]+)\}", a)
        if m:
            return (-1 if m[1] else 1) * float(m[2]) / float(m[3])
        m = re.fullmatch(r"(-?[\d.]+)/(-?[\d.]+)", a)
        if m:
            return float(m[1]) / float(m[2])
        return float(a)
    except Exception:
        return None


def math_correct(item, text):
    text = strip_think(text)
    pred = last_boxed(text)
    if pred is None and item["task"] == "gsm8k":
        m = re.findall(r"-?\d[\d,]*\.?\d*", text)
        pred = m[-1] if m else None
    if pred is None:
        return False
    p, g = norm(pred), norm(item["gold"])
    if p == g:
        return True
    x, y = to_num(p), to_num(g)
    return x is not None and y is not None and abs(x - y) < 1e-6


# ----------------------------------------------------------------------------
# Scoring: code execution
# ----------------------------------------------------------------------------
def extract_code(text, entry):
    text = strip_think(text)
    blocks = re.findall(r"```(?:python|py|Python)?[ \t]*\n(.*?)```", text, flags=re.S)
    if not blocks:
        m = re.search(r"```(?:python|py|Python)?[ \t]*\n(.*)$", text, flags=re.S)  # block bị cắt
        return m.group(1) if m else text
    cands = [b for b in blocks if entry and f"def {entry}" in b]
    return (cands or blocks)[-1]


def _limits():
    try:
        import resource
        resource.setrlimit(resource.RLIMIT_AS, (2 << 30, 2 << 30))
    except Exception:
        pass


async def run_python(program, timeout):
    with tempfile.TemporaryDirectory() as d:
        f = Path(d) / "main.py"
        f.write_text(program, encoding="utf-8", errors="replace")
        kw = {} if os.name == "nt" else {"preexec_fn": _limits, "start_new_session": True}
        p = await asyncio.create_subprocess_exec(sys.executable, "-I", str(f), cwd=d,
                                                 stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL, **kw)
        try:
            await asyncio.wait_for(p.wait(), timeout)
            return p.returncode == 0
        except asyncio.TimeoutError:
            try:
                os.killpg(p.pid, signal.SIGKILL) if os.name != "nt" else p.kill()
            except Exception:
                pass
            await p.wait()
            return False


async def score(item, text, timeout):
    if item["kind"] == "math":
        return float(math_correct(item, text))
    code = extract_code(text, item["entry"])
    program = f"{item['pre']}\n\n{code}\n\n{item['post']}\n"
    async with EXEC_SEM:
        return float(await run_python(program, timeout))


def rep_rate(text, n=4):
    w = text.split()
    if len(w) < n + 1:
        return 0.0
    g = [tuple(w[i:i + n]) for i in range(len(w) - n + 1)]
    return 1 - len(set(g)) / len(g)


# ----------------------------------------------------------------------------
# Runner
# ----------------------------------------------------------------------------
async def eval_item(client, args, cfg, item, sem):
    n = 1 if cfg["temperature"] == 0 else args.n_samples
    last = None
    async with sem:
        for attempt in range(4):
            try:
                r = await client.chat.completions.create(
                    model=args.model, messages=[{"role": "user", "content": item["prompt"]}],
                    temperature=cfg["temperature"], top_p=cfg["top_p"], max_tokens=args.max_tokens, n=n,
                    extra_body={"top_k": cfg["top_k"], "repetition_penalty": cfg["repetition_penalty"]})
                break
            except Exception as e:  # noqa
                last = e
                await asyncio.sleep(2 ** attempt)
        else:
            raise RuntimeError(f"API lỗi: {last}")
    texts = [c.message.content or "" for c in r.choices]
    scores = await asyncio.gather(*[score(item, t, args.exec_timeout) for t in texts])
    return {"id": item["id"], "acc": float(np.mean(scores)),
            "rep": float(np.mean([rep_rate(strip_think(t)) for t in texts])),
            "trunc": float(np.mean([c.finish_reason == "length" for c in r.choices]))}


def signature(args, items):
    return hashlib.md5(json.dumps([[i["id"] for i in items], args.n_samples, args.max_tokens,
                                   args.model, args.exec_timeout]).encode()).hexdigest()


def load_records(path, sig):
    if not path.exists():
        return {}
    out = {}
    for line in path.read_text().splitlines():
        d = json.loads(line)
        if d.get("sig") == sig:
            out[d["key"]] = d
    return out


async def run_all(args, items, configs, sig):
    global EXEC_SEM
    EXEC_SEM = asyncio.Semaphore(args.exec_workers)
    path = Path(args.out) / "raw_results.jsonl"
    path.parent.mkdir(parents=True, exist_ok=True)
    done = load_records(path, sig)
    client = AsyncOpenAI(base_url=args.base_url, api_key=args.api_key, timeout=900)
    sem = asyncio.Semaphore(args.concurrency)
    for i, cfg in enumerate(configs, 1):
        key = json.dumps(cfg, sort_keys=True)
        if key in done:
            print(f"[{i}/{len(configs)}] bỏ qua (đã có): {cfg}")
            continue
        print(f"[{i}/{len(configs)}] {cfg}")
        res = await asyncio.gather(*[eval_item(client, args, cfg, it, sem) for it in items])
        rec = {"key": key, "sig": sig, "config": cfg, "items": res}
        done[key] = rec
        with path.open("a") as f:
            f.write(json.dumps(rec) + "\n")
        by = {c: np.mean([r["acc"] for r, it in zip(res, items) if it["cat"] == c]) for c in {it["cat"] for it in items}}
        print("    " + "  ".join(f"{c}={v:.3f}" for c, v in sorted(by.items())))
    return list(done.values())


# ----------------------------------------------------------------------------
# Analysis (bootstrap phân tầng theo category)
# ----------------------------------------------------------------------------
def summarize(boots, mean):
    lo, hi = np.percentile(boots, [2.5, 97.5], axis=1)
    p_best = np.bincount(boots.argmax(0), minlength=len(mean)) / boots.shape[1]
    best = int(mean.argmax())
    tied = [c for c in range(len(mean)) if c != best and np.percentile(boots[best] - boots[c], 2.5) <= 0]
    return lo, hi, p_best, best, tied


def cfg_str(c):
    return f"temp={c['temperature']}, top_p={c['top_p']}, top_k={c['top_k']}, rep_p={c['repetition_penalty']}"


def analyze(args, records, items):
    ids = [it["id"] for it in items]
    cats = [c for c in CATS if any(it["cat"] == c for it in items)]
    idx = {c: np.array([j for j, it in enumerate(items) if it["cat"] == c]) for c in cats}
    w = {c: float(args.weights.get(c, 1.0)) for c in cats}
    tw = sum(w.values())
    w = {c: v / tw for c, v in w.items()}

    C, N = len(records), len(ids)
    acc, rep, trunc = np.zeros((C, N)), np.zeros((C, N)), np.zeros((C, N))
    for c, r in enumerate(records):
        m = {x["id"]: x for x in r["items"]}
        for j, i in enumerate(ids):
            acc[c, j], rep[c, j], trunc[c, j] = m[i]["acc"], m[i]["rep"], m[i]["trunc"]

    rng = np.random.default_rng(args.seed)
    B = 2000
    cboot = {c: np.stack([acc[:, rng.choice(idx[c], len(idx[c]))].mean(1) for _ in range(B)], axis=1) for c in cats}
    cmean = {c: acc[:, idx[c]].mean(1) for c in cats}
    oboot = sum(w[c] * cboot[c] for c in cats)
    omean = sum(w[c] * cmean[c] for c in cats)

    lo, hi, pb, best, tied = summarize(oboot, omean)
    b = records[best]["config"]
    L = [f"# Kết quả: `{args.model}`\n",
         f"- Câu hỏi: **{N}** | task: {', '.join(args.tasks)} | samples/câu: **{args.n_samples}** | max_tokens: {args.max_tokens}",
         f"- Trọng số category: " + ", ".join(f"{c}={w[c]:.2f}" for c in cats),
         f"- Số cấu hình đã test: **{C}**\n",
         "## 🏆 Cấu hình tốt nhất (tổng hợp)\n```",
         f"temp = {b['temperature']}\ntop p = {b['top_p']}\ntop k = {b['top_k']}\nrep p (repetition_penalty) = {b['repetition_penalty']}",
         f"```\nScore: **{omean[best]:.4f}** (95% CI {lo[best]:.4f} – {hi[best]:.4f}), P(best) = {pb[best]:.2f}\n"]
    if tied:
        L.append(f"> ⚠️ **{len(tied)}** cấu hình khác không khác biệt có ý nghĩa thống kê so với cấu hình này (cột `Tied`).\n")

    L.append("## Cấu hình tốt nhất cho từng loại\n\n| Loại | Cấu hình | Acc | 95% CI | Số cấu hình hòa |\n|:--|:--|--:|:--|--:|")
    per_cat = {}
    for c in cats:
        l2, h2, _, b2, t2 = summarize(cboot[c], cmean[c])
        per_cat[c] = {"config": records[b2]["config"], "accuracy": float(cmean[c][b2]), "ci95": [float(l2[b2]), float(h2[b2])]}
        L.append(f"| {c} | {cfg_str(records[b2]['config'])} | {cmean[c][b2]:.4f} | {l2[b2]:.3f}–{h2[b2]:.3f} | {len(t2)} |")

    L.append("\n## Bảng xếp hạng (top 20)\n")
    L.append("| # | temp | top_p | top_k | rep_p | Score | 95% CI | P(best) | " + " | ".join(cats) + " | Rep4 | Trunc | Tied |")
    L.append("|--:|--:|--:|--:|--:|--:|:--|--:|" + "--:|" * len(cats) + "--:|--:|:-:|")
    for rank, c in enumerate(np.argsort(-omean)[:20], 1):
        g = records[c]["config"]
        L.append(f"| {rank} | {g['temperature']} | {g['top_p']} | {g['top_k']} | {g['repetition_penalty']} | {omean[c]:.4f} | "
                 f"{lo[c]:.3f}–{hi[c]:.3f} | {pb[c]:.2f} | " + " | ".join(f"{cmean[k][c]:.3f}" for k in cats) +
                 f" | {rep[c].mean():.3f} | {trunc[c].mean():.3f} | {'✅' if c == best or c in tied else ''} |")

    L.append("\n## Ảnh hưởng trung bình của từng tham số\n")
    for k in GRID:
        L.append(f"**{k}**\n\n| giá trị | Score TB |\n|--:|--:|")
        for v in GRID[k]:
            ix = [c for c in range(C) if records[c]["config"][k] == v]
            if ix:
                L.append(f"| {v} | {omean[ix].mean():.4f} |")
        L.append("")

    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    (out / "results.md").write_text("\n".join(L))
    (out / "best_config.json").write_text(json.dumps({
        "model": args.model, "best_overall": b, "score": float(omean[best]), "ci95": [float(lo[best]), float(hi[best])],
        "best_per_category": per_cat, "statistically_tied": [records[c]["config"] for c in tied]},
        indent=2, ensure_ascii=False))
    print("\n".join(L[:22]))
    print(f"\nĐã lưu: {out}/results.md, best_config.json")


# ----------------------------------------------------------------------------
def parse_weights(s):
    return {k: float(v) for k, v in (p.split("=") for p in s.split(","))} if s else {}


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--model", required=True)
    p.add_argument("--base-url", default="http://localhost:8000/v1")
    p.add_argument("--api-key", default="EMPTY")
    p.add_argument("--tasks", nargs="+", default=list(SUBTASKS), choices=list(SUBTASKS))
    p.add_argument("--n-per-task", type=int, default=80, help="số câu mỗi task")
    p.add_argument("--n-samples", type=int, default=4, help="số lần sample mỗi câu (giảm nhiễu)")
    p.add_argument("--max-tokens", type=int, default=2048)
    p.add_argument("--concurrency", type=int, default=64)
    p.add_argument("--exec-workers", type=int, default=8, help="số tiến trình chạy code song song")
    p.add_argument("--exec-timeout", type=float, default=10.0)
    p.add_argument("--weights", type=parse_weights, default={}, help='vd "code=1,fix=1,math=2"')
    p.add_argument("--mode", choices=["grid", "random"], default="grid")
    p.add_argument("--n-random", type=int, default=40)
    p.add_argument("--seed", type=int, default=42)
    p.add_argument("--out", default="results")
    p.add_argument("--analyze-only", action="store_true")
    args = p.parse_args()

    items = load_items(args.tasks, args.n_per_task, args.seed)
    configs = make_configs(args.mode, args.n_random, args.seed)
    sig = signature(args, items)
    print(f"{len(items)} câu hỏi | {len(configs)} cấu hình")
    if args.analyze_only:
        recs = list(load_records(Path(args.out) / "raw_results.jsonl", sig).values())
    else:
        recs = asyncio.run(run_all(args, items, configs, sig))
    if not recs:
        sys.exit("Chưa có kết quả nào khớp với tham số hiện tại.")
    analyze(args, recs, items)


if __name__ == "__main__":
    main()