File size: 8,420 Bytes
e042d72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
"""Play Qwen3.8-27B (thinking off) on the proxy tasks with arena-style prompts.

Each episode is scored twice from one conversation:
- strict: the arena's rule. A reply that is not exactly one JSON object, or an action that fails the task's
  schema, ends the episode and the task scores its finish_action.
- lenient: the conversation continues (first JSON object in the reply is used; schema errors are reported back
  to the model), to show what the model would reach without format failures.

Usage: HF_TOKEN_PATH=... .venv/bin/python -m proxy_eval.run --samples 2 --out reports/proxy/run1
"""

import argparse
import copy
import json
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from statistics import mean

from pydantic import ValidationError

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))

from calibrate import Model, first_json_object, system_prompt  # noqa: E402

from .tasks import FAMILIES  # noqa: E402


def classify(reply: str):
    s = reply.strip()
    if not s:
        return None, "empty"
    try:
        obj = json.loads(s)
        return (obj, None) if isinstance(obj, dict) else (None, "not_object")
    except json.JSONDecodeError:
        pass
    if s.startswith("```"):
        return None, "code_fence"
    if first_json_object(s) is not None:
        return None, "json_plus_text"
    return None, "no_json"


def unwrap(action):
    if isinstance(action, dict) and set(action) == {"action"} and isinstance(action["action"], dict):
        return action["action"]
    return action


def finish_score(task):
    """Reward the arena would record if the episode were ended now through finish_action."""
    if task.done:
        return None
    try:
        clone = copy.deepcopy(task)
    except TypeError:  # tasks holding a database connection score 0 on an empty finish
        return 0.0
    return clone.step(clone.Action.model_validate(task.finish_action)).reward


def play(task, model, completion_budget, context_budget, system_extra=""):
    schema = task.Action.model_json_schema()
    messages = [{"role": "system", "content": system_prompt(schema) + system_extra}]
    obs = task.reset()
    ep = {"task_id": task.task_id, "family": task.family, "domain": task.domain, "turns": [],
          "strict": None, "lenient": None, "strict_end": None, "lenient_end": None, "schema_errors": 0}
    completion_used = 0
    first = True

    def strict_fail(kind):
        if ep["strict"] is None:
            ep["strict"], ep["strict_end"] = finish_score(task) or 0.0, kind

    while True:
        obs_text = json.dumps(obs)
        messages.append({"role": "user", "content": obs_text})
        if not first:
            completion_used += len(obs_text) // 3
        first = False
        if completion_used >= completion_budget or sum(len(m["content"]) for m in messages) // 3 >= context_budget:
            strict_fail("budget")
            ep["lenient"], ep["lenient_end"] = finish_score(task) or 0.0, "budget"
            break
        reply, used, finish_reason = model.chat(messages)
        completion_used += used
        messages.append({"role": "assistant", "content": reply})
        ep["turns"].append({"obs": obs_text[:1500], "reply": reply[:1500], "tokens": used})
        if finish_reason == "length":
            strict_fail("truncated")
            ep["lenient"], ep["lenient_end"] = finish_score(task) or 0.0, "truncated"
            break
        strict_obj, kind = classify(reply)
        if kind:
            strict_fail(kind)
        action = unwrap(strict_obj if strict_obj is not None else first_json_object(reply))
        if action is None:
            ep["lenient"], ep["lenient_end"] = finish_score(task) or 0.0, kind
            break
        if action.get("finish") is True:
            score = finish_score(task) or 0.0
            strict_fail("finish")
            ep["lenient"], ep["lenient_end"] = score, "finish"
            break
        try:
            parsed = task.Action.model_validate(action)
        except ValidationError as exc:
            ep["schema_errors"] += 1
            strict_fail("schema_invalid")
            errors = "; ".join(f"{'.'.join(map(str, e['loc']))}: {e['msg']}" for e in exc.errors()[:3])
            obs = {"error": f"Invalid action: {errors}"}
            if task.steps + ep["schema_errors"] > task.max_steps + 3:
                ep["lenient"], ep["lenient_end"] = finish_score(task) or 0.0, "schema_invalid"
                break
            continue
        step = task.step(parsed)
        obs = step.observation
        if step.done:
            if ep["strict"] is None:
                ep["strict"], ep["strict_end"] = step.reward, "done"
            ep["lenient"], ep["lenient_end"] = step.reward, "done"
            break
    ep["n_turns"] = len(ep["turns"])
    return ep


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--model", default="Qwen/Qwen3.8-27B:deepinfra")
    parser.add_argument("--families", default="", help="comma-separated family prefixes (default: all)")
    parser.add_argument("--seeds", default="0-4")
    parser.add_argument("--samples", type=int, default=2)
    parser.add_argument("--workers", type=int, default=8)
    parser.add_argument("--temperature", type=float, default=1.0)
    parser.add_argument("--max-tokens", type=int, default=2048)
    parser.add_argument("--completion-budget", type=int, default=8192)
    parser.add_argument("--context-budget", type=int, default=16384)
    parser.add_argument("--thinking", action="store_true", help="enable the model's thinking mode")
    parser.add_argument("--system-extra", default="", help="file whose text is appended to the system prompt "
                        "(to imitate a model that has learned a habit)")
    parser.add_argument("--out", required=True)
    args = parser.parse_args()
    extra = "\n\n" + Path(args.system_extra).read_text().strip() if args.system_extra else ""

    lo, hi = map(int, args.seeds.split("-"))
    fams = [f for f in FAMILIES if not args.families or any(f.startswith(p) for p in args.families.split(","))]
    jobs = [(f, s) for f in fams for s in range(lo, hi + 1) for _ in range(args.samples)]
    model = Model(args.model, args.max_tokens, args.temperature, args.thinking)
    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    started, results = time.monotonic(), []

    def run(job):
        fam, seed = job
        return play(FAMILIES[fam](seed), model, args.completion_budget, args.context_budget, extra)

    with ThreadPoolExecutor(args.workers) as pool, open(out / "episodes.jsonl", "w") as log:
        for fut in [pool.submit(run, j) for j in jobs]:
            try:
                ep = fut.result()
            except Exception as exc:  # 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()

    summary = {}
    for fam in fams:
        eps = [e for e in results if e["family"] == fam]
        if not eps:
            continue
        ends = {}
        for e in eps:
            ends[e["strict_end"]] = ends.get(e["strict_end"], 0) + 1
        summary[fam] = {"n": len(eps), "strict": round(mean(e["strict"] for e in eps), 3),
                        "lenient": round(mean(e["lenient"] for e in eps), 3), "strict_ends": ends,
                        "turns": round(mean(e["n_turns"] for e in eps), 1)}
    report = {"model": args.model, "system_extra": args.system_extra, "temperature": args.temperature, "thinking": args.thinking, "episodes": len(results),
              "seconds": round(time.monotonic() - started), "usage": model.usage, "families": summary,
              "overall": {"strict": round(mean(e["strict"] for e in results), 3),
                          "lenient": round(mean(e["lenient"] for e in results), 3)}}
    (out / "summary.json").write_text(json.dumps(report, indent=2) + "\n")
    print(f"{'family':24s} {'n':>3s} {'strict':>6s} {'lenient':>7s}  strict ends")
    for fam, s in summary.items():
        print(f"{fam:24s} {s['n']:3d} {s['strict']:6.2f} {s['lenient']:7.2f}  {s['strict_ends']}")
    print("overall", report["overall"], "usage", model.usage, "seconds", report["seconds"])


if __name__ == "__main__":
    main()