five-desks-control / source /scripts /failure_study.py
rca-umb's picture
Five Desks v5 (control)
7f7e3bf verified
Raw History Blame Contribute Delete
6.46 kB
"""Why does the untrained model fail? Play Qwen3.8-27B on other entrants' environments and record how each episode ends.
Arena rules (strict): a reply that is not exactly one JSON object ends the episode. To see what that rule costs,
this runner keeps playing when a reply has text around a valid JSON action (lenient continuation) but records every
reply's format, so each episode yields both outcomes:
strict_reward = the reward if the episode had ended at the first non-strict reply (scored as 0 here)
lenient_reward = the reward with the format problem forgiven
Transcripts are written locally only (they contain other entrants' task text) and are never published.
Usage: HF_TOKEN_PATH=... .venv/bin/python scripts/failure_study.py --env NAME=URL --tasks a,b --samples 2 --out DIR
"""
import argparse
import json
import random
import sys
import time
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from calibrate import Model, first_json_object, system_prompt # noqa: E402
from proxy_eval.run import classify, unwrap # noqa: E402
from wsclient import Session # noqa: E402
MAX_TURNS = 40
def play(url, model, schema, task_id, budgets, extra=""):
messages = [{"role": "system", "content": system_prompt(schema) + extra}]
ep = {"task_id": task_id, "turns": 0, "end": None, "reward": 0.0, "formats": [], "first_bad_turn": None,
"reply_tokens": 0, "obs_chars": 0}
completion, first = 0, True
with Session(url, timeout=180) as s:
data = s.reset(task_id=task_id)
while ep["turns"] < MAX_TURNS:
obs = json.dumps({k: v for k, v in data["observation"].items() if k != "metadata" or v})
messages.append({"role": "user", "content": obs})
ep["obs_chars"] += len(obs)
if not first:
completion += len(obs) // 3
first = False
if completion >= budgets[0] or sum(len(m["content"]) for m in messages) // 3 >= budgets[1]:
ep["end"] = "budget"
break
reply, used, finish_reason = model.chat(messages)
completion += used
ep["reply_tokens"] += used
messages.append({"role": "assistant", "content": reply})
ep["turns"] += 1
if finish_reason == "length":
ep["formats"].append("truncated")
ep["end"] = "truncated"
break
obj, kind = classify(reply)
fmt = kind or "clean"
if kind and (rescued := first_json_object(reply)) is not None:
obj = rescued # forgive text around a valid JSON action, but remember it
elif kind:
ep["formats"].append(fmt)
ep["end"] = fmt
break
ep["formats"].append(fmt)
if fmt != "clean" and ep["first_bad_turn"] is None:
ep["first_bad_turn"] = ep["turns"]
action = unwrap(obj)
if action.get("finish") is True:
ep["end"] = "finish"
break
try:
data = s.step(action)
except RuntimeError as exc: # the server rejected the action (schema)
ep["end"] = "schema_invalid"
ep["error"] = str(exc)[:200]
break
if data["done"]:
ep["end"], ep["reward"] = "done", float(data.get("reward") or 0.0)
break
else:
ep["end"] = "max_turns"
ep["lenient_reward"] = ep["reward"]
ep["strict_reward"] = ep["reward"] if ep["first_bad_turn"] is None and ep["end"] == "done" else 0.0
return ep, messages[1:]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--env", required=True, help="NAME=URL")
ap.add_argument("--tasks", required=True)
ap.add_argument("--samples", type=int, default=2)
ap.add_argument("--workers", type=int, default=8)
ap.add_argument("--model", default="Qwen/Qwen3.8-27B:deepinfra")
ap.add_argument("--max-tokens", type=int, default=2048)
ap.add_argument("--completion-budget", type=int, default=16384)
ap.add_argument("--context-budget", type=int, default=32768)
ap.add_argument("--system-extra", default="", help="file appended to the system prompt")
ap.add_argument("--out", required=True)
args = ap.parse_args()
extra = "\n\n" + Path(args.system_extra).read_text().strip() if args.system_extra else ""
name, url = args.env.split("=", 1)
schema = json.load(urllib.request.urlopen(url.rstrip("/") + "/schema"))["action"]
model = Model(args.model, args.max_tokens, 1.0)
jobs = [t for t in args.tasks.split(",") for _ in range(args.samples)]
random.Random(0).shuffle(jobs)
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
started, results = time.monotonic(), []
with ThreadPoolExecutor(args.workers) as pool, open(out / "episodes.jsonl", "w") as log, \
open(out / "transcripts.jsonl", "w") as tr:
futures = [pool.submit(play, url, model, schema, t, (args.completion_budget, args.context_budget), extra)
for t in jobs]
for fut in futures:
try:
ep, messages = fut.result()
except Exception as exc: # noqa: BLE001 infrastructure errors are excluded, not scored
print("episode error:", repr(exc)[:300], file=sys.stderr)
continue
ep["env"] = name
results.append(ep)
log.write(json.dumps(ep) + "\n")
log.flush()
tr.write(json.dumps({**ep, "messages": messages}) + "\n")
n = max(1, len(results))
ends = {}
for e in results:
ends[e["end"]] = ends.get(e["end"], 0) + 1
report = {"env": name, "episodes": len(results), "seconds": round(time.monotonic() - started), "usage": model.usage,
"lenient_mean": round(sum(e["lenient_reward"] for e in results) / n, 3),
"strict_mean": round(sum(e["strict_reward"] for e in results) / n, 3),
"episodes_with_text_around_json": sum(e["first_bad_turn"] is not None for e in results), "ends": ends}
(out / "summary.json").write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps(report))
if __name__ == "__main__":
main()