opencode-rollout-trace / screen_launcher.py
sergiopaniego's picture
sergiopaniego HF Staff
Dump the trace of any rollout that scores zero: one turn and a zero is not the same as solving it wrong
6e1c88f verified
Raw History Blame Contribute Delete
8.61 kB
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# /// script
# dependencies = [
# "trl",
# "vllm",
# "datasets>=3.2",
# "huggingface_hub",
# "openenv-opencode-env @ git+https://github.com/huggingface/OpenEnv.git#subdirectory=envs/opencode_env",
# ]
# ///
"""
Measure base vs trained on candidate tasks, in one job, and print the table that picks the task.
Serves the base model, screens the candidates, tears vLLM down, serves the trained model, screens the
same candidates, then merges both results into a comparison table. Two passes in one job because vLLM
holds the GPU, and one job because the answer is the comparison, not either half.
```sh
TASK_INDICES=11,34,39,25 ROLLOUTS=2 \
hf jobs uv run --flavor a100-large --secrets HF_TOKEN --timeout 7200s screen_launcher.py
```
Env vars: `BASE_MODEL`, `TRAINED_MODEL`, `TASK_INDICES`, `ROLLOUTS`, `N_PROMPTS`, `SEED`,
`SANDBOX_FLAVOR`, `PUSH_TO_DATASET`.
Budget: `len(TASK_INDICES) * ROLLOUTS * 2` rollouts, each booting its own remote sandbox, plus two
vLLM starts. Four tasks at two rollouts is sixteen rollouts, roughly an hour. Raise the job timeout
before raising either number.
Index 11 is in the default list as a control: the base model already scored 1.0 on it in a measured
run, so if the screen disagrees about 11, the screen is wrong.
"""
import json
import os
import re
import signal
import subprocess
import sys
import time
import urllib.request
BASE_URL = "https://huggingface.co/datasets/sergiopaniego/opencode-rollout-trace/resolve/main"
SCREEN_URL = f"{BASE_URL}/screen_tasks.py"
EXAMPLE_URL = (
"https://raw.githubusercontent.com/huggingface/trl/"
"main/examples/async_grpo_opencode/opencode_hf_sandbox.py"
)
CLOUDFLARED = "https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64"
BASE_MODEL = os.environ.get("BASE_MODEL", "Qwen/Qwen3-8B")
TRAINED_MODEL = os.environ.get("TRAINED_MODEL", "sergiopaniego/Qwen3-8B-opencode-deepcoder-grpo")
TASK_INDICES = os.environ.get("TASK_INDICES", "11,34,39,25")
ROLLOUTS = os.environ.get("ROLLOUTS", "2")
N_PROMPTS = os.environ.get("N_PROMPTS", "64")
SEED = os.environ.get("SEED", "0")
SANDBOX_FLAVOR = os.environ.get("SANDBOX_FLAVOR", "cpu-basic")
def _log(m):
print(">>> " + m, flush=True)
def _kill_pg(p):
if p is None:
return
try:
os.killpg(os.getpgid(p.pid), signal.SIGKILL)
except Exception:
try:
p.kill()
except Exception:
pass
def serve(model):
"""Bring up vLLM for one model and a public tunnel to it. Returns (vllm, cloudflared, public_url)."""
_log(f"serving {model}...")
vllm = subprocess.Popen(
["vllm", "serve", model, "--max-model-len", "40960", "--logprobs-mode", "processed_logprobs",
"--return-tokens-as-token-ids", "--enable-auto-tool-choice", "--tool-call-parser", "hermes"],
env={**os.environ, "VLLM_USE_FLASHINFER_SAMPLER": "0"},
start_new_session=True,
)
for _ in range(300):
if vllm.poll() is not None:
_log(f"vLLM died early rc={vllm.returncode}")
return vllm, None, None
try:
urllib.request.urlopen("http://localhost:8000/health", timeout=3)
break
except Exception:
time.sleep(2)
else:
_log("vLLM never became healthy")
return vllm, None, None
logname = f"cf_{re.sub(r'[^a-z0-9]+', '_', model.lower())}.log"
cflog = open(logname, "w")
cf = subprocess.Popen(["./cloudflared", "tunnel", "--no-autoupdate", "--url", "http://localhost:8000"],
stdout=cflog, stderr=subprocess.STDOUT, start_new_session=True)
for _ in range(60):
time.sleep(2)
m = re.search(r"https://[a-z0-9-]+\.trycloudflare\.com", open(logname).read())
if m:
_log(f"public url: {m.group(0)}")
return vllm, cf, m.group(0)
_log("cloudflared did not produce a public URL")
return vllm, cf, None
def screen(which, model, public, out):
cmd = [sys.executable, "screen_tasks.py",
"--base-model", BASE_MODEL, "--trained-model", TRAINED_MODEL,
"--sandbox-vllm-url", public, "--serving", which,
"--task-indices", TASK_INDICES, "--rollouts", ROLLOUTS,
"--n-prompts", N_PROMPTS, "--seed", SEED,
"--sandbox-flavor", SANDBOX_FLAVOR, "--out", out]
_log(f"screening with the {which} model ({model})...")
return subprocess.run(cmd).returncode
def table(base, trained):
"""The deliverable: one row per task, and whether the gap is worth recording."""
lines = ["", "idx seen? base trained gap", "--- ----- ------ ------- ----------"]
picks = []
for idx in sorted(set(base["tasks"]) | set(trained["tasks"]), key=int):
b = base["tasks"].get(idx, {})
t = trained["tasks"].get(idx, {})
bm, tm = b.get("mean"), t.get("mean")
seen = "yes" if b.get("seen_in_training", t.get("seen_in_training")) else "no"
if bm is None or tm is None:
verdict = "unscorable"
elif bm <= 0.05 and tm >= 0.95:
verdict = "CLEAN"
picks.append(idx)
elif tm - bm >= 0.3:
verdict = "partial"
elif tm - bm <= 0.05:
verdict = "no gap"
else:
verdict = "weak"
lines.append("%-4s %-6s %-7s %-8s %s" % (idx, seen,
"n/a" if bm is None else "%.2f" % bm,
"n/a" if tm is None else "%.2f" % tm, verdict))
lines.append("")
if picks:
lines.append("record one of these: " + ", ".join(picks))
unseen = [p for p in picks if not base["tasks"].get(p, {}).get("seen_in_training", True)]
if unseen:
lines.append("and prefer an unseen one, which is the stronger story: " + ", ".join(unseen))
else:
lines.append("no clean gap. Take the largest partial one and say so out loud in the talk.")
return "\n".join(lines)
def main():
urllib.request.urlretrieve(CLOUDFLARED, "cloudflared")
os.chmod("cloudflared", 0o755)
urllib.request.urlretrieve(SCREEN_URL, "screen_tasks.py")
urllib.request.urlretrieve(EXAMPLE_URL, "opencode_hf_sandbox.py")
_log("downloaded cloudflared + screener + the example it imports")
for which, model, out in (("base", BASE_MODEL, "screen_base.json"),
("trained", TRAINED_MODEL, "screen_trained.json")):
vllm = cf = None
try:
vllm, cf, public = serve(model)
if not public:
return 1
if screen(which, model, public, out) != 0:
_log(f"the {which} pass failed")
return 1
finally:
_log(f"tearing down vLLM for {model}...")
_kill_pg(cf)
_kill_pg(vllm)
time.sleep(20) # let the GPU actually free before the next serve
base = json.load(open("screen_base.json"))
trained = json.load(open("screen_trained.json"))
result = table(base, trained)
print(result, flush=True)
with open("screen_table.txt", "w") as fh:
fh.write(result + "\n")
if os.environ.get("PUSH_TO_DATASET"):
from huggingface_hub import HfApi
repo = os.environ["PUSH_TO_DATASET"]
api = HfApi()
api.create_repo(repo, repo_type="dataset", exist_ok=True)
import glob
files = ["screen_base.json", "screen_trained.json", "screen_table.txt"]
files += sorted(glob.glob("fail_*.json")) # the traces of the rollouts that scored 0
for f in files:
api.upload_file(path_or_fileobj=f, path_in_repo=f"screening/{f}", repo_id=repo, repo_type="dataset",
commit_message="Screen base vs trained to pick the before/after task")
_log(f"uploaded {len(files)} files, {len(files) - 3} of them failure traces")
_log(f"pushed to https://huggingface.co/datasets/{repo}")
return 0
if __name__ == "__main__":
raise SystemExit(main())