Spaces:
Running

foresightbench-rl / scripts /sample_policy.py
ruhzi's picture
ForesightBench RL environment + rollout browser
effcad2 verified
Raw History Blame Contribute Delete
2.63 kB
"""Sample a small policy on train prompts through HF Inference Providers.
HF_TOKEN=... python scripts/sample_policy.py --model Qwen/Qwen3.5-4B \
--n 8 --prompts 40 --out samples.jsonl --live
Writes rows {sample_id, completion, model}. Thinking is disabled so the
reasoning is the visible prose the judge grades. Refuses to run without --live.
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from foresightbench_env import prompt
from foresightbench_env.data import load_split
from foresightbench_env.judge import HF_BASE_URL
ROOT = Path(__file__).resolve().parents[1]
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--model", default="Qwen/Qwen3.5-4B")
ap.add_argument("--n", type=int, default=8)
ap.add_argument("--prompts", type=int, default=40)
ap.add_argument("--split", default="train")
ap.add_argument("--out", type=Path, required=True)
ap.add_argument("--max-tokens", type=int, default=2048)
ap.add_argument("--workers", type=int, default=8)
ap.add_argument("--live", action="store_true")
a = ap.parse_args()
if not a.live:
sys.exit("refusing: this script makes paid API calls; pass --live to run it")
token = os.environ.get("HF_TOKEN")
if not token:
sys.exit("HF_TOKEN is not set")
from openai import OpenAI
client = OpenAI(base_url=HF_BASE_URL, api_key=token)
rows = sorted(load_split(a.split), key=lambda r: r["sample_id"])[: a.prompts]
jobs = [(r, k) for r in rows for k in range(a.n)]
def one(job):
r, _k = job
resp = client.chat.completions.create(
model=a.model, messages=prompt.messages(r), max_tokens=a.max_tokens,
temperature=1.0, extra_body={"chat_template_kwargs": {"enable_thinking": False}})
return {"sample_id": r["sample_id"], "model": a.model,
"completion": resp.choices[0].message.content or "",
"finish_reason": resp.choices[0].finish_reason}
a.out.parent.mkdir(parents=True, exist_ok=True)
done = 0
with a.out.open("a", encoding="utf-8") as fh, ThreadPoolExecutor(max_workers=a.workers) as ex:
for rec in ex.map(one, jobs):
fh.write(json.dumps(rec, ensure_ascii=False) + "\n")
done += 1
if done % 20 == 0:
print(f"{done}/{len(jobs)}", file=sys.stderr)
print(f"wrote {done} samples to {a.out}")
if __name__ == "__main__":
main()