File size: 7,293 Bytes
647451b d3f3bc7 c2e8d04 647451b c2e8d04 647451b d3f3bc7 647451b d3f3bc7 647451b c2e8d04 647451b d3f3bc7 647451b c2e8d04 647451b c2e8d04 647451b c2e8d04 647451b c2e8d04 647451b c2e8d04 647451b | 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 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 | """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())
|