File size: 8,606 Bytes
32faf7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e1c88f
 
 
 
 
32faf7b
 
6e1c88f
32faf7b
 
 
 
 
 
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
# 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())