noodcon commited on
Commit
5493f13
·
verified ·
1 Parent(s): 23f0411

Upload 3 files

Browse files
Files changed (1) hide show
  1. benchmark.py +295 -158
benchmark.py CHANGED
@@ -1,49 +1,60 @@
1
  #!/usr/bin/env python3
2
  """
3
- Sampling Config Benchmark
4
- =========================
5
  Tìm cấu hình sampling tốt nhất (temperature, top_p, top_k, repetition_penalty)
6
- cho một model, bằng các task có đáp án kiểm chứng tự động (GSM8K, ARC, MMLU)
7
- + đo độ lặp (degeneration). Kết quả có khoảng tin cậy bootstrap để biết
8
- cấu hình nào thực sự hơn, cấu hình nào chỉ "hòa" do nhiễu.
9
 
10
- Chạy với bất kỳ server tương thích OpenAI API (vLLM, SGLang, llama.cpp server, ...):
 
 
 
 
11
 
12
  vllm serve Qwen/Qwen3-8B --port 8000
13
  python benchmark.py --model Qwen/Qwen3-8B --base-url http://localhost:8000/v1
 
 
14
  """
15
  import argparse
16
  import asyncio
 
17
  import itertools
18
  import json
 
19
  import random
20
  import re
 
 
 
 
21
  from pathlib import Path
22
 
23
  import numpy as np
24
  from datasets import load_dataset
25
  from openai import AsyncOpenAI
26
 
27
- # ----------------------------------------------------------------------------
28
- # Search space
29
- # ----------------------------------------------------------------------------
30
  GRID = {
31
  "temperature": [0.0, 0.3, 0.6, 0.8, 1.0, 1.2],
32
  "top_p": [0.8, 0.9, 0.95, 1.0],
33
  "top_k": [0, 20, 40, 100], # 0 = tắt
34
  "repetition_penalty": [1.0, 1.05, 1.1],
35
  }
36
- LETTERS = "ABCD"
 
 
37
 
38
 
 
 
 
39
  def make_configs(mode, n_random, seed):
40
  keys = list(GRID)
41
- full = [dict(zip(keys, v)) for v in itertools.product(*GRID.values())]
42
- # temperature = 0 là greedy: top_p/top_k không có tác dụng -> chỉ giữ biến thể theo rep_p
43
  seen, out = set(), []
44
- for c in full:
45
- if c["temperature"] == 0:
46
- c = {**c, "top_p": 1.0, "top_k": 0}
 
47
  k = json.dumps(c, sort_keys=True)
48
  if k not in seen:
49
  seen.add(k)
@@ -55,86 +66,179 @@ def make_configs(mode, n_random, seed):
55
 
56
 
57
  # ----------------------------------------------------------------------------
58
- # Tasks
59
  # ----------------------------------------------------------------------------
60
- def fmt_mc(question, choices):
61
- opts = "\n".join(f"{LETTERS[i]}. {c}" for i, c in enumerate(choices))
62
- return (
63
- f"{question}\n\n{opts}\n\n"
64
- "Think step by step, then finish with a final line exactly like: Answer: <letter>"
65
- )
66
 
67
 
68
- def load_items(tasks, n_per_task, seed):
69
  rng = random.Random(seed)
70
  items = []
71
 
72
- def take(ds):
73
  idx = list(range(len(ds)))
74
  rng.shuffle(idx)
75
- return idx[:n_per_task]
76
-
77
- if "gsm8k" in tasks:
78
- ds = load_dataset("openai/gsm8k", "main", split="test")
79
- for i in take(ds):
80
- r = ds[i]
81
- gold = r["answer"].split("####")[-1].strip().replace(",", "")
82
- items.append({
83
- "id": f"gsm8k-{i}", "task": "gsm8k", "kind": "num", "gold": gold,
84
- "prompt": r["question"] + "\n\nSolve step by step, then finish with a final line exactly like: Answer: <number>",
85
- })
86
- if "arc" in tasks:
87
- ds = load_dataset("allenai/ai2_arc", "ARC-Challenge", split="test")
88
- for i in take(ds):
89
- r = ds[i]
90
- if len(r["choices"]["text"]) != 4 or r["answerKey"] not in LETTERS:
91
- continue
92
- items.append({
93
- "id": f"arc-{i}", "task": "arc", "kind": "mc", "gold": r["answerKey"],
94
- "prompt": fmt_mc(r["question"], r["choices"]["text"]),
95
- })
96
- if "mmlu" in tasks:
97
- ds = load_dataset("cais/mmlu", "all", split="test")
98
- for i in take(ds):
99
- r = ds[i]
100
- items.append({
101
- "id": f"mmlu-{i}", "task": "mmlu", "kind": "mc", "gold": LETTERS[r["answer"]],
102
- "prompt": fmt_mc(r["question"], r["choices"]),
103
- })
 
 
 
 
 
 
 
 
104
  return items
105
 
106
 
107
  # ----------------------------------------------------------------------------
108
- # Scoring
109
  # ----------------------------------------------------------------------------
110
  def strip_think(t):
111
  t = re.sub(r"<think>.*?</think>", "", t, flags=re.S)
112
  return t.split("</think>")[-1].strip()
113
 
114
 
115
- def score(item, text):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  text = strip_think(text)
117
- if item["kind"] == "mc":
118
- m = re.findall(r"Answer:\s*\**\(?([A-D])\b", text, flags=re.I)
119
- return float(bool(m) and m[-1].upper() == item["gold"])
120
- m = re.findall(r"Answer:\s*\**\$?\s*(-?[\d,]*\.?\d+)", text, flags=re.I)
121
- if not m:
122
- m = re.findall(r"-?[\d,]*\.?\d+", text)
123
- if not m:
124
- return 0.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  try:
126
- return float(abs(float(m[-1].replace(",", "")) - float(item["gold"])) < 1e-4)
127
- except ValueError:
128
- return 0.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
 
130
 
131
  def rep_rate(text, n=4):
132
- """Tỉ lệ n-gram (từ) bị lặp lại. Càng cao càng bị lặp."""
133
  w = text.split()
134
  if len(w) < n + 1:
135
  return 0.0
136
- grams = [tuple(w[i:i + n]) for i in range(len(w) - n + 1)]
137
- return 1 - len(set(grams)) / len(grams)
138
 
139
 
140
  # ----------------------------------------------------------------------------
@@ -147,14 +251,9 @@ async def eval_item(client, args, cfg, item, sem):
147
  for attempt in range(4):
148
  try:
149
  r = await client.chat.completions.create(
150
- model=args.model,
151
- messages=[{"role": "user", "content": item["prompt"]}],
152
- temperature=cfg["temperature"],
153
- top_p=cfg["top_p"],
154
- max_tokens=args.max_tokens,
155
- n=n,
156
- extra_body={"top_k": cfg["top_k"], "repetition_penalty": cfg["repetition_penalty"]},
157
- )
158
  break
159
  except Exception as e: # noqa
160
  last = e
@@ -162,24 +261,35 @@ async def eval_item(client, args, cfg, item, sem):
162
  else:
163
  raise RuntimeError(f"API lỗi: {last}")
164
  texts = [c.message.content or "" for c in r.choices]
165
- return {
166
- "id": item["id"],
167
- "acc": float(np.mean([score(item, t) for t in texts])),
168
- "rep": float(np.mean([rep_rate(strip_think(t)) for t in texts])),
169
- "trunc": float(np.mean([c.finish_reason == "length" for c in r.choices])),
170
- }
171
-
172
-
173
- async def run_all(args, items, configs):
174
- out_path = Path(args.out) / "raw_results.jsonl"
175
- out_path.parent.mkdir(parents=True, exist_ok=True)
176
- done = {}
177
- if out_path.exists():
178
- for line in out_path.read_text().splitlines():
179
- d = json.loads(line)
180
- done[d["key"]] = d
181
-
182
- client = AsyncOpenAI(base_url=args.base_url, api_key=args.api_key, timeout=600)
 
 
 
 
 
 
 
 
 
 
 
183
  sem = asyncio.Semaphore(args.concurrency)
184
  for i, cfg in enumerate(configs, 1):
185
  key = json.dumps(cfg, sort_keys=True)
@@ -188,96 +298,120 @@ async def run_all(args, items, configs):
188
  continue
189
  print(f"[{i}/{len(configs)}] {cfg}")
190
  res = await asyncio.gather(*[eval_item(client, args, cfg, it, sem) for it in items])
191
- rec = {"key": key, "config": cfg, "items": res}
192
  done[key] = rec
193
- with out_path.open("a") as f:
194
  f.write(json.dumps(rec) + "\n")
195
- print(f" acc={np.mean([r['acc'] for r in res]):.4f} rep={np.mean([r['rep'] for r in res]):.4f}")
 
196
  return list(done.values())
197
 
198
 
199
  # ----------------------------------------------------------------------------
200
- # Analysis
201
  # ----------------------------------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
202
  def analyze(args, records, items):
203
  ids = [it["id"] for it in items]
204
- tasks = sorted({it["task"] for it in items})
205
- recs = [r for r in records if all(any(x["id"] == i for x in r["items"]) for i in ids[:1])]
206
- C, N = len(recs), len(ids)
207
- acc = np.zeros((C, N)); rep = np.zeros((C, N)); trunc = np.zeros((C, N))
208
- for c, r in enumerate(recs):
 
 
 
 
209
  m = {x["id"]: x for x in r["items"]}
210
  for j, i in enumerate(ids):
211
  acc[c, j], rep[c, j], trunc[c, j] = m[i]["acc"], m[i]["rep"], m[i]["trunc"]
212
 
213
  rng = np.random.default_rng(args.seed)
214
  B = 2000
215
- boots = np.stack([acc[:, rng.integers(0, N, N)].mean(1) for _ in range(B)], axis=1) # (C,B)
216
- mean = acc.mean(1)
217
- lo, hi = np.percentile(boots, [2.5, 97.5], axis=1)
218
- p_best = np.bincount(boots.argmax(0), minlength=C) / B
219
-
220
- best = int(mean.argmax())
221
- tied = []
222
- for c in range(C):
223
- diff = boots[best] - boots[c]
224
- if c != best and np.percentile(diff, 2.5) <= 0:
225
- tied.append(c)
226
-
227
- order = np.argsort(-mean)
228
- lines = []
229
- lines.append(f"# Kết quả: `{args.model}`\n")
230
- lines.append(f"- Số câu hỏi: **{N}** ({', '.join(tasks)}) | samples/câu: **{args.n_samples}** | max_tokens: {args.max_tokens}")
231
- lines.append(f"- Số cấu hình đã test: **{C}**\n")
232
- b = recs[best]["config"]
233
- lines.append("## 🏆 Cấu hình tốt nhất\n```")
234
- lines.append(f"temp = {b['temperature']}\ntop p = {b['top_p']}\ntop k = {b['top_k']}\nrep p (repetition_penalty) = {b['repetition_penalty']}")
235
- lines.append(f"```\nAccuracy: **{mean[best]:.4f}** (95% CI {lo[best]:.4f} – {hi[best]:.4f}), P(best) = {p_best[best]:.2f}\n")
236
  if tied:
237
- lines.append(f"> ⚠️ Có **{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 (xem cột `Tied`).\n")
238
-
239
- lines.append("## Bảng xếp hạng (top 20)\n")
240
- lines.append("| # | temp | top_p | top_k | rep_p | Acc | 95% CI | P(best) | Rep4 | Trunc | Tied |")
241
- lines.append("|--:|--:|--:|--:|--:|--:|:--|--:|--:|--:|:-:|")
242
- for rank, c in enumerate(order[:20], 1):
243
- g = recs[c]["config"]
244
- t = "✅" if (c == best or c in tied) else ""
245
- lines.append(f"| {rank} | {g['temperature']} | {g['top_p']} | {g['top_k']} | {g['repetition_penalty']} | "
246
- f"{mean[c]:.4f} | {lo[c]:.3f}–{hi[c]:.3f} | {p_best[c]:.2f} | {rep[c].mean():.3f} | {trunc[c].mean():.3f} | {t} |")
247
-
248
- lines.append("\n## Ảnh hưởng trung bình của từng tham số (marginal)\n")
 
 
 
 
 
 
 
249
  for k in GRID:
250
- lines.append(f"**{k}**\n\n| giá trị | Acc TB |\n|--:|--:|")
251
  for v in GRID[k]:
252
- idx = [c for c in range(C) if recs[c]["config"][k] == v]
253
- if idx:
254
- lines.append(f"| {v} | {mean[idx].mean():.4f} |")
255
- lines.append("")
256
-
257
- Path(args.out).mkdir(parents=True, exist_ok=True)
258
- (Path(args.out) / "results.md").write_text("\n".join(lines))
259
- (Path(args.out) / "best_config.json").write_text(json.dumps({
260
- "model": args.model, "best": b, "accuracy": float(mean[best]),
261
- "ci95": [float(lo[best]), float(hi[best])],
262
- "statistically_tied": [recs[c]["config"] for c in tied],
263
- }, indent=2, ensure_ascii=False))
264
- print("\n".join(lines[:12]))
265
- print(f"\nĐã lưu: {args.out}/results.md, best_config.json")
266
 
267
 
268
  # ----------------------------------------------------------------------------
 
 
 
 
269
  def main():
270
  p = argparse.ArgumentParser()
271
  p.add_argument("--model", required=True)
272
  p.add_argument("--base-url", default="http://localhost:8000/v1")
273
  p.add_argument("--api-key", default="EMPTY")
274
- p.add_argument("--tasks", nargs="+", default=["gsm8k", "arc", "mmlu"], choices=["gsm8k", "arc", "mmlu"])
275
- p.add_argument("--n-per-task", type=int, default=200, help="số câu hỏi mỗi task")
276
  p.add_argument("--n-samples", type=int, default=4, help="số lần sample mỗi câu (giảm nhiễu)")
277
- p.add_argument("--max-tokens", type=int, default=1024)
278
  p.add_argument("--concurrency", type=int, default=64)
 
 
 
279
  p.add_argument("--mode", choices=["grid", "random"], default="grid")
280
- p.add_argument("--n-random", type=int, default=40, help="số config nếu mode=random")
281
  p.add_argument("--seed", type=int, default=42)
282
  p.add_argument("--out", default="results")
283
  p.add_argument("--analyze-only", action="store_true")
@@ -285,11 +419,14 @@ def main():
285
 
286
  items = load_items(args.tasks, args.n_per_task, args.seed)
287
  configs = make_configs(args.mode, args.n_random, args.seed)
 
288
  print(f"{len(items)} câu hỏi | {len(configs)} cấu hình")
289
  if args.analyze_only:
290
- recs = [json.loads(l) for l in (Path(args.out) / "raw_results.jsonl").read_text().splitlines()]
291
  else:
292
- recs = asyncio.run(run_all(args, items, configs))
 
 
293
  analyze(args, recs, items)
294
 
295
 
 
1
  #!/usr/bin/env python3
2
  """
3
+ Sampling Config Benchmark (code / fix bug / toán, mức dễ-trung bình)
4
+ ====================================================================
5
  Tìm cấu hình sampling tốt nhất (temperature, top_p, top_k, repetition_penalty)
6
+ cho một model, chấm hoàn toàn tự động:
 
 
7
 
8
+ code : HumanEval + MBPP (chạy unit test)
9
+ fix : HumanEvalFix (sửa code lỗi, chạy unit test)
10
+ math : GSM8K + MATH-500 (chỉ level 1-3)
11
+
12
+ Chạy với server tương thích OpenAI API (vLLM, SGLang, llama.cpp server, ...):
13
 
14
  vllm serve Qwen/Qwen3-8B --port 8000
15
  python benchmark.py --model Qwen/Qwen3-8B --base-url http://localhost:8000/v1
16
+
17
+ CẢNH BÁO: script chạy code do model sinh ra. Hãy chạy trong Docker/VM/máy cô lập.
18
  """
19
  import argparse
20
  import asyncio
21
+ import hashlib
22
  import itertools
23
  import json
24
+ import os
25
  import random
26
  import re
27
+ import signal
28
+ import sys
29
+ import tempfile
30
+ from asyncio.subprocess import DEVNULL
31
  from pathlib import Path
32
 
33
  import numpy as np
34
  from datasets import load_dataset
35
  from openai import AsyncOpenAI
36
 
 
 
 
37
  GRID = {
38
  "temperature": [0.0, 0.3, 0.6, 0.8, 1.0, 1.2],
39
  "top_p": [0.8, 0.9, 0.95, 1.0],
40
  "top_k": [0, 20, 40, 100], # 0 = tắt
41
  "repetition_penalty": [1.0, 1.05, 1.1],
42
  }
43
+ CATS = ["code", "fix", "math"]
44
+ SUBTASKS = {"humaneval": "code", "mbpp": "code", "humanevalfix": "fix", "gsm8k": "math", "math500": "math"}
45
+ EXEC_SEM = None
46
 
47
 
48
+ # ----------------------------------------------------------------------------
49
+ # Configs
50
+ # ----------------------------------------------------------------------------
51
  def make_configs(mode, n_random, seed):
52
  keys = list(GRID)
 
 
53
  seen, out = set(), []
54
+ for v in itertools.product(*GRID.values()):
55
+ c = dict(zip(keys, v))
56
+ if c["temperature"] == 0: # greedy: top_p/top_k vô nghĩa
57
+ c["top_p"], c["top_k"] = 1.0, 0
58
  k = json.dumps(c, sort_keys=True)
59
  if k not in seen:
60
  seen.add(k)
 
66
 
67
 
68
  # ----------------------------------------------------------------------------
69
+ # Datasets
70
  # ----------------------------------------------------------------------------
71
+ CODE_REPLY = "Reply with the complete code in a single ```python code block."
72
+
73
+
74
+ def imports_of(code):
75
+ return "\n".join(l for l in code.splitlines() if re.match(r"^(import|from)\s+\S", l))
 
76
 
77
 
78
+ def load_items(subtasks, n, seed):
79
  rng = random.Random(seed)
80
  items = []
81
 
82
+ def pick(ds):
83
  idx = list(range(len(ds)))
84
  rng.shuffle(idx)
85
+ return [ds[i] for i in idx[:n]]
86
+
87
+ if "humaneval" in subtasks:
88
+ for r in pick(load_dataset("openai/openai_humaneval", split="test")):
89
+ items.append(dict(
90
+ id=f"he-{r['task_id']}", cat="code", task="humaneval", kind="exec", entry=r["entry_point"],
91
+ pre=r["prompt"], post=r["test"] + f"\ncheck({r['entry_point']})",
92
+ prompt=f"Complete the following Python function.\n\n```python\n{r['prompt']}\n```\n\n{CODE_REPLY}"))
93
+ if "mbpp" in subtasks:
94
+ for r in pick(load_dataset("google-research-datasets/mbpp", "sanitized", split="test")):
95
+ m = re.search(r"def\s+(\w+)", r["code"])
96
+ tests = "\n".join(r["test_list"])
97
+ items.append(dict(
98
+ id=f"mbpp-{r['task_id']}", cat="code", task="mbpp", kind="exec", entry=m.group(1) if m else "",
99
+ pre="\n".join(r["test_imports"]), post=tests,
100
+ prompt=f"{r['prompt']}\n\nYour code must pass these tests:\n```python\n{tests}\n```\n\n{CODE_REPLY}"))
101
+ if "humanevalfix" in subtasks:
102
+ for r in pick(load_dataset("bigcode/humanevalpack", "python", split="test")):
103
+ buggy = r["prompt"] + r["buggy_solution"]
104
+ items.append(dict(
105
+ id=f"hef-{r['task_id']}", cat="fix", task="humanevalfix", kind="exec", entry=r["entry_point"],
106
+ pre=imports_of(buggy), post=r["test"] + f"\ncheck({r['entry_point']})",
107
+ prompt=("The following Python code contains a bug and fails its unit tests. "
108
+ f"Find and fix the bug.\n\n```python\n{buggy}\n```\n\n"
109
+ "Reply with the complete fixed code (including any helper functions) in a single ```python code block.")))
110
+ if "gsm8k" in subtasks:
111
+ for r in pick(load_dataset("openai/gsm8k", "main", split="test")):
112
+ items.append(dict(
113
+ id="gsm8k-" + hashlib.md5(r["question"].encode()).hexdigest()[:10], cat="math", task="gsm8k", kind="math",
114
+ gold=r["answer"].split("####")[-1].strip().replace(",", ""),
115
+ prompt=r["question"] + "\n\nSolve step by step. Put the final answer in \\boxed{}."))
116
+ if "math500" in subtasks:
117
+ ds = load_dataset("HuggingFaceH4/MATH-500", split="test").filter(lambda r: r["level"] <= 3)
118
+ for r in pick(ds):
119
+ items.append(dict(
120
+ id=f"math-{r['unique_id']}", cat="math", task="math500", kind="math", gold=r["answer"],
121
+ prompt=r["problem"] + "\n\nSolve step by step. Put the final answer in \\boxed{}."))
122
  return items
123
 
124
 
125
  # ----------------------------------------------------------------------------
126
+ # Scoring: math
127
  # ----------------------------------------------------------------------------
128
  def strip_think(t):
129
  t = re.sub(r"<think>.*?</think>", "", t, flags=re.S)
130
  return t.split("</think>")[-1].strip()
131
 
132
 
133
+ def last_boxed(s):
134
+ i = s.rfind("\\boxed")
135
+ j = s.find("{", i) if i >= 0 else -1
136
+ if j < 0:
137
+ return None
138
+ depth = 0
139
+ for k in range(j, len(s)):
140
+ if s[k] == "{":
141
+ depth += 1
142
+ elif s[k] == "}":
143
+ depth -= 1
144
+ if depth == 0:
145
+ return s[j + 1:k]
146
+ return None
147
+
148
+
149
+ def norm(a):
150
+ a = re.sub(r"\\text\{([^}]*)\}", r"\1", a.strip())
151
+ for t in ["\\left", "\\right", "\\!", "\\,", "\\;", "\\ ", "$", "\\%", "%", "^\\circ", "^{\\circ}", "\\displaystyle"]:
152
+ a = a.replace(t, "")
153
+ a = a.replace("dfrac", "frac").replace("tfrac", "frac").replace(" ", "").rstrip(".")
154
+ if re.fullmatch(r"-?[\d,]+(\.\d+)?", a):
155
+ a = a.replace(",", "")
156
+ return a
157
+
158
+
159
+ def to_num(a):
160
+ try:
161
+ m = re.fullmatch(r"(-?)\\frac\{(-?[\d.]+)\}\{(-?[\d.]+)\}", a)
162
+ if m:
163
+ return (-1 if m[1] else 1) * float(m[2]) / float(m[3])
164
+ m = re.fullmatch(r"(-?[\d.]+)/(-?[\d.]+)", a)
165
+ if m:
166
+ return float(m[1]) / float(m[2])
167
+ return float(a)
168
+ except Exception:
169
+ return None
170
+
171
+
172
+ def math_correct(item, text):
173
  text = strip_think(text)
174
+ pred = last_boxed(text)
175
+ if pred is None and item["task"] == "gsm8k":
176
+ m = re.findall(r"-?\d[\d,]*\.?\d*", text)
177
+ pred = m[-1] if m else None
178
+ if pred is None:
179
+ return False
180
+ p, g = norm(pred), norm(item["gold"])
181
+ if p == g:
182
+ return True
183
+ x, y = to_num(p), to_num(g)
184
+ return x is not None and y is not None and abs(x - y) < 1e-6
185
+
186
+
187
+ # ----------------------------------------------------------------------------
188
+ # Scoring: code execution
189
+ # ----------------------------------------------------------------------------
190
+ def extract_code(text, entry):
191
+ text = strip_think(text)
192
+ blocks = re.findall(r"```(?:python|py|Python)?[ \t]*\n(.*?)```", text, flags=re.S)
193
+ if not blocks:
194
+ m = re.search(r"```(?:python|py|Python)?[ \t]*\n(.*)$", text, flags=re.S) # block bị cắt
195
+ return m.group(1) if m else text
196
+ cands = [b for b in blocks if entry and f"def {entry}" in b]
197
+ return (cands or blocks)[-1]
198
+
199
+
200
+ def _limits():
201
  try:
202
+ import resource
203
+ resource.setrlimit(resource.RLIMIT_AS, (2 << 30, 2 << 30))
204
+ except Exception:
205
+ pass
206
+
207
+
208
+ async def run_python(program, timeout):
209
+ with tempfile.TemporaryDirectory() as d:
210
+ f = Path(d) / "main.py"
211
+ f.write_text(program, encoding="utf-8", errors="replace")
212
+ kw = {} if os.name == "nt" else {"preexec_fn": _limits, "start_new_session": True}
213
+ p = await asyncio.create_subprocess_exec(sys.executable, "-I", str(f), cwd=d,
214
+ stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL, **kw)
215
+ try:
216
+ await asyncio.wait_for(p.wait(), timeout)
217
+ return p.returncode == 0
218
+ except asyncio.TimeoutError:
219
+ try:
220
+ os.killpg(p.pid, signal.SIGKILL) if os.name != "nt" else p.kill()
221
+ except Exception:
222
+ pass
223
+ await p.wait()
224
+ return False
225
+
226
+
227
+ async def score(item, text, timeout):
228
+ if item["kind"] == "math":
229
+ return float(math_correct(item, text))
230
+ code = extract_code(text, item["entry"])
231
+ program = f"{item['pre']}\n\n{code}\n\n{item['post']}\n"
232
+ async with EXEC_SEM:
233
+ return float(await run_python(program, timeout))
234
 
235
 
236
  def rep_rate(text, n=4):
 
237
  w = text.split()
238
  if len(w) < n + 1:
239
  return 0.0
240
+ g = [tuple(w[i:i + n]) for i in range(len(w) - n + 1)]
241
+ return 1 - len(set(g)) / len(g)
242
 
243
 
244
  # ----------------------------------------------------------------------------
 
251
  for attempt in range(4):
252
  try:
253
  r = await client.chat.completions.create(
254
+ model=args.model, messages=[{"role": "user", "content": item["prompt"]}],
255
+ temperature=cfg["temperature"], top_p=cfg["top_p"], max_tokens=args.max_tokens, n=n,
256
+ extra_body={"top_k": cfg["top_k"], "repetition_penalty": cfg["repetition_penalty"]})
 
 
 
 
 
257
  break
258
  except Exception as e: # noqa
259
  last = e
 
261
  else:
262
  raise RuntimeError(f"API lỗi: {last}")
263
  texts = [c.message.content or "" for c in r.choices]
264
+ scores = await asyncio.gather(*[score(item, t, args.exec_timeout) for t in texts])
265
+ return {"id": item["id"], "acc": float(np.mean(scores)),
266
+ "rep": float(np.mean([rep_rate(strip_think(t)) for t in texts])),
267
+ "trunc": float(np.mean([c.finish_reason == "length" for c in r.choices]))}
268
+
269
+
270
+ def signature(args, items):
271
+ return hashlib.md5(json.dumps([[i["id"] for i in items], args.n_samples, args.max_tokens,
272
+ args.model, args.exec_timeout]).encode()).hexdigest()
273
+
274
+
275
+ def load_records(path, sig):
276
+ if not path.exists():
277
+ return {}
278
+ out = {}
279
+ for line in path.read_text().splitlines():
280
+ d = json.loads(line)
281
+ if d.get("sig") == sig:
282
+ out[d["key"]] = d
283
+ return out
284
+
285
+
286
+ async def run_all(args, items, configs, sig):
287
+ global EXEC_SEM
288
+ EXEC_SEM = asyncio.Semaphore(args.exec_workers)
289
+ path = Path(args.out) / "raw_results.jsonl"
290
+ path.parent.mkdir(parents=True, exist_ok=True)
291
+ done = load_records(path, sig)
292
+ client = AsyncOpenAI(base_url=args.base_url, api_key=args.api_key, timeout=900)
293
  sem = asyncio.Semaphore(args.concurrency)
294
  for i, cfg in enumerate(configs, 1):
295
  key = json.dumps(cfg, sort_keys=True)
 
298
  continue
299
  print(f"[{i}/{len(configs)}] {cfg}")
300
  res = await asyncio.gather(*[eval_item(client, args, cfg, it, sem) for it in items])
301
+ rec = {"key": key, "sig": sig, "config": cfg, "items": res}
302
  done[key] = rec
303
+ with path.open("a") as f:
304
  f.write(json.dumps(rec) + "\n")
305
+ 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}}
306
+ print(" " + " ".join(f"{c}={v:.3f}" for c, v in sorted(by.items())))
307
  return list(done.values())
308
 
309
 
310
  # ----------------------------------------------------------------------------
311
+ # Analysis (bootstrap phân tầng theo category)
312
  # ----------------------------------------------------------------------------
313
+ def summarize(boots, mean):
314
+ lo, hi = np.percentile(boots, [2.5, 97.5], axis=1)
315
+ p_best = np.bincount(boots.argmax(0), minlength=len(mean)) / boots.shape[1]
316
+ best = int(mean.argmax())
317
+ tied = [c for c in range(len(mean)) if c != best and np.percentile(boots[best] - boots[c], 2.5) <= 0]
318
+ return lo, hi, p_best, best, tied
319
+
320
+
321
+ def cfg_str(c):
322
+ return f"temp={c['temperature']}, top_p={c['top_p']}, top_k={c['top_k']}, rep_p={c['repetition_penalty']}"
323
+
324
+
325
  def analyze(args, records, items):
326
  ids = [it["id"] for it in items]
327
+ cats = [c for c in CATS if any(it["cat"] == c for it in items)]
328
+ idx = {c: np.array([j for j, it in enumerate(items) if it["cat"] == c]) for c in cats}
329
+ w = {c: float(args.weights.get(c, 1.0)) for c in cats}
330
+ tw = sum(w.values())
331
+ w = {c: v / tw for c, v in w.items()}
332
+
333
+ C, N = len(records), len(ids)
334
+ acc, rep, trunc = np.zeros((C, N)), np.zeros((C, N)), np.zeros((C, N))
335
+ for c, r in enumerate(records):
336
  m = {x["id"]: x for x in r["items"]}
337
  for j, i in enumerate(ids):
338
  acc[c, j], rep[c, j], trunc[c, j] = m[i]["acc"], m[i]["rep"], m[i]["trunc"]
339
 
340
  rng = np.random.default_rng(args.seed)
341
  B = 2000
342
+ cboot = {c: np.stack([acc[:, rng.choice(idx[c], len(idx[c]))].mean(1) for _ in range(B)], axis=1) for c in cats}
343
+ cmean = {c: acc[:, idx[c]].mean(1) for c in cats}
344
+ oboot = sum(w[c] * cboot[c] for c in cats)
345
+ omean = sum(w[c] * cmean[c] for c in cats)
346
+
347
+ lo, hi, pb, best, tied = summarize(oboot, omean)
348
+ b = records[best]["config"]
349
+ L = [f"# Kết quả: `{args.model}`\n",
350
+ f"- Câu hỏi: **{N}** | task: {', '.join(args.tasks)} | samples/câu: **{args.n_samples}** | max_tokens: {args.max_tokens}",
351
+ f"- Trọng số category: " + ", ".join(f"{c}={w[c]:.2f}" for c in cats),
352
+ f"- Số cấu hình đã test: **{C}**\n",
353
+ "## 🏆 Cấu hình tốt nhất (tổng hợp)\n```",
354
+ f"temp = {b['temperature']}\ntop p = {b['top_p']}\ntop k = {b['top_k']}\nrep p (repetition_penalty) = {b['repetition_penalty']}",
355
+ f"```\nScore: **{omean[best]:.4f}** (95% CI {lo[best]:.4f} – {hi[best]:.4f}), P(best) = {pb[best]:.2f}\n"]
 
 
 
 
 
 
 
356
  if tied:
357
+ 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")
358
+
359
+ 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|:--|:--|--:|:--|--:|")
360
+ per_cat = {}
361
+ for c in cats:
362
+ l2, h2, _, b2, t2 = summarize(cboot[c], cmean[c])
363
+ per_cat[c] = {"config": records[b2]["config"], "accuracy": float(cmean[c][b2]), "ci95": [float(l2[b2]), float(h2[b2])]}
364
+ L.append(f"| {c} | {cfg_str(records[b2]['config'])} | {cmean[c][b2]:.4f} | {l2[b2]:.3f}–{h2[b2]:.3f} | {len(t2)} |")
365
+
366
+ L.append("\n## Bảng xếp hạng (top 20)\n")
367
+ L.append("| # | temp | top_p | top_k | rep_p | Score | 95% CI | P(best) | " + " | ".join(cats) + " | Rep4 | Trunc | Tied |")
368
+ L.append("|--:|--:|--:|--:|--:|--:|:--|--:|" + "--:|" * len(cats) + "--:|--:|:-:|")
369
+ for rank, c in enumerate(np.argsort(-omean)[:20], 1):
370
+ g = records[c]["config"]
371
+ L.append(f"| {rank} | {g['temperature']} | {g['top_p']} | {g['top_k']} | {g['repetition_penalty']} | {omean[c]:.4f} | "
372
+ f"{lo[c]:.3f}–{hi[c]:.3f} | {pb[c]:.2f} | " + " | ".join(f"{cmean[k][c]:.3f}" for k in cats) +
373
+ f" | {rep[c].mean():.3f} | {trunc[c].mean():.3f} | {'✅' if c == best or c in tied else ''} |")
374
+
375
+ L.append("\n## Ảnh hưởng trung bình của từng tham số\n")
376
  for k in GRID:
377
+ L.append(f"**{k}**\n\n| giá trị | Score TB |\n|--:|--:|")
378
  for v in GRID[k]:
379
+ ix = [c for c in range(C) if records[c]["config"][k] == v]
380
+ if ix:
381
+ L.append(f"| {v} | {omean[ix].mean():.4f} |")
382
+ L.append("")
383
+
384
+ out = Path(args.out)
385
+ out.mkdir(parents=True, exist_ok=True)
386
+ (out / "results.md").write_text("\n".join(L))
387
+ (out / "best_config.json").write_text(json.dumps({
388
+ "model": args.model, "best_overall": b, "score": float(omean[best]), "ci95": [float(lo[best]), float(hi[best])],
389
+ "best_per_category": per_cat, "statistically_tied": [records[c]["config"] for c in tied]},
390
+ indent=2, ensure_ascii=False))
391
+ print("\n".join(L[:22]))
392
+ print(f"\nĐã lưu: {out}/results.md, best_config.json")
393
 
394
 
395
  # ----------------------------------------------------------------------------
396
+ def parse_weights(s):
397
+ return {k: float(v) for k, v in (p.split("=") for p in s.split(","))} if s else {}
398
+
399
+
400
  def main():
401
  p = argparse.ArgumentParser()
402
  p.add_argument("--model", required=True)
403
  p.add_argument("--base-url", default="http://localhost:8000/v1")
404
  p.add_argument("--api-key", default="EMPTY")
405
+ p.add_argument("--tasks", nargs="+", default=list(SUBTASKS), choices=list(SUBTASKS))
406
+ p.add_argument("--n-per-task", type=int, default=80, help="số câu mỗi task")
407
  p.add_argument("--n-samples", type=int, default=4, help="số lần sample mỗi câu (giảm nhiễu)")
408
+ p.add_argument("--max-tokens", type=int, default=2048)
409
  p.add_argument("--concurrency", type=int, default=64)
410
+ p.add_argument("--exec-workers", type=int, default=8, help="số tiến trình chạy code song song")
411
+ p.add_argument("--exec-timeout", type=float, default=10.0)
412
+ p.add_argument("--weights", type=parse_weights, default={}, help='vd "code=1,fix=1,math=2"')
413
  p.add_argument("--mode", choices=["grid", "random"], default="grid")
414
+ p.add_argument("--n-random", type=int, default=40)
415
  p.add_argument("--seed", type=int, default=42)
416
  p.add_argument("--out", default="results")
417
  p.add_argument("--analyze-only", action="store_true")
 
419
 
420
  items = load_items(args.tasks, args.n_per_task, args.seed)
421
  configs = make_configs(args.mode, args.n_random, args.seed)
422
+ sig = signature(args, items)
423
  print(f"{len(items)} câu hỏi | {len(configs)} cấu hình")
424
  if args.analyze_only:
425
+ recs = list(load_records(Path(args.out) / "raw_results.jsonl", sig).values())
426
  else:
427
+ recs = asyncio.run(run_all(args, items, configs, sig))
428
+ if not recs:
429
+ sys.exit("Chưa có kết quả nào khớp với tham số hiện tại.")
430
  analyze(args, recs, items)
431
 
432