File size: 5,947 Bytes
daf7aaa | 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 | #!/usr/bin/env python3
"""Generate benchmark responses from an OpenAI-compatible endpoint (vLLM / GPUStack), resumable.
export OPENAI_BASE_URL=http://<server>/v1 OPENAI_API_KEY=<token> # never commit the token
python scripts/bench_api.py --bench ifbench --model qwen3 --tag looped_t3 --concurrency 6
ifbench allenai/IFBench test set (300 prompts). Writes <out>/<tag>-responses.jsonl in the format
the official scorer expects ({"prompt", "response"}); score it with
`python -m run_eval --input_data=IFBench_test.jsonl --input_response_data=<file> --output_dir=...`
from https://github.com/allenai/IFBench (`pip install ifbench`). The paper reports prompt-level
loose accuracy.
Sampling follows the model card (temperature 1.0, top_p 0.95, top_k 20, thinking on). The
`response` is the final answer only (`content`, i.e. with the reasoning split off by the server's
reasoning parser). A response cut off at --max-tokens is kept as-is (it will usually fail).
"""
from __future__ import annotations
import argparse
import json
import os
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
def load(bench: str, path: str | None) -> list[dict]:
if bench == "ifbench":
if path:
rows = [json.loads(x) for x in Path(path).read_text().split("\n") if x.strip()]
else:
from datasets import load_dataset
rows = list(load_dataset("allenai/IFBench_test", split="train"))
return [{"key": str(r["key"]), "prompt": r["prompt"]} for r in rows]
raise SystemExit(f"unknown bench {bench}")
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--bench", default="ifbench")
ap.add_argument("--data", default=None, help="local jsonl instead of the HF dataset")
ap.add_argument("--model", required=True)
ap.add_argument("--tag", required=True)
ap.add_argument("--base-url", default=os.environ.get("OPENAI_BASE_URL"))
ap.add_argument("--concurrency", type=int, default=6)
ap.add_argument("--max-tokens", type=int, default=32768)
ap.add_argument("--temperature", type=float, default=1.0)
ap.add_argument("--no-thinking", action="store_true")
ap.add_argument("--limit", type=int, default=0)
ap.add_argument("--out", default="runs/bench")
ap.add_argument("--expect-served", default=None,
help="drop (and retry on resume) responses whose reported model differs, e.g. large-llm")
args = ap.parse_args()
if not args.base_url or not os.environ.get("OPENAI_API_KEY"):
raise SystemExit("set OPENAI_BASE_URL and OPENAI_API_KEY")
from openai import OpenAI
client = OpenAI(base_url=args.base_url, timeout=3600, max_retries=3)
rows = load(args.bench, args.data)
if args.limit:
rows = rows[: args.limit]
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
path = out / f"{args.bench}-{args.tag}-responses.jsonl"
done = set()
if path.exists():
done = {json.loads(x)["key"] for x in path.read_text().split("\n") if x.strip()}
todo = [r for r in rows if r["key"] not in done]
print(f"[bench] {args.bench}/{args.tag}: {len(todo)} to do, {len(done)} done, model={args.model}", flush=True)
lock = threading.Lock()
stats = {"n": 0, "tok": 0, "length": 0, "empty": 0}
t0 = time.time()
def one(r: dict) -> dict:
t = time.time()
resp = client.chat.completions.create(
model=args.model, messages=[{"role": "user", "content": r["prompt"]}],
temperature=args.temperature, top_p=0.95, max_tokens=args.max_tokens,
extra_body={"top_k": 20, "chat_template_kwargs": {"enable_thinking": not args.no_thinking}},
)
if args.expect_served and resp.model != args.expect_served:
raise RuntimeError(f"served by {resp.model!r}, expected {args.expect_served!r}; not saved")
ch = resp.choices[0]
m = ch.message
extra = m.model_extra or {}
reasoning = (getattr(m, "reasoning_content", None) or getattr(m, "reasoning", None)
or extra.get("reasoning_content") or extra.get("reasoning") or "")
content = m.content or ""
if not reasoning and "</think>" in content: # server without a reasoning parser
reasoning, content = content.split("</think>", 1)
return {"key": r["key"], "prompt": r["prompt"], "response": content.strip(), "finish": ch.finish_reason,
"completion_tokens": resp.usage.completion_tokens if resp.usage else None,
"reasoning_chars": len(reasoning), "sec": round(time.time() - t, 1), "served_model": resp.model}
with open(path, "a", encoding="utf-8") as f, ThreadPoolExecutor(args.concurrency) as pool:
futs = [pool.submit(one, r) for r in todo]
for fut in as_completed(futs):
try:
rec = fut.result()
except Exception as e: # noqa: BLE001
print(f"[bench] request failed: {type(e).__name__}: {str(e)[:200]}", flush=True)
continue
with lock:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
f.flush()
stats["n"] += 1
stats["tok"] += rec["completion_tokens"] or 0
stats["length"] += rec["finish"] == "length"
stats["empty"] += not rec["response"]
if stats["n"] % 10 == 0 or stats["n"] == len(todo):
el = time.time() - t0
print(f"[bench] {stats['n']}/{len(todo)} mean_tok={stats['tok'] / stats['n']:.0f} "
f"capped={stats['length']} empty={stats['empty']} {stats['tok'] / el:.0f} tok/s "
f"{el / 60:.1f} min", flush=True)
print(f"[bench] done -> {path}", flush=True)
if __name__ == "__main__":
main()
|