Microck's picture
Card: state the license and how the data was made; evaluator gains --adapter-only
d3f3bc7 verified
Raw History Blame Contribute Delete
7.29 kB
"""One command that scores the base model and the LoRA adapter on CSV import repair over several seeds.
It starts one vLLM server holding the base model and (optionally) the adapter, so both arms run on the same server,
hardware, template and decoding; then, for each seed, it runs ``evaluate.py`` on every item file and the general
controls, and writes a ``report.json`` with per-seed and mean numbers.
python -m scripts.csv_repair.run_eval --items data/test_items.jsonl data/fresh_items.jsonl \\
--adapter <adapter dir or HF repo> --seeds 1 2 3 --out results/
``--adapter-only`` scores the adapter alone; without ``--adapter`` only the base model is scored.
The server command is printed and saved in the report. Needs ``vllm`` and ``openai``, both in the vLLM image.
"""
from __future__ import annotations
import argparse
import asyncio
import json
import os
import statistics
import subprocess
import sys
import time
import urllib.request
from pathlib import Path
from scripts.csv_repair import controls, evaluate
BASE_MODEL = "Qwen/Qwen3-4B-Instruct-2507"
BASE_REVISION = "cdbee75f17c01a7cc42f958dc650907174af0554"
ADAPTER_NAME = "csv-sft"
def server_command(args: argparse.Namespace) -> list[str]:
cmd = [
"vllm",
"serve",
BASE_MODEL,
"--revision",
BASE_REVISION,
"--port",
str(args.port),
"--max-model-len",
"32768",
"--gpu-memory-utilization",
"0.85",
"--enable-auto-tool-choice",
"--tool-call-parser",
"hermes",
"--seed",
"0",
]
if args.adapter:
cmd += ["--enable-lora", "--max-lora-rank", "64", "--lora-modules", f"{ADAPTER_NAME}={args.adapter}"]
return cmd
def wait_ready(port: int, proc: subprocess.Popen, timeout: float = 1800) -> None:
deadline = time.time() + timeout
while time.time() < deadline:
if proc.poll() is not None:
raise SystemExit(f"vllm exited with {proc.returncode}")
try:
with urllib.request.urlopen(f"http://localhost:{port}/v1/models", timeout=5):
return
except OSError:
time.sleep(5)
raise SystemExit("vllm did not come up in time")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
parser.add_argument("--items", nargs="+", required=True)
parser.add_argument("--adapter", default="", help="LoRA adapter dir or HF repo; omit to score the base model only")
parser.add_argument("--adapter-only", action="store_true", help="score the adapter but not the base model")
parser.add_argument("--seeds", nargs="+", type=int, default=[1, 2, 3])
parser.add_argument("--controls", action="store_true", help="also run the GSM8K and tool-use controls")
parser.add_argument("--gsm8k", type=int, default=250)
parser.add_argument("--port", type=int, default=8000)
parser.add_argument("--concurrency", type=int, default=48)
parser.add_argument("--out", required=True)
args = parser.parse_args()
if args.adapter_only and not args.adapter:
parser.error("--adapter-only needs --adapter")
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
cmd = server_command(args)
print("server:", " ".join(cmd), flush=True)
with open(out / "vllm.log", "w") as log:
proc = subprocess.Popen(
cmd, stdout=log, stderr=subprocess.STDOUT, env={**os.environ, "VLLM_LOGGING_LEVEL": "WARNING"}
)
try:
wait_ready(args.port, proc)
models = ([] if args.adapter_only else [BASE_MODEL]) + ([ADAPTER_NAME] if args.adapter else [])
report: dict = {"server_command": " ".join(cmd), "seeds": args.seeds, "runs": []}
for seed in args.seeds:
for model in models:
for items in args.items:
ns = argparse.Namespace(
items=items,
model=model,
base_url=f"http://localhost:{args.port}/v1",
seed=seed,
temperature=0.7,
top_p=0.8,
max_turns=20,
max_tokens=2048,
concurrency=args.concurrency,
limit=0,
out=str(out),
)
summary = asyncio.run(evaluate.evaluate(ns))
report["runs"].append(summary)
print(
json.dumps(
{
k: summary[k]
for k in (
"model",
"seed",
"items",
"strict_rate",
"tamper_rate",
"false_success_rate",
"mean_tool_calls",
"seconds",
)
}
),
flush=True,
)
if args.controls:
report["runs"].append(asyncio.run(_controls(args, model, seed)))
print(json.dumps(report["runs"][-1]), flush=True)
report["mean"] = _means(report["runs"])
(out / "report.json").write_text(json.dumps(report, indent=2))
print(json.dumps(report["mean"], indent=2))
finally:
proc.terminate()
proc.wait(timeout=60)
async def _controls(args: argparse.Namespace, model: str, seed: int) -> dict:
from openai import AsyncOpenAI # noqa: PLC0415
client = AsyncOpenAI(base_url=f"http://localhost:{args.port}/v1", api_key="EMPTY", timeout=600)
gate = asyncio.Semaphore(args.concurrency)
result = {"model": model, "seed": seed, "items": "controls"}
tag = f"controls.{model.replace('/', '_')}.seed{seed}"
for name, (summary, records) in (
("gsm8k", await controls.run_gsm8k(client, model, seed, args.gsm8k, gate)),
("tool_use", await controls.run_tool_use(client, model, seed, gate)),
):
result.update(summary)
with open(Path(args.out) / f"{tag}.{name}.jsonl", "w") as fh:
fh.writelines(json.dumps(rec) + "\n" for rec in records)
return result
def _means(runs: list[dict]) -> dict:
"""Mean and sample std over seeds of every numeric headline, per (model, item file)."""
groups: dict[tuple[str, str], list[dict]] = {}
for r in runs:
groups.setdefault((r["model"], r["items"]), []).append(r)
means = {}
for (model, items), rows in groups.items():
keys = [k for k, v in rows[0].items() if isinstance(v, (int, float)) and k not in ("seed", "episodes")]
means[f"{model} | {Path(items).name}"] = {
k: {
"mean": round(statistics.fmean(r[k] for r in rows), 2),
"std": round(statistics.stdev(r[k] for r in rows), 2) if len(rows) > 1 else 0.0,
"per_seed": [r[k] for r in rows],
}
for k in keys
}
return means
if __name__ == "__main__":
sys.exit(main())