The capture code for the Lisbon talk artefact (the trace itself lands after the run)
Browse files- README.md +77 -0
- capture_launcher.py +147 -0
- capture_trace.py +207 -0
README.md
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
tags:
|
| 4 |
+
- rl
|
| 5 |
+
- trl
|
| 6 |
+
- openenv
|
| 7 |
+
- agents
|
| 8 |
+
---
|
| 9 |
+
|
| 10 |
+
# One opencode rollout, as the trainer sees it
|
| 11 |
+
|
| 12 |
+
The artefact behind the talk **Training a coding agent through a harness you did not write**
|
| 13 |
+
([Lisbon AI](https://lisbonai.org/), September 2026).
|
| 14 |
+
|
| 15 |
+
An off-the-shelf coding agent, [opencode](https://github.com/sst/opencode), runs untouched in a
|
| 16 |
+
remote sandbox. A proxy sits between it and vLLM, speaks the agent's own dialect, and records every
|
| 17 |
+
model call the agent makes together with the exact token ids and logprobs. That recording is what
|
| 18 |
+
gets trained on. This repo is one of those recordings, plus the code that produced it.
|
| 19 |
+
|
| 20 |
+
Nothing here is a transcript. A transcript would be text, and retokenising text gives you different
|
| 21 |
+
ids than the ones the model actually sampled. That difference is the point.
|
| 22 |
+
|
| 23 |
+
## Files
|
| 24 |
+
|
| 25 |
+
| File | What it is |
|
| 26 |
+
|---|---|
|
| 27 |
+
| `trace.json` | the raw proxy trace: every captured model call, in order, as recorded |
|
| 28 |
+
| `turns.json` | the real agent turns, derived exactly as training derives them (see below) |
|
| 29 |
+
| `task.json` | the instruction the agent was given, and its task id |
|
| 30 |
+
| `visible_tests.txt` | the example cases the agent could see, from the problem statement |
|
| 31 |
+
| `held_out_tests.json` | the tests that produce the reward, which the agent never sees |
|
| 32 |
+
| `summary.json` | reward, turn counts, tool counts, and how many turns training keeps |
|
| 33 |
+
| `capture_trace.py` | drives one session and writes all of the above |
|
| 34 |
+
| `capture_launcher.py` | serves vLLM, opens a tunnel, runs the capture, as one HF Job |
|
| 35 |
+
|
| 36 |
+
### Reading `turns.json`
|
| 37 |
+
|
| 38 |
+
Each turn carries what the training path actually uses:
|
| 39 |
+
|
| 40 |
+
- `prompt_ids`: the conversation sent to the model that turn, re-tokenized with its tools, so the
|
| 41 |
+
prompt matches what the upstream rendered
|
| 42 |
+
- `output_ids`: the ids the model generated, taken from the capture and **not** re-encoded
|
| 43 |
+
- `per_token_logps`: the generator's logprobs for those ids
|
| 44 |
+
- `trained`: whether the training policy keeps this turn. Here it is `has_tool_call`, so turns where
|
| 45 |
+
the model took an action are kept and pure-text turns are not
|
| 46 |
+
- `mask`: **derived, not recorded.** `0` for the context, `1` for the tokens the model generated.
|
| 47 |
+
The proxy never stores a mask, the distinction is structural: only `output_ids` get a gradient.
|
| 48 |
+
It is materialised here because that distinction is the whole reason the artefact is interesting.
|
| 49 |
+
|
| 50 |
+
Turn count in `turns.json` is smaller than in `trace.json` on purpose. opencode fires extra model
|
| 51 |
+
calls for its own bookkeeping, a title generator and a context summariser, and those are not the
|
| 52 |
+
task. Training them with the rollout's reward would reinforce the wrong thing, so they are filtered
|
| 53 |
+
by anchoring on the system prompt of the first tool-enabled turn.
|
| 54 |
+
|
| 55 |
+
## Reproducing it
|
| 56 |
+
|
| 57 |
+
```sh
|
| 58 |
+
TASK_INDEX=0 PUSH_TO_DATASET=sergiopaniego/opencode-rollout-trace \
|
| 59 |
+
hf jobs uv run --flavor a100-large --secrets HF_TOKEN --timeout 3600s \
|
| 60 |
+
"https://huggingface.co/datasets/sergiopaniego/opencode-rollout-trace/resolve/main/capture_launcher.py"
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
One GPU is enough: this captures, it does not train, so there is no weight sync. The vLLM flags
|
| 64 |
+
matter, `--return-tokens-as-token-ids` is what lets the proxy recover exact ids instead of
|
| 65 |
+
re-encoding decoded text.
|
| 66 |
+
|
| 67 |
+
`build_dataset(n_prompts, seed)` in the training example is deterministic, so `TASK_INDEX` selects a
|
| 68 |
+
reproducible task. Keep `N_PROMPTS` equal to what the training run used and the indices line up.
|
| 69 |
+
|
| 70 |
+
## Where this comes from
|
| 71 |
+
|
| 72 |
+
- Training script, maintained upstream in TRL:
|
| 73 |
+
[`examples/async_grpo_opencode/opencode_hf_sandbox.py`](https://github.com/huggingface/trl/blob/main/examples/async_grpo_opencode/opencode_hf_sandbox.py)
|
| 74 |
+
- Write-up: [Training a coding agent using the OpenCode harness](https://huggingface.co/blog/sergiopaniego/trl-openenv-harness-training)
|
| 75 |
+
- Task data: [DeepCoder-Preview-Dataset](https://huggingface.co/datasets/agentica-org/DeepCoder-Preview-Dataset)
|
| 76 |
+
- Sandbox image: `ghcr.io/huggingface/openenv-opencode-sandbox:latest`
|
| 77 |
+
- The policy trained this way: [Qwen3-8B-opencode-deepcoder-grpo](https://huggingface.co/sergiopaniego/Qwen3-8B-opencode-deepcoder-grpo)
|
capture_launcher.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl",
|
| 18 |
+
# "vllm",
|
| 19 |
+
# "datasets>=3.2",
|
| 20 |
+
# "huggingface_hub",
|
| 21 |
+
# "openenv-opencode-env @ git+https://github.com/huggingface/OpenEnv.git#subdirectory=envs/opencode_env",
|
| 22 |
+
# ]
|
| 23 |
+
# ///
|
| 24 |
+
|
| 25 |
+
"""
|
| 26 |
+
Capture one opencode rollout trace in a single HF Job.
|
| 27 |
+
|
| 28 |
+
Same shape as `launcher.py` but without the trainer, so one GPU is enough: serve vLLM, expose it with a
|
| 29 |
+
cloudflared tunnel so the remote sandbox can reach it, then run `capture_trace.py` for exactly one
|
| 30 |
+
rollout and write the artifact out.
|
| 31 |
+
|
| 32 |
+
```sh
|
| 33 |
+
TASK_INDEX=0 PUSH_TO_DATASET=sergiopaniego/opencode-rollout-trace \
|
| 34 |
+
hf jobs uv run --flavor a100-large --secrets HF_TOKEN --timeout 3600s capture_launcher.py
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
Environment variables: `MODEL` (default `Qwen/Qwen3-8B`), `TASK_INDEX` (default 0), `N_PROMPTS`
|
| 38 |
+
(default 64, keep it equal to what training used so task indices line up), `SEED` (default 0),
|
| 39 |
+
`PUSH_TO_DATASET` (optional dataset repo to upload the artifact to).
|
| 40 |
+
|
| 41 |
+
The vLLM flags matter: `--return-tokens-as-token-ids` is what lets the in-sandbox proxy recover exact
|
| 42 |
+
token ids instead of re-encoding decoded text, and `--logprobs-mode processed_logprobs` gives the
|
| 43 |
+
logprobs the trainer would use. `--weight-transfer-config` is NOT set here: nothing is training.
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
import os
|
| 47 |
+
import re
|
| 48 |
+
import signal
|
| 49 |
+
import subprocess
|
| 50 |
+
import sys
|
| 51 |
+
import time
|
| 52 |
+
import urllib.request
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
SCRIPT_URL = (
|
| 56 |
+
"https://huggingface.co/datasets/sergiopaniego/opencode-rollout-trace/resolve/main/capture_trace.py"
|
| 57 |
+
)
|
| 58 |
+
EXAMPLE_URL = (
|
| 59 |
+
"https://raw.githubusercontent.com/huggingface/trl/"
|
| 60 |
+
"main/examples/async_grpo_opencode/opencode_hf_sandbox.py"
|
| 61 |
+
)
|
| 62 |
+
CLOUDFLARED = "https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64"
|
| 63 |
+
|
| 64 |
+
MODEL = os.environ.get("MODEL", "Qwen/Qwen3-8B")
|
| 65 |
+
TASK_INDEX = os.environ.get("TASK_INDEX", "0")
|
| 66 |
+
N_PROMPTS = os.environ.get("N_PROMPTS", "64")
|
| 67 |
+
SEED = os.environ.get("SEED", "0")
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _log(m):
|
| 71 |
+
print(">>> " + m, flush=True)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _kill_pg(p):
|
| 75 |
+
try:
|
| 76 |
+
os.killpg(os.getpgid(p.pid), signal.SIGKILL)
|
| 77 |
+
except Exception:
|
| 78 |
+
try:
|
| 79 |
+
p.kill()
|
| 80 |
+
except Exception:
|
| 81 |
+
pass
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def main():
|
| 85 |
+
urllib.request.urlretrieve(CLOUDFLARED, "cloudflared")
|
| 86 |
+
os.chmod("cloudflared", 0o755)
|
| 87 |
+
urllib.request.urlretrieve(SCRIPT_URL, "capture_trace.py")
|
| 88 |
+
urllib.request.urlretrieve(EXAMPLE_URL, "opencode_hf_sandbox.py")
|
| 89 |
+
_log("downloaded cloudflared + capture script + the example it imports")
|
| 90 |
+
|
| 91 |
+
_log(f"serving {MODEL} on GPU 0...")
|
| 92 |
+
vllm = subprocess.Popen(
|
| 93 |
+
["vllm", "serve", MODEL, "--max-model-len", "40960", "--logprobs-mode", "processed_logprobs",
|
| 94 |
+
"--return-tokens-as-token-ids", "--enable-auto-tool-choice", "--tool-call-parser", "hermes"],
|
| 95 |
+
env={**os.environ, "VLLM_USE_FLASHINFER_SAMPLER": "0"},
|
| 96 |
+
start_new_session=True,
|
| 97 |
+
)
|
| 98 |
+
cf = None
|
| 99 |
+
try:
|
| 100 |
+
for _ in range(300):
|
| 101 |
+
if vllm.poll() is not None:
|
| 102 |
+
_log(f"vLLM died early rc={vllm.returncode}")
|
| 103 |
+
return 1
|
| 104 |
+
try:
|
| 105 |
+
urllib.request.urlopen("http://localhost:8000/health", timeout=3)
|
| 106 |
+
break
|
| 107 |
+
except Exception:
|
| 108 |
+
time.sleep(2)
|
| 109 |
+
else:
|
| 110 |
+
_log("vLLM never became healthy")
|
| 111 |
+
return 1
|
| 112 |
+
_log("vLLM healthy (local)")
|
| 113 |
+
|
| 114 |
+
cflog = open("cf.log", "w")
|
| 115 |
+
cf = subprocess.Popen(["./cloudflared", "tunnel", "--no-autoupdate", "--url", "http://localhost:8000"],
|
| 116 |
+
stdout=cflog, stderr=subprocess.STDOUT, start_new_session=True)
|
| 117 |
+
public = None
|
| 118 |
+
for _ in range(60):
|
| 119 |
+
time.sleep(2)
|
| 120 |
+
m = re.search(r"https://[a-z0-9-]+\.trycloudflare\.com", open("cf.log").read())
|
| 121 |
+
if m:
|
| 122 |
+
public = m.group(0)
|
| 123 |
+
break
|
| 124 |
+
if not public:
|
| 125 |
+
_log("cloudflared did not produce a public URL")
|
| 126 |
+
return 1
|
| 127 |
+
_log(f"public url for the sandbox: {public}")
|
| 128 |
+
|
| 129 |
+
cmd = [sys.executable, "capture_trace.py",
|
| 130 |
+
"--model", MODEL,
|
| 131 |
+
"--sandbox-vllm-url", public,
|
| 132 |
+
"--task-index", TASK_INDEX,
|
| 133 |
+
"--n-prompts", N_PROMPTS,
|
| 134 |
+
"--seed", SEED,
|
| 135 |
+
"--out-dir", "trace_artifact"]
|
| 136 |
+
_log("capturing one rollout (boots a remote HF sandbox with opencode + the proxy)...")
|
| 137 |
+
r = subprocess.run(cmd)
|
| 138 |
+
return r.returncode
|
| 139 |
+
finally:
|
| 140 |
+
_log("shutting down vLLM + cloudflared...")
|
| 141 |
+
if cf:
|
| 142 |
+
_kill_pg(cf)
|
| 143 |
+
_kill_pg(vllm)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
if __name__ == "__main__":
|
| 147 |
+
raise SystemExit(main())
|
capture_trace.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""
|
| 16 |
+
Capture ONE opencode rollout and write the trace out as a readable artifact.
|
| 17 |
+
|
| 18 |
+
This is not training. It reuses the same pieces as `opencode_hf_sandbox.py` (the session factory, the
|
| 19 |
+
in-sandbox capture proxy, the held-out verifier) but drives a single session and dumps what the proxy
|
| 20 |
+
recorded. No trainer, no GRPO, no weight sync, so one GPU is enough.
|
| 21 |
+
|
| 22 |
+
What it writes to `--out-dir`:
|
| 23 |
+
|
| 24 |
+
trace.json the raw proxy trace, every captured model call in order
|
| 25 |
+
turns.json the real agent turns, re-derived exactly as training does, with the fields
|
| 26 |
+
the training path actually uses: prompt_ids, output_ids, per_token_logps,
|
| 27 |
+
plus a derived `mask` (0 = context, 1 = model-generated) and `trained`
|
| 28 |
+
task.json the instruction the agent was given, and its task id
|
| 29 |
+
visible_tests.txt the example cases the agent could see, lifted from the statement
|
| 30 |
+
held_out_tests.json the tests that produce the reward, which the agent never sees
|
| 31 |
+
summary.json reward, turn counts, tool counts, how many turns training would keep
|
| 32 |
+
|
| 33 |
+
The `mask` field does not exist in the proxy trace: the trace has `completion_token_ids` for what the
|
| 34 |
+
model generated, and the context is re-tokenized from the request. It is emitted here because the
|
| 35 |
+
distinction is the whole point of the artifact, and it is labelled derived so nobody mistakes it for
|
| 36 |
+
something the proxy recorded.
|
| 37 |
+
|
| 38 |
+
Needs a public OpenAI-compatible URL the remote sandbox can reach, serving `--model` with
|
| 39 |
+
`--return-tokens-as-token-ids` so the proxy can recover exact ids. `capture_launcher.py` sets that up.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
import argparse
|
| 43 |
+
import json
|
| 44 |
+
import os
|
| 45 |
+
import re
|
| 46 |
+
import pathlib
|
| 47 |
+
import uuid
|
| 48 |
+
|
| 49 |
+
from transformers import AutoTokenizer
|
| 50 |
+
|
| 51 |
+
from opencode_hf_sandbox import ( # the example is the source of truth for task + factory construction
|
| 52 |
+
N_TESTS_EVAL,
|
| 53 |
+
_instruction_id,
|
| 54 |
+
build_dataset,
|
| 55 |
+
build_factory,
|
| 56 |
+
opencode_agent_turns,
|
| 57 |
+
opencode_reward,
|
| 58 |
+
)
|
| 59 |
+
from trl.experimental.async_grpo.openenv_harness import (
|
| 60 |
+
HarnessRolloutOutcome,
|
| 61 |
+
_entry_to_turn,
|
| 62 |
+
_messages_from_trace,
|
| 63 |
+
_tool_call_counts_by_name,
|
| 64 |
+
_tool_failure_count,
|
| 65 |
+
_trace_output_ids,
|
| 66 |
+
has_tool_call,
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def parse_args():
|
| 71 |
+
p = argparse.ArgumentParser(description="Capture one opencode rollout trace as a shareable artifact.")
|
| 72 |
+
p.add_argument("--model", default="Qwen/Qwen3-8B")
|
| 73 |
+
p.add_argument("--sandbox-vllm-url", required=True, help="Public url the remote sandbox reaches vLLM through.")
|
| 74 |
+
p.add_argument("--n-prompts", type=int, default=64, help="Same as training, so task indices line up.")
|
| 75 |
+
p.add_argument("--seed", type=int, default=0, help="build_dataset is deterministic on this.")
|
| 76 |
+
p.add_argument("--task-index", type=int, default=0, help="Which task of the built dataset to capture.")
|
| 77 |
+
p.add_argument("--sandbox-image", default="ghcr.io/huggingface/openenv-opencode-sandbox:latest")
|
| 78 |
+
p.add_argument("--sandbox-flavor", default="cpu-basic")
|
| 79 |
+
p.add_argument("--out-dir", default="trace_artifact")
|
| 80 |
+
p.add_argument("--timeout-s", type=float, default=900.0)
|
| 81 |
+
return p.parse_args()
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def visible_tests_from(instruction: str) -> str:
|
| 85 |
+
"""The example cases live inside the statement, which is what makes them the agent's feedback. Pull the lines
|
| 86 |
+
that look like input/output examples so the talk can show them next to the held-out ones."""
|
| 87 |
+
keep = [
|
| 88 |
+
line
|
| 89 |
+
for line in instruction.splitlines()
|
| 90 |
+
if re.search(r"^\s*(input|output|example|sample)\b", line, re.I) or re.match(r"^\s*-?\d+(\s+-?\d+)*\s*$", line)
|
| 91 |
+
]
|
| 92 |
+
return "\n".join(keep) if keep else instruction
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def main():
|
| 96 |
+
args = parse_args()
|
| 97 |
+
out = pathlib.Path(args.out_dir)
|
| 98 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 99 |
+
|
| 100 |
+
rows, tests_by_id = build_dataset(n_prompts=args.n_prompts, seed=args.seed)
|
| 101 |
+
if not 0 <= args.task_index < len(rows):
|
| 102 |
+
raise SystemExit(f"--task-index {args.task_index} outside 0..{len(rows) - 1}")
|
| 103 |
+
prompt = rows[args.task_index]["prompt"]
|
| 104 |
+
instruction = prompt[-1]["content"]
|
| 105 |
+
task_id = _instruction_id(instruction)
|
| 106 |
+
held_out = tests_by_id[task_id]
|
| 107 |
+
print(f"[task] index={args.task_index} id={task_id[:12]} held_out_tests={len(held_out)}", flush=True)
|
| 108 |
+
|
| 109 |
+
factory = build_factory(args.sandbox_vllm_url, args.model, tests_by_id, args.sandbox_image, args.sandbox_flavor)
|
| 110 |
+
episode_id = uuid.uuid4().hex
|
| 111 |
+
print("[session] creating (boots sandbox + opencode + capture proxy)...", flush=True)
|
| 112 |
+
session = factory.create(prompt, seed=args.seed, episode_id=episode_id)
|
| 113 |
+
|
| 114 |
+
timed_out = False
|
| 115 |
+
try:
|
| 116 |
+
print("[session] waiting for the agent to finish its own loop...", flush=True)
|
| 117 |
+
try:
|
| 118 |
+
session.wait_for_completion(timeout_s=args.timeout_s)
|
| 119 |
+
except TimeoutError:
|
| 120 |
+
timed_out = True
|
| 121 |
+
print("[session] agent timed out; capturing what it did produce", flush=True)
|
| 122 |
+
trace = session.fetch_proxy_trace()
|
| 123 |
+
print(f"[trace] {len(trace)} captured model calls", flush=True)
|
| 124 |
+
|
| 125 |
+
entries = opencode_agent_turns(trace)
|
| 126 |
+
completion = _messages_from_trace(entries)
|
| 127 |
+
tool_calls = _tool_call_counts_by_name(entries)
|
| 128 |
+
verify = session.verify(completion)
|
| 129 |
+
env_reward = float(verify.env_reward) if verify.env_reward is not None else None
|
| 130 |
+
reward = opencode_reward(
|
| 131 |
+
HarnessRolloutOutcome(
|
| 132 |
+
env_reward=env_reward,
|
| 133 |
+
completion=completion,
|
| 134 |
+
trace=trace,
|
| 135 |
+
tool_call_count=sum(tool_calls.values()),
|
| 136 |
+
tool_failure_count=_tool_failure_count(entries),
|
| 137 |
+
tool_calls_by_name=tool_calls,
|
| 138 |
+
timed_out=timed_out,
|
| 139 |
+
)
|
| 140 |
+
)
|
| 141 |
+
finally:
|
| 142 |
+
try:
|
| 143 |
+
session.close()
|
| 144 |
+
except Exception:
|
| 145 |
+
pass
|
| 146 |
+
|
| 147 |
+
tokenizer = AutoTokenizer.from_pretrained(args.model)
|
| 148 |
+
turns = []
|
| 149 |
+
for n, entry in enumerate(entries):
|
| 150 |
+
request = entry["request"]
|
| 151 |
+
prompt_ids = tokenizer.apply_chat_template(
|
| 152 |
+
request["messages"], tools=request.get("tools"), add_generation_prompt=True, tokenize=True,
|
| 153 |
+
return_dict=False,
|
| 154 |
+
)
|
| 155 |
+
output_ids = _trace_output_ids(entry)
|
| 156 |
+
view = _entry_to_turn(entry)
|
| 157 |
+
turns.append(
|
| 158 |
+
{
|
| 159 |
+
"turn": n,
|
| 160 |
+
"trained": has_tool_call(view),
|
| 161 |
+
"tool_calls": [tc.get("function", {}).get("name") for tc in view.tool_calls],
|
| 162 |
+
"n_prompt_ids": len(prompt_ids),
|
| 163 |
+
"n_output_ids": len(output_ids),
|
| 164 |
+
"prompt_ids": prompt_ids,
|
| 165 |
+
"output_ids": output_ids,
|
| 166 |
+
"per_token_logps": entry.get("per_token_logps") or [],
|
| 167 |
+
# DERIVED, not recorded by the proxy: 0 = context the environment and the history contributed,
|
| 168 |
+
# 1 = tokens the model generated. Only the 1s get a gradient.
|
| 169 |
+
"mask": [0] * len(prompt_ids) + [1] * len(output_ids),
|
| 170 |
+
}
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
(out / "trace.json").write_text(json.dumps({"turns": trace}, indent=2))
|
| 174 |
+
(out / "turns.json").write_text(json.dumps({"turns": turns}, indent=2))
|
| 175 |
+
(out / "task.json").write_text(json.dumps({"task_id": task_id, "task_index": args.task_index,
|
| 176 |
+
"instruction": instruction}, indent=2))
|
| 177 |
+
(out / "visible_tests.txt").write_text(visible_tests_from(instruction))
|
| 178 |
+
(out / "held_out_tests.json").write_text(json.dumps(held_out, indent=2))
|
| 179 |
+
summary = {
|
| 180 |
+
"model": args.model,
|
| 181 |
+
"task_id": task_id,
|
| 182 |
+
"captured_calls": len(trace),
|
| 183 |
+
"agent_turns": len(entries),
|
| 184 |
+
"trained_turns": sum(1 for t in turns if t["trained"]),
|
| 185 |
+
"tool_calls_by_name": tool_calls,
|
| 186 |
+
"held_out_tests": len(held_out),
|
| 187 |
+
"n_tests_eval_cap": N_TESTS_EVAL,
|
| 188 |
+
"env_reward": env_reward,
|
| 189 |
+
"reward_after_penalties": reward,
|
| 190 |
+
"timed_out": timed_out,
|
| 191 |
+
}
|
| 192 |
+
(out / "summary.json").write_text(json.dumps(summary, indent=2))
|
| 193 |
+
print("[done] " + json.dumps(summary), flush=True)
|
| 194 |
+
|
| 195 |
+
if os.environ.get("PUSH_TO_DATASET"):
|
| 196 |
+
from huggingface_hub import HfApi
|
| 197 |
+
|
| 198 |
+
repo = os.environ["PUSH_TO_DATASET"]
|
| 199 |
+
api = HfApi()
|
| 200 |
+
api.create_repo(repo, repo_type="dataset", exist_ok=True)
|
| 201 |
+
api.upload_folder(folder_path=str(out), repo_id=repo, repo_type="dataset",
|
| 202 |
+
commit_message="Capture one opencode rollout trace")
|
| 203 |
+
print(f"[push] https://huggingface.co/datasets/{repo}", flush=True)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
if __name__ == "__main__":
|
| 207 |
+
main()
|