opencode-rollout-trace / screen_tasks.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
b87064c verified
Raw History Blame Contribute Delete
6.2 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.
"""
Pick the before/after task by measuring it, not by guessing.
Runs opencode on the same candidate tasks with two models in turn, the base and the trained one,
scores each rollout with the task's held-out tests, and prints a table. The task to record is one
where the gap is clean: base fails, trained passes.
Nothing from the training path is involved: no trainer, no GRPO, no capture proxy. Just the agent,
the task, and the held-out tests. `capture_launcher.py` handles the trace separately.
idx seen? base trained gap
11 yes 1.00 1.00 no (trivial, both solve it)
34 no 0.00 1.00 CLEAN <- record this one
39 no 0.42 0.58 weak
`build_dataset(n_prompts, seed)` is deterministic, so indices are reproducible and `< 32` means the
training run saw it. A task the run never saw is the stronger story, but the black-box run trained on
32 prompts with no held-out eval, so an unseen task may simply not improve. That is what this
measures instead of assuming.
"""
import argparse
import json
import statistics
from opencode_hf_sandbox import build_dataset, build_factory, opencode_agent_turns
from trl.experimental.async_grpo.openenv_harness import _messages_from_trace
def parse_args():
p = argparse.ArgumentParser(description="Measure base vs trained on candidate tasks, one rollout each.")
p.add_argument("--base-model", default="Qwen/Qwen3-8B")
p.add_argument("--trained-model", default="sergiopaniego/Qwen3-8B-opencode-deepcoder-grpo")
p.add_argument("--sandbox-vllm-url", required=True)
p.add_argument("--serving", required=True, choices=("base", "trained"),
help="Which model the url in front of this process is currently serving.")
p.add_argument("--task-indices", default="11,34,39,25,33",
help="Comma separated indices into the built dataset.")
p.add_argument("--n-prompts", type=int, default=64)
p.add_argument("--seed", type=int, default=0)
p.add_argument("--rollouts", type=int, default=2, help="Rollouts per task, to see through sampling noise.")
p.add_argument("--sandbox-image", default="ghcr.io/huggingface/openenv-opencode-sandbox:latest")
p.add_argument("--sandbox-flavor", default="cpu-basic")
p.add_argument("--timeout-s", type=float, default=900.0)
p.add_argument("--out", default="screen_results.json")
return p.parse_args()
def score_one(factory, prompt, seed, timeout_s, dump_prefix=None):
"""One rollout: let the agent run its loop, then score the workspace with the held-out tests.
A rollout that ends with one turn and a zero is not "solved it wrong", it is "did not do the
task", and the difference matters when you are about to record this. So when the score comes
back at 0 or None, the raw trace is dumped next to the results for inspection."""
session = factory.create(prompt, seed=seed, episode_id=None)
timed_out = False
try:
try:
session.wait_for_completion(timeout_s=timeout_s)
except TimeoutError:
timed_out = True
trace = session.fetch_proxy_trace()
entries = opencode_agent_turns(trace)
verify = session.verify(_messages_from_trace(entries))
score = float(verify.env_reward) if verify.env_reward is not None else None
if dump_prefix and (score is None or score == 0.0):
with open(f"{dump_prefix}.json", "w") as fh:
json.dump({"score": score, "timed_out": timed_out, "captured_calls": len(trace),
"agent_turns": len(entries), "trace": trace}, fh, indent=2)
print(f"[dump] {dump_prefix}.json captured={len(trace)} agent_turns={len(entries)} "
f"timed_out={timed_out}", flush=True)
return (score, len(entries), timed_out)
finally:
try:
session.close()
except Exception:
pass
def main():
args = parse_args()
model = args.base_model if args.serving == "base" else args.trained_model
rows, tests_by_id = build_dataset(n_prompts=args.n_prompts, seed=args.seed)
factory = build_factory(args.sandbox_vllm_url, model, tests_by_id, args.sandbox_image, args.sandbox_flavor)
indices = [int(x) for x in args.task_indices.split(",") if x.strip()]
out = {"serving": args.serving, "model": model, "tasks": {}}
for idx in indices:
if not 0 <= idx < len(rows):
print(f"[skip] index {idx} outside 0..{len(rows) - 1}", flush=True)
continue
prompt = rows[idx]["prompt"]
scores, turns, timeouts = [], [], []
for r in range(args.rollouts):
score, n_turns, timed_out = score_one(
factory, prompt, seed=args.seed + r, timeout_s=args.timeout_s,
dump_prefix=f"fail_{args.serving}_idx{idx}_r{r}",
)
scores.append(score)
turns.append(n_turns)
timeouts.append(timed_out)
print(f"[{args.serving}] idx={idx} rollout={r} score={score} turns={n_turns} "
f"timed_out={timed_out}", flush=True)
clean = [s for s in scores if s is not None]
out["tasks"][str(idx)] = {
"seen_in_training": idx < 32,
"scores": scores,
"mean": statistics.mean(clean) if clean else None,
"turns": turns,
"timed_out": timeouts,
}
print("[results] " + json.dumps(out), flush=True)
with open(args.out, "w") as fh:
json.dump(out, fh, indent=2)
if __name__ == "__main__":
main()