File size: 6,443 Bytes
ab59633
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Play Qwen3.8-27B on any OpenEnv server under arena rules, optionally with extra system-prompt text.

Used to check transfer: does a model that behaves the way Five Desks v2 rewards (imitated with a hint or with
demonstrations in the system prompt) do better on other people's environments?

Rules follow the arena guide: arena-style system prompt with the server's action schema; reset observation
as the first user turn, later observations as JSON user turns; a reply that is not exactly one JSON object,
an action the server rejects, or an exhausted token budget ends the episode (scored 0 here, the same in every
arm); unseeded resets.

Usage: HF_TOKEN_PATH=... .venv/bin/python scripts/transfer_eval.py --url http://localhost:8021 \
           --tasks a,b,c --samples 3 [--system-extra file] --out reports/transfer/far-x
"""

import argparse
import json
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().parent))
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from calibrate import Model, 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, extra, budgets, count, transcripts=None):
    messages = [{"role": "system", "content": system_prompt(schema) + extra}]
    ep = {"task_id": task_id, "turns": 0, "end": None, "reward": 0.0}
    if transcripts is not None:
        transcripts.append((ep, messages))  # kept local: holds other environments' task text
    completion, first = 0, True
    with Session(url, timeout=120) as s:
        data = s.reset(task_id=task_id)
        for _ in range(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})
            if not first:
                completion += count(obs)
            first = False
            if completion >= budgets[0] or sum(count(m["content"]) for m in messages) >= budgets[1]:
                ep["end"] = "budget"
                return ep
            reply, used, finish_reason = model.chat(messages)
            completion += used
            messages.append({"role": "assistant", "content": reply})
            ep["turns"] += 1
            if finish_reason == "length":
                ep["end"] = "truncated"
                return ep
            obj, kind = classify(reply)
            if kind:
                ep["end"] = kind
                return ep
            action = unwrap(obj)
            if action.get("finish") is True:
                ep["end"] = "finish"
                return ep
            try:
                data = s.step(action)
            except RuntimeError:  # the server rejected the action (schema)
                ep["end"] = "schema_invalid"
                return ep
            if data["done"]:
                ep["end"], ep["reward"] = "done", float(data.get("reward") or 0.0)
                return ep
    ep["end"] = "max_turns"
    return ep


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--url", required=True)
    ap.add_argument("--tasks", required=True)
    ap.add_argument("--samples", type=int, default=3)
    ap.add_argument("--workers", type=int, default=8)
    ap.add_argument("--system-extra", default="")
    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=8192)
    ap.add_argument("--context-budget", type=int, default=16384)
    ap.add_argument("--tokenizer", default="")
    ap.add_argument("--out", required=True)
    ap.add_argument("--save-transcripts", action="store_true", help="also write transcripts.jsonl (do not publish)")
    args = ap.parse_args()

    extra = "\n\n" + Path(args.system_extra).read_text().strip() if args.system_extra else ""
    schema = json.load(urllib.request.urlopen(args.url.rstrip("/") + "/schema"))["action"]
    if args.tokenizer:
        from tokenizers import Tokenizer
        tok = Tokenizer.from_file(args.tokenizer)
        count = lambda text: len(tok.encode(text).ids)  # noqa: E731
    else:
        count = lambda text: len(text) // 3  # noqa: E731
    model = Model(args.model, args.max_tokens, 1.0)
    tasks = args.tasks.split(",")
    jobs = [t for t in tasks for _ in range(args.samples)]
    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    started, results = time.monotonic(), []
    transcripts = [] if args.save_transcripts else None
    with ThreadPoolExecutor(args.workers) as pool, open(out / "episodes.jsonl", "w") as log:
        futures = [pool.submit(play, args.url, model, schema, t, extra, (args.completion_budget, args.context_budget),
                               count, transcripts) for t in jobs]
        for fut in futures:
            try:
                ep = fut.result()
            except Exception as exc:  # noqa: BLE001  infrastructure errors are excluded, not scored
                print("episode error:", repr(exc)[:300], file=sys.stderr)
                continue
            results.append(ep)
            log.write(json.dumps(ep) + "\n")
            log.flush()
    per_task = {t: round(mean(e["reward"] for e in results if e["task_id"] == t), 3)
                for t in tasks if any(e["task_id"] == t for e in results)}
    ends = {}
    for e in results:
        ends[e["end"]] = ends.get(e["end"], 0) + 1
    report = {"url": args.url, "system_extra": args.system_extra, "episodes": len(results),
              "mean_reward": round(mean(e["reward"] for e in results), 3),
              "solved": sum(e["reward"] >= 0.999 for e in results), "ends": ends, "per_task": per_task,
              "mean_turns": round(mean(e["turns"] for e in results), 1), "usage": model.usage,
              "seconds": round(time.monotonic() - started)}
    if transcripts is not None:
        with open(out / "transcripts.jsonl", "w") as f:
            for ep, messages in transcripts:
                f.write(json.dumps({**ep, "messages": messages[1:]}) + "\n")
    (out / "summary.json").write_text(json.dumps(report, indent=2) + "\n")
    print(json.dumps({k: v for k, v in report.items() if k != "per_task"}))


if __name__ == "__main__":
    main()