The capture code for the Lisbon talk artefact (the trace itself lands after the run)
Browse filesFiles changed (3)
- README.mdAdded+77
- capture_launcher.pyAdded+147
- capture_trace.pyAdded+207
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677---license: apache-2.0tags:- rl- trl- openenv- agents---
# One opencode rollout, as the trainer sees it
The artefact behind the talk **Training a coding agent through a harness you did not write**([Lisbon AI](https://lisbonai.org/), September 2026).
An off-the-shelf coding agent, [opencode](https://github.com/sst/opencode), runs untouched in aremote sandbox. A proxy sits between it and vLLM, speaks the agent's own dialect, and records everymodel call the agent makes together with the exact token ids and logprobs. That recording is whatgets trained on. This repo is one of those recordings, plus the code that produced it.
Nothing here is a transcript. A transcript would be text, and retokenising text gives you differentids than the ones the model actually sampled. That difference is the point.
## Files
| File | What it is ||---|---|| `trace.json` | the raw proxy trace: every captured model call, in order, as recorded || `turns.json` | the real agent turns, derived exactly as training derives them (see below) || `task.json` | the instruction the agent was given, and its task id || `visible_tests.txt` | the example cases the agent could see, from the problem statement || `held_out_tests.json` | the tests that produce the reward, which the agent never sees || `summary.json` | reward, turn counts, tool counts, and how many turns training keeps || `capture_trace.py` | drives one session and writes all of the above || `capture_launcher.py` | serves vLLM, opens a tunnel, runs the capture, as one HF Job |
### Reading `turns.json`
Each turn carries what the training path actually uses:
- `prompt_ids`: the conversation sent to the model that turn, re-tokenized with its tools, so the prompt matches what the upstream rendered- `output_ids`: the ids the model generated, taken from the capture and **not** re-encoded- `per_token_logps`: the generator's logprobs for those ids- `trained`: whether the training policy keeps this turn. Here it is `has_tool_call`, so turns where the model took an action are kept and pure-text turns are not- `mask`: **derived, not recorded.** `0` for the context, `1` for the tokens the model generated. The proxy never stores a mask, the distinction is structural: only `output_ids` get a gradient. It is materialised here because that distinction is the whole reason the artefact is interesting.
Turn count in `turns.json` is smaller than in `trace.json` on purpose. opencode fires extra modelcalls for its own bookkeeping, a title generator and a context summariser, and those are not thetask. Training them with the rollout's reward would reinforce the wrong thing, so they are filteredby anchoring on the system prompt of the first tool-enabled turn.
## Reproducing it
```shTASK_INDEX=0 PUSH_TO_DATASET=sergiopaniego/opencode-rollout-trace \hf jobs uv run --flavor a100-large --secrets HF_TOKEN --timeout 3600s \ "https://huggingface.co/datasets/sergiopaniego/opencode-rollout-trace/resolve/main/capture_launcher.py"```
One GPU is enough: this captures, it does not train, so there is no weight sync. The vLLM flagsmatter, `--return-tokens-as-token-ids` is what lets the proxy recover exact ids instead ofre-encoding decoded text.
`build_dataset(n_prompts, seed)` in the training example is deterministic, so `TASK_INDEX` selects areproducible task. Keep `N_PROMPTS` equal to what the training run used and the indices line up.
## Where this comes from
- Training script, maintained upstream in TRL: [`examples/async_grpo_opencode/opencode_hf_sandbox.py`](https://github.com/huggingface/trl/blob/main/examples/async_grpo_opencode/opencode_hf_sandbox.py)- Write-up: [Training a coding agent using the OpenCode harness](https://huggingface.co/blog/sergiopaniego/trl-openenv-harness-training)- Task data: [DeepCoder-Preview-Dataset](https://huggingface.co/datasets/agentica-org/DeepCoder-Preview-Dataset)- Sandbox image: `ghcr.io/huggingface/openenv-opencode-sandbox:latest`- The policy trained this way: [Qwen3-8B-opencode-deepcoder-grpo](https://huggingface.co/sergiopaniego/Qwen3-8B-opencode-deepcoder-grpo)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147# 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",# ]# ///
"""Capture one opencode rollout trace in a single HF Job.
Same shape as `launcher.py` but without the trainer, so one GPU is enough: serve vLLM, expose it with acloudflared tunnel so the remote sandbox can reach it, then run `capture_trace.py` for exactly onerollout and write the artifact out.
```shTASK_INDEX=0 PUSH_TO_DATASET=sergiopaniego/opencode-rollout-trace \hf jobs uv run --flavor a100-large --secrets HF_TOKEN --timeout 3600s capture_launcher.py```
Environment variables: `MODEL` (default `Qwen/Qwen3-8B`), `TASK_INDEX` (default 0), `N_PROMPTS`(default 64, keep it equal to what training used so task indices line up), `SEED` (default 0),`PUSH_TO_DATASET` (optional dataset repo to upload the artifact to).
The vLLM flags matter: `--return-tokens-as-token-ids` is what lets the in-sandbox proxy recover exacttoken ids instead of re-encoding decoded text, and `--logprobs-mode processed_logprobs` gives thelogprobs the trainer would use. `--weight-transfer-config` is NOT set here: nothing is training."""
import osimport reimport signalimport subprocessimport sysimport timeimport urllib.request
SCRIPT_URL = ( "https://huggingface.co/datasets/sergiopaniego/opencode-rollout-trace/resolve/main/capture_trace.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"
MODEL = os.environ.get("MODEL", "Qwen/Qwen3-8B")TASK_INDEX = os.environ.get("TASK_INDEX", "0")N_PROMPTS = os.environ.get("N_PROMPTS", "64")SEED = os.environ.get("SEED", "0")
def _log(m): print(">>> " + m, flush=True)
def _kill_pg(p): try: os.killpg(os.getpgid(p.pid), signal.SIGKILL) except Exception: try: p.kill() except Exception: pass
def main(): urllib.request.urlretrieve(CLOUDFLARED, "cloudflared") os.chmod("cloudflared", 0o755) urllib.request.urlretrieve(SCRIPT_URL, "capture_trace.py") urllib.request.urlretrieve(EXAMPLE_URL, "opencode_hf_sandbox.py") _log("downloaded cloudflared + capture script + the example it imports")
_log(f"serving {MODEL} on GPU 0...") 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, ) cf = None try: for _ in range(300): if vllm.poll() is not None: _log(f"vLLM died early rc={vllm.returncode}") return 1 try: urllib.request.urlopen("http://localhost:8000/health", timeout=3) break except Exception: time.sleep(2) else: _log("vLLM never became healthy") return 1 _log("vLLM healthy (local)")
cflog = open("cf.log", "w") cf = subprocess.Popen(["./cloudflared", "tunnel", "--no-autoupdate", "--url", "http://localhost:8000"], stdout=cflog, stderr=subprocess.STDOUT, start_new_session=True) public = None for _ in range(60): time.sleep(2) m = re.search(r"https://[a-z0-9-]+\.trycloudflare\.com", open("cf.log").read()) if m: public = m.group(0) break if not public: _log("cloudflared did not produce a public URL") return 1 _log(f"public url for the sandbox: {public}")
cmd = [sys.executable, "capture_trace.py", "--model", MODEL, "--sandbox-vllm-url", public, "--task-index", TASK_INDEX, "--n-prompts", N_PROMPTS, "--seed", SEED, "--out-dir", "trace_artifact"] _log("capturing one rollout (boots a remote HF sandbox with opencode + the proxy)...") r = subprocess.run(cmd) return r.returncode finally: _log("shutting down vLLM + cloudflared...") if cf: _kill_pg(cf) _kill_pg(vllm)
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207# 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.
"""Capture ONE opencode rollout and write the trace out as a readable artifact.
This is not training. It reuses the same pieces as `opencode_hf_sandbox.py` (the session factory, thein-sandbox capture proxy, the held-out verifier) but drives a single session and dumps what the proxyrecorded. No trainer, no GRPO, no weight sync, so one GPU is enough.
What it writes to `--out-dir`:
trace.json the raw proxy trace, every captured model call in order turns.json the real agent turns, re-derived exactly as training does, with the fields the training path actually uses: prompt_ids, output_ids, per_token_logps, plus a derived `mask` (0 = context, 1 = model-generated) and `trained` task.json the instruction the agent was given, and its task id visible_tests.txt the example cases the agent could see, lifted from the statement held_out_tests.json the tests that produce the reward, which the agent never sees summary.json reward, turn counts, tool counts, how many turns training would keep
The `mask` field does not exist in the proxy trace: the trace has `completion_token_ids` for what themodel generated, and the context is re-tokenized from the request. It is emitted here because thedistinction is the whole point of the artifact, and it is labelled derived so nobody mistakes it forsomething the proxy recorded.
Needs a public OpenAI-compatible URL the remote sandbox can reach, serving `--model` with`--return-tokens-as-token-ids` so the proxy can recover exact ids. `capture_launcher.py` sets that up."""
import argparseimport jsonimport osimport reimport pathlibimport uuid
from transformers import AutoTokenizer
from opencode_hf_sandbox import ( # the example is the source of truth for task + factory construction N_TESTS_EVAL, _instruction_id, build_dataset, build_factory, opencode_agent_turns, opencode_reward,)from trl.experimental.async_grpo.openenv_harness import ( HarnessRolloutOutcome, _entry_to_turn, _messages_from_trace, _tool_call_counts_by_name, _tool_failure_count, _trace_output_ids, has_tool_call,)
def parse_args(): p = argparse.ArgumentParser(description="Capture one opencode rollout trace as a shareable artifact.") p.add_argument("--model", default="Qwen/Qwen3-8B") p.add_argument("--sandbox-vllm-url", required=True, help="Public url the remote sandbox reaches vLLM through.") p.add_argument("--n-prompts", type=int, default=64, help="Same as training, so task indices line up.") p.add_argument("--seed", type=int, default=0, help="build_dataset is deterministic on this.") p.add_argument("--task-index", type=int, default=0, help="Which task of the built dataset to capture.") p.add_argument("--sandbox-image", default="ghcr.io/huggingface/openenv-opencode-sandbox:latest") p.add_argument("--sandbox-flavor", default="cpu-basic") p.add_argument("--out-dir", default="trace_artifact") p.add_argument("--timeout-s", type=float, default=900.0) return p.parse_args()
def visible_tests_from(instruction: str) -> str: """The example cases live inside the statement, which is what makes them the agent's feedback. Pull the lines that look like input/output examples so the talk can show them next to the held-out ones.""" keep = [ line for line in instruction.splitlines() if re.search(r"^\s*(input|output|example|sample)\b", line, re.I) or re.match(r"^\s*-?\d+(\s+-?\d+)*\s*$", line) ] return "\n".join(keep) if keep else instruction
def main(): args = parse_args() out = pathlib.Path(args.out_dir) out.mkdir(parents=True, exist_ok=True)
rows, tests_by_id = build_dataset(n_prompts=args.n_prompts, seed=args.seed) if not 0 <= args.task_index < len(rows): raise SystemExit(f"--task-index {args.task_index} outside 0..{len(rows) - 1}") prompt = rows[args.task_index]["prompt"] instruction = prompt[-1]["content"] task_id = _instruction_id(instruction) held_out = tests_by_id[task_id] print(f"[task] index={args.task_index} id={task_id[:12]} held_out_tests={len(held_out)}", flush=True)
factory = build_factory(args.sandbox_vllm_url, args.model, tests_by_id, args.sandbox_image, args.sandbox_flavor) episode_id = uuid.uuid4().hex print("[session] creating (boots sandbox + opencode + capture proxy)...", flush=True) session = factory.create(prompt, seed=args.seed, episode_id=episode_id)
timed_out = False try: print("[session] waiting for the agent to finish its own loop...", flush=True) try: session.wait_for_completion(timeout_s=args.timeout_s) except TimeoutError: timed_out = True print("[session] agent timed out; capturing what it did produce", flush=True) trace = session.fetch_proxy_trace() print(f"[trace] {len(trace)} captured model calls", flush=True)
entries = opencode_agent_turns(trace) completion = _messages_from_trace(entries) tool_calls = _tool_call_counts_by_name(entries) verify = session.verify(completion) env_reward = float(verify.env_reward) if verify.env_reward is not None else None reward = opencode_reward( HarnessRolloutOutcome( env_reward=env_reward, completion=completion, trace=trace, tool_call_count=sum(tool_calls.values()), tool_failure_count=_tool_failure_count(entries), tool_calls_by_name=tool_calls, timed_out=timed_out, ) ) finally: try: session.close() except Exception: pass
tokenizer = AutoTokenizer.from_pretrained(args.model) turns = [] for n, entry in enumerate(entries): request = entry["request"] prompt_ids = tokenizer.apply_chat_template( request["messages"], tools=request.get("tools"), add_generation_prompt=True, tokenize=True, return_dict=False, ) output_ids = _trace_output_ids(entry) view = _entry_to_turn(entry) turns.append( { "turn": n, "trained": has_tool_call(view), "tool_calls": [tc.get("function", {}).get("name") for tc in view.tool_calls], "n_prompt_ids": len(prompt_ids), "n_output_ids": len(output_ids), "prompt_ids": prompt_ids, "output_ids": output_ids, "per_token_logps": entry.get("per_token_logps") or [], # DERIVED, not recorded by the proxy: 0 = context the environment and the history contributed, # 1 = tokens the model generated. Only the 1s get a gradient. "mask": [0] * len(prompt_ids) + [1] * len(output_ids), } )
(out / "trace.json").write_text(json.dumps({"turns": trace}, indent=2)) (out / "turns.json").write_text(json.dumps({"turns": turns}, indent=2)) (out / "task.json").write_text(json.dumps({"task_id": task_id, "task_index": args.task_index, "instruction": instruction}, indent=2)) (out / "visible_tests.txt").write_text(visible_tests_from(instruction)) (out / "held_out_tests.json").write_text(json.dumps(held_out, indent=2)) summary = { "model": args.model, "task_id": task_id, "captured_calls": len(trace), "agent_turns": len(entries), "trained_turns": sum(1 for t in turns if t["trained"]), "tool_calls_by_name": tool_calls, "held_out_tests": len(held_out), "n_tests_eval_cap": N_TESTS_EVAL, "env_reward": env_reward, "reward_after_penalties": reward, "timed_out": timed_out, } (out / "summary.json").write_text(json.dumps(summary, indent=2)) print("[done] " + json.dumps(summary), flush=True)
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) api.upload_folder(folder_path=str(out), repo_id=repo, repo_type="dataset", commit_message="Capture one opencode rollout trace") print(f"[push] https://huggingface.co/datasets/{repo}", flush=True)
if __name__ == "__main__": main()README.mdAdded+77
capture_launcher.pyAdded+147
capture_trace.pyAdded+207