Upload 3 files
Browse files- README.md +77 -1
- benchmark.py +297 -0
- requirements.txt +3 -0
README.md
CHANGED
|
@@ -1,3 +1,79 @@
|
|
| 1 |
---
|
| 2 |
-
license:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
tags:
|
| 4 |
+
- benchmark
|
| 5 |
+
- sampling
|
| 6 |
+
- inference
|
| 7 |
+
- llm
|
| 8 |
---
|
| 9 |
+
|
| 10 |
+
# Sampling Config Benchmark
|
| 11 |
+
|
| 12 |
+
Tìm **cấu hình sampling tốt nhất** (`temperature`, `top_p`, `top_k`, `repetition_penalty`) cho một LLM, không cần chat thử bằng tay.
|
| 13 |
+
|
| 14 |
+
Ví dụ output:
|
| 15 |
+
|
| 16 |
+
```
|
| 17 |
+
temp = 1.0
|
| 18 |
+
top p = 0.95
|
| 19 |
+
top k = 40
|
| 20 |
+
rep p (repetition_penalty) = 1.05
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
## Cách hoạt động
|
| 24 |
+
|
| 25 |
+
1. Lấy mẫu câu hỏi có đáp án kiểm chứng tự động: **GSM8K** (toán), **ARC-Challenge** (khoa học), **MMLU** (kiến thức).
|
| 26 |
+
2. Chạy từng cấu hình sampling trong grid (hoặc random search), mỗi câu sample nhiều lần (`--n-samples`) để giảm nhiễu.
|
| 27 |
+
3. Đo: accuracy, tỉ lệ lặp 4-gram (`Rep4`), tỉ lệ bị cắt do hết token (`Trunc`).
|
| 28 |
+
4. Bootstrap 2000 lần trên các câu hỏi để ra **khoảng tin cậy 95%**, **P(best)**, và đánh dấu những cấu hình **không khác biệt có ý nghĩa** với cấu hình tốt nhất (cột `Tied`). Nếu nhiều cấu hình "hòa", hãy chọn cấu hình ít rủi ro lặp nhất.
|
| 29 |
+
|
| 30 |
+
## Cài đặt
|
| 31 |
+
|
| 32 |
+
```bash
|
| 33 |
+
pip install -r requirements.txt
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
## Chạy
|
| 37 |
+
|
| 38 |
+
Bật server tương thích OpenAI API (vLLM khuyến nghị vì hỗ trợ đủ `top_k` và `repetition_penalty`):
|
| 39 |
+
|
| 40 |
+
```bash
|
| 41 |
+
vllm serve Qwen/Qwen3-8B --port 8000
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
Chạy benchmark:
|
| 45 |
+
|
| 46 |
+
```bash
|
| 47 |
+
# Grid đầy đủ (~200+ cấu hình, tốn thời gian)
|
| 48 |
+
python benchmark.py --model Qwen/Qwen3-8B --base-url http://localhost:8000/v1
|
| 49 |
+
|
| 50 |
+
# Nhanh: random 40 cấu hình
|
| 51 |
+
python benchmark.py --model Qwen/Qwen3-8B --mode random --n-random 40
|
| 52 |
+
|
| 53 |
+
# Chính xác hơn: nhiều câu + nhiều sample
|
| 54 |
+
python benchmark.py --model Qwen/Qwen3-8B --n-per-task 500 --n-samples 8
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
Có thể ngắt giữa chừng và chạy lại: các cấu hình đã xong được lưu trong `results/raw_results.jsonl` và sẽ được bỏ qua.
|
| 58 |
+
|
| 59 |
+
Chỉ phân tích lại: `python benchmark.py --model X --analyze-only`
|
| 60 |
+
|
| 61 |
+
## Output
|
| 62 |
+
|
| 63 |
+
- `results/results.md`: bảng xếp hạng, cấu hình tốt nhất, ảnh hưởng của từng tham số
|
| 64 |
+
- `results/best_config.json`: cấu hình tốt nhất (đọc bằng máy)
|
| 65 |
+
- `results/raw_results.jsonl`: điểm từng câu, từng cấu hình
|
| 66 |
+
|
| 67 |
+
## Lưu ý
|
| 68 |
+
|
| 69 |
+
- `temperature = 0` (greedy) thì `top_p`/`top_k` vô nghĩa nên script tự gộp.
|
| 70 |
+
- `top_k = 0` nghĩa là tắt top-k.
|
| 71 |
+
- Model reasoning (có `<think>`): tăng `--max-tokens` (vd 4096+), phần `<think>` được tự động bỏ khi chấm.
|
| 72 |
+
- Cấu hình tốt nhất ở đây tối ưu cho **câu trả lời đúng**. Với viết sáng tạo/roleplay, temperature tối ưu thường cao hơn.
|
| 73 |
+
- Kết quả phụ thuộc model, prompt, và task; hãy ghi rõ khi đăng.
|
| 74 |
+
|
| 75 |
+
## Ghi kết quả của model (mẫu cho Hugging Face)
|
| 76 |
+
|
| 77 |
+
| Model | temp | top_p | top_k | rep_p | Acc | 95% CI |
|
| 78 |
+
|---|--:|--:|--:|--:|--:|:--|
|
| 79 |
+
| ... | | | | | | |
|
benchmark.py
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|
| 50 |
+
out.append(c)
|
| 51 |
+
if mode == "random":
|
| 52 |
+
random.Random(seed).shuffle(out)
|
| 53 |
+
out = out[:n_random]
|
| 54 |
+
return out
|
| 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 |
+
# ----------------------------------------------------------------------------
|
| 141 |
+
# Runner
|
| 142 |
+
# ----------------------------------------------------------------------------
|
| 143 |
+
async def eval_item(client, args, cfg, item, sem):
|
| 144 |
+
n = 1 if cfg["temperature"] == 0 else args.n_samples
|
| 145 |
+
last = None
|
| 146 |
+
async with 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
|
| 161 |
+
await asyncio.sleep(2 ** attempt)
|
| 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)
|
| 186 |
+
if key in done:
|
| 187 |
+
print(f"[{i}/{len(configs)}] bỏ qua (đã có): {cfg}")
|
| 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")
|
| 284 |
+
args = p.parse_args()
|
| 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 |
+
|
| 296 |
+
if __name__ == "__main__":
|
| 297 |
+
main()
|
requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
openai>=1.40
|
| 2 |
+
datasets>=2.20
|
| 3 |
+
numpy
|