Vendor the GSM8K control items, save per-item control predictions, format the evaluator
Browse filesFiles changed (6)
21 unmodified lines2223242521 unmodified linesThe item files contain hidden grading data. The evaluator gives the model only the ticket and sandbox observations. A strict pass requires the expected status, an untouched validator, the reference tables and zero unintended edits. A 100-row audit replayed the supervised tool calls and checked for overlapping families and tables across splits.The `scripts/csv_repair` directory contains the evaluator distributed with these fixtures. It runs the base model and adapter with identical seeds on one vLLM server. Use a disposable, unprivileged environment without credentials or host mounts because models can edit the Python validator. [Stage 1 adapter](https://huggingface.co/Microck/qwen3-4b-csv-repair-lora)21 unmodified lines2223242521 unmodified linesThe item files contain hidden grading data. The evaluator gives the model only the ticket and sandbox observations. A strict pass requires the expected status, an untouched validator, the reference tables and zero unintended edits. A 100-row audit replayed the supervised tool calls and checked for overlapping families and tables across splits.The `scripts/csv_repair` directory contains the evaluator distributed with these fixtures. `scripts/csv_repair/gsm8k_main_test_first250.jsonl` holds the first 250 problems of the GSM8K test split ([openai/gsm8k](https://huggingface.co/datasets/openai/gsm8k), config `main`, revision `740312add88f781978c0658806c59bc2815b9866`, MIT license) for the general-capability control, so the evaluator needs no `datasets` install. It runs the base model and adapter with identical seeds on one vLLM server. Use a disposable, unprivileged environment without credentials or host mounts because models can edit the Python validator. [Stage 1 adapter](https://huggingface.co/Microck/qwen3-4b-csv-repair-lora)
2 unmodified lines34567891011122 unmodified lines1516171819202122232425262728293031323334353637383940414243443 unmodified lines48495051525354555 unmodified lines6162636465666710 unmodified lines7879808182838485868788899091922 unmodified lines95969798991001011026 unmodified lines1091101111121131141151161171181191201211221231241251261271282 unmodified linesThey check that training on repair episodes did not cost ordinary skills (a drop of more than 3 points is flagged).Both score a model on the same OpenAI-compatible server as ``evaluate.py``:- ``gsm8k``: the first ``--gsm8k`` problems of ``openai/gsm8k`` (main, test), answered in one turn; correct when thelast number of the reply equals the reference answer.- ``tool_use``: 120 seeded requests over four unrelated tools (weather, currency, calendar, stock quote); correctwhen the reply is exactly one call to the right tool with the right arguments."""from __future__ import annotations2 unmodified linesimport jsonimport randomimport refrom typing import Any_NUMBER = re.compile(r"-?\d[\d,]*(?:\.\d+)?")CONTROL_TOOLS = [{"type": "function", "function": {"name": "get_weather", "description": "Current weather for a city.","parameters": {"type": "object", "properties": {"city": {"type": "string"},"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}}, "required": ["city", "unit"]}}},{"type": "function", "function": {"name": "convert_currency", "description": "Convert an amount between currencies.","parameters": {"type": "object", "properties": {"amount": {"type": "number"}, "from_currency": {"type": "string"},"to_currency": {"type": "string"}}, "required": ["amount", "from_currency", "to_currency"]}}},{"type": "function", "function": {"name": "create_event", "description": "Add an event to the user's calendar.","parameters": {"type": "object", "properties": {"title": {"type": "string"},"date": {"type": "string", "description": "YYYY-MM-DD"}, "duration_minutes": {"type": "integer"}},"required": ["title", "date", "duration_minutes"]}}},{"type": "function", "function": {"name": "get_stock_quote", "description": "Latest price for a ticker symbol.","parameters": {"type": "object", "properties": {"ticker": {"type": "string"}}, "required": ["ticker"]}}},]_CITIES = ["Nairobi", "Montreal", "Hanoi", "Bergen", "Cordoba", "Adelaide", "Krakow", "Osaka"]_CCY = ["USD", "EUR", "JPY", "GBP", "CHF", "INR"]_TICKERS = ["AAPL", "MSFT", "NVDA", "TSLA", "SAP", "TM"]_MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October","November", "December"]def tool_use_items(count: int = 120, seed: int = 7) -> list[dict[str, Any]]:3 unmodified lineskind = i % 4if kind == 0:city, unit = rng.choice(_CITIES), rng.choice(["celsius", "fahrenheit"])text = rng.choice([f"What's the weather in {city} right now? Give it in {unit}.",f"Check the current weather for {city}, in {unit} please."])want = ("get_weather", {"city": city, "unit": unit})elif kind == 1:amount = rng.choice([25, 100, 250, 1200, 75.5])5 unmodified linesminutes = rng.choice([30, 45, 60, 90])title = rng.choice(["Dentist", "Team sync", "Call with Priya", "Gym", "Budget review"])text = f"Put '{title}' on my calendar for {_MONTHS[month - 1]} {day}, 2027, {minutes} minutes."want = ("create_event", {"title": title, "date": f"2027-{month:02d}-{day:02d}", "duration_minutes": minutes})else:ticker = rng.choice(_TICKERS)text = rng.choice([f"What's {ticker} trading at?", f"Get me the latest quote for {ticker}."])10 unmodified linesreturn a == basync def run_tool_use(client: Any, model: str, seed: int, gate: asyncio.Semaphore) -> dict[str, Any]:items = tool_use_items()async def one(i: int, item: dict[str, Any]) -> bool:async with gate:r = await client.chat.completions.create(model=model, messages=[{"role": "user", "content": item["prompt"]}], tools=CONTROL_TOOLS,tool_choice="auto", temperature=0.7, top_p=0.8, max_tokens=512, seed=seed * 100_003 + i)calls = r.choices[0].message.tool_calls or []if len(calls) != 1 or calls[0].function.name != item["tool"]:return Falsetry:2 unmodified linesreturn Falsereturn set(args) == set(item["arguments"]) and all(_same(args[k], v) for k, v in item["arguments"].items())hits = await asyncio.gather(*(one(i, item) for i, item in enumerate(items)))return {"tool_use_accuracy": round(100.0 * sum(hits) / len(hits), 2), "tool_use_n": len(hits)}def _last_number(text: str) -> float | None:6 unmodified linesreturn Noneasync def run_gsm8k(client: Any, model: str, seed: int, count: int, gate: asyncio.Semaphore) -> dict[str, Any]:from datasets import load_dataset # noqa: PLC0415 — only the control needs itrows = load_dataset("openai/gsm8k", "main", split="test").select(range(count))async def one(i: int, row: dict[str, Any]) -> bool:async with gate:r = await client.chat.completions.create(model=model, temperature=0.7, top_p=0.8, max_tokens=1024, seed=seed * 100_003 + i,messages=[{"role": "user", "content": row["question"] + "\nSolve it step by step and end with the ""final answer as a number on its own line."}])want = float(row["answer"].split("####")[-1].strip().replace(",", ""))got = _last_number(r.choices[0].message.content or "")return got is not None and abs(got - want) < 1e-6hits = await asyncio.gather(*(one(i, row) for i, row in enumerate(rows)))return {"gsm8k_accuracy": round(100.0 * sum(hits) / len(hits), 2), "gsm8k_n": len(hits)}2 unmodified lines3456789101112131415162 unmodified lines1920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071083 unmodified lines1121131141151161171181191201211221235 unmodified lines12913013113213313413513613713810 unmodified lines1491501511521531541551561571581591602 unmodified lines1631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921936 unmodified lines2002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402 unmodified linesThey check that training on repair episodes did not cost ordinary skills (a drop of more than 3 points is flagged).Both score a model on the same OpenAI-compatible server as ``evaluate.py``:- ``gsm8k``: the first ``--gsm8k`` (at most 250) problems of ``openai/gsm8k`` (main, test), answered in one turn;correct when the last number of the reply equals the reference answer. The 250 problems are vendored next to thisfile (``GSM8K_FILE``: dataset revision ``GSM8K_REVISION``, MIT license) so the control needs neither ``datasets``nor network access.- ``tool_use``: 120 seeded requests over four unrelated tools (weather, currency, calendar, stock quote); correctwhen the reply is exactly one call to the right tool with the right arguments.Both return a summary of numbers and the per-item records, which ``run_eval.py`` saves next to the repair episodes."""from __future__ import annotations2 unmodified linesimport jsonimport randomimport refrom pathlib import Pathfrom typing import Any# The first 250 rows of openai/gsm8k, config main, split test, in file order, as {"index", "question", "answer"}.GSM8K_FILE = Path(__file__).with_name("gsm8k_main_test_first250.jsonl")GSM8K_REVISION = "740312add88f781978c0658806c59bc2815b9866"_NUMBER = re.compile(r"-?\d[\d,]*(?:\.\d+)?")CONTROL_TOOLS = [{"type": "function","function": {"name": "get_weather","description": "Current weather for a city.","parameters": {"type": "object","properties": {"city": {"type": "string"},"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},},"required": ["city", "unit"],},},},{"type": "function","function": {"name": "convert_currency","description": "Convert an amount between currencies.","parameters": {"type": "object","properties": {"amount": {"type": "number"},"from_currency": {"type": "string"},"to_currency": {"type": "string"},},"required": ["amount", "from_currency", "to_currency"],},},},{"type": "function","function": {"name": "create_event","description": "Add an event to the user's calendar.","parameters": {"type": "object","properties": {"title": {"type": "string"},"date": {"type": "string", "description": "YYYY-MM-DD"},"duration_minutes": {"type": "integer"},},"required": ["title", "date", "duration_minutes"],},},},{"type": "function","function": {"name": "get_stock_quote","description": "Latest price for a ticker symbol.","parameters": {"type": "object", "properties": {"ticker": {"type": "string"}}, "required": ["ticker"]},},},]_CITIES = ["Nairobi", "Montreal", "Hanoi", "Bergen", "Cordoba", "Adelaide", "Krakow", "Osaka"]_CCY = ["USD", "EUR", "JPY", "GBP", "CHF", "INR"]_TICKERS = ["AAPL", "MSFT", "NVDA", "TSLA", "SAP", "TM"]_MONTHS = ["January","February","March","April","May","June","July","August","September","October","November","December",]def tool_use_items(count: int = 120, seed: int = 7) -> list[dict[str, Any]]:3 unmodified lineskind = i % 4if kind == 0:city, unit = rng.choice(_CITIES), rng.choice(["celsius", "fahrenheit"])text = rng.choice([f"What's the weather in {city} right now? Give it in {unit}.",f"Check the current weather for {city}, in {unit} please.",])want = ("get_weather", {"city": city, "unit": unit})elif kind == 1:amount = rng.choice([25, 100, 250, 1200, 75.5])5 unmodified linesminutes = rng.choice([30, 45, 60, 90])title = rng.choice(["Dentist", "Team sync", "Call with Priya", "Gym", "Budget review"])text = f"Put '{title}' on my calendar for {_MONTHS[month - 1]} {day}, 2027, {minutes} minutes."want = ("create_event",{"title": title, "date": f"2027-{month:02d}-{day:02d}", "duration_minutes": minutes},)else:ticker = rng.choice(_TICKERS)text = rng.choice([f"What's {ticker} trading at?", f"Get me the latest quote for {ticker}."])10 unmodified linesreturn a == basync def run_tool_use(client: Any, model: str, seed: int, gate: asyncio.Semaphore) -> tuple[dict[str, Any], list[dict[str, Any]]]:items = tool_use_items()def correct(item: dict[str, Any], calls: list[Any]) -> bool:if len(calls) != 1 or calls[0].function.name != item["tool"]:return Falsetry:2 unmodified linesreturn Falsereturn set(args) == set(item["arguments"]) and all(_same(args[k], v) for k, v in item["arguments"].items())async def one(i: int, item: dict[str, Any]) -> dict[str, Any]:async with gate:r = await client.chat.completions.create(model=model,messages=[{"role": "user", "content": item["prompt"]}],tools=CONTROL_TOOLS,tool_choice="auto",temperature=0.7,top_p=0.8,max_tokens=512,seed=seed * 100_003 + i,)calls = r.choices[0].message.tool_calls or []return {"index": i,"tool": item["tool"],"arguments": item["arguments"],"calls": [{"name": c.function.name, "arguments": c.function.arguments} for c in calls],"content": r.choices[0].message.content or "","correct": correct(item, calls),}records = await asyncio.gather(*(one(i, item) for i, item in enumerate(items)))hits = sum(rec["correct"] for rec in records)return {"tool_use_accuracy": round(100.0 * hits / len(records), 2), "tool_use_n": len(records)}, recordsdef _last_number(text: str) -> float | None:6 unmodified linesreturn Noneasync def run_gsm8k(client: Any, model: str, seed: int, count: int, gate: asyncio.Semaphore) -> tuple[dict[str, Any], list[dict[str, Any]]]:rows = [json.loads(line) for line in GSM8K_FILE.read_text().splitlines() if line.strip()]if not 0 < count <= len(rows):raise ValueError(f"--gsm8k must be between 1 and {len(rows)}, the problems vendored in {GSM8K_FILE.name}")rows = rows[:count]async def one(i: int, row: dict[str, Any]) -> dict[str, Any]:async with gate:r = await client.chat.completions.create(model=model,temperature=0.7,top_p=0.8,max_tokens=1024,seed=seed * 100_003 + i,messages=[{"role": "user","content": row["question"] + "\nSolve it step by step and end with the ""final answer as a number on its own line.",}],)want = float(row["answer"].split("####")[-1].strip().replace(",", ""))content = r.choices[0].message.content or ""got = _last_number(content)return {"index": row["index"],"reference": want,"parsed": got,"content": content,"correct": got is not None and abs(got - want) < 1e-6,}records = await asyncio.gather(*(one(i, row) for i, row in enumerate(rows)))hits = sum(rec["correct"] for rec in records)return {"gsm8k_accuracy": round(100.0 * hits / len(records), 2), "gsm8k_n": len(records)}, records
23 unmodified lines2425262728293031323334353637383940413 unmodified lines454647484950515 unmodified lines57585960616263646520 unmodified lines8687888990919210 unmodified lines10310410510610710810911011111211311411511611723 unmodified linesfrom scripts.csv_repair.sandbox import TOOLS, Sandbox, first_messages, gradeasync def run_episode(client: Any, model: str, item: dict[str, Any], *, seed: int, temperature: float, top_p: float,max_turns: int, max_tokens: int) -> dict[str, Any]:box = Sandbox(item)messages = first_messages(item)final_text: str | None = Noneturns = 0error = Nonefor turns in range(1, max_turns + 1):try:response = await client.chat.completions.create(model=model, messages=messages, tools=TOOLS, tool_choice="auto", temperature=temperature,top_p=top_p, max_tokens=max_tokens, seed=seed,)except Exception as e: # a context overflow or server error ends the episode ungraded-as-failederror = f"{type(e).__name__}: {str(e)[:300]}"3 unmodified linesentry: dict[str, Any] = {"role": "assistant", "content": message.content or ""}if calls:entry["tool_calls"] = [{"id": c.id, "type": "function", "function": {"name": c.function.name, "arguments": c.function.arguments}}for c in calls]messages.append(entry)5 unmodified linesmessages.append({"role": "tool", "tool_call_id": c.id, "name": c.function.name, "content": output})verdict = grade(box, final_text)return {"item_id": item["item_id"], "kind": item["kind"], "family": item["family"],"error_classes": item["error_classes"], "turns": turns, "error": error,"validator_edits": box.validator_edits, **verdict.as_dict(), "messages": messages,}20 unmodified lines"mean_tool_calls": round(sum(e["tool_calls"] for e in episodes) / n, 2),"no_status_rate": round(100.0 * sum(e["status"] is None for e in episodes) / n, 2),"error_rate": round(100.0 * sum(e["error"] is not None for e in episodes) / n, 2),"noop_untouched_rate": round(100.0 * sum(e["unintended_edits"] == 0 and not e["tampered"] for e in noop) / len(noop), 2) if noop else None,"strict_by_kind": {k: rate("strict", v) for k, v in sorted(by_kind.items())},"strict_by_class": {k: rate("strict", v) for k, v in sorted(by_class.items())},}10 unmodified linesasync def one(index: int, item: dict[str, Any]) -> dict[str, Any]:async with gate:return await run_episode(client, args.model, item, seed=args.seed * 100_003 + index,temperature=args.temperature, top_p=args.top_p, max_turns=args.max_turns,max_tokens=args.max_tokens)start = time.time()episodes = await asyncio.gather(*(one(i, item) for i, item in enumerate(items)))summary = summarize(episodes)summary.update({"model": args.model, "seed": args.seed, "items": args.items, "temperature": args.temperature,"top_p": args.top_p, "max_turns": args.max_turns, "seconds": round(time.time() - start, 1)})out = Path(args.out)out.mkdir(parents=True, exist_ok=True)tag = f"{Path(args.items).stem}.{args.model.replace('/', '_')}.seed{args.seed}"23 unmodified lines242526272829303132333435363738394041424344454647484950515253545556573 unmodified lines61626364656667686970715 unmodified lines77787980818283848586878889909120 unmodified lines11211311411511611711811912012112210 unmodified lines13313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216323 unmodified linesfrom scripts.csv_repair.sandbox import TOOLS, Sandbox, first_messages, gradeasync def run_episode(client: Any,model: str,item: dict[str, Any],*,seed: int,temperature: float,top_p: float,max_turns: int,max_tokens: int,) -> dict[str, Any]:box = Sandbox(item)messages = first_messages(item)final_text: str | None = Noneturns = 0error = Nonefor turn in range(1, max_turns + 1):turns = turntry:response = await client.chat.completions.create(model=model,messages=messages,tools=TOOLS,tool_choice="auto",temperature=temperature,top_p=top_p,max_tokens=max_tokens,seed=seed,)except Exception as e: # a context overflow or server error ends the episode ungraded-as-failederror = f"{type(e).__name__}: {str(e)[:300]}"3 unmodified linesentry: dict[str, Any] = {"role": "assistant", "content": message.content or ""}if calls:entry["tool_calls"] = [{"id": c.id,"type": "function","function": {"name": c.function.name, "arguments": c.function.arguments},}for c in calls]messages.append(entry)5 unmodified linesmessages.append({"role": "tool", "tool_call_id": c.id, "name": c.function.name, "content": output})verdict = grade(box, final_text)return {"item_id": item["item_id"],"kind": item["kind"],"family": item["family"],"error_classes": item["error_classes"],"turns": turns,"error": error,"validator_edits": box.validator_edits,**verdict.as_dict(),"messages": messages,}20 unmodified lines"mean_tool_calls": round(sum(e["tool_calls"] for e in episodes) / n, 2),"no_status_rate": round(100.0 * sum(e["status"] is None for e in episodes) / n, 2),"error_rate": round(100.0 * sum(e["error"] is not None for e in episodes) / n, 2),"noop_untouched_rate": round(100.0 * sum(e["unintended_edits"] == 0 and not e["tampered"] for e in noop) / len(noop), 2)if noopelse None,"strict_by_kind": {k: rate("strict", v) for k, v in sorted(by_kind.items())},"strict_by_class": {k: rate("strict", v) for k, v in sorted(by_class.items())},}10 unmodified linesasync def one(index: int, item: dict[str, Any]) -> dict[str, Any]:async with gate:return await run_episode(client,args.model,item,seed=args.seed * 100_003 + index,temperature=args.temperature,top_p=args.top_p,max_turns=args.max_turns,max_tokens=args.max_tokens,)start = time.time()episodes = await asyncio.gather(*(one(i, item) for i, item in enumerate(items)))summary = summarize(episodes)summary.update({"model": args.model,"seed": args.seed,"items": args.items,"temperature": args.temperature,"top_p": args.top_p,"max_turns": args.max_turns,"seconds": round(time.time() - start, 1),})out = Path(args.out)out.mkdir(parents=True, exist_ok=True)tag = f"{Path(args.items).stem}.{args.model.replace('/', '_')}.seed{args.seed}"
6 unmodified lines7891011121317 unmodified lines31323334353637383928 unmodified lines68697071727374751 unmodified line777879808182838485868788899011 unmodified lines1021031041051061071081096 unmodified lines1161171181191201211221231246 unmodified linespython -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/The server command is printed and saved in the report. Needs ``vllm``, ``openai`` and ``datasets``."""from __future__ import annotations17 unmodified linesdef 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 cmd28 unmodified linesout.mkdir(parents=True, exist_ok=True)cmd = server_command(args)print("server:", " ".join(cmd), flush=True)log = open(out / "vllm.log", "w")proc = subprocess.Popen(cmd, stdout=log, stderr=subprocess.STDOUT, env={**os.environ, "VLLM_LOGGING_LEVEL": "WARNING"})try:wait_ready(args.port, proc)models = [BASE_MODEL] + ([ADAPTER_NAME] if args.adapter else [])1 unmodified linefor 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)11 unmodified linesclient = 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"}result.update(await controls.run_gsm8k(client, model, seed, args.gsm8k, gate))result.update(await controls.run_tool_use(client, model, seed, gate))return result6 unmodified linesfor (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 means6 unmodified lines7891011121317 unmodified lines31323334353637383940414243444546474849505152535428 unmodified lines838485868788899091921 unmodified line94959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113211 unmodified lines1441451461471481491501511521531541551561576 unmodified lines1641651661671681691701711721731746 unmodified linespython -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/The server command is printed and saved in the report. Needs ``vllm`` and ``openai``, both in the vLLM image."""from __future__ import annotations17 unmodified linesdef 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 cmd28 unmodified linesout.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 = [BASE_MODEL] + ([ADAPTER_NAME] if args.adapter else [])1 unmodified linefor 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)11 unmodified linesclient = 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 result6 unmodified linesfor (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
262 unmodified lines26326426526626726826927075 unmodified lines346347348349350351352353354355356357358359360361362363364365262 unmodified linesparts = []for name, spec in schema["tables"].items():cols = ",\n".join(f" {json.dumps(c)}" for c in spec["columns"])parts.append(f' {json.dumps(name)}: {{\n "primary_key": {json.dumps(spec["primary_key"])},\n'f' "columns": [\n{cols}\n ],\n "invariants": {json.dumps(spec.get("invariants", []))}\n }}')return '{\n "tables": {\n' + ",\n".join(parts) + "\n }\n}\n"75 unmodified linesdef read_file(self, path: str) -> str:path = str(path).strip().lstrip("./")if path not in READABLE_FILES:raise ToolError(f"cannot read {path!r}: readable files are {', '.join(READABLE_FILES)}; use inspect_rows ""for tables")return _clip(self.files()[path])def inspect_rows(self, table: str, rows: list[int] | None = None, match: dict[str, Any] | None = None,start: int | None = None, limit: int | None = None) -> str:current = self._table(table)if match:header = self.headers[table]unknown = [c for c in match if c not in header]if unknown:raise ToolError(f"no column {unknown[0]!r} in {table}")picked = [(r, cells) for r, cells in sorted(current.items())if all(cells[header.index(c)] == str(v) for c, v in match.items())][:MAX_ROWS_PER_INSPECT]note = f"\n({len(picked)} matching row(s))"elif rows:wanted = [int(r) for r in rows][:MAX_ROWS_PER_INSPECT]262 unmodified lines26326426526626726826927027127275 unmodified lines348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377262 unmodified linesparts = []for name, spec in schema["tables"].items():cols = ",\n".join(f" {json.dumps(c)}" for c in spec["columns"])parts.append(f' {json.dumps(name)}: {{\n "primary_key": {json.dumps(spec["primary_key"])},\n'f' "columns": [\n{cols}\n ],\n "invariants": {json.dumps(spec.get("invariants", []))}\n }}')return '{\n "tables": {\n' + ",\n".join(parts) + "\n }\n}\n"75 unmodified linesdef read_file(self, path: str) -> str:path = str(path).strip().lstrip("./")if path not in READABLE_FILES:raise ToolError(f"cannot read {path!r}: readable files are {', '.join(READABLE_FILES)}; use inspect_rows for tables")return _clip(self.files()[path])def inspect_rows(self,table: str,rows: list[int] | None = None,match: dict[str, Any] | None = None,start: int | None = None,limit: int | None = None,) -> str:current = self._table(table)if match:header = self.headers[table]unknown = [c for c in match if c not in header]if unknown:raise ToolError(f"no column {unknown[0]!r} in {table}")picked = [(r, cells)for r, cells in sorted(current.items())if all(cells[header.index(c)] == str(v) for c, v in match.items())][:MAX_ROWS_PER_INSPECT]note = f"\n({len(picked)} matching row(s))"elif rows:wanted = [int(r) for r in rows][:MAX_ROWS_PER_INSPECT]
README.md+1-1
scripts/csv_repair/controls.py+153-41
scripts/csv_repair/evaluate.py+61-15
scripts/csv_repair/gsm8k_main_test_first250.jsonlAdded
scripts/csv_repair/run_eval.py+66-16
scripts/csv_repair/sandbox.py+20-8