File size: 11,534 Bytes
440d35c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
226
227
228
229
230
231
232
233
234
"""Local stand-in for the arena's training run: GRPO with LoRA on Tinker, arena reply rules.

Each step takes the next task in the list and plays a group of episodes against any OpenEnv
server, as the arena does: the system message holds the action schema, every observation is
sent as JSON, a reply must be exactly one JSON object that fits the schema (or {"finish": true}),
and anything else ends the episode through the finish action. Rewards come from the environment.
Advantages are reward minus the group mean; groups with no reward spread are skipped.

`--steps 0` only evaluates (no training), which is also how held-out tests run.
The run tracks its own token use and stops before its estimated cost passes --max-usd.

    python tinker_grpo.py --env-url http://127.0.0.1:18104 --tasks a,b --steps 60 \
        --model Qwen/Qwen3-8B --out runs/v8_8b --max-usd 5
"""

import argparse
import json
import os
import random
import re
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from urllib.request import urlopen

import jsonschema
import tinker
from tinker_cookbook import model_info, renderers
from websockets.sync.client import connect

# USD per million tokens (https://thinkingmachines.ai/tinker/pricing/, 2026-10-21).
PRICES = {
    "Qwen/Qwen3-8B": {"prefill": 0.195, "cached": 0.039, "sample": 0.60, "train": 0.44},
    "Qwen/Qwen3.8-27B": {"prefill": 0.6975, "cached": 0.1395, "sample": 5.595, "train": 4.103},
}
FENCE = re.compile(r"^```(?:json)?\s*\{.*\}\s*```$", re.S)
TOKENIZER = threading.Lock()  # the fast tokenizer is not safe across threads


def system_prompt(action_schema):
    return ("You are an agent acting in an environment. Each user message is an observation. "
            "Reply with exactly one JSON object and nothing else: an action matching this JSON "
            "schema, or {\"finish\": true} to end the episode.\n\nAction schema:\n"
            + json.dumps(action_schema))


def parse(text, action_schema):
    """Arena rule: exactly one JSON object that fits the schema. Returns (action, status)."""
    text = text.strip()
    if FENCE.match(text):
        return None, "fenced"
    try:
        obj = json.loads(text)
    except json.JSONDecodeError:
        return None, "unparseable"
    if not isinstance(obj, dict):
        return None, "not_object"
    if obj == {"finish": True}:
        return "finish", "finish"
    if set(obj) == {"action"} and isinstance(obj["action"], dict):
        obj = obj["action"]
    try:
        jsonschema.validate(obj, action_schema)
    except jsonschema.ValidationError:
        return None, "schema_invalid"
    return obj, "ok"


class Cost:
    def __init__(self, model):
        self.p = PRICES[model]
        self.tokens = {"prefill": 0, "cached": 0, "sample": 0, "train": 0}

    def usd(self):
        return sum(self.tokens[k] * self.p[k] for k in self.tokens) / 1e6


def episode(args, sampler, renderer, schema, task_id, cost):
    """One episode. Returns reward, end reason and the sampled turns for training."""
    turns, end, last_text = [], None, ""
    with connect(args.env_url.replace("http", "ws", 1) + "/ws", open_timeout=30, max_size=2**24) as ws:
        def send(msg):
            ws.send(json.dumps(msg))
            return json.loads(ws.recv(timeout=300))["data"]

        data = send({"type": "reset", "data": {"task_id": task_id}})
        messages = [{"role": "system", "content": system_prompt(schema["action"])},
                    {"role": "user", "content": json.dumps(data["observation"])}]
        used, prev_prompt = 0, 0
        while not data["done"]:
            with TOKENIZER:
                prompt = renderer.build_generation_prompt(messages)
            n_prompt = prompt.length
            left = min(args.budget - used, args.ctx - n_prompt)
            if left <= 0:
                end = "token_budget"
                data = send({"type": "step", "data": args.finish_action})
                break
            params = tinker.SamplingParams(max_tokens=min(left, args.max_reply), temperature=args.temperature,
                                           stop=renderer.get_stop_sequences())
            seq = sampler.sample(prompt=prompt, num_samples=1, sampling_params=params).result().sequences[0]
            # Earlier turns are in the prompt cache; old thinking is dropped from the history,
            # so the new prompt can be shorter than the previous prompt plus its reply.
            cost.tokens["cached"] += min(prev_prompt, n_prompt)
            cost.tokens["prefill"] += max(0, n_prompt - prev_prompt)
            cost.tokens["sample"] += len(seq.tokens)
            used += len(seq.tokens)
            turns.append({"prompt": prompt, "tokens": seq.tokens, "logprobs": seq.logprobs})
            with TOKENIZER:
                message, term = renderer.parse_response(seq.tokens)
                text = renderers.get_text_content(message)
            last_text = text
            if not term.is_clean:  # cut off at the token limit, or broken chat markup
                end = "cut_off"
                data = send({"type": "step", "data": args.finish_action})
                break
            action, status = parse(text, schema["action"])
            if action is None:
                end = status
                data = send({"type": "step", "data": args.finish_action})
                break
            data = send({"type": "step", "data": args.finish_action if action == "finish" else action})
            obs = dict(data["observation"], done=data["done"], reward=data["reward"])
            messages += [{"role": "assistant", "content": text}, {"role": "user", "content": json.dumps(obs)}]
            used += len(json.dumps(obs)) // 3  # arena: later observations count against completion_tokens
            prev_prompt = n_prompt + len(seq.tokens)
        if end is None:
            out = (data.get("observation") or {}).get("output", "")
            end = "misfit_call" if "Episode over" in out else "finished" if data["done"] else "budget"
    return float(data.get("reward") or 0.0), end, turns, last_text[:300]


def safe_episode(*a):
    """Infrastructure failures (dropped socket, server error) must not end a long run."""
    try:
        return episode(*a)
    except Exception as exc:  # noqa: BLE001
        return None, "error: " + repr(exc)[:120], [], ""


def datums(turns, advantage):
    out = []
    for t in turns:
        p, toks, lps = t["prompt"].to_ints(), t["tokens"], t["logprobs"]
        full = p + toks
        out.append(tinker.Datum(
            model_input=tinker.ModelInput.from_ints(full[:-1]),
            loss_fn_inputs={"target_tokens": full[1:],
                            "logprobs": [0.0] * (len(p) - 1) + list(lps),
                            "advantages": [0.0] * (len(p) - 1) + [advantage] * len(toks)}))
    return out


def main():
    a = argparse.ArgumentParser()
    a.add_argument("--env-url", required=True)
    a.add_argument("--tasks", required=True)
    a.add_argument("--model", default="Qwen/Qwen3-8B")
    a.add_argument("--steps", type=int, default=0, help="GRPO steps; 0 = evaluate only")
    a.add_argument("--group", type=int, default=5, help="episodes per step (the arena plays 5)")
    a.add_argument("--train-on", type=int, default=4, help="episodes per group that train (the arena uses 4)")
    a.add_argument("--eval-episodes", type=int, default=0, help="episodes per task when evaluating")
    a.add_argument("--weights", default="", help="tinker:// sampler weights to evaluate")
    a.add_argument("--finish-action", default='{"tool": "finish", "args": {}}')
    a.add_argument("--lr", type=float, default=4e-5)
    a.add_argument("--rank", type=int, default=32)
    a.add_argument("--temperature", type=float, default=0.6)
    a.add_argument("--budget", type=int, default=32768)
    a.add_argument("--ctx", type=int, default=32768)
    a.add_argument("--max-reply", type=int, default=32768, help="per reply; the arena caps only the episode")
    a.add_argument("--max-usd", type=float, required=True)
    a.add_argument("--seed", type=int, default=0)
    a.add_argument("--out", required=True)
    args = a.parse_args()
    args.finish_action = json.loads(args.finish_action)
    os.environ.setdefault("TINKER_API_KEY", Path("~/.tinker_key").expanduser().read_text().strip())
    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    log = open(out / "log.jsonl", "a")
    random.seed(args.seed)
    tasks = args.tasks.split(",")
    schema = json.load(urlopen(args.env_url + "/schema"))
    service = tinker.ServiceClient()
    cost = Cost(args.model)

    if args.steps == 0:  # evaluation only
        sampler = (service.create_sampling_client(model_path=args.weights) if args.weights
                   else service.create_sampling_client(base_model=args.model))
        renderer = renderers.get_renderer(model_info.get_recommended_renderer_name(args.model), sampler.get_tokenizer())
        jobs = [t for t in tasks for _ in range(args.eval_episodes)]
        with ThreadPoolExecutor(8) as pool:
            for tid, (r, end, _, last) in zip(jobs, pool.map(lambda t: safe_episode(args, sampler, renderer, schema, t, cost), jobs)):
                log.write(json.dumps({"task_id": tid, "reward": r, "end": end, "last": last, "usd": round(cost.usd(), 4)}) + "\n")
                log.flush()
                if cost.usd() > args.max_usd:
                    print("cost cap reached; stopping"); break
        print(json.dumps({"episodes": len(jobs), "usd": round(cost.usd(), 3), "tokens": cost.tokens}))
        return

    trainer = service.create_lora_training_client(base_model=args.model, rank=args.rank)
    renderer = renderers.get_renderer(model_info.get_recommended_renderer_name(args.model), trainer.get_tokenizer())
    adam = tinker.AdamParams(learning_rate=args.lr, beta1=0.9, beta2=0.95, eps=1e-8)
    for step in range(args.steps):
        t0 = time.time()
        sampler = trainer.save_weights_and_get_sampling_client()
        tid = tasks[step % len(tasks)]
        with ThreadPoolExecutor(args.group) as pool:
            results = list(pool.map(lambda _: safe_episode(args, sampler, renderer, schema, tid, cost), range(args.group)))
        group = [x for x in results if x[0] is not None][:args.train_on]  # the arena trains on the first 4 valid
        rewards = [r for r, _, _, _ in group]
        mean = sum(rewards) / len(rewards) if rewards else 0.0
        batch = [d for r, _, turns, _ in group if r != mean for d in datums(turns, r - mean)]
        if batch:
            cost.tokens["train"] += sum(d.model_input.length for d in batch)
            trainer.forward_backward(batch, loss_fn="importance_sampling").result()
            trainer.optim_step(adam).result()
        row = {"step": step, "task_id": tid, "rewards": [x[0] for x in results],
               "ends": [x[1] for x in results], "last": [x[3][:160] for x in results], "trained": bool(batch),
               "usd": round(cost.usd(), 4), "seconds": round(time.time() - t0, 1)}
        log.write(json.dumps(row) + "\n")
        log.flush()
        print(json.dumps(row), flush=True)
        if cost.usd() > args.max_usd:
            print("cost cap reached; stopping")
            break
    path = trainer.save_weights_for_sampler(name="final").result().path
    (out / "weights.txt").write_text(path + "\n")
    print(json.dumps({"weights": path, "usd": round(cost.usd(), 3), "tokens": cost.tokens}))


if __name__ == "__main__":
    main()