ZHZisZZ commited on
Commit
c32c04e
·
1 Parent(s): 9c2c8f3

temp save

Browse files
src/cua_data/messages_map/convert_to_uitars15_v1.py DELETED
File without changes
src/cua_data/messages_map/convert_to_uitars15_v2.py DELETED
File without changes
src/cua_lite/data/interfaces/base.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+ import copy
3
+ from typing import Callable, Any
4
+
5
+ @dataclasses.dataclass
6
+ class BaseDataInterface:
7
+
8
+ @staticmethod
9
+ def _process_batch_generic(
10
+ func: Callable[[dict[str, Any]], dict[str, Any]],
11
+ batch: dict[str, list[Any]],
12
+ output_col: str = "messages"
13
+ ) -> dict[str, list[Any]]:
14
+ """
15
+ Core reusable logic:
16
+ Process 'list of dicts' (Batch) -> Reconstruct 'Row' -> func -> Aggregate Results.
17
+
18
+ Suitable for all 1-to-1 mapping operations.
19
+ """
20
+ # Determine batch size (by checking the length of an arbitrary column)
21
+ # Assumes batch is not empty and columns are aligned.
22
+ first_key = next(iter(batch))
23
+ batch_size = len(batch[first_key])
24
+
25
+ results = []
26
+
27
+ for i in range(batch_size):
28
+ # 1. Dynamically reconstruct a Single Row: {'images': img, 'messages': msg ...}
29
+ # This replaces manually constructing `single_row` in every function.
30
+ row = {key: batch[key][i] for key in batch}
31
+
32
+ # 2. Call the processing function.
33
+ # The function receives a single row and MUST return a dict (e.g., {'messages': ...})
34
+ processed_output = func(row)
35
+
36
+ # 3. Extract result.
37
+ if output_col in processed_output:
38
+ results.append(processed_output[output_col])
39
+ else:
40
+ # Fallback or error handling if key is missing
41
+ raise KeyError(f"Function output missing expected key: {output_col}")
42
+
43
+ return {output_col: results}
44
+
45
+ @staticmethod
46
+ def fill_images(row: dict[str, Any]) -> dict[str, Any]:
47
+ """
48
+ Processes a single row to inject images into messages.
49
+ """
50
+ # CRITICAL FIX: Use deepcopy.
51
+ # Modifying 'row' in-place can corrupt the dataset cache or cause issues if data is reused.
52
+ messages = copy.deepcopy(row.get("messages", []))
53
+ images = row.get("images", [])
54
+
55
+ for msg in messages:
56
+ content = msg.get("content", [])
57
+ for item in content:
58
+ if item.get("type") == "image":
59
+ idx = item.get("index", None)
60
+
61
+ # Safety check: Ensure index is valid integer and within bounds
62
+ if idx is None or not isinstance(idx, int):
63
+ continue
64
+
65
+ if 0 <= idx < len(images):
66
+ # Replace in-place (on the copied object)
67
+ item.pop("index", None)
68
+ item.pop("text", None)
69
+ item["image"] = images[idx]
70
+ else:
71
+ # Handle out-of-bounds error gracefully or log warning
72
+ pass
73
+
74
+ return {"messages": messages}
75
+
76
+ @staticmethod
77
+ def fill_images_batch(batch: dict[str, list[Any]]) -> dict[str, list[Any]]:
78
+ return BaseDataInterface._process_batch_generic(
79
+ BaseDataInterface.fill_images,
80
+ batch
81
+ )
82
+
83
+ def planning_action_map(self, row: dict[str, Any]) -> dict[str, Any]:
84
+ # FIX: The generic helper expects a dict return, not a list.
85
+ return {"messages": row["messages"]}
86
+
87
+ def planning_action_map_batch(self, batch: dict[str, list[Any]]) -> dict[str, list[Any]]:
88
+ return BaseDataInterface._process_batch_generic(
89
+ self.planning_action_map,
90
+ batch
91
+ )
92
+
93
+ def planning_context_map_messages(self, messages: list[dict]) -> list[dict]:
94
+ # Placeholder for actual logic
95
+ return messages
96
+
97
+ def planning_context_map_batch(self, batch: dict[str, list[Any]]) -> dict[str, list[Any]]:
98
+ """
99
+ Handles 1-to-N data expansion (Unrolling conversation history).
100
+ Note: This changes the number of rows.
101
+ """
102
+ messages_list = []
103
+
104
+ # Note: If there are other columns in 'batch' (like 'images'),
105
+ # they will be out of sync because we are expanding 'messages'.
106
+ # HF Datasets usually requires dropping other columns or expanding them manually here.
107
+
108
+ for messages in batch["messages"]:
109
+ assistant_indices = [i for i, msg in enumerate(messages) if msg.get("role") == "assistant"]
110
+ for assistant_index in assistant_indices:
111
+ # Slicing includes the assistant message
112
+ context = messages[:assistant_index+1]
113
+ processed_context = self.planning_context_map_messages(context)
114
+ messages_list.append(processed_context)
115
+
116
+ return {"messages": messages_list}
117
+
118
+
119
+ if __name__ == "__main__":
120
+ from datasets import load_from_disk
121
+ dataset = load_from_disk(".data/scalecua/ubuntu/shard-00000-of-00256")
122
+ breakpoint()
123
+ # dataset = dataset.map(
124
+ # BaseDataInterface.fill_images_batch,
125
+ # batched=True,
126
+ # )
127
+ dataset = dataset.map(
128
+ BaseDataInterface.fill_images,
129
+ )
130
+ breakpoint()
src/cua_lite/data/interfaces/qwen3_vl.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from cua_lite.data.interfaces.base import BaseDataInterface
2
+
3
+
4
+ class Qwen3VLDataInterface(BaseDataInterface):
5
+
6
+ def planning_context_map_messages(self, messages: List[Dict]) -> List[Dict]:
7
+ # Placeholder for actual logic
8
+ return messages
9
+
src/{cua_data/messages_map/convert_to_glmv.py → cua_lite/data/interfaces/uitars15_v1.py} RENAMED
File without changes
src/{cua_data/messages_map/convert_to_qwenvl.py → cua_lite/data/interfaces/uitars15_v2.py} RENAMED
File without changes
src/{cua_data/preprocessing → cua_lite/data/raw_ds_preproc}/opencua/README.md RENAMED
@@ -19,9 +19,15 @@ cd ..
19
 
20
  ```shell
21
  # process 1/256 of the dataset
22
- python src/cua_data/preprocessing/opencua/opencua.py \
23
  --jsonl_path ".data/huggingface/xlangai/AgentNet/agentnet_ubuntu_5k.jsonl" \
24
  --extracted_images_dir ".data/huggingface/xlangai/AgentNet/extracted_ubuntu_images" \
25
  --output_path ".data/scalecua/ubuntu" \
26
  --rank 0 --world_size 256 --overwrite
 
 
 
 
 
 
27
  ```
 
19
 
20
  ```shell
21
  # process 1/256 of the dataset
22
+ python src/cua_lite/data/raw_ds_preproc/opencua/opencua.py \
23
  --jsonl_path ".data/huggingface/xlangai/AgentNet/agentnet_ubuntu_5k.jsonl" \
24
  --extracted_images_dir ".data/huggingface/xlangai/AgentNet/extracted_ubuntu_images" \
25
  --output_path ".data/scalecua/ubuntu" \
26
  --rank 0 --world_size 256 --overwrite
27
+
28
+ python src/cua_lite/data/raw_ds_preproc/opencua/opencua_v2.py \
29
+ --jsonl_path ".data/huggingface/xlangai/AgentNet/agentnet_ubuntu_5k.jsonl" \
30
+ --extracted_images_dir ".data/huggingface/xlangai/AgentNet/extracted_ubuntu_images" \
31
+ --output_path ".data/scalecua/ubuntu_v2" \
32
+ --rank 0 --world_size 256 --overwrite
33
  ```
src/{cua_data/preprocessing → cua_lite/data/raw_ds_preproc}/opencua/opencua.py RENAMED
File without changes
src/cua_lite/data/raw_ds_preproc/opencua/opencua_v2.py ADDED
@@ -0,0 +1,560 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Convert AgentNet JSONL trajectories into a HuggingFace dataset.
3
+
4
+ Each JSONL line is expected to be a single task record with at least:
5
+ - instruction: str
6
+ - traj: list[step]
7
+ - step.image: str (image filename)
8
+ - step.value.thought: str
9
+ - step.value.action: str
10
+ - step.value.code: str (pyautogui/computer action code)
11
+
12
+ Output dataset:
13
+ - messages: list[dict] in a multi-turn user/assistant format with interleaved images.
14
+
15
+ Error handling (strict):
16
+ 1) Raises if final action is not terminate.
17
+ 2) Raises if any referenced image file is missing/unreadable.
18
+ 3) Raises on any JSON/parsing/unexpected code formats.
19
+
20
+ Requires:
21
+ pip install datasets pillow tyro
22
+
23
+ Sharding (contiguous):
24
+ - If rank and world_size are specified (both not None), rank=0 processes the
25
+ first 1/world_size chunk of the dataset (by JSONL order), rank=1 the next
26
+ chunk, etc.
27
+ - Shards are saved to:
28
+ {output_path}/shard_{rank}of{world_size}
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import ast
34
+ import json
35
+ import shutil
36
+ from dataclasses import dataclass
37
+ from pathlib import Path
38
+ from typing import Any, Dict, Iterable, List, Optional, Tuple
39
+
40
+ from PIL import Image as PILImage
41
+ import tqdm
42
+ import tyro
43
+
44
+
45
+ # -----------------------------
46
+ # Args
47
+ # -----------------------------
48
+
49
+ @dataclass
50
+ class ScriptArguments:
51
+ jsonl_path: str = ".data/huggingface/xlangai/AgentNet/agentnet_ubuntu_5k.jsonl"
52
+ extracted_images_dir: str = ".data/huggingface/xlangai/AgentNet/extracted_ubuntu_images"
53
+ output_path: str = ".data/scalecua/ubuntu"
54
+ rank: Optional[int] = None
55
+ world_size: Optional[int] = None
56
+ overwrite: bool = False
57
+
58
+
59
+ # -----------------------------
60
+ # Qwen3-VL tool call formatting
61
+ # -----------------------------
62
+
63
+ def _make_computer_use_tool_call(arguments: Dict[str, Any]) -> Dict[str, Any]:
64
+ """Wrap a computer_use tool call in Qwen3-VL tool_call structure."""
65
+ if "action" not in arguments:
66
+ raise ValueError(f"computer_use arguments must include 'action'. Got: {arguments}")
67
+ return {
68
+ "type": "function",
69
+ "function": {
70
+ "name": "computer_use",
71
+ "arguments": arguments,
72
+ },
73
+ }
74
+
75
+
76
+ # -----------------------------
77
+ # AgentNet code parsing
78
+ # -----------------------------
79
+
80
+ class AgentNetCodeParseError(RuntimeError):
81
+ pass
82
+
83
+
84
+ def _dotted_name(expr: ast.AST) -> str:
85
+ """Return dotted name for ast.Name / ast.Attribute chains, else empty string."""
86
+ if isinstance(expr, ast.Name):
87
+ return expr.id
88
+ if isinstance(expr, ast.Attribute):
89
+ base = _dotted_name(expr.value)
90
+ return f"{base}.{expr.attr}" if base else expr.attr
91
+ return ""
92
+
93
+
94
+ def _literal_eval(node: ast.AST) -> Any:
95
+ try:
96
+ return ast.literal_eval(node)
97
+ except Exception as e:
98
+ raise AgentNetCodeParseError(f"Failed literal_eval on node={ast.dump(node)}") from e
99
+
100
+
101
+ def _get_kw(call: ast.Call, name: str) -> Optional[ast.AST]:
102
+ for kw in call.keywords:
103
+ if kw.arg == name:
104
+ return kw.value
105
+ return None
106
+
107
+
108
+ def _extract_xy(call: ast.Call) -> Tuple[float, float]:
109
+ """Extract x,y from a pyautogui-like call.
110
+
111
+ Supports keyword x=, y= (preferred), or positional (x, y).
112
+ """
113
+ x_node = _get_kw(call, "x")
114
+ y_node = _get_kw(call, "y")
115
+
116
+ if x_node is None and len(call.args) >= 1:
117
+ x_node = call.args[0]
118
+ if y_node is None and len(call.args) >= 2:
119
+ y_node = call.args[1]
120
+
121
+ if x_node is None or y_node is None:
122
+ raise AgentNetCodeParseError(
123
+ f"Expected x and y arguments, got args={len(call.args)} keywords={[kw.arg for kw in call.keywords]}"
124
+ )
125
+
126
+ x = float(_literal_eval(x_node))
127
+ y = float(_literal_eval(y_node))
128
+ return x, y
129
+
130
+
131
+ def _norm01_to_0_1000(x: float, y: float) -> List[int]:
132
+ """Convert normalized [0,1] floats -> int [0,1000] with rounding."""
133
+ eps = 1e-6
134
+ if x < -eps or x > 1 + eps or y < -eps or y > 1 + eps:
135
+ raise AgentNetCodeParseError(f"Coordinates out of normalized range [0,1]: x={x}, y={y}")
136
+ xi = int(round(x * 1000))
137
+ yi = int(round(y * 1000))
138
+ xi = max(0, min(1000, xi))
139
+ yi = max(0, min(1000, yi))
140
+ return [xi, yi]
141
+
142
+
143
+ def agentnet_code_to_qwen_tool_calls(code: str) -> List[Dict[str, Any]]:
144
+ """Convert AgentNet pyautogui/computer code string into Qwen3-VL computer_use tool calls."""
145
+ if not isinstance(code, str) or not code.strip():
146
+ raise AgentNetCodeParseError(f"Expected non-empty code string. Got: {code!r}")
147
+
148
+ try:
149
+ module = ast.parse(code)
150
+ except Exception as e:
151
+ raise AgentNetCodeParseError(f"ast.parse failed for code:\n{code}") from e
152
+
153
+ tool_calls: List[Dict[str, Any]] = []
154
+
155
+ for stmt in module.body:
156
+ if not isinstance(stmt, ast.Expr) or not isinstance(stmt.value, ast.Call):
157
+ raise AgentNetCodeParseError(
158
+ f"Unsupported statement type: {type(stmt).__name__}. Only expression calls are supported.\ncode=\n{code}"
159
+ )
160
+
161
+ call: ast.Call = stmt.value
162
+ fname = _dotted_name(call.func)
163
+
164
+ # ---- Mouse clicks ----
165
+ if fname == "pyautogui.click":
166
+ x, y = _extract_xy(call)
167
+ tool_calls.append(
168
+ _make_computer_use_tool_call({"action": "left_click", "coordinate": _norm01_to_0_1000(x, y)})
169
+ )
170
+ continue
171
+
172
+ if fname == "pyautogui.rightClick":
173
+ x, y = _extract_xy(call)
174
+ tool_calls.append(
175
+ _make_computer_use_tool_call({"action": "right_click", "coordinate": _norm01_to_0_1000(x, y)})
176
+ )
177
+ continue
178
+
179
+ if fname == "pyautogui.middleClick":
180
+ x, y = _extract_xy(call)
181
+ tool_calls.append(
182
+ _make_computer_use_tool_call({"action": "middle_click", "coordinate": _norm01_to_0_1000(x, y)})
183
+ )
184
+ continue
185
+
186
+ if fname == "pyautogui.doubleClick":
187
+ x, y = _extract_xy(call)
188
+ tool_calls.append(
189
+ _make_computer_use_tool_call({"action": "double_click", "coordinate": _norm01_to_0_1000(x, y)})
190
+ )
191
+ continue
192
+
193
+ if fname in {"pyautogui.tripleClick", "computer.tripleClick"}:
194
+ x, y = _extract_xy(call)
195
+ tool_calls.append(
196
+ _make_computer_use_tool_call({"action": "double_click", "coordinate": _norm01_to_0_1000(x, y)})
197
+ )
198
+ continue
199
+
200
+ # ---- Mouse movement / drag ----
201
+ if fname == "pyautogui.moveTo":
202
+ x, y = _extract_xy(call)
203
+ tool_calls.append(
204
+ _make_computer_use_tool_call({"action": "mouse_move", "coordinate": _norm01_to_0_1000(x, y)})
205
+ )
206
+ continue
207
+
208
+ if fname == "pyautogui.dragTo":
209
+ btn_node = _get_kw(call, "button")
210
+ btn = "left" if btn_node is None else str(_literal_eval(btn_node))
211
+ if btn != "left":
212
+ raise AgentNetCodeParseError(
213
+ f"Only button='left' dragTo is supported. Got button={btn!r}.\ncode=\n{code}"
214
+ )
215
+ x, y = _extract_xy(call)
216
+ tool_calls.append(
217
+ _make_computer_use_tool_call({"action": "left_click_drag", "coordinate": _norm01_to_0_1000(x, y)})
218
+ )
219
+ continue
220
+
221
+ # ---- Scroll ----
222
+ if fname in {"pyautogui.scroll", "pyautogui.hscroll"}:
223
+ if len(call.args) < 1:
224
+ raise AgentNetCodeParseError(f"scroll/hscroll requires a pixels argument.\ncode=\n{code}")
225
+ pixels = int(_literal_eval(call.args[0]))
226
+ tool_calls.append(_make_computer_use_tool_call({"action": "scroll", "pixels": pixels}))
227
+ continue
228
+
229
+ # ---- Keyboard ----
230
+ if fname == "pyautogui.hotkey":
231
+ if len(call.args) != 1:
232
+ raise AgentNetCodeParseError(f"hotkey expected a single list argument.\ncode=\n{code}")
233
+ keys_val = _literal_eval(call.args[0])
234
+ if not isinstance(keys_val, (list, tuple)) or not keys_val:
235
+ raise AgentNetCodeParseError(f"hotkey arg must be a non-empty list/tuple. Got: {keys_val!r}")
236
+ keys = [str(k).lower() for k in keys_val]
237
+ tool_calls.append(_make_computer_use_tool_call({"action": "key", "keys": keys}))
238
+ continue
239
+
240
+ if fname == "pyautogui.press":
241
+ if len(call.args) != 1:
242
+ raise AgentNetCodeParseError(f"press expected a single key argument.\ncode=\n{code}")
243
+ key_val = _literal_eval(call.args[0])
244
+ if isinstance(key_val, (list, tuple)):
245
+ for k in key_val:
246
+ tool_calls.append(_make_computer_use_tool_call({"action": "key", "keys": [str(k).lower()]}))
247
+ else:
248
+ tool_calls.append(_make_computer_use_tool_call({"action": "key", "keys": [str(key_val).lower()]}))
249
+ continue
250
+
251
+ if fname in {"pyautogui.write", "pyautogui.typewrite"}:
252
+ msg_node = _get_kw(call, "message")
253
+ if msg_node is None and len(call.args) == 1:
254
+ msg_node = call.args[0]
255
+ if msg_node is None:
256
+ raise AgentNetCodeParseError(f"write/typewrite requires message argument.\ncode=\n{code}")
257
+ text = str(_literal_eval(msg_node))
258
+ tool_calls.append(_make_computer_use_tool_call({"action": "type", "text": text}))
259
+ continue
260
+
261
+ # ---- Wait / Terminate ----
262
+ if fname == "computer.wait":
263
+ if len(call.args) == 0 and len(call.keywords) == 0:
264
+ t = 1.0
265
+ elif len(call.args) == 1 and len(call.keywords) == 0:
266
+ t = float(_literal_eval(call.args[0]))
267
+ else:
268
+ raise AgentNetCodeParseError(f"Unsupported wait signature.\ncode=\n{code}")
269
+ tool_calls.append(_make_computer_use_tool_call({"action": "wait", "time": t}))
270
+ continue
271
+
272
+ if fname == "computer.terminate":
273
+ status_node = _get_kw(call, "status")
274
+ if status_node is None:
275
+ raise AgentNetCodeParseError(f"terminate requires status='success'|'failure'.\ncode=\n{code}")
276
+ status = str(_literal_eval(status_node))
277
+ if status not in {"success", "failure"}:
278
+ raise AgentNetCodeParseError(f"Unsupported terminate status={status!r}.\ncode=\n{code}")
279
+ tool_calls.append(_make_computer_use_tool_call({"action": "terminate", "status": status}))
280
+ continue
281
+
282
+ raise AgentNetCodeParseError(f"Unsupported function call: {fname!r}.\ncode=\n{code}")
283
+
284
+ return tool_calls
285
+
286
+
287
+ # -----------------------------
288
+ # Trajectory -> dataset example
289
+ # -----------------------------
290
+
291
+ def _load_image_or_raise(path: Path) -> PILImage.Image:
292
+ if not path.exists():
293
+ raise FileNotFoundError(f"Missing image file: {path}")
294
+ try:
295
+ with PILImage.open(path) as im:
296
+ return im.convert("RGB").copy()
297
+ except Exception as e:
298
+ raise RuntimeError(f"Failed to open image: {path}") from e
299
+
300
+
301
+ def record_to_example(record: Dict[str, Any], extracted_images_dir: Path) -> Dict[str, Any]:
302
+ """Convert one JSONL record into one dataset row with key: messages."""
303
+ instruction = record.get("instruction")
304
+ if not isinstance(instruction, str) or not instruction.strip():
305
+ raise ValueError(f"Missing/invalid 'instruction' in record. Keys={list(record.keys())}")
306
+
307
+ traj = record.get("traj")
308
+ if not isinstance(traj, list) or len(traj) == 0:
309
+ raise ValueError(f"Missing/invalid 'traj' in record. task_id={record.get('task_id')}")
310
+
311
+ images: List[PILImage.Image] = []
312
+ for i, step in enumerate(traj):
313
+ img_name = step.get("image")
314
+ if not isinstance(img_name, str) or not img_name:
315
+ raise ValueError(
316
+ f"Missing/invalid step.image at traj[{i}]. task_id={record.get('task_id')} step={step}"
317
+ )
318
+ img_path = extracted_images_dir / img_name
319
+ images.append(_load_image_or_raise(img_path))
320
+
321
+ messages: List[Dict[str, Any]] = []
322
+
323
+ messages.append(
324
+ {
325
+ "role": "user",
326
+ "content": [
327
+ {"type": "image", "image": images[0]},
328
+ {"type": "text", "text": instruction},
329
+ ],
330
+ }
331
+ )
332
+
333
+ for i, step in enumerate(traj):
334
+ value = step.get("value")
335
+ if not isinstance(value, dict):
336
+ raise ValueError(f"Missing/invalid step.value at traj[{i}] task_id={record.get('task_id')}")
337
+
338
+ thought = value.get("thought")
339
+ action_text = value.get("action")
340
+ code = value.get("code")
341
+
342
+ if not isinstance(thought, str):
343
+ raise ValueError(f"Missing/invalid value.thought at traj[{i}] task_id={record.get('task_id')}")
344
+ if not isinstance(action_text, str):
345
+ raise ValueError(f"Missing/invalid value.action at traj[{i}] task_id={record.get('task_id')}")
346
+ if not isinstance(code, str):
347
+ raise ValueError(f"Missing/invalid value.code at traj[{i}] task_id={record.get('task_id')}")
348
+
349
+ tool_calls = agentnet_code_to_qwen_tool_calls(code)
350
+
351
+ messages.append(
352
+ {
353
+ "role": "assistant",
354
+ "reasoning_content": thought,
355
+ "content": [{"type": "text", "text": action_text}],
356
+ "tool_calls": tool_calls,
357
+ }
358
+ )
359
+
360
+ if i != len(traj) - 1:
361
+ messages.append(
362
+ {
363
+ "role": "user",
364
+ "content": [
365
+ {"type": "image", "image": images[i + 1]},
366
+ ],
367
+ }
368
+ )
369
+
370
+ last_step_tool_calls = messages[-1].get("tool_calls")
371
+ if not isinstance(last_step_tool_calls, list) or len(last_step_tool_calls) == 0:
372
+ raise ValueError(f"Last assistant message has no tool_calls. task_id={record.get('task_id')}")
373
+
374
+ last_call = last_step_tool_calls[-1]
375
+ try:
376
+ last_action = last_call["function"]["arguments"]["action"]
377
+ except Exception:
378
+ raise ValueError(
379
+ f"Malformed tool_call structure in last step. task_id={record.get('task_id')} tool_call={last_call}"
380
+ )
381
+
382
+ if last_action != "terminate":
383
+ raise ValueError(
384
+ f"Final action is not terminate. task_id={record.get('task_id')} final_action={last_action!r}"
385
+ )
386
+
387
+ return {"messages": messages}
388
+
389
+
390
+ def compute_shard_range(num_records: int, rank: int, world_size: int) -> Tuple[int, int]:
391
+ """Contiguous shard ranges.
392
+
393
+ Ensures:
394
+ - rank=0 gets the first chunk
395
+ - total coverage is exact (some ranks may get +1 if num_records % world_size != 0)
396
+ """
397
+ if world_size <= 0:
398
+ raise ValueError(f"Invalid world_size={world_size}")
399
+ if rank < 0 or rank >= world_size:
400
+ raise ValueError(f"Invalid rank={rank} for world_size={world_size}")
401
+
402
+ shard_size = num_records // world_size
403
+ remainder = num_records % world_size
404
+
405
+ start = rank * shard_size + min(rank, remainder)
406
+ end = start + shard_size + (1 if rank < remainder else 0)
407
+ return start, end
408
+
409
+
410
+ def _count_nonempty_lines(jsonl_path: Path) -> int:
411
+ n = 0
412
+ with jsonl_path.open("r", encoding="utf-8") as f:
413
+ for line in f:
414
+ if line.strip():
415
+ n += 1
416
+ return n
417
+
418
+
419
+ def iter_examples(
420
+ jsonl_path: Path,
421
+ extracted_images_dir: Path,
422
+ rank: Optional[int] = None,
423
+ world_size: Optional[int] = None,
424
+ ) -> Iterable[Dict[str, Any]]:
425
+ """Yield dataset rows from a JSONL file, optionally sharded contiguously by (rank, world_size)."""
426
+ if (rank is None) ^ (world_size is None):
427
+ raise ValueError("rank and world_size must be both specified or both None.")
428
+ if rank is not None:
429
+ if world_size is None:
430
+ raise ValueError("world_size must be provided if rank is provided.")
431
+ if world_size <= 0:
432
+ raise ValueError(f"Invalid world_size={world_size}")
433
+ if rank < 0 or rank >= world_size:
434
+ raise ValueError(f"Invalid rank={rank} for world_size={world_size}")
435
+
436
+ num_records = _count_nonempty_lines(jsonl_path)
437
+ if rank is not None:
438
+ start, end = compute_shard_range(num_records, rank, world_size) # [start, end)
439
+ else:
440
+ start, end = 0, num_records
441
+
442
+ record_idx = 0 # counts non-empty JSONL lines
443
+ with jsonl_path.open("r", encoding="utf-8") as f:
444
+ for line_no, line in tqdm.tqdm(enumerate(f, start=1)):
445
+ line = line.strip()
446
+ if not line:
447
+ continue
448
+
449
+ if record_idx < start:
450
+ record_idx += 1
451
+ continue
452
+ if record_idx >= end:
453
+ break
454
+
455
+ try:
456
+ record = json.loads(line)
457
+ except Exception as e:
458
+ raise ValueError(f"JSON parse error at line {line_no} (record_idx={record_idx}) in {jsonl_path}") from e
459
+
460
+ if not isinstance(record, dict):
461
+ raise ValueError(f"Expected JSON object at line {line_no} (record_idx={record_idx})")
462
+
463
+ yield record_to_example(record, extracted_images_dir=extracted_images_dir)
464
+ record_idx += 1
465
+
466
+
467
+ def build_features() -> Any:
468
+ """Define HuggingFace datasets Features for stable serialization."""
469
+ from datasets import Features, Image, Sequence, Value
470
+
471
+ return Features(
472
+ {
473
+ "messages": Sequence(
474
+ {
475
+ "role": Value("string"),
476
+ "content": Sequence(
477
+ {
478
+ "type": Value("string"),
479
+ "text": Value("string"),
480
+ "image": Image(),
481
+ }
482
+ ),
483
+ "reasoning_content": Value("string"),
484
+ "tool_calls": Sequence(
485
+ {
486
+ "type": Value("string"),
487
+ "function": {
488
+ "name": Value("string"),
489
+ "arguments": {
490
+ "action": Value("string"),
491
+ "keys": Sequence(Value("string")),
492
+ "text": Value("string"),
493
+ "coordinate": Sequence(Value("int64")),
494
+ "pixels": Value("int64"),
495
+ "time": Value("float32"),
496
+ "status": Value("string"),
497
+ },
498
+ },
499
+ }
500
+ ),
501
+ }
502
+ ),
503
+ }
504
+ )
505
+
506
+
507
+ def main() -> None:
508
+ args = tyro.cli(ScriptArguments)
509
+
510
+ jsonl_path = Path(args.jsonl_path)
511
+ extracted_images_dir = Path(args.extracted_images_dir)
512
+ output_path = Path(args.output_path)
513
+
514
+ if not jsonl_path.exists():
515
+ raise FileNotFoundError(f"jsonl_path not found: {jsonl_path}")
516
+ if not extracted_images_dir.exists():
517
+ raise FileNotFoundError(f"extracted_images_dir not found: {extracted_images_dir}")
518
+
519
+ # If sharded, save into a deterministic shard subdir so ranks don't clobber each other.
520
+ if args.rank is not None and args.world_size is not None:
521
+ output_path = output_path / f"shard-{args.rank:05d}-of-{args.world_size:05d}"
522
+
523
+ if output_path.exists():
524
+ if not args.overwrite:
525
+ raise FileExistsError(
526
+ f"output_path already exists: {output_path}. Use --overwrite to replace it."
527
+ )
528
+ shutil.rmtree(output_path)
529
+
530
+ from datasets import Dataset
531
+
532
+ features = build_features()
533
+
534
+ if hasattr(Dataset, "from_generator"):
535
+ ds = Dataset.from_generator(
536
+ iter_examples,
537
+ gen_kwargs={
538
+ "jsonl_path": jsonl_path,
539
+ "extracted_images_dir": extracted_images_dir,
540
+ "rank": args.rank,
541
+ "world_size": args.world_size,
542
+ },
543
+ )
544
+ else:
545
+ rows = list(
546
+ iter_examples(
547
+ jsonl_path=jsonl_path,
548
+ extracted_images_dir=extracted_images_dir,
549
+ rank=args.rank,
550
+ world_size=args.world_size,
551
+ )
552
+ )
553
+ ds = Dataset.from_list(rows)
554
+
555
+ ds.save_to_disk(str(output_path))
556
+ print(f"Saved dataset with {len(ds)} rows to: {output_path}")
557
+
558
+
559
+ if __name__ == "__main__":
560
+ main()
src/{cua_train → cua_lite/train}/sft.py RENAMED
File without changes
src/cua_lite/utils/utils.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def fill_images_into_messages(example: dict) -> dict:
2
+ """
3
+ Convert content items like:
4
+ {'type':'image','index':k,'text':None}
5
+ into:
6
+ {'type':'image','image': example['images'][k]}
7
+ (keeps other fields untouched)
8
+ """
9
+ images = example.get("images", [])
10
+ messages = example.get("messages", [])
11
+
12
+ for msg in messages:
13
+ content = msg.get("content", [])
14
+ for item in content:
15
+ if item.get("type") == "image":
16
+ idx = item.get("index", None)
17
+ if idx is None:
18
+ continue
19
+ # replace in-place
20
+ item.pop("index", None)
21
+ item.pop("text", None)
22
+ item["image"] = images[idx]
23
+
24
+ return example["messages"]