asaverren commited on
Commit
b3e698c
·
verified ·
1 Parent(s): 013ae35

5k resolved OpenHands trajectories, tool-call arguments deserialized, Qwen3-Coder-template-verified

Browse files
.gitattributes CHANGED
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ sft_success.jsonl.gz.box-store-snap-6600a926e22faf88 filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-4.0
3
+ task_categories:
4
+ - text-generation
5
+ tags:
6
+ - agent-trajectories
7
+ - tool-calling
8
+ - sft
9
+ - openhands
10
+ - swe-bench
11
+ - qwen3-coder
12
+ size_categories:
13
+ - 1K<n<10K
14
+ configs:
15
+ - config_name: default
16
+ data_files:
17
+ - split: train
18
+ path: data/train-00000-of-00001.parquet
19
+ ---
20
+
21
+ # openhands-train-ready
22
+
23
+ **SFT-ready normalization** of
24
+ [nebius/SWE-rebench-openhands-trajectories](https://huggingface.co/datasets/nebius/SWE-rebench-openhands-trajectories)
25
+ — 5,000 resolved OpenHands (v0.54.0) agent trajectories on real GitHub issues,
26
+ bootstrapped by `Qwen/Qwen3-Coder-480B-A35B-Instruct`, with **tool-call
27
+ arguments deserialized to objects** so chat templates just work.
28
+
29
+ ## What was fixed
30
+
31
+ The upstream parquet stores `tool_call.function.arguments` as a serialized
32
+ JSON *string* "for storage efficiency" (per the Nebius README). Chat templates
33
+ that iterate `arguments|items` — including the Qwen3-Coder family — emit
34
+ empty/broken tool calls if you train on the raw rows. Every record here has:
35
+
36
+ - `arguments` deserialized `str → dict` (double-encoded JSON and Python-repr
37
+ dicts handled),
38
+ - canonical per-role fields (`system`/`user`/`assistant`/`tool`),
39
+ - the per-trajectory `tools` list kept on the record — pass it straight to
40
+ `apply_chat_template`.
41
+
42
+ ## Usage
43
+
44
+ ```python
45
+ from datasets import load_dataset
46
+ from transformers import AutoTokenizer
47
+
48
+ ds = load_dataset("asaverren/openhands-train-ready", split="train")
49
+ tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-Coder-30B-A3B-Instruct")
50
+
51
+ ex = ds[0]
52
+ text = tok.apply_chat_template(ex["messages"], tools=ex["tools"], tokenize=False)
53
+ ```
54
+
55
+ TRL/axolotl: point your chat-template mapping at the `messages` column;
56
+ `tools` is a per-row column for templates that accept it.
57
+
58
+ ## Qwen3-Coder tool-call format (verified)
59
+
60
+ - Assistant calls render as `<tool_call><function=NAME><parameter=KEY>VALUE
61
+ </parameter></function></tool_call>` inside the `<|im_start|>assistant` turn.
62
+ - `arguments` must be a mapping — the template iterates `arguments|items`.
63
+ (This is the upstream storage bug this dataset fixes.)
64
+ - Tool results render as `<tool_response>...</tool_response>` inside a `user`
65
+ turn; `name`/`tool_call_id` are kept for provenance but unused by the template.
66
+
67
+ ## Counts (see `meta.json`)
68
+
69
+ | | |
70
+ |---|---|
71
+ | upstream rows scanned | 67,074 |
72
+ | upstream resolved | 32,161 |
73
+ | this shard (resolved, seed-0 sample) | 5,000 |
74
+ | tool-call arguments deserialized | 295,524 |
75
+ | unparseable arguments | 0 |
76
+ | unknown tools / missing required params | 0 / 0 |
77
+ | trajectories dropped | 0 |
78
+ | avg tokens (Qwen3-Coder tokenizer) | ≈ 49k / trajectory |
79
+
80
+ Tool calls validated against upstream `tools.json` (soft; all calls match the
81
+ 5-tool OpenHands v0.54.0 set). All 5,000 records render through the real
82
+ Qwen3-Coder chat template with zero errors.
83
+
84
+ ## Rebuild / extend
85
+
86
+ `run_normalize.py` (+ the `traj_normalize` package, both in this repo) reproduces this shard and can emit the full 32k resolved
87
+ set (or failure trajectories via `--include-failures`):
88
+
89
+ ```bash
90
+ pip install pyarrow huggingface_hub
91
+ python run_normalize.py --input nebius/SWE-rebench-openhands-trajectories \
92
+ --out-dir out --max-success 5000 --seed 0 --shuffle
93
+ ```
94
+
95
+ `sft_success.jsonl.gz` is the raw tool output; `data/` is the same content as
96
+ parquet for `load_dataset` + viewer support.
97
+
98
+ ## Honest limitations
99
+
100
+ - `resolved` is upstream's SWE-bench-style judgment — **no re-execution
101
+ verification** was performed downstream.
102
+ - Trajectories are long (~49k tokens avg); filter/truncate to your context
103
+ budget.
104
+ - Single bootstrap model (Qwen3-Coder-480B) and single scaffold
105
+ (OpenHands v0.54.0) — behavior/diversity is bounded accordingly.
106
+ - Same-instance duplicates are possible (upstream samples multiple attempts
107
+ per issue); dedupe on `instance_id` if that matters to you.
108
+
109
+ ## Attribution & license
110
+
111
+ Upstream data: [Nebius](https://nebius.com/blog/posts/openhands-trajectories-with-qwen3-coder-480b),
112
+ **CC-BY-4.0**. This derivative shard redistributes normalized data under the
113
+ same license — please attribute Nebius.
114
+
115
+ ```bibtex
116
+ @article{trofimova2025openhandstrajs,
117
+ title={OpenHands Trajectories with Qwen3-Coder-480B-A35B-Instruct},
118
+ author={Trofimova, Maria and Shevtsov, Anton and Ibragim, Badertdinov and Pyaev, Konstantin and Karasik, Simon and Golubev, Alexander},
119
+ year={2025},
120
+ journal={Nebius blog},
121
+ }
122
+ ```
data/train-00000-of-00001.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ee32b313863be211ba717c7806c1963a88ca54611ed2441f96afb4fd35ce6655
3
+ size 1273663192
meta.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "tool": "traj-normalize",
3
+ "source": "nebius/SWE-rebench-openhands-trajectories",
4
+ "tools_schema": "/home/box/.cache/huggingface/hub/datasets--nebius--SWE-rebench-openhands-trajectories/snapshots/35455389ab51bf5e2306bfd436ef72d0f98bf882/tools.json",
5
+ "params": {
6
+ "limit": 0,
7
+ "max_success": 5000,
8
+ "max_fail": null,
9
+ "include_failures": false,
10
+ "seed": 0,
11
+ "shuffle": true,
12
+ "strict_tools": false
13
+ },
14
+ "counts": {
15
+ "input_rows": 67074,
16
+ "resolved_rows": 32161,
17
+ "written_success": 5000,
18
+ "written_fail": 0,
19
+ "skipped_unresolved": 34913,
20
+ "dropped": 0
21
+ },
22
+ "drop_reasons": {},
23
+ "fixes": {
24
+ "arguments_deserialized": 295524
25
+ },
26
+ "unknown_tools": {},
27
+ "missing_required_params": {},
28
+ "unparseable_examples": [],
29
+ "outputs": {
30
+ "sft_success.jsonl": 1311591174
31
+ },
32
+ "elapsed_sec": 51.9
33
+ }
pyproject.toml ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "traj-normalize"
3
+ version = "0.1.0"
4
+ description = "Normalize Nebius SWE-rebench OpenHands trajectories into chat-template-ready SFT messages (deserializes stringified tool-call arguments)."
5
+ requires-python = ">=3.10"
6
+ dependencies = [
7
+ "pyarrow>=15",
8
+ "huggingface_hub>=0.24",
9
+ ]
10
+
11
+ [project.scripts]
12
+ traj-normalize = "traj_normalize:main"
13
+
14
+ [build-system]
15
+ requires = ["hatchling"]
16
+ build-backend = "hatchling.build"
17
+
18
+ [tool.hatch.build.targets.wheel]
19
+ packages = ["traj_normalize"]
run_normalize.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ from traj_normalize.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
sft_success.jsonl.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6fa2d861940766aeaa077c58927c114677b64ecc2602a7f1dfe2701f11340e3a
3
+ size 214412373
sft_success.jsonl.gz.box-store-snap-6600a926e22faf88 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6fa2d861940766aeaa077c58927c114677b64ecc2602a7f1dfe2701f11340e3a
3
+ size 214412373
tools.json ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "function": {
4
+ "description": "Execute a bash command in the terminal within a persistent shell session.\n\n\n### Command Execution\n* One command at a time: You can only execute one bash command at a time. If you need to run multiple commands sequentially, use `&&` or `;` to chain them together.\n* Persistent session: Commands execute in a persistent shell session where environment variables, virtual environments, and working directory persist between commands.\n* Soft timeout: Commands have a soft timeout of 10 seconds, once that's reached, you have the option to continue or interrupt the command (see section below for details)\n\n### Long-running Commands\n* For commands that may run indefinitely, run them in the background and redirect output to a file, e.g. `python3 app.py > server.log 2>&1 &`.\n* For commands that may run for a long time (e.g. installation or testing commands), or commands that run for a fixed amount of time (e.g. sleep), you should set the \"timeout\" parameter of your function call to an appropriate value.\n* If a bash command returns exit code `-1`, this means the process hit the soft timeout and is not yet finished. By setting `is_input` to `true`, you can:\n - Send empty `command` to retrieve additional logs\n - Send text (set `command` to the text) to STDIN of the running process\n - Send control commands like `C-c` (Ctrl+C), `C-d` (Ctrl+D), or `C-z` (Ctrl+Z) to interrupt the process\n - If you do C-c, you can re-start the process with a longer \"timeout\" parameter to let it run to completion\n\n### Best Practices\n* Directory verification: Before creating new directories or files, first verify the parent directory exists and is the correct location.\n* Directory management: Try to maintain working directory by using absolute paths and avoiding excessive use of `cd`.\n\n### Output Handling\n* Output truncation: If the output exceeds a maximum length, it will be truncated before being returned.\n",
5
+ "name": "execute_bash",
6
+ "parameters": {
7
+ "properties": {
8
+ "command": {
9
+ "description": "The bash command to execute. Can be empty string to view additional logs when previous exit code is `-1`. Can be `C-c` (Ctrl+C) to interrupt the currently running process. Note: You can only execute one bash command at a time. If you need to run multiple commands sequentially, you can use `&&` or `;` to chain them together.",
10
+ "type": "string"
11
+ },
12
+ "is_input": {
13
+ "description": "If True, the command is an input to the running process. If False, the command is a bash command to be executed in the terminal. Default is False.",
14
+ "enum": [
15
+ "true",
16
+ "false"
17
+ ],
18
+ "type": "string"
19
+ },
20
+ "timeout": {
21
+ "description": "Optional. Sets a hard timeout in seconds for the command execution. If not provided, the command will use the default soft timeout behavior.",
22
+ "type": "number"
23
+ }
24
+ },
25
+ "required": [
26
+ "command"
27
+ ],
28
+ "type": "object"
29
+ }
30
+ },
31
+ "type": "function"
32
+ },
33
+ {
34
+ "function": {
35
+ "description": "Use the tool to think about something. It will not obtain new information or make any changes to the repository, but just log the thought. Use it when complex reasoning or brainstorming is needed.\n\nCommon use cases:\n1. When exploring a repository and discovering the source of a bug, call this tool to brainstorm several unique ways of fixing the bug, and assess which change(s) are likely to be simplest and most effective.\n2. After receiving test results, use this tool to brainstorm ways to fix failing tests.\n3. When planning a complex refactoring, use this tool to outline different approaches and their tradeoffs.\n4. When designing a new feature, use this tool to think through architecture decisions and implementation details.\n5. When debugging a complex issue, use this tool to organize your thoughts and hypotheses.\n\nThe tool simply logs your thought process for better transparency and does not execute any code or make changes.",
36
+ "name": "think",
37
+ "parameters": {
38
+ "properties": {
39
+ "thought": {
40
+ "description": "The thought to log.",
41
+ "type": "string"
42
+ }
43
+ },
44
+ "required": [
45
+ "thought"
46
+ ],
47
+ "type": "object"
48
+ }
49
+ },
50
+ "type": "function"
51
+ },
52
+ {
53
+ "function": {
54
+ "description": "Signals the completion of the current task or conversation.\n\nUse this tool when:\n- You have successfully completed the user's requested task\n- You cannot proceed further due to technical limitations or missing information\n\nThe message should include:\n- A clear summary of actions taken and their results\n- Any next steps for the user\n- Explanation if you're unable to complete the task\n- Any follow-up questions if more information is needed\n",
55
+ "name": "finish",
56
+ "parameters": {
57
+ "properties": {
58
+ "message": {
59
+ "description": "Final message to send to the user",
60
+ "type": "string"
61
+ }
62
+ },
63
+ "required": [
64
+ "message"
65
+ ],
66
+ "type": "object"
67
+ }
68
+ },
69
+ "type": "function"
70
+ },
71
+ {
72
+ "function": {
73
+ "description": "This tool provides structured task management capabilities for development workflows.\nIt enables systematic tracking of work items, progress monitoring, and efficient\norganization of complex development activities.\n\nThe tool maintains visibility into project status and helps communicate\nprogress effectively to users.\n\n## Application Guidelines\n\nUtilize this tool in the following situations:\n\n1. Multi-phase development work - When projects involve multiple sequential or\n parallel activities\n2. Complex implementation tasks - Work requiring systematic planning and\n coordination across multiple components\n3. Explicit user request for task organization - When users specifically ask\n for structured task management\n4. Multiple concurrent requirements - When users present several work items\n that need coordination\n5. Project initiation - Capture and organize user requirements at project start\n6. Work commencement - Update task status to in_progress before beginning\n implementation. Maintain focus by limiting active work to one task\n7. Task completion - Update status to done and identify any additional work\n that emerged during implementation\n\n## Situations Where Tool Usage Is Unnecessary\n\nAvoid using this tool when:\n\n1. Single atomic tasks that require no decomposition\n2. Trivial operations where tracking adds no organizational value\n3. Simple activities completable in minimal steps\n4. Pure information exchange or discussion\n\nNote: For single straightforward tasks, proceed with direct implementation\nrather than creating tracking overhead.\n\n## Usage Scenarios\n\n**Scenario A: Feature Development with Validation**\nUser request: \"Build a user authentication system with login/logout functionality.\nDon't forget to include input validation and error handling!\"\n\nResponse approach: I'll implement a user authentication system with comprehensive\nvalidation. Let me organize this work systematically.\n\n*Task breakdown includes:*\n1. Design authentication API endpoints and data models\n2. Implement user login/logout controllers with session management\n3. Add client-side form validation and error display\n4. Create backend input sanitization and security checks\n5. Implement comprehensive error handling for edge cases\n6. Perform integration testing and fix any issues\n\n**Scenario B: Codebase Refactoring**\nUser request: \"I need to update all instances of the method 'fetchData' to\n'retrieveInformation' throughout the entire project\"\n\nResponse approach: Let me first analyze your codebase to identify all locations\nwhere 'fetchData' appears.\n\n*After code analysis*\n\nI've located 12 occurrences of 'fetchData' across 6 files in your project.\nI'll create a systematic plan to update these references.\n\n*Organized task list includes specific file-by-file updates*\n\n**Scenario C: Multi-feature Development**\nUser request: \"Set up a blog platform with these components: admin dashboard,\narticle management, comment system, and user profiles.\"\n\nResponse approach: I'll help build your blog platform. Let me break down these\ncomponents into manageable implementation phases.\n\n*Creates structured plan with each feature decomposed into specific development tasks*\n\n## Counter-examples - Direct Implementation Preferred\n\n**Counter-example A: Simple inquiry**\nUser request: \"What's the syntax for a for loop in JavaScript?\"\n\nResponse approach: Here's how to write a for loop in JavaScript:\n\n```javascript\nfor (let i = 0; i < array.length; i++) {\n console.log(array[i]);\n}\n```\n\n*No task tracking needed - single informational response*\n\n**Counter-example B: Minor modification**\nUser request: \"Please add a docstring to the processPayment function explaining\nits parameters.\"\n\nResponse approach: I'll add a docstring to explain the processPayment function.\n\n*Direct edit without task tracking for simple modification*\n\n## Status Management and Workflow\n\n1. **Status Values**: Track work using these states:\n - todo: Not yet initiated\n - in_progress: Currently active (maintain single focus)\n - done: Successfully completed\n\n2. **Workflow Practices**:\n - Update status dynamically as work progresses\n - Mark completion immediately upon task finish\n - Limit active work to ONE task at any given time\n - Complete current activities before initiating new ones\n - Remove obsolete tasks from tracking entirely\n\n3. **Completion Criteria**:\n - Mark tasks as done only when fully achieved\n - Keep status as in_progress if errors, blocks, or partial completion exist\n - Create new tasks for discovered issues or dependencies\n - Never mark done when:\n - Test suites are failing\n - Implementation remains incomplete\n - Unresolved errors persist\n - Required resources are unavailable\n\n4. **Task Organization**:\n - Write precise, actionable descriptions\n - Decompose complex work into manageable units\n - Use descriptive, clear naming conventions\n\nWhen uncertain, favor using this tool. Proactive task management demonstrates\nsystematic approach and ensures comprehensive requirement fulfillment.\n",
74
+ "name": "task_tracker",
75
+ "parameters": {
76
+ "additionalProperties": false,
77
+ "properties": {
78
+ "command": {
79
+ "description": "The command to execute. `view` shows the current task list. `plan` creates or updates the task list based on provided requirements and progress. Always `view` the current list before making changes.",
80
+ "enum": [
81
+ "view",
82
+ "plan"
83
+ ],
84
+ "type": "string"
85
+ },
86
+ "task_list": {
87
+ "description": "The full task list. Required parameter of `plan` command.",
88
+ "items": {
89
+ "additionalProperties": false,
90
+ "properties": {
91
+ "id": {
92
+ "description": "Unique task identifier",
93
+ "type": "string"
94
+ },
95
+ "notes": {
96
+ "description": "Optional additional context or details",
97
+ "type": "string"
98
+ },
99
+ "status": {
100
+ "description": "Current task status",
101
+ "enum": [
102
+ "todo",
103
+ "in_progress",
104
+ "done"
105
+ ],
106
+ "type": "string"
107
+ },
108
+ "title": {
109
+ "description": "Brief task description",
110
+ "type": "string"
111
+ }
112
+ },
113
+ "required": [
114
+ "title",
115
+ "status",
116
+ "id"
117
+ ],
118
+ "type": "object"
119
+ },
120
+ "type": "array"
121
+ }
122
+ },
123
+ "required": [
124
+ "command"
125
+ ],
126
+ "type": "object"
127
+ }
128
+ },
129
+ "type": "function"
130
+ },
131
+ {
132
+ "function": {
133
+ "description": "Custom editing tool for viewing, creating and editing files in plain-text format\n* State is persistent across command calls and discussions with the user\n* If `path` is a text file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep\n* The following binary file extensions can be viewed in Markdown format: [\".xlsx\", \".pptx\", \".wav\", \".mp3\", \".m4a\", \".flac\", \".pdf\", \".docx\"]. IT DOES NOT HANDLE IMAGES.\n* The `create` command cannot be used if the specified `path` already exists as a file\n* If a `command` generates a long output, it will be truncated and marked with `<response clipped>`\n* The `undo_edit` command will revert the last edit made to the file at `path`\n* This tool can be used for creating and editing files in plain-text format.\n\n\nBefore using this tool:\n1. Use the view tool to understand the file's contents and context\n2. Verify the directory path is correct (only applicable when creating new files):\n - Use the view tool to verify the parent directory exists and is the correct location\n\nWhen making edits:\n - Ensure the edit results in idiomatic, correct code\n - Do not leave the code in a broken state\n - Always use absolute file paths (starting with /)\n\nCRITICAL REQUIREMENTS FOR USING THIS TOOL:\n\n1. EXACT MATCHING: The `old_str` parameter must match EXACTLY one or more consecutive lines from the file, including all whitespace and indentation. The tool will fail if `old_str` matches multiple locations or doesn't match exactly with the file content.\n\n2. UNIQUENESS: The `old_str` must uniquely identify a single instance in the file:\n - Include sufficient context before and after the change point (3-5 lines recommended)\n - If not unique, the replacement will not be performed\n\n3. REPLACEMENT: The `new_str` parameter should contain the edited lines that replace the `old_str`. Both strings must be different.\n\nRemember: when making multiple file edits in a row to the same file, you should prefer to send all edits in a single message with multiple calls to this tool, rather than multiple messages with a single call each.\n",
134
+ "name": "str_replace_editor",
135
+ "parameters": {
136
+ "properties": {
137
+ "command": {
138
+ "description": "The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`, `undo_edit`.",
139
+ "enum": [
140
+ "view",
141
+ "create",
142
+ "str_replace",
143
+ "insert",
144
+ "undo_edit"
145
+ ],
146
+ "type": "string"
147
+ },
148
+ "file_text": {
149
+ "description": "Required parameter of `create` command, with the content of the file to be created.",
150
+ "type": "string"
151
+ },
152
+ "insert_line": {
153
+ "description": "Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`.",
154
+ "type": "integer"
155
+ },
156
+ "new_str": {
157
+ "description": "Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert.",
158
+ "type": "string"
159
+ },
160
+ "old_str": {
161
+ "description": "Required parameter of `str_replace` command containing the string in `path` to replace.",
162
+ "type": "string"
163
+ },
164
+ "path": {
165
+ "description": "Absolute path to file or directory, e.g. `/workspace/file.py` or `/workspace`.",
166
+ "type": "string"
167
+ },
168
+ "view_range": {
169
+ "description": "Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.",
170
+ "items": {
171
+ "type": "integer"
172
+ },
173
+ "type": "array"
174
+ }
175
+ },
176
+ "required": [
177
+ "command",
178
+ "path"
179
+ ],
180
+ "type": "object"
181
+ }
182
+ },
183
+ "type": "function"
184
+ }
185
+ ]
traj_normalize/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ """traj-normalize: Nebius OpenHands trajectories -> SFT-ready messages."""
2
+
3
+ from .core import Stats, load_tools_schema, normalize_row, row_to_record
4
+ from .cli import main
5
+
6
+ __all__ = ["Stats", "load_tools_schema", "normalize_row", "row_to_record", "main"]
7
+ __version__ = "0.1.0"
traj_normalize/__main__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
traj_normalize/cli.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """traj-normalize CLI: Nebius OpenHands parquet -> SFT-ready jsonl.
2
+
3
+ Usage:
4
+ traj-normalize --input nebius/SWE-rebench-openhands-trajectories \
5
+ --out-dir out --max-success 5000 --seed 0
6
+ traj-normalize --input /path/to/trajectories.parquet --out-dir out
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import random
14
+ import sys
15
+ import time
16
+ from pathlib import Path
17
+
18
+ import pyarrow.parquet as pq
19
+
20
+ from .core import Stats, load_tools_schema, normalize_row, row_to_record
21
+
22
+ META_COLS = ["trajectory_id", "instance_id", "repo", "resolved"]
23
+ DEFAULT_REPO = "nebius/SWE-rebench-openhands-trajectories"
24
+ DEFAULT_DATA_FILE = "trajectories.parquet"
25
+
26
+
27
+ def resolve_input(inp: str) -> tuple[Path, str]:
28
+ """Return (parquet_path, source_desc). Downloads from the Hub if needed."""
29
+ p = Path(inp)
30
+ if p.is_file():
31
+ return p, str(p.resolve())
32
+ from huggingface_hub import hf_hub_download
33
+
34
+ path = hf_hub_download(repo_id=inp, repo_type="dataset", filename=DEFAULT_DATA_FILE)
35
+ return Path(path), inp
36
+
37
+
38
+ def resolve_tools_json(tools_arg: str | None, source: str) -> str | None:
39
+ if tools_arg:
40
+ return tools_arg
41
+ # If input came from the Hub, try to fetch tools.json from the same repo.
42
+ if not Path(source).is_file():
43
+ try:
44
+ from huggingface_hub import hf_hub_download
45
+
46
+ return hf_hub_download(repo_id=source, repo_type="dataset", filename="tools.json")
47
+ except Exception:
48
+ return None
49
+ # Local file: look for tools.json next to the parquet.
50
+ cand = Path(source).parent / "tools.json"
51
+ return str(cand) if cand.exists() else None
52
+
53
+
54
+ def pass1_select_indices(pf: pq.ParquetFile, args) -> tuple[set[int], Stats]:
55
+ """Scan light columns; return selected row indices + populated counters."""
56
+ stats = Stats()
57
+ resolved_idx, fail_idx = [], []
58
+ offset = 0
59
+ for batch in pf.iter_batches(batch_size=args.batch_size, columns=META_COLS):
60
+ for row in batch.to_pylist():
61
+ stats.input_rows += 1
62
+ if row.get("resolved") == 1:
63
+ stats.resolved_rows += 1
64
+ resolved_idx.append(offset)
65
+ else:
66
+ fail_idx.append(offset)
67
+ offset += 1
68
+ if args.limit and stats.input_rows >= args.limit:
69
+ break
70
+ if args.limit and stats.input_rows >= args.limit:
71
+ break
72
+
73
+ rng = random.Random(args.seed)
74
+ if args.max_success and len(resolved_idx) > args.max_success:
75
+ resolved_idx = sorted(rng.sample(resolved_idx, args.max_success))
76
+ if args.include_failures:
77
+ if args.max_fail and len(fail_idx) > args.max_fail:
78
+ fail_idx = sorted(rng.sample(fail_idx, args.max_fail))
79
+ else:
80
+ fail_idx = []
81
+
82
+ selected = set(resolved_idx) | set(fail_idx)
83
+ return selected, stats
84
+
85
+
86
+ def run(args) -> int:
87
+ parquet_path, source = resolve_input(args.input)
88
+ tools_path = resolve_tools_json(args.tools_json, source)
89
+ tools_schema = load_tools_schema(tools_path)
90
+ if args.tools_json and tools_schema is None:
91
+ print(f"warning: could not load tools schema from {args.tools_json}", file=sys.stderr)
92
+
93
+ out_dir = Path(args.out_dir)
94
+ out_dir.mkdir(parents=True, exist_ok=True)
95
+ success_path = out_dir / "sft_success.jsonl"
96
+ fail_path = out_dir / "sft_fail.jsonl"
97
+ meta_path = out_dir / "meta.json"
98
+
99
+ pf = pq.ParquetFile(parquet_path)
100
+ t0 = time.time()
101
+
102
+ selected, stats = pass1_select_indices(pf, args)
103
+ print(f"scanned {stats.input_rows} rows ({stats.resolved_rows} resolved); "
104
+ f"selected {len(selected)} for extraction", file=sys.stderr)
105
+
106
+ # Pass 2: full rows for selected indices.
107
+ records = [] if args.shuffle else None
108
+ f_succ = open(success_path, "w")
109
+ f_fail = open(fail_path, "w") if args.include_failures else None
110
+ offset = 0
111
+ try:
112
+ for batch in pf.iter_batches(batch_size=args.batch_size):
113
+ for row in batch.to_pylist():
114
+ idx = offset
115
+ offset += 1
116
+ if args.limit and idx >= args.limit:
117
+ break
118
+ if idx not in selected:
119
+ continue
120
+ messages, err = normalize_row(row, stats, tools_schema, args.strict_tools)
121
+ if err:
122
+ stats.drop(err)
123
+ continue
124
+ rec = row_to_record(row, messages, emit_tools=not args.no_tools)
125
+ if records is not None:
126
+ records.append(rec)
127
+ else:
128
+ (f_succ if rec["resolved"] == 1 else f_fail).write(
129
+ json.dumps(rec, ensure_ascii=False) + "\n")
130
+ if rec["resolved"] == 1:
131
+ stats.written_success += 1
132
+ else:
133
+ stats.written_fail += 1
134
+ if args.limit and offset >= args.limit:
135
+ break
136
+
137
+ if records is not None:
138
+ rng = random.Random(args.seed)
139
+ rng.shuffle(records)
140
+ stats.written_success = stats.written_fail = 0
141
+ for rec in records:
142
+ (f_succ if rec["resolved"] == 1 else f_fail).write(
143
+ json.dumps(rec, ensure_ascii=False) + "\n")
144
+ if rec["resolved"] == 1:
145
+ stats.written_success += 1
146
+ else:
147
+ stats.written_fail += 1
148
+ finally:
149
+ f_succ.close()
150
+ if f_fail:
151
+ f_fail.close()
152
+
153
+ if not args.include_failures and fail_path.exists():
154
+ fail_path.unlink()
155
+
156
+ stats.skipped_unresolved = stats.input_rows - stats.resolved_rows
157
+
158
+ meta = {
159
+ "tool": "traj-normalize",
160
+ "source": source,
161
+ "tools_schema": tools_path if tools_schema else None,
162
+ "params": {
163
+ "limit": args.limit,
164
+ "max_success": args.max_success,
165
+ "max_fail": args.max_fail if args.include_failures else None,
166
+ "include_failures": args.include_failures,
167
+ "seed": args.seed,
168
+ "shuffle": args.shuffle,
169
+ "strict_tools": args.strict_tools,
170
+ },
171
+ "counts": {
172
+ "input_rows": stats.input_rows,
173
+ "resolved_rows": stats.resolved_rows,
174
+ "written_success": stats.written_success,
175
+ "written_fail": stats.written_fail,
176
+ "skipped_unresolved": stats.skipped_unresolved,
177
+ "dropped": sum(stats.drop_reasons.values()),
178
+ },
179
+ "drop_reasons": stats.drop_reasons,
180
+ "fixes": stats.fixes,
181
+ "unknown_tools": stats.unknown_tools,
182
+ "missing_required_params": stats.missing_required_params,
183
+ "unparseable_examples": stats.unparseable_examples,
184
+ "outputs": {
185
+ p.name: p.stat().st_size for p in (success_path, fail_path) if p.exists()
186
+ },
187
+ "elapsed_sec": round(time.time() - t0, 1),
188
+ }
189
+ meta_path.write_text(json.dumps(meta, indent=2, ensure_ascii=False))
190
+ print(json.dumps(meta["counts"], indent=2), file=sys.stderr)
191
+ print(f"wrote {success_path} (+meta {meta_path})", file=sys.stderr)
192
+ return 0
193
+
194
+
195
+ def build_parser() -> argparse.ArgumentParser:
196
+ ap = argparse.ArgumentParser(
197
+ prog="traj-normalize",
198
+ description="Deserialize Nebius OpenHands trajectories into SFT-ready message lists.",
199
+ )
200
+ ap.add_argument("--input", default=DEFAULT_REPO,
201
+ help="Local parquet path or HF dataset repo id (default: %(default)s)")
202
+ ap.add_argument("--out-dir", default="out")
203
+ ap.add_argument("--tools-json", default=None,
204
+ help="Path to upstream tools.json for soft validation (auto-fetched for Hub input)")
205
+ ap.add_argument("--limit", type=int, default=0, help="Max input rows to scan (0 = all)")
206
+ ap.add_argument("--max-success", type=int, default=0,
207
+ help="Cap on resolved trajectories written (0 = all). Random sample with --seed.")
208
+ ap.add_argument("--include-failures", action="store_true",
209
+ help="Also write unresolved trajectories to sft_fail.jsonl")
210
+ ap.add_argument("--max-fail", type=int, default=0, help="Cap on failure trajectories (0 = all)")
211
+ ap.add_argument("--seed", type=int, default=0)
212
+ ap.add_argument("--shuffle", action="store_true",
213
+ help="Shuffle output records (buffers selected rows in memory)")
214
+ ap.add_argument("--strict-tools", action="store_true",
215
+ help="Drop trajectories calling tools absent from tools.json")
216
+ ap.add_argument("--no-tools", action="store_true",
217
+ help="Do not embed the per-row tool list in each record")
218
+ ap.add_argument("--batch-size", type=int, default=32)
219
+ return ap
220
+
221
+
222
+ def main(argv=None) -> int:
223
+ args = build_parser().parse_args(argv)
224
+ return run(args)
225
+
226
+
227
+ if __name__ == "__main__":
228
+ sys.exit(main())
traj_normalize/core.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Core normalization logic for Nebius SWE-rebench OpenHands trajectories.
2
+
3
+ The upstream parquet stores ``tool_call.function.arguments`` as a *serialized
4
+ JSON string*. Chat templates (e.g. Qwen3-Coder) iterate ``arguments|items`` and
5
+ therefore require a mapping -- feeding the raw string produces empty or broken
6
+ tool calls at train/infer time. This module deserializes arguments, canonicalizes
7
+ message fields per role, and optionally validates tool calls against the
8
+ upstream ``tools.json``.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import ast
14
+ import json
15
+ from dataclasses import dataclass, field
16
+ from typing import Any, Iterable, Optional
17
+
18
+ # Canonical per-role fields, mirroring the upstream README's role2field_names.
19
+ ROLE_FIELDS = {
20
+ "system": ("role", "content"),
21
+ "user": ("role", "content"),
22
+ "assistant": ("role", "content", "tool_calls"),
23
+ "tool": ("role", "content", "name", "tool_call_id"),
24
+ }
25
+ KNOWN_ROLES = frozenset(ROLE_FIELDS)
26
+
27
+
28
+ @dataclass
29
+ class Stats:
30
+ """Accumulates fix/drop counters; serialized into meta.json."""
31
+
32
+ input_rows: int = 0
33
+ resolved_rows: int = 0
34
+ written_success: int = 0
35
+ written_fail: int = 0
36
+ skipped_unresolved: int = 0
37
+ drop_reasons: dict = field(default_factory=dict)
38
+ fixes: dict = field(default_factory=dict)
39
+ unknown_tools: dict = field(default_factory=dict)
40
+ missing_required_params: dict = field(default_factory=dict)
41
+ unparseable_examples: list = field(default_factory=list)
42
+
43
+ def bump(self, bucket: dict, key: str, n: int = 1) -> None:
44
+ bucket[key] = bucket.get(key, 0) + n
45
+
46
+ def drop(self, reason: str) -> None:
47
+ self.bump(self.drop_reasons, reason)
48
+
49
+ def fix(self, kind: str, n: int = 1) -> None:
50
+ self.bump(self.fixes, kind, n)
51
+
52
+
53
+ def load_tools_schema(path: Optional[str]) -> Optional[dict]:
54
+ """Load an OpenAI-style tools.json -> {name: {required: set, properties: set}}."""
55
+ if not path:
56
+ return None
57
+ with open(path) as f:
58
+ tools = json.load(f)
59
+ schema = {}
60
+ for entry in tools:
61
+ fn = entry.get("function", entry)
62
+ name = fn.get("name")
63
+ if not name:
64
+ continue
65
+ params = fn.get("parameters") or {}
66
+ schema[name] = {
67
+ "required": set(params.get("required") or []),
68
+ "properties": set((params.get("properties") or {}).keys()),
69
+ }
70
+ return schema
71
+
72
+
73
+ def deserialize_arguments(raw: Any, stats: Stats) -> tuple[Optional[dict], Optional[str]]:
74
+ """Return (arguments_dict, drop_reason). arguments_dict is None on failure."""
75
+ if raw is None:
76
+ stats.fix("missing_arguments")
77
+ return {}, None
78
+ if isinstance(raw, dict):
79
+ return raw, None
80
+ if not isinstance(raw, str):
81
+ return None, "arguments_not_object"
82
+
83
+ value: Any = raw
84
+ rounds = 0
85
+ while isinstance(value, str):
86
+ rounds += 1
87
+ if rounds > 3:
88
+ return None, "arguments_unparseable"
89
+ try:
90
+ value = json.loads(value)
91
+ except (json.JSONDecodeError, ValueError):
92
+ try:
93
+ value = ast.literal_eval(value)
94
+ stats.fix("literal_eval_fallback")
95
+ except (ValueError, SyntaxError, MemoryError):
96
+ snippet = value[:200] if isinstance(value, str) else repr(value)[:200]
97
+ if len(stats.unparseable_examples) < 5:
98
+ stats.unparseable_examples.append(snippet)
99
+ return None, "arguments_unparseable"
100
+ if rounds > 1:
101
+ stats.fix("double_encoded_arguments")
102
+ stats.fix("arguments_deserialized")
103
+ if not isinstance(value, dict):
104
+ return None, "arguments_not_object"
105
+ return value, None
106
+
107
+
108
+ def normalize_tool_call(tc: Any, stats: Stats) -> tuple[Optional[dict], Optional[str]]:
109
+ """Normalize one tool call to {"id"?, "type"?, "function": {"name", "arguments": dict}}."""
110
+ if not isinstance(tc, dict):
111
+ return None, "tool_call_not_object"
112
+
113
+ # Some producers put name/arguments at the top level instead of under "function".
114
+ fn = tc.get("function") if isinstance(tc.get("function"), dict) else None
115
+ if fn is None:
116
+ if "name" in tc or "arguments" in tc:
117
+ fn = {"name": tc.get("name"), "arguments": tc.get("arguments")}
118
+ stats.fix("flattened_tool_call")
119
+ else:
120
+ return None, "tool_call_missing_function"
121
+
122
+ args, err = deserialize_arguments(fn.get("arguments"), stats)
123
+ if err:
124
+ return None, err
125
+
126
+ out = {"type": tc.get("type", "function"),
127
+ "function": {"name": fn.get("name"), "arguments": args}}
128
+ if tc.get("id") is not None:
129
+ out["id"] = tc["id"]
130
+ return out, None
131
+
132
+
133
+ def normalize_message(msg: Any, stats: Stats) -> tuple[Optional[dict], Optional[str]]:
134
+ if not isinstance(msg, dict):
135
+ return None, "message_not_object"
136
+ role = msg.get("role")
137
+ if role not in KNOWN_ROLES:
138
+ return None, f"unknown_role:{role}"
139
+
140
+ out = {k: msg.get(k) for k in ROLE_FIELDS[role] if msg.get(k) is not None or k in ("role", "content")}
141
+
142
+ if role == "assistant":
143
+ tcs = msg.get("tool_calls")
144
+ if tcs:
145
+ norm = []
146
+ for tc in tcs:
147
+ ntc, err = normalize_tool_call(tc, stats)
148
+ if err:
149
+ return None, err
150
+ norm.append(ntc)
151
+ out["tool_calls"] = norm
152
+ else:
153
+ out.pop("tool_calls", None)
154
+ return out, None
155
+
156
+
157
+ def validate_against_tools(messages: Iterable[dict], schema: dict, stats: Stats) -> int:
158
+ """Soft validation: count tool calls whose name or required params are off.
159
+
160
+ Returns the number of calls in *these* messages using an unknown tool name.
161
+ """
162
+ unknown = 0
163
+ for msg in messages:
164
+ if msg.get("role") != "assistant":
165
+ continue
166
+ for tc in msg.get("tool_calls") or []:
167
+ fn = tc.get("function", {})
168
+ name = fn.get("name")
169
+ spec = schema.get(name)
170
+ if spec is None:
171
+ stats.bump(stats.unknown_tools, str(name))
172
+ unknown += 1
173
+ continue
174
+ missing = spec["required"] - set((fn.get("arguments") or {}).keys())
175
+ for p in missing:
176
+ stats.bump(stats.missing_required_params, f"{name}:{p}")
177
+ return unknown
178
+
179
+
180
+ def normalize_row(row: dict, stats: Stats, tools_schema: Optional[dict] = None,
181
+ strict_tools: bool = False) -> tuple[Optional[list], Optional[str]]:
182
+ """Normalize one parquet row -> messages list, or (None, drop_reason)."""
183
+ traj = row.get("trajectory")
184
+ if not traj:
185
+ return None, "empty_trajectory"
186
+
187
+ messages = []
188
+ for msg in traj:
189
+ nm, err = normalize_message(msg, stats)
190
+ if err:
191
+ return None, err
192
+ messages.append(nm)
193
+
194
+ if not any(m["role"] == "assistant" for m in messages):
195
+ return None, "no_assistant_messages"
196
+
197
+ if tools_schema:
198
+ n_unknown = validate_against_tools(messages, tools_schema, stats)
199
+ if strict_tools and n_unknown:
200
+ return None, "unknown_tool"
201
+
202
+ return messages, None
203
+
204
+
205
+ def row_to_record(row: dict, messages: list, emit_tools: bool = True) -> dict:
206
+ rec = {
207
+ "messages": messages,
208
+ "trajectory_id": row.get("trajectory_id"),
209
+ "instance_id": row.get("instance_id"),
210
+ "repo": row.get("repo"),
211
+ "resolved": int(row.get("resolved") or 0),
212
+ "exit_status": row.get("exit_status"),
213
+ "model_patch": row.get("model_patch"),
214
+ "gen_tests_correct": row.get("gen_tests_correct"),
215
+ "pred_passes_gen_tests": row.get("pred_passes_gen_tests"),
216
+ }
217
+ if emit_tools and row.get("tools"):
218
+ rec["tools"] = row["tools"]
219
+ return rec