Download source/scripts/tinker_grpo.py from ajinkyamulay/analyst-workbench: direct link, hf CLI and curl.
- Browser
- Download file 11.5 kB
-
https://huggingface.co/datasets/ajinkyamulay/analyst-workbench/resolve/main/source/scripts/tinker_grpo.py
- Command line
-
hf download hf://datasets/ajinkyamulay/analyst-workbench/source/scripts/tinker_grpo.py
-
curl -L -o tinker_grpo.py https://huggingface.co/datasets/ajinkyamulay/analyst-workbench/resolve/main/source/scripts/tinker_grpo.py
11.5 kB
| """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() | |