Download eval/agent_eval.py from sebika123123/Qwen3.8-27B-Fast-Coder: direct link, hf CLI and curl.
- Browser
- Download file 33.7 kB
-
https://huggingface.co/sebika123123/Qwen3.8-27B-Fast-Coder/resolve/main/eval/agent_eval.py
- Command line
-
hf download hf://sebika123123/Qwen3.8-27B-Fast-Coder/eval/agent_eval.py
-
curl -L -o agent_eval.py https://huggingface.co/sebika123123/Qwen3.8-27B-Fast-Coder/resolve/main/eval/agent_eval.py
33.7 kB
| """Agent eval for local models served by llama-server (or any OpenAI-compatible server). | |
| python agent_eval.py list the tasks and tool-call cases | |
| python agent_eval.py selftest no server needed: fake models check the harness itself | |
| python agent_eval.py run --studio agent tasks against the model loaded in Unsloth Studio | |
| python agent_eval.py run --serve agent --seeds 3 start our own llama-server with a bench.py config | |
| python agent_eval.py toolcalls --studio --think off | |
| python agent_eval.py compare <results folder> <results folder> | |
| A task gives the model six tools in a throwaway project folder (list_dir, read_file, grep, edit_file, write_file, | |
| run) and a job. When the model stops calling tools, a hidden check decides if the job is really done. Besides | |
| pass/fail the run records turns, bad and failed tool calls, and llama.cpp's own timings (decode and prefill | |
| tok/s, how many guessed tokens were accepted), so a speed setting can be judged on "still solves the tasks", | |
| not just "faster". Results go to eval/results/<time>-<label>/. | |
| """ | |
| import argparse | |
| import datetime | |
| import json | |
| import os | |
| import re | |
| import subprocess | |
| import sys | |
| import tempfile | |
| import time | |
| import urllib.error | |
| import urllib.request | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| sys.path.insert(0, HERE) | |
| OUT = os.path.join(HERE, "results") | |
| import sandbox # noqa: E402 | |
| import tasks as tasklib # noqa: E402 | |
| import toolcalls # noqa: E402 | |
| AGENT_SYSTEM = ("You are a coding agent working in a project folder. Use the tools to read the code, change it and " | |
| "run it. Paths are relative to the project root. Work until the job is done, then reply with a short " | |
| "summary, or with the answer if the job asked a question.") | |
| # Qwen's recommended sampling for thinking and for non-thinking mode. | |
| SAMPLING = {True: dict(temperature=1.0, top_p=0.95, top_k=20, presence_penalty=0.0), | |
| False: dict(temperature=0.7, top_p=0.8, top_k=20, presence_penalty=1.5)} | |
| class ServerError(Exception): | |
| pass | |
| class Client: | |
| def __init__(self, url, key=None, think=True, effort=None, max_tokens=16384, timeout=1800, keep_thinking=False, | |
| sampling=None): | |
| base = url.rstrip("/") | |
| self.base = base if base.endswith("/v1") else base + "/v1" | |
| self.root = self.base[:-3] | |
| self.key, self.think, self.effort = key, think, effort | |
| self.max_tokens, self.timeout, self.keep_thinking = max_tokens, timeout, keep_thinking | |
| self.sampling = dict(SAMPLING[think], **(sampling or {})) | |
| def headers(self): | |
| h = {"Content-Type": "application/json"} | |
| if self.key: | |
| h["Authorization"] = "Bearer " + self.key | |
| return h | |
| def alive(self): | |
| try: | |
| with urllib.request.urlopen(urllib.request.Request(self.root + "/health", headers=self.headers()), timeout=5) as r: | |
| return r.status == 200 | |
| except Exception: | |
| return False | |
| def chat(self, messages, tools=None, seed=0): | |
| kwargs = {"enable_thinking": self.think} | |
| if self.effort: | |
| kwargs["reasoning_effort"] = self.effort | |
| body = {"model": "qwen", "messages": messages, "max_tokens": self.max_tokens, "seed": seed, "stream": False, | |
| "cache_prompt": True, "chat_template_kwargs": kwargs, **self.sampling} | |
| if tools: | |
| body["tools"], body["tool_choice"] = tools, "auto" | |
| req = urllib.request.Request(self.base + "/chat/completions", data=json.dumps(body).encode(), | |
| headers=self.headers()) | |
| t0 = time.time() | |
| try: | |
| with urllib.request.urlopen(req, timeout=self.timeout) as r: | |
| data = json.load(r) | |
| except urllib.error.HTTPError as e: | |
| raise ServerError(f"HTTP {e.code}: {e.read().decode(errors='replace')[:300]}") | |
| except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as e: | |
| raise ServerError(f"{type(e).__name__}: {e}") | |
| choice = data["choices"][0] | |
| return {"message": choice["message"], "finish": choice.get("finish_reason"), | |
| "timings": data.get("timings") or {}, "wall": time.time() - t0} | |
| def visible(text): | |
| """The reply without any thinking block that came back inside the content.""" | |
| text = re.sub(r"<think>.*?</think>", "", text or "", flags=re.S) | |
| return text.split("</think>")[-1].strip() | |
| def extract_calls(msg): | |
| """The tool calls of an assistant message as (id, name, args, raw). args is None when the JSON is broken.""" | |
| out = [] | |
| for i, tc in enumerate(msg.get("tool_calls") or []): | |
| f = tc.get("function") or {} | |
| raw = f.get("arguments") | |
| if isinstance(raw, dict): | |
| args = raw | |
| else: | |
| try: | |
| args = json.loads(raw) if raw not in (None, "") else {} | |
| except (TypeError, ValueError): | |
| args = None | |
| out.append((tc.get("id") or f"call_{i}", f.get("name") or "", args if isinstance(args, dict) else None, raw)) | |
| return out | |
| def new_meter(): | |
| return dict(turns=0, calls=0, bad=0, failed=0, failed_edits=0, truncated=0, gen_tokens=0, gen_ms=0.0, | |
| prompt_tokens=0, prompt_ms=0.0, cached_tokens=0, draft_n=0, draft_ok=0) | |
| def add_timings(m, t): | |
| m["gen_tokens"] += t.get("predicted_n", 0) | |
| m["gen_ms"] += t.get("predicted_ms", 0.0) | |
| m["prompt_tokens"] += t.get("prompt_n", 0) | |
| m["prompt_ms"] += t.get("prompt_ms", 0.0) | |
| m["cached_tokens"] += t.get("cache_n", 0) | |
| m["draft_n"] += t.get("draft_n", 0) | |
| m["draft_ok"] += t.get("draft_n_accepted", 0) | |
| def run_trial(client, task, seed): | |
| """One attempt at one task. Returns (result, transcript).""" | |
| files = task["files"]() if callable(task["files"]) else task["files"] | |
| sb = sandbox.Sandbox(files) | |
| m, steps = new_meter(), [] | |
| msgs = [{"role": "system", "content": AGENT_SYSTEM}, {"role": "user", "content": task["prompt"]}] | |
| final, error, t0 = "", None, time.time() | |
| try: | |
| for turn in range(task["max_turns"]): | |
| r = client.chat(msgs, tools=sandbox.TOOLS, seed=seed * 1000 + turn) | |
| m["turns"] += 1 | |
| add_timings(m, r["timings"]) | |
| msg = r["message"] | |
| calls = extract_calls(msg) | |
| reasoning = msg.get("reasoning_content") or "" | |
| steps.append({"turn": turn + 1, "finish": r["finish"], "gen_tokens": r["timings"].get("predicted_n", 0), | |
| "tok_s": round(r["timings"].get("predicted_per_second", 0), 1), "thinking_chars": len(reasoning), | |
| "calls": [c[1] for c in calls], | |
| "thinking": reasoning if len(reasoning) <= 6000 else reasoning[:3000] + "\n...[cut]...\n" + reasoning[-3000:]}) | |
| if not calls: | |
| if r["finish"] == "length": | |
| m["truncated"] += 1 | |
| else: | |
| final = visible(msg.get("content")) | |
| msgs.append({"role": "assistant", "content": msg.get("content") or ""}) | |
| break | |
| keep = {"role": "assistant", "content": msg.get("content") or "", "tool_calls": msg["tool_calls"]} | |
| if client.keep_thinking and reasoning: | |
| keep["reasoning_content"] = reasoning | |
| msgs.append(keep) | |
| for cid, name, args, raw in calls: | |
| m["calls"] += 1 | |
| if args is None: | |
| text, status = "error: the arguments are not valid JSON", "bad" | |
| else: | |
| text, status = sb.call(name, args) | |
| if status == "bad": | |
| m["bad"] += 1 | |
| elif status == "fail": | |
| m["failed"] += 1 | |
| m["failed_edits"] += name == "edit_file" | |
| msgs.append({"role": "tool", "tool_call_id": cid, "content": text}) | |
| try: | |
| ok, detail = task["check"](sb, final) | |
| except Exception as e: # a crashing check must not look like a pass | |
| ok, detail = False, f"the check crashed: {type(e).__name__}: {e}" | |
| except ServerError as e: | |
| error, ok = str(e), False | |
| detail = ("the server could not parse the model's tool call (cut off or broken JSON)" | |
| if "parse tool call" in error else "server error") | |
| finally: | |
| sb.close() | |
| if m["truncated"] and not ok: | |
| detail = f"a reply hit the token limit ({detail})" | |
| res = dict(task=task["id"], seed=seed, ok=bool(ok), detail=detail, error=error, final=final[:400], | |
| wall=round(time.time() - t0, 1), **m) | |
| return res, {"task": task["id"], "seed": seed, "steps": steps, "messages": msgs} | |
| def aggregate(trials): | |
| n = len(trials) | |
| ok = [t for t in trials if t["ok"]] | |
| s = lambda k: sum(t[k] for t in trials) # noqa: E731 | |
| per = lambda a, b, nd=1: round(a / b, nd) if b else None # noqa: E731 | |
| return dict(trials=n, passed=len(ok), success_pct=per(100 * len(ok), n), | |
| turns_per_pass=per(sum(t["turns"] for t in ok), len(ok)), calls=s("calls"), bad_calls=s("bad"), | |
| bad_pct=per(100 * s("bad"), s("calls")), failed_calls=s("failed"), failed_edits=s("failed_edits"), | |
| truncated=s("truncated"), gen_tokens=s("gen_tokens"), decode_tok_s=per(s("gen_tokens"), s("gen_ms") / 1000), | |
| prompt_tokens=s("prompt_tokens"), prefill_tok_s=per(s("prompt_tokens"), s("prompt_ms") / 1000, 0), | |
| cached_tokens=s("cached_tokens"), accept_pct=per(100 * s("draft_ok"), s("draft_n")), | |
| wall_s=round(s("wall"), 1), sec_per_pass=per(s("wall"), len(ok)), | |
| gen_tokens_per_pass=per(s("gen_tokens"), len(ok), 0)) | |
| def per_task(trials): | |
| out = {} | |
| for t in trials: | |
| out.setdefault(t["task"], []).append(t) | |
| return {k: aggregate(v) for k, v in out.items()} | |
| def f(v, suffix="", none="-"): | |
| return none if v is None else f"{v}{suffix}" | |
| def report(label, overall, tasks): | |
| print(f"\n== {label}") | |
| print(f"{'task':<26}{'passed':>8}{'turns':>7}{'calls':>7}{'bad':>5}{'tok/s':>8}{'wall s':>8}") | |
| for tid, a in tasks.items(): | |
| print(f"{tid:<26}{str(a['passed']) + '/' + str(a['trials']):>8}{f(a['turns_per_pass']):>7}{a['calls']:>7}{a['bad_calls']:>5}" | |
| f"{f(a['decode_tok_s']):>8}{a['wall_s']:>8}") | |
| o = overall | |
| print(f"\nsolved {o['passed']}/{o['trials']} ({f(o['success_pct'], '%')}), {f(o['turns_per_pass'])} turns per solve, " | |
| f"{o['calls']} tool calls ({o['bad_calls']} malformed, {o['failed_calls']} failed, {o['failed_edits']} failed edits)") | |
| print(f"decode {f(o['decode_tok_s'])} tok/s, prefill {f(o['prefill_tok_s'])} tok/s, guesses accepted {f(o['accept_pct'], '%')}, " | |
| f"{f(o['sec_per_pass'])} s and {f(o['gen_tokens_per_pass'])} generated tokens per solved task") | |
| def stamp(): | |
| return datetime.datetime.now().strftime("%Y%m%d-%H%M%S") | |
| def dump(path, data): | |
| with open(path, "w", encoding="utf-8") as fh: | |
| json.dump(data, fh, indent=1, ensure_ascii=False) | |
| def run_suite(client, label, args, settings): | |
| chosen = tasklib.pick([x for x in (args.tasks or "").split(",") if x]) | |
| out = os.path.join(OUT, f"{stamp()}-{label}") | |
| os.makedirs(os.path.join(out, "transcripts"), exist_ok=True) | |
| trials = [] | |
| for task in chosen: | |
| for seed in range(1, args.seeds + 1): | |
| res, transcript = run_trial(client, task, seed) | |
| trials.append(res) | |
| dump(os.path.join(out, "trials.json"), trials) | |
| dump(os.path.join(out, "transcripts", f"{task['id']}-s{seed}.json"), transcript) | |
| tok_s = res["gen_tokens"] / (res["gen_ms"] / 1000) if res["gen_ms"] else 0 | |
| print(f"{'PASS' if res['ok'] else 'FAIL'} {task['id']:<26} seed {seed} {res['turns']:>2} turns " | |
| f"{res['calls']:>2} calls {res['bad']} bad {tok_s:5.1f} tok/s {res['wall']:>6.1f} s " | |
| f"{res['error'] or res['detail']}", flush=True) | |
| if res["error"] and not client.alive(): | |
| print("the server went away; stopping here with what finished.") | |
| break | |
| else: | |
| continue | |
| break | |
| summary = dict(label=label, when=datetime.datetime.now().isoformat(timespec="seconds"), settings=settings, | |
| overall=aggregate(trials), tasks=per_task(trials)) | |
| dump(os.path.join(out, "summary.json"), summary) | |
| report(label, summary["overall"], summary["tasks"]) | |
| print(f"\nsaved in {out}") | |
| return summary | |
| def score_reply(c, msg): | |
| calls = [(n, a) for _, n, a, _ in extract_calls(msg)] | |
| return toolcalls.judge(c, calls, visible(msg.get("content"))) | |
| def run_toolcalls(client, label, args, settings): | |
| out = os.path.join(OUT, f"{stamp()}-{label}-toolcalls") | |
| os.makedirs(out, exist_ok=True) | |
| rows, m = [], new_meter() | |
| for c in toolcalls.CASES: | |
| for seed in range(1, args.seeds + 1): | |
| try: | |
| r = client.chat(toolcalls.messages_for(c), tools=c["tools"], seed=seed) | |
| except ServerError as e: | |
| rows.append(dict(case=c["id"], kind=c["kind"], seed=seed, ok=False, detail=str(e))) | |
| print(f"FAIL {c['id']:<24} {e}", flush=True) | |
| if not client.alive(): | |
| print("the server went away; stopping.") | |
| break | |
| continue | |
| add_timings(m, r["timings"]) | |
| if r["finish"] == "length": | |
| ok, detail = False, "cut off at the token limit" | |
| else: | |
| ok, detail = score_reply(c, r["message"]) | |
| rows.append(dict(case=c["id"], kind=c["kind"], seed=seed, ok=ok, detail=detail, | |
| gen_tokens=r["timings"].get("predicted_n", 0))) | |
| if not ok or args.verbose: | |
| print(f"{'PASS' if ok else 'FAIL'} {c['id']:<24} {detail}", flush=True) | |
| else: | |
| continue | |
| break | |
| kinds = {} | |
| for r in rows: | |
| k = kinds.setdefault(r["kind"], [0, 0]) | |
| k[0] += r["ok"] | |
| k[1] += 1 | |
| passed = sum(r["ok"] for r in rows) | |
| summary = dict(label=label + "-toolcalls", settings=settings, passed=passed, total=len(rows), | |
| by_kind={k: f"{a}/{b}" for k, (a, b) in kinds.items()}, | |
| decode_tok_s=round(m["gen_tokens"] / (m["gen_ms"] / 1000), 1) if m["gen_ms"] else None, | |
| gen_tokens_per_case=round(m["gen_tokens"] / len(rows)) if rows else None) | |
| dump(os.path.join(out, "summary.json"), summary) | |
| dump(os.path.join(out, "cases.json"), rows) | |
| print(f"\n== {label}: tool-call cases correct {passed}/{len(rows)} " | |
| + " ".join(f"{k} {v}" for k, v in summary["by_kind"].items())) | |
| print(f"decode {f(summary['decode_tok_s'])} tok/s, {f(summary['gen_tokens_per_case'])} generated tokens per case\nsaved in {out}") | |
| return summary | |
| # ---- finding the server ------------------------------------------------------------------------------------- | |
| def find_studio(): | |
| """(url, api key) of the llama-server Unsloth Studio is running, read from its command line (Windows only).""" | |
| if os.name != "nt": | |
| sys.exit("--studio reads the server's command line with PowerShell and only works on Windows; use --url.") | |
| ps = ("[Console]::OutputEncoding = [Text.Encoding]::UTF8; " | |
| "Get-CimInstance Win32_Process -Filter \"Name='llama-server.exe'\" | " | |
| "Select-Object CommandLine | ConvertTo-Json -Compress") | |
| out = subprocess.run(["powershell", "-NoProfile", "-Command", ps], capture_output=True, text=True, | |
| encoding="utf-8", errors="replace").stdout.strip() | |
| if not out: | |
| sys.exit("no llama-server is running. Load the model in Unsloth Studio first, or use --serve / --url.") | |
| rows = json.loads(out) | |
| cmd = (rows[0] if isinstance(rows, list) else rows).get("CommandLine") or "" | |
| port = re.search(r"--port\s+(\d+)", cmd) | |
| host = re.search(r"--host\s+(\S+)", cmd) | |
| if not port: | |
| sys.exit("found a llama-server but could not read its port from the command line.") | |
| key = None | |
| m = re.search(r'--api-key-file\s+(?:"([^"]+)"|(\S+))', cmd) | |
| if m: | |
| with open(m.group(1) or m.group(2), encoding="utf-8") as fh: | |
| key = fh.read().strip() | |
| elif re.search(r"--api-key\s+(\S+)", cmd): | |
| key = re.search(r"--api-key\s+(\S+)", cmd).group(1).strip('"') | |
| h = host.group(1).strip('"') if host else "127.0.0.1" | |
| return f"http://{'127.0.0.1' if h in ('0.0.0.0', '::') else h}:{port.group(1)}", key | |
| def make_client(args, url, key): | |
| sampling = {k: getattr(args, k) for k in ("temperature", "top_p", "top_k", "presence_penalty") | |
| if getattr(args, k) is not None} | |
| c = Client(url, key, think=args.think == "on", effort=args.effort, max_tokens=args.max_tokens, | |
| keep_thinking=args.keep_thinking, sampling=sampling) | |
| if not c.alive(): | |
| sys.exit(f"nothing answers at {c.root}/health") | |
| return c | |
| def settings_of(args, where): | |
| return dict(where=where, think=args.think, effort=args.effort, seeds=args.seeds, max_tokens=args.max_tokens, | |
| keep_thinking=args.keep_thinking, tasks=args.tasks or "all") | |
| def execute(args, runner): | |
| tag = "" if args.think == "on" else "-nothink" | |
| if args.serve: | |
| sys.path.insert(0, os.path.dirname(HERE)) | |
| import bench | |
| if bench.other_server_running(): | |
| sys.exit("another llama-server is running (Unsloth Studio?). Unload it first, or use --studio to test that one.") | |
| card = bench.vram() | |
| if card and card[1] - card[0] < bench.MIN_FREE_MIB: | |
| sys.exit(f"only {card[1] - card[0]} MiB of VRAM free, need {bench.MIN_FREE_MIB}.") | |
| for name in args.serve.split(","): | |
| if name not in bench.CONFIGS: | |
| sys.exit(f"unknown config '{name}'; see: python ../bench.py list") | |
| try: | |
| with bench.server(name) as info: | |
| client = make_client(args, bench.URL, None) | |
| runner(client, (args.label or name) + tag, args, dict(settings_of(args, "bench config " + name), | |
| server=info, flags=bench.CONFIGS[name][1])) | |
| except RuntimeError as e: | |
| print(f"{name}: could not run: {e}", flush=True) | |
| return | |
| if args.studio: | |
| url, key = find_studio() | |
| print(f"using the llama-server Unsloth Studio started at {url}") | |
| elif args.url: | |
| url, key = args.url, args.key | |
| else: | |
| sys.exit("say where the model is: --studio, --url URL [--key KEY], or --serve CONFIG") | |
| client = make_client(args, url, key) | |
| runner(client, (args.label or ("studio" if args.studio else "server")) + tag, args, settings_of(args, url)) | |
| # ---- comparing runs ------------------------------------------------------------------------------------------- | |
| def load_summary(name): | |
| path = name if os.path.isdir(name) else os.path.join(OUT, name) | |
| if name == "latest": | |
| runs = sorted(d for d in os.listdir(OUT) if not d.endswith("-toolcalls") | |
| and os.path.exists(os.path.join(OUT, d, "summary.json"))) | |
| if not runs: | |
| sys.exit("no saved runs yet") | |
| path = os.path.join(OUT, runs[-1]) | |
| if not os.path.exists(os.path.join(path, "summary.json")): | |
| sys.exit(f"no summary.json in {path}") | |
| with open(os.path.join(path, "summary.json"), encoding="utf-8") as fh: | |
| return json.load(fh) | |
| def compare_markdown(runs): | |
| """The same comparison as GitHub tables: one row per run, then one row per task.""" | |
| def row(cells): | |
| return "| " + " | ".join(cells) + " |" | |
| print(row(["run", "solved", "decode tok/s", "prefill tok/s", "seconds per solve", "tokens per solve", "malformed calls"])) | |
| print(row(["---"] * 7)) | |
| for r in runs: | |
| o = r["overall"] | |
| print(row([r["label"], f"{o['passed']}/{o['trials']}", f(o["decode_tok_s"]), f(o["prefill_tok_s"]), | |
| f(o["sec_per_pass"]), f(o["gen_tokens_per_pass"]), f"{o['bad_calls']}/{o['calls']}"])) | |
| ids = sorted({t for r in runs for t in r["tasks"]}) | |
| print() | |
| print(row(["task"] + [r["label"] for r in runs])) | |
| print(row(["---"] * (len(runs) + 1))) | |
| for t in ids: | |
| print(row([t] + [f"{r['tasks'][t]['passed']}/{r['tasks'][t]['trials']}" if t in r["tasks"] else "-" for r in runs])) | |
| def compare(names, markdown=False): | |
| runs = [load_summary(n) for n in names] | |
| if markdown: | |
| return compare_markdown(runs) | |
| w = 22 | |
| print(f"\n{'':<24}" + "".join(f"{r['label'][:w - 2]:<{w}}" for r in runs)) | |
| rows = [("solved", lambda o: f"{o['passed']}/{o['trials']} ({f(o['success_pct'], '%')})"), | |
| ("turns per solve", lambda o: f(o["turns_per_pass"])), | |
| ("malformed calls", lambda o: f"{o['bad_calls']}/{o['calls']} ({f(o['bad_pct'], '%')})"), | |
| ("failed edits", lambda o: str(o["failed_edits"])), | |
| ("decode tok/s", lambda o: f(o["decode_tok_s"])), | |
| ("prefill tok/s", lambda o: f(o["prefill_tok_s"])), | |
| ("guesses accepted", lambda o: f(o["accept_pct"], "%")), | |
| ("seconds per solve", lambda o: f(o["sec_per_pass"])), | |
| ("tokens per solve", lambda o: f(o["gen_tokens_per_pass"]))] | |
| for title, fn_ in rows: | |
| print(f"{title:<24}" + "".join(f"{fn_(r['overall']):<{w}}" for r in runs)) | |
| ids = sorted({t for r in runs for t in r["tasks"]}) | |
| print("\nper task (solved / tried)") | |
| for t in ids: | |
| cells = [] | |
| for r in runs: | |
| a = r["tasks"].get(t) | |
| cells.append(f"{a['passed']}/{a['trials']}" if a else "-") | |
| print(f"{t:<24}" + "".join(f"{c:<{w}}" for c in cells)) | |
| def rescore(name): | |
| """Judge the answer-only tasks of a saved run again with the current checks, after a check was fixed. | |
| Tasks judged on the project folder cannot be re-judged (the folder is gone) and are left alone.""" | |
| path = name if os.path.isdir(name) else os.path.join(OUT, name) | |
| with open(os.path.join(path, "trials.json"), encoding="utf-8") as fh: | |
| trials = json.load(fh) | |
| with open(os.path.join(path, "summary.json"), encoding="utf-8") as fh: | |
| summary = json.load(fh) | |
| by_id = {t["id"]: t for t in tasklib.pick()} | |
| changed = 0 | |
| for tr in trials: | |
| task = by_id.get(tr["task"]) | |
| if not task or not task["answers"]: | |
| continue | |
| with open(os.path.join(path, "transcripts", f"{tr['task']}-s{tr['seed']}.json"), encoding="utf-8") as fh: | |
| msgs = json.load(fh)["messages"] | |
| final = visible(msgs[-1].get("content")) if msgs[-1]["role"] == "assistant" and not msgs[-1].get("tool_calls") else "" | |
| sb = sandbox.Sandbox(task["files"]() if callable(task["files"]) else task["files"]) | |
| try: | |
| ok, detail = task["check"](sb, final) | |
| finally: | |
| sb.close() | |
| if bool(ok) != tr["ok"]: | |
| changed += 1 | |
| print(f"{tr['task']} seed {tr['seed']}: {'PASS' if tr['ok'] else 'FAIL'} -> {'PASS' if ok else 'FAIL'} ({detail})") | |
| tr.update(ok=bool(ok), detail=detail, **({"rescored": True} if bool(ok) != tr["ok"] else {})) | |
| dump(os.path.join(path, "trials.json"), trials) | |
| summary.update(overall=aggregate(trials), tasks=per_task(trials)) | |
| dump(os.path.join(path, "summary.json"), summary) | |
| print(f"{changed} trial(s) changed in {path}") | |
| report(summary["label"], summary["overall"], summary["tasks"]) | |
| # ---- selftest --------------------------------------------------------------------------------------------------- | |
| def assistant(calls, text="", raw=None): | |
| return {"role": "assistant", "content": text, "tool_calls": [ | |
| {"id": f"call_{i}", "type": "function", | |
| "function": {"name": n, "arguments": raw if raw is not None else json.dumps(a, ensure_ascii=False)}} | |
| for i, (n, a) in enumerate(calls)]} if calls else {"role": "assistant", "content": text} | |
| class Scripted: | |
| """A fake model that follows a fixed script, shaped like Client so the harness runs without a server.""" | |
| keep_thinking = False | |
| def __init__(self, steps): | |
| self.steps, self.i = list(steps), 0 | |
| def chat(self, messages, tools=None, seed=0): | |
| step = self.steps[self.i] if self.i < len(self.steps) else ("final", "Done.") | |
| self.i += 1 | |
| msg = assistant([], step[1]) if isinstance(step, tuple) and step[0] == "final" else assistant(step) | |
| t = {"predicted_n": 20, "predicted_ms": 250.0, "prompt_n": 100, "prompt_ms": 20.0, "cache_n": 50, | |
| "draft_n": 10, "draft_n_accepted": 8, "predicted_per_second": 80.0} | |
| return {"message": msg, "finish": "stop", "timings": t, "wall": 0.3} | |
| class Garbage: | |
| """Always answers with a broken call, to prove the loop stops and the bad calls are counted.""" | |
| keep_thinking = False | |
| def __init__(self): | |
| self.n = 0 | |
| def chat(self, messages, tools=None, seed=0): | |
| self.n += 1 | |
| msg = assistant([("read_file", {})], raw="{oops") if self.n % 2 else assistant([("fly_to_moon", {"x": 1})]) | |
| return {"message": msg, "finish": "stop", "timings": {}, "wall": 0.0} | |
| def selftest(): | |
| bad = [] | |
| def expect(cond, what): | |
| if not cond: | |
| bad.append(what) | |
| bad += toolcalls.selftest() | |
| chosen = tasklib.pick() | |
| expect(len({t["id"] for t in chosen}) == len(chosen), "duplicate task ids") | |
| trials = [] | |
| for t in chosen: | |
| res, _ = run_trial(Scripted(t["reference"]), t, 1) | |
| trials.append(res) | |
| expect(res["ok"], f"{t['id']}: the reference solution was rejected: {res['detail']} {res['error'] or ''}") | |
| expect(res["bad"] == 0, f"{t['id']}: the reference solution made {res['bad']} malformed call(s)") | |
| lazy, _ = run_trial(Scripted([("final", "All done.")]), t, 1) | |
| expect(not lazy["ok"], f"{t['id']}: a model that does nothing was accepted") | |
| for n, alt in enumerate(t["alternatives"], 1): | |
| res_alt, _ = run_trial(Scripted(alt), t, 1) | |
| expect(res_alt["ok"], f"{t['id']}: alternative solution {n} was rejected: {res_alt['detail']}") | |
| for text, should_pass in t["answers"]: | |
| sb2 = sandbox.Sandbox(t["files"]() if callable(t["files"]) else t["files"]) | |
| try: | |
| got, _ = t["check"](sb2, text) | |
| finally: | |
| sb2.close() | |
| expect(bool(got) == should_pass, | |
| f"{t['id']}: the answer {text[:50]!r} was {'accepted' if got else 'rejected'} but should be " | |
| f"{'accepted' if should_pass else 'rejected'}") | |
| junk, _ = run_trial(Garbage(), chosen[0], 1) | |
| expect(not junk["ok"] and junk["bad"] >= 3 and junk["turns"] == chosen[0]["max_turns"], | |
| f"garbage calls: ok={junk['ok']} bad={junk['bad']} turns={junk['turns']}") | |
| agg = aggregate(trials) | |
| expect(agg["passed"] == len(chosen) and agg["decode_tok_s"] == 80.0 and agg["accept_pct"] == 80.0, | |
| f"aggregate numbers are off: {agg}") | |
| # the tool-call path, through the same parsing a live run uses | |
| for c in toolcalls.CASES: | |
| text = "Which one? Tell me." if c["ask"] else "Here you go." | |
| ok, d = score_reply(c, assistant(c["oracle"], "" if c["oracle"] else text)) | |
| expect(ok, f"{c['id']}: parsed oracle reply rejected: {d}") | |
| ok, _ = score_reply(c, assistant(c["wrong"])) | |
| expect(not ok, f"{c['id']}: parsed wrong reply accepted") | |
| ok, d = score_reply(toolcalls.CASES[0], assistant([("get_weather", {})], raw="{oops")) | |
| expect(not ok and "valid JSON" in d, f"broken JSON not reported: {d}") | |
| expect(visible("<think>hmm</think>\nAnswer") == "Answer" and visible("hmm</think> Answer") == "Answer", | |
| "visible() does not strip thinking") | |
| # the sandbox must stay inside its folder and refuse arbitrary commands | |
| sb = sandbox.Sandbox({"a.txt": "x\n", "s.py": "print(1)\n", "d/b.txt": "y\n"}) | |
| try: | |
| escapes = [("read_file", {"path": "../a.txt"}), ("read_file", {"path": os.path.abspath(sys.executable)}), | |
| ("write_file", {"path": "../evil.txt", "content": "x"}), ("list_dir", {"path": ".."}), | |
| ("grep", {"pattern": "x", "path": ".."}), ("edit_file", {"path": "../a.txt", "old_text": "x", "new_text": "y"}), | |
| ("run", {"command": "python -m http.server"}), ("run", {"command": "python ../s.py"}), | |
| ("run", {"command": "node --version"}), ("run", {"command": "python -c"}), | |
| ("run", {"command": "cmd /c dir"}), ("run", {"command": "rm a.txt"})] | |
| for name, a in escapes: | |
| text, status = sb.call(name, a) | |
| expect(status == "fail", f"sandbox let this through: {name} {a} -> {status}: {text[:80]}") | |
| expect(sb.call("nope", {})[1] == "bad" and sb.call("read_file", {"path": 5})[1] == "bad" | |
| and sb.call("read_file", {})[1] == "bad", "malformed calls are not reported as bad") | |
| expect(sb.call("run", {"command": "python s.py"})[0].strip().endswith("1"), "run does not run a script") | |
| expect(sb.call("run", {"command": 'python -c "print(1 + 1)"'})[0].strip().endswith("2"), "python -c does not run") | |
| expect(sb.call("run", {"command": "node -e \"console.log(3)\""})[0].strip().endswith("3"), "node -e does not run") | |
| sb.put("dup.txt", "a\na\n") | |
| expect(sb.call("edit_file", {"path": "dup.txt", "old_text": "a", "new_text": "b"})[1] == "fail", | |
| "edit_file accepted a non-unique match") | |
| expect(sb.call("edit_file", {"path": "dup.txt", "old_text": "zzz", "new_text": "b"})[1] == "fail", | |
| "edit_file accepted a missing match") | |
| expect(not os.path.exists(os.path.join(os.path.dirname(str(sb.root)), "evil.txt")), "a file escaped the sandbox") | |
| finally: | |
| sb.close() | |
| expect(not os.path.exists(str(sb.root)), "the sandbox folder was not removed") | |
| # results can be saved, loaded and compared | |
| with tempfile.TemporaryDirectory() as tmp: | |
| s = dict(label="a", overall=agg, tasks=per_task(trials)) | |
| dump(os.path.join(tmp, "summary.json"), s) | |
| expect(load_summary(tmp)["label"] == "a", "saved summary cannot be loaded") | |
| if bad: | |
| print("SELFTEST FAILED:") | |
| for b in bad: | |
| print(" -", b) | |
| sys.exit(1) | |
| print(f"selftest ok: {len(chosen)} tasks (reference solutions pass, a lazy model fails), " | |
| f"{len(toolcalls.CASES)} tool-call cases, sandbox limits, broken-call handling, aggregation.") | |
| def show_list(): | |
| print(f"{'task':<26}{'level':<8}{'kind':<11}{'turns':>5} title") | |
| for t in tasklib.pick(): | |
| print(f"{t['id']:<26}{t['difficulty']:<8}{t['kind']:<11}{t['max_turns']:>5} {t['title']}") | |
| print(f"\n{'tool-call case':<26}kind") | |
| for c in toolcalls.CASES: | |
| print(f"{c['id']:<26}{c['kind']}") | |
| def main(): | |
| for stream in (sys.stdout, sys.stderr): | |
| stream.reconfigure(encoding="utf-8", errors="replace") | |
| ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| sub = ap.add_subparsers(dest="cmd", required=True) | |
| sub.add_parser("list") | |
| sub.add_parser("selftest") | |
| cmp_ = sub.add_parser("compare") | |
| cmp_.add_argument("runs", nargs="+", help="results folders (names under eval/results, paths, or 'latest')") | |
| cmp_.add_argument("--md", action="store_true", help="print GitHub markdown tables instead") | |
| resc = sub.add_parser("rescore", help="re-judge the answer-only tasks of a saved run after fixing a check") | |
| resc.add_argument("run", help="a results folder") | |
| for name in ("run", "toolcalls"): | |
| p = sub.add_parser(name) | |
| where = p.add_mutually_exclusive_group() | |
| where.add_argument("--studio", action="store_true", help="the llama-server Unsloth Studio is running") | |
| where.add_argument("--url", help="any OpenAI-compatible server, e.g. http://127.0.0.1:8080") | |
| where.add_argument("--serve", help="start our own llama-server with these bench.py configs (comma list)") | |
| p.add_argument("--key", help="API key for --url") | |
| p.add_argument("--tasks", help="only tasks whose id starts with one of these, comma separated (t01,t05)") | |
| p.add_argument("--seeds", type=int, default=1, help="attempts per task (default 1)") | |
| p.add_argument("--think", choices=["on", "off"], default="on") | |
| p.add_argument("--effort", choices=["low", "medium", "high"], help="reasoning_effort template argument") | |
| p.add_argument("--max-tokens", type=int, default=16384, help="per reply, thinking included (default 16384)") | |
| p.add_argument("--keep-thinking", action="store_true", help="send earlier thinking back with each request") | |
| p.add_argument("--temperature", type=float) | |
| p.add_argument("--top-p", dest="top_p", type=float) | |
| p.add_argument("--top-k", dest="top_k", type=int) | |
| p.add_argument("--presence-penalty", dest="presence_penalty", type=float) | |
| p.add_argument("--label", help="name for the results folder") | |
| p.add_argument("--verbose", action="store_true") | |
| args = ap.parse_args() | |
| if args.cmd == "list": | |
| show_list() | |
| elif args.cmd == "selftest": | |
| selftest() | |
| elif args.cmd == "compare": | |
| compare(args.runs, args.md) | |
| elif args.cmd == "rescore": | |
| rescore(args.run) | |
| elif args.cmd == "run": | |
| execute(args, run_suite) | |
| else: | |
| execute(args, run_toolcalls) | |
| if __name__ == "__main__": | |
| main() | |