Datasets:
Download source/tools/calibrate.py from Syndicate604/science-desk: direct link, hf CLI and curl.
- Browser
- Download file 10.9 kB
-
https://huggingface.co/datasets/Syndicate604/science-desk/resolve/main/source/tools/calibrate.py
- Command line
-
hf download hf://datasets/Syndicate604/science-desk/source/tools/calibrate.py
-
curl -L -o calibrate.py https://huggingface.co/datasets/Syndicate604/science-desk/resolve/main/source/tools/calibrate.py
10.9 kB
| """Screen task difficulty against Qwen3.8-27B (thinking off) through OpenRouter, under the arena's budgets. | |
| The model plays real episodes against Terminal Desk containers over WebSocket, one | |
| session per container, so its commands never run on the host. The prompt follows | |
| the arena guide: a system message with the action schema, the reset observation as | |
| the first user turn, each later observation as JSON. A reply that is not exactly one | |
| JSON object ends the episode through the finish action ({"action_type": "evaluate"}). | |
| Budgets follow the guide: completion_tokens (default 4096) covers the model's tokens | |
| plus every observation after the first; context_tokens (default 8192) covers the | |
| whole conversation. Each observation is counted with the Qwen3.8-27B tokenizer | |
| (tools/qwen_tok) as soon as it arrives, so an exhausted budget ends the episode | |
| before another reply is generated or executed. Each reply's max_tokens is the | |
| smaller of the remaining completion and context budgets. The arena's exact chat | |
| template is unknown; ChatML framing (5 tokens per message) is assumed. | |
| Requests go only to --provider (default DeepInfra, bf16) with fallbacks off and | |
| quantization restricted to --quant; the serving provider of every call is recorded | |
| and an episode served by anything else is marked as an error. | |
| Spend is capped in code: no new episode starts once reported cost reaches --budget. | |
| Every record carries the full trajectory: each reply, its token counts, and the observation it produced. | |
| Usage: | |
| python tools/calibrate.py --ports 18001-18008 --episodes 6 --out runs/screen2.jsonl [--tasks all] | |
| """ | |
| import argparse | |
| import asyncio | |
| import json | |
| import os | |
| import sys | |
| import time | |
| import httpx | |
| import websockets | |
| sys.path.insert(0, os.path.dirname(__file__)) | |
| sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) | |
| from orkey import env_key # noqa: E402 | |
| from tokenizers import Tokenizer # noqa: E402 | |
| from terminal_desk.families import all_task_ids # noqa: E402 | |
| URL = "https://openrouter.ai/api/v1/chat/completions" | |
| MODEL = "qwen/qwen3.8-27b" | |
| FINISH = {"action_type": "evaluate"} | |
| MAX_REPLY_TOKENS = 1024 | |
| COMPLETION_BUDGET = 4096 | |
| CONTEXT_BUDGET = 8192 | |
| MAX_CALLS = 32 | |
| MSG_OVERHEAD = 5 # <|im_start|>role\n ... <|im_end|>\n | |
| TOK = Tokenizer.from_file(os.path.join(os.path.dirname(__file__), "qwen_tok", "tokenizer.json")) | |
| def ntok(text: str) -> int: | |
| return len(TOK.encode(text, add_special_tokens=False).ids) + MSG_OVERHEAD | |
| def system_prompt(schema: dict) -> str: | |
| return ( | |
| "You are acting in an environment. Each reply must be exactly one JSON object and nothing else: " | |
| 'an action matching the action schema below, or {"finish": true} to end the episode.\n' | |
| "Action schema:\n" + json.dumps(schema["action"]) | |
| ) | |
| def parse(text: str): | |
| try: | |
| value = json.loads(text.strip()) | |
| except (ValueError, TypeError): | |
| return None | |
| return value if isinstance(value, dict) else None | |
| class Budget: | |
| def __init__(self, cap: float): | |
| self.cap, self.spent = cap, 0.0 | |
| def add(self, usage: dict) -> None: | |
| self.spent += float(usage.get("cost") or 0.0) | |
| def exhausted(self) -> bool: | |
| return self.spent >= self.cap | |
| async def chat(client, key, messages, budget: Budget, max_tokens: int, route: dict): | |
| body = { | |
| "provider": {"order": [route["provider"]], "allow_fallbacks": False, "quantizations": [route["quant"]]}, | |
| "model": MODEL, | |
| "messages": messages, | |
| "max_tokens": max_tokens, | |
| "temperature": 1.0, | |
| "reasoning": {"enabled": False}, | |
| "usage": {"include": True}, | |
| } | |
| for attempt in range(6): | |
| r = await client.post(URL, headers={"Authorization": f"Bearer {key}"}, json=body, timeout=180) | |
| if r.status_code == 429 or r.status_code >= 500: | |
| await asyncio.sleep(2**attempt) | |
| continue | |
| if r.status_code != 200: | |
| raise RuntimeError(f"openrouter {r.status_code}: {r.text[:200]}") | |
| d = r.json() | |
| if "choices" not in d: | |
| raise RuntimeError(f"openrouter error body: {str(d)[:200]}") | |
| usage = d.get("usage") or {} | |
| budget.add(usage) | |
| ch = d["choices"][0] | |
| if d.get("provider") != route["provider"]: | |
| raise RuntimeError(f"served by {d.get('provider')!r}, not {route['provider']}") | |
| return ( | |
| ch["message"].get("content") or "", | |
| ch.get("finish_reason") or "", | |
| int(usage.get("completion_tokens") or 0), | |
| int(usage.get("prompt_tokens") or 0), | |
| ) | |
| raise RuntimeError("openrouter kept failing") | |
| async def episode(port: int, task_id: str, schema: dict, client, key, budget: Budget, route: dict) -> dict: | |
| rec = { | |
| "task_id": task_id, "reward": 0.0, "steps": 0, "ended": "", "completion_tokens": 0, | |
| "completion_spent": 0, "context_local": 0, "prompt_tokens_last": 0, "used_write_file": False, | |
| "actions": [], "invalid": None, "provider": route["provider"], "quant": route["quant"], "trajectory": [], | |
| } | |
| async with websockets.connect(f"ws://127.0.0.1:{port}/ws", max_size=2**24) as ws: | |
| async def send(kind, data): | |
| await ws.send(json.dumps({"type": kind, "data": data})) | |
| msg = json.loads(await ws.recv()) | |
| if msg.get("type") != "observation": | |
| if (msg.get("data") or {}).get("code") == "VALIDATION_ERROR" and kind == "step": | |
| return None # an action outside the schema: the arena ends the episode through the finish action | |
| raise RuntimeError(f"server error: {msg}") | |
| return msg["data"] | |
| async def finish(reason: str): | |
| rec["ended"] = reason | |
| res = await send("step", FINISH) | |
| rec["reward"] = res["reward"] | |
| rec["results"] = (res["observation"].get("info") or {}).get("results") | |
| rec["final_output"] = res["observation"].get("output") | |
| first = await send("reset", {"task_id": task_id}) | |
| messages = [ | |
| {"role": "system", "content": system_prompt(schema)}, | |
| {"role": "user", "content": json.dumps(first["observation"])}, | |
| ] | |
| context = sum(ntok(m["content"]) for m in messages) | |
| while True: | |
| remaining = COMPLETION_BUDGET - rec["completion_spent"] | |
| room = CONTEXT_BUDGET - context | |
| if remaining <= 16 or room <= 16: | |
| await finish("budget" if remaining <= 16 else "context") | |
| break | |
| reply, finish_reason, toks, prompt_toks = await chat( | |
| client, key, messages, budget, min(MAX_REPLY_TOKENS, remaining, room), route | |
| ) | |
| rec["completion_tokens"] += toks | |
| rec["completion_spent"] += toks | |
| rec["prompt_tokens_last"] = prompt_toks | |
| context += toks + MSG_OVERHEAD | |
| turn = {"reply": reply, "finish_reason": finish_reason, "reply_tokens": toks, "api_prompt_tokens": prompt_toks} | |
| rec["trajectory"].append(turn) | |
| action = parse(reply) | |
| if action is None or action.get("finish") is True: | |
| if action is None: | |
| rec["invalid"] = reply[:300] | |
| await finish("finish" if action else ("truncated" if finish_reason == "length" else "invalid_reply")) | |
| break | |
| rec["actions"].append(action.get("action_type", "?")) | |
| rec["used_write_file"] |= action.get("action_type") == "write_file" | |
| res = await send("step", action) | |
| if res is None: | |
| rec["invalid"] = reply[:300] | |
| await finish("invalid_action") | |
| break | |
| rec["steps"] += 1 | |
| o = res["observation"] | |
| turn["observation"] = {k: o.get(k) for k in ("output", "success", "error")} | |
| if res["done"]: | |
| rec["reward"] = res["reward"] | |
| rec["ended"] = "evaluate" if action.get("action_type") == "evaluate" else ( | |
| "cap" if rec["steps"] > MAX_CALLS else "close") | |
| rec["results"] = (res["observation"].get("info") or {}).get("results") | |
| break | |
| obs = json.dumps(res["observation"]) | |
| messages.append({"role": "assistant", "content": reply.strip()}) | |
| messages.append({"role": "user", "content": obs}) | |
| rec["completion_spent"] += ntok(obs) # counted on arrival, before the next reply | |
| context += ntok(obs) | |
| rec["context_local"] = context | |
| turn.update(obs_tokens=ntok(obs), completion_spent=rec["completion_spent"], context=context) | |
| return rec | |
| async def main() -> None: | |
| p = argparse.ArgumentParser() | |
| p.add_argument("--ports", required=True, help="e.g. 18001-18008") | |
| p.add_argument("--tasks", default="all") | |
| p.add_argument("--episodes", type=int, default=6) | |
| p.add_argument("--budget", type=float, default=1.0, help="USD cap for this run") | |
| p.add_argument("--out", required=True) | |
| p.add_argument("--provider", default="DeepInfra") | |
| p.add_argument("--quant", default="bf16") | |
| a = p.parse_args() | |
| lo, hi = map(int, a.ports.split("-")) | |
| ports = list(range(lo, hi + 1)) | |
| tasks = all_task_ids() if a.tasks == "all" else a.tasks.split(",") | |
| jobs = asyncio.Queue() | |
| for _ in range(a.episodes): | |
| for t in tasks: | |
| jobs.put_nowait(t) | |
| key = env_key("OPENROUTER_API_KEY") | |
| schema = httpx.get(f"http://127.0.0.1:{ports[0]}/schema").json() | |
| budget = Budget(a.budget) | |
| route = {"provider": a.provider, "quant": a.quant} | |
| os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True) | |
| started = time.time() | |
| done = 0 | |
| with open(a.out, "a") as fh: | |
| async with httpx.AsyncClient() as client: | |
| async def worker(port): | |
| nonlocal done | |
| while not jobs.empty() and not budget.exhausted: | |
| t = jobs.get_nowait() | |
| try: | |
| rec = await episode(port, t, schema, client, key, budget, route) | |
| except Exception as exc: # recorded per episode and counted below; the run itself goes on | |
| rec = {"task_id": t, "error": f"{type(exc).__name__}: {exc}"[:300]} | |
| rec["model"] = MODEL | |
| fh.write(json.dumps(rec) + "\n") | |
| fh.flush() | |
| done += 1 | |
| if done % 20 == 0: | |
| print(f"{done} episodes, ${budget.spent:.3f}, {time.time() - started:.0f}s", flush=True) | |
| await asyncio.gather(*(worker(pt) for pt in ports)) | |
| print(f"finished {done} episodes, spent ${budget.spent:.3f}, {time.time() - started:.0f}s, budget hit: {budget.exhausted}") | |
| if __name__ == "__main__": | |
| asyncio.run(main()) | |