File size: 9,684 Bytes
2ed66ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e4497c4
 
 
 
 
 
2ed66ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e4497c4
2ed66ed
 
 
 
 
 
 
e4497c4
 
2ed66ed
 
 
 
e4497c4
2ed66ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 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, the
in-sandbox capture proxy, the held-out verifier) but drives a single session and dumps what the proxy
recorded. 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 the
model generated, and the context is re-tokenized from the request. It is emitted here because the
distinction is the whole point of the artifact, and it is labelled derived so nobody mistakes it for
something 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 argparse
import json
import os
import re
import pathlib
import 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="Dataset seed. build_dataset is deterministic on this, so it also decides WHICH task "
                        "each index points at. Change it and --task-index selects a different problem.")
    p.add_argument("--rollout-seed", type=int, default=None,
                   help="Seed for the rollout only, so you can sample the SAME task several times. "
                        "Defaults to --seed.")
    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)

    rollout_seed = args.rollout_seed if args.rollout_seed is not None else args.seed
    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)} "
          f"dataset_seed={args.seed} rollout_seed={rollout_seed}", 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=rollout_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()