File size: 10,247 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
"""Play Qwen3.8-27B (thinking off) against a running server to measure per-task solve rates.

The HF token is read inside this process via huggingface_hub (HF_TOKEN_PATH selects the file);
it is never printed or written anywhere.

Usage: HF_TOKEN_PATH=... python scripts/calibrate.py --url http://localhost:8000 --episodes 4 --out reports/calibration/run1
"""

import argparse
import json
import random
import re
import sys
import threading
import time
import urllib.error
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 huggingface_hub import get_token  # noqa: E402
from pydantic import ValidationError  # noqa: E402

from five_desks.models import DeskAction  # noqa: E402
from five_desks.tasks import TASK_IDS  # noqa: E402
from wsclient import Session  # noqa: E402

ROUTER = "https://router.huggingface.co/v1/chat/completions"
FINISH_ACTION = {"tool": "submit", "answer": {}}
_decoder = json.JSONDecoder(strict=False)


def system_prompt(action_schema: dict) -> str:
    return (
        "You are an agent acting in an environment. Reply to every message with exactly one JSON object and "
        "nothing else: an action that matches the action schema below, or {\"finish\": true} to end the episode.\n"
        f"Action schema: {json.dumps(action_schema)}"
    )


def first_json_object(text: str):
    text = re.sub(r"<think>.*?</think>", "", text or "", flags=re.S)
    for match in re.finditer(r"\{", text):
        try:
            obj, _ = _decoder.raw_decode(text[match.start():])
            if isinstance(obj, dict):
                return obj
        except json.JSONDecodeError:
            continue
    return None


class Model:
    def __init__(self, model: str, max_tokens: int, temperature: float, thinking: bool = False):
        self.model, self.max_tokens, self.temperature, self.thinking = model, max_tokens, temperature, thinking
        self._token = get_token()
        if not self._token:
            raise SystemExit("No Hugging Face token found (set HF_TOKEN_PATH).")
        self.usage = {"prompt_tokens": 0, "completion_tokens": 0, "calls": 0}
        self._lock = threading.Lock()
        self.empty_examples = []

    def chat(self, messages):
        # Some provider responses come back with no content at all; retry those rather than score them.
        for _ in range(3):
            content, used, finish = self._chat_once(messages)
            if content.strip() or finish == "length":
                break
        return content, used, finish

    def _chat_once(self, messages):
        body = {"model": self.model, "messages": messages, "max_tokens": self.max_tokens,
                "temperature": self.temperature, "chat_template_kwargs": {"enable_thinking": self.thinking}}
        for attempt in range(5):
            req = urllib.request.Request(ROUTER, data=json.dumps(body).encode(), headers={
                "Authorization": f"Bearer {self._token}", "Content-Type": "application/json"})
            try:
                with urllib.request.urlopen(req, timeout=180) as response:
                    data = json.load(response)
                break
            except urllib.error.HTTPError as exc:
                if exc.code in (429, 500, 502, 503, 504) and attempt < 4:
                    time.sleep(2 ** attempt * 3)
                    continue
                raise RuntimeError(f"inference HTTP {exc.code}: {exc.read().decode()[:200]}") from None
            except (urllib.error.URLError, TimeoutError):  # DNS hiccups and slow responses are retried too
                if attempt < 4:
                    time.sleep(2 ** attempt * 3)
                    continue
                raise
        usage = data.get("usage") or {}
        with self._lock:
            self.usage["prompt_tokens"] += usage.get("prompt_tokens", 0)
            self.usage["completion_tokens"] += usage.get("completion_tokens", 0)
            self.usage["calls"] += 1
        choice = data["choices"][0]
        message = choice["message"]
        content = message.get("content") or ""
        if not content.strip():
            with self._lock:
                self.usage["empty_content"] = self.usage.get("empty_content", 0) + 1
                self.empty_examples.append({k: v for k, v in message.items() if v})
        return content, usage.get("completion_tokens", 0), choice.get("finish_reason")


def play(url, model, schema, task_id, completion_budget, context_budget):
    messages = [{"role": "system", "content": system_prompt(schema)}]
    episode = {"task_id": task_id, "turns": [], "end": None, "reward": 0.0}
    completion_used = 0
    with Session(url) as session:
        episode["seed"] = random.SystemRandom().randrange(2**48)
        data = session.reset(task_id=task_id, seed=episode["seed"])
        obs = data["observation"]
        while True:
            obs_text = json.dumps({k: v for k, v in obs.items() if k != "metadata" or v})
            messages.append({"role": "user", "content": obs_text})
            if len(messages) > 2:
                completion_used += len(obs_text) // 3  # later observations count against the budget
            if completion_used >= completion_budget or sum(len(m["content"]) for m in messages) // 3 >= context_budget:
                episode["end"] = "budget"
                data = session.step(FINISH_ACTION)
                break
            reply, used, finish_reason = model.chat(messages)
            completion_used += used
            messages.append({"role": "assistant", "content": reply})
            episode["turns"].append({"obs": obs_text[:4000], "reply": reply[:2000], "finish_reason": finish_reason, "tokens": used})
            if finish_reason == "length":
                episode["end"] = "truncated"
                data = session.step(FINISH_ACTION)
                break
            action = first_json_object(reply)
            if isinstance(action, dict) and set(action) == {"action"} and isinstance(action["action"], dict):
                action = action["action"]
            if action is None:
                episode["end"] = "empty_reply" if not reply.strip() else "invalid_json"
                data = session.step(FINISH_ACTION)
                break
            if action.get("finish") is True:
                episode["end"] = "finish"
                data = session.step(FINISH_ACTION)
                break
            try:
                DeskAction.model_validate(action)
            except ValidationError:
                episode["end"] = "schema_invalid"
                data = session.step(FINISH_ACTION)
                break
            data = session.step(action)
            obs = data["observation"]
            if data["done"]:
                episode["end"] = "submitted" if action.get("tool") == "submit" else "out_of_steps"
                episode["final"] = obs.get("output")
                break
    episode["reward"] = data.get("reward") or 0.0
    episode["n_turns"] = len(episode["turns"])
    episode["completion_tokens_est"] = completion_used
    return episode


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--url", default="http://localhost:8000")
    parser.add_argument("--model", default="Qwen/Qwen3.8-27B:deepinfra")
    parser.add_argument("--episodes", type=int, default=4)
    parser.add_argument("--tasks", default="", help="comma-separated task ids or prefixes (default: all)")
    parser.add_argument("--workers", type=int, default=8)
    parser.add_argument("--max-tokens", type=int, default=1024)
    parser.add_argument("--temperature", type=float, default=1.0)
    parser.add_argument("--completion-budget", type=int, default=8192)
    parser.add_argument("--context-budget", type=int, default=16384)
    parser.add_argument("--out", required=True)
    args = parser.parse_args()

    tasks = TASK_IDS
    if args.tasks:
        wanted = args.tasks.split(",")
        tasks = [t for t in TASK_IDS if any(t.startswith(w) for w in wanted)]
    with urllib.request.urlopen(f"{args.url}/schema", timeout=15) as response:
        schema = json.load(response)["action"]
    model = Model(args.model, args.max_tokens, args.temperature)
    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    jobs = [t for t in tasks for _ in range(args.episodes)]
    started = time.monotonic()
    results = []
    with ThreadPoolExecutor(args.workers) as pool, open(out / "episodes.jsonl", "w") as log:
        futures = [pool.submit(play, args.url, model, schema, t, args.completion_budget, args.context_budget) for t in jobs]
        for fut in futures:
            try:
                ep = fut.result()
            except Exception as exc:  # infrastructure errors are excluded, not scored as 0
                print("episode error:", exc, file=sys.stderr)
                continue
            results.append(ep)
            log.write(json.dumps(ep) + "\n")

    summary = {}
    for task_id in tasks:
        eps = [e for e in results if e["task_id"] == task_id]
        if not eps:
            continue
        rewards = [e["reward"] for e in eps]
        ends = {}
        for e in eps:
            ends[e["end"]] = ends.get(e["end"], 0) + 1
        summary[task_id] = {"n": len(eps), "mean": round(mean(rewards), 3), "rewards": rewards,
                            "mixed": len(set(rewards)) > 1, "ends": ends,
                            "turns": round(mean(e["n_turns"] for e in eps), 1)}
    report = {"model": args.model, "episodes": len(results), "seconds": round(time.monotonic() - started),
              "usage": model.usage, "tasks": summary}
    (out / "summary.json").write_text(json.dumps(report, indent=2) + "\n")
    (out / "empty_examples.json").write_text(json.dumps(model.empty_examples[:20], indent=2) + "\n")
    print(f"{'task':24s} {'mean':>5s}  rewards                        ends")
    for task_id, s in summary.items():
        print(f"{task_id:24s} {s['mean']:5.2f}  {str(s['rewards']):30s} {s['ends']}")
    print("usage:", model.usage, "seconds:", report["seconds"])


if __name__ == "__main__":
    main()