File size: 8,849 Bytes
b3e698c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
223
224
225
226
227
228
229
"""traj-normalize CLI: Nebius OpenHands parquet -> SFT-ready jsonl.

Usage:
    traj-normalize --input nebius/SWE-rebench-openhands-trajectories \
        --out-dir out --max-success 5000 --seed 0
    traj-normalize --input /path/to/trajectories.parquet --out-dir out
"""

from __future__ import annotations

import argparse
import json
import random
import sys
import time
from pathlib import Path

import pyarrow.parquet as pq

from .core import Stats, load_tools_schema, normalize_row, row_to_record

META_COLS = ["trajectory_id", "instance_id", "repo", "resolved"]
DEFAULT_REPO = "nebius/SWE-rebench-openhands-trajectories"
DEFAULT_DATA_FILE = "trajectories.parquet"


def resolve_input(inp: str) -> tuple[Path, str]:
    """Return (parquet_path, source_desc). Downloads from the Hub if needed."""
    p = Path(inp)
    if p.is_file():
        return p, str(p.resolve())
    from huggingface_hub import hf_hub_download

    path = hf_hub_download(repo_id=inp, repo_type="dataset", filename=DEFAULT_DATA_FILE)
    return Path(path), inp


def resolve_tools_json(tools_arg: str | None, source: str) -> str | None:
    if tools_arg:
        return tools_arg
    # If input came from the Hub, try to fetch tools.json from the same repo.
    if not Path(source).is_file():
        try:
            from huggingface_hub import hf_hub_download

            return hf_hub_download(repo_id=source, repo_type="dataset", filename="tools.json")
        except Exception:
            return None
    # Local file: look for tools.json next to the parquet.
    cand = Path(source).parent / "tools.json"
    return str(cand) if cand.exists() else None


def pass1_select_indices(pf: pq.ParquetFile, args) -> tuple[set[int], Stats]:
    """Scan light columns; return selected row indices + populated counters."""
    stats = Stats()
    resolved_idx, fail_idx = [], []
    offset = 0
    for batch in pf.iter_batches(batch_size=args.batch_size, columns=META_COLS):
        for row in batch.to_pylist():
            stats.input_rows += 1
            if row.get("resolved") == 1:
                stats.resolved_rows += 1
                resolved_idx.append(offset)
            else:
                fail_idx.append(offset)
            offset += 1
            if args.limit and stats.input_rows >= args.limit:
                break
        if args.limit and stats.input_rows >= args.limit:
            break

    rng = random.Random(args.seed)
    if args.max_success and len(resolved_idx) > args.max_success:
        resolved_idx = sorted(rng.sample(resolved_idx, args.max_success))
    if args.include_failures:
        if args.max_fail and len(fail_idx) > args.max_fail:
            fail_idx = sorted(rng.sample(fail_idx, args.max_fail))
    else:
        fail_idx = []

    selected = set(resolved_idx) | set(fail_idx)
    return selected, stats


def run(args) -> int:
    parquet_path, source = resolve_input(args.input)
    tools_path = resolve_tools_json(args.tools_json, source)
    tools_schema = load_tools_schema(tools_path)
    if args.tools_json and tools_schema is None:
        print(f"warning: could not load tools schema from {args.tools_json}", file=sys.stderr)

    out_dir = Path(args.out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)
    success_path = out_dir / "sft_success.jsonl"
    fail_path = out_dir / "sft_fail.jsonl"
    meta_path = out_dir / "meta.json"

    pf = pq.ParquetFile(parquet_path)
    t0 = time.time()

    selected, stats = pass1_select_indices(pf, args)
    print(f"scanned {stats.input_rows} rows ({stats.resolved_rows} resolved); "
          f"selected {len(selected)} for extraction", file=sys.stderr)

    # Pass 2: full rows for selected indices.
    records = [] if args.shuffle else None
    f_succ = open(success_path, "w")
    f_fail = open(fail_path, "w") if args.include_failures else None
    offset = 0
    try:
        for batch in pf.iter_batches(batch_size=args.batch_size):
            for row in batch.to_pylist():
                idx = offset
                offset += 1
                if args.limit and idx >= args.limit:
                    break
                if idx not in selected:
                    continue
                messages, err = normalize_row(row, stats, tools_schema, args.strict_tools)
                if err:
                    stats.drop(err)
                    continue
                rec = row_to_record(row, messages, emit_tools=not args.no_tools)
                if records is not None:
                    records.append(rec)
                else:
                    (f_succ if rec["resolved"] == 1 else f_fail).write(
                        json.dumps(rec, ensure_ascii=False) + "\n")
                if rec["resolved"] == 1:
                    stats.written_success += 1
                else:
                    stats.written_fail += 1
            if args.limit and offset >= args.limit:
                break

        if records is not None:
            rng = random.Random(args.seed)
            rng.shuffle(records)
            stats.written_success = stats.written_fail = 0
            for rec in records:
                (f_succ if rec["resolved"] == 1 else f_fail).write(
                    json.dumps(rec, ensure_ascii=False) + "\n")
                if rec["resolved"] == 1:
                    stats.written_success += 1
                else:
                    stats.written_fail += 1
    finally:
        f_succ.close()
        if f_fail:
            f_fail.close()

    if not args.include_failures and fail_path.exists():
        fail_path.unlink()

    stats.skipped_unresolved = stats.input_rows - stats.resolved_rows

    meta = {
        "tool": "traj-normalize",
        "source": source,
        "tools_schema": tools_path if tools_schema else None,
        "params": {
            "limit": args.limit,
            "max_success": args.max_success,
            "max_fail": args.max_fail if args.include_failures else None,
            "include_failures": args.include_failures,
            "seed": args.seed,
            "shuffle": args.shuffle,
            "strict_tools": args.strict_tools,
        },
        "counts": {
            "input_rows": stats.input_rows,
            "resolved_rows": stats.resolved_rows,
            "written_success": stats.written_success,
            "written_fail": stats.written_fail,
            "skipped_unresolved": stats.skipped_unresolved,
            "dropped": sum(stats.drop_reasons.values()),
        },
        "drop_reasons": stats.drop_reasons,
        "fixes": stats.fixes,
        "unknown_tools": stats.unknown_tools,
        "missing_required_params": stats.missing_required_params,
        "unparseable_examples": stats.unparseable_examples,
        "outputs": {
            p.name: p.stat().st_size for p in (success_path, fail_path) if p.exists()
        },
        "elapsed_sec": round(time.time() - t0, 1),
    }
    meta_path.write_text(json.dumps(meta, indent=2, ensure_ascii=False))
    print(json.dumps(meta["counts"], indent=2), file=sys.stderr)
    print(f"wrote {success_path} (+meta {meta_path})", file=sys.stderr)
    return 0


def build_parser() -> argparse.ArgumentParser:
    ap = argparse.ArgumentParser(
        prog="traj-normalize",
        description="Deserialize Nebius OpenHands trajectories into SFT-ready message lists.",
    )
    ap.add_argument("--input", default=DEFAULT_REPO,
                    help="Local parquet path or HF dataset repo id (default: %(default)s)")
    ap.add_argument("--out-dir", default="out")
    ap.add_argument("--tools-json", default=None,
                    help="Path to upstream tools.json for soft validation (auto-fetched for Hub input)")
    ap.add_argument("--limit", type=int, default=0, help="Max input rows to scan (0 = all)")
    ap.add_argument("--max-success", type=int, default=0,
                    help="Cap on resolved trajectories written (0 = all). Random sample with --seed.")
    ap.add_argument("--include-failures", action="store_true",
                    help="Also write unresolved trajectories to sft_fail.jsonl")
    ap.add_argument("--max-fail", type=int, default=0, help="Cap on failure trajectories (0 = all)")
    ap.add_argument("--seed", type=int, default=0)
    ap.add_argument("--shuffle", action="store_true",
                    help="Shuffle output records (buffers selected rows in memory)")
    ap.add_argument("--strict-tools", action="store_true",
                    help="Drop trajectories calling tools absent from tools.json")
    ap.add_argument("--no-tools", action="store_true",
                    help="Do not embed the per-row tool list in each record")
    ap.add_argument("--batch-size", type=int, default=32)
    return ap


def main(argv=None) -> int:
    args = build_parser().parse_args(argv)
    return run(args)


if __name__ == "__main__":
    sys.exit(main())