Upload 3 files
Browse files12343456786789101110121314151617181920212223242526272829303132333435362728293738394041423643444546474849505152414253444546545556575859605 unmodified lines66676858697060616263646571727374757677687879808172828384757677787980818283848586878889909192939495969798991001011021038586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251081261271281291301311321151331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731171181191201211221231241741751761771781791801811821831841851861871881891901911921931941951961971981992002011261271282022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352361322372382391361372402412422432446 unmodified lines2512522531501511521531541551561572542552562572582591 unmodified line2612622631651661671681691701711721731741751761771781791801811822642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952 unmodified lines2982993001913013021933033041953053063073083093102003113123133143153163173183193203213223233243253262042052062072083273283293303313323333343353363373383393403412152162172182192202212222232242252262272282292302312322332342353423433443453463473483493503513523533543553562372382392402412422432442452462472483573583593603613623633643653663673683693703713723733743753762503773782522532542552562572582592602612622632642653793803813823833843853863873883893903913923933943953963973983994004014024034042742754054064072774084094104114124132804144154164171 unmodified line419420421422423424290425426292427428429430431432#!/usr/bin/env python3"""Sampling Config Benchmark=========================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, bằng các task có đáp án kiểm chứng tự động (GSM8K, ARC, MMLU)+ đo độ lặp (degeneration). Kết quả có khoảng tin cậy bootstrap để biếtcấu hình nào thực sự hơn, cấu hình nào chỉ "hòa" do nhiễu.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 bất kỳ server tương thích OpenAI API (vLLM, SGLang, llama.cpp server, ...):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 argparseimport asyncioimport hashlibimport itertoolsimport jsonimport osimport randomimport reimport signalimport sysimport tempfilefrom asyncio.subprocess import DEVNULLfrom pathlib import Path
import numpy as npfrom datasets import load_datasetfrom openai import AsyncOpenAI
# ----------------------------------------------------------------------------# Search space# ----------------------------------------------------------------------------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],}LETTERS = "ABCD"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) full = [dict(zip(keys, v)) for v in itertools.product(*GRID.values())] # temperature = 0 là greedy: top_p/top_k không có tác dụng -> chỉ giữ biến thể theo rep_p seen, out = set(), [] for c in full: if c["temperature"] == 0: c = {**c, "top_p": 1.0, "top_k": 0} 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)5 unmodified lines
# ----------------------------------------------------------------------------# Tasks# Datasets# ----------------------------------------------------------------------------def fmt_mc(question, choices): opts = "\n".join(f"{LETTERS[i]}. {c}" for i, c in enumerate(choices)) return ( f"{question}\n\n{opts}\n\n" "Think step by step, then finish with a final line exactly like: Answer: <letter>" )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(tasks, n_per_task, seed):def load_items(subtasks, n, seed): rng = random.Random(seed) items = []
def take(ds): def pick(ds): idx = list(range(len(ds))) rng.shuffle(idx) return idx[:n_per_task]
if "gsm8k" in tasks: ds = load_dataset("openai/gsm8k", "main", split="test") for i in take(ds): r = ds[i] gold = r["answer"].split("####")[-1].strip().replace(",", "") items.append({ "id": f"gsm8k-{i}", "task": "gsm8k", "kind": "num", "gold": gold, "prompt": r["question"] + "\n\nSolve step by step, then finish with a final line exactly like: Answer: <number>", }) if "arc" in tasks: ds = load_dataset("allenai/ai2_arc", "ARC-Challenge", split="test") for i in take(ds): r = ds[i] if len(r["choices"]["text"]) != 4 or r["answerKey"] not in LETTERS: continue items.append({ "id": f"arc-{i}", "task": "arc", "kind": "mc", "gold": r["answerKey"], "prompt": fmt_mc(r["question"], r["choices"]["text"]), }) if "mmlu" in tasks: ds = load_dataset("cais/mmlu", "all", split="test") for i in take(ds): r = ds[i] items.append({ "id": f"mmlu-{i}", "task": "mmlu", "kind": "mc", "gold": LETTERS[r["answer"]], "prompt": fmt_mc(r["question"], r["choices"]), }) 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# Scoring: math# ----------------------------------------------------------------------------def strip_think(t): t = re.sub(r"<think>.*?</think>", "", t, flags=re.S) return t.split("</think>")[-1].strip()
def score(item, text):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) if item["kind"] == "mc": m = re.findall(r"Answer:\s*\**\(?([A-D])\b", text, flags=re.I) return float(bool(m) and m[-1].upper() == item["gold"]) m = re.findall(r"Answer:\s*\**\$?\s*(-?[\d,]*\.?\d+)", text, flags=re.I) if not m: m = re.findall(r"-?[\d,]*\.?\d+", text) if not m: return 0.0 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: return float(abs(float(m[-1].replace(",", "")) - float(item["gold"])) < 1e-4) except ValueError: return 0.0 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): """Tỉ lệ n-gram (từ) bị lặp lại. Càng cao càng bị lặp.""" w = text.split() if len(w) < n + 1: return 0.0 grams = [tuple(w[i:i + n]) for i in range(len(w) - n + 1)] return 1 - len(set(grams)) / len(grams) g = [tuple(w[i:i + n]) for i in range(len(w) - n + 1)] return 1 - len(set(g)) / len(g)
# ----------------------------------------------------------------------------6 unmodified lines 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"]}, ) 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 = e1 unmodified line else: raise RuntimeError(f"API lỗi: {last}") texts = [c.message.content or "" for c in r.choices] return { "id": item["id"], "acc": float(np.mean([score(item, t) for t in texts])), "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])), }
async def run_all(args, items, configs): out_path = Path(args.out) / "raw_results.jsonl" out_path.parent.mkdir(parents=True, exist_ok=True) done = {} if out_path.exists(): for line in out_path.read_text().splitlines(): d = json.loads(line) done[d["key"]] = d
client = AsyncOpenAI(base_url=args.base_url, api_key=args.api_key, timeout=600) 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)2 unmodified lines 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, "config": cfg, "items": res} rec = {"key": key, "sig": sig, "config": cfg, "items": res} done[key] = rec with out_path.open("a") as f: with path.open("a") as f: f.write(json.dumps(rec) + "\n") print(f" acc={np.mean([r['acc'] for r in res]):.4f} rep={np.mean([r['rep'] for r in res]):.4f}") 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# 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] tasks = sorted({it["task"] for it in items}) recs = [r for r in records if all(any(x["id"] == i for x in r["items"]) for i in ids[:1])] C, N = len(recs), len(ids) acc = np.zeros((C, N)); rep = np.zeros((C, N)); trunc = np.zeros((C, N)) for c, r in enumerate(recs): 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 boots = np.stack([acc[:, rng.integers(0, N, N)].mean(1) for _ in range(B)], axis=1) # (C,B) mean = acc.mean(1) lo, hi = np.percentile(boots, [2.5, 97.5], axis=1) p_best = np.bincount(boots.argmax(0), minlength=C) / B
best = int(mean.argmax()) tied = [] for c in range(C): diff = boots[best] - boots[c] if c != best and np.percentile(diff, 2.5) <= 0: tied.append(c)
order = np.argsort(-mean) lines = [] lines.append(f"# Kết quả: `{args.model}`\n") lines.append(f"- Số câu hỏi: **{N}** ({', '.join(tasks)}) | samples/câu: **{args.n_samples}** | max_tokens: {args.max_tokens}") lines.append(f"- Số cấu hình đã test: **{C}**\n") b = recs[best]["config"] lines.append("## 🏆 Cấu hình tốt nhất\n```") lines.append(f"temp = {b['temperature']}\ntop p = {b['top_p']}\ntop k = {b['top_k']}\nrep p (repetition_penalty) = {b['repetition_penalty']}") lines.append(f"```\nAccuracy: **{mean[best]:.4f}** (95% CI {lo[best]:.4f} – {hi[best]:.4f}), P(best) = {p_best[best]:.2f}\n") 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: 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")
lines.append("## Bảng xếp hạng (top 20)\n") lines.append("| # | temp | top_p | top_k | rep_p | Acc | 95% CI | P(best) | Rep4 | Trunc | Tied |") lines.append("|--:|--:|--:|--:|--:|--:|:--|--:|--:|--:|:-:|") for rank, c in enumerate(order[:20], 1): g = recs[c]["config"] t = "✅" if (c == best or c in tied) else "" lines.append(f"| {rank} | {g['temperature']} | {g['top_p']} | {g['top_k']} | {g['repetition_penalty']} | " f"{mean[c]:.4f} | {lo[c]:.3f}–{hi[c]:.3f} | {p_best[c]:.2f} | {rep[c].mean():.3f} | {trunc[c].mean():.3f} | {t} |")
lines.append("\n## Ảnh hưởng trung bình của từng tham số (marginal)\n") 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: lines.append(f"**{k}**\n\n| giá trị | Acc TB |\n|--:|--:|") L.append(f"**{k}**\n\n| giá trị | Score TB |\n|--:|--:|") for v in GRID[k]: idx = [c for c in range(C) if recs[c]["config"][k] == v] if idx: lines.append(f"| {v} | {mean[idx].mean():.4f} |") lines.append("")
Path(args.out).mkdir(parents=True, exist_ok=True) (Path(args.out) / "results.md").write_text("\n".join(lines)) (Path(args.out) / "best_config.json").write_text(json.dumps({ "model": args.model, "best": b, "accuracy": float(mean[best]), "ci95": [float(lo[best]), float(hi[best])], "statistically_tied": [recs[c]["config"] for c in tied], }, indent=2, ensure_ascii=False)) print("\n".join(lines[:12])) print(f"\nĐã lưu: {args.out}/results.md, best_config.json") 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=["gsm8k", "arc", "mmlu"], choices=["gsm8k", "arc", "mmlu"]) p.add_argument("--n-per-task", type=int, default=200, help="số câu hỏi mỗi task") 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=1024) 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, help="số config nếu mode=random") 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")1 unmodified line
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 = [json.loads(l) for l in (Path(args.out) / "raw_results.jsonl").read_text().splitlines()] recs = list(load_records(Path(args.out) / "raw_results.jsonl", sig).values()) else: recs = asyncio.run(run_all(args, items, configs)) 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)
benchmark.py+295-158