Download source/scripts/calibrate_v2.py from rca-umb/five-desks-code: direct link, hf CLI and curl.
- Browser
- Download file 7.08 kB
-
https://huggingface.co/datasets/rca-umb/five-desks-code/resolve/main/source/scripts/calibrate_v2.py
- Command line
-
hf download hf://datasets/rca-umb/five-desks-code/source/scripts/calibrate_v2.py
-
curl -L -o calibrate_v2.py https://huggingface.co/datasets/rca-umb/five-desks-code/resolve/main/source/scripts/calibrate_v2.py
7.08 kB
| """Calibrate Five Desks against Qwen3.8-27B (thinking off) under the arena's reply rules. | |
| A reply that is not exactly one JSON object, or an action that fails the schema, ends the episode through the | |
| finish action. With --lenient, a reply with text around one JSON object is played instead: the v2 run showed the | |
| arena accepts those (industrial trained at 0.80 against 0.31 measured strictly), and v1's lenient calibration | |
| matched its arena run. The token is read in-process via HF_TOKEN_PATH and never printed. | |
| Usage: HF_TOKEN_PATH=... .venv/bin/python scripts/calibrate_v2.py --url http://localhost:8001 --episodes 8 --out reports/calibration-v2/run1 | |
| """ | |
| import argparse | |
| import json | |
| import random | |
| import sys | |
| import time | |
| import urllib.request | |
| from concurrent.futures import ThreadPoolExecutor | |
| from pathlib import Path | |
| from statistics import mean | |
| sys.path.insert(0, str(Path(__file__).resolve().parents[1])) | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| from pydantic import ValidationError # noqa: E402 | |
| from calibrate import Model, first_json_object, system_prompt # noqa: E402 | |
| from diligence.environment import TASK_IDS # noqa: E402 | |
| from diligence.models import ToolAction # noqa: E402 | |
| from proxy_eval.run import classify, unwrap # noqa: E402 | |
| from wsclient import Session # noqa: E402 | |
| FINISH = {"tool": "submit", "args": {}} | |
| def play(url, model, schema, task_id, completion_budget, context_budget, extra="", lenient=False): | |
| messages = [{"role": "system", "content": system_prompt(schema) + extra}] | |
| ep = {"task_id": task_id, "turns": [], "end": None, "reward": 0.0, "bad_args": 0, "rescued": 0} | |
| used_total, first = 0, True | |
| with Session(url, timeout=60) as s: | |
| ep["seed"] = random.SystemRandom().randrange(2**48) | |
| data = s.reset(task_id=task_id, seed=ep["seed"]) | |
| while True: | |
| obs = json.dumps({k: v for k, v in data["observation"].items() if k != "metadata" or v}) | |
| messages.append({"role": "user", "content": obs}) | |
| if not first: | |
| used_total += len(obs) // 3 | |
| first = False | |
| if used_total >= completion_budget or sum(len(m["content"]) for m in messages) // 3 >= context_budget: | |
| ep["end"], data = "budget", s.step(FINISH) | |
| break | |
| reply, used, finish_reason = model.chat(messages) | |
| used_total += used | |
| messages.append({"role": "assistant", "content": reply}) | |
| ep["turns"].append({"obs": obs[:2500], "reply": reply[:2500]}) | |
| if finish_reason == "length": | |
| ep["end"], data = "truncated", s.step(FINISH) | |
| break | |
| obj, kind = classify(reply) | |
| if kind and lenient and (rescued := first_json_object(reply)) is not None: | |
| obj, kind = rescued, None | |
| ep["rescued"] += 1 | |
| if kind: | |
| ep["end"], data = kind, s.step(FINISH) | |
| break | |
| action = unwrap(obj) | |
| if action.get("finish") is True: | |
| ep["end"], data = "finish", s.step(FINISH) | |
| break | |
| try: | |
| ToolAction.model_validate(action) | |
| except ValidationError: | |
| ep["end"], data = "schema_invalid", s.step(FINISH) | |
| break | |
| data = s.step(action) | |
| out = data["observation"].get("output", "") | |
| if out.startswith(("Unknown tool", "Unknown argument", "Missing argument")) or "must be a" in out[:80]: | |
| ep["bad_args"] += 1 | |
| if data["done"]: | |
| ep["end"] = "submitted" if out.startswith("Submitted") else "out_of_steps" | |
| break | |
| ep["reward"] = data.get("reward") or 0.0 | |
| ep["n_turns"] = len(ep["turns"]) | |
| return ep | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--url", default="http://localhost:8001") | |
| ap.add_argument("--model", default="Qwen/Qwen3.8-27B:deepinfra") | |
| ap.add_argument("--episodes", type=int, default=8) | |
| ap.add_argument("--tasks", default="") | |
| ap.add_argument("--task-ids", default="", help="explicit comma-separated task ids (for other servers)") | |
| ap.add_argument("--workers", type=int, default=8) | |
| ap.add_argument("--temperature", type=float, default=1.0) | |
| ap.add_argument("--max-tokens", type=int, default=2048) | |
| ap.add_argument("--completion-budget", type=int, default=8192) | |
| ap.add_argument("--context-budget", type=int, default=16384) | |
| ap.add_argument("--system-extra", default="", help="file appended to the system prompt") | |
| ap.add_argument("--lenient", action="store_true", help="play the JSON object out of replies with extra text") | |
| ap.add_argument("--out", required=True) | |
| args = ap.parse_args() | |
| tasks = args.task_ids.split(",") if args.task_ids else [ | |
| t for t in TASK_IDS if not args.tasks or any(t.startswith(p) for p in args.tasks.split(","))] | |
| with urllib.request.urlopen(f"{args.url}/schema", timeout=15) as r: | |
| schema = json.load(r)["action"] | |
| model = Model(args.model, args.max_tokens, args.temperature) | |
| extra = "\n\n" + Path(args.system_extra).read_text().strip() if args.system_extra else "" | |
| out = Path(args.out) | |
| out.mkdir(parents=True, exist_ok=True) | |
| started, results = time.monotonic(), [] | |
| jobs = [t for t in tasks for _ in range(args.episodes)] | |
| with ThreadPoolExecutor(args.workers) as pool, open(out / "episodes.jsonl", "w") as log: | |
| for fut in [pool.submit(play, args.url, model, schema, t, args.completion_budget, args.context_budget, extra, args.lenient) for t in jobs]: | |
| try: | |
| ep = fut.result() | |
| except Exception as exc: # infrastructure errors are excluded, not scored | |
| print("episode error:", repr(exc)[:200], file=sys.stderr) | |
| continue | |
| results.append(ep) | |
| log.write(json.dumps(ep) + "\n") | |
| log.flush() | |
| summary = {} | |
| for t in tasks: | |
| eps = [e for e in results if e["task_id"] == t] | |
| if not eps: | |
| continue | |
| ends = {} | |
| for e in eps: | |
| ends[e["end"]] = ends.get(e["end"], 0) + 1 | |
| summary[t] = {"n": len(eps), "mean": round(mean(e["reward"] for e in eps), 3), | |
| "solved": sum(e["reward"] == 1.0 for e in eps), "rewards": [e["reward"] for e in eps], | |
| "ends": ends, "turns": round(mean(e["n_turns"] for e in eps), 1), | |
| "rescued_replies": sum(e.get("rescued", 0) for e in eps)} | |
| report = {"model": args.model, "lenient": args.lenient, "episodes": len(results), "seconds": round(time.monotonic() - started), | |
| "usage": model.usage, "tasks": summary} | |
| (out / "summary.json").write_text(json.dumps(report, indent=2) + "\n") | |
| print(f"{'task':24s} {'mean':>5s} solved ends") | |
| for t, s in summary.items(): | |
| print(f"{t:24s} {s['mean']:5.2f} {s['solved']:2d}/{s['n']:<2d} {s['ends']}") | |
| print("usage:", model.usage, "seconds:", report["seconds"]) | |
| if __name__ == "__main__": | |
| main() | |