mxk1998 commited on
Commit
407f617
·
verified ·
1 Parent(s): 3998c19

Publish sealed evaluation sources, batch 19

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. script/add_annotation.py +379 -0
  2. script/collect_data.py +250 -0
  3. script/create_messy_data.py +1078 -0
  4. script/create_object_data.py +1093 -0
  5. script/eval_groot.sh +40 -0
  6. script/eval_policy.py +389 -0
  7. script/eval_policy_client.py +535 -0
  8. script/groot_simulation_client.py +638 -0
  9. script/policy_model_server.py +268 -0
  10. script/requirements.txt +26 -0
  11. script/set_log.py +51 -0
  12. script/test_render.py +64 -0
  13. script/update_embodiment_config_path.py +104 -0
  14. scripts/check_agibot_future_video_motion.py +642 -0
  15. scripts/cosmos25_image_to_video_compare.py +353 -0
  16. scripts/rsync_push.sh +101 -0
  17. scripts/run_scripts/Robocasa/run_lerobot_datasets_qwenGR00T.sh +57 -0
  18. scripts/run_scripts/run_lerobot_datasets_qwenGR00T.sh +72 -0
  19. scripts/run_scripts/run_lerobot_datasets_qwenfast.sh +75 -0
  20. scripts/run_scripts/run_lerobot_datasets_qwenoft.sh +74 -0
  21. scripts/run_scripts/run_lerobot_datasets_qwenpi.sh +72 -0
  22. starVLA/__init__.py +0 -0
  23. starVLA/config/deepseeds/deepspeed_zero2.yaml +9 -0
  24. starVLA/config/deepseeds/deepspeed_zero3.yaml +7 -0
  25. starVLA/config/deepseeds/ds_config.yaml +23 -0
  26. starVLA/config/deepseeds/zero2.yaml +21 -0
  27. starVLA/config/deepseeds/zero3.yaml +28 -0
  28. starVLA/config/training/starvla_cotrain_libero.yaml +111 -0
  29. starVLA/config/training/starvla_cotrain_oxe.yaml +112 -0
  30. starVLA/config/training/starvla_train_adapter.yaml +73 -0
  31. starVLA/dataloader/__init__.py +101 -0
  32. starVLA/dataloader/gr00t_lerobot/README.md +0 -0
  33. starVLA/dataloader/gr00t_lerobot/__init__.py +0 -0
  34. starVLA/dataloader/gr00t_lerobot/data_config.py +1208 -0
  35. starVLA/dataloader/gr00t_lerobot/datasets.py +0 -0
  36. starVLA/dataloader/gr00t_lerobot/embodiment_tags.py +111 -0
  37. starVLA/dataloader/gr00t_lerobot/mixtures.py +301 -0
  38. starVLA/dataloader/gr00t_lerobot/schema.py +221 -0
  39. starVLA/dataloader/gr00t_lerobot/transform/__init__.py +41 -0
  40. starVLA/dataloader/gr00t_lerobot/transform/base.py +134 -0
  41. starVLA/dataloader/gr00t_lerobot/transform/concat.py +215 -0
  42. starVLA/dataloader/gr00t_lerobot/transform/gr00ttransform.py +459 -0
  43. starVLA/dataloader/gr00t_lerobot/transform/gr00ttransform_1.py +301 -0
  44. starVLA/dataloader/gr00t_lerobot/transform/state_action.py +606 -0
  45. starVLA/dataloader/gr00t_lerobot/transform/video.py +683 -0
  46. starVLA/dataloader/gr00t_lerobot/video.py +338 -0
  47. starVLA/dataloader/lerobot_datasets.py +295 -0
  48. starVLA/dataloader/qwenvl_llavajson/qwen_data_config.py +121 -0
  49. starVLA/dataloader/qwenvl_llavajson/rope2d.py +351 -0
  50. starVLA/dataloader/vlm_datasets.py +946 -0
script/add_annotation.py ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ast
2
+ import tokenize
3
+ import io
4
+ import re
5
+
6
+
7
+ def remove_comments_and_docstrings(source):
8
+ """
9
+ 删除 Python 源码中的注释和文档字符串。
10
+ """
11
+ src = io.StringIO(source)
12
+ out = []
13
+ prev_tok_type = tokenize.INDENT
14
+ last_lineno = -1
15
+ last_col = 0
16
+
17
+ for tok in tokenize.generate_tokens(src.readline):
18
+ token_type = tok.type
19
+ token_string = tok.string
20
+ start_line, start_col = tok.start
21
+ end_line, end_col = tok.end
22
+
23
+ if start_line > last_lineno:
24
+ out.append("\n" * (start_line - last_lineno - 1))
25
+ last_col = 0
26
+ elif start_col > last_col:
27
+ out.append(" " * (start_col - last_col))
28
+
29
+ if token_type == tokenize.COMMENT:
30
+ pass
31
+ elif token_type == tokenize.STRING:
32
+ if prev_tok_type not in (tokenize.INDENT, tokenize.NEWLINE):
33
+ # 判断是否为 docstring
34
+ if re.match(r'^\s*"""(?:[^"]|"{1,2})*"""$', token_string) or re.match(
35
+ r"^\s*'''(?:[^']|'{1,2})*'''$", token_string):
36
+ continue
37
+ else:
38
+ out.append(token_string)
39
+ else:
40
+ continue
41
+ else:
42
+ out.append(token_string)
43
+
44
+ prev_tok_type = token_type
45
+ last_col = end_col
46
+ last_lineno = end_line
47
+
48
+ return "".join([i for i in out if i.strip() != ""]).strip()
49
+
50
+
51
+ def get_method_source(filename, method_name):
52
+ """
53
+ 提取指定类中的方法源码。
54
+ """
55
+ with open(filename, "r", encoding="utf-8") as f:
56
+ source = f.read()
57
+ tree = ast.parse(source)
58
+
59
+ for node in ast.walk(tree):
60
+ if isinstance(node, ast.ClassDef):
61
+ # 遍历类中的所有方法
62
+ for item in node.body:
63
+ if isinstance(item, ast.FunctionDef) and item.name == method_name:
64
+ lines = source.splitlines(keepends=True)
65
+ start_line = item.lineno - 1
66
+ end_line = _get_function_end_line(item, lines)
67
+ method_source = "".join(lines[start_line:end_line])
68
+ return method_source
69
+
70
+ raise ValueError(f"Method '{method_name}' not found.")
71
+
72
+
73
+ def _get_function_end_line(node, lines):
74
+ last_child = None
75
+ for child in ast.walk(node):
76
+ if hasattr(child, "lineno"):
77
+ if last_child is None or child.lineno > last_child.lineno:
78
+ last_child = child
79
+ if last_child:
80
+ return last_child.lineno
81
+ return node.lineno
82
+
83
+
84
+ def save_to_tmp(method_source, tmp_file="tmp.txt"):
85
+ with open(tmp_file, "w", encoding="utf-8") as f:
86
+ f.write(method_source)
87
+
88
+
89
+ def read_from_new(new_file="new.txt"):
90
+ with open(new_file, "r", encoding="utf-8") as f:
91
+ return f.read()
92
+
93
+
94
+ def normalize_code(code):
95
+ code_no_comments = remove_comments_and_docstrings(code)
96
+ return code_no_comments
97
+
98
+
99
+ def compare_functions(code1, code2):
100
+ normalized1 = normalize_code(code1)
101
+ normalized2 = normalize_code(code2)
102
+ return normalized1 == normalized2
103
+
104
+
105
+ def replace_method_in_file_with_comments(filename, method_name, new_method_source):
106
+ """
107
+ 将指定类中的方法替换为新内容(保留注释等原始结构)。
108
+ """
109
+ with open(filename, "r", encoding="utf-8") as f:
110
+ lines = f.readlines()
111
+
112
+ with open(filename, "r", encoding="utf-8") as f:
113
+ source = f.read()
114
+
115
+ tree = ast.parse(source)
116
+
117
+ for node in ast.walk(tree):
118
+ if isinstance(node, ast.ClassDef):
119
+ for item in node.body:
120
+ if isinstance(item, ast.FunctionDef) and item.name == method_name:
121
+ start_line = item.lineno - 1 # lineno 是 1-based
122
+ end_line = _get_function_end_line(item, lines)
123
+
124
+ # 新方法内容按行分割,并保留缩进结构
125
+ # 注意:new_method_source 应当是 new.txt 的原始字符串
126
+ new_lines = new_method_source.splitlines(keepends=True)
127
+
128
+ # 替换对应行区间
129
+ lines[start_line:end_line] = new_lines
130
+
131
+ # 写回文件
132
+ with open(filename, "w", encoding="utf-8") as f:
133
+ f.writelines(lines)
134
+ return
135
+
136
+ raise ValueError(f"Method '{method_name}' not found.")
137
+
138
+
139
+ system_prompt = """
140
+ 角色:你是一个专业的程序员,具有深厚的 Python 编程能力,能够快速理解和修改代码。你会根据我的要求来为代码添加相应的解释。
141
+ 任务:我会给你一段 Python 代码,你需要根据我的要求添加注释。注意,你不能对代码内容进行任何修改,只能添加注释。
142
+ - 在 play_once 中:
143
+ - 你需要理解下面这些可用的函数调用:
144
+ - 我定义了 self.move() 函数,可以传递至多两个参数,分别是 actions_by_arm1, actions_by_arm2。
145
+ - 以下函数会返回 actions(即一个动作序列):
146
+ - self.grasp_actor(actor, arm_tag:ArmTag, **args)
147
+ - self.place_actor(actor, arm_tag:ArmTag, target_pose, **args)
148
+ - self.move_to_pose(arm_tag:ArmTag, target_pose)
149
+ - self.move_by_displacement(arm_tag:ArmTag, x, y, z)
150
+ - self.close_gripper(arm_tag:ArmTag, **args)
151
+ - self.open_gripper(arm_tag:ArmTag, **args)
152
+ - self.back_to_origin(arm_tag:ArmTag)
153
+ - 你需要对每一个 self.move 进行注释,说明这个动作/组合动作是做什么的,这里的注释要**使用英文**。
154
+
155
+ 举例:
156
+ - 没加注释前:
157
+ def play_once(self):
158
+ arm_tag = ArmTag('right' if self.object.get_pose().p[0] > 0 else 'left')
159
+
160
+ self.move(self.grasp_actor(self.object, arm_tag=arm_tag, pre_grasp_dis=0.1))
161
+ self.move(self.move_by_displacement(arm_tag=arm_tag, z=0.06))
162
+
163
+ displaystand_pose = self.displaystand.get_functional_point(0)
164
+
165
+ self.move(self.place_actor(self.object, arm_tag=arm_tag, target_pose=displaystand_pose, constrain='free', pre_dis=0.07))
166
+
167
+ self.info['info'] = {'{A}': f"{self.selected_modelname}/base{self.selected_model_id}", '{B}': f"074_displaystand/base{self.displaystand_id}", '{a}': f'{arm_tag}'}
168
+ return self.info
169
+
170
+ - 加注释后:
171
+ ```python
172
+ def play_once(self):
173
+ arm_tag = ArmTag('right' if self.object.get_pose().p[0] > 0 else 'left')
174
+
175
+ # Grasp the object
176
+ self.move(self.grasp_actor(self.object, arm_tag=arm_tag, pre_grasp_dis=0.1))
177
+ # Move up
178
+ self.move(self.move_by_displacement(arm_tag=arm_tag, z=0.06))
179
+
180
+ # Get display stand's functional point as target pose
181
+ displaystand_pose = self.displaystand.get_functional_point(0)
182
+
183
+ # Place the object on the display stand
184
+ self.move(self.place_actor(self.object, arm_tag=arm_tag, target_pose=displaystand_pose, constrain='free', pre_dis=0.07))
185
+
186
+ self.info['info'] = {'{A}': f"{self.selected_modelname}/base{self.selected_model_id}", '{B}': f"074_displaystand/base{self.displaystand_id}", '{a}': f'{arm_tag}'}
187
+ return self.info
188
+ ```
189
+
190
+ 约束:你不能对代码内容进行任何修改,只需要添加注释即可。
191
+
192
+ 现在,开始你的工作!你只需要输出代码块即可。
193
+ """
194
+
195
+ import os
196
+ import time
197
+ import traceback
198
+ from openai import OpenAI
199
+
200
+
201
+ def parse(source, max_try=5, verbose=True):
202
+ """AI 解析代码"""
203
+ os.environ["all_proxy"] = ""
204
+ os.environ["http_proxy"] = ""
205
+ os.environ["https_proxy"] = ""
206
+ client = OpenAI(api_key="", base_url="")
207
+ start, try_times = time.time(), 0
208
+ while try_times < max_try:
209
+ try_times += 1
210
+ try:
211
+ response = client.chat.completions.create(
212
+ model="deepseek-v3-250324",
213
+ messages=[
214
+ {
215
+ "role": "system",
216
+ "content": system_prompt
217
+ },
218
+ {
219
+ "role": "user",
220
+ "content": source
221
+ },
222
+ ],
223
+ stream=True,
224
+ )
225
+ on_thinking, thinking, answering = False, "", ""
226
+ process_count, process = 0, ["|", "/", "-", "\\"]
227
+ for chunk in response:
228
+ content = chunk.choices[0].delta.content
229
+ if content is None:
230
+ continue
231
+ if hasattr(chunk.choices[0].delta, "reasoning_content"):
232
+ thinking += chunk.choices[0].delta.reasoning_content
233
+ else:
234
+ if content == "<think>":
235
+ on_thinking = True
236
+ elif content == "</think>":
237
+ on_thinking = False
238
+ elif on_thinking:
239
+ thinking += content
240
+ else:
241
+ answering += content
242
+
243
+ if verbose:
244
+ process_count = (process_count + 1) % 4
245
+ process_show = (thinking + answering)[-50:].replace("\n", "")
246
+ print(f'\r {" "*100}', end="")
247
+ print(f"\r{process[process_count]} {process_show}", end="", flush=True)
248
+ except SyntaxError:
249
+ print(traceback.format_exc())
250
+ break
251
+ except:
252
+ print(traceback.format_exc())
253
+ continue
254
+
255
+ result = re.search(r"```python\n([\s\S]*?)\n```", answering, re.S)
256
+ if result is not None:
257
+ if verbose:
258
+ print(
259
+ f"cost {time.time()-start:.2f}s, try {try_times} time(s)",
260
+ flush=True,
261
+ )
262
+ return result.group(1)
263
+ return None
264
+
265
+
266
+ def main(file_path, max_try=5, verbose=True):
267
+ try_count = 0
268
+ while try_count < max_try:
269
+ try_count += 1
270
+ # Step 1: 提取类中的方法
271
+ method_source = get_method_source(file_path, "play_once")
272
+
273
+ # Step 2: 调用 AI 解析代码
274
+ processed_source = parse(method_source, max_try=5, verbose=verbose)
275
+
276
+ # Step 3: 比较两个方法
277
+ if compare_functions(method_source, processed_source):
278
+ replace_method_in_file_with_comments(file_path, "play_once", processed_source)
279
+ break
280
+
281
+ if try_count >= max_try:
282
+ with open("error.log", "a", encoding="utf-8") as f:
283
+ f.write(f"Error processing {file_path}: Exceeded maximum retries.\n")
284
+
285
+
286
+ from threading import Thread
287
+ from pathlib import Path
288
+
289
+
290
+ def batch(batch_size=5, root="./envs"):
291
+ name_list = [
292
+ "beat_block_hammer",
293
+ "blocks_ranking_rgb",
294
+ "blocks_ranking_size",
295
+ "dump_bin_bigbin",
296
+ "grab_roller",
297
+ "lift_pot",
298
+ "move_can_pot",
299
+ "move_playingcard_away",
300
+ "move_stapler_pad",
301
+ "place_a2b_left",
302
+ "place_a2b_right",
303
+ "place_bread_basket",
304
+ "place_bread_skillet",
305
+ "place_can_basket",
306
+ "place_cylinder_box",
307
+ "place_fan",
308
+ "place_medicine_spot",
309
+ "place_mouse_pad",
310
+ "place_object_scale",
311
+ "place_object_stand",
312
+ "place_phone_stand",
313
+ "place_remote_storage",
314
+ "place_object_basket",
315
+ "put_bottles_dustbin",
316
+ "rotate_qrcode",
317
+ "shake_bottle",
318
+ "shake_bottle_horizontally",
319
+ "place_shoe",
320
+ "slide_mouse_pad",
321
+ "stamp_seal",
322
+ "handover_block",
323
+ "stack_blocks_three",
324
+ "stack_blocks_two",
325
+ "adjust_bottle",
326
+ "stack_bowls_three",
327
+ "stack_bowls_two",
328
+ "click_alarmclock",
329
+ "click_bell",
330
+ "place_container_plate",
331
+ "pick_diverse_bottles",
332
+ "pick_dual_bottles",
333
+ "place_dual_shoes",
334
+ "place_empty_cup",
335
+ "place_object_into_plasticbox",
336
+ ]
337
+ process_list = []
338
+ for file in name_list:
339
+ file = Path(root) / f"{file}.py"
340
+ if file.exists():
341
+ process_list.append(file)
342
+ else:
343
+ print(f"WARNNING: {file.name} not exists!")
344
+
345
+ # Create and start a thread for each file
346
+ threads = []
347
+ finish_count, total_count = 0, len(process_list)
348
+ for file in process_list:
349
+ thread = Thread(target=main, args=(file, 5, False))
350
+ thread.start()
351
+ threads.append([file, thread])
352
+ while len(threads) >= batch_size:
353
+ for t in threads:
354
+ if not t[1].is_alive():
355
+ threads.remove(t)
356
+ finish_count += 1
357
+ print(
358
+ f"[{finish_count:>3d}/{total_count:03d}] files processed. new finish:",
359
+ t[0].name,
360
+ flush=True,
361
+ )
362
+ time.sleep(0.1)
363
+
364
+ # Wait for all threads to complete
365
+ while len(threads) > 0:
366
+ for t in threads:
367
+ if not t[1].is_alive():
368
+ threads.remove(t)
369
+ finish_count += 1
370
+ print(
371
+ f"[{finish_count:>3d}/{total_count:03d}] files processed. new finish:",
372
+ t[0].name,
373
+ flush=True,
374
+ )
375
+ time.sleep(0.1)
376
+
377
+
378
+ if __name__ == "__main__":
379
+ batch()
script/collect_data.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ sys.path.append("./")
4
+
5
+ import sapien.core as sapien
6
+ from sapien.render import clear_cache
7
+ from collections import OrderedDict
8
+ import pdb
9
+ from envs import *
10
+ import yaml
11
+ import importlib
12
+ import json
13
+ import traceback
14
+ import os
15
+ import time
16
+ from argparse import ArgumentParser
17
+
18
+ current_file_path = os.path.abspath(__file__)
19
+ parent_directory = os.path.dirname(current_file_path)
20
+
21
+
22
+ def class_decorator(task_name):
23
+ envs_module = importlib.import_module(f"envs.{task_name}")
24
+ try:
25
+ env_class = getattr(envs_module, task_name)
26
+ env_instance = env_class()
27
+ except:
28
+ raise SystemExit("No such task")
29
+ return env_instance
30
+
31
+
32
+ def get_embodiment_config(robot_file):
33
+ robot_config_file = os.path.join(robot_file, "config.yml")
34
+ with open(robot_config_file, "r", encoding="utf-8") as f:
35
+ embodiment_args = yaml.load(f.read(), Loader=yaml.FullLoader)
36
+ return embodiment_args
37
+
38
+
39
+ def main(task_name=None, task_config=None):
40
+
41
+ task = class_decorator(task_name)
42
+ config_path = f"./task_config/{task_config}.yml"
43
+
44
+ with open(config_path, "r", encoding="utf-8") as f:
45
+ args = yaml.load(f.read(), Loader=yaml.FullLoader)
46
+
47
+ args['task_name'] = task_name
48
+
49
+ embodiment_type = args.get("embodiment")
50
+ embodiment_config_path = os.path.join(CONFIGS_PATH, "_embodiment_config.yml")
51
+
52
+ with open(embodiment_config_path, "r", encoding="utf-8") as f:
53
+ _embodiment_types = yaml.load(f.read(), Loader=yaml.FullLoader)
54
+
55
+ def get_embodiment_file(embodiment_type):
56
+ robot_file = _embodiment_types[embodiment_type]["file_path"]
57
+ if robot_file is None:
58
+ raise "missing embodiment files"
59
+ return robot_file
60
+
61
+ if len(embodiment_type) == 1:
62
+ args["left_robot_file"] = get_embodiment_file(embodiment_type[0])
63
+ args["right_robot_file"] = get_embodiment_file(embodiment_type[0])
64
+ args["dual_arm_embodied"] = True
65
+ elif len(embodiment_type) == 3:
66
+ args["left_robot_file"] = get_embodiment_file(embodiment_type[0])
67
+ args["right_robot_file"] = get_embodiment_file(embodiment_type[1])
68
+ args["embodiment_dis"] = embodiment_type[2]
69
+ args["dual_arm_embodied"] = False
70
+ else:
71
+ raise "number of embodiment config parameters should be 1 or 3"
72
+
73
+ args["left_embodiment_config"] = get_embodiment_config(args["left_robot_file"])
74
+ args["right_embodiment_config"] = get_embodiment_config(args["right_robot_file"])
75
+
76
+ if len(embodiment_type) == 1:
77
+ embodiment_name = str(embodiment_type[0])
78
+ else:
79
+ embodiment_name = str(embodiment_type[0]) + "+" + str(embodiment_type[1])
80
+
81
+ # show config
82
+ print("============= Config =============\n")
83
+ print("\033[95mMessy Table:\033[0m " + str(args["domain_randomization"]["cluttered_table"]))
84
+ print("\033[95mRandom Background:\033[0m " + str(args["domain_randomization"]["random_background"]))
85
+ if args["domain_randomization"]["random_background"]:
86
+ print(" - Clean Background Rate: " + str(args["domain_randomization"]["clean_background_rate"]))
87
+ print("\033[95mRandom Light:\033[0m " + str(args["domain_randomization"]["random_light"]))
88
+ if args["domain_randomization"]["random_light"]:
89
+ print(" - Crazy Random Light Rate: " + str(args["domain_randomization"]["crazy_random_light_rate"]))
90
+ print("\033[95mRandom Table Height:\033[0m " + str(args["domain_randomization"]["random_table_height"]))
91
+ print("\033[95mRandom Head Camera Distance:\033[0m " + str(args["domain_randomization"]["random_head_camera_dis"]))
92
+
93
+ print("\033[94mHead Camera Config:\033[0m " + str(args["camera"]["head_camera_type"]) + f", " +
94
+ str(args["camera"]["collect_head_camera"]))
95
+ print("\033[94mWrist Camera Config:\033[0m " + str(args["camera"]["wrist_camera_type"]) + f", " +
96
+ str(args["camera"]["collect_wrist_camera"]))
97
+ print("\033[94mEmbodiment Config:\033[0m " + embodiment_name)
98
+ print("\n==================================")
99
+
100
+ args["embodiment_name"] = embodiment_name
101
+ args['task_config'] = task_config
102
+ args["save_path"] = os.path.join(args["save_path"], str(args["task_name"]), args["task_config"])
103
+ run(task, args)
104
+
105
+
106
+ def run(TASK_ENV, args):
107
+ epid, suc_num, fail_num, seed_list = 0, 0, 0, []
108
+
109
+ print(f"Task Name: \033[34m{args['task_name']}\033[0m")
110
+
111
+ # =========== Collect Seed ===========
112
+ os.makedirs(args["save_path"], exist_ok=True)
113
+
114
+ if not args["use_seed"]:
115
+ print("\033[93m" + "[Start Seed and Pre Motion Data Collection]" + "\033[0m")
116
+ args["need_plan"] = True
117
+
118
+ if os.path.exists(os.path.join(args["save_path"], "seed.txt")):
119
+ with open(os.path.join(args["save_path"], "seed.txt"), "r") as file:
120
+ seed_list = file.read().split()
121
+ if len(seed_list) != 0:
122
+ seed_list = [int(i) for i in seed_list]
123
+ suc_num = len(seed_list)
124
+ epid = max(seed_list) + 1
125
+ print(f"Exist seed file, Start from: {epid} / {suc_num}")
126
+
127
+ while suc_num < args["episode_num"]:
128
+ try:
129
+ TASK_ENV.setup_demo(now_ep_num=suc_num, seed=epid, **args)
130
+ TASK_ENV.play_once()
131
+
132
+ if TASK_ENV.plan_success and TASK_ENV.check_success():
133
+ print(f"simulate data episode {suc_num} success! (seed = {epid})")
134
+ seed_list.append(epid)
135
+ TASK_ENV.save_traj_data(suc_num)
136
+ suc_num += 1
137
+ else:
138
+ print(f"simulate data episode {suc_num} fail! (seed = {epid})")
139
+ fail_num += 1
140
+
141
+ TASK_ENV.close_env()
142
+
143
+ if args["render_freq"]:
144
+ TASK_ENV.viewer.close()
145
+ except UnStableError as e:
146
+ print(" -------------")
147
+ print(f"simulate data episode {suc_num} fail! (seed = {epid})")
148
+ print("Error: ", e)
149
+ print(" -------------")
150
+ fail_num += 1
151
+ TASK_ENV.close_env()
152
+
153
+ if args["render_freq"]:
154
+ TASK_ENV.viewer.close()
155
+ time.sleep(0.3)
156
+ except Exception as e:
157
+ # stack_trace = traceback.format_exc()
158
+ print(" -------------")
159
+ print(f"simulate data episode {suc_num} fail! (seed = {epid})")
160
+ print("Error: ", e)
161
+ print(" -------------")
162
+ fail_num += 1
163
+ TASK_ENV.close_env()
164
+
165
+ if args["render_freq"]:
166
+ TASK_ENV.viewer.close()
167
+ time.sleep(1)
168
+
169
+ epid += 1
170
+
171
+ with open(os.path.join(args["save_path"], "seed.txt"), "w") as file:
172
+ for sed in seed_list:
173
+ file.write("%s " % sed)
174
+
175
+ print(f"\nComplete simulation, failed \033[91m{fail_num}\033[0m times / {epid} tries \n")
176
+ else:
177
+ print("\033[93m" + "Use Saved Seeds List".center(30, "-") + "\033[0m")
178
+ with open(os.path.join(args["save_path"], "seed.txt"), "r") as file:
179
+ seed_list = file.read().split()
180
+ seed_list = [int(i) for i in seed_list]
181
+
182
+ # =========== Collect Data ===========
183
+
184
+ if args["collect_data"]:
185
+ print("\033[93m" + "[Start Data Collection]" + "\033[0m")
186
+
187
+ args["need_plan"] = False
188
+ args["render_freq"] = 0
189
+ args["save_data"] = True
190
+
191
+ clear_cache_freq = args["clear_cache_freq"]
192
+
193
+ st_idx = 0
194
+
195
+ def exist_hdf5(idx):
196
+ file_path = os.path.join(args["save_path"], 'data', f'episode{idx}.hdf5')
197
+ return os.path.exists(file_path)
198
+
199
+ while exist_hdf5(st_idx):
200
+ st_idx += 1
201
+
202
+ for episode_idx in range(st_idx, args["episode_num"]):
203
+ print(f"\033[34mTask name: {args['task_name']}\033[0m")
204
+
205
+ TASK_ENV.setup_demo(now_ep_num=episode_idx, seed=seed_list[episode_idx], **args)
206
+
207
+ traj_data = TASK_ENV.load_tran_data(episode_idx)
208
+ args["left_joint_path"] = traj_data["left_joint_path"]
209
+ args["right_joint_path"] = traj_data["right_joint_path"]
210
+ TASK_ENV.set_path_lst(args)
211
+
212
+ info_file_path = os.path.join(args["save_path"], "scene_info.json")
213
+
214
+ if not os.path.exists(info_file_path):
215
+ with open(info_file_path, "w", encoding="utf-8") as file:
216
+ json.dump({}, file, ensure_ascii=False)
217
+
218
+ with open(info_file_path, "r", encoding="utf-8") as file:
219
+ info_db = json.load(file)
220
+
221
+ info = TASK_ENV.play_once()
222
+ info_db[f"episode_{episode_idx}"] = info
223
+
224
+ with open(info_file_path, "w", encoding="utf-8") as file:
225
+ json.dump(info_db, file, ensure_ascii=False, indent=4)
226
+
227
+ TASK_ENV.close_env(clear_cache=((episode_idx + 1) % clear_cache_freq == 0))
228
+ TASK_ENV.merge_pkl_to_hdf5_video()
229
+ TASK_ENV.remove_data_cache()
230
+ assert TASK_ENV.check_success(), "Collect Error"
231
+
232
+ command = f"cd description && bash gen_episode_instructions.sh {args['task_name']} {args['task_config']} {args['language_num']}"
233
+ os.system(command)
234
+
235
+
236
+ if __name__ == "__main__":
237
+ from test_render import Sapien_TEST
238
+ Sapien_TEST()
239
+
240
+ import torch.multiprocessing as mp
241
+ mp.set_start_method("spawn", force=True)
242
+
243
+ parser = ArgumentParser()
244
+ parser.add_argument("task_name", type=str)
245
+ parser.add_argument("task_config", type=str)
246
+ parser = parser.parse_args()
247
+ task_name = parser.task_name
248
+ task_config = parser.task_config
249
+
250
+ main(task_name=task_name, task_config=task_config)
script/create_messy_data.py ADDED
@@ -0,0 +1,1078 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import trimesh
2
+ import importlib
3
+ import numpy as np
4
+ from pathlib import Path
5
+ from copy import deepcopy
6
+ import transforms3d as t3d
7
+ from threading import Thread
8
+ import readline
9
+
10
+ import sys
11
+
12
+ import trimesh.bounds
13
+
14
+ sys.path.append(".")
15
+ from envs.utils import *
16
+ import sapien.core as sapien
17
+ from sapien.utils.viewer import Viewer
18
+ from tqdm import tqdm
19
+ from PIL import Image
20
+
21
+ import re
22
+ import time
23
+ from typing import List, Literal
24
+
25
+ from sapien import Pose
26
+
27
+ # obj square
28
+ CAMERA_POSE = Pose([0, 0.134123, 0.96], [0.684988, 0.174248, 0.173926, -0.685696])
29
+ # main graph
30
+ # CAMERA_POSE = Pose([0.0293144, -1.12261, 1.52599], [0.665553, 0.233024, 0.231257, -0.670268])
31
+
32
+ class Helper:
33
+ POINTS = [
34
+ ("target_pose", "target"),
35
+ ("contact_points_pose", "contact"),
36
+ ("functional_matrix", "functional"),
37
+ ("orientation_point", "orientation"),
38
+ ]
39
+
40
+ def create_scene(self, viewer=True, **kwargs):
41
+ """
42
+ Set the scene
43
+ - Set up the basic scene: light source, viewer.
44
+ """
45
+ self.engine = sapien.Engine()
46
+ # declare sapien renderer
47
+ from sapien.render import set_global_config
48
+
49
+ set_global_config(max_num_materials=50000, max_num_textures=50000)
50
+ self.renderer = sapien.SapienRenderer()
51
+ # give renderer to sapien sim
52
+ self.engine.set_renderer(self.renderer)
53
+
54
+ sapien.render.set_camera_shader_dir("rt")
55
+ sapien.render.set_ray_tracing_samples_per_pixel(32)
56
+ sapien.render.set_ray_tracing_path_depth(8)
57
+ sapien.render.set_ray_tracing_denoiser("oidn")
58
+
59
+ # declare sapien scene
60
+ scene_config = sapien.SceneConfig()
61
+ self.scene = self.engine.create_scene(scene_config)
62
+ # set simulation timestep
63
+ self.scene.set_timestep(kwargs.get("timestep", 1 / 250))
64
+
65
+ # initialize viewer with camera position and orientation
66
+ if viewer:
67
+ self.viewer = Viewer(self.renderer)
68
+ self.viewer.set_scene(self.scene)
69
+ self.viewer.set_camera_xyz(
70
+ x=kwargs.get("camera_xyz_x", 0.4),
71
+ y=kwargs.get("camera_xyz_y", 0.22),
72
+ z=kwargs.get("camera_xyz_z", 1.5),
73
+ )
74
+ self.viewer.set_camera_rpy(
75
+ r=kwargs.get("camera_rpy_r", 0),
76
+ p=kwargs.get("camera_rpy_p", -0.8),
77
+ y=kwargs.get("camera_rpy_y", 2.45),
78
+ )
79
+ else:
80
+ self.viewer = None
81
+ self.camera = self.scene.add_camera("camera", 2390, 1000, 1.57, 0.1, 1000)
82
+ self.camera.set_pose(CAMERA_POSE)
83
+ # scale = 1
84
+ # self.camera = self.scene.add_camera(name="", width=2560*scale, height=1600*scale, fovy=1.57, near=0.1, far=1e+03)
85
+ # self.camera.set_local_pose(sapien.Pose([-0.893507, -0.358009, 0.983116], [0.869079, 0.128192, 0.298895, -0.372735]))
86
+
87
+ def create_table_and_wall(self):
88
+ # add ground to scene
89
+ # self.scene.add_ground(0)
90
+ # set default physical material
91
+ self.scene.default_physical_material = self.scene.create_physical_material(0.5, 0.5, 0)
92
+ # give some white ambient light of moderate intensity
93
+ self.scene.set_ambient_light([0.5, 0.5, 0.5])
94
+ # default enable shadow unless specified otherwise
95
+ shadow = False
96
+ # default spotlight angle and intensity
97
+ direction_lights = [[[0, 0.5, -1], [0.5, 0.5, 0.5]]]
98
+ self.direction_light_lst = []
99
+ for direction_light in direction_lights:
100
+ self.direction_light_lst.append(self.scene.add_directional_light(direction_light[0], direction_light[1], shadow=shadow))
101
+ # default point lights position and intensity
102
+ point_lights = [
103
+ [[1, 0, 1.8], [1, 1, 1]],
104
+ [[-1, 0, 1.8], [1, 1, 1]],
105
+ [[2.6, -1.7, 0.76], [1, 1, 1]],
106
+ [[-2.6, -1.7, 0.76], [1, 1, 1]],
107
+ [[-1.2, -4.4, 0.76], [1, 1, 1]],
108
+ [[1.2, -4.4, 0.76], [1, 1, 1]],
109
+ ]
110
+ self.point_light_lst = []
111
+ for point_light in point_lights:
112
+ self.point_light_lst.append(self.scene.add_point_light(point_light[0], point_light[1], shadow=shadow))
113
+
114
+ # creat wall
115
+ wall_texture, table_texture = None, None
116
+ # self.wall_texture, self.table_texture = 0, 0
117
+ # self.wall = create_box(
118
+ # self.scene,
119
+ # sapien.Pose(p=[0, 1, 1.5]),
120
+ # half_size=[3, 0.6, 1.5],
121
+ # color=(1, 0.9, 0.9),
122
+ # name='wall',
123
+ # texture_id=wall_texture
124
+ # )
125
+
126
+ # self.table_z_bias = np.random.random()*0.3 - 0.15
127
+ # print('bias:', self.table_z_bias)
128
+ # self.table_z_bias = 0
129
+ # table_height = self.table_z_bias + 0.74
130
+
131
+ # creat table
132
+ # self.table = create_table(
133
+ # self.scene,
134
+ # sapien.Pose(p = [0, 0, table_height]),
135
+ # length=2,
136
+ # width=4,
137
+ # height=table_height,
138
+ # thickness=0.05,
139
+ # is_static=True,
140
+ # texture_id=table_texture
141
+ # )
142
+
143
+ def init_messy(self):
144
+ with open("./assets/objects/objaverse/list.json", "r") as file:
145
+ self.messy_item_info = json.load(file)
146
+ self.obj_names = self.messy_item_info["item_names"]
147
+ self.size_dict = []
148
+ self.obj_list = []
149
+ self.max_obj_num = 1
150
+
151
+ def add_messy_obj(self, name, idx, xlim=[-0.3, 0.3], ylim=[-0.2, 0.2], zlim=[0.741]):
152
+ tyrs, max_try = 0, 100
153
+ success_count, messy_obj = 0, None
154
+ while tyrs < max_try:
155
+ obj_str = f"{name}_{idx}"
156
+ obj_radius = self.messy_item_info["radius"][obj_str]
157
+ obj_offset = self.messy_item_info["z_offset"][obj_str]
158
+ obj_maxz = self.messy_item_info["z_max"][obj_str]
159
+
160
+ success, messy_obj = rand_create_cluttered_actor(
161
+ self.scene,
162
+ xlim=xlim,
163
+ ylim=ylim,
164
+ zlim=np.array(zlim),
165
+ modelname=obj_str,
166
+ rotate_rand=True,
167
+ rotate_lim=[0, 0, np.pi],
168
+ size_dict=self.size_dict,
169
+ obj_radius=obj_radius,
170
+ z_offset=obj_offset,
171
+ z_max=obj_maxz,
172
+ prohibited_area=[],
173
+ )
174
+ if not success:
175
+ continue
176
+ # self.viewer.paused = True
177
+ # while self.viewer.paused:
178
+ # self.scene.update_render()
179
+ # self.viewer.render()
180
+ messy_obj: sapien.Entity = messy_obj[0]
181
+ messy_obj.set_name(obj_str)
182
+ messy_obj.find_component_by_type(sapien.physx.PhysxRigidDynamicComponent).mass = 0.01
183
+ success_count += 1
184
+
185
+ pose = sapien.pysapien.Entity.get_pose(messy_obj).p.tolist()
186
+ pose.append(obj_radius)
187
+ self.size_dict.append(pose)
188
+ self.obj_list.append(messy_obj)
189
+
190
+ if len(self.obj_list) > self.max_obj_num:
191
+ obj = self.obj_list.pop(0)
192
+ self.size_dict.pop(0)
193
+ self.scene.remove_actor(obj)
194
+ self.scene.update_render()
195
+ self.viewer.render()
196
+
197
+ break
198
+ return success_count == 1, messy_obj
199
+
200
+ def check_urdf(self, name, idx, d_range=50, pose=None):
201
+ if pose is None:
202
+ success, obj = self.add_messy_obj(name, idx)
203
+ if not success:
204
+ return False
205
+
206
+ def to_array(pose: sapien.Pose) -> np.ndarray:
207
+ return np.array(pose.p.tolist() + pose.q.tolist())
208
+
209
+ is_step, max_step = 0, 200
210
+ pose_list = [to_array(obj.get_pose())]
211
+ while is_step < max_step:
212
+ self.scene.step()
213
+ self.scene.update_render()
214
+ self.viewer.render()
215
+
216
+ new_pose = obj.get_pose()
217
+ pose_list.append(to_array(new_pose))
218
+
219
+ if len(pose_list) > d_range:
220
+ check_succ = True
221
+ for i in range(-d_range, 0):
222
+ if not np.allclose(pose_list[i], pose_list[-d_range], 1e-4):
223
+ check_succ = False
224
+ break
225
+ if check_succ:
226
+ break
227
+ is_step += 1
228
+
229
+ if is_step > 0 and is_step < max_step:
230
+ success = True
231
+ elif is_step >= max_step:
232
+ success = False
233
+
234
+ # self.viewer.paused = True
235
+ # while self.viewer.paused:
236
+ # self.scene.update_render()
237
+ # self.viewer.render()
238
+ return success
239
+ else:
240
+ modeldir = f"./assets/objects/objaverse/{name}/{idx}/"
241
+ loader: sapien.URDFLoader = self.scene.create_urdf_loader()
242
+
243
+ loader.fix_root_link = True
244
+ loader.load_multiple_collisions_from_file = False
245
+ object = loader.load_multiple(modeldir + "model.urdf")[1][0]
246
+
247
+ object.set_pose(sapien.Pose(pose, [1, 0, 0, 0]))
248
+ object.set_name(name)
249
+
250
+ return True
251
+
252
+ def test_messy(self):
253
+ self.create_scene()
254
+ self.create_table_and_wall()
255
+ self.init_messy()
256
+
257
+ self.result = []
258
+
259
+ test_list = []
260
+ for name in self.obj_names:
261
+ for idx in self.messy_item_info["list_of_items"][name]:
262
+ test_list.append((name, idx))
263
+
264
+ # test_list = test_list[19:]
265
+ for cnt, (name, idx) in enumerate(tqdm(test_list)):
266
+ if name != "ramen_package":
267
+ continue
268
+ # if cnt > 0 and cnt % 100 == 0:
269
+ # time.sleep(3)
270
+ # self.scene.clear()
271
+ # self.create_table_and_wall()
272
+ success = self.check_urdf(name, idx)
273
+ self.result.append({"name": name, "idx": idx, "success": success})
274
+ with open("result.jsonl", "a", encoding="utf-8") as f:
275
+ f.write(json.dumps(self.result[-1]) + "\n")
276
+
277
+ while len(self.obj_list) > 0:
278
+ obj = self.obj_list.pop(0)
279
+ self.size_dict.pop(0)
280
+ self.scene.remove_actor(obj)
281
+ self.scene.update_render()
282
+ self.viewer.render()
283
+
284
+ @staticmethod
285
+ def trans_mat(to_mat: np.ndarray, from_mat: np.ndarray):
286
+ to_rot = to_mat[:3, :3]
287
+ from_rot = from_mat[:3, :3]
288
+ rot_mat = to_rot @ from_rot.T
289
+
290
+ trans_mat = to_mat[:3, 3] - from_mat[:3, 3]
291
+
292
+ result = np.eye(4)
293
+ result[:3, :3] = rot_mat
294
+ result[:3, 3] = trans_mat
295
+ result = np.where(np.abs(result) < 1e-5, 0, result)
296
+ return result
297
+
298
+ @staticmethod
299
+ def trans_base(
300
+ init_pose_mat: np.ndarray,
301
+ now_base_mat: np.ndarray,
302
+ init_base_mat: np.ndarray = np.eye(4),
303
+ ):
304
+ now_pose_mat = np.eye(4)
305
+ base_trans_mat = Helper.trans_mat(now_base_mat, init_base_mat)
306
+ now_pose_mat[:3, :3] = (base_trans_mat[:3, :3] @ init_pose_mat[:3, :3] @ base_trans_mat[:3, :3].T)
307
+ now_pose_mat[:3, 3] = base_trans_mat[:3, :3] @ init_pose_mat[:3, 3]
308
+
309
+ # 转化为世界坐标
310
+ p = now_pose_mat[:3, 3] + now_base_mat[:3, 3]
311
+ q_mat = now_pose_mat[:3, :3] @ now_base_mat[:3, :3]
312
+ return sapien.Pose(p, t3d.quaternions.mat2quat(q_mat))
313
+
314
+ def add_visual_box(self, pose: sapien.Pose, name: str = "box"):
315
+ box, _ = create_obj(
316
+ scene=self.scene,
317
+ pose=pose,
318
+ modelname="vis_box",
319
+ # modelname="cube",
320
+ is_static=True,
321
+ scale=[0.025, 0.025, 0.025],
322
+ no_collision=True,
323
+ )
324
+ box.set_name(name)
325
+
326
+ def check_obj(self, name, idx, mid, d_range=50, pose=None, anno=None):
327
+ if pose is None:
328
+ obj, config = rand_create_actor(
329
+ self.scene,
330
+ xlim=[0, 0],
331
+ ylim=[0, 0],
332
+ zlim=[0.743],
333
+ modelname=f"{idx}_{name}",
334
+ model_id=mid,
335
+ convex=True,
336
+ qpos=[0, 0, 0.707107, 0.707107],
337
+ scale=(0.1, 0.1, 0.1),
338
+ )
339
+ else:
340
+ obj = create_actor(
341
+ self.scene,
342
+ pose=sapien.Pose(pose[:3], [0, 0, 0.707107, 0.707107]),
343
+ modelname=f"{idx}_{name}",
344
+ model_id=mid,
345
+ convex=True,
346
+ is_static=True,
347
+ )
348
+ if obj is None:
349
+ print(f"create obj[{idx}_{name}/{mid}] failed")
350
+ return False
351
+ if anno is not None and (anno is True or (anno[0] <= pose[0] <= anno[1] and anno[2] <= pose[1] <= anno[3])):
352
+ try:
353
+ scale = config["scale"]
354
+ base_mat = obj.get_pose().to_transformation_matrix()
355
+ for key, name in self.POINTS:
356
+ if key == "orientation_point":
357
+ if len(config.get(key, [])) <= 1:
358
+ continue
359
+ points = [config.get(key, [])]
360
+ else:
361
+ points = config.get(key, [])
362
+
363
+ for idx, mat in enumerate(points):
364
+ mat = np.array(mat)
365
+ mat[:3, 3] *= scale
366
+ pose = self.trans_base(mat, base_mat)
367
+ self.add_visual_box(pose, name=f"{name}_{idx}")
368
+ except:
369
+ return False
370
+
371
+ # def to_array(pose:sapien.Pose) -> np.ndarray:
372
+ # return np.array(pose.p.tolist()+pose.q.tolist())
373
+
374
+ # is_step, max_step = 0, 200
375
+ # pose_list = [to_array(obj.get_pose())]
376
+ # while is_step < max_step:
377
+ # self.scene.step()
378
+ # self.scene.update_render()
379
+ # self.viewer.render()
380
+
381
+ # new_pose = obj.get_pose()
382
+ # pose_list.append(to_array(new_pose))
383
+
384
+ # if len(pose_list) > d_range:
385
+ # check_succ = True
386
+ # for i in range(-d_range, 0):
387
+ # if not np.allclose(pose_list[i], pose_list[-d_range], 1e-4):
388
+ # check_succ = False
389
+ # break
390
+ # if check_succ:
391
+ # break
392
+ # is_step += 1
393
+
394
+ # if is_step > 0 and is_step < max_step:
395
+ # success = True
396
+ # elif is_step >= max_step:
397
+ # success = False
398
+
399
+ # self.scene.remove_actor(obj)
400
+ # self.scene.update_render()
401
+ # self.viewer.render()
402
+ # return success
403
+
404
+ def add_robot(self):
405
+
406
+ def init_joints(entity: sapien.physx.PhysxArticulation, config):
407
+ # set joints
408
+ active_joints = entity.get_active_joints()
409
+ arm_joints = [entity.find_joint_by_name(i) for i in config["arm_joints_name"][0]]
410
+
411
+ def get_gripper_joints(find, gripper_name: str):
412
+ gripper = [(find(gripper_name["base"]), 1.0, 0.0)]
413
+ for g in gripper_name["mimic"]:
414
+ gripper.append((find(g[0]), g[1], g[2]))
415
+ return gripper
416
+
417
+ gripper = get_gripper_joints(entity.find_joint_by_name, config["gripper_name"][0])
418
+
419
+ for i, joint in enumerate(active_joints):
420
+ joint.set_drive_property(
421
+ stiffness=config.get("joint_stiffness", 1000),
422
+ damping=config.get("joint_damping", 200),
423
+ )
424
+ for joint in gripper:
425
+ joint[0].set_drive_property(
426
+ stiffness=config.get("gripper_stiffness", 1000),
427
+ damping=config.get("gripper_damping", 200),
428
+ )
429
+ for i, joint in enumerate(active_joints):
430
+ joint.set_drive_target(config["joints"][0][i])
431
+ for i, joint in enumerate(gripper):
432
+ real_joint: sapien.physx.PhysxArticulationJoint = joint[0]
433
+ drive_target = config["gripper_scale"][1] * joint[1] + joint[2]
434
+ drive_velocity_target = (np.clip(drive_target - real_joint.drive_target, -1.0, 1.0) * 0.05)
435
+ real_joint.set_drive_target(drive_target)
436
+ real_joint.set_drive_velocity_target(drive_velocity_target)
437
+
438
+ radius = 2.5
439
+ count, max_count = 0, 13
440
+ emb = Path("./assets/embodiments")
441
+
442
+ joint_dict = {
443
+ "ARX-X5": [-6.155617, 1.1425792, 1.4179262, -0.97225964, -1.4429708e-05, -3.082031e-06, 0.044, 0.044],
444
+ # "ARX-X5": [
445
+ # -6.155634,
446
+ # 0.816421,
447
+ # 1.0468683,
448
+ # -0.9384637,
449
+ # -3.4565306e-05,
450
+ # -8.612996e-06,
451
+ # 0.044,
452
+ # 0.044,
453
+ # ],
454
+ "piper": [
455
+ -0.34990656,
456
+ 1.2450953,
457
+ -1.5324507,
458
+ 0.10282991,
459
+ 1.22,
460
+ 0.00065908127,
461
+ 0.039999943,
462
+ 0.03997663,
463
+ ],
464
+ "franka-panda": [
465
+ -0.00021794076,
466
+ 0.041278794,
467
+ -0.0013123713,
468
+ -1.8957008,
469
+ 0.009215873,
470
+ 2.0166128,
471
+ 0.8549956,
472
+ 0.04,
473
+ 0.04,
474
+ ],
475
+ "aloha-agilex": [
476
+ 0.0,
477
+ 0.0,
478
+ -2.5302018e-14,
479
+ -2.5302018e-14,
480
+ -2.5302018e-14,
481
+ -2.5302018e-14,
482
+ 1.1234251e-05,
483
+ 1.0832736e-05,
484
+ -0.00048545605,
485
+ 1.5486969e-05,
486
+ -2.5418809e-17,
487
+ -2.5418809e-17,
488
+ -2.5418809e-17,
489
+ -2.5418809e-17,
490
+ 0.002626635,
491
+ 0.002626792,
492
+ 0.0027120241,
493
+ 0.0021979488,
494
+ -0.0399116,
495
+ -0.03991316,
496
+ -0.031362604,
497
+ -0.031362318,
498
+ -0.0021148901,
499
+ -0.002130989,
500
+ -0.0031363545,
501
+ -0.0031357573,
502
+ -0.00090792944,
503
+ -0.0009686581,
504
+ -1.6246497e-06,
505
+ -1.6584742e-06,
506
+ -6.803319e-05,
507
+ -6.932296e-05,
508
+ 1.0387723e-06,
509
+ 1.125215e-06,
510
+ 0.044976402,
511
+ 0.044976484,
512
+ 0.04762502,
513
+ 0.047625143,
514
+ ],
515
+ "ur5-wsg": [-1.5452573, -1.7434453, -1.3246999, -1.75, 1.5422482, -3.1415927, -0.055, 0.055],
516
+ "z1": [
517
+ 0.2046731,
518
+ 1.5261446,
519
+ -1.7666384,
520
+ 1.1484289,
521
+ 8.120951e-06,
522
+ -7.348934e-05,
523
+ -7.787227e-08,
524
+ 0.040000536,
525
+ 0.040000137,
526
+ ],
527
+ "ufactory_lite6": [
528
+ -0.16042127,
529
+ 0.53086734,
530
+ 2.0658371,
531
+ 0.006172284,
532
+ 0.92715985,
533
+ 1.5044298,
534
+ 3.7193262e-05,
535
+ 0.040008515,
536
+ 0.03999608,
537
+ ],
538
+ # 'ARX-X5': [-6.1558957, 0.81342375, 1.0558599, -0.937343, -3.2896776e-05, -7.4935256e-06, 0.044, 0.044],
539
+ # 'ufactory_lite6': [-0.25563017, 0.35529876, 2.0722473, 0.005538411, 0.9270778, 1.5045198, 3.138106e-05, 0.040005907, 0.03998957],
540
+ # 'franka-panda': [-0.00016283647, 0.0074461037, -0.0010076275, -1.8719686, 0.008220577, 2.018346, 0.85500133, 0.04, 0.04],
541
+ # 'aloha-agilex-1': [0.0, 0.0, -2.2630008e-14, -2.2630008e-14, -2.2630008e-14, -2.2630008e-14, 7.525569e-06, 7.171039e-06, -0.00035828358, 1.0665836e-06, -1.6544881e-17, -1.6544881e-17, -1.6544881e-17, -1.6544881e-17, 0.0017437901, 0.0017439453, 0.0018454427, 0.0014031429, -0.026461456, -0.02646318, -0.023825448, -0.023819776, -0.0014078408, -0.001425338, -0.0022293383, -0.0022303618, -0.0006110415, -0.00067730586, -9.73302e-07, -9.84728e-07, -4.5029174e-05, -4.632743e-05, 2.28171e-07, 2.6904584e-07, 0.044995338, 0.044996887, 0.04765, 0.04765],
542
+ # 'ur5-wsg-gripper': [-1.5494769, -1.5602797, -1.3733442, -1.7500004, 1.5424018, -0.000120613506, -0.055, 0.055],
543
+ # 'z1': [0.20469421, 1.5193493, -1.7742655, 1.1475929, 7.234784e-06, -5.6515753e-05, -1.4886399e-07, 0.039999034, 0.039998993],
544
+ # 'piper': [-0.23096707, 1.2409755, -1.4549325, 0.10388685, 1.2199999, 0.000500452, 0.039999936, 0.03997564],
545
+ # 'ur5-wsg-gripper': [-1.57, -0.78, -1.33, -1.70, 1.56, 3.14, 0, 0],
546
+ # 'franka-panda': [-2.89, 1.03, 2.89, -1.93, -0.21, 1.27, 0.78, 0, 0],
547
+ }
548
+
549
+ pose_dict = {
550
+ "ARX-X5": sapien.Pose([-0.821443, -1.6714, 0.781873], [0.999601, 5.86649e-08, -7.04128e-07, -0.0282362]),
551
+ "piper": sapien.Pose([0.846021, -1.70083, 0.731933], [-0.0329616, 4.47035e-08, -1.49012e-08, 0.999457]),
552
+ "franka-panda": sapien.Pose(
553
+ [0.880834, -2.30439, 0.75],
554
+ [0.4564, 4.47035e-08, -1.16415e-10, 0.889775],
555
+ ),
556
+ "aloha-agilex": sapien.Pose(
557
+ [1.75423e-08, -2.39183, 0.465],
558
+ [0.709881, 8.9407e-08, -4.74683e-08, 0.704321],
559
+ ),
560
+ "ur5-wsg": sapien.Pose(
561
+ [-0.907954, -2.31459, 0.77098],
562
+ [0.956935, -2.55658e-08, -1.0741e-07, -0.290302],
563
+ ),
564
+ # "z1": sapien.Pose(
565
+ # [-1.08728, -1.74981, 0.743286],
566
+ # [0.999384, -5.50994e-07, 4.56203e-09, 0.035102],
567
+ # ),
568
+ # "ufactory_lite6": sapien.Pose([-1.14082, -1.26895, 0.654833], [1, 0, 0, 8.66251e-07]),
569
+ # 'ARX-X5': sapien.Pose([0.97715, -1.28326, 0.783988], [-9.09963e-07, 6.85768e-07, 9.68444e-08, 1]),
570
+ # 'ufactory_lite6': sapien.Pose([1.11059, -1.72772, 0.654833], [-9.09963e-07, 0, 0, 1]),
571
+ # 'franka-panda': sapien.Pose([0.880834, -2.30439, 0.75], [0.4564, 4.47035e-08, -1.16415e-10, 0.889775]),
572
+ # 'aloha-agilex-1': sapien.Pose([8.77117e-09, -2.39183, 0.315], [0.709881, 8.9407e-08, -4.74683e-08, 0.704321]),
573
+ # 'ur5-wsg-gripper': sapien.Pose([-0.907954, -2.31459, 0.77098], [0.956935, -2.55658e-08, -1.0741e-07, -0.290302]),
574
+ # 'z1': sapien.Pose([-1.08728, -1.74981, 0.743286], [0.999384, -5.50994e-07, 8.28732e-09, 0.035102]),
575
+ # 'piper': sapien.Pose([-1.02042, -1.22711, 0.731933], [1, 0, 0, 0]),
576
+ # 'piper': sapien.Pose([-1.08728, -1.28692, 0.743286], [-0.99999, 5.36442e-07, 4.47035e-08, -0.00445333]),
577
+ # 'ur5-wsg-gripper': sapien.Pose([1.11433, -2.06679, 0.75], [0.935868, 3.53431e-08, -1.04601e-07, 0.35235]),
578
+ # 'z1': sapien.Pose([-1.08376, -0.879804, 0.75], [0.999983, 8.50705e-08, -2.12434e-07, 0.00582502]),
579
+ # 'ufactory_lite6': sapien.Pose([1.10847, -0.967647, 0.6], [0.0313626, 0, 0, 0.999508]),
580
+ # 'ARX-X5': sapien.Pose([1.072, -1.29, 0.783988], [0.0159038, 6.87222e-07, 8.59252e-08, 0.999874]),
581
+ # 'franka-wsg': sapien.Pose([0.622937, -2.38999, 0.750243], [0.710587, 9.08971e-07, 9.36911e-07, 0.703609]),
582
+ # 'ur5-robotic85-gripper': sapien.Pose([-1.38769, -1.8014, 0.75], [-0.879306, 5.93055e-08, 8.07258e-08, 0.476258]),
583
+ # 'RM65B-EG24C2': sapien.Pose([1.02471, -1.10745, 0.85], [0.999792, 3.72529e-08, 2.26079e-07, -0.0204]),
584
+ # 'ufactory_xarm7': sapien.Pose([-1.09916, -1.35288, 0.72], [0.998108, -4.47035e-08, -2.98023e-08, 0.0614921]),
585
+ # 'piper': sapien.Pose([-1.08728, -0.786483, 0.743286], [0.99999, -2.98023e-08, 7.45058e-08, 0.00445369]),
586
+ # 'z1': sapien.Pose([-1.08376, -0.536377, 0.75], [0.999983, 8.58563e-08, -2.12394e-07, 0.00582501]),
587
+ # 'ufactory_lite6': sapien.Pose([1.10847, -0.601613, 0.6], [0.0313626, 0, 0, 0.999508]),
588
+ # 'ARX-X5': sapien.Pose([1.072, -0.884706, 0.783988], [0.0159033, 6.87222e-07, 8.59257e-08, 0.999874]),
589
+ # 'kinova': sapien.Pose([-1.29571, -1.1639, 0.618725], [0.999138, -2.0683e-06, 0.000454868, 0.0415031]),
590
+ # 'rethink_robotics_sawyer': sapien.Pose([1.40007, -1.41166, 0.7], [0.0748435, -7.82311e-08, -4.47035e-08, 0.997195]),
591
+ }
592
+ name_list = list(pose_dict.keys())
593
+
594
+ for robot in emb.iterdir():
595
+ if not robot.is_dir():
596
+ continue
597
+ cfg_path = robot / "config.yml"
598
+ if robot.name not in name_list:
599
+ continue
600
+ if not cfg_path.exists():
601
+ continue
602
+
603
+ cfg = yaml.load(open(cfg_path, "r", encoding="utf-8"), Loader=yaml.FullLoader)
604
+ urdf_path = robot / cfg["urdf_path"]
605
+ loader: sapien.URDFLoader = self.scene.create_urdf_loader()
606
+ loader.fix_root_link = True
607
+ entity: sapien.physx.PhysxArticulation = loader.load(str(urdf_path))
608
+ entity.set_name(robot.name)
609
+ print(f"load {robot.name} from {urdf_path}")
610
+ # x = 0.1 - radius * np.cos(np.pi/12+(np.pi*5/6)/max_count*count)
611
+ # entity.set_pose(sapien.Pose([
612
+ # x,
613
+ # -radius * np.sin(np.pi/12+(np.pi*5/6)/max_count*count),
614
+ # cfg['robot_pose'][0][2]
615
+ # ], t3d.quaternions.axangle2quat([0, 0, 1], np.pi/max_count*count)
616
+ # ))
617
+ cfg["joints"] = [joint_dict[robot.name]]
618
+ entity.set_pose(pose_dict[robot.name])
619
+ init_joints(entity, cfg)
620
+ count += 1
621
+
622
+ def block(self):
623
+ if self.viewer is None:
624
+ return
625
+ while True:
626
+ self.scene.step()
627
+ self.scene.update_render()
628
+ self.viewer.render()
629
+
630
+ def run(self, step=200, no_step=False):
631
+ if no_step:
632
+ self.scene.update_render()
633
+ if self.viewer is not None:
634
+ self.viewer.render()
635
+ return
636
+ for _ in tqdm(range(step), desc="running"):
637
+ if not no_step:
638
+ self.scene.step()
639
+ self.scene.update_render()
640
+ if self.viewer is not None:
641
+ self.viewer.render()
642
+
643
+ def take_picture(self, name="camera.png"):
644
+ print("start taking picture")
645
+ self.camera.take_picture()
646
+ camera_rgba = self.camera.get_picture("Color")
647
+ position = self.camera.get_picture("Position")
648
+ depth = -position[..., 2]
649
+
650
+ camera_rgba_img = (camera_rgba * 255).clip(0, 255).astype("uint8")[:, :, :3]
651
+ camera_rgba_img = Image.fromarray(camera_rgba_img)
652
+ camera_rgba_img.save(name)
653
+ np.save("depth_data.npy", depth)
654
+ print("picture saved:", name)
655
+
656
+ def generate_in(
657
+ self,
658
+ obj_list,
659
+ x_min,
660
+ x_max,
661
+ y_min,
662
+ y_max,
663
+ z=0.74,
664
+ padding=0.05,
665
+ anno=None,
666
+ table=True,
667
+ max_z_stack=1,
668
+ logo=False,
669
+ ):
670
+ max_z_count = 0
671
+
672
+ def create_table():
673
+ nonlocal max_z_count, table
674
+ max_z_count += 1
675
+ if max_z_count > max_z_stack:
676
+ return False
677
+ if not table:
678
+ return True
679
+ builder = self.scene.create_actor_builder()
680
+ builder.set_physx_body_type("static")
681
+
682
+ length, width, thickness = x_max - x_min, y_max - y_min, 0.02
683
+ tabletop_pose = sapien.Pose([0.0, 0.0, -thickness / 2]) # Center the tabletop at z=0
684
+ tabletop_half_size = [length / 2, width / 2, thickness / 2]
685
+ builder.add_box_collision(
686
+ pose=tabletop_pose,
687
+ half_size=tabletop_half_size,
688
+ material=self.scene.default_physical_material,
689
+ )
690
+
691
+ builder.add_box_visual(
692
+ pose=tabletop_pose,
693
+ half_size=tabletop_half_size,
694
+ material=(1, 1, 1),
695
+ )
696
+ table = builder.build("table")
697
+ table.set_pose(sapien.Pose(p=[(x_min + x_max) / 2, (y_min + y_max) / 2, z], q=[0, 0, 0, 1]))
698
+ return True
699
+
700
+ def load_logo():
701
+ name = "rbt.glb"
702
+ scale = (0.6, ) * 3
703
+ builder = self.scene.create_actor_builder()
704
+ builder.set_physx_body_type("static")
705
+ builder.add_multiple_convex_collisions_from_file(filename=name, scale=scale)
706
+ builder.add_visual_from_file(filename=name, scale=scale)
707
+ mesh = builder.build(name="logo")
708
+ mesh.set_pose(sapien.Pose([0, -1.37182, 0.991556], [-4.88642e-06, 4.02623e-06, 0.348843, 0.937181]))
709
+
710
+ create_table()
711
+
712
+ if logo:
713
+ load_logo()
714
+ y_max -= 0.5
715
+
716
+ sum_x, sum_y, max_y, max_z = x_min, y_max - padding, 0, 0
717
+ batch = []
718
+ for cnt, (name, idx, mid, tagged, t, height) in enumerate(tqdm(obj_list)):
719
+ if t == "obj":
720
+ cfg = Path(f"./assets/objects/{idx}_{name}/model_data{mid}.json")
721
+ if not cfg.exists():
722
+ print(f"WARNING: {idx}_{name}/{mid} not found")
723
+ continue
724
+ with open(cfg, "r", encoding="utf-8") as f:
725
+ cfg = json.load(f)
726
+ w, h, tall = (
727
+ cfg["extents"][0] * cfg["scale"][0],
728
+ cfg["extents"][2] * cfg["scale"][2],
729
+ cfg["extents"][1] * cfg["scale"][1],
730
+ )
731
+ else:
732
+ w, h, tall, z_off = (
733
+ self.messy_item_info["radius"][f"{name}_{idx}"] * 2,
734
+ self.messy_item_info["radius"][f"{name}_{idx}"] * 2,
735
+ self.messy_item_info["z_max"][f"{name}_{idx}"] - self.messy_item_info["z_offset"][f"{name}_{idx}"],
736
+ self.messy_item_info["z_offset"][f"{name}_{idx}"],
737
+ )
738
+ if sum_y - padding - h < y_min or sum_x + padding > x_max or cnt == len(obj_list) - 1:
739
+ for x, y, zz, (n, i, m, tg, tp, h) in tqdm(batch):
740
+ if tp == "obj":
741
+ success = self.check_obj(n, i, m, pose=[x, sum_y - max_y / 2, zz], anno=anno)
742
+ else:
743
+ success = self.check_urdf(n, i, d_range=50, pose=[x, sum_y - max_y / 2, zz])
744
+ batch = []
745
+ sum_y -= max_y + padding
746
+ max_y = 0
747
+
748
+ if sum_y - padding - h < y_min:
749
+ sum_y = y_max - padding
750
+ # z += max_z + 0.01
751
+ # z += 0.3
752
+ # z -= 0.3
753
+ z -= 0.3
754
+ x_min -= 0.25
755
+ x_max += 0.25
756
+ if not create_table():
757
+ return obj_list[cnt:]
758
+ max_z = 0
759
+ sum_x = x_min
760
+
761
+ if t == "obj":
762
+ batch.append((sum_x + padding + w / 2, h, z, (name, idx, mid, tagged, t, h)))
763
+ else:
764
+ batch.append((
765
+ sum_x + padding + w / 2,
766
+ h,
767
+ z - z_off,
768
+ (name, idx, mid, tagged, t, h),
769
+ ))
770
+
771
+ sum_x += w + padding
772
+ max_y = max(max_y, h)
773
+ max_z = max(tall, max_z)
774
+ return []
775
+
776
+ def test_obj(self):
777
+ try:
778
+ self.create_scene(viewer=True)
779
+ self.rendered = True
780
+ except:
781
+ self.create_scene(viewer=False)
782
+ self.rendered = False
783
+ self.create_table_and_wall()
784
+
785
+ if self.viewer is not None:
786
+ self.viewer.set_camera_pose(self.camera.get_pose())
787
+
788
+ self.result = []
789
+ test_list_1, test_list_2 = [], []
790
+ for root_path in Path("./assets/objects").iterdir():
791
+ if not root_path.is_dir():
792
+ continue
793
+ if re.search(r"^(\d+)_(.*)$", root_path.name) is None:
794
+ continue
795
+
796
+ new_list = []
797
+ try:
798
+ idx, name = root_path.name.split("_", 1)
799
+ if name in ["dustbin", "tabletrashbin"]:
800
+ continue
801
+ collision = [i.name for i in (root_path / "collision").iterdir()]
802
+ visual = [i.name for i in (root_path / "visual").iterdir()]
803
+ config = [i.name for i in (root_path).iterdir() if i.name.endswith(".json")]
804
+ models = set(collision) & set(visual)
805
+ for model in models:
806
+ modelid = re.search(r"(\d+)", model)
807
+ minz = 999.9
808
+ if modelid is not None:
809
+ modelid = int(modelid.group(1))
810
+ cfg = Path(f"./assets/objects/{idx}_{name}/model_data{modelid}.json")
811
+ if not cfg.exists():
812
+ print(f"WARNING: {idx}_{name}/{modelid} not found")
813
+ continue
814
+ with open(cfg, "r", encoding="utf-8") as f:
815
+ cfg = json.load(f)
816
+ # cfg["scale"] = cfg.get("scale", [0.1, 0.1, 0.1])
817
+ size = np.array(cfg["extents"]) * np.array(cfg["scale"])
818
+ minz = np.exp(min(max(2*(size[0]-size[1])**2, (size[0]-size[2])**2, 2*(size[1]-size[2])**2), minz))+size[1]
819
+ new_list.append([
820
+ name,
821
+ idx,
822
+ modelid,
823
+ f"model_data{modelid}.json" in config,
824
+ "obj",
825
+ 0.0
826
+ ])
827
+ new_list.sort(key=lambda x: x[2])
828
+ for i in new_list: i[5] = minz
829
+
830
+ if name in ['sauce-can', 'french-fries', 'hamburg', 'stapler', 'tea-box', 'coffee-box', 'tissue-box', 'bread', 'toycar', 'playingcards', 'small-speaker', 'cup']:
831
+ test_list_1 += new_list
832
+ else:
833
+ test_list_2 += new_list
834
+ # test_list += new_list
835
+ except Exception as e:
836
+ print(f"WARNING: [{name}_{idx}] failed:", e)
837
+
838
+ # self.init_messy()
839
+ # for name in self.obj_names:
840
+ # for idx in self.messy_item_info["list_of_items"][name]:
841
+ # test_list_2.append((
842
+ # name,
843
+ # idx,
844
+ # "",
845
+ # "",
846
+ # "urdf",
847
+ # self.messy_item_info["z_max"][f"{name}_{idx}"],
848
+ # ))
849
+
850
+ # test_list_1.sort(key=lambda x: x[5])
851
+ # np.random.seed(42)
852
+ # np.random.shuffle(test_list_2)
853
+ # test_list_2.sort(key=lambda x: x[5][1])
854
+ # test_list_1 = test_list_1
855
+ # test_list_2 = test_list_2
856
+
857
+ # self.add_robot()
858
+ # self.run(500)
859
+ # self.block()
860
+ print(f"{len(test_list_1)=}, {len(test_list_2)=}")
861
+ # test_list_1 = test_list_1 + test_list_2
862
+ test_list_1 = test_list_1 + test_list_2
863
+ test_list_1.sort(key=lambda x: x[5])
864
+ # np.random.shuffle(test_list_1)
865
+ # test_list_1_idx = np.random.choice(np.arange(len(test_list_1)), size=250, replace=False)
866
+ # test_list_1 = [i for idx, i in enumerate(test_list_1) if idx in test_list_1_idx]
867
+ # test_list_1, test_list_2 = [], []
868
+
869
+ # self.generate_in(test_list_1, -0.5, 0.5, -2.2, -1.1, z=1.0, logo=True)
870
+ if self.rendered:
871
+ test_list_1 = test_list_1[:50]
872
+ print(test_list_1)
873
+ # res = self.generate_in(test_list_1, -1.25, 1.25, -1.8, -0.4, table=False, max_z_stack=5)
874
+ res = self.generate_in(test_list_1, -1.2, 1.2, -1.8, -0.4, table=False, max_z_stack=5)
875
+ print('rest', len(res))
876
+ # self.block()
877
+ # list_2 = self.generate_in(test_list_2, 1.7, 2.4, -3, -0.5, 0.2, max_z_stack=5)
878
+ # list_2 = self.generate_in(list_2, -2.4, -1.7, -3, -0.5, 0.2, max_z_stack=5)
879
+ # list_2 = self.generate_in(list_2, -2.4, 2.4, -4, -3.5, 0.4, max_z_stack=5)
880
+
881
+ # list_2 = self.generate_in(test_list_2[:2], 1.7, 2.4, -3, -0.5, 0.2, max_z_stack=1)
882
+ # list_2 = self.generate_in(test_list_2[:2], -2.4, -1.7, -3, -0.5, 0.2, max_z_stack=1)
883
+ # list_2 = self.generate_in(test_list_2[:2], -2.4, 2.4, -4, -3.5, 0.4, max_z_stack=1)
884
+ # self.block()
885
+ # x_max = 1
886
+ # sum_x = -x_max
887
+ # sum_y, max_y = -0.2, 0
888
+ # padding = 0.05
889
+ # for cnt, (name, idx, mid, tagged) in enumerate(tqdm(test_list_1)):
890
+ # cfg = Path(f'./assets/objects/{idx}_{name}/model_data{mid}.json')
891
+ # if not cfg.exists():
892
+ # print(f'WARNING: {idx}_{name}/{mid} not found')
893
+ # continue
894
+ # with open(cfg, 'r', encoding='utf-8') as f:
895
+ # cfg = json.load(f)
896
+ # w, h = cfg['extents'][0] * cfg['scale'][0], cfg['extents'][2] * cfg['scale'][2]
897
+ # if sum_x + padding + w > x_max:
898
+ # sum_x = -x_max
899
+ # sum_y -= max_y + padding
900
+ # max_y = 0
901
+
902
+ # success = self.check_obj(name, idx, mid, pose=[sum_x+padding+w/2, sum_y-h/2, 0.743])
903
+ # sum_x += w + padding
904
+ # max_y = max(max_y, h)
905
+
906
+ # self.result.append({
907
+ # 'name': f'{idx}_{name}',
908
+ # 'id': mid,
909
+ # 'tagged': tagged,
910
+ # 'stable': success
911
+ # })
912
+ # with open('result.jsonl', 'a', encoding='utf-8') as f:
913
+ # f.write(json.dumps(self.result[-1]) + '\n')
914
+ # with open('success.txt', 'a', encoding='utf-8') as f:
915
+ # f.write(
916
+ # f'{idx}_{name:<15}/{mid:2d} 标定:{"是" if tagged else "否"} 稳定:{"是" if success else "否"}\n')
917
+
918
+ # if cnt > 0 and cnt % 20 == 0:
919
+ # self.scene.clear()
920
+ # time.sleep(2)
921
+ # self.create_table_and_wall()
922
+ # self.block()
923
+ self.run(no_step=True)
924
+ self.take_picture('./script/camera.png')
925
+ self.block()
926
+
927
+
928
+ import os
929
+
930
+
931
+ def cpy():
932
+ models = []
933
+ with open("./success.txt", "r", encoding="utf-8") as f:
934
+ lines = [i.strip() for i in f.readlines()]
935
+ for i in lines:
936
+ i_split = i.split("_")
937
+ models.append(("_".join(i_split[:-1]), i_split[-1], i))
938
+
939
+ for name, idx, original_name in tqdm(models):
940
+ from_path = Path(f"./assets/messy_objects/{original_name}")
941
+ to_path = Path(f"./assets/messy_objects_stable/{original_name}")
942
+ os.system(f"cp -r {from_path} {to_path}")
943
+
944
+ with open("./assets/messy_objects/list.json", "r", encoding="utf-8") as f:
945
+ metadata = json.load(f)
946
+
947
+ list_of_items = {}
948
+ for name, idx, original_name in models:
949
+ if name not in list_of_items:
950
+ list_of_items[name] = []
951
+ list_of_items[name].append(idx)
952
+
953
+ new_metadata = {
954
+ "item_names": list(set([n[0] for n in models])),
955
+ "list_of_items": list_of_items,
956
+ "radius": {
957
+ n[2]: metadata["radius"][n[2]]
958
+ for n in models
959
+ },
960
+ "z_offset": {
961
+ n[2]: metadata["z_offset"][n[2]]
962
+ for n in models
963
+ },
964
+ "z_max": {
965
+ n[2]: metadata["z_max"][n[2]]
966
+ for n in models
967
+ },
968
+ }
969
+
970
+ with open("./assets/messy_objects_stable/list.json", "w", encoding="utf-8") as f:
971
+ json.dump(new_metadata, f, ensure_ascii=False, indent=4)
972
+
973
+
974
+ def cfg():
975
+ result = []
976
+ with open("result.jsonl", "r", encoding="utf-8") as f:
977
+ for i in f.readlines():
978
+ result.append(json.loads(i.strip()))
979
+ root_path = Path("./assets/objects")
980
+ for res in result:
981
+ res_cfg = root_path / res["name"] / f'model_data{res["id"]}.json'
982
+ if res_cfg.exists():
983
+ with open(res_cfg, "r", encoding="utf-8") as f:
984
+ cfg = json.load(f)
985
+ cfg["stable"] = res["stable"]
986
+ with open(res_cfg, "w", encoding="utf-8") as f:
987
+ json.dump(cfg, f, ensure_ascii=False, indent=4)
988
+ else:
989
+ print(f'WARNING: {res["name"]}/{res["id"]} not found')
990
+
991
+ if __name__ == "__main__":
992
+ helper = Helper()
993
+ helper.test_obj()
994
+ # cpy()
995
+ # cfg()
996
+ # pass
997
+
998
+ # all_items = [
999
+ # "bottle", "bowl", "brush", "can", "chip_can", "clock", "drinkbox", "hammer", "marker", "notebook", "pencil", "plate", "pot", "ramen_box", "remote", "slipper", "snack_box", "snack_package", "sneaker", "spoon", "steel_tape", "tape", "thermos", "tissue", "toothbrush", "toy_car", "wallet",
1000
+
1001
+ # "001_bottle", "002_bowl", "003_plate", "004_fluted-block", "007_shoe_box", "019_coaster", "020_hammer", "021_cup", "022_cup-with-liquid", "027_table-tennis", "028_dustpan", "030_drill", "032_screwdriver", "033_fork", "034_knife", "035_apple", "036_cabinet", "037_box", "039_mug", "040_rack", "041_shoe", "042_wooden_box", "043_book", "045_sand-clock", "046_alarm-clock", "047_mouse", "048_stapler", "049_shampoo", "050_bell", "051_candlestick", "052_dumbbell", "053_teanet", "054_baguette", "055_small-speaker", "057_toycars", "058_markpen", "059_pencup", "061_battery", "062_plasticbox", "063_tabletrashbin", "068_boxdrink", "069_vagetables", "070_paymentsign", "071_cans", "072_electronicscale", "073_rubikscube", "074_displaystand", "075_bread", "076_breadbasket", "077_phone", "078_phonestand", "079_remotecontrol", "080_pillbottle", "081_playingcards", "082_smallshovel", "083_brush", "084_woodenmallet", "085_gong", "086_woodenblock", "087_waterer", "088_wineglass", "089_globe", "090_trophy", "091_kettle", "092_notebook", "093_brush-pen", "094_rest", "095_glue", "096_cleaner", "097_screen", "098_speaker", "099_fan", "100_seal", "101_milk-tea", "103_fruits", "104_board", "105_sauce-can", "106_skillet", "108_block", "110_basket", "111_callbell", "112_tea-box", "113_coffee-box", "109_hydrating-oil", "107_soap", "102_roller", "067_steamer", "066_vinegar", "065_soy-sauce", "064_msg", "060_kitchenpot", "056_switch", "044_microwave", "038_milk-box", "031_jam-jar", "029_olive-oil", "028_roll-paper", "026_pet-collar", "025_chips-tub", "024_scanner", "023_tissue-box", "018_microphone", "017_calculator", "016_oven", "015_laptop", "014_bookcase", "013_dumbbell-rack", "012_plant-pot", "011_dustbin", "010_pen", "009_kettle", "008_tray", "006_hamburg", "005_french-fries"
1002
+ # ]
1003
+
1004
+ # # # Stricter groups based on high visual/shape similarity
1005
+ # strict_groups = [
1006
+ # # Groups from the user's example
1007
+ # ["plate", "003_plate"],
1008
+ # ["toy_car", "057_toycars"],
1009
+ # ["remote", "079_remotecontrol"],
1010
+ # ["marker", "058_markpen", "pencil"],
1011
+ # ["can", "071_cans"],
1012
+ # ["mug", "039_mug"],
1013
+
1014
+ # # Additional groups based on clear, direct similarities,
1015
+ # # trying to match the style and granularity of the examples.
1016
+
1017
+ # # Direct L1 to L2 counterparts or very similar items
1018
+ # ["bottle", "001_bottle"],
1019
+ # ["bowl", "002_bowl"],
1020
+ # ["brush", "083_brush"],
1021
+ # ["clock", "046_alarm-clock"], # "alarm-clock" is a type of clock
1022
+ # ["hammer", "020_hammer"],
1023
+ # ["notebook", "092_notebook"], # L1 "notebook" matches L2 "notebook"
1024
+ # ["pot", "060_kitchenpot"], # "kitchenpot" is a type of pot
1025
+ # ["tissue", "023_tissue-box"], # "tissue" and "tissue-box" are directly related
1026
+
1027
+ # # Small groups of highly similar items from L1 and/or L2
1028
+ # ["chip_can", "025_chips-tub"], # Both are tube-shaped snack containers
1029
+ # ["slipper", "sneaker", "041_shoe"], # All are types of footwear
1030
+ # ["spoon", "033_fork", "034_knife"], # Cutlery items
1031
+ # ["steel_tape", "tape"], # Types of tape
1032
+ # ["drinkbox", "068_boxdrink"], # Drinks in boxes
1033
+ # ["091_kettle", "009_kettle"], # Both are kettles
1034
+ # ["055_small-speaker", "098_speaker"], # Types of speakers
1035
+ # ["035_apple", "103_fruits"], # Fruits
1036
+ # ["054_baguette", "075_bread"], # Types of bread
1037
+ # ["050_bell", "111_callbell"], # Types of bells
1038
+ # ["004_fluted-block", "086_woodenblock", "108_block"], # Types of blocks
1039
+
1040
+ # # Grouping L2 items that are similar concepts, or direct matches not yet covered
1041
+ # ["021_cup", "022_cup-with-liquid"], # Cups
1042
+ # ["112_tea-box", "113_coffee-box"], # Specific types of boxes
1043
+ # ["037_box", "042_wooden_box", "062_plasticbox", "007_shoe_box"], # General boxes
1044
+
1045
+ # ["019_coaster", "008_tray"],
1046
+ # ["036_cabinet", "040_rack", "014_bookcase", "013_dumbbell-rack"], # Furniture/storage units
1047
+ # ["063_tabletrashbin", "011_dustbin"], # Trash receptacles
1048
+ # ["074_displaystand", "078_phonestand"],
1049
+ # ["110_basket", "076_breadbasket"],
1050
+ # ]
1051
+
1052
+ # similar_items_dict = {item: set() for item in all_items}
1053
+
1054
+ # for group in strict_groups:
1055
+ # # Ensure all items in defined groups are known (they should be from all_items)
1056
+ # for item_in_group in group:
1057
+ # if item_in_group not in similar_items_dict:
1058
+ # # This case should ideally not happen if groups only contain items from all_items
1059
+ # print(f"Warning: Item '{item_in_group}' in a group is not in the master list of all_items.")
1060
+ # continue # Skip if item not in master list, or handle as error
1061
+
1062
+ # for item_in_group in group:
1063
+ # if item_in_group in similar_items_dict: # Process only if item is in master list
1064
+ # # Add all other items from this specific group as similar
1065
+ # for other_item_in_group in group:
1066
+ # if item_in_group != other_item_in_group:
1067
+ # similar_items_dict[item_in_group].add(other_item_in_group)
1068
+
1069
+ # # Convert sets to sorted lists for consistent output
1070
+ # final_strict_dict = {item: sorted(list(similar_set)) for item, similar_set in similar_items_dict.items()}
1071
+
1072
+ # # Example of how to print the resulting dictionary (optional)
1073
+ # # import json
1074
+ # # print(json.dumps(final_strict_dict, indent=2))
1075
+
1076
+ # # To display the dictionary (optional, for verification)
1077
+ # import json
1078
+ # json.dump(final_strict_dict, open('similar_items.json', 'w'), indent=4)
script/create_object_data.py ADDED
@@ -0,0 +1,1093 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import argparse
3
+ import readline
4
+ import importlib
5
+ import numpy as np
6
+ from pathlib import Path
7
+ from copy import deepcopy
8
+ import transforms3d as t3d
9
+ from threading import Thread, Lock
10
+ import trimesh
11
+ import trimesh.bounds
12
+
13
+ import sys
14
+
15
+ sys.path.append(".")
16
+ from envs.utils import *
17
+
18
+ import sapien
19
+ from sapien.render import set_global_config
20
+
21
+ render_pause = False
22
+
23
+
24
+ class BaseViewer:
25
+ scene: sapien.Scene
26
+ viewer: sapien.utils.Viewer
27
+
28
+ actor: Actor
29
+ modelid: str
30
+ modelname: str
31
+ config_path: Path
32
+ EMPTY_CONFIG: dict
33
+ POINTS: list[tuple[str, str]]
34
+
35
+ def __init__(self):
36
+ # create scene and viewer
37
+ set_global_config(max_num_materials=50000, max_num_textures=50000)
38
+ self.scene = sapien.Scene()
39
+ self.scene.set_timestep(1 / 250)
40
+
41
+ # initialize viewer with camera position and orientation
42
+ self.viewer = None
43
+ self.reset()
44
+
45
+ def open_viewer(self):
46
+ if self.viewer is not None and not self.viewer.closed:
47
+ return
48
+ self.viewer = self.scene.create_viewer()
49
+ self.viewer.set_scene(self.scene)
50
+ self.viewer.set_camera_pose(pose=sapien.Pose(
51
+ [-0.0096987, -0.19846, 0.0955636],
52
+ [0.71241, -0.118063, 0.123576, 0.680634],
53
+ ))
54
+
55
+ def reset(self):
56
+ self.scene.clear()
57
+ self.open_viewer()
58
+
59
+ # ground
60
+ self.scene.add_ground(0)
61
+
62
+ # lights
63
+ self.scene.set_ambient_light([0.5, 0.5, 0.5])
64
+ shadow = True
65
+ # default spotlight angle and intensity
66
+ direction_lights = [[[0, 0.5, -1], [0.5, 0.5, 0.5]]]
67
+ for direction_light in direction_lights:
68
+ self.scene.add_directional_light(direction_light[0], direction_light[1], shadow=shadow)
69
+ # default point lights position and intensity
70
+ point_lights = [[[1, 0, 1.8], [1, 1, 1]], [[-1, 0, 1.8], [1, 1, 1]]]
71
+ for point_light in point_lights:
72
+ self.scene.add_point_light(point_light[0], point_light[1], shadow=shadow)
73
+
74
+ self.update_render()
75
+
76
+ @staticmethod
77
+ def trans_mat(to_mat: np.ndarray, from_mat: np.ndarray):
78
+ to_rot = to_mat[:3, :3]
79
+ from_rot = from_mat[:3, :3]
80
+ rot_mat = to_rot @ from_rot.T
81
+
82
+ trans_mat = to_mat[:3, 3] - from_mat[:3, 3]
83
+
84
+ result = np.eye(4)
85
+ result[:3, :3] = rot_mat
86
+ result[:3, 3] = trans_mat
87
+ result = np.where(np.abs(result) < 1e-5, 0, result)
88
+ return result
89
+
90
+ @staticmethod
91
+ def trans_base(
92
+ init_pose_mat: np.ndarray,
93
+ now_base_mat: np.ndarray,
94
+ init_base_mat: np.ndarray = np.eye(4),
95
+ ):
96
+ now_pose_mat = np.eye(4)
97
+ base_trans_mat = BaseViewer.trans_mat(now_base_mat, init_base_mat)
98
+ now_pose_mat[:3, :3] = (base_trans_mat[:3, :3] @ init_pose_mat[:3, :3] @ base_trans_mat[:3, :3].T)
99
+ now_pose_mat[:3, 3] = base_trans_mat[:3, :3] @ init_pose_mat[:3, 3]
100
+
101
+ p = now_pose_mat[:3, 3] + now_base_mat[:3, 3]
102
+ q_mat = now_pose_mat[:3, :3] @ now_base_mat[:3, :3]
103
+ return sapien.Pose(p, t3d.quaternions.mat2quat(q_mat))
104
+
105
+ def add_visual_box(self, pose: sapien.Pose, name: str = "box", type: str = "cube"):
106
+ global render_pause
107
+ modelname = {
108
+ # 'functional': 'functional.glb',
109
+ # 'contact': 'gripper.glb'
110
+ }.get(type, 'base.glb')
111
+ modelpath = Path("assets/objects/vis_box") / modelname
112
+
113
+ builder = self.scene.create_actor_builder()
114
+ builder.set_physx_body_type("static")
115
+ builder.add_visual_from_file(filename=str(modelpath))
116
+ builder.set_initial_pose(pose)
117
+ builder.set_name(name)
118
+ render_pause = True
119
+ builder.build()
120
+ render_pause = False
121
+
122
+ def clear_scene(self):
123
+ global render_pause
124
+ render_pause = True
125
+ self.scene.clear()
126
+ render_pause = False
127
+ self.update_render()
128
+
129
+ def update_render(self):
130
+ global render_pause
131
+ if not render_pause and not self.viewer.closed:
132
+ self.scene.update_render()
133
+ self.viewer.render()
134
+
135
+ def save_config(self):
136
+ with open(self.config_path, "w", encoding="utf-8") as f:
137
+ json.dump(self.actor.config, f, ensure_ascii=False, indent=4)
138
+ logging.info(f"Config saved to {self.config_path}")
139
+
140
+ def main(self, pose, modelname, modelid, inherit_config: dict = None):
141
+ ...
142
+
143
+ def load_actor(self, pose, inherit_config):
144
+ ...
145
+
146
+ def update_config(self):
147
+ ...
148
+
149
+ def visualize(self):
150
+ ...
151
+
152
+
153
+ class ObjectViewer(BaseViewer):
154
+ EMPTY_CONFIG = {
155
+ "center": [], # Center Point
156
+ "extents": [], # Bounding Box Extents
157
+ "scale": [1.0, 1.0, 1.0], # Scale
158
+ "transform_matrix": np.eye(4).tolist(), # Model to Axis Rotation Matrix, fixed as Identity Matrix
159
+
160
+ # Target Point Matrix (multiple), special points that can be obtained during planning (e.g., cup handle)
161
+ "target_pose": [],
162
+ # Grasping Point Matrix (multiple), grasping points are the positions where the robotic arm grasps the object (e.g., cup mouth)
163
+ "contact_points_pose": [],
164
+ # Functional Point Matrix (multiple), functional points are the positions where the object interacts with other objects (e.g., hammer head)
165
+ "functional_matrix": [],
166
+ # Orientation Point Matrix (single), orientation points specify the orientation of the object (e.g., shoe head facing left)
167
+ "orientation_point": [],
168
+ # Grasping Point Groups (same group should have the same position, different directions)
169
+ "contact_points_group": [],
170
+ # The number should be the same as the number of groups, should be set to true
171
+ "contact_points_mask": [],
172
+
173
+ "target_point_description": [], # Target Point Description
174
+ "contact_points_description": [], # Grasping Point Description
175
+ "functional_point_description": [], # Functional Point Description
176
+ "orientation_point_description": [], # Orientation Point Description
177
+ }
178
+ POINTS = [
179
+ ("target_pose", "target"),
180
+ ("contact_points_pose", "contact"),
181
+ ("functional_matrix", "functional"),
182
+ ("orientation_point", "orientation"),
183
+ ]
184
+
185
+ def __init__(self):
186
+ super().__init__()
187
+
188
+ def main(self, pose, modelname, modelid, inherit_config: dict = None):
189
+ global render_pause
190
+ self.modelid = modelid
191
+ self.modelname = modelname
192
+ self.reset()
193
+ self.load_actor(pose, inherit_config)
194
+ self.visualize()
195
+
196
+ self.active = True
197
+
198
+ def render():
199
+ while self.active:
200
+ self.update_render()
201
+ self.clear_scene()
202
+
203
+ self.render = Thread(target=render)
204
+ self.render.start()
205
+ self.console()
206
+ self.active = False
207
+ self.render.join()
208
+
209
+ def __del__(self):
210
+ self.active = False
211
+ if hasattr(self, 'render'):
212
+ self.render.join()
213
+ self.scene.clear()
214
+ if self.viewer is not None and not self.viewer.closed:
215
+ self.viewer.close()
216
+
217
+ def load_actor(self, pose, inherit_config=None, inherit_type: Literal['force', 'advice'] = 'advice'):
218
+ modeldir = Path("assets/objects") / self.modelname
219
+ modelid = '' if self.modelid is None else self.modelid
220
+ self.config_path = modeldir / f"model_data{modelid}.json"
221
+
222
+ # try to load as glb
223
+ collision = modeldir / "collision" / f"base{modelid}.glb"
224
+ visual = modeldir / "visual" / f"base{modelid}.glb"
225
+ if not collision.exists() or not visual.exists():
226
+ # try to load as obj
227
+ collision = modeldir / "collision" / f"textured{modelid}.obj"
228
+ visual = modeldir / "visual" / f"textured{modelid}.obj"
229
+
230
+ if not collision.exists() or not visual.exists():
231
+ logging.error(
232
+ f"Model files not found in {modeldir}({modelid}): "
233
+ f"collision {collision.exists()}, visual {visual.exists()}"
234
+ )
235
+ return False
236
+
237
+ if self.config_path.exists():
238
+ try:
239
+ actor_config = json.load(open(self.config_path, "r", encoding="utf-8"))
240
+ if len(actor_config['orientation_point']) > 1:
241
+ actor_config['orientation_point'] = [actor_config['orientation_point']]
242
+ except json.JSONDecodeError:
243
+ logging.warning(f"Invalid JSON in {self.config_path}, using empty config.")
244
+ actor_config = None
245
+ else:
246
+ actor_config = None
247
+
248
+ if actor_config is None:
249
+ if inherit_config is None:
250
+ actor_config = deepcopy(self.EMPTY_CONFIG)
251
+ else:
252
+ actor_config = deepcopy(inherit_config)
253
+ else:
254
+ if inherit_config is not None and inherit_type == 'force':
255
+ actor_config = deepcopy(inherit_config)
256
+ else:
257
+ actor_config = actor_config
258
+ actor_config.update(self.get_shape_data(collision))
259
+
260
+ scale = actor_config['scale']
261
+ builder = self.scene.create_actor_builder()
262
+ builder.set_physx_body_type("dynamic")
263
+ builder.add_multiple_convex_collisions_from_file(filename=str(collision), scale=scale)
264
+ builder.add_visual_from_file(filename=str(visual), scale=scale)
265
+ builder.set_initial_pose(pose)
266
+ mesh = builder.build(name=f'{self.modelname}({self.modelid})')
267
+ self.actor = Actor(mesh, actor_config)
268
+ return True
269
+
270
+ def get_shape_data(self, modelpath: Path):
271
+ with open(modelpath, "rb") as file_obj:
272
+ mesh: trimesh.Geometry = trimesh.load(
273
+ file_obj, file_type=modelpath.suffix.strip("."))
274
+
275
+ box: trimesh.primitives.Box = mesh.bounding_box_oriented
276
+ return {
277
+ "center": box.centroid.tolist(), # Center Point
278
+ "extents": box.extents.tolist(), # Bounding Box Extents
279
+ }
280
+
281
+ def visualize(self):
282
+ for key, name in self.POINTS:
283
+ for idx in range(len(self.actor.config.get(key, []))):
284
+ self.add_visual_box(pose=self.actor.get_point(name, idx, 'pose'), name=f"{name}_{idx}", type=name)
285
+ self.update_render()
286
+
287
+ def update_config(self, save: bool = False):
288
+ config = deepcopy(self.EMPTY_CONFIG)
289
+ config.update(self.actor.config)
290
+ for key, _ in self.POINTS:
291
+ config[key] = []
292
+
293
+ actor_mat = self.actor.get_pose().to_transformation_matrix()
294
+
295
+ def get_mat(entity: sapien.Entity):
296
+ nonlocal config, actor_mat
297
+ mat = entity.get_pose().to_transformation_matrix()
298
+ p = actor_mat[:3, :3].T @ (mat[:3, 3] - actor_mat[:3, 3])
299
+ mat[:3, 3] = p / config["scale"]
300
+ mat[:3, :3] = actor_mat[:3, :3].T @ mat[:3, :3]
301
+ return np.around(mat, 5)
302
+
303
+ for entity in self.scene.get_all_actors():
304
+ for key, name in self.POINTS:
305
+ if entity.get_name().startswith(name):
306
+ config[key].append(get_mat(entity).tolist())
307
+
308
+ self.actor.config = config
309
+ if save:
310
+ self.save_config()
311
+
312
+ def reset_scale(self, scale):
313
+ if len(scale) != 3:
314
+ scale = [scale[0], scale[0], scale[0]]
315
+ self.actor.config["scale"] = scale
316
+ self.update_config()
317
+ logging.info("Reloading scene, please wait for about 10 seconds...")
318
+ self.reset()
319
+ self.load_actor(self.actor.get_pose(), self.actor.config)
320
+ self.visualize()
321
+
322
+ @staticmethod
323
+ def parse_point(cmd: str, req_id: bool = True):
324
+ parse_map = {
325
+ 'c': 'contact',
326
+ 't': 'target',
327
+ 'f': 'functional',
328
+ 'o': 'orientation',
329
+ 'contact': 'contact',
330
+ 'target': 'target',
331
+ 'functional': 'functional',
332
+ 'orientation': 'orientation'
333
+ }
334
+ if cmd.strip() == '':
335
+ cmd = input(" >> (t)arget, (c)ontact, (f)unctional, (o)rientation:")
336
+ cmd = cmd.strip().split(" ")
337
+ if req_id:
338
+ try:
339
+ type, pid = parse_map[cmd[0]], int(cmd[1])
340
+ except (IndexError, ValueError, KeyError):
341
+ return None, None
342
+ return type, pid
343
+ else:
344
+ if len(cmd) != 1:
345
+ return None
346
+ return parse_map.get(cmd[0], None)
347
+
348
+ def get_points(self, type: str) -> list[sapien.Entity]:
349
+ points = []
350
+ for entity in self.scene.get_all_actors():
351
+ if entity.get_name().startswith(type):
352
+ points.append(entity)
353
+ return points
354
+
355
+ def get_next_id(self, type: str):
356
+ points = self.get_points(type)
357
+ max_id = -1
358
+ for p in points:
359
+ max_id = max(max_id, int(p.get_name().split("_")[-1]))
360
+ return max_id + 1
361
+
362
+ def console(self):
363
+ global render_pause
364
+ modified = 0
365
+ try:
366
+ while not self.viewer.closed:
367
+ cmd = input("Input command: ")
368
+ if self.viewer.closed:
369
+ logging.warning("Viewer has been closed manually.")
370
+ cmd = input("Please choose to reopen, exit with save or exit without save: (r/s/e) ")
371
+ cmd = cmd.strip().lower()
372
+ if cmd in ['r', 'reopen']:
373
+ self.open_viewer()
374
+ if cmd in ['s', 'save']:
375
+ self.update_config(True)
376
+ break
377
+ if cmd in ['e', 'exit']:
378
+ break
379
+
380
+ modified += 1
381
+ if cmd == "save":
382
+ self.update_config(True)
383
+ modified = 0
384
+ elif cmd[:6] == "resize":
385
+ """
386
+ Usage:
387
+ resize <x_size> <y_size> <z_size>: Set scaling along x, y, z axes
388
+ resize <size>: Uniformly scale all three axes
389
+ Example:
390
+ resize 0.1
391
+ """
392
+ args = cmd[7:].strip().split(" ")
393
+ if len(args) == 1:
394
+ size = float(args[0])
395
+ self.reset_scale((size, size, size))
396
+ elif len(args) == 3:
397
+ x_size = float(args[0])
398
+ y_size = float(args[1])
399
+ z_size = float(args[2])
400
+ self.reset_scale((x_size, y_size, z_size))
401
+ modified = 0
402
+ elif cmd[:6] == "create":
403
+ """
404
+ Usage:
405
+ create <type>: Create (t)arget, (c)ontact, (f)unctional, (o)rientation point
406
+ create: Waits for input of point name
407
+ Example:
408
+ create t
409
+ create f
410
+ """
411
+ type = self.parse_point(cmd[6:], req_id=False)
412
+ if type is None:
413
+ logging.warning("Invalid type.")
414
+ continue
415
+ pid = self.get_next_id(type)
416
+ if type == "orientation" and pid > 0:
417
+ logging.warning("The orientation point is unique, please modify the existing one.")
418
+ else:
419
+ self.add_visual_box(self.actor.get_pose(), name=f"{type}_{pid}", type=type)
420
+ logging.info(f"Successfully created {type}_{pid}")
421
+ elif cmd[:5] == "clone":
422
+ """
423
+ Usage:
424
+ clone <type> <id>: Clone a specified type and ID point in place
425
+ clone: Waits for input of point type and ID
426
+ Example:
427
+ clone t 1: Clones target_1 to create a new target point (e.g., target_2)
428
+ """
429
+ type, idx = self.parse_point(cmd[5:], req_id=True)
430
+ if type is None or idx is None:
431
+ logging.warning("Invalid type or id.")
432
+ continue
433
+ for entity in self.scene.get_all_actors():
434
+ if entity.get_name() == cmd and "_" in cmd:
435
+ type = cmd.split("_")[0]
436
+ if type == "orientation":
437
+ logging.warning("Orientation point is unique, cloning not supported!")
438
+ else:
439
+ pid = self.get_next_id(type)
440
+ self.add_visual_box(entity.get_pose(), name=f"{type}_{pid}", type=type)
441
+ logging.info(f"Successfully cloned {type}_{idx} to {type}_{pid}")
442
+ elif cmd[:6] == "rotate":
443
+ """
444
+ Usage:
445
+ rotate <id> <axis> <interval>: Rotate a specified contact point around its own axis by a given interval, generating points belonging to the same group
446
+ Example:
447
+ rotate 1 x 90: Rotates contact_1 around its x-axis every 90 degrees, creating three additional contact points, and writes the group into concat_points_group
448
+ """
449
+ cmd = cmd[6:].strip().split(" ")
450
+ if len(cmd) != 3:
451
+ continue
452
+
453
+ name, axis, interval = cmd
454
+ if not name.isdigit():
455
+ logging.warning("Invalid id, must be a number.")
456
+ continue
457
+ name = int(name)
458
+
459
+ axis = {
460
+ "x": [1, 0, 0],
461
+ "y": [0, 1, 0],
462
+ "z": [0, 0, 1],
463
+ "r": [1, 0, 0],
464
+ "g": [0, 1, 0],
465
+ "b": [0, 0, 1],
466
+ }.get(axis, None)
467
+ if axis is None:
468
+ continue
469
+ axis = np.array(axis)
470
+
471
+ interval = int(interval)
472
+ for entity in self.scene.get_all_actors():
473
+ if entity.get_name() == f"contact_{name}":
474
+ pos_mat = entity.get_pose().to_transformation_matrix()
475
+ group_list = [name]
476
+ for i in range(interval, 360, interval):
477
+ pid = self.get_next_id("contact")
478
+ new_mat = np.eye(4)
479
+ new_mat[:3, 3] = pos_mat[:3, 3]
480
+
481
+ new_rot = axis * np.radians(i)
482
+ rot_mat = t3d.euler.euler2mat(new_rot[0], new_rot[1], new_rot[2])
483
+ new_mat[:3, :3] = pos_mat[:3, :3] @ rot_mat
484
+
485
+ pose = sapien.Pose(
486
+ new_mat[:3, 3],
487
+ t3d.quaternions.mat2quat(new_mat[:3, :3]),
488
+ )
489
+ self.add_visual_box(pose, name=f"contact_{pid}", type="contact")
490
+ group_list.append(pid)
491
+ self.actor.config["contact_points_group"].append(group_list)
492
+ self.actor.config["contact_points_mask"].append(True)
493
+ logging.info(f"Successfully rotated contact_{name} group, created {len(group_list)} points")
494
+ break
495
+ elif cmd[:5] == "align":
496
+ """
497
+ Usage:
498
+ align: Aligns all group points' positions to the first point in the group
499
+ """
500
+ concat_points = {int(i.get_name().split("_")[-1]): i for i in self.get_points("contact")}
501
+ for group in self.actor.config["contact_points_group"]:
502
+ base = concat_points[group[0]]
503
+ base_p = base.get_pose().p
504
+ for pt in group[1:]:
505
+ concat_points[pt].set_pose(sapien.Pose(base_p, concat_points[pt].get_pose().q))
506
+ logging.info(f"Aligning group with {', '.join([str(i) for i in group[1:]])} to {group[0]}")
507
+ elif cmd[:6] == "remove":
508
+ """
509
+ Usage:
510
+ remove <type> <id>: Removes a point with the specified name
511
+ remove: Waits for input of point name
512
+ Example:
513
+ remove t 0
514
+ """
515
+ type, idx = self.parse_point(cmd[6:], req_id=True)
516
+ if type is None or idx is None:
517
+ logging.warning("Invalid type or id.")
518
+ continue
519
+
520
+ for entity in self.scene.get_all_actors():
521
+ if entity.get_name() == f'{type}_{idx}':
522
+ render_pause = True
523
+ self.scene.remove_actor(entity)
524
+ render_pause = False
525
+ logging.info(f"Successfully removed {type}_{idx}")
526
+ break
527
+ elif cmd == "exit":
528
+ if modified > 1:
529
+ cmd = input(
530
+ f'You have made {modified-1} changes without save, do you want to save them? (y/n/others to abort)'
531
+ )
532
+ if cmd.strip().lower() == 'y':
533
+ self.update_config(True)
534
+ break
535
+ elif cmd.strip().lower() == 'n':
536
+ break
537
+ else:
538
+ logging.info("Operation has been aborted.")
539
+ else:
540
+ break
541
+ else:
542
+ modified -= 1
543
+ except KeyboardInterrupt:
544
+ pass
545
+
546
+
547
+ class URDFViewer(BaseViewer):
548
+ EMPTY_CONFIG = {
549
+ "scale": 1.0, # Scale
550
+ "transform_matrix": np.eye(4).tolist(),
551
+ # Expected loading position to model actual pose transformation matrix, for example:
552
+ # transform_matrix @ cube's bottom center point pose = cube pose
553
+ "init_qpos": [], # Initial joint state
554
+ # Marker point matrix (multiple), marker points are special points that can be accessed during planning (e.g., cup handle)
555
+ "target_points": [],
556
+ # Grasping point matrix (multiple), grasping points are the positions where the robotic arm grasps the object (e.g., cup mouth)
557
+ "contact_points": [],
558
+ # Functional point matrix (multiple), functional points are the positions where the object interacts with other objects (e.g., hammer head)
559
+ "functional_points": [],
560
+ # Orientation point matrix (single), orientation points specify the orientation of the object (e.g., shoe head facing left)
561
+ "orientation_point": [],
562
+ # Grasping point groups (same group should have the same position, different directions)
563
+ "contact_points_group": [],
564
+ # The number should be the same as the number of groups, should be set to true
565
+ "contact_points_mask": [],
566
+
567
+ "target_points_description": [], # Marker point description
568
+ "contact_points_description": [], # Grasping point description
569
+ "functional_points_description": [], # Functional point description
570
+ "orientation_point_description": [], # Orientation point description
571
+ }
572
+ """
573
+ For each point:
574
+ {
575
+ "matrix": np.eye(4) # 4x4 transformation matrix
576
+ "base" : "base_name" # Base link name
577
+ }
578
+ """
579
+ POINTS = [
580
+ ("target_points", "target"),
581
+ ("contact_points", "contact"),
582
+ ("functional_points", "functional"),
583
+ ("orientation_point", "orientation"),
584
+ ]
585
+
586
+ def __init__(self):
587
+ super().__init__()
588
+
589
+ def main(self, pose, modelname, modelid, inherit_config: dict = None):
590
+ self.modelid = modelid
591
+ self.modelname = modelname
592
+ self.reset()
593
+ self.load_actor(pose, inherit_config)
594
+ self.visualize()
595
+
596
+ self.active = True
597
+
598
+ def render():
599
+ while self.active and not self.viewer.closed:
600
+ self.update_render()
601
+ self.clear_scene()
602
+
603
+ self.render = Thread(target=render)
604
+ self.render.start()
605
+ self.console()
606
+ self.active = False
607
+ self.render.join()
608
+
609
+ def __del__(self):
610
+ self.active = False
611
+ if hasattr(self, 'render'):
612
+ self.render.join()
613
+ self.scene.clear()
614
+ if self.viewer is not None and not self.viewer.closed:
615
+ self.viewer.close()
616
+
617
+ def load_actor(self, pose, inherit_config=None, inherit_type: Literal['force', 'advice'] = 'advice'):
618
+ modeldir = Path("assets/objects") / self.modelname / str(self.modelid)
619
+ self.config_path = modeldir / f"model_data.json"
620
+
621
+ if self.config_path.exists():
622
+ try:
623
+ actor_config = json.load(open(self.config_path, "r", encoding="utf-8"))
624
+ except json.JSONDecodeError:
625
+ logging.warning(f"Invalid JSON in {self.config_path}, using empty config.")
626
+ actor_config = None
627
+ else:
628
+ actor_config = None
629
+
630
+ if actor_config is None:
631
+ if inherit_config is None:
632
+ actor_config = deepcopy(self.EMPTY_CONFIG)
633
+ else:
634
+ actor_config = deepcopy(inherit_config)
635
+ else:
636
+ if inherit_config is not None and inherit_type == 'force':
637
+ actor_config = deepcopy(inherit_config)
638
+ else:
639
+ actor_config = actor_config
640
+
641
+ loader: sapien.URDFLoader = self.scene.create_urdf_loader()
642
+ loader.scale = actor_config["scale"]
643
+ loader.fix_root_link = False
644
+ loader.load_multiple_collisions_from_file = True
645
+ actor: sapien.physx.PhysxArticulation = loader.load_multiple(str(modeldir / "mobility.urdf"))[0][0]
646
+ actor.set_name(f"{self.modelname}({self.modelid})")
647
+ actor.set_pose(self.get_real_pose(pose, np.array(actor_config.get("transform_matrix", np.eye(4)))))
648
+
649
+ self.actor = ArticulationActor(actor, actor_config)
650
+ for joint in self.actor.actor.get_joints():
651
+ joint.set_drive_properties(
652
+ damping=1000,
653
+ stiffness=0,
654
+ )
655
+ if (self.actor.config.get("init_qpos") is not None and len(self.actor.config["init_qpos"]) > 0):
656
+ self.actor.set_qpos(np.array(self.actor.config["init_qpos"]))
657
+ return True
658
+
659
+ def get_real_pose(self, pose: sapien.Pose, trans_matrix):
660
+ pose_matrix = pose.to_transformation_matrix()
661
+ return sapien.Pose(
662
+ p=pose_matrix[:3, 3] + trans_matrix[:3, 3],
663
+ q=t3d.quaternions.mat2quat(trans_matrix[:3, :3] @ pose_matrix[:3, :3]),
664
+ )
665
+
666
+ def visualize(self):
667
+ for key, name in self.POINTS:
668
+ for idx in range(len(self.actor.config.get(key, []))):
669
+ self.add_visual_box(pose=self.actor.get_point(name, idx, 'pose'),
670
+ name=f"{name}_{idx}<{self.actor.config[key][idx]['base']}>",
671
+ type=name)
672
+ self.update_render()
673
+
674
+ def get_link(self, link_name: str):
675
+ for link in self.actor.actor.get_links():
676
+ if link.get_name() == link_name:
677
+ return link
678
+ return self.actor.actor
679
+
680
+ def get_link_dict(self):
681
+ link_dict = {}
682
+ for link in self.actor.actor.get_links():
683
+ link_dict[link.get_name()] = link
684
+ return link_dict
685
+
686
+ def get_base_name(self, point_name: str):
687
+ res = re.search(r'(.*?)<(.*?)>', point_name)
688
+ return res.group(2) if res else None
689
+
690
+ def get_id(self, point_name: str):
691
+ res = re.search(r'_(\d+)', point_name)
692
+ return int(res.group(1)) if res else None
693
+
694
+ def update_config(self, save: bool = False):
695
+ config = deepcopy(self.EMPTY_CONFIG)
696
+ config.update(self.actor.config)
697
+ for key, _ in self.POINTS:
698
+ config[key] = []
699
+
700
+ link_dict = self.get_link_dict()
701
+
702
+ def get_mat(entity: sapien.Entity, base: str):
703
+ nonlocal config, link_dict
704
+ mat = entity.get_pose().to_transformation_matrix()
705
+ base_link = link_dict.get(base, self.actor)
706
+ base_mat = base_link.get_pose().to_transformation_matrix()
707
+
708
+ p = base_mat[:3, :3].T @ (mat[:3, 3] - base_mat[:3, 3])
709
+ mat[:3, 3] = p / config["scale"]
710
+ mat[:3, :3] = base_mat[:3, :3].T @ mat[:3, :3]
711
+ return np.around(mat, 5)
712
+
713
+ for entity in self.scene.get_all_actors():
714
+ e_name = entity.get_name()
715
+ for key, name in self.POINTS:
716
+ if e_name.startswith(name):
717
+ base_name = self.get_base_name(e_name)
718
+ config[key].append({
719
+ "matrix": get_mat(entity, base_name).tolist(),
720
+ "base": base_name,
721
+ })
722
+
723
+ self.actor.config = config
724
+ if save:
725
+ self.save_config()
726
+
727
+ def reset_scale(self, scale):
728
+ if not isinstance(scale, float) \
729
+ and not isinstance(scale, int):
730
+ scale = float(scale[0])
731
+ self.actor.config["scale"] = scale
732
+ self.update_config()
733
+ logging.info("Reloading scene, please wait for about 10 seconds...")
734
+ self.reset()
735
+ self.load_actor(self.actor.get_pose(), self.actor.config)
736
+ self.visualize()
737
+
738
+ @staticmethod
739
+ def parse_point(cmd: str, req_id: bool = True):
740
+ parse_map = {
741
+ 'c': 'contact',
742
+ 't': 'target',
743
+ 'f': 'functional',
744
+ 'o': 'orientation',
745
+ 'contact': 'contact',
746
+ 'target': 'target',
747
+ 'functional': 'functional',
748
+ 'orientation': 'orientation'
749
+ }
750
+ if cmd.strip() == '':
751
+ cmd = input(" >> (t)arget, (c)ontact, (f)unctional, (o)rientation:")
752
+ cmd = cmd.strip().split(" ")
753
+
754
+ if req_id:
755
+ try:
756
+ if len(cmd) == 2:
757
+ type, pid, base = parse_map[cmd[0]], int(cmd[1]), None
758
+ else:
759
+ type, pid, base = parse_map[cmd[0]], int(cmd[1]), cmd[2]
760
+ except (IndexError, ValueError, KeyError):
761
+ return None, None, None
762
+ return type, pid, base
763
+ else:
764
+ if len(cmd) != 2:
765
+ return None, None
766
+ return parse_map.get(cmd[0], None), cmd[1]
767
+
768
+ def get_points(self, type: str) -> list[sapien.Entity]:
769
+ points = []
770
+ for entity in self.scene.get_all_actors():
771
+ if entity.get_name().startswith(type):
772
+ points.append(entity)
773
+ return points
774
+
775
+ def get_next_id(self, type: str):
776
+ points = self.get_points(type)
777
+ max_id = -1
778
+ for p in points:
779
+ res = re.search('_(\d+)<(.*?)>', p.get_name())
780
+ max_id = max(max_id, int(res.group(1)))
781
+ return max_id + 1
782
+
783
+ def console(self):
784
+ global render_pause
785
+ modified = 0
786
+ try:
787
+ while not self.viewer.closed:
788
+ cmd = input("Input command: ")
789
+ if self.viewer.closed:
790
+ logging.warning("Viewer has been closed manually.")
791
+ cmd = input("Please choose to reopen, exit with save or exit without save: (r/s/e) ")
792
+ cmd = cmd.strip().lower()
793
+ if cmd in ['r', 'reopen']:
794
+ self.open_viewer()
795
+ if cmd in ['s', 'save']:
796
+ self.update_config(True)
797
+ break
798
+ if cmd in ['e', 'exit']:
799
+ break
800
+
801
+ modified += 1
802
+ if cmd == "save":
803
+ self.update_config(True)
804
+ modified = 0
805
+ elif cmd[:6] == "resize":
806
+ """
807
+ Usage:
808
+ resize <size>: Synchronize the scaling of all three axes of the object
809
+ Example:
810
+ resize 0.1
811
+ """
812
+ args = cmd[7:].strip().split(" ")
813
+ size = float(args[0])
814
+ self.reset_scale(size)
815
+ modified = 0
816
+ elif cmd == "run":
817
+ """
818
+ Get stable points through steps, press Ctrl+C to stop
819
+ """
820
+ try:
821
+ self.run = True
822
+ while True:
823
+ pass
824
+ except KeyboardInterrupt:
825
+ self.run = False
826
+ self.actor.config["transform_matrix"] = (
827
+ self.actor.get_pose().to_transformation_matrix().tolist())
828
+ self.actor.config["transform_matrix"][0][3] = 0
829
+ self.actor.config["transform_matrix"][1][3] = 0
830
+ self.update_config(True)
831
+ except Exception as e:
832
+ logging.warning(f"Error: {e}")
833
+ elif cmd == "qpos":
834
+ """
835
+ Get current joint state
836
+ """
837
+ qpos = self.actor.get_qpos()
838
+ self.actor.config["init_qpos"] = qpos.tolist()
839
+ self.update_config(True)
840
+ elif cmd[:4] == "mass":
841
+ '''
842
+ Set joint mass
843
+ '''
844
+ mass = cmd[5:].split(' ')
845
+ links = [(link.get_name(), link) for link in self.actor.actor.get_links()]
846
+ if len(mass) != len(links):
847
+ logging.warning(f"Mass list length({len(mass)}) does not match link count({len(links)}).")
848
+ continue
849
+ links.sort(key=lambda x: x[0])
850
+ self.actor.config['mass'] = {}
851
+ idx = 0
852
+ for name, link in links:
853
+ if name == 'base': continue
854
+ self.actor.config['mass'][name] = float(mass[idx])
855
+ idx += 1
856
+ self.save_config()
857
+ elif cmd[:6] == "create":
858
+ """
859
+ Usage:
860
+ create <type> <base_link>: Create (t)arget, (c)ontact, (f)unctional, (o)rientation points
861
+ create: Wait for point name input
862
+ Example:
863
+ create t link_1
864
+ """
865
+ type, base = self.parse_point(cmd[6:], req_id=False)
866
+ if type is None or base is None:
867
+ logging.warning("Invalid type or base.")
868
+ continue
869
+
870
+ pid = self.get_next_id(type)
871
+ if type == "orientation" and pid > 0:
872
+ logging.warning("Orientation point is unique, please modify the existing one.")
873
+ continue
874
+
875
+ base_link = self.get_link(base)
876
+ if base_link is None:
877
+ logging.warning(f"Base link '{base}' not found.")
878
+ else:
879
+ self.add_visual_box(self.actor.get_pose(), name=f"{type}_{pid}<{base}>", type=type)
880
+ logging.info(f"Successfully created {type}_{pid}")
881
+ elif cmd[:6] == "rebase":
882
+ """
883
+ Usage:
884
+ rebase <type> <id> <base_link>: Modify the base link of the specified point
885
+ Example:
886
+ rebase c 0 link1
887
+ """
888
+ type, pid, base = self.parse_point(cmd[6:], req_id=True)
889
+ if type is None or pid is None or base is None:
890
+ logging.warning("Invalid type, id or base link.")
891
+ continue
892
+
893
+ for entity in self.get_points(type):
894
+ name = entity.get_name()
895
+ if name.startswith(f"{type}_{pid}"):
896
+ new_name = f"{type}_{pid}<{base}>"
897
+ entity.set_name(new_name)
898
+ logging.info(f"Successfully rebased {name} to {new_name}")
899
+ elif cmd[:5] == "clone":
900
+ """
901
+ Usage:
902
+ clone <type> <id>: Clone a specified type and ID point in place
903
+ clone: Wait for input of point type and ID
904
+ Example:
905
+ clone t 1: Clone target_1 to create a new target point (e.g., target_2)
906
+ """
907
+ type, pid, base = self.parse_point(cmd[5:], req_id=True)
908
+ if type is None or pid is None:
909
+ logging.warning("Invalid type or id.")
910
+ continue
911
+ if type == "orientation":
912
+ logging.warning("Orientation point is unique, cloning not supported!")
913
+ continue
914
+
915
+ name = f"{type}_{pid}"
916
+ for entity in self.scene.get_all_actors():
917
+ if entity.get_name().startswith(name):
918
+ pid = self.get_next_id(type)
919
+ base = self.get_base_name(entity.get_name())
920
+ self.add_visual_box(entity.get_pose(), name=f"{type}_{pid}<{base}>", type=type)
921
+ logging.info(f"Successfully cloned {name}<{base}> to {type}_{pid}<{base}>")
922
+ elif cmd[:6] == "rotate":
923
+ """
924
+ Usage:
925
+ rotate <id> <axis> <interval>: Rotate a specified contact point around its own axis by a given interval, generating points belonging to the same group
926
+ Example:
927
+ rotate 1 x 90: Rotate contact_1 around its x-axis every 90 degrees, creating three additional contact points, and writes the group into concat_points_group
928
+ """
929
+ cmd = cmd[7:].strip().split(" ")
930
+ if len(cmd) != 3:
931
+ continue
932
+
933
+ name, axis, interval = cmd
934
+ if not name.isdigit():
935
+ logging.warning("Invalid id, must be a number.")
936
+ continue
937
+ name = int(name)
938
+
939
+ axis = {
940
+ "x": [1, 0, 0],
941
+ "y": [0, 1, 0],
942
+ "z": [0, 0, 1],
943
+ "r": [1, 0, 0],
944
+ "g": [0, 1, 0],
945
+ "b": [0, 0, 1],
946
+ }.get(axis, None)
947
+ if axis is None:
948
+ continue
949
+ axis = np.array(axis)
950
+
951
+ interval = int(interval)
952
+ for entity in self.scene.get_all_actors():
953
+ e_name = entity.get_name()
954
+ if e_name.startswith(f"contact_{name}"):
955
+ pos_mat = entity.get_pose().to_transformation_matrix()
956
+ base_name = self.get_base_name(e_name)
957
+ group_list = [name]
958
+ for i in range(interval, 360, interval):
959
+ pid = self.get_next_id("contact")
960
+ new_mat = np.eye(4)
961
+ new_mat[:3, 3] = pos_mat[:3, 3]
962
+
963
+ new_rot = axis * np.radians(i)
964
+ rot_mat = t3d.euler.euler2mat(new_rot[0], new_rot[1], new_rot[2])
965
+ new_mat[:3, :3] = pos_mat[:3, :3] @ rot_mat
966
+
967
+ pose = sapien.Pose(
968
+ new_mat[:3, 3],
969
+ t3d.quaternions.mat2quat(new_mat[:3, :3]),
970
+ )
971
+ self.add_visual_box(pose, name=f"contact_{pid}<{base_name}>", type="contact")
972
+ group_list.append(pid)
973
+ self.actor.config["contact_points_group"].append(group_list)
974
+ self.actor.config["contact_points_mask"].append(True)
975
+ logging.info(f"Successfully rotated {e_name} group, created {len(group_list)} points")
976
+ elif cmd[:5] == "align":
977
+ """
978
+ Usage:
979
+ align: Align all group points' positions to the first point in the group
980
+ """
981
+ concat_points = {self.get_id(i.get_name()): i for i in self.get_points("contact")}
982
+ for group in self.actor.config["contact_points_group"]:
983
+ base = concat_points[group[0]]
984
+ base_p = base.get_pose().p
985
+ for pt in group[1:]:
986
+ concat_points[pt].set_pose(sapien.Pose(base_p, concat_points[pt].get_pose().q))
987
+ logging.info(f"Aligning group with {', '.join([str(i) for i in group[1:]])} to {group[0]}")
988
+ elif cmd[:6] == "remove":
989
+ """
990
+ Usage:
991
+ remove <type> <id>: Remove a point with the specified name
992
+ remove: Wait for input of point name
993
+ Example:
994
+ remove t 0
995
+ """
996
+ type, idx, _ = self.parse_point(cmd[6:], req_id=True)
997
+ if type is None or idx is None:
998
+ logging.warning("Invalid type or id.")
999
+ continue
1000
+
1001
+ for entity in self.get_points(type):
1002
+ name = entity.get_name()
1003
+ if name.startswith(f"{type}_{idx}"):
1004
+ render_pause = True
1005
+ self.scene.remove_actor(entity)
1006
+ render_pause = False
1007
+ logging.info(f"Successfully removed {name}")
1008
+ break
1009
+ elif cmd == "exit":
1010
+ if modified > 1:
1011
+ cmd = input(
1012
+ f'You have made {modified-1} changes without save, do you want to save them? (y/n/others to abort)'
1013
+ )
1014
+ if cmd.strip().lower() == 'y':
1015
+ self.update_config(True)
1016
+ break
1017
+ elif cmd.strip().lower() == 'n':
1018
+ break
1019
+ else:
1020
+ logging.info("Operation has been aborted.")
1021
+ else:
1022
+ break
1023
+ else:
1024
+ modified -= 1
1025
+ if cmd != 'help':
1026
+ logging.info(f"Unknown command: {cmd}")
1027
+ help_info = ""
1028
+ except KeyboardInterrupt:
1029
+ pass
1030
+
1031
+ def auto_loader(model_name: str):
1032
+ model_dir = Path("./assets/objects/") / model_name
1033
+ collision = model_dir / "collision"
1034
+ visual = model_dir / "visual"
1035
+
1036
+ if not collision.exists():
1037
+ # URDF
1038
+ id_list = [
1039
+ int(i.name) for i in list(model_dir.iterdir()) \
1040
+ if i.is_dir() and i.name != 'visual'
1041
+ ]
1042
+ logging.info(f"<URDF> Found {len(id_list)} valid models: {id_list}")
1043
+ return URDFViewer(), id_list, sapien.Pose([0, 0, 0], [1, 0, 0, 0])
1044
+ else:
1045
+ collision_list = [
1046
+ int(re.search(r'\d+', i.name).group()) \
1047
+ for i in list(collision.iterdir()) \
1048
+ if i.suffix in ['.obj', '.glb']
1049
+ ]
1050
+ visual_list = [
1051
+ int(re.search(r'\d+', i.name).group()) \
1052
+ for i in list(visual.iterdir()) \
1053
+ if i.suffix in ['.obj', '.glb']
1054
+ ]
1055
+ id_list = list(
1056
+ set(visual_list) & set(collision_list))
1057
+ logging.info(f"<OBJECT> Found {len(id_list)} valid models: {id_list}")
1058
+ return ObjectViewer(), id_list, sapien.Pose([0, 0, 0], [0.707, 0.707, 0, 0])
1059
+
1060
+
1061
+ def main(model_name: str, start: int = 0):
1062
+ try:
1063
+ viewer, id_list, init_pose = auto_loader(model_name)
1064
+ except Exception as e:
1065
+ logging.error(f"Failed to load model {model_name}: {e}")
1066
+ return
1067
+
1068
+ for oid in id_list:
1069
+ if oid < start:
1070
+ continue
1071
+ os.environ["MODEL_NAME"] = f"{model_name}/{oid}"
1072
+ os.environ["MODEL_ID"] = "None"
1073
+
1074
+ inherit_config = None
1075
+ try:
1076
+ logging.info(f'Annotating {model_name}({oid})')
1077
+ viewer.main(
1078
+ pose=init_pose,
1079
+ modelname=f'{model_name}',
1080
+ modelid=oid,
1081
+ inherit_config=inherit_config)
1082
+ inherit_config = viewer.actor.config
1083
+ except KeyboardInterrupt:
1084
+ break
1085
+
1086
+
1087
+ if __name__ == '__main__':
1088
+ logging.basicConfig(level=logging.INFO, format='[{levelname:^8}] {message}', style="{")
1089
+ parser = argparse.ArgumentParser(description="Annotation Tool")
1090
+ parser.add_argument("model_name", type=str, help="Model Name")
1091
+ parser.add_argument("-s", "--start", type=int, default=0, help="Start ID")
1092
+ args = parser.parse_args()
1093
+ main(args.model_name, args.start)
script/eval_groot.sh ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ export XLA_PYTHON_CLIENT_MEM_FRACTION=0.4 # ensure GPU < 24G
4
+ # 禁用 CUDA,因为 GR00T client 不需要本地 GPU(推理在服务器端)
5
+
6
+ # # 简化的参数定义
7
+ # task_name=${1}
8
+ # task_config=${2}
9
+ # seed=${3}
10
+
11
+ # GR00T server 连接参数(可选,有默认值)
12
+ # GROOT_HOST=${4:-localhost} # 默认 localhost
13
+ # GROOT_PORT=${5:-8811} # 默认 8811(匹配服务端端口)
14
+
15
+ # instruction_type(可选,默认是 "unseen")
16
+ # INSTRUCTION_TYPE=${6:-unseen}
17
+
18
+ gpu_id="${GPU_ID:-0}" # 允许用环境变量 GPU_ID 覆盖
19
+ export CUDA_VISIBLE_DEVICES="${gpu_id}"
20
+ echo -e "\033[33mgpu id (to use): ${gpu_id}\033[0m"
21
+
22
+ # source .venv/bin/activate
23
+ # cd ../.. # move to root
24
+ source /mnt/workspace/users/zhangtianle/RoboTwin_utils/RoboTwin/policy/pi0/.venv/bin/activate
25
+
26
+ # source .venv/bin/activate
27
+ cd /mnt/workspace/users/zhangtianle/RoboTwin_utils/RoboTwin
28
+
29
+ which python
30
+
31
+ # 注意:GR00T client 不需要本地 GPU(推理在服务器端)
32
+
33
+ TORCH_USE_CUDA_DSA=1 CUDA_LAUNCH_BLOCKING=1 PYTHONWARNINGS=ignore::UserWarning \
34
+ python script/groot_simulation_client.py \
35
+ --task_name adjust_bottle \
36
+ --task_config demo_clean \
37
+ --seed 0 \
38
+ --host localhost \
39
+ --port 8811 \
40
+ --save_dir /mnt/workspace/users/lijiayi/GR00T_QwenVLA/outputs_robotwin/eval_result_eepose
script/eval_policy.py ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /RoboTwin/script/eval_policy.py
2
+ import sys
3
+ import os
4
+ import subprocess
5
+
6
+ sys.path.append("./")
7
+ sys.path.append(f"./policy")
8
+ sys.path.append("./description/utils")
9
+ from envs import CONFIGS_PATH
10
+ from envs.utils.create_actor import UnStableError
11
+
12
+ import numpy as np
13
+ from pathlib import Path
14
+ from collections import deque
15
+ import traceback
16
+
17
+ import yaml
18
+ from datetime import datetime
19
+ import importlib
20
+ import argparse
21
+ import pdb
22
+
23
+ from generate_episode_instructions import *
24
+
25
+ current_file_path = os.path.abspath(__file__)
26
+ parent_directory = os.path.dirname(current_file_path)
27
+
28
+
29
+ def class_decorator(task_name):
30
+ envs_module = importlib.import_module(f"envs.{task_name}")
31
+ try:
32
+ env_class = getattr(envs_module, task_name)
33
+ env_instance = env_class()
34
+ except:
35
+ raise SystemExit("No Task")
36
+ return env_instance
37
+
38
+
39
+ def eval_function_decorator(policy_name, model_name):
40
+ try:
41
+ policy_model = importlib.import_module(policy_name)
42
+ return getattr(policy_model, model_name)
43
+ except ImportError as e:
44
+ raise e
45
+
46
+ def get_camera_config(camera_type):
47
+ camera_config_path = os.path.join(parent_directory, "../task_config/_camera_config.yml")
48
+
49
+ assert os.path.isfile(camera_config_path), "task config file is missing"
50
+
51
+ with open(camera_config_path, "r", encoding="utf-8") as f:
52
+ args = yaml.load(f.read(), Loader=yaml.FullLoader)
53
+
54
+ assert camera_type in args, f"camera {camera_type} is not defined"
55
+ return args[camera_type]
56
+
57
+
58
+ def get_embodiment_config(robot_file):
59
+ robot_config_file = os.path.join(robot_file, "config.yml")
60
+ with open(robot_config_file, "r", encoding="utf-8") as f:
61
+ embodiment_args = yaml.load(f.read(), Loader=yaml.FullLoader)
62
+ return embodiment_args
63
+
64
+
65
+ def main(usr_args):
66
+ current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
67
+ task_name = usr_args["task_name"]
68
+ task_config = usr_args["task_config"]
69
+ ckpt_setting = usr_args["ckpt_setting"]
70
+ # checkpoint_num = usr_args['checkpoint_num']
71
+ policy_name = usr_args["policy_name"]
72
+ instruction_type = usr_args["instruction_type"]
73
+ save_dir = None
74
+ video_save_dir = None
75
+ video_size = None
76
+
77
+ get_model = eval_function_decorator(policy_name, "get_model")
78
+
79
+ with open(f"./task_config/{task_config}.yml", "r", encoding="utf-8") as f:
80
+ args = yaml.load(f.read(), Loader=yaml.FullLoader)
81
+
82
+ args['task_name'] = task_name
83
+ args["task_config"] = task_config
84
+ args["ckpt_setting"] = ckpt_setting
85
+
86
+ embodiment_type = args.get("embodiment")
87
+ embodiment_config_path = os.path.join(CONFIGS_PATH, "_embodiment_config.yml")
88
+
89
+ with open(embodiment_config_path, "r", encoding="utf-8") as f:
90
+ _embodiment_types = yaml.load(f.read(), Loader=yaml.FullLoader)
91
+
92
+ def get_embodiment_file(embodiment_type):
93
+ robot_file = _embodiment_types[embodiment_type]["file_path"]
94
+ if robot_file is None:
95
+ raise "No embodiment files"
96
+ return robot_file
97
+
98
+ with open(CONFIGS_PATH + "_camera_config.yml", "r", encoding="utf-8") as f:
99
+ _camera_config = yaml.load(f.read(), Loader=yaml.FullLoader)
100
+
101
+ head_camera_type = args["camera"]["head_camera_type"]
102
+ args["head_camera_h"] = _camera_config[head_camera_type]["h"]
103
+ args["head_camera_w"] = _camera_config[head_camera_type]["w"]
104
+
105
+ if len(embodiment_type) == 1:
106
+ args["left_robot_file"] = get_embodiment_file(embodiment_type[0])
107
+ args["right_robot_file"] = get_embodiment_file(embodiment_type[0])
108
+ args["dual_arm_embodied"] = True
109
+ elif len(embodiment_type) == 3:
110
+ args["left_robot_file"] = get_embodiment_file(embodiment_type[0])
111
+ args["right_robot_file"] = get_embodiment_file(embodiment_type[1])
112
+ args["embodiment_dis"] = embodiment_type[2]
113
+ args["dual_arm_embodied"] = False
114
+ else:
115
+ raise "embodiment items should be 1 or 3"
116
+
117
+ args["left_embodiment_config"] = get_embodiment_config(args["left_robot_file"])
118
+ args["right_embodiment_config"] = get_embodiment_config(args["right_robot_file"])
119
+
120
+ if len(embodiment_type) == 1:
121
+ embodiment_name = str(embodiment_type[0])
122
+ else:
123
+ embodiment_name = str(embodiment_type[0]) + "+" + str(embodiment_type[1])
124
+
125
+ save_dir = Path(f"eval_result/{task_name}/{policy_name}/{task_config}/{ckpt_setting}/{current_time}")
126
+ save_dir.mkdir(parents=True, exist_ok=True)
127
+
128
+ if args["eval_video_log"]:
129
+ video_save_dir = save_dir
130
+ camera_config = get_camera_config(args["camera"]["head_camera_type"])
131
+ video_size = str(camera_config["w"]) + "x" + str(camera_config["h"])
132
+ video_save_dir.mkdir(parents=True, exist_ok=True)
133
+ args["eval_video_save_dir"] = video_save_dir
134
+
135
+ # output camera config
136
+ print("============= Config =============\n")
137
+ print("\033[95mMessy Table:\033[0m " + str(args["domain_randomization"]["cluttered_table"]))
138
+ print("\033[95mRandom Background:\033[0m " + str(args["domain_randomization"]["random_background"]))
139
+ if args["domain_randomization"]["random_background"]:
140
+ print(" - Clean Background Rate: " + str(args["domain_randomization"]["clean_background_rate"]))
141
+ print("\033[95mRandom Light:\033[0m " + str(args["domain_randomization"]["random_light"]))
142
+ if args["domain_randomization"]["random_light"]:
143
+ print(" - Crazy Random Light Rate: " + str(args["domain_randomization"]["crazy_random_light_rate"]))
144
+ print("\033[95mRandom Table Height:\033[0m " + str(args["domain_randomization"]["random_table_height"]))
145
+ print("\033[95mRandom Head Camera Distance:\033[0m " + str(args["domain_randomization"]["random_head_camera_dis"]))
146
+
147
+ print("\033[94mHead Camera Config:\033[0m " + str(args["camera"]["head_camera_type"]) + f", " +
148
+ str(args["camera"]["collect_head_camera"]))
149
+ print("\033[94mWrist Camera Config:\033[0m " + str(args["camera"]["wrist_camera_type"]) + f", " +
150
+ str(args["camera"]["collect_wrist_camera"]))
151
+ print("\033[94mEmbodiment Config:\033[0m " + embodiment_name)
152
+ print("\n==================================")
153
+
154
+ TASK_ENV = class_decorator(args["task_name"])
155
+ args["policy_name"] = policy_name
156
+ usr_args["left_arm_dim"] = len(args["left_embodiment_config"]["arm_joints_name"][0])
157
+ usr_args["right_arm_dim"] = len(args["right_embodiment_config"]["arm_joints_name"][1])
158
+
159
+ seed = usr_args["seed"]
160
+
161
+ # Use start_seed from scheduler if provided, otherwise compute from seed
162
+ if "start_seed" in usr_args and usr_args["start_seed"] is not None:
163
+ st_seed = int(usr_args["start_seed"])
164
+ else:
165
+ st_seed = 100000 * (1 + seed)
166
+
167
+ # Use test_num from scheduler if provided, otherwise default to 100
168
+ if "test_num" in usr_args and usr_args["test_num"] is not None:
169
+ test_num = int(usr_args["test_num"])
170
+ else:
171
+ test_num = 100
172
+
173
+ suc_nums = []
174
+ topk = 1
175
+
176
+ # Write FINAL_RESULT for scheduler to parse
177
+ worker_id = usr_args.get("worker_id", 0)
178
+ num_workers = usr_args.get("num_workers", 1)
179
+
180
+ model = get_model(usr_args)
181
+ st_seed, suc_num = eval_policy(task_name,
182
+ TASK_ENV,
183
+ args,
184
+ model,
185
+ st_seed,
186
+ test_num=test_num,
187
+ video_size=video_size,
188
+ instruction_type=instruction_type)
189
+ suc_nums.append(suc_num)
190
+
191
+ # Print FINAL_RESULT for scheduler to parse
192
+ print(f"FINAL_RESULT task={task_name} success={suc_num} total={test_num} worker={worker_id}/{num_workers}")
193
+
194
+ topk_success_rate = sorted(suc_nums, reverse=True)[:topk]
195
+
196
+ file_path = os.path.join(save_dir, f"_result.txt")
197
+ with open(file_path, "w") as file:
198
+ file.write(f"Timestamp: {current_time}\n\n")
199
+ file.write(f"Instruction Type: {instruction_type}\n\n")
200
+ # file.write(str(task_reward) + '\n')
201
+ file.write("\n".join(map(str, np.array(suc_nums) / test_num)))
202
+
203
+ print(f"Data has been saved to {file_path}")
204
+ # return task_reward
205
+
206
+
207
+ def eval_policy(task_name,
208
+ TASK_ENV,
209
+ args,
210
+ model,
211
+ st_seed,
212
+ test_num=100,
213
+ video_size=None,
214
+ instruction_type=None):
215
+ print(f"\033[34mTask Name: {args['task_name']}\033[0m")
216
+ print(f"\033[34mPolicy Name: {args['policy_name']}\033[0m")
217
+
218
+ expert_check = True
219
+ TASK_ENV.suc = 0
220
+ TASK_ENV.test_num = 0
221
+
222
+ now_id = 0
223
+ succ_seed = 0
224
+ suc_test_seed_list = []
225
+
226
+ policy_name = args["policy_name"]
227
+ eval_func = eval_function_decorator(policy_name, "eval")
228
+ reset_func = eval_function_decorator(policy_name, "reset_model")
229
+
230
+ now_seed = st_seed
231
+ task_total_reward = 0
232
+ clear_cache_freq = args["clear_cache_freq"]
233
+
234
+ args["eval_mode"] = True
235
+
236
+ while succ_seed < test_num:
237
+ render_freq = args["render_freq"]
238
+ args["render_freq"] = 0
239
+
240
+ if expert_check:
241
+ try:
242
+ TASK_ENV.setup_demo(now_ep_num=now_id, seed=now_seed, is_test=True, **args)
243
+ episode_info = TASK_ENV.play_once()
244
+ TASK_ENV.close_env()
245
+ except UnStableError as e:
246
+ # print(" -------------")
247
+ # print("Error: ", e)
248
+ # print(" -------------")
249
+ TASK_ENV.close_env()
250
+ now_seed += 1
251
+ args["render_freq"] = render_freq
252
+ continue
253
+ except Exception as e:
254
+ # stack_trace = traceback.format_exc()
255
+ # print(" -------------")
256
+ # print("Error: ", e)
257
+ # print(" -------------")
258
+ TASK_ENV.close_env()
259
+ now_seed += 1
260
+ args["render_freq"] = render_freq
261
+ print("error occurs !")
262
+ continue
263
+
264
+ if (not expert_check) or (TASK_ENV.plan_success and TASK_ENV.check_success()):
265
+ succ_seed += 1
266
+ suc_test_seed_list.append(now_seed)
267
+ else:
268
+ now_seed += 1
269
+ args["render_freq"] = render_freq
270
+ continue
271
+
272
+ args["render_freq"] = render_freq
273
+
274
+ TASK_ENV.setup_demo(now_ep_num=now_id, seed=now_seed, is_test=True, **args)
275
+ episode_info_list = [episode_info["info"]]
276
+ results = generate_episode_descriptions(args["task_name"], episode_info_list, test_num)
277
+ instruction = np.random.choice(results[0][instruction_type])
278
+ TASK_ENV.set_instruction(instruction=instruction) # set language instruction
279
+
280
+ if TASK_ENV.eval_video_path is not None:
281
+ ffmpeg = subprocess.Popen(
282
+ [
283
+ "ffmpeg",
284
+ "-y",
285
+ "-loglevel",
286
+ "error",
287
+ "-f",
288
+ "rawvideo",
289
+ "-pixel_format",
290
+ "rgb24",
291
+ "-video_size",
292
+ video_size,
293
+ "-framerate",
294
+ "30",
295
+ "-i",
296
+ "-",
297
+ "-pix_fmt",
298
+ "yuv420p",
299
+ "-vcodec",
300
+ "libx264",
301
+ "-crf",
302
+ "23",
303
+ f"{TASK_ENV.eval_video_path}/episode{TASK_ENV.test_num}.mp4",
304
+ ],
305
+ stdin=subprocess.PIPE,
306
+ )
307
+ TASK_ENV._set_eval_video_ffmpeg(ffmpeg)
308
+
309
+ succ = False
310
+ reset_func(model)
311
+ while TASK_ENV.take_action_cnt < TASK_ENV.step_lim:
312
+ observation = TASK_ENV.get_obs()
313
+ eval_func(TASK_ENV, model, observation)
314
+ if TASK_ENV.eval_success:
315
+ succ = True
316
+ break
317
+ # task_total_reward += TASK_ENV.episode_score
318
+ if TASK_ENV.eval_video_path is not None:
319
+ TASK_ENV._del_eval_video_ffmpeg()
320
+
321
+ # Print final progress bar showing the step at which episode ended
322
+ _steps = TASK_ENV.take_action_cnt
323
+ _lim = TASK_ENV.step_lim
324
+ _pct = _steps / _lim
325
+ _bar_width = 30
326
+ _filled = int(_bar_width * _pct)
327
+ _bar = "#" * _filled + "-" * (_bar_width - _filled)
328
+ print(f"[{_bar}] {_steps}/{_lim} ({_pct*100:.0f}%)")
329
+
330
+ if succ:
331
+ TASK_ENV.suc += 1
332
+ print("\033[92mSuccess!\033[0m")
333
+ else:
334
+ print("\033[91mFail!\033[0m")
335
+
336
+ now_id += 1
337
+ TASK_ENV.close_env(clear_cache=((succ_seed + 1) % clear_cache_freq == 0))
338
+
339
+ if TASK_ENV.render_freq:
340
+ TASK_ENV.viewer.close()
341
+
342
+ TASK_ENV.test_num += 1
343
+
344
+ print(
345
+ f"\033[93m{task_name}\033[0m | \033[94m{args['policy_name']}\033[0m | \033[92m{args['task_config']}\033[0m | \033[91m{args['ckpt_setting']}\033[0m\n"
346
+ f"Success rate: \033[96m{TASK_ENV.suc}/{TASK_ENV.test_num}\033[0m => \033[95m{round(TASK_ENV.suc/TASK_ENV.test_num*100, 1)}%\033[0m, current seed: \033[90m{now_seed}\033[0m\n"
347
+ )
348
+ # TASK_ENV._take_picture()
349
+ now_seed += 1
350
+
351
+ return now_seed, TASK_ENV.suc
352
+
353
+
354
+ def parse_args_and_config():
355
+ parser = argparse.ArgumentParser()
356
+ parser.add_argument("--config", type=str, required=True)
357
+ parser.add_argument("--overrides", nargs=argparse.REMAINDER)
358
+ args = parser.parse_args()
359
+
360
+ with open(args.config, "r", encoding="utf-8") as f:
361
+ config = yaml.safe_load(f)
362
+
363
+ # Parse overrides
364
+ def parse_override_pairs(pairs):
365
+ override_dict = {}
366
+ for i in range(0, len(pairs), 2):
367
+ key = pairs[i].lstrip("--")
368
+ value = pairs[i + 1]
369
+ try:
370
+ value = eval(value)
371
+ except:
372
+ pass
373
+ override_dict[key] = value
374
+ return override_dict
375
+
376
+ if args.overrides:
377
+ overrides = parse_override_pairs(args.overrides)
378
+ config.update(overrides)
379
+
380
+ return config
381
+
382
+
383
+ if __name__ == "__main__":
384
+ from test_render import Sapien_TEST
385
+ Sapien_TEST()
386
+
387
+ usr_args = parse_args_and_config()
388
+
389
+ main(usr_args)
script/eval_policy_client.py ADDED
@@ -0,0 +1,535 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import os
3
+ import subprocess
4
+
5
+ sys.path.append("./")
6
+ sys.path.append(f"./policy")
7
+ sys.path.append("./description/utils")
8
+ from envs import CONFIGS_PATH
9
+ from envs.utils.create_actor import UnStableError
10
+
11
+ import numpy as np
12
+ from pathlib import Path
13
+ from collections import deque
14
+ import traceback
15
+
16
+ import yaml
17
+ from datetime import datetime
18
+ import importlib
19
+ import argparse
20
+ import pdb
21
+
22
+ from generate_episode_instructions import *
23
+
24
+
25
+ import sys
26
+ import os
27
+ import subprocess
28
+ import socket
29
+ import json
30
+ import threading
31
+ import time
32
+ import random
33
+ import traceback
34
+ import yaml
35
+ from datetime import datetime
36
+ import importlib
37
+ import argparse
38
+ from pathlib import Path
39
+ from collections import deque
40
+
41
+ import numpy as np
42
+ import json
43
+ from typing import Any
44
+
45
+ current_file_path = os.path.abspath(__file__)
46
+ parent_directory = os.path.dirname(current_file_path)
47
+
48
+ import numpy as np
49
+ import json
50
+ from typing import Any
51
+ import base64
52
+
53
+ class NumpyEncoder(json.JSONEncoder):
54
+ """Enhanced json encoder for numpy types with array reconstruction info"""
55
+ def default(self, obj):
56
+ if isinstance(obj, np.ndarray):
57
+ if obj.dtype == np.float32:
58
+ dtype = 'float32'
59
+ elif obj.dtype == np.float64:
60
+ dtype = 'float64'
61
+ elif obj.dtype == np.int32:
62
+ dtype = 'int32'
63
+ elif obj.dtype == np.int64:
64
+ dtype = 'int64'
65
+ else:
66
+ dtype = str(obj.dtype)
67
+
68
+ return {
69
+ '__numpy_array__': True,
70
+ 'data': base64.b64encode(obj.tobytes()).decode('ascii'),
71
+ 'dtype': dtype,
72
+ 'shape': obj.shape
73
+ }
74
+ elif isinstance(obj, np.integer):
75
+ return int(obj)
76
+ elif isinstance(obj, np.floating):
77
+ return float(obj)
78
+ elif isinstance(obj, np.bool_):
79
+ return bool(obj)
80
+ return super().default(obj)
81
+
82
+ def numpy_to_json(data: Any) -> str:
83
+ """Convert numpy-containing data to JSON string with reconstruction info"""
84
+ return json.dumps(data, cls=NumpyEncoder)
85
+
86
+ def json_to_numpy(json_str: str) -> Any:
87
+ """Convert JSON string back to Python objects with numpy arrays"""
88
+ def object_hook(dct):
89
+ if '__numpy_array__' in dct:
90
+ data = base64.b64decode(dct['data'])
91
+ return np.frombuffer(data, dtype=dct['dtype']).reshape(dct['shape'])
92
+ return dct
93
+
94
+ return json.loads(json_str, object_hook=object_hook)
95
+
96
+ def class_decorator(task_name):
97
+ envs_module = importlib.import_module(f"envs.{task_name}")
98
+ try:
99
+ env_class = getattr(envs_module, task_name)
100
+ env_instance = env_class()
101
+ except:
102
+ raise SystemExit("No Task")
103
+ return env_instance
104
+
105
+
106
+ def eval_function_decorator(policy_name, model_name, conda_env=None):
107
+ # conda_env is abandoned
108
+ try:
109
+ policy_model = importlib.import_module(policy_name)
110
+ return getattr(policy_model, model_name)
111
+ except ImportError as e:
112
+ raise e
113
+
114
+
115
+ def get_camera_config(camera_type):
116
+ camera_config_path = os.path.join(parent_directory, "../task_config/_camera_config.yml")
117
+
118
+ assert os.path.isfile(camera_config_path), "task config file is missing"
119
+
120
+ with open(camera_config_path, "r", encoding="utf-8") as f:
121
+ args = yaml.load(f.read(), Loader=yaml.FullLoader)
122
+
123
+ assert camera_type in args, f"camera {camera_type} is not defined"
124
+ return args[camera_type]
125
+
126
+
127
+ def get_embodiment_config(robot_file):
128
+ robot_config_file = os.path.join(robot_file, "config.yml")
129
+ with open(robot_config_file, "r", encoding="utf-8") as f:
130
+ embodiment_args = yaml.load(f.read(), Loader=yaml.FullLoader)
131
+ return embodiment_args
132
+
133
+ class ModelClient:
134
+ def __init__(self, host='localhost', port=9999, timeout=30):
135
+ self.host = host
136
+ self.port = port
137
+ self.timeout = timeout
138
+ self.sock = None
139
+ self._connect()
140
+
141
+ def _connect(self):
142
+ attempts = 0
143
+ max_attempts = 1000
144
+ retry_delay = 5
145
+
146
+ while attempts < max_attempts:
147
+ try:
148
+ self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
149
+ self.sock.settimeout(self.timeout)
150
+ self.sock.connect((self.host, self.port))
151
+ print(f"🔗 Connected to model server at {self.host}:{self.port}")
152
+ return
153
+ except Exception as e:
154
+ attempts += 1
155
+ if self.sock:
156
+ self.sock.close()
157
+ if attempts < max_attempts:
158
+ print(f"⚠️ Connection attempt {attempts} failed: {str(e)}")
159
+ print(f"🔄 Retrying in {retry_delay} seconds...")
160
+ time.sleep(retry_delay)
161
+ else:
162
+ raise ConnectionError(
163
+ f"Failed to connect to server after {max_attempts} attempts: {str(e)}"
164
+ )
165
+
166
+ def _send_recv(self, data):
167
+ """Send request and receive response with numpy array support"""
168
+ try:
169
+ # Serialize with numpy support
170
+ json_data = numpy_to_json(data).encode('utf-8')
171
+
172
+ # Send data length and data
173
+ self.sock.sendall(len(json_data).to_bytes(4, 'big'))
174
+ self.sock.sendall(json_data)
175
+
176
+ # Receive and deserialize response
177
+ response = self._recv_response()
178
+ return response
179
+
180
+ except Exception as e:
181
+ self.close()
182
+ raise ConnectionError(f"Communication error: {str(e)}")
183
+
184
+ def _recv_response(self):
185
+ """Receive response with numpy array reconstruction"""
186
+ # Read response length
187
+ len_data = self.sock.recv(4)
188
+ if not len_data:
189
+ raise ConnectionError("Connection closed by server")
190
+
191
+ size = int.from_bytes(len_data, 'big')
192
+
193
+ # Read complete response
194
+ chunks = []
195
+ received = 0
196
+ while received < size:
197
+ chunk = self.sock.recv(min(size - received, 4096))
198
+ if not chunk:
199
+ raise ConnectionError("Incomplete response received")
200
+ chunks.append(chunk)
201
+ received += len(chunk)
202
+
203
+ # Deserialize with numpy reconstruction
204
+ return json_to_numpy(b''.join(chunks).decode('utf-8'))
205
+
206
+ def call(self, func_name=None, obs=None):
207
+ response = self._send_recv({"cmd": func_name, "obs": obs})
208
+ return response['res']
209
+
210
+ def close(self):
211
+ """Close the connection"""
212
+ if self.sock:
213
+ try:
214
+ self.sock.close()
215
+ except:
216
+ pass
217
+ finally:
218
+ self.sock = None
219
+ print("🔌 Connection closed")
220
+
221
+ def __enter__(self):
222
+ return self
223
+
224
+ def __exit__(self, exc_type, exc_val, exc_tb):
225
+ self.close()
226
+
227
+
228
+ def main(usr_args):
229
+ current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
230
+ task_name = usr_args["task_name"]
231
+ task_config = usr_args["task_config"]
232
+ ckpt_setting = usr_args["ckpt_setting"]
233
+ # checkpoint_num = usr_args['checkpoint_num']
234
+ policy_name = usr_args["policy_name"]
235
+ instruction_type = usr_args["instruction_type"]
236
+ port = usr_args["port"]
237
+ save_dir = None
238
+ video_save_dir = None
239
+ video_size = None
240
+
241
+ policy_conda_env = usr_args.get("policy_conda_env", None)
242
+
243
+ get_model = eval_function_decorator(policy_name, "get_model", conda_env=policy_conda_env)
244
+
245
+ with open(f"./task_config/{task_config}.yml", "r", encoding="utf-8") as f:
246
+ args = yaml.load(f.read(), Loader=yaml.FullLoader)
247
+
248
+ args['task_name'] = task_name
249
+ args["task_config"] = task_config
250
+ args["ckpt_setting"] = ckpt_setting
251
+
252
+ embodiment_type = args.get("embodiment")
253
+ embodiment_config_path = os.path.join(CONFIGS_PATH, "_embodiment_config.yml")
254
+
255
+ with open(embodiment_config_path, "r", encoding="utf-8") as f:
256
+ _embodiment_types = yaml.load(f.read(), Loader=yaml.FullLoader)
257
+
258
+ def get_embodiment_file(embodiment_type):
259
+ robot_file = _embodiment_types[embodiment_type]["file_path"]
260
+ if robot_file is None:
261
+ raise "No embodiment files"
262
+ return robot_file
263
+
264
+ with open(CONFIGS_PATH + "_camera_config.yml", "r", encoding="utf-8") as f:
265
+ _camera_config = yaml.load(f.read(), Loader=yaml.FullLoader)
266
+
267
+ head_camera_type = args["camera"]["head_camera_type"]
268
+ args["head_camera_h"] = _camera_config[head_camera_type]["h"]
269
+ args["head_camera_w"] = _camera_config[head_camera_type]["w"]
270
+
271
+ if len(embodiment_type) == 1:
272
+ args["left_robot_file"] = get_embodiment_file(embodiment_type[0])
273
+ args["right_robot_file"] = get_embodiment_file(embodiment_type[0])
274
+ args["dual_arm_embodied"] = True
275
+ elif len(embodiment_type) == 3:
276
+ args["left_robot_file"] = get_embodiment_file(embodiment_type[0])
277
+ args["right_robot_file"] = get_embodiment_file(embodiment_type[1])
278
+ args["embodiment_dis"] = embodiment_type[2]
279
+ args["dual_arm_embodied"] = False
280
+ else:
281
+ raise "embodiment items should be 1 or 3"
282
+
283
+ args["left_embodiment_config"] = get_embodiment_config(args["left_robot_file"])
284
+ args["right_embodiment_config"] = get_embodiment_config(args["right_robot_file"])
285
+
286
+ if len(embodiment_type) == 1:
287
+ embodiment_name = str(embodiment_type[0])
288
+ else:
289
+ embodiment_name = str(embodiment_type[0]) + "+" + str(embodiment_type[1])
290
+
291
+ save_dir = Path(f"eval_result/{task_name}/{policy_name}/{task_config}/{ckpt_setting}/{current_time}")
292
+ save_dir.mkdir(parents=True, exist_ok=True)
293
+
294
+ if args["eval_video_log"]:
295
+ video_save_dir = save_dir
296
+ camera_config = get_camera_config(args["camera"]["head_camera_type"])
297
+ video_size = str(camera_config["w"]) + "x" + str(camera_config["h"])
298
+ video_save_dir.mkdir(parents=True, exist_ok=True)
299
+ args["eval_video_save_dir"] = video_save_dir
300
+
301
+ # output camera config
302
+ print("============= Config =============\n")
303
+ print("\033[95mMessy Table:\033[0m " + str(args["domain_randomization"]["cluttered_table"]))
304
+ print("\033[95mRandom Background:\033[0m " + str(args["domain_randomization"]["random_background"]))
305
+ if args["domain_randomization"]["random_background"]:
306
+ print(" - Clean Background Rate: " + str(args["domain_randomization"]["clean_background_rate"]))
307
+ print("\033[95mRandom Light:\033[0m " + str(args["domain_randomization"]["random_light"]))
308
+ if args["domain_randomization"]["random_light"]:
309
+ print(" - Crazy Random Light Rate: " + str(args["domain_randomization"]["crazy_random_light_rate"]))
310
+ print("\033[95mRandom Table Height:\033[0m " + str(args["domain_randomization"]["random_table_height"]))
311
+ print("\033[95mRandom Head Camera Distance:\033[0m " + str(args["domain_randomization"]["random_head_camera_dis"]))
312
+
313
+ print("\033[94mHead Camera Config:\033[0m " + str(args["camera"]["head_camera_type"]) + f", " +
314
+ str(args["camera"]["collect_head_camera"]))
315
+ print("\033[94mWrist Camera Config:\033[0m " + str(args["camera"]["wrist_camera_type"]) + f", " +
316
+ str(args["camera"]["collect_wrist_camera"]))
317
+ print("\033[94mEmbodiment Config:\033[0m " + embodiment_name)
318
+ print("\n==================================")
319
+
320
+ TASK_ENV = class_decorator(args["task_name"])
321
+ args["policy_name"] = policy_name
322
+ usr_args["left_arm_dim"] = len(args["left_embodiment_config"]["arm_joints_name"][0])
323
+ usr_args["right_arm_dim"] = len(args["right_embodiment_config"]["arm_joints_name"][1])
324
+
325
+ seed = usr_args["seed"]
326
+
327
+ st_seed = 100000 * (1 + seed)
328
+ suc_nums = []
329
+ test_num = 100
330
+ topk = 1
331
+
332
+ # model = get_model(usr_args)
333
+ model = ModelClient(port=port)
334
+ st_seed, suc_num = eval_policy(task_name,
335
+ TASK_ENV,
336
+ args,
337
+ model,
338
+ st_seed,
339
+ test_num=test_num,
340
+ video_size=video_size,
341
+ instruction_type=instruction_type,
342
+ policy_conda_env=policy_conda_env)
343
+ suc_nums.append(suc_num)
344
+
345
+ topk_success_rate = sorted(suc_nums, reverse=True)[:topk]
346
+
347
+ file_path = os.path.join(save_dir, f"_result.txt")
348
+ with open(file_path, "w") as file:
349
+ file.write(f"Timestamp: {current_time}\n\n")
350
+ file.write(f"Instruction Type: {instruction_type}\n\n")
351
+ # file.write(str(task_reward) + '\n')
352
+ file.write("\n".join(map(str, np.array(suc_nums) / test_num)))
353
+
354
+ print(f"Data has been saved to {file_path}")
355
+ # return task_reward
356
+
357
+
358
+ def eval_policy(task_name,
359
+ TASK_ENV,
360
+ args,
361
+ model,
362
+ st_seed,
363
+ test_num=100,
364
+ video_size=None,
365
+ instruction_type=None,
366
+ policy_conda_env=None):
367
+ print(f"\033[34mTask Name: {args['task_name']}\033[0m")
368
+ print(f"\033[34mPolicy Name: {args['policy_name']}\033[0m")
369
+
370
+ expert_check = True
371
+ TASK_ENV.suc = 0
372
+ TASK_ENV.test_num = 0
373
+
374
+ now_id = 0
375
+ succ_seed = 0
376
+ suc_test_seed_list = []
377
+
378
+ policy_name = args["policy_name"]
379
+ eval_func = eval_function_decorator(policy_name, "eval", conda_env=policy_conda_env)
380
+
381
+ now_seed = st_seed
382
+ task_total_reward = 0
383
+ clear_cache_freq = args["clear_cache_freq"]
384
+
385
+ args["eval_mode"] = True
386
+
387
+ while succ_seed < test_num:
388
+ render_freq = args["render_freq"]
389
+ args["render_freq"] = 0
390
+
391
+ if expert_check:
392
+ try:
393
+ TASK_ENV.setup_demo(now_ep_num=now_id, seed=now_seed, is_test=True, **args)
394
+ episode_info = TASK_ENV.play_once()
395
+ TASK_ENV.close_env()
396
+ except UnStableError as e:
397
+ print(" -------------")
398
+ print("Error: ", e)
399
+ print(" -------------")
400
+ TASK_ENV.close_env()
401
+ now_seed += 1
402
+ args["render_freq"] = render_freq
403
+ continue
404
+ except Exception as e:
405
+ stack_trace = traceback.format_exc()
406
+ print(" -------------")
407
+ print("Error: ", stack_trace)
408
+ print(" -------------")
409
+ TASK_ENV.close_env()
410
+ now_seed += 1
411
+ args["render_freq"] = render_freq
412
+ print("error occurs !")
413
+ continue
414
+
415
+ if (not expert_check) or (TASK_ENV.plan_success and TASK_ENV.check_success()):
416
+ succ_seed += 1
417
+ suc_test_seed_list.append(now_seed)
418
+ else:
419
+ now_seed += 1
420
+ args["render_freq"] = render_freq
421
+ continue
422
+
423
+ args["render_freq"] = render_freq
424
+
425
+ TASK_ENV.setup_demo(now_ep_num=now_id, seed=now_seed, is_test=True, **args)
426
+ episode_info_list = [episode_info["info"]]
427
+ results = generate_episode_descriptions(args["task_name"], episode_info_list, test_num)
428
+ instruction = np.random.choice(results[0][instruction_type])
429
+ TASK_ENV.set_instruction(instruction=instruction) # set language instruction
430
+
431
+ if TASK_ENV.eval_video_path is not None:
432
+ ffmpeg = subprocess.Popen(
433
+ [
434
+ "ffmpeg",
435
+ "-y",
436
+ "-loglevel",
437
+ "error",
438
+ "-f",
439
+ "rawvideo",
440
+ "-pixel_format",
441
+ "rgb24",
442
+ "-video_size",
443
+ video_size,
444
+ "-framerate",
445
+ "10",
446
+ "-i",
447
+ "-",
448
+ "-pix_fmt",
449
+ "yuv420p",
450
+ "-vcodec",
451
+ "libx264",
452
+ "-crf",
453
+ "23",
454
+ f"{TASK_ENV.eval_video_path}/episode{TASK_ENV.test_num}.mp4",
455
+ ],
456
+ stdin=subprocess.PIPE,
457
+ )
458
+ TASK_ENV._set_eval_video_ffmpeg(ffmpeg)
459
+
460
+ succ = False
461
+ model.call(func_name='reset_model')
462
+ while TASK_ENV.take_action_cnt < TASK_ENV.step_lim:
463
+ observation = TASK_ENV.get_obs()
464
+ eval_func(TASK_ENV, model, observation)
465
+ if TASK_ENV.eval_success:
466
+ succ = True
467
+ break
468
+ # task_total_reward += TASK_ENV.episode_score
469
+ if TASK_ENV.eval_video_path is not None:
470
+ TASK_ENV._del_eval_video_ffmpeg()
471
+
472
+ if succ:
473
+ TASK_ENV.suc += 1
474
+ print("\033[92mSuccess!\033[0m")
475
+ else:
476
+ print("\033[91mFail!\033[0m")
477
+
478
+ now_id += 1
479
+ TASK_ENV.close_env(clear_cache=((succ_seed + 1) % clear_cache_freq == 0))
480
+
481
+ if TASK_ENV.render_freq:
482
+ TASK_ENV.viewer.close()
483
+
484
+ TASK_ENV.test_num += 1
485
+
486
+ print(
487
+ f"\033[93m{task_name}\033[0m | \033[94m{args['policy_name']}\033[0m | \033[92m{args['task_config']}\033[0m | \033[91m{args['ckpt_setting']}\033[0m\n"
488
+ f"Success rate: \033[96m{TASK_ENV.suc}/{TASK_ENV.test_num}\033[0m => \033[95m{round(TASK_ENV.suc/TASK_ENV.test_num*100, 1)}%\033[0m, current seed: \033[90m{now_seed}\033[0m\n"
489
+ )
490
+ # TASK_ENV._take_picture()
491
+ now_seed += 1
492
+
493
+ return now_seed, TASK_ENV.suc
494
+
495
+
496
+ def parse_args_and_config():
497
+ parser = argparse.ArgumentParser()
498
+ parser.add_argument("--port", type=int)
499
+ parser.add_argument("--config", type=str, required=True)
500
+ parser.add_argument("--overrides", nargs=argparse.REMAINDER)
501
+ args = parser.parse_args()
502
+
503
+ with open(args.config, "r", encoding="utf-8") as f:
504
+ config = yaml.safe_load(f)
505
+
506
+ config['port'] = args.port
507
+
508
+ # Parse overrides
509
+ def parse_override_pairs(pairs):
510
+ override_dict = {}
511
+ for i in range(0, len(pairs), 2):
512
+ key = pairs[i].lstrip("--")
513
+ value = pairs[i + 1]
514
+ try:
515
+ value = eval(value)
516
+ except:
517
+ pass
518
+ override_dict[key] = value
519
+ return override_dict
520
+
521
+ if args.overrides:
522
+ overrides = parse_override_pairs(args.overrides)
523
+ config.update(overrides)
524
+
525
+ return config
526
+
527
+
528
+ if __name__ == "__main__":
529
+ if os.environ.get("SKIP_RENDER_TEST", "0") != "1":
530
+ from test_render import Sapien_TEST
531
+ Sapien_TEST()
532
+
533
+ usr_args = parse_args_and_config()
534
+
535
+ main(usr_args)
script/groot_simulation_client.py ADDED
@@ -0,0 +1,638 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ import sys
4
+ import os
5
+ import subprocess
6
+ import traceback
7
+ from pathlib import Path
8
+ from datetime import datetime
9
+ from collections import deque
10
+ import importlib
11
+ import argparse
12
+
13
+ import numpy as np
14
+ import yaml
15
+
16
+ import cv2
17
+
18
+
19
+ # 让 Python 能找到 RoboTwin 的包
20
+ sys.path.append("./")
21
+ sys.path.append("./policy")
22
+ sys.path.append("./description/utils")
23
+
24
+ from envs import CONFIGS_PATH
25
+ from envs.utils.create_actor import UnStableError
26
+ from generate_episode_instructions import *
27
+
28
+ # 引入你在 RoboTwin 里 cp 的 GR00T client 协议实现
29
+ from groot_client_config.service import BaseInferenceClient
30
+
31
+
32
+ # ========================= 环境与配置相关工具函数 =========================
33
+
34
+
35
+ current_file_path = os.path.abspath(__file__)
36
+ parent_directory = os.path.dirname(current_file_path)
37
+
38
+ def class_decorator(task_name):
39
+ """根据 task_name 实例化对应 env 类(沿用原 eval_policy_client 逻辑)"""
40
+ envs_module = importlib.import_module(f"envs.{task_name}")
41
+ try:
42
+ env_class = getattr(envs_module, task_name)
43
+ env_instance = env_class()
44
+ except Exception:
45
+ raise SystemExit("No Task")
46
+ return env_instance
47
+
48
+
49
+ def get_camera_config(camera_type):
50
+ """读取 task_config/_camera_config.yml 中的相机配置"""
51
+ camera_config_path = os.path.join(parent_directory, "../task_config/_camera_config.yml")
52
+
53
+ assert os.path.isfile(camera_config_path), "task config file is missing"
54
+
55
+ with open(camera_config_path, "r", encoding="utf-8") as f:
56
+ args = yaml.load(f.read(), Loader=yaml.FullLoader)
57
+
58
+ assert camera_type in args, f"camera {camera_type} is not defined"
59
+ return args[camera_type]
60
+
61
+
62
+ def get_embodiment_config(robot_file):
63
+ """读取 robot embodiment 的 config.yml"""
64
+ robot_config_file = os.path.join(robot_file, "config.yml")
65
+ with open(robot_config_file, "r", encoding="utf-8") as f:
66
+ embodiment_args = yaml.load(f.read(), Loader=yaml.FullLoader)
67
+ return embodiment_args
68
+
69
+
70
+ # ========================= 与 GR00T server 通讯的 client =========================
71
+
72
+ class GrootPolicyClient(BaseInferenceClient):
73
+ """
74
+ 用 GR00T 的 ZMQ 协议与远程 policy server 通讯的 client。
75
+
76
+ 对应 GR00T 侧的 RobotInferenceServer:
77
+ - endpoint "get_action"
78
+ - endpoint "get_modality_config"
79
+ """
80
+
81
+ def __init__(
82
+ self,
83
+ host: str = "localhost",
84
+ port: int = 5555,
85
+ api_token: str | None = None,
86
+ use_msgpack: bool = True,
87
+ ):
88
+ super().__init__(host=host, port=port, api_token=api_token, use_msgpack=use_msgpack)
89
+
90
+ def get_action(self, observations: dict) -> dict:
91
+ return self.call_endpoint("get_action", observations)
92
+
93
+ def get_modality_config(self) -> dict:
94
+ return self.call_endpoint("get_modality_config", requires_input=False)
95
+
96
+
97
+ # ========================= RoboTwin <-> GR00T 适配函数 =========================
98
+
99
+ def robottwin_obs_to_groot_obs(TASK_ENV, raw_obs: dict) -> dict:
100
+ """
101
+ 将 RoboTwin 的 TASK_ENV.get_obs() 输出转成 GR00T policy 期望的 obs 字典。
102
+ """
103
+ obs = {}
104
+ obs_dict = raw_obs.get("observation", {})
105
+
106
+ # 统一目标分辨率:与 GR00T robotwin 训练时记录的 original_resolutions 对齐
107
+ TARGET_W, TARGET_H = 640, 480 # (width, height)
108
+
109
+ # ====================== 1. 头部相机 ======================
110
+ if "head_camera" in obs_dict and "rgb" in obs_dict["head_camera"]:
111
+ head_rgb = obs_dict["head_camera"]["rgb"] # (H, W, 3),当前一般为 (240, 320, 3)
112
+
113
+ # 转为 uint8
114
+ if head_rgb.dtype != np.uint8:
115
+ head_rgb = (head_rgb * 255).clip(0, 255).astype(np.uint8)
116
+
117
+ # 如果分辨率不是 640x480,则先 resize 到 640x480
118
+ h, w = head_rgb.shape[:2]
119
+ if (w, h) != (TARGET_W, TARGET_H):
120
+ head_rgb = cv2.resize(head_rgb, (TARGET_W, TARGET_H), interpolation=cv2.INTER_LINEAR)
121
+
122
+ # 添加时间维度 T=1 -> (1, H, W, 3)
123
+ if head_rgb.ndim == 3:
124
+ head_rgb = head_rgb[None, ...]
125
+ obs["video.image_high"] = head_rgb
126
+ else:
127
+ raise KeyError(
128
+ f"head_camera.rgb not found in observation keys: {list(obs_dict.keys())}"
129
+ )
130
+
131
+ # ====================== 2. 手腕相机:兼容两种命名 ======================
132
+ # - 旧:cam_left_wrist / cam_right_wrist(离线数据)
133
+ # - 现:left_camera / right_camera(在线 RoboTwin 相机)
134
+ left_cam_key = "cam_left_wrist" if "cam_left_wrist" in obs_dict else "left_camera"
135
+ right_cam_key = "cam_right_wrist" if "cam_right_wrist" in obs_dict else "right_camera"
136
+
137
+ if left_cam_key in obs_dict and "rgb" in obs_dict[left_cam_key]:
138
+ left_rgb = obs_dict[left_cam_key]["rgb"]
139
+
140
+ if left_rgb.dtype != np.uint8:
141
+ left_rgb = (left_rgb * 255).clip(0, 255).astype(np.uint8)
142
+
143
+ h, w = left_rgb.shape[:2]
144
+ if (w, h) != (TARGET_W, TARGET_H):
145
+ left_rgb = cv2.resize(left_rgb, (TARGET_W, TARGET_H), interpolation=cv2.INTER_LINEAR)
146
+
147
+ if left_rgb.ndim == 3:
148
+ left_rgb = left_rgb[None, ...]
149
+ obs["video.image_left_wrist"] = left_rgb
150
+ else:
151
+ print(
152
+ f"[WARN] left wrist camera '{left_cam_key}' not found in observation; "
153
+ f"skip sending to GR00T."
154
+ )
155
+
156
+ if right_cam_key in obs_dict and "rgb" in obs_dict[right_cam_key]:
157
+ right_rgb = obs_dict[right_cam_key]["rgb"]
158
+
159
+ if right_rgb.dtype != np.uint8:
160
+ right_rgb = (right_rgb * 255).clip(0, 255).astype(np.uint8)
161
+
162
+ h, w = right_rgb.shape[:2]
163
+ if (w, h) != (TARGET_W, TARGET_H):
164
+ right_rgb = cv2.resize(right_rgb, (TARGET_W, TARGET_H), interpolation=cv2.INTER_LINEAR)
165
+
166
+ if right_rgb.ndim == 3:
167
+ right_rgb = right_rgb[None, ...]
168
+ obs["video.image_right_wrist"] = right_rgb
169
+ else:
170
+ print(
171
+ f"[WARN] right wrist camera '{right_cam_key}' not found in observation; "
172
+ f"skip sending to GR00T."
173
+ )
174
+
175
+ # ====================== 3. 关节状态 ======================
176
+ joint_vec = raw_obs["joint_action"]["vector"] # 例如 (14,)
177
+ obs["state.left_arm"] = joint_vec[0:6][None, ...]
178
+ obs["state.left_gripper"] = joint_vec[6:7][None, ...]
179
+ obs["state.right_arm"] = joint_vec[7:13][None, ...]
180
+ obs["state.right_gripper"] = joint_vec[13:14][None, ...]
181
+
182
+ # ====================== 4. 文本指令 ======================
183
+ if hasattr(TASK_ENV, "get_instruction"):
184
+ instruction = TASK_ENV.get_instruction()
185
+ else:
186
+ instruction = "do your thing!"
187
+ obs["annotation.human.task_description"] = [instruction]
188
+
189
+ return obs
190
+
191
+ def apply_groot_action_to_env(TASK_ENV, action_dict: dict, n_action_steps: int):
192
+ """
193
+ 将 GR00T policy 返回的 action_dict 转换为 RoboTwin env 的动作,并执行若干步。
194
+
195
+ !!! 重要:
196
+ - GR00T policy 返回的格式是字典:{"action.left_arm": (H, D1), "action.left_gripper": (H, D2), ...}
197
+ - 需要将这些动作合并成 joint vector 格式
198
+ """
199
+ # GR00T 返回的 action 格式:{"action.left_arm": (H, 6), "action.left_gripper": (H, 1), ...}
200
+ # 需要合并成完整的 joint vector: (H, 14)
201
+
202
+ if "action.left_arm" in action_dict and "action.right_arm" in action_dict:
203
+
204
+ left_arm = np.asarray(action_dict["action.left_arm"])
205
+ left_gripper = np.asarray(action_dict["action.left_gripper"])
206
+ right_arm = np.asarray(action_dict["action.right_arm"])
207
+ right_gripper = np.asarray(action_dict["action.right_gripper"])
208
+
209
+ # 新增:处理 (B,H,D) -> (H,D)(单环境 B=1)
210
+ if left_arm.ndim == 3 and left_arm.shape[0] == 1:
211
+ left_arm = left_arm[0]
212
+ if right_arm.ndim == 3 and right_arm.shape[0] == 1:
213
+ right_arm = right_arm[0]
214
+ if left_gripper.ndim == 3 and left_gripper.shape[0] == 1:
215
+ left_gripper = left_gripper[0]
216
+ if right_gripper.ndim == 3 and right_gripper.shape[0] == 1:
217
+ right_gripper = right_gripper[0]
218
+
219
+ # 保持 gripper 是 (H,1)
220
+ if left_gripper.ndim == 1:
221
+ left_gripper = left_gripper[:, None]
222
+ if right_gripper.ndim == 1:
223
+ right_gripper = right_gripper[:, None]
224
+
225
+ traj = np.concatenate([left_arm, left_gripper, right_arm, right_gripper], axis=-1) # (H,14)
226
+
227
+ H = min(n_action_steps, traj.shape[0])
228
+ for t in range(H):
229
+ action_vec = traj[t] # (14,)
230
+ TASK_ENV.take_action(action_vec)
231
+ return
232
+
233
+ elif "actions" in action_dict:
234
+ # 情况 2:如果返回的是统一的 "actions" 数组(向后兼容)
235
+ traj = np.asarray(action_dict["actions"]) # (H, D)
236
+ H = min(n_action_steps, traj.shape[0])
237
+ for t in range(H):
238
+ action_vec = traj[t]
239
+ TASK_ENV.take_action(action_vec)
240
+ return
241
+
242
+ else:
243
+ raise ValueError(f"Unknown action format: {action_dict.keys()}")
244
+
245
+
246
+ # ========================= 评测主逻辑(替代原 eval_policy_client 的 eval_policy) =========================
247
+
248
+ def eval_policy_with_groot(
249
+ task_name,
250
+ TASK_ENV,
251
+ args,
252
+ st_seed,
253
+ test_num=100,
254
+ video_size=None,
255
+ instruction_type=None,
256
+ groot_host: str = "localhost",
257
+ groot_port: int = 5555,
258
+ groot_api_token: str | None = None,
259
+ n_action_steps: int = 4,
260
+ ):
261
+ print(f"\033[34mTask Name: {args['task_name']}\033[0m")
262
+ print(f"\033[34mPolicy: GR00T Remote Policy ({groot_host}:{groot_port})\033[0m")
263
+
264
+ expert_check = True
265
+ TASK_ENV.suc = 0
266
+ TASK_ENV.test_num = 0
267
+
268
+ now_id = 0
269
+ succ_seed = 0
270
+ suc_test_seed_list = []
271
+
272
+ now_seed = st_seed
273
+ clear_cache_freq = args["clear_cache_freq"]
274
+
275
+ args["eval_mode"] = True
276
+
277
+ # 创建 GR00T 的 ZMQ 客户端
278
+ groot_client = GrootPolicyClient(
279
+ host=groot_host,
280
+ port=groot_port,
281
+ api_token=groot_api_token,
282
+ use_msgpack=True,
283
+ )
284
+
285
+ while succ_seed < test_num:
286
+ render_freq = args["render_freq"]
287
+ args["render_freq"] = 0
288
+
289
+ # ========== 1. 先跑一次 expert_check(完全复用原逻辑) ==========
290
+ if expert_check:
291
+ try:
292
+ TASK_ENV.setup_demo(now_ep_num=now_id, seed=now_seed, is_test=True, **args)
293
+ episode_info = TASK_ENV.play_once()
294
+ TASK_ENV.close_env()
295
+ except UnStableError as e:
296
+ print(" -------------")
297
+ print("Error: ", e)
298
+ print(" -------------")
299
+ TASK_ENV.close_env()
300
+ now_seed += 1
301
+ args["render_freq"] = render_freq
302
+ continue
303
+ except Exception as e:
304
+ stack_trace = traceback.format_exc()
305
+ print(" -------------")
306
+ print("Error: ", stack_trace)
307
+ print(" -------------")
308
+ TASK_ENV.close_env()
309
+ now_seed += 1
310
+ args["render_freq"] = render_freq
311
+ print("error occurs !")
312
+ continue
313
+
314
+ if (not expert_check) or (TASK_ENV.plan_success and TASK_ENV.check_success()):
315
+ succ_seed += 1
316
+ suc_test_seed_list.append(now_seed)
317
+ else:
318
+ now_seed += 1
319
+ args["render_freq"] = render_freq
320
+ continue
321
+
322
+ args["render_freq"] = render_freq
323
+
324
+ # ========== 2. 正式评测 episode:设置 demo + 指令 ==========
325
+ TASK_ENV.setup_demo(now_ep_num=now_id, seed=now_seed, is_test=True, **args)
326
+ episode_info_list = [episode_info["info"]]
327
+ results = generate_episode_descriptions(args["task_name"], episode_info_list, test_num)
328
+ instruction = np.random.choice(results[0][instruction_type])
329
+ TASK_ENV.set_instruction(instruction=instruction) # set language instruction
330
+
331
+ # ========== 3. 如果需要,打开 ffmpeg 录制 ==========
332
+ if TASK_ENV.eval_video_path is not None:
333
+ ffmpeg = subprocess.Popen(
334
+ [
335
+ "ffmpeg",
336
+ "-y",
337
+ "-loglevel",
338
+ "error",
339
+ "-f",
340
+ "rawvideo",
341
+ "-pixel_format",
342
+ "rgb24",
343
+ "-video_size",
344
+ video_size,
345
+ "-framerate",
346
+ "10",
347
+ "-i",
348
+ "-",
349
+ "-pix_fmt",
350
+ "yuv420p",
351
+ "-vcodec",
352
+ "libx264",
353
+ "-crf",
354
+ "23",
355
+ f"{TASK_ENV.eval_video_path}/episode{TASK_ENV.test_num}.mp4",
356
+ ],
357
+ stdin=subprocess.PIPE,
358
+ )
359
+ TASK_ENV._set_eval_video_ffmpeg(ffmpeg)
360
+
361
+ # ========== 4. 主循环:get_obs -> 调 GR00T get_action -> 多步执行 ==========
362
+ succ = False
363
+ first_step_of_episode = True # 用于标记是否是episode的第一步
364
+
365
+ while TASK_ENV.take_action_cnt < TASK_ENV.step_lim:
366
+ raw_obs = TASK_ENV.get_obs()
367
+ groot_obs = robottwin_obs_to_groot_obs(TASK_ENV, raw_obs)
368
+
369
+ # 第一次 rollout:强制让 server 清掉所有 env slot 的 IK 历史缓存
370
+ if first_step_of_episode:
371
+ print("[RobotwinClient] send meta.reset_mask=True", flush=True)
372
+ groot_obs["meta.reset_mask"] = True
373
+ first_step_of_episode = False
374
+
375
+ action_dict = groot_client.get_action(groot_obs)
376
+ apply_groot_action_to_env(TASK_ENV, action_dict, n_action_steps=n_action_steps)
377
+
378
+ if TASK_ENV.eval_success:
379
+ succ = True
380
+ break
381
+
382
+ # ========== 5. 清理视频录制 ==========
383
+ if TASK_ENV.eval_video_path is not None:
384
+ TASK_ENV._del_eval_video_ffmpeg()
385
+
386
+ # ========== 6. 统计成功/失败 & 打印 ==========
387
+ if succ:
388
+ TASK_ENV.suc += 1
389
+ print("\033[92mSuccess!\033[0m")
390
+ else:
391
+ print("\033[91mFail!\033[0m")
392
+
393
+ now_id += 1
394
+ TASK_ENV.close_env(clear_cache=((succ_seed + 1) % clear_cache_freq == 0))
395
+
396
+ if TASK_ENV.render_freq:
397
+ TASK_ENV.viewer.close()
398
+
399
+ TASK_ENV.test_num += 1
400
+
401
+ print(
402
+ f"\033[93m{task_name}\033[0m | "
403
+ f"\033[92m{args['task_config']}\033[0m | "
404
+ f"Success rate: \033[96m{TASK_ENV.suc}/{TASK_ENV.test_num}\033[0m"
405
+ f" => \033[95m{round(TASK_ENV.suc / TASK_ENV.test_num * 100, 1)}%\033[0m,"
406
+ f" current seed: \033[90m{now_seed}\033[0m\n"
407
+ )
408
+ now_seed += 1
409
+
410
+ return now_seed, TASK_ENV.suc
411
+
412
+
413
+ # ========================= main + 配置解析(基本沿用原 eval_policy_client) =========================
414
+
415
+ def main(usr_args):
416
+ current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
417
+ task_name = usr_args["task_name"]
418
+ task_config = usr_args["task_config"]
419
+ instruction_type = usr_args["instruction_type"]
420
+
421
+ # GR00T server 相关参数(可以放在 config 里)
422
+ groot_host = usr_args.get("host", "localhost")
423
+ groot_port = usr_args.get("port", 5555)
424
+ groot_api_token = usr_args.get("api_token", None)
425
+ groot_n_action_steps = usr_args.get("n_action_steps", 4)
426
+
427
+ save_dir = usr_args.get("save_dir", None)
428
+ video_size = None
429
+
430
+ with open(f"./task_config/{task_config}.yml", "r", encoding="utf-8") as f:
431
+ args = yaml.load(f.read(), Loader=yaml.FullLoader)
432
+
433
+
434
+ args["task_name"] = task_name
435
+ args["task_config"] = task_config
436
+
437
+ embodiment_type = args.get("embodiment")
438
+ embodiment_config_path = os.path.join(CONFIGS_PATH, "_embodiment_config.yml")
439
+
440
+ with open(embodiment_config_path, "r", encoding="utf-8") as f:
441
+ _embodiment_types = yaml.load(f.read(), Loader=yaml.FullLoader)
442
+
443
+ def get_embodiment_file(embodiment_type_item):
444
+ robot_file = _embodiment_types[embodiment_type_item]["file_path"]
445
+ if robot_file is None:
446
+ raise "No embodiment files"
447
+ return robot_file
448
+
449
+ with open(CONFIGS_PATH + "_camera_config.yml", "r", encoding="utf-8") as f:
450
+ _camera_config = yaml.load(f.read(), Loader=yaml.FullLoader)
451
+
452
+ head_camera_type = args["camera"]["head_camera_type"]
453
+ args["head_camera_h"] = _camera_config[head_camera_type]["h"]
454
+ args["head_camera_w"] = _camera_config[head_camera_type]["w"]
455
+
456
+ if len(embodiment_type) == 1:
457
+ args["left_robot_file"] = get_embodiment_file(embodiment_type[0])
458
+ args["right_robot_file"] = get_embodiment_file(embodiment_type[0])
459
+ args["dual_arm_embodied"] = True
460
+ elif len(embodiment_type) == 3:
461
+ args["left_robot_file"] = get_embodiment_file(embodiment_type[0])
462
+ args["right_robot_file"] = get_embodiment_file(embodiment_type[1])
463
+ args["embodiment_dis"] = embodiment_type[2]
464
+ args["dual_arm_embodied"] = False
465
+ else:
466
+ raise "embodiment items should be 1 or 3"
467
+
468
+ args["left_embodiment_config"] = get_embodiment_config(args["left_robot_file"])
469
+ args["right_embodiment_config"] = get_embodiment_config(args["right_robot_file"])
470
+
471
+ if len(embodiment_type) == 1:
472
+ embodiment_name = str(embodiment_type[0])
473
+ else:
474
+ embodiment_name = str(embodiment_type[0]) + "+" + str(embodiment_type[1])
475
+
476
+ # 简化 save_dir 路径,不再包含 ckpt_setting
477
+ if save_dir is None:
478
+ raise ValueError("save_dir is required")
479
+ else:
480
+ save_dir = Path(save_dir)
481
+ save_dir = save_dir / current_time
482
+ save_dir.mkdir(parents=True, exist_ok=True)
483
+
484
+ if args["eval_video_log"]:
485
+ video_save_dir = save_dir
486
+ camera_config = get_camera_config(args["camera"]["head_camera_type"])
487
+ video_size = str(camera_config["w"]) + "x" + str(camera_config["h"])
488
+ video_save_dir.mkdir(parents=True, exist_ok=True)
489
+ args["eval_video_save_dir"] = video_save_dir
490
+
491
+ # 输出当前配置,完全沿用原 eval_policy_client
492
+ print("============= Config =============\n")
493
+ print("\033[95mMessy Table:\033[0m " + str(args["domain_randomization"]["cluttered_table"]))
494
+ print(
495
+ "\033[95mRandom Background:\033[0m "
496
+ + str(args["domain_randomization"]["random_background"])
497
+ )
498
+ if args["domain_randomization"]["random_background"]:
499
+ print(
500
+ " - Clean Background Rate: "
501
+ + str(args["domain_randomization"]["clean_background_rate"])
502
+ )
503
+ print("\033[95mRandom Light:\033[0m " + str(args["domain_randomization"]["random_light"]))
504
+ if args["domain_randomization"]["random_light"]:
505
+ print(
506
+ " - Crazy Random Light Rate: "
507
+ + str(args["domain_randomization"]["crazy_random_light_rate"])
508
+ )
509
+ print(
510
+ "\033[95mRandom Table Height:\033[0m "
511
+ + str(args["domain_randomization"]["random_table_height"])
512
+ )
513
+ print(
514
+ "\033[95mRandom Head Camera Distance:\033[0m "
515
+ + str(args["domain_randomization"]["random_head_camera_dis"])
516
+ )
517
+
518
+ print(
519
+ "\033[94mHead Camera Config:\033[0m "
520
+ + str(args["camera"]["head_camera_type"])
521
+ + f", "
522
+ + str(args["camera"]["collect_head_camera"])
523
+ )
524
+ print(
525
+ "\033[94mWrist Camera Config:\033[0m "
526
+ + str(args["camera"]["wrist_camera_type"])
527
+ + f", "
528
+ + str(args["camera"]["collect_wrist_camera"])
529
+ )
530
+ print("\033[94mEmbodiment Config:\033[0m " + embodiment_name)
531
+ print("\n==================================")
532
+
533
+ TASK_ENV = class_decorator(args["task_name"])
534
+ usr_args["left_arm_dim"] = len(args["left_embodiment_config"]["arm_joints_name"][0])
535
+ usr_args["right_arm_dim"] = len(args["right_embodiment_config"]["arm_joints_name"][1])
536
+
537
+ seed = usr_args["seed"]
538
+
539
+ st_seed = 100000 * (1 + seed)
540
+ suc_nums = []
541
+ test_num = usr_args["test_num"]
542
+ topk = 1
543
+
544
+ st_seed, suc_num = eval_policy_with_groot(
545
+ task_name,
546
+ TASK_ENV,
547
+ args,
548
+ st_seed,
549
+ test_num=test_num,
550
+ video_size=video_size,
551
+ instruction_type=instruction_type,
552
+ groot_host=groot_host,
553
+ groot_port=groot_port,
554
+ groot_api_token=groot_api_token,
555
+ n_action_steps=groot_n_action_steps,
556
+ )
557
+ suc_nums.append(suc_num)
558
+
559
+ topk_success_rate = sorted(suc_nums, reverse=True)[:topk]
560
+
561
+ file_path = os.path.join(save_dir, f"_result.txt")
562
+ with open(file_path, "w") as file:
563
+ file.write(f"Timestamp: {current_time}\n\n")
564
+ file.write(f"Task: {task_name}\n")
565
+ file.write(f"Task Config: {task_config}\n")
566
+ file.write(f"GR00T Server: {groot_host}:{groot_port}\n")
567
+ file.write(f"Instruction Type: {instruction_type}\n\n")
568
+ file.write(f"Success Rate: {suc_num}/{test_num} = {suc_num/test_num*100:.2f}%\n")
569
+ file.write("\n".join(map(str, np.array(suc_nums) / test_num)))
570
+
571
+ # 在终端打印最终的成功率统计
572
+ print("\n" + "="*60)
573
+ print("\033[1m========== Evaluation Results ==========\033[0m")
574
+ print("="*60)
575
+ print(f"\033[93mTask Name:\033[0m {task_name}")
576
+ print(f"\033[93mTask Config:\033[0m {task_config}")
577
+ print(f"\033[93mGR00T Server:\033[0m {groot_host}:{groot_port}")
578
+ print(f"\033[93mInstruction Type:\033[0m {instruction_type}")
579
+ print(f"\033[93mTotal Episodes:\033[0m {test_num}")
580
+ print(f"\033[93mSuccessful Episodes:\033[0m {suc_num}")
581
+ print(f"\033[93mSuccess Rate:\033[0m \033[92m{suc_num}/{test_num} = {suc_num/test_num*100:.2f}%\033[0m")
582
+ print("="*60)
583
+ print(f"\033[94mResults saved to:\033[0m {file_path}")
584
+ print("="*60 + "\n")
585
+
586
+
587
+
588
+ if __name__ == "__main__":
589
+ parser = argparse.ArgumentParser(description="GR00T Simulation Client for RoboTwin")
590
+
591
+ # ========== 必需的任务参数 ==========
592
+ parser.add_argument("--task_name", type=str, required=True,
593
+ help="Task name (e.g., beat_block_hammer)")
594
+ parser.add_argument("--task_config", type=str, required=True,
595
+ help="Task config file name (e.g., demo_clean)")
596
+ parser.add_argument("--instruction_type", type=str, default="unseen", # 添加默认值
597
+ help="Instruction type (e.g., language, unseen, default: unseen)")
598
+ parser.add_argument("--seed", type=int, required=True,
599
+ help="Random seed")
600
+
601
+ # ========== GR00T server 连接参数 ==========
602
+ parser.add_argument("--host", type=str, default="localhost",
603
+ help="GR00T server host (default: localhost)")
604
+ parser.add_argument("--port", type=int, default=8811,
605
+ help="GR00T server port (default: 8811)")
606
+ parser.add_argument("--api_token", type=str, default=None,
607
+ help="API token for GR00T server (optional)")
608
+ parser.add_argument("--n_action_steps", type=int, default=4,
609
+ help="Number of action steps per inference (default: 4)")
610
+
611
+ # ========== 可选的保存路径 ==========
612
+ parser.add_argument("--save_dir", type=str, default=None,
613
+ help="Directory to save evaluation results (default: eval_result/...)")
614
+
615
+ # ========== 可选的测试数量 ==========
616
+ parser.add_argument("--test_num", type=int, default=100,
617
+ help="Number of episodes to test (default: 100)")
618
+
619
+ args = parser.parse_args()
620
+
621
+ from test_render import Sapien_TEST
622
+ Sapien_TEST()
623
+
624
+ # 转换为字典格式供 main() 使用
625
+ usr_args = {
626
+ "task_name": args.task_name,
627
+ "task_config": args.task_config,
628
+ "instruction_type": args.instruction_type,
629
+ "seed": args.seed,
630
+ "host": args.host,
631
+ "port": args.port,
632
+ "api_token": args.api_token,
633
+ "n_action_steps": args.n_action_steps,
634
+ "save_dir": args.save_dir,
635
+ "test_num": args.test_num,
636
+ }
637
+
638
+ main(usr_args)
script/policy_model_server.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import os
3
+ import subprocess
4
+ import socket
5
+ import json
6
+ import threading
7
+ import time
8
+ import random
9
+ import traceback
10
+ import yaml
11
+ from datetime import datetime
12
+ import importlib
13
+ import argparse
14
+ from pathlib import Path
15
+ from collections import deque
16
+
17
+ sys.path.append("./")
18
+ sys.path.append(f"./policy")
19
+ sys.path.append("./description/utils")
20
+ from envs._GLOBAL_CONFIGS import CONFIGS_PATH
21
+
22
+ import numpy as np
23
+ from typing import Any
24
+ import base64
25
+
26
+
27
+ class NumpyEncoder(json.JSONEncoder):
28
+ """JSON encoder extension for numpy types, includes reconstruction metadata"""
29
+ def default(self, obj):
30
+ if isinstance(obj, np.ndarray):
31
+ # Determine dtype for reconstruction
32
+ if obj.dtype == np.float32:
33
+ dtype = 'float32'
34
+ elif obj.dtype == np.float64:
35
+ dtype = 'float64'
36
+ elif obj.dtype == np.int32:
37
+ dtype = 'int32'
38
+ elif obj.dtype == np.int64:
39
+ dtype = 'int64'
40
+ else:
41
+ dtype = str(obj.dtype)
42
+ # Encode array bytes as base64
43
+ return {
44
+ '__numpy_array__': True,
45
+ 'data': base64.b64encode(obj.tobytes()).decode('ascii'),
46
+ 'dtype': dtype,
47
+ 'shape': obj.shape
48
+ }
49
+ elif isinstance(obj, np.integer):
50
+ return int(obj)
51
+ elif isinstance(obj, np.floating):
52
+ return float(obj)
53
+ elif isinstance(obj, np.bool_):
54
+ return bool(obj)
55
+ return super().default(obj)
56
+
57
+
58
+ def numpy_to_json(data: Any) -> str:
59
+ """Serialize Python data (including numpy arrays) to JSON string"""
60
+ return json.dumps(data, cls=NumpyEncoder)
61
+
62
+
63
+ def json_to_numpy(json_str: str) -> Any:
64
+ """Deserialize JSON string back to Python objects, reconstructing numpy arrays"""
65
+ def object_hook(dct):
66
+ if '__numpy_array__' in dct:
67
+ raw = base64.b64decode(dct['data'])
68
+ return np.frombuffer(raw, dtype=dct['dtype']).reshape(dct['shape'])
69
+ return dct
70
+ return json.loads(json_str, object_hook=object_hook)
71
+
72
+
73
+ # --------------------- Model Server Implementation ---------------------
74
+ class ModelServer:
75
+ def __init__(self, model, host='localhost', port=None):
76
+ self.model = model
77
+ self.host = host
78
+ self.port = port
79
+ self.server_socket = None
80
+ self.running = False
81
+ self.wait_interval = 10
82
+ self.client_threads = []
83
+
84
+ def start(self):
85
+ """Start the model server and listen for incoming client connections"""
86
+ self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
87
+ self.server_socket.bind((self.host, self.port))
88
+ self.server_socket.settimeout(self.wait_interval)
89
+ self.server_socket.listen(5)
90
+ self.running = True
91
+
92
+ print(f"🚀 Model server started on {self.host}:{self.port}")
93
+ print("🔄 Server is waiting for client connections...")
94
+
95
+ self._accept_connections()
96
+
97
+ def stop(self):
98
+ """Stop the server and clean up resources gracefully"""
99
+ self.running = False
100
+ if self.server_socket:
101
+ try:
102
+ self.server_socket.close()
103
+ except:
104
+ pass
105
+ for t in self.client_threads:
106
+ t.join(timeout=1)
107
+ print("🛑 Server has been stopped")
108
+
109
+ def _accept_connections(self):
110
+ """Accept and handle new client connections"""
111
+ while self.running:
112
+ try:
113
+ client_socket, addr = self.server_socket.accept()
114
+ print(f"✅ Client connected from {addr}")
115
+ # Handle each client in a separate thread
116
+ t = threading.Thread(target=self._handle_client,
117
+ args=(client_socket,), daemon=True)
118
+ t.start()
119
+ self.client_threads.append(t)
120
+ except socket.timeout:
121
+ continue
122
+ except Exception as e:
123
+ if self.running:
124
+ print(f"⚠️ Error accepting connection: {e}")
125
+ break
126
+
127
+ def _handle_client(self, client_socket):
128
+ """Process requests from a single client"""
129
+ with client_socket:
130
+ while self.running:
131
+ try:
132
+ # Read message length header (4 bytes, big-endian)
133
+ len_bytes = client_socket.recv(4)
134
+ if not len_bytes:
135
+ print("🔌 Client disconnected")
136
+ break
137
+ msg_length = int.from_bytes(len_bytes, 'big')
138
+
139
+ # Read the full message based on length
140
+ chunks = []
141
+ remaining = msg_length
142
+ while remaining > 0:
143
+ chunk = client_socket.recv(min(remaining, 4096))
144
+ if not chunk:
145
+ raise ConnectionError("Incomplete data received")
146
+ chunks.append(chunk)
147
+ remaining -= len(chunk)
148
+ raw_msg = b''.join(chunks).decode('utf-8')
149
+
150
+ # Deserialize JSON to Python, reconstruct any numpy arrays
151
+ data = json_to_numpy(raw_msg)
152
+
153
+ # Extract command and observation
154
+ cmd = data.get("cmd")
155
+ obs = data.get("obs") # None if not provided
156
+
157
+ # Find corresponding model method
158
+ method = getattr(self.model, cmd, None)
159
+ if not callable(method):
160
+ raise AttributeError(f"No model method named '{cmd}'")
161
+
162
+ # Call method with or without obs
163
+ result = method(obs) if obs is not None else method()
164
+ response = {"res": result}
165
+
166
+ # Serialize response and send back with length header
167
+ resp_bytes = numpy_to_json(response).encode('utf-8')
168
+ client_socket.sendall(len(resp_bytes).to_bytes(4, 'big'))
169
+ client_socket.sendall(resp_bytes)
170
+
171
+ except (ConnectionResetError, BrokenPipeError):
172
+ print("🔌 Client connection lost")
173
+ break
174
+ except Exception as e:
175
+ err = f"Error handling request: {e}"
176
+ print(f"⚠️ {err}")
177
+ tb = traceback.format_exc()
178
+ error_resp = numpy_to_json({"error": err, "traceback": tb}).encode('utf-8')
179
+ client_socket.sendall(len(error_resp).to_bytes(4, 'big'))
180
+ client_socket.sendall(error_resp)
181
+ break
182
+
183
+
184
+ # --------------------- Utility Decorators ---------------------
185
+ def class_decorator(task_name):
186
+ """Instantiate environment class for given task"""
187
+ envs_module = importlib.import_module(f"envs.{task_name}")
188
+ if not hasattr(envs_module, task_name):
189
+ raise SystemExit("Task not found")
190
+ return getattr(envs_module, task_name)()
191
+
192
+
193
+ def eval_function_decorator(policy_name, model_name, conda_env=None):
194
+ """Load a specified function (e.g., get_model) from a policy module"""
195
+ module = importlib.import_module(policy_name)
196
+ return getattr(module, model_name)
197
+
198
+
199
+ def get_camera_config(camera_type):
200
+ """Load camera configuration from YAML file"""
201
+ cfg_path = os.path.join(os.path.dirname(__file__), "../task_config/_camera_config.yml")
202
+ if not os.path.isfile(cfg_path):
203
+ raise FileNotFoundError("Camera config file not found")
204
+ with open(cfg_path, 'r', encoding='utf-8') as f:
205
+ cfg = yaml.safe_load(f)
206
+ if camera_type not in cfg:
207
+ raise KeyError(f"Camera type '{camera_type}' is not defined")
208
+ return cfg[camera_type]
209
+
210
+
211
+ def get_embodiment_config(robot_file):
212
+ """Load robot embodiment configuration from YAML"""
213
+ path = os.path.join(robot_file, "config.yml")
214
+ with open(path, 'r', encoding='utf-8') as f:
215
+ return yaml.safe_load(f)
216
+
217
+
218
+ def main(usr_args):
219
+ """Main entry: load model, start server, run indefinitely"""
220
+ # Extract basic arguments
221
+ policy_name = usr_args['policy_name']
222
+ port = usr_args.get('port')
223
+
224
+ # Instantiate model
225
+ get_model = eval_function_decorator(policy_name, 'get_model')
226
+ model = get_model(usr_args)
227
+
228
+ # Start server in background thread
229
+ server = ModelServer(model, port=port)
230
+ thread = threading.Thread(target=server.start, daemon=True)
231
+ thread.start()
232
+
233
+ # Keep main thread alive until KeyboardInterrupt
234
+ try:
235
+ while True:
236
+ time.sleep(1)
237
+ except KeyboardInterrupt:
238
+ print("\n🛑 Shutting down server...")
239
+ server.stop()
240
+ thread.join()
241
+
242
+
243
+ def parse_args_and_config():
244
+ """Parse CLI args and YAML config, merge overrides"""
245
+ parser = argparse.ArgumentParser()
246
+ parser.add_argument('--port', type=int, help='Port for ModelServer (optional)')
247
+ parser.add_argument('--config', type=str, required=True, help='Path to config YAML')
248
+ parser.add_argument('--overrides', nargs=argparse.REMAINDER,
249
+ help='Override config values')
250
+ args = parser.parse_args()
251
+
252
+ # Load base config
253
+ with open(args.config, 'r', encoding='utf-8') as f:
254
+ cfg = yaml.safe_load(f)
255
+ cfg['port'] = args.port
256
+
257
+ # Parse overrides: --key value pairs
258
+ if args.overrides:
259
+ it = iter(args.overrides)
260
+ for key in it:
261
+ val = next(it)
262
+ cfg[key.lstrip('--')] = eval(val) if val.isnumeric() else val
263
+ return cfg
264
+
265
+
266
+ if __name__ == '__main__':
267
+ usr_args = parse_args_and_config()
268
+ main(usr_args)
script/requirements.txt ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch==2.4.1
2
+ torchvision
3
+ transforms3d==0.4.2
4
+ sapien==3.0.0b1
5
+ scipy==1.10.1
6
+ mplib==0.2.1
7
+ gymnasium==0.29.1
8
+ trimesh==4.4.3
9
+ open3d==0.18.0
10
+ imageio==2.34.2
11
+ pydantic
12
+ zarr
13
+ openai
14
+ huggingface_hub==0.25.0
15
+ h5py
16
+ # For Description Generation
17
+ azure==4.0.0
18
+ azure-ai-inference
19
+ pyglet<2
20
+ wandb
21
+ moviepy
22
+ imageio
23
+ termcolor
24
+ av
25
+ matplotlib
26
+ ffmpeg
script/set_log.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import time
4
+ import argparse
5
+ import logging
6
+ from datetime import datetime
7
+
8
+
9
+ def setup_logging(output_path: str, log_level=logging.INFO):
10
+ """
11
+ 设置日志记录,同时输出到控制台和文件
12
+
13
+ Args:
14
+ output_path: 输出目录路径,日志文件将保存在此目录下
15
+ log_level: 日志级别,默认为 INFO
16
+
17
+ Returns:
18
+ logger: 日志记录器
19
+ log_file: 日志文件路径
20
+ """
21
+ # 创建日志目录
22
+ log_dir = os.path.join(output_path, 'logs')
23
+ os.makedirs(log_dir, exist_ok=True)
24
+
25
+ # 生成日志文件名(带时间戳)
26
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
27
+ log_file = os.path.join(log_dir, f"batch_eval_{timestamp}.log")
28
+
29
+ # 配置日志格式
30
+ log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
31
+ date_format = '%Y-%m-%d %H:%M:%S'
32
+
33
+ # 配置根日志记录器
34
+ logging.basicConfig(
35
+ level=log_level,
36
+ format=log_format,
37
+ datefmt=date_format,
38
+ handlers=[
39
+ # 文件处理器 - 记录所有级别的日志
40
+ logging.FileHandler(log_file, encoding='utf-8'),
41
+ # 控制台处理器 - 只显示 INFO 及以上级别
42
+ logging.StreamHandler(sys.stdout)
43
+ ],
44
+ force=True # 强制重新配置,避免重复配置问题
45
+ )
46
+
47
+ logger = logging.getLogger(__name__)
48
+ logger.info(f"日志文件已创建: {log_file}")
49
+ logger.info(f"日志级别: {logging.getLevelName(log_level)}")
50
+
51
+ return logger, log_file
script/test_render.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import warnings
3
+ import os
4
+
5
+ warnings.simplefilter(action="ignore", category=FutureWarning)
6
+ warnings.simplefilter(action="ignore", category=UserWarning)
7
+ current_file_path = os.path.abspath(__file__)
8
+ parent_dir = os.path.dirname(current_file_path)
9
+
10
+ sys.path.append(os.path.join(parent_dir, "../../tools"))
11
+ import numpy as np
12
+ import pdb
13
+ import json
14
+ import torch
15
+ import sapien.core as sapien
16
+ from sapien.utils.viewer import Viewer
17
+ import gymnasium as gym
18
+ import toppra as ta
19
+ import transforms3d as t3d
20
+ from collections import OrderedDict
21
+
22
+
23
+ class Sapien_TEST(gym.Env):
24
+
25
+ def __init__(self):
26
+ super().__init__()
27
+ ta.setup_logging("CRITICAL")
28
+ try:
29
+ self.setup_scene()
30
+ print("\033[32mRender Well\033[0m")
31
+ except Exception as e:
32
+ import traceback
33
+ print("\033[31mRender Error\033[0m", e)
34
+ traceback.print_exc()
35
+ raise
36
+
37
+ def setup_scene(self, **kwargs):
38
+ """
39
+ Set the scene
40
+ - Set up the basic scene: light source, viewer.
41
+ """
42
+ self.engine = sapien.Engine()
43
+ # declare sapien renderer
44
+ from sapien.render import set_global_config
45
+
46
+ set_global_config(max_num_materials=50000, max_num_textures=50000)
47
+ self.renderer = sapien.SapienRenderer()
48
+ # give renderer to sapien sim
49
+ self.engine.set_renderer(self.renderer)
50
+
51
+ sapien.render.set_camera_shader_dir("rt")
52
+ sapien.render.set_ray_tracing_samples_per_pixel(32)
53
+ sapien.render.set_ray_tracing_path_depth(8)
54
+ sapien.render.set_ray_tracing_denoiser("oidn")
55
+
56
+ # declare sapien scene
57
+ scene_config = sapien.SceneConfig()
58
+ self.scene = self.engine.create_scene(scene_config)
59
+
60
+
61
+ if __name__ == "__main__":
62
+ a = Sapien_TEST()
63
+
64
+
script/update_embodiment_config_path.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import os
3
+ import sys
4
+ import glob
5
+
6
+ def print_color(message, color_code):
7
+ NC = '\033[0m'
8
+ print(f"{color_code}{message}{NC}")
9
+
10
+ BLUE = '\033[0;34m'
11
+ YELLOW = '\033[0;33m'
12
+ GREEN = '\033[0;32m'
13
+
14
+
15
+ def prompt_path():
16
+ answer = input("Do you want to manually specify the absolute path to the assets directory? (y/n): ")
17
+ if answer.lower() != 'y':
18
+ sys.exit(1)
19
+ return input("Please enter the absolute path: ")
20
+
21
+
22
+ def main():
23
+ # Get current directory
24
+ assets_path = os.getcwd()
25
+ print_color(f"Current path: {assets_path}", BLUE)
26
+
27
+ # Check ./assets/embodiments
28
+ if not os.path.isdir(os.path.join(assets_path, 'assets', 'embodiments')):
29
+ print_color("Warning: ./assets/embodiments directory not found", YELLOW)
30
+ parent = os.path.abspath(os.path.join(assets_path, '..'))
31
+ if os.path.isdir(os.path.join(parent, 'assets', 'embodiments')):
32
+ print("Found assets/embodiments in parent directory, switching...")
33
+ assets_path = parent
34
+ os.chdir(assets_path)
35
+ print_color(f"Updated path: {assets_path}", BLUE)
36
+ else:
37
+ print_color("Please ensure you're running this script in the correct directory", YELLOW)
38
+ print("Script should be run in the repository root directory containing assets/embodiments")
39
+ assets_path = prompt_path()
40
+ if not os.path.isdir(os.path.join(assets_path, 'assets', 'embodiments')):
41
+ print_color("Error: Cannot find assets/embodiments directory at the specified path", YELLOW)
42
+ sys.exit(1)
43
+ os.chdir(assets_path)
44
+ print_color(f"Switched to: {assets_path}", BLUE)
45
+
46
+ # Export environment variable
47
+ os.environ['ASSETS_PATH'] = assets_path
48
+ print_color(f"Setting environment variable: ASSETS_PATH={assets_path}", BLUE)
49
+
50
+ # Counters
51
+ count_total = count_updated = count_error = 0
52
+
53
+ # Find *_tmp.yml files
54
+ print_color("Searching for configuration template files...", BLUE)
55
+ pattern = os.path.join(assets_path, 'assets', 'embodiments', '**', '*_tmp.yml')
56
+ config_files = glob.glob(pattern, recursive=True)
57
+
58
+ if not config_files:
59
+ print_color("No *_tmp.yml files found", YELLOW)
60
+ sys.exit(1)
61
+
62
+ print_color("Starting to process configuration files...", BLUE)
63
+ for tmp_file in config_files:
64
+ count_total += 1
65
+ target_file = tmp_file.replace('_tmp.yml', '.yml')
66
+ print(f"Processing [{count_total}]: {tmp_file} -> {target_file}")
67
+
68
+ try:
69
+ with open(tmp_file, 'r') as f:
70
+ content = f.read()
71
+
72
+ new_content = content.replace('${ASSETS_PATH}', assets_path)
73
+ new_content = new_content.replace('$ASSETS_PATH', assets_path)
74
+
75
+ with open(target_file, 'w') as f:
76
+ f.write(new_content)
77
+
78
+ print_color(f" ✓ Successfully replaced ${{ASSETS_PATH}} -> {assets_path}", GREEN)
79
+ count_updated += 1
80
+
81
+ if '${ASSETS_PATH}' in content and assets_path in new_content:
82
+ print_color(" ✓ Confirmed path was correctly replaced", GREEN)
83
+ elif '${ASSETS_PATH}' in content:
84
+ print_color(" ! Warning: Could not confirm if path was correctly replaced", YELLOW)
85
+
86
+ except Exception as e:
87
+ print_color(f" ✗ Replacement failed: {e}", YELLOW)
88
+ count_error += 1
89
+
90
+ # Summary
91
+ print()
92
+ print_color("Processing complete!", BLUE)
93
+ print(f"Total processed: {count_total} files")
94
+ print_color(f"Successfully updated: {count_updated} files", GREEN)
95
+ if count_error > 0:
96
+ print_color(f"Failed to process: {count_error} files", YELLOW)
97
+
98
+ print()
99
+ print_color("All template files have been processed!", GREEN)
100
+ print("To use in a new environment, run this script again")
101
+
102
+
103
+ if __name__ == '__main__':
104
+ main()
scripts/check_agibot_future_video_motion.py ADDED
@@ -0,0 +1,642 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Check whether AgiBot GT future video frames are static.
3
+
4
+ This script reads LeRobot samples through the same starVLA dataset code used by
5
+ cosmos25_perceiver_pretrain.sh, then compares frames at:
6
+
7
+ t, t + future_video_delta_indices[0], ..., t + future_video_delta_indices[-1]
8
+
9
+ It reports pixel-difference metrics per camera view and writes contact sheets so
10
+ you can visually confirm whether the GT future frames actually move.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import csv
17
+ import json
18
+ import math
19
+ import random
20
+ import sys
21
+ from collections import defaultdict
22
+ from pathlib import Path
23
+ from typing import Any
24
+
25
+ import numpy as np
26
+ import av
27
+ from omegaconf import OmegaConf
28
+ from PIL import Image, ImageDraw
29
+
30
+
31
+ REPO_ROOT = Path(__file__).resolve().parents[1]
32
+ if str(REPO_ROOT) not in sys.path:
33
+ sys.path.insert(0, str(REPO_ROOT))
34
+
35
+ from starVLA.dataloader.gr00t_lerobot.mixtures import DATASET_NAMED_MIXTURES
36
+ from starVLA.dataloader.gr00t_lerobot.video import get_frames_by_timestamps
37
+ from starVLA.dataloader.lerobot_datasets import make_LeRobotSingleDataset
38
+
39
+
40
+ DEFAULT_CONFIG_YAML = REPO_ROOT / "examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml"
41
+ DEFAULT_DATA_ROOT_DIR = "/mnt/workspace1/"
42
+ DEFAULT_DATA_MIX = "sq_agi-beta_robocasa"
43
+ DEFAULT_FUTURE_OFFSETS = [2, 4, 6, 8, 10, 12, 14, 16]
44
+ DEFAULT_ROBOT_TYPES = ["agibot_beta", "agibot_genie1"]
45
+
46
+
47
+ def parse_int_list(value: str) -> list[int]:
48
+ text = value.strip()
49
+ if text.startswith("["):
50
+ parsed = json.loads(text)
51
+ return [int(item) for item in parsed]
52
+ return [int(item) for item in text.split(",") if item.strip()]
53
+
54
+
55
+ def parse_str_list(value: str) -> list[str]:
56
+ return [item.strip() for item in value.split(",") if item.strip()]
57
+
58
+
59
+ def parse_args() -> argparse.Namespace:
60
+ parser = argparse.ArgumentParser(description=__doc__)
61
+ parser.add_argument("--config-yaml", default=str(DEFAULT_CONFIG_YAML))
62
+ parser.add_argument("--data-root-dir", default=DEFAULT_DATA_ROOT_DIR)
63
+ parser.add_argument("--data-mix", default=DEFAULT_DATA_MIX)
64
+ parser.add_argument("--video-backend", default="torchvision_av")
65
+ parser.add_argument(
66
+ "--compare-video-backends",
67
+ default="",
68
+ help="Comma-separated extra backends to read with the same timestamps, e.g. decord,torchvision_av.",
69
+ )
70
+ parser.add_argument("--future-video-delta-indices", default=json.dumps(DEFAULT_FUTURE_OFFSETS))
71
+ parser.add_argument(
72
+ "--robot-types",
73
+ default=",".join(DEFAULT_ROBOT_TYPES),
74
+ help="Comma-separated robot types to inspect from the mixture.",
75
+ )
76
+ parser.add_argument("--samples-per-dataset", type=int, default=16)
77
+ parser.add_argument("--seed", type=int, default=0)
78
+ parser.add_argument("--out-dir", default="outputs/agibot_future_video_debug")
79
+ parser.add_argument(
80
+ "--changed-pixel-threshold",
81
+ type=float,
82
+ default=3.0,
83
+ help="A pixel is treated as changed if any RGB channel differs by more than this value.",
84
+ )
85
+ parser.add_argument(
86
+ "--frozen-ratio-threshold",
87
+ type=float,
88
+ default=0.001,
89
+ help="Frame pairs below this changed-pixel ratio are flagged as frozen.",
90
+ )
91
+ parser.add_argument("--max-contact-sheets", type=int, default=64)
92
+ parser.add_argument("--skip-video-timestamp-map", action="store_true")
93
+ parser.add_argument(
94
+ "--show-all-frames",
95
+ action="store_true",
96
+ help="Save all sampled frames in contact sheets. Default saves only first and last frames for easier inspection.",
97
+ )
98
+ return parser.parse_args()
99
+
100
+
101
+ def image_to_uint8_rgb(frame: Any) -> np.ndarray:
102
+ array = np.asarray(frame)
103
+ if array.ndim == 4:
104
+ array = array[0]
105
+ if array.ndim != 3:
106
+ raise ValueError(f"Expected HWC image or THWC video with T=1, got shape {array.shape}")
107
+ if array.shape[-1] == 4:
108
+ array = array[..., :3]
109
+ if array.shape[-1] != 3:
110
+ raise ValueError(f"Expected RGB/RGBA image, got shape {array.shape}")
111
+ if array.dtype != np.uint8:
112
+ if np.issubdtype(array.dtype, np.floating):
113
+ max_value = float(np.nanmax(array)) if array.size else 1.0
114
+ if max_value <= 1.0:
115
+ array = array * 255.0
116
+ array = np.clip(array, 0, 255).astype(np.uint8)
117
+ return np.ascontiguousarray(array)
118
+
119
+
120
+ def resize_for_metrics(a: np.ndarray, b: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
121
+ if a.shape[:2] == b.shape[:2]:
122
+ return a, b
123
+ image = Image.fromarray(b).resize((a.shape[1], a.shape[0]), Image.Resampling.BILINEAR)
124
+ return a, np.asarray(image, dtype=np.uint8)
125
+
126
+
127
+ def frame_diff_metrics(a: np.ndarray, b: np.ndarray, changed_threshold: float) -> dict[str, float]:
128
+ a, b = resize_for_metrics(a, b)
129
+ diff = np.abs(a.astype(np.float32) - b.astype(np.float32))
130
+ mse = float(np.mean(diff * diff))
131
+ psnr = float("inf") if mse == 0.0 else 20.0 * math.log10(255.0 / math.sqrt(mse))
132
+ changed = np.any(diff > changed_threshold, axis=-1)
133
+ return {
134
+ "mae": float(np.mean(diff)),
135
+ "rmse": float(math.sqrt(mse)),
136
+ "psnr": psnr,
137
+ "max_abs": float(np.max(diff)),
138
+ "changed_pixel_ratio": float(np.mean(changed)),
139
+ }
140
+
141
+
142
+ def concat_raw_action(raw_data: dict[str, Any], action_keys: list[str]) -> np.ndarray | None:
143
+ chunks = []
144
+ for key in action_keys:
145
+ if key not in raw_data:
146
+ continue
147
+ value = np.asarray(raw_data[key])
148
+ if value.ndim == 1:
149
+ value = value[:, None]
150
+ chunks.append(value)
151
+ if not chunks:
152
+ return None
153
+ return np.concatenate(chunks, axis=1).astype(np.float32)
154
+
155
+
156
+ def get_video_frame_timestamps(video_path: Path) -> np.ndarray:
157
+ container = av.open(video_path.as_posix(), options={"threads": "1"})
158
+ stream = container.streams.video[0]
159
+ timestamps = []
160
+ try:
161
+ for frame in container.decode(video=0):
162
+ if frame.pts is None:
163
+ continue
164
+ timestamps.append(float(frame.pts * stream.time_base))
165
+ finally:
166
+ container.close()
167
+ if not timestamps:
168
+ raise ValueError(f"No decodable frame timestamps in {video_path}")
169
+ return np.asarray(timestamps, dtype=np.float64)
170
+
171
+
172
+ def get_video_frames_by_indices_pyav(video_path: Path, indices: np.ndarray) -> list[np.ndarray]:
173
+ requested = np.asarray(indices, dtype=np.int64)
174
+ if requested.ndim != 1:
175
+ requested = requested.reshape(-1)
176
+ if len(requested) == 0:
177
+ return []
178
+
179
+ order = np.argsort(requested)
180
+ sorted_indices = requested[order]
181
+ frames_sorted: list[np.ndarray | None] = [None] * len(sorted_indices)
182
+ container = av.open(video_path.as_posix(), options={"threads": "1"})
183
+ try:
184
+ want = 0
185
+ for frame_index, frame in enumerate(container.decode(video=0)):
186
+ while want < len(sorted_indices) and sorted_indices[want] < frame_index:
187
+ want += 1
188
+ if want >= len(sorted_indices):
189
+ break
190
+ if frame_index == sorted_indices[want]:
191
+ frame_array = frame.to_ndarray(format="rgb24")
192
+ while want < len(sorted_indices) and sorted_indices[want] == frame_index:
193
+ frames_sorted[want] = frame_array
194
+ want += 1
195
+ if want >= len(sorted_indices):
196
+ break
197
+ finally:
198
+ container.close()
199
+
200
+ if any(frame is None for frame in frames_sorted):
201
+ missing = [int(sorted_indices[idx]) for idx, frame in enumerate(frames_sorted) if frame is None]
202
+ raise ValueError(f"Missing video frame indices {missing[:8]} from {video_path}")
203
+
204
+ restored: list[np.ndarray | None] = [None] * len(requested)
205
+ for sorted_pos, original_pos in enumerate(order):
206
+ restored[int(original_pos)] = frames_sorted[sorted_pos]
207
+ return [image_to_uint8_rgb(frame) for frame in restored if frame is not None]
208
+
209
+
210
+ def nearest_video_frame_indices(video_timestamps: np.ndarray, target_timestamps: np.ndarray) -> np.ndarray:
211
+ positions = np.searchsorted(video_timestamps, target_timestamps)
212
+ positions = np.clip(positions, 0, len(video_timestamps) - 1)
213
+ prev_positions = np.clip(positions - 1, 0, len(video_timestamps) - 1)
214
+ use_prev = np.abs(video_timestamps[prev_positions] - target_timestamps) <= np.abs(
215
+ video_timestamps[positions] - target_timestamps
216
+ )
217
+ return np.where(use_prev, prev_positions, positions).astype(np.int64)
218
+
219
+
220
+ def proportional_video_indices(step_indices: list[int], trajectory_length: int, num_video_frames: int) -> np.ndarray:
221
+ if trajectory_length <= 1 or num_video_frames <= 1:
222
+ return np.zeros(len(step_indices), dtype=np.int64)
223
+ ratio = np.asarray(step_indices, dtype=np.float64) / float(trajectory_length - 1)
224
+ ratio = np.clip(ratio, 0.0, 1.0)
225
+ return np.rint(ratio * float(num_video_frames - 1)).astype(np.int64)
226
+
227
+
228
+ def save_contact_sheet(
229
+ frames: list[np.ndarray],
230
+ labels: list[str],
231
+ output_path: Path,
232
+ cell_width: int = 224,
233
+ label_height: int = 24,
234
+ ) -> None:
235
+ if not frames:
236
+ return
237
+ resample = getattr(Image, "Resampling", Image).BILINEAR
238
+ resized = [
239
+ Image.fromarray(frame).convert("RGB").resize((cell_width, int(cell_width * frame.shape[0] / frame.shape[1])), resample)
240
+ for frame in frames
241
+ ]
242
+ cell_height = max(image.height for image in resized)
243
+ sheet = Image.new("RGB", (cell_width * len(resized), cell_height + label_height), "white")
244
+ draw = ImageDraw.Draw(sheet)
245
+ for idx, image in enumerate(resized):
246
+ x = idx * cell_width
247
+ y = label_height
248
+ sheet.paste(image, (x, y))
249
+ draw.text((x + 4, 4), labels[idx], fill=(0, 0, 0))
250
+ output_path.parent.mkdir(parents=True, exist_ok=True)
251
+ sheet.save(output_path)
252
+
253
+
254
+ def save_comparison_contact_sheet(
255
+ rows: list[tuple[str, list[np.ndarray]]],
256
+ labels: list[str],
257
+ output_path: Path,
258
+ cell_width: int = 224,
259
+ label_height: int = 24,
260
+ row_label_width: int = 92,
261
+ ) -> None:
262
+ rows = [(name, frames) for name, frames in rows if frames]
263
+ if not rows:
264
+ return
265
+ resample = getattr(Image, "Resampling", Image).BILINEAR
266
+ resized_rows = []
267
+ max_cell_height = 1
268
+ for row_name, frames in rows:
269
+ resized = [
270
+ Image.fromarray(frame)
271
+ .convert("RGB")
272
+ .resize((cell_width, int(cell_width * frame.shape[0] / frame.shape[1])), resample)
273
+ for frame in frames
274
+ ]
275
+ max_cell_height = max(max_cell_height, *(image.height for image in resized))
276
+ resized_rows.append((row_name, resized))
277
+
278
+ row_height = max_cell_height + label_height
279
+ sheet = Image.new("RGB", (row_label_width + cell_width * len(labels), row_height * len(resized_rows)), "white")
280
+ draw = ImageDraw.Draw(sheet)
281
+ for row_idx, (row_name, images) in enumerate(resized_rows):
282
+ y0 = row_idx * row_height
283
+ draw.text((4, y0 + label_height + 4), row_name, fill=(0, 0, 0))
284
+ for col_idx, image in enumerate(images):
285
+ x = row_label_width + col_idx * cell_width
286
+ if row_idx == 0:
287
+ draw.text((x + 4, y0 + 4), labels[col_idx], fill=(0, 0, 0))
288
+ sheet.paste(image, (x, y0 + label_height))
289
+ output_path.parent.mkdir(parents=True, exist_ok=True)
290
+ sheet.save(output_path)
291
+
292
+
293
+ def select_visual_frames(frames: list[np.ndarray], labels: list[str], show_all_frames: bool) -> tuple[list[np.ndarray], list[str]]:
294
+ if show_all_frames or len(frames) <= 2:
295
+ return frames, labels
296
+ return [frames[0], frames[-1]], [labels[0], labels[-1]]
297
+
298
+
299
+ def build_data_cfg(args: argparse.Namespace, future_offsets: list[int]):
300
+ cfg = OmegaConf.load(args.config_yaml)
301
+ data_cfg = cfg.datasets.vla_data
302
+ data_cfg.data_root_dir = args.data_root_dir
303
+ data_cfg.data_mix = args.data_mix
304
+ data_cfg.include_state = True
305
+ data_cfg.video_backend = args.video_backend
306
+ data_cfg.future_video_delta_indices = future_offsets
307
+ return data_cfg
308
+
309
+
310
+ def choose_steps(dataset, count: int, rng: random.Random) -> list[tuple[int, int]]:
311
+ all_steps = [(int(traj), int(step)) for traj, step in np.asarray(dataset.all_steps)]
312
+ if len(all_steps) <= count:
313
+ return all_steps
314
+ return rng.sample(all_steps, count)
315
+
316
+
317
+ def inspect_dataset(
318
+ data_cfg,
319
+ data_name: str,
320
+ robot_type: str,
321
+ args: argparse.Namespace,
322
+ future_offsets: list[int],
323
+ rng: random.Random,
324
+ csv_writer,
325
+ ) -> dict[str, Any]:
326
+ dataset = make_LeRobotSingleDataset(
327
+ Path(args.data_root_dir),
328
+ data_name,
329
+ robot_type,
330
+ delete_pause_frame=data_cfg.get("delete_pause_frame", False),
331
+ data_cfg=data_cfg,
332
+ )
333
+ chosen_steps = choose_steps(dataset, args.samples_per_dataset, rng)
334
+ dataset_summary: dict[str, Any] = {
335
+ "data_name": data_name,
336
+ "robot_type": robot_type,
337
+ "dataset_path": str(dataset.dataset_path),
338
+ "num_trajectories": int(len(dataset.trajectory_ids)),
339
+ "num_valid_steps": int(len(dataset.all_steps)),
340
+ "num_checked_steps": int(len(chosen_steps)),
341
+ "views": {},
342
+ }
343
+ view_stats: dict[str, dict[str, list[float]]] = defaultdict(lambda: defaultdict(list))
344
+ frozen_counts: dict[str, int] = defaultdict(int)
345
+ pair_counts: dict[str, int] = defaultdict(int)
346
+ out_dir = Path(args.out_dir)
347
+ saved_sheets = 0
348
+ video_timestamp_cache: dict[Path, np.ndarray] = {}
349
+ video_ratio_frame_cache: dict[tuple[Path, tuple[int, ...]], list[np.ndarray]] = {}
350
+
351
+ for sample_idx, (trajectory_id, step) in enumerate(chosen_steps):
352
+ raw_data = dataset.get_step_data(trajectory_id, step)
353
+ trajectory_index = dataset.get_trajectory_index(trajectory_id)
354
+ trajectory_length = int(dataset.trajectory_lengths[trajectory_index])
355
+ action = concat_raw_action(raw_data, dataset.modality_keys.get("action", []))
356
+ action_mean_l2 = float(np.mean(np.linalg.norm(action, axis=1))) if action is not None else float("nan")
357
+ action_max_l2 = float(np.max(np.linalg.norm(action, axis=1))) if action is not None else float("nan")
358
+
359
+ for video_key in dataset.modality_keys["video"]:
360
+ frames = []
361
+ offsets = [0] + future_offsets
362
+ frame_indices = [step + offset for offset in offsets]
363
+ timestamps = dataset.curr_traj_data["timestamp"].to_numpy()[frame_indices]
364
+ video_path = dataset.get_video_path(trajectory_id, video_key.replace("video.", ""))
365
+ mapped_video_indices = None
366
+ mapped_video_timestamps = None
367
+ ratio_video_indices = None
368
+ ratio_frames = None
369
+ video_num_frames = None
370
+ video_duration = None
371
+ timestamps_in_video_range = None
372
+ if not args.skip_video_timestamp_map:
373
+ try:
374
+ if video_path not in video_timestamp_cache:
375
+ video_timestamp_cache[video_path] = get_video_frame_timestamps(video_path)
376
+ video_timestamps = video_timestamp_cache[video_path]
377
+ video_num_frames = int(len(video_timestamps))
378
+ video_duration = float(video_timestamps[-1] - video_timestamps[0]) if len(video_timestamps) > 1 else 0.0
379
+ timestamps_in_video_range = bool(
380
+ np.min(timestamps) >= video_timestamps[0] and np.max(timestamps) <= video_timestamps[-1]
381
+ )
382
+ mapped_video_indices = nearest_video_frame_indices(video_timestamps, timestamps)
383
+ mapped_video_timestamps = video_timestamps[mapped_video_indices]
384
+ ratio_video_indices = proportional_video_indices(frame_indices, trajectory_length, len(video_timestamps))
385
+ ratio_key = (video_path, tuple(int(index) for index in ratio_video_indices))
386
+ if ratio_key not in video_ratio_frame_cache:
387
+ video_ratio_frame_cache[ratio_key] = get_video_frames_by_indices_pyav(video_path, ratio_video_indices)
388
+ ratio_frames = video_ratio_frame_cache[ratio_key]
389
+ except Exception as exc:
390
+ print(
391
+ f"Warning: video index diagnosis failed for {data_name} "
392
+ f"traj={trajectory_id} step={step} {video_key}: {exc}",
393
+ flush=True,
394
+ )
395
+ labels = []
396
+ for offset in offsets:
397
+ frame = dataset.get_video(trajectory_id, video_key, step + offset)
398
+ frames.append(image_to_uint8_rgb(frame))
399
+ labels.append(f"t+{offset}")
400
+ backend_compare_frames: dict[str, list[np.ndarray]] = {}
401
+ for compare_backend in parse_str_list(args.compare_video_backends):
402
+ try:
403
+ compare_frames = get_frames_by_timestamps(
404
+ video_path.as_posix(),
405
+ timestamps,
406
+ video_backend=compare_backend,
407
+ video_backend_kwargs={},
408
+ )
409
+ backend_compare_frames[compare_backend] = [image_to_uint8_rgb(frame) for frame in compare_frames]
410
+ except Exception as exc:
411
+ print(
412
+ f"Warning: backend compare failed for {compare_backend} on {data_name} "
413
+ f"traj={trajectory_id} step={step} {video_key}: {exc}",
414
+ flush=True,
415
+ )
416
+
417
+ metrics_vs_prev = []
418
+ metrics_vs_t0 = []
419
+ for pair_idx in range(1, len(frames)):
420
+ prev_metrics = frame_diff_metrics(frames[pair_idx - 1], frames[pair_idx], args.changed_pixel_threshold)
421
+ t0_metrics = frame_diff_metrics(frames[0], frames[pair_idx], args.changed_pixel_threshold)
422
+ ratio_prev_metrics = None
423
+ ratio_t0_metrics = None
424
+ if ratio_frames is not None and pair_idx < len(ratio_frames):
425
+ ratio_prev_metrics = frame_diff_metrics(
426
+ ratio_frames[pair_idx - 1], ratio_frames[pair_idx], args.changed_pixel_threshold
427
+ )
428
+ ratio_t0_metrics = frame_diff_metrics(ratio_frames[0], ratio_frames[pair_idx], args.changed_pixel_threshold)
429
+ metrics_vs_prev.append(prev_metrics)
430
+ metrics_vs_t0.append(t0_metrics)
431
+ pair_counts[video_key] += 1
432
+ for name, value in prev_metrics.items():
433
+ view_stats[video_key][f"prev_{name}"].append(value)
434
+ for name, value in t0_metrics.items():
435
+ view_stats[video_key][f"t0_{name}"].append(value)
436
+ if prev_metrics["changed_pixel_ratio"] < args.frozen_ratio_threshold:
437
+ frozen_counts[video_key] += 1
438
+
439
+ csv_writer.writerow(
440
+ {
441
+ "dataset": data_name,
442
+ "robot_type": robot_type,
443
+ "trajectory_id": trajectory_id,
444
+ "step": step,
445
+ "video_key": video_key,
446
+ "offset_from": offsets[pair_idx - 1],
447
+ "offset_to": offsets[pair_idx],
448
+ "frame_index_from": frame_indices[pair_idx - 1],
449
+ "frame_index_to": frame_indices[pair_idx],
450
+ "trajectory_length": trajectory_length,
451
+ "timestamp_from": float(timestamps[pair_idx - 1]),
452
+ "timestamp_to": float(timestamps[pair_idx]),
453
+ "timestamp_delta": float(timestamps[pair_idx] - timestamps[pair_idx - 1]),
454
+ "video_path": str(video_path),
455
+ "video_num_frames": video_num_frames if video_num_frames is not None else "",
456
+ "video_duration": video_duration if video_duration is not None else "",
457
+ "timestamps_in_video_range": timestamps_in_video_range if timestamps_in_video_range is not None else "",
458
+ "video_frame_index_from": int(mapped_video_indices[pair_idx - 1])
459
+ if mapped_video_indices is not None
460
+ else "",
461
+ "video_frame_index_to": int(mapped_video_indices[pair_idx])
462
+ if mapped_video_indices is not None
463
+ else "",
464
+ "video_timestamp_from": float(mapped_video_timestamps[pair_idx - 1])
465
+ if mapped_video_timestamps is not None
466
+ else "",
467
+ "video_timestamp_to": float(mapped_video_timestamps[pair_idx])
468
+ if mapped_video_timestamps is not None
469
+ else "",
470
+ "video_frame_index_delta": int(mapped_video_indices[pair_idx] - mapped_video_indices[pair_idx - 1])
471
+ if mapped_video_indices is not None
472
+ else "",
473
+ "ratio_video_frame_index_from": int(ratio_video_indices[pair_idx - 1])
474
+ if ratio_video_indices is not None
475
+ else "",
476
+ "ratio_video_frame_index_to": int(ratio_video_indices[pair_idx])
477
+ if ratio_video_indices is not None
478
+ else "",
479
+ "ratio_video_frame_index_delta": int(ratio_video_indices[pair_idx] - ratio_video_indices[pair_idx - 1])
480
+ if ratio_video_indices is not None
481
+ else "",
482
+ "prev_mae": prev_metrics["mae"],
483
+ "prev_changed_pixel_ratio": prev_metrics["changed_pixel_ratio"],
484
+ "t0_mae": t0_metrics["mae"],
485
+ "t0_changed_pixel_ratio": t0_metrics["changed_pixel_ratio"],
486
+ "ratio_prev_mae": ratio_prev_metrics["mae"] if ratio_prev_metrics is not None else "",
487
+ "ratio_prev_changed_pixel_ratio": ratio_prev_metrics["changed_pixel_ratio"]
488
+ if ratio_prev_metrics is not None
489
+ else "",
490
+ "ratio_t0_mae": ratio_t0_metrics["mae"] if ratio_t0_metrics is not None else "",
491
+ "ratio_t0_changed_pixel_ratio": ratio_t0_metrics["changed_pixel_ratio"]
492
+ if ratio_t0_metrics is not None
493
+ else "",
494
+ "action_mean_l2": action_mean_l2,
495
+ "action_max_l2": action_max_l2,
496
+ }
497
+ )
498
+
499
+ if saved_sheets < args.max_contact_sheets:
500
+ safe_name = data_name.replace("/", "__").replace("..", "dotdot")
501
+ safe_view = video_key.replace(".", "_").replace("/", "_")
502
+ visual_frames, visual_labels = select_visual_frames(frames, labels, args.show_all_frames)
503
+ sheet_path = out_dir / "contact_sheets" / safe_name / (
504
+ f"{sample_idx:04d}_traj{trajectory_id}_step{step}_{safe_view}.jpg"
505
+ )
506
+ save_contact_sheet(visual_frames, visual_labels, sheet_path)
507
+ compare_rows = [(f"loader_{args.video_backend}", visual_frames)]
508
+ for compare_backend, compare_frames in backend_compare_frames.items():
509
+ compare_visual_frames, _ = select_visual_frames(compare_frames, labels, args.show_all_frames)
510
+ compare_rows.append((f"backend_{compare_backend}", compare_visual_frames))
511
+ if ratio_frames is not None:
512
+ ratio_visual_frames, _ = select_visual_frames(ratio_frames, labels, args.show_all_frames)
513
+ compare_rows.append(("ratio_idx", ratio_visual_frames))
514
+ compare_sheet_path = out_dir / "contact_sheets_compare" / safe_name / (
515
+ f"{sample_idx:04d}_traj{trajectory_id}_step{step}_{safe_view}.jpg"
516
+ )
517
+ save_comparison_contact_sheet(compare_rows, visual_labels, compare_sheet_path)
518
+ saved_sheets += 1
519
+
520
+ for video_key, stats in view_stats.items():
521
+ frozen_pairs = frozen_counts[video_key]
522
+ total_pairs = pair_counts[video_key]
523
+ dataset_summary["views"][video_key] = {
524
+ "pair_count": total_pairs,
525
+ "frozen_pair_count": frozen_pairs,
526
+ "frozen_pair_ratio": float(frozen_pairs / total_pairs) if total_pairs else None,
527
+ "mean_prev_changed_pixel_ratio": float(np.mean(stats["prev_changed_pixel_ratio"]))
528
+ if stats["prev_changed_pixel_ratio"]
529
+ else None,
530
+ "median_prev_changed_pixel_ratio": float(np.median(stats["prev_changed_pixel_ratio"]))
531
+ if stats["prev_changed_pixel_ratio"]
532
+ else None,
533
+ "mean_t0_changed_pixel_ratio": float(np.mean(stats["t0_changed_pixel_ratio"]))
534
+ if stats["t0_changed_pixel_ratio"]
535
+ else None,
536
+ "median_t0_changed_pixel_ratio": float(np.median(stats["t0_changed_pixel_ratio"]))
537
+ if stats["t0_changed_pixel_ratio"]
538
+ else None,
539
+ "mean_prev_mae": float(np.mean(stats["prev_mae"])) if stats["prev_mae"] else None,
540
+ "median_prev_mae": float(np.median(stats["prev_mae"])) if stats["prev_mae"] else None,
541
+ "mean_t0_mae": float(np.mean(stats["t0_mae"])) if stats["t0_mae"] else None,
542
+ "median_t0_mae": float(np.median(stats["t0_mae"])) if stats["t0_mae"] else None,
543
+ }
544
+ return dataset_summary
545
+
546
+
547
+ def main() -> None:
548
+ args = parse_args()
549
+ future_offsets = parse_int_list(args.future_video_delta_indices)
550
+ robot_types = {item.strip() for item in args.robot_types.split(",") if item.strip()}
551
+ if not future_offsets:
552
+ raise ValueError("--future-video-delta-indices must not be empty")
553
+ if args.data_mix not in DATASET_NAMED_MIXTURES:
554
+ raise KeyError(f"Unknown data mix {args.data_mix!r}. Available keys include: {list(DATASET_NAMED_MIXTURES)[:10]}")
555
+
556
+ data_cfg = build_data_cfg(args, future_offsets)
557
+ rng = random.Random(args.seed)
558
+ out_dir = Path(args.out_dir)
559
+ out_dir.mkdir(parents=True, exist_ok=True)
560
+
561
+ mixture_entries = [
562
+ (data_name, weight, robot_type)
563
+ for data_name, weight, robot_type in DATASET_NAMED_MIXTURES[args.data_mix]
564
+ if "all" in robot_types or robot_type in robot_types
565
+ ]
566
+ if not mixture_entries:
567
+ raise ValueError(f"No entries in data_mix={args.data_mix!r} matched robot_types={sorted(robot_types)}")
568
+
569
+ summary = {
570
+ "config_yaml": str(args.config_yaml),
571
+ "data_root_dir": args.data_root_dir,
572
+ "data_mix": args.data_mix,
573
+ "video_backend": args.video_backend,
574
+ "future_video_delta_indices": future_offsets,
575
+ "changed_pixel_threshold": args.changed_pixel_threshold,
576
+ "frozen_ratio_threshold": args.frozen_ratio_threshold,
577
+ "datasets": [],
578
+ }
579
+
580
+ csv_path = out_dir / "frame_diff_rows.csv"
581
+ with csv_path.open("w", newline="") as csv_file:
582
+ fieldnames = [
583
+ "dataset",
584
+ "robot_type",
585
+ "trajectory_id",
586
+ "step",
587
+ "video_key",
588
+ "offset_from",
589
+ "offset_to",
590
+ "frame_index_from",
591
+ "frame_index_to",
592
+ "trajectory_length",
593
+ "timestamp_from",
594
+ "timestamp_to",
595
+ "timestamp_delta",
596
+ "video_path",
597
+ "video_num_frames",
598
+ "video_duration",
599
+ "timestamps_in_video_range",
600
+ "video_frame_index_from",
601
+ "video_frame_index_to",
602
+ "video_timestamp_from",
603
+ "video_timestamp_to",
604
+ "video_frame_index_delta",
605
+ "ratio_video_frame_index_from",
606
+ "ratio_video_frame_index_to",
607
+ "ratio_video_frame_index_delta",
608
+ "prev_mae",
609
+ "prev_changed_pixel_ratio",
610
+ "t0_mae",
611
+ "t0_changed_pixel_ratio",
612
+ "ratio_prev_mae",
613
+ "ratio_prev_changed_pixel_ratio",
614
+ "ratio_t0_mae",
615
+ "ratio_t0_changed_pixel_ratio",
616
+ "action_mean_l2",
617
+ "action_max_l2",
618
+ ]
619
+ writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
620
+ writer.writeheader()
621
+ for data_name, _weight, robot_type in mixture_entries:
622
+ print(f"\n=== Checking {robot_type}: {data_name} ===", flush=True)
623
+ dataset_summary = inspect_dataset(data_cfg, data_name, robot_type, args, future_offsets, rng, writer)
624
+ summary["datasets"].append(dataset_summary)
625
+ for view_key, view_summary in dataset_summary["views"].items():
626
+ print(
627
+ f"{view_key}: frozen_pair_ratio={view_summary['frozen_pair_ratio']:.4f}, "
628
+ f"mean_prev_changed={view_summary['mean_prev_changed_pixel_ratio']:.4f}, "
629
+ f"mean_t0_changed={view_summary['mean_t0_changed_pixel_ratio']:.4f}",
630
+ flush=True,
631
+ )
632
+
633
+ summary_path = out_dir / "summary.json"
634
+ summary_path.write_text(json.dumps(summary, indent=2), encoding="utf-8")
635
+ print(f"\nWrote summary: {summary_path}")
636
+ print(f"Wrote per-pair rows: {csv_path}")
637
+ print(f"Wrote contact sheets under: {out_dir / 'contact_sheets'}")
638
+ print(f"Wrote loader-vs-index contact sheets under: {out_dir / 'contact_sheets_compare'}")
639
+
640
+
641
+ if __name__ == "__main__":
642
+ main()
scripts/cosmos25_image_to_video_compare.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Generate a Cosmos-Predict2.5 video from current image(s) and compare with GT.
3
+
4
+ Example:
5
+ python scripts/cosmos25_image_to_video_compare.py \
6
+ --model-path /path/to/Cosmos-Predict2.5-2B-Post-Trained \
7
+ --image current.png \
8
+ --instruction "pick up the mug and place it on the plate" \
9
+ --gt gt.mp4 \
10
+ --out-dir outputs/cosmos25_debug
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import json
17
+ import os
18
+ from pathlib import Path
19
+ from typing import Iterable
20
+
21
+
22
+ class _DisabledCosmosSafetyChecker:
23
+ """No-op safety checker for local robot data visualization."""
24
+
25
+ def to(self, *args, **kwargs):
26
+ return self
27
+
28
+ def check_text_safety(self, *args, **kwargs):
29
+ return True
30
+
31
+ def check_video_safety(self, video, *args, **kwargs):
32
+ return video
33
+
34
+
35
+ def parse_args() -> argparse.Namespace:
36
+ parser = argparse.ArgumentParser(description=__doc__)
37
+ parser.add_argument("--model-path", required=True, help="HF repo id or local diffusers-format Cosmos2.5 checkpoint.")
38
+ parser.add_argument("--revision", default="diffusers/base/post-trained", help="HF revision. Ignored for local paths.")
39
+ parser.add_argument("--image", nargs="+", required=True, help="Current image path(s). One image uses image conditioning; multiple images use video conditioning.")
40
+ parser.add_argument("--instruction", required=True, help="Language instruction, or @path/to/file.txt.")
41
+ parser.add_argument("--gt", default=None, help="Optional GT image/video path for side-by-side comparison.")
42
+ parser.add_argument("--out-dir", default="outputs/cosmos25_image_to_video_compare", help="Directory for generated artifacts.")
43
+ parser.add_argument("--height", type=int, default=704)
44
+ parser.add_argument("--width", type=int, default=1280)
45
+ parser.add_argument("--num-frames", type=int, default=93)
46
+ parser.add_argument("--num-inference-steps", type=int, default=36)
47
+ parser.add_argument("--guidance-scale", type=float, default=7.0)
48
+ parser.add_argument("--fps", type=int, default=16)
49
+ parser.add_argument("--seed", type=int, default=0)
50
+ parser.add_argument("--negative-prompt", default=None)
51
+ parser.add_argument("--max-sequence-length", type=int, default=512)
52
+ parser.add_argument("--conditional-frame-timestep", type=float, default=0.1)
53
+ parser.add_argument("--num-latent-conditional-frames", type=int, default=2)
54
+ parser.add_argument("--dtype", choices=("bf16", "fp16", "fp32"), default="bf16")
55
+ parser.add_argument("--device", default="cuda", help="Usually cuda. Use cpu only for very small smoke tests.")
56
+ parser.add_argument("--cpu-offload", action="store_true", help="Use diffusers CPU offload instead of moving the full pipe to CUDA.")
57
+ parser.add_argument("--enable-safety-checker", action="store_true", help="Keep the Cosmos text/video safety checker enabled.")
58
+ return parser.parse_args()
59
+
60
+
61
+ def read_instruction(value: str) -> str:
62
+ if value.startswith("@"):
63
+ return Path(value[1:]).read_text(encoding="utf-8").strip()
64
+ return value
65
+
66
+
67
+ def load_image(path: str) -> Image.Image:
68
+ Image, _, _ = require_pil()
69
+ return Image.open(path).convert("RGB")
70
+
71
+
72
+ def require_torch():
73
+ try:
74
+ import torch
75
+ except ImportError as exc:
76
+ raise ImportError("This script needs torch installed to run Cosmos generation.") from exc
77
+ return torch
78
+
79
+
80
+ def maybe_torch():
81
+ try:
82
+ import torch
83
+ except ImportError:
84
+ return None
85
+ return torch
86
+
87
+
88
+ def require_av():
89
+ try:
90
+ import av
91
+ except ImportError as exc:
92
+ raise ImportError("This script needs av installed to read/write videos. Install requirements.txt first.") from exc
93
+ return av
94
+
95
+
96
+ def require_numpy():
97
+ try:
98
+ import numpy as np
99
+ except ImportError as exc:
100
+ raise ImportError("This script needs numpy installed. Install requirements.txt first.") from exc
101
+ return np
102
+
103
+
104
+ def require_pil():
105
+ try:
106
+ from PIL import Image, ImageDraw, ImageFont
107
+ except ImportError as exc:
108
+ raise ImportError("This script needs pillow installed. Install requirements.txt first.") from exc
109
+ return Image, ImageDraw, ImageFont
110
+
111
+
112
+ def to_uint8_image(frame) -> Image.Image:
113
+ Image, _, _ = require_pil()
114
+ if isinstance(frame, Image.Image):
115
+ return frame.convert("RGB")
116
+
117
+ np = require_numpy()
118
+ torch = maybe_torch()
119
+ if torch is not None and torch.is_tensor(frame):
120
+ array = frame.detach().float().cpu().numpy()
121
+ else:
122
+ array = np.asarray(frame)
123
+
124
+ if array.ndim == 3 and array.shape[0] in (1, 3) and array.shape[-1] not in (1, 3):
125
+ array = np.transpose(array, (1, 2, 0))
126
+ if array.dtype != np.uint8:
127
+ if array.size and array.min() >= -1.0 and array.max() <= 1.0:
128
+ array = (array + 1.0) * 127.5
129
+ elif array.size and array.min() >= 0.0 and array.max() <= 1.0:
130
+ array = array * 255.0
131
+ array = np.clip(array, 0, 255).astype(np.uint8)
132
+ if array.ndim == 2:
133
+ array = np.repeat(array[..., None], 3, axis=-1)
134
+ if array.shape[-1] == 1:
135
+ array = np.repeat(array, 3, axis=-1)
136
+ return Image.fromarray(array[..., :3]).convert("RGB")
137
+
138
+
139
+ def normalize_generated_frames(output) -> list[Image.Image]:
140
+ np = require_numpy()
141
+ torch = maybe_torch()
142
+ videos = getattr(output, "frames", None)
143
+ if videos is None:
144
+ videos = getattr(output, "videos", None)
145
+ if videos is None:
146
+ videos = getattr(output, "images", None)
147
+ if videos is None and isinstance(output, tuple):
148
+ videos = output[0]
149
+ if videos is None:
150
+ videos = output
151
+
152
+ if torch is not None and torch.is_tensor(videos):
153
+ videos = videos.detach().cpu()
154
+ if videos.ndim == 5:
155
+ videos = videos[0]
156
+ return [to_uint8_image(frame) for frame in videos]
157
+
158
+ if isinstance(videos, np.ndarray):
159
+ if videos.ndim == 5:
160
+ videos = videos[0]
161
+ return [to_uint8_image(frame) for frame in videos]
162
+
163
+ if isinstance(videos, (list, tuple)) and videos:
164
+ first = videos[0]
165
+ if isinstance(first, (list, tuple)):
166
+ return [to_uint8_image(frame) for frame in first]
167
+ if torch is not None and torch.is_tensor(first) and first.ndim >= 4:
168
+ return [to_uint8_image(frame) for frame in first]
169
+ if isinstance(first, np.ndarray) and first.ndim >= 4:
170
+ return [to_uint8_image(frame) for frame in first]
171
+ return [to_uint8_image(frame) for frame in videos]
172
+
173
+ raise ValueError("Could not extract frames from Cosmos generation output.")
174
+
175
+
176
+ def read_video(path: Path) -> list[Image.Image]:
177
+ Image, _, _ = require_pil()
178
+ av = require_av()
179
+ frames: list[Image.Image] = []
180
+ with av.open(str(path)) as container:
181
+ stream = container.streams.video[0]
182
+ for frame in container.decode(stream):
183
+ frames.append(frame.to_image().convert("RGB"))
184
+ if not frames:
185
+ raise ValueError(f"No video frames decoded from {path}.")
186
+ return frames
187
+
188
+
189
+ def read_gt(path: str, target_len: int) -> list[Image.Image]:
190
+ np = require_numpy()
191
+ gt_path = Path(path)
192
+ suffix = gt_path.suffix.lower()
193
+ if suffix in {".png", ".jpg", ".jpeg", ".bmp", ".webp"}:
194
+ frame = load_image(str(gt_path))
195
+ return [frame.copy() for _ in range(target_len)]
196
+
197
+ frames = read_video(gt_path)
198
+ if len(frames) == target_len:
199
+ return frames
200
+ if len(frames) == 1:
201
+ return [frames[0].copy() for _ in range(target_len)]
202
+
203
+ # Resample by nearest index so comparison stays aligned even when FPS/count differs.
204
+ indices = np.linspace(0, len(frames) - 1, target_len).round().astype(int)
205
+ return [frames[int(i)] for i in indices]
206
+
207
+
208
+ def save_video(frames: Iterable[Image.Image], path: Path, fps: int) -> None:
209
+ require_av()
210
+ frames = [frame.convert("RGB") for frame in frames]
211
+ if not frames:
212
+ raise ValueError(f"No frames to save for {path}.")
213
+
214
+ width, height = frames[0].size
215
+ encoded_width = width + (width % 2)
216
+ encoded_height = height + (height % 2)
217
+ path.parent.mkdir(parents=True, exist_ok=True)
218
+ try:
219
+ _save_video_with_codec(frames, path, fps, "h264", encoded_width, encoded_height)
220
+ except Exception:
221
+ _save_video_with_codec(frames, path, fps, "mpeg4", encoded_width, encoded_height)
222
+
223
+
224
+ def _save_video_with_codec(
225
+ frames: list[Image.Image],
226
+ path: Path,
227
+ fps: int,
228
+ codec: str,
229
+ encoded_width: int,
230
+ encoded_height: int,
231
+ ) -> None:
232
+ av = require_av()
233
+ with av.open(str(path), mode="w") as container:
234
+ stream = container.add_stream(codec, rate=fps)
235
+ stream.width = encoded_width
236
+ stream.height = encoded_height
237
+ stream.pix_fmt = "yuv420p"
238
+ for frame in frames:
239
+ if frame.size != (encoded_width, encoded_height):
240
+ canvas = Image.new("RGB", (encoded_width, encoded_height))
241
+ canvas.paste(frame, (0, 0))
242
+ frame = canvas
243
+ video_frame = av.VideoFrame.from_image(frame)
244
+ for packet in stream.encode(video_frame):
245
+ container.mux(packet)
246
+ for packet in stream.encode():
247
+ container.mux(packet)
248
+
249
+
250
+ def labelled(frame: Image.Image, label: str) -> Image.Image:
251
+ _, ImageDraw, ImageFont = require_pil()
252
+ frame = frame.convert("RGB")
253
+ draw = ImageDraw.Draw(frame)
254
+ font = ImageFont.load_default()
255
+ try:
256
+ bbox = draw.textbbox((0, 0), label, font=font)
257
+ text_w, text_h = bbox[2] - bbox[0], bbox[3] - bbox[1]
258
+ except AttributeError:
259
+ text_w, text_h = draw.textsize(label, font=font)
260
+ pad = 8
261
+ draw.rectangle((0, 0, text_w + pad * 2, text_h + pad * 2), fill=(0, 0, 0))
262
+ draw.text((pad, pad), label, fill=(255, 255, 255), font=font)
263
+ return frame
264
+
265
+
266
+ def make_compare_frames(pred_frames: list[Image.Image], gt_frames: list[Image.Image] | None) -> list[Image.Image]:
267
+ Image, _, _ = require_pil()
268
+ if gt_frames is None:
269
+ return pred_frames
270
+
271
+ compare_frames = []
272
+ for pred, gt in zip(pred_frames, gt_frames):
273
+ gt = gt.resize(pred.size, Image.BILINEAR)
274
+ canvas = Image.new("RGB", (pred.width * 2, pred.height))
275
+ canvas.paste(labelled(gt.copy(), "GT"), (0, 0))
276
+ canvas.paste(labelled(pred.copy(), "Cosmos"), (pred.width, 0))
277
+ compare_frames.append(canvas)
278
+ return compare_frames
279
+
280
+
281
+ def main() -> None:
282
+ args = parse_args()
283
+ out_dir = Path(args.out_dir)
284
+ out_dir.mkdir(parents=True, exist_ok=True)
285
+
286
+ if not args.enable_safety_checker:
287
+ from diffusers.pipelines.cosmos import pipeline_cosmos2_5_predict
288
+
289
+ pipeline_cosmos2_5_predict.CosmosSafetyChecker = _DisabledCosmosSafetyChecker
290
+
291
+ from diffusers import Cosmos2_5_PredictBasePipeline
292
+
293
+ torch = require_torch()
294
+ dtype = {"bf16": torch.bfloat16, "fp16": torch.float16, "fp32": torch.float32}[args.dtype]
295
+ load_kwargs = {"torch_dtype": dtype}
296
+ if args.revision and not os.path.isdir(args.model_path):
297
+ load_kwargs["revision"] = args.revision
298
+
299
+ pipe = Cosmos2_5_PredictBasePipeline.from_pretrained(args.model_path, **load_kwargs)
300
+ if args.cpu_offload:
301
+ pipe.enable_model_cpu_offload()
302
+ else:
303
+ pipe.to(args.device)
304
+
305
+ images = [load_image(path) for path in args.image]
306
+ instruction = read_instruction(args.instruction)
307
+ generator = torch.Generator(device=args.device if args.device.startswith("cuda") else "cpu").manual_seed(args.seed)
308
+
309
+ generation_kwargs = {
310
+ "prompt": instruction,
311
+ "height": args.height,
312
+ "width": args.width,
313
+ "num_frames": args.num_frames,
314
+ "num_inference_steps": args.num_inference_steps,
315
+ "guidance_scale": args.guidance_scale,
316
+ "return_dict": True,
317
+ "output_type": "pil",
318
+ "max_sequence_length": args.max_sequence_length,
319
+ "conditional_frame_timestep": args.conditional_frame_timestep,
320
+ "num_latent_conditional_frames": args.num_latent_conditional_frames,
321
+ "generator": generator,
322
+ }
323
+ if args.negative_prompt:
324
+ generation_kwargs["negative_prompt"] = args.negative_prompt
325
+ if len(images) == 1:
326
+ generation_kwargs["image"] = images[0]
327
+ else:
328
+ generation_kwargs["video"] = images
329
+
330
+ with torch.inference_mode():
331
+ output = pipe(**generation_kwargs)
332
+
333
+ pred_frames = normalize_generated_frames(output)
334
+ gt_frames = read_gt(args.gt, len(pred_frames)) if args.gt else None
335
+ compare_frames = make_compare_frames(pred_frames, gt_frames)
336
+
337
+ pred_path = out_dir / "pred.mp4"
338
+ compare_path = out_dir / "compare.mp4"
339
+ last_path = out_dir / "last_frame_compare.png"
340
+ meta_path = out_dir / "run_args.json"
341
+
342
+ save_video(pred_frames, pred_path, args.fps)
343
+ save_video(compare_frames, compare_path, args.fps)
344
+ compare_frames[-1].save(last_path)
345
+ meta_path.write_text(json.dumps(vars(args), indent=2, ensure_ascii=False), encoding="utf-8")
346
+
347
+ print(f"Saved prediction video: {pred_path}")
348
+ print(f"Saved comparison video: {compare_path}")
349
+ print(f"Saved last-frame comparison: {last_path}")
350
+
351
+
352
+ if __name__ == "__main__":
353
+ main()
scripts/rsync_push.sh ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # 固定远程主机地址
4
+ REMOTE_HOST="root@6.178.134.136"
5
+
6
+ # 固定远程 W&B 根目录;传入第二个参数可覆盖该默认值。
7
+ DEFAULT_REMOTE_ROOT="/mnt/workspace/users/yuanzhihao/wandb"
8
+
9
+ # 固定 W&B API key;运行前设置 WANDB_API_KEY 可覆盖该默认值。
10
+ DEFAULT_WANDB_API_KEY="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"
11
+
12
+ # 检查参数数量
13
+ if [ $# -lt 1 ] || [ $# -gt 2 ]; then
14
+ echo "用法: $0 <本地wandb run路径> [远程wandb根目录]"
15
+ echo "示例: $0 outputs/exp_name/task_name/wandb/wandb/latest-run/"
16
+ echo "示例: $0 outputs/exp_name/task_name/wandb/wandb/latest-run/ /mnt/workspace/users/yuanzhihao/wandb/"
17
+ exit 1
18
+ fi
19
+
20
+ # 提取参数
21
+ LOCAL_SOURCE="$1"
22
+ REMOTE_ROOT="${2:-$DEFAULT_REMOTE_ROOT}"
23
+ REMOTE_ROOT="${REMOTE_ROOT%/}"
24
+
25
+ # 如果传入的是 latest-run 软链接目录,自动补上末尾 /,同步真实目录内容而不是链接本身。
26
+ if [ -L "$LOCAL_SOURCE" ] && [ -d "$LOCAL_SOURCE" ] && [[ "$LOCAL_SOURCE" != */ ]]; then
27
+ LOCAL_SOURCE="${LOCAL_SOURCE}/"
28
+ fi
29
+
30
+ # 从 outputs/exp/task/wandb/wandb/latest-run/ 自动推导远程目录:
31
+ # /remote/wandb/exp/task/
32
+ REMOTE_SUBDIR=""
33
+ SOURCE_PREFIX="${LOCAL_SOURCE%%/wandb/wandb/*}"
34
+ if [[ "$SOURCE_PREFIX" != "$LOCAL_SOURCE" ]]; then
35
+ REMOTE_SUBDIR="${SOURCE_PREFIX#outputs/}"
36
+ REMOTE_SUBDIR="${REMOTE_SUBDIR#/}"
37
+ fi
38
+
39
+ if [ -n "$REMOTE_SUBDIR" ]; then
40
+ REMOTE_DEST="${REMOTE_ROOT}/${REMOTE_SUBDIR}/"
41
+ else
42
+ REMOTE_DEST="${REMOTE_ROOT}/"
43
+ fi
44
+
45
+ # 执行rsync命令
46
+ echo "开始传输:${LOCAL_SOURCE} -> ${REMOTE_HOST}:${REMOTE_DEST}"
47
+ rsync -avz --progress --rsync-path="mkdir -p '${REMOTE_DEST}' && rsync" "${LOCAL_SOURCE}" "${REMOTE_HOST}:${REMOTE_DEST}"
48
+
49
+ # 检查传输结果
50
+ if [ $? -eq 0 ]; then
51
+ echo "传输成功!"
52
+ else
53
+ echo "传输失败!"
54
+ exit 1
55
+ fi
56
+
57
+ # 检查 W&B 登录状态。优先使用当前环境里的 WANDB_API_KEY,否则使用脚本内置 key。
58
+ echo "检查远程wandb登录状态:${REMOTE_HOST}"
59
+ if [ -n "${WANDB_API_KEY:-}" ] || [ -n "${DEFAULT_WANDB_API_KEY}" ]; then
60
+ EFFECTIVE_WANDB_API_KEY="${WANDB_API_KEY:-$DEFAULT_WANDB_API_KEY}"
61
+ REMOTE_WANDB_ENV="WANDB_API_KEY='${EFFECTIVE_WANDB_API_KEY}'"
62
+ elif ssh "${REMOTE_HOST}" "wandb status | grep -q '\"api_key\": null'"; then
63
+ echo "远程wandb未登录,请先在远程机器执行:wandb login --relogin"
64
+ echo "或在本机运行:WANDB_API_KEY=<你的key> $0 <本地wandb run路径> <远程wandb根目录>"
65
+ exit 1
66
+ else
67
+ REMOTE_WANDB_ENV=""
68
+ fi
69
+
70
+ # 在远程机器上同步到 W&B
71
+ echo "开始同步wandb:${REMOTE_HOST}:${REMOTE_DEST}"
72
+ SYNC_OUTPUT=$(ssh "${REMOTE_HOST}" "${REMOTE_WANDB_ENV} REMOTE_DEST='${REMOTE_DEST}' bash -lc '
73
+ set -e
74
+ shopt -s nullglob
75
+ sync_targets=()
76
+
77
+ for run_dir in \"\${REMOTE_DEST}\"/offline-run-* \"\${REMOTE_DEST}\"/run-*; do
78
+ if [ -d \"\${run_dir}\" ]; then
79
+ sync_targets+=(\"\${run_dir}\")
80
+ fi
81
+ done
82
+
83
+ if [ \${#sync_targets[@]} -eq 0 ]; then
84
+ sync_targets=(\"\${REMOTE_DEST}\")
85
+ fi
86
+
87
+ for sync_target in \"\${sync_targets[@]}\"; do
88
+ echo \"wandb sync \${sync_target}\"
89
+ wandb sync \"\${sync_target}\"
90
+ done
91
+ '" 2>&1)
92
+ SYNC_STATUS=$?
93
+ echo "${SYNC_OUTPUT}"
94
+
95
+ # 检查同步结果
96
+ if [ $SYNC_STATUS -eq 0 ] && ! echo "${SYNC_OUTPUT}" | grep -Eq "wandb: ERROR|Traceback|Exception|AssertionError|RuntimeError"; then
97
+ echo "wandb同步成功!"
98
+ else
99
+ echo "wandb同步失败!"
100
+ exit 1
101
+ fi
scripts/run_scripts/Robocasa/run_lerobot_datasets_qwenGR00T.sh ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export NCCL_SOCKET_IFNAME=bond0
2
+ export NCCL_IB_HCA=mlx5_2,mlx5_3
3
+
4
+ # used for check save when communication
5
+ export NCCL_BLOCKING_WAIT=1
6
+ export NCCL_ASYNC_ERROR_HANDLING=1
7
+ export NCCL_TIMEOUT=1000 # timeout set to 1 hour (unit: seconds)
8
+
9
+
10
+ Framework_name=QwenGR00T
11
+ base_vlm=./playground/Pretrained_models/Qwen3-VL-4B-Instruct
12
+
13
+ freeze_module_list='' # just for fast debug, sota is under fully FT, i.g., freeze_module_list=""
14
+ DIT_TYPE="DiT-B"
15
+ # freeze_module_list="qwen_vl_interface.model.model.visual,dino_encoder" # just for fast debug, sota is under fully FT, i.g., freeze_module_list=""
16
+
17
+ llavadata="asv2_conversation_en,asv2_detailed_description_en"
18
+ # data_root_dir=/mnt/petrelfs/wangfangjing/p_ceph/datasets/PhysicalAI-Robotics-GR00T-X-Embodiment-Sim
19
+ data_root_dir=./playground/Datasets/PhysicalAI-Robotics-GR00T-X-Embodiment-Sim
20
+ data_mix=fourier_gr1_unified_1000
21
+ # data_mix=fourier_gr1_unified_1000_PnPMilkToMicrowaveClose
22
+ # data_mix=fourier_gr1_10K_pretrain
23
+
24
+ run_root_dir=./playground/Checkpoints
25
+ run_id=starvla_qwenGR00T_fourier_gr1_unified_1000_withState
26
+
27
+ export WANDB_MODE=disabled
28
+
29
+ output_dir=${run_root_dir}/${run_id}
30
+ mkdir -p ${output_dir}
31
+ # mv this script to the output dir
32
+ cp $0 ${output_dir}/
33
+
34
+ accelerate launch \
35
+ --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \
36
+ --num_processes 8 \
37
+ starVLA/training/train_starvla.py \
38
+ --config_yaml ./starVLA/config/training/internvla_cotrain_robocasa_gr1.yaml \
39
+ --framework.name ${Framework_name} \
40
+ --framework.qwenvl.base_vlm ${base_vlm} \
41
+ --framework.action_model.action_model_type ${DIT_TYPE} \
42
+ --datasets.vla_data.data_root_dir ${data_root_dir} \
43
+ --datasets.vla_data.data_mix ${data_mix} \
44
+ --datasets.vla_data.per_device_batch_size 16 \
45
+ --trainer.freeze_modules ${freeze_module_list} \
46
+ --trainer.max_train_steps 100000 \
47
+ --trainer.save_interval 10000 \
48
+ --trainer.logging_frequency 10 \
49
+ --trainer.eval_interval 100 \
50
+ --trainer.learning_rate.base 4e-5 \
51
+ --run_root_dir ${run_root_dir} \
52
+ --run_id ${run_id} \
53
+ --wandb_project starVLA \
54
+ --wandb_entity ailab-manipulation \
55
+ --is_debug True
56
+
57
+
scripts/run_scripts/run_lerobot_datasets_qwenGR00T.sh ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export NCCL_SOCKET_IFNAME=bond0
2
+ export NCCL_IB_HCA=mlx5_2,mlx5_3
3
+
4
+ # used for check save when communication
5
+ export NCCL_BLOCKING_WAIT=1
6
+ export NCCL_ASYNC_ERROR_HANDLING=1
7
+ export NCCL_TIMEOUT=1000 # timeout set to 1 hour (unit: seconds)
8
+
9
+
10
+ # === Please modify the following paths according to your environment ===
11
+ ###########################################################################################
12
+
13
+ Framework_name=QwenGR00T
14
+ base_vlm=StarVLA/Qwen3-VL-4B-Instruct-Action
15
+ action_input_dim=2560
16
+ DIT_TYPE="DiT-B"
17
+ oxe_data_root=playground/Datasets/OXE_LEROBOT
18
+ data_mix=bridge_rt_1
19
+ run_root_dir=./playground/Checkpoints
20
+ run_id=1004_starvla_qwengroot_oxe
21
+ # === End of environment variable configuration ===
22
+ ###########################################################################################
23
+
24
+ output_dir=${run_root_dir}/${run_id}
25
+ mkdir -p ${output_dir}
26
+ cp $0 ${output_dir}/
27
+ export WANDB_MODE=disabled
28
+
29
+ accelerate launch \
30
+ --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \
31
+ --num_processes 8 \
32
+ starVLA/training/train_starvla.py \
33
+ --config_yaml ./starVLA/config/training/starvla_cotrain_oxe.yaml \
34
+ --framework.name ${Framework_name} \
35
+ --framework.qwenvl.base_vlm ${base_vlm} \
36
+ --framework.action_model.action_hidden_dim ${action_input_dim} \
37
+ --framework.action_model.action_model_type ${DIT_TYPE} \
38
+ --datasets.vla_data.data_root_dir ${oxe_data_root}\
39
+ --datasets.vla_data.data_mix ${data_mix} \
40
+ --datasets.vla_data.per_device_batch_size 16 \
41
+ --trainer.freeze_modules ${freeze_module_list} \
42
+ --trainer.max_train_steps 100000 \
43
+ --trainer.save_interval 20000 \
44
+ --trainer.logging_frequency 10 \
45
+ --trainer.eval_interval 100 \
46
+ --run_root_dir ${run_root_dir} \
47
+ --run_id ${run_id} \
48
+ --wandb_project starVLA \
49
+ --wandb_entity jinhuiye \
50
+ # --is_debug True
51
+
52
+
53
+
54
+
55
+ # multi-node launch example
56
+
57
+ # accelerate launch \
58
+ # --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \
59
+ # --main_process_ip $MASTER_ADDR \
60
+ # --main_process_port $MASTER_PORT \
61
+ # --machine_rank $SLURM_PROCID \
62
+ # --num_machines $SLURM_NNODES \
63
+ # --num_processes=${TOTAL_GPUS} \
64
+ # starVLA/training/train_starvla.py \
65
+ # --config_yaml ./starVLA/config/training/starvla_cotrain_oxe.yaml \
66
+ # --framework.framework_py QwenGR00T \
67
+ # --framework.qwenvl.base_vlm microsoft/Florence-2-large \
68
+ # --run_root_dir ${run_root_dir} \
69
+ # --run_id ${run_id} \
70
+ # --wandb_project your_project \
71
+ # --wandb_entity your_name
72
+
scripts/run_scripts/run_lerobot_datasets_qwenfast.sh ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ export NCCL_SOCKET_IFNAME=bond0
4
+ export NCCL_IB_HCA=mlx5_2,mlx5_3
5
+
6
+ # used for check save when communication
7
+ export NCCL_BLOCKING_WAIT=1
8
+ export NCCL_ASYNC_ERROR_HANDLING=1
9
+ export NCCL_TIMEOUT=1000 # timeout set to 1 hour (unit: seconds)
10
+
11
+ ###########################################################################################
12
+ # === Please modify the following paths according to your environment ===
13
+ ## Model
14
+ Framework_name=QwenFast
15
+ base_vlm=StarVLA/Qwen3-VL-4B-Instruct-Action
16
+ action_input_dim=2048
17
+ ## Data
18
+ oxe_data_root=playground/Datasets/OXE_LEROBOT
19
+ data_mix=bridge_rt_1
20
+ # To save
21
+ run_root_dir=./playground/Checkpoints
22
+ run_id=1004_starvla_qwenoft_oxe
23
+ output_dir=${run_root_dir}/${run_id}
24
+ mkdir -p ${output_dir}
25
+ cp $0 ${output_dir}/
26
+ # === End of environment variable configuration ===
27
+ ###########################################################################################
28
+
29
+
30
+
31
+
32
+ # mv this script to the output dir
33
+ export WANDB_MODE=disableds
34
+
35
+ accelerate launch \
36
+ --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \
37
+ --num_processes 8 \
38
+ starVLA/training/train_starvla.py \
39
+ --config_yaml ./starVLA/config/training/starvla_cotrain_oxe.yaml \
40
+ --framework.name ${Framework_name} \
41
+ --framework.qwenvl.base_vlm ${base_vlm} \
42
+ --framework.action_model.action_hidden_dim ${action_input_dim} \
43
+ --datasets.vla_data.data_root_dir ${oxe_data_root}\
44
+ --datasets.vla_data.data_mix ${data_mix} \
45
+ --datasets.vla_data.per_device_batch_size 16 \
46
+ --trainer.freeze_modules ${freeze_module_list} \
47
+ --trainer.max_train_steps 100000 \
48
+ --trainer.save_interval 20000 \
49
+ --trainer.logging_frequency 10 \
50
+ --trainer.eval_interval 1000 \
51
+ --run_root_dir ${run_root_dir} \
52
+ --run_id ${run_id} \
53
+ --wandb_project starVLA \
54
+ --wandb_entity jinhuiye \
55
+ # --is_debug True
56
+
57
+
58
+ # multi-node launch example
59
+
60
+ # accelerate launch \
61
+ # --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \
62
+ # --main_process_ip $MASTER_ADDR \
63
+ # --main_process_port $MASTER_PORT \
64
+ # --machine_rank $SLURM_PROCID \
65
+ # --num_machines $SLURM_NNODES \
66
+ # --num_processes=${TOTAL_GPUS} \
67
+ # starVLA/training/train_starvla.py \
68
+ # --config_yaml ./starVLA/config/training/starvla_cotrain_oxe.yaml \
69
+ # --framework.framework_py QwenGR00T \
70
+ # --framework.qwenvl.base_vlm microsoft/Florence-2-large \
71
+ # --run_root_dir ${run_root_dir} \
72
+ # --run_id ${run_id} \
73
+ # --wandb_project your_project \
74
+ # --wandb_entity your_name
75
+
scripts/run_scripts/run_lerobot_datasets_qwenoft.sh ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export NCCL_SOCKET_IFNAME=bond0
2
+ export NCCL_IB_HCA=mlx5_2,mlx5_3
3
+
4
+ # used for check save when communication
5
+ export NCCL_BLOCKING_WAIT=1
6
+ export NCCL_ASYNC_ERROR_HANDLING=1
7
+ export NCCL_TIMEOUT=1000 # timeout set to 1 hour (unit: seconds)
8
+
9
+
10
+ # === Please modify the following paths according to your environment ===
11
+ ###########################################################################################
12
+
13
+ Framework_name=QwenOFT
14
+ base_vlm=StarVLA/Qwen3-VL-4B-Instruct-Action
15
+ action_input_dim=2560
16
+ oxe_data_root=playground/Datasets/OXE_LEROBOT
17
+ data_mix=bridge_rt_1
18
+ run_root_dir=./playground/Checkpoints
19
+ run_id=1004_starvla_qwenoft_oxe
20
+ # === End of environment variable configuration ===
21
+ ###########################################################################################
22
+
23
+ export WANDB_MODE=disabled
24
+
25
+ output_dir=${run_root_dir}/${run_id}
26
+ mkdir -p ${output_dir}
27
+ # mv this script to the output dir
28
+ cp $0 ${output_dir}/
29
+
30
+
31
+ accelerate launch \
32
+ --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \
33
+ --num_processes 8 \
34
+ starVLA/training/train_starvla.py \
35
+ --config_yaml ./starVLA/config/training/starvla_cotrain_oxe.yaml \
36
+ --framework.name ${Framework_name} \
37
+ --framework.qwenvl.base_vlm ${base_vlm} \
38
+ --framework.action_model.action_hidden_dim ${action_input_dim} \
39
+ --datasets.vla_data.data_root_dir ${oxe_data_root}\
40
+ --datasets.vla_data.data_mix ${data_mix} \
41
+ --datasets.vla_data.per_device_batch_size 16 \
42
+ --trainer.freeze_modules ${freeze_module_list} \
43
+ --trainer.max_train_steps 100000 \
44
+ --trainer.save_interval 20000 \
45
+ --trainer.logging_frequency 10 \
46
+ --trainer.eval_interval 100 \
47
+ --run_root_dir ${run_root_dir} \
48
+ --run_id ${run_id} \
49
+ --wandb_project starVLA \
50
+ --wandb_entity jinhuiye \
51
+ # --is_debug True
52
+
53
+
54
+
55
+ ###########################################################################################
56
+ ####### multi-node launch example #######
57
+ ###########################################################################################
58
+
59
+ # accelerate launch \
60
+ # --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \
61
+ # --main_process_ip $MASTER_ADDR \
62
+ # --main_process_port $MASTER_PORT \
63
+ # --machine_rank $SLURM_PROCID \
64
+ # --num_machines $SLURM_NNODES \
65
+ # --num_processes=${TOTAL_GPUS} \
66
+ # starVLA/training/train_starvla.py \
67
+ # --config_yaml ./starVLA/config/training/starvla_cotrain_oxe.yaml \
68
+ # --framework.framework_py QwenGR00T \
69
+ # --framework.qwenvl.base_vlm microsoft/Florence-2-large \
70
+ # --run_root_dir ${run_root_dir} \
71
+ # --run_id ${run_id} \
72
+ # --wandb_project your_project \
73
+ # --wandb_entity your_name
74
+
scripts/run_scripts/run_lerobot_datasets_qwenpi.sh ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export NCCL_SOCKET_IFNAME=bond0
2
+ export NCCL_IB_HCA=mlx5_2,mlx5_3
3
+
4
+ export NCCL_BLOCKING_WAIT=1
5
+ export NCCL_ASYNC_ERROR_HANDLING=1
6
+ export NCCL_TIMEOUT=1000 # timeout set to 1 hour (unit: seconds)
7
+
8
+
9
+ # === Please modify the following paths according to your environment ===
10
+ ###########################################################################################
11
+
12
+ Framework_name=QwenPI
13
+ base_vlm=StarVLA/Qwen2.5-VL-3B-Instruct-Action
14
+ DIT_TYPE="DiT-B"
15
+ oxe_data_root=playground/Datasets/OXE_LEROBOT
16
+ data_mix=bridge_rt_1
17
+ run_root_dir=./playground/Checkpoints
18
+ run_id=1011_starvla_qwenpi
19
+ export action_input_dim=2048
20
+ ###########################################################################################
21
+
22
+
23
+ output_dir=${run_root_dir}/${run_id}
24
+ mkdir -p ${output_dir}
25
+ # mv this script to the output dir
26
+ cp $0 ${output_dir}/
27
+
28
+
29
+ accelerate launch \
30
+ --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \
31
+ --num_processes 8 \
32
+ starVLA/training/train_starvla.py \
33
+ --config_yaml ./starVLA/config/training/starvla_cotrain_oxe.yaml \
34
+ --framework.name ${Framework_name} \
35
+ --framework.qwenvl.base_vlm ${base_vlm} \
36
+ --framework.action_model.action_hidden_dim ${action_input_dim} \
37
+ --framework.action_model.action_model_type ${DIT_TYPE} \
38
+ --datasets.vla_data.data_root_dir ${oxe_data_root}\
39
+ --datasets.vla_data.data_mix ${data_mix} \
40
+ --datasets.vla_data.per_device_batch_size 16 \
41
+ --trainer.freeze_modules ${freeze_module_list} \
42
+ --trainer.max_train_steps 100000 \
43
+ --trainer.save_interval 10000 \
44
+ --trainer.logging_frequency 10 \
45
+ --trainer.eval_interval 100 \
46
+ --run_root_dir ${run_root_dir} \
47
+ --run_id ${run_id} \
48
+ --wandb_project starVLA \
49
+ --wandb_entity jinhuiye \
50
+ # --is_debug True
51
+
52
+
53
+
54
+
55
+ # multi-node launch example
56
+
57
+ # accelerate launch \
58
+ # --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \
59
+ # --main_process_ip $MASTER_ADDR \
60
+ # --main_process_port $MASTER_PORT \
61
+ # --machine_rank $SLURM_PROCID \
62
+ # --num_machines $SLURM_NNODES \
63
+ # --num_processes=${TOTAL_GPUS} \
64
+ # starVLA/training/train_starvla.py \
65
+ # --config_yaml ./starVLA/config/training/starvla_cotrain_oxe.yaml \
66
+ # --framework.framework_py QwenGR00T \
67
+ # --framework.qwenvl.base_vlm microsoft/Florence-2-large \
68
+ # --run_root_dir ${run_root_dir} \
69
+ # --run_id ${run_id} \
70
+ # --wandb_project your_project \
71
+ # --wandb_entity your_name
72
+
starVLA/__init__.py ADDED
File without changes
starVLA/config/deepseeds/deepspeed_zero2.yaml ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ compute_environment: LOCAL_MACHINE
2
+ debug: false
3
+ deepspeed_config:
4
+ deepspeed_config_file: "./starVLA/config/deepseeds/ds_config.yaml"
5
+ deepspeed_multinode_launcher: standard
6
+ zero3_init_flag: false
7
+ distributed_type: DEEPSPEED
8
+ num_machines: 1
9
+ num_processes: 8
starVLA/config/deepseeds/deepspeed_zero3.yaml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ compute_environment: LOCAL_MACHINE
2
+ debug: false
3
+ deepspeed_config:
4
+ deepspeed_config_file: "./starVLA/config/deepseeds/zero3.yaml"
5
+ deepspeed_multinode_launcher: standard
6
+ zero3_init_flag: false
7
+ distributed_type: DEEPSPEED
starVLA/config/deepseeds/ds_config.yaml ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fp16": {
3
+ "enabled": false
4
+ },
5
+ "bf16": {
6
+ "enabled": true
7
+ },
8
+ "train_micro_batch_size_per_gpu": "auto",
9
+ "train_batch_size": "auto",
10
+ "gradient_accumulation_steps": 1,
11
+ "zero_optimization": {
12
+ "stage": 2,
13
+ "allgather_partitions": true,
14
+ "allgather_bucket_size": 5e8,
15
+ "reduce_scatter": true,
16
+ "reduce_bucket_size": 5e8,
17
+ "overlap_comm": true,
18
+ "contiguous_gradients": true,
19
+ "cpu_offload": false
20
+ },
21
+ "gradient_clipping": 1.0,
22
+ "steps_per_print": 10
23
+ }
starVLA/config/deepseeds/zero2.yaml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ compute_environment: LOCAL_MACHINE
2
+ debug: false
3
+ deepspeed_config:
4
+ deepspeed_multinode_launcher: standard
5
+ offload_optimizer_device: none
6
+ offload_param_device: none
7
+ zero3_init_flag: false
8
+ zero_stage: 2
9
+ distributed_type: DEEPSPEED
10
+ downcast_bf16: 'no'
11
+ machine_rank: 0
12
+ main_training_function: main
13
+ mixed_precision: bf16
14
+ num_machines: 1
15
+ num_processes: 8
16
+ rdzv_backend: static
17
+ same_network: true
18
+ tpu_env: []
19
+ tpu_use_cluster: false
20
+ tpu_use_sudo: false
21
+ use_cpu: false
starVLA/config/deepseeds/zero3.yaml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fp16": {
3
+ "enabled": "auto",
4
+ "loss_scale": 0,
5
+ "loss_scale_window": 1000,
6
+ "initial_scale_power": 16,
7
+ "hysteresis": 2,
8
+ "min_loss_scale": 1
9
+ },
10
+ "bf16": {
11
+ "enabled": "auto"
12
+ },
13
+ "train_micro_batch_size_per_gpu": "auto",
14
+ "train_batch_size": "auto",
15
+ "gradient_accumulation_steps": "auto",
16
+ "zero_optimization": {
17
+ "stage": 3,
18
+ "overlap_comm": true,
19
+ "contiguous_gradients": true,
20
+ "sub_group_size": 1e9,
21
+ "reduce_bucket_size": 5e8,
22
+ "stage3_prefetch_bucket_size": 5e8,
23
+ "stage3_param_persistence_threshold": 1e6,
24
+ "stage3_max_live_parameters": 1e9,
25
+ "stage3_max_reuse_distance": 1e9,
26
+ "stage3_gather_16bit_weights_on_model_save": true
27
+ }
28
+ }
starVLA/config/training/starvla_cotrain_libero.yaml ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ run_id: starvla
2
+ run_root_dir: results/Checkpoints
3
+ seed: 42
4
+ trackers: [jsonl, wandb]
5
+ wandb_entity: your_wandb_entity
6
+ wandb_project: llavavla
7
+ is_debug: false
8
+
9
+
10
+ framework:
11
+ name: QwenGR00T
12
+ qwenvl:
13
+ base_vlm: ./playground/Pretrained_models/Qwen2.5-VL-3B-Instruct
14
+ attn_implementation: flash_attention_2
15
+ vl_hidden_dim: 2048
16
+ dino:
17
+ dino_backbone: dinov2_vits14
18
+ action_model:
19
+ action_model_type: DiT-B
20
+ action_hidden_dim: 1024 # TODO merge with hidden_size, in config v2
21
+ hidden_size: 1024
22
+ add_pos_embed: True
23
+ max_seq_len: 1024
24
+ action_dim: 7
25
+ state_dim: 7
26
+ future_action_window_size: 7
27
+ action_horizon: 8 # need merge with future_action_window_size
28
+ past_action_window_size: 0
29
+ repeated_diffusion_steps: 8
30
+ noise_beta_alpha: 1.5
31
+ noise_beta_beta: 1.0
32
+ noise_s: 0.999
33
+ num_timestep_buckets: 1000
34
+ num_inference_timesteps: 4
35
+ num_target_vision_tokens: 32
36
+ diffusion_model_cfg: # DiT Transformers 的参数
37
+ cross_attention_dim: 2048 # VLM 的 dim
38
+ dropout: 0.2
39
+ final_dropout: true
40
+ interleave_self_attention: true
41
+ norm_type: "ada_norm"
42
+ num_layers: 16
43
+ output_dim: 1024
44
+ positional_embeddings: null
45
+
46
+ reduce_in_full_precision: true
47
+
48
+
49
+ datasets:
50
+ vlm_data:
51
+ dataset_py: vlm_datasets
52
+ dataformat: llava_json
53
+ dataset_use: asv2_conversation_en,asv2_detailed_description_en,asv2_region_captioning_en,coco_internvl_longcap_en,coco_karpathy_train_567_en,coco_negative_gpt4o_en,coco_poetry_zh,coco_rem_en_zh,cocorem_exist_yorn_en,cocotextv2_en,cocotextv2_gpt4o_en,okvqa_en,refcoco_grounding_aug_en,refcoco_grounding_en,tallyqa_coco_en,toloka_grounding_aug_en,vqav2_en,vsr_en
54
+ eval_dataset: aokvqa_cauldron_llava_format
55
+ data_flatten: false
56
+ base_interval: 2
57
+ max_pixels: 12845056
58
+ min_pixels: 3136
59
+ model_max_length: 2048
60
+ model_type: qwen2.5vl
61
+ per_device_batch_size: 4
62
+
63
+ vla_data:
64
+ dataset_py: lerobot_datasets
65
+ data_root_dir: playground/Datasets/LEROBOT_LIBERO_DATA
66
+ data_mix: libero_goal # libero_goal
67
+ action_type: delta_qpos
68
+ CoT_prompt: "Your task is {instruction}. To identify the key objects for your task. Locate their bounding boxes in [x1,y1,x2,y2] format."
69
+ CoT_answer: bbox
70
+ default_image_resolution: [3, 224, 224]
71
+ per_device_batch_size: 16
72
+ load_all_data_for_training: true
73
+ obs: ["image_0"]
74
+
75
+
76
+ trainer:
77
+ epochs: 100
78
+ max_train_steps: 100000
79
+ num_warmup_steps: 5000
80
+ save_interval: 5000
81
+ eval_interval: 100
82
+ learning_rate:
83
+ base: 2.5e-05
84
+ qwen_vl_interface: 1.0e-05
85
+ action_model: 1.0e-04
86
+ lr_scheduler_type: cosine_with_min_lr
87
+ scheduler_specific_kwargs:
88
+ min_lr: 1.0e-06
89
+ freeze_modules: ''
90
+ loss_scale:
91
+ vla: 1.0
92
+ vlm: 0.1
93
+ max_grad_norm: 1.0
94
+ warmup_ratio: 0.1
95
+ weight_decay: 0.0
96
+ logging_frequency: 10
97
+ gradient_clipping: 1.0
98
+ gradient_accumulation_steps: 1
99
+
100
+ optimizer:
101
+ name: AdamW
102
+ betas: [0.9, 0.95]
103
+ eps: 1.0e-08
104
+ weight_decay: 1.0e-08
105
+
106
+ # parameters to be determined
107
+ is_resume: false
108
+ resume_epoch: null
109
+ resume_step: null
110
+ enable_gradient_checkpointing: true
111
+ enable_mixed_precision_training: true
starVLA/config/training/starvla_cotrain_oxe.yaml ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ run_id: qwenact
2
+ run_root_dir: results/Checkpoints
3
+ seed: 42
4
+ trackers: [jsonl, wandb]
5
+ wandb_entity: your_wandb_entity
6
+ wandb_project: llavavla
7
+ is_debug: false
8
+
9
+ framework:
10
+ name: QwenFM
11
+ qwenvl:
12
+ base_vlm: ./playground/Pretrained_models/Qwen2.5-VL-3B-Instruct
13
+ attn_implementation: flash_attention_2
14
+ vl_hidden_dim: 2048
15
+ dino:
16
+ dino_backbone: dinov2_vits14
17
+
18
+ action_model:
19
+ action_model_type: DiT-B
20
+ hidden_size: 1024 # 和 DiT 最后的 projection 对应,用于 ActionDecoder
21
+ add_pos_embed: True
22
+ max_seq_len: 1024
23
+ action_dim: 7
24
+ state_dim: 7
25
+ future_action_window_size: 15
26
+ action_horizon: 16
27
+ past_action_window_size: 0
28
+ repeated_diffusion_steps: 8
29
+ noise_beta_alpha: 1.5
30
+ noise_beta_beta: 1.0
31
+ noise_s: 0.999
32
+ num_timestep_buckets: 1000
33
+ num_inference_timesteps: 4
34
+ num_target_vision_tokens: 32
35
+ diffusion_model_cfg: # DiT Transformers 的参数
36
+ cross_attention_dim: 2048 # VLM 的 dim
37
+ dropout: 0.2
38
+ final_dropout: true
39
+ interleave_self_attention: true
40
+ norm_type: "ada_norm"
41
+ num_layers: 16
42
+ output_dim: 2560
43
+ positional_embeddings: null
44
+
45
+
46
+
47
+ datasets:
48
+ vlm_data:
49
+ dataset_py: vlm_datasets
50
+ dataformat: llava_json
51
+ dataset_use: asv2_conversation_en,asv2_detailed_description_en,asv2_region_captioning_en,coco_internvl_longcap_en,coco_karpathy_train_567_en,coco_negative_gpt4o_en,coco_poetry_zh,coco_rem_en_zh,cocorem_exist_yorn_en,cocotextv2_en,cocotextv2_gpt4o_en,okvqa_en,refcoco_grounding_aug_en,refcoco_grounding_en,tallyqa_coco_en,toloka_grounding_aug_en,vqav2_en,vsr_en
52
+ eval_dataset: aokvqa_cauldron_llava_format
53
+ data_flatten: false
54
+ base_interval: 2
55
+ max_pixels: 50176
56
+ min_pixels: 784
57
+ model_max_length: 2048
58
+ model_type: qwen2.5vl
59
+ per_device_batch_size: 4
60
+
61
+ vla_data:
62
+ dataset_py: lerobot_datasets
63
+ data_root_dir: playground/Datasets/OXE_LEROBOT_DATASET
64
+ data_mix: bridge_rt_1 # bridge_rt_1
65
+ action_type: delta_ee
66
+ CoT_prompt: "Your task is {instruction}. To identify the key objects for your task. Locate their bounding boxes in [x1,y1,x2,y2] format."
67
+ CoT_answer: bbox
68
+ default_image_resolution: [3, 224, 224]
69
+ per_device_batch_size: 16
70
+ load_all_data_for_training: true
71
+ obs: ["image_0"]
72
+ image_size: [224,224]
73
+
74
+ trainer:
75
+ epochs: 100
76
+ max_train_steps: 100000
77
+ num_warmup_steps: 5000
78
+ save_interval: 5000
79
+ eval_interval: 100
80
+ learning_rate:
81
+ base: 1e-05
82
+ qwen_vl_interface: 1.0e-05
83
+ action_model: 1.0e-04
84
+ lr_scheduler_type: cosine_with_min_lr
85
+ scheduler_specific_kwargs:
86
+ min_lr: 5.0e-07
87
+ freeze_modules: ''
88
+ loss_scale:
89
+ vla: 1.0
90
+ vlm: 0.1
91
+ # pretrained_checkpoint: ./results/Checkpoints/1_need/0601_qwenact_fixqwen_32gpus_lr_1e-3_qformer_36_37/steps_100000/pytorch_model.pt
92
+ # reload_modules: 'action_model,layer_qformer' # warning: this may cause model to not converge
93
+ repeated_diffusion_steps: 4
94
+ max_grad_norm: 1.0
95
+ warmup_ratio: 0.1
96
+ weight_decay: 0.0
97
+ logging_frequency: 10
98
+ gradient_clipping: 1.0
99
+ gradient_accumulation_steps: 1
100
+
101
+ optimizer:
102
+ name: AdamW
103
+ betas: [0.9, 0.95]
104
+ eps: 1.0e-08
105
+ weight_decay: 1.0e-08
106
+
107
+ # parameters to be determined
108
+ is_resume: false
109
+ resume_epoch: null
110
+ resume_step: null
111
+ enable_gradient_checkpointing: true
112
+ enable_mixed_precision_training: true
starVLA/config/training/starvla_train_adapter.yaml ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ run_id: starvla
2
+ run_root_dir: path/to/result
3
+ seed: 42
4
+ trackers: [jsonl, wandb]
5
+ wandb_entity: your-wandb-entity
6
+ wandb_project: your-wandb-project
7
+ is_debug: false
8
+
9
+ framework:
10
+ name: QwenAdapter
11
+ qwenvl:
12
+ base_vlm: /path/to/your/qwen_vl_base_checkpoint
13
+ attn_implementation: flash_attention_2
14
+ vl_hidden_dim: 2048
15
+ action_model:
16
+ action_model_type: VLA-Adapter
17
+ hidden_dim: 2048
18
+ action_dim: 14
19
+ state_dim: 14
20
+ action_query_num: 64
21
+ use_pro_version: true # use the pro version of MLPResNet
22
+ use_proprio: false
23
+ phase: Training
24
+ num_actions_chunk: 16
25
+
26
+
27
+ datasets:
28
+ vla_data:
29
+ dataset_py: lerobot_datasets
30
+ data_root_dir: path/to/train_data
31
+ data_mix: train_data
32
+ per_device_batch_size: 16
33
+ num_workers: 16
34
+ action_type: delta_qpos
35
+
36
+
37
+ trainer:
38
+ epochs: 100
39
+ max_train_steps: 100000
40
+ num_warmup_steps: 5000
41
+ save_interval: 5000
42
+ # save_interval: 5
43
+ eval_interval: 100
44
+ learning_rate:
45
+ base: 2.5e-05
46
+ qwen_vl_interface: 1.0e-05
47
+ action_model: 1.0e-04
48
+ lr_scheduler_type: cosine_with_min_lr
49
+ scheduler_specific_kwargs:
50
+ min_lr: 1.0e-06
51
+ freeze_modules: ''
52
+ loss_scale:
53
+ vla: 1.0
54
+ vlm: 0.1
55
+ max_grad_norm: 1.0
56
+ warmup_ratio: 0.1
57
+ weight_decay: 0.0
58
+ logging_frequency: 10
59
+ gradient_clipping: 1.0
60
+ gradient_accumulation_steps: 1
61
+ pretrained_checkpoint: "your pretrained checkpoint path"
62
+ optimizer:
63
+ name: AdamW
64
+ betas: [0.9, 0.95]
65
+ eps: 1.0e-08
66
+ weight_decay: 1.0e-08
67
+
68
+ # parameters to be determined
69
+ is_resume: false
70
+ resume_epoch: null
71
+ resume_step: null
72
+ enable_gradient_checkpointing: true
73
+ enable_mixed_precision_training: true
starVLA/dataloader/__init__.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from accelerate.logging import get_logger
4
+ import numpy as np
5
+ from torch.utils.data import DataLoader
6
+ import numpy as np
7
+ import torch.distributed as dist
8
+ from pathlib import Path
9
+ from starVLA.dataloader.vlm_datasets import make_vlm_dataloader
10
+
11
+ logger = get_logger(__name__)
12
+
13
+ def save_dataset_statistics(dataset_statistics, run_dir):
14
+ """Saves a `dataset_statistics.json` file."""
15
+ out_path = run_dir / "dataset_statistics.json"
16
+ with open(out_path, "w") as f_json:
17
+ for _, stats in dataset_statistics.items():
18
+ for k in stats["action"].keys():
19
+ if isinstance(stats["action"][k], np.ndarray):
20
+ stats["action"][k] = stats["action"][k].tolist()
21
+ if "proprio" in stats:
22
+ for k in stats["proprio"].keys():
23
+ if isinstance(stats["proprio"][k], np.ndarray):
24
+ stats["proprio"][k] = stats["proprio"][k].tolist()
25
+ if "num_trajectories" in stats:
26
+ if isinstance(stats["num_trajectories"], np.ndarray):
27
+ stats["num_trajectories"] = stats["num_trajectories"].item()
28
+ if "num_transitions" in stats:
29
+ if isinstance(stats["num_transitions"], np.ndarray):
30
+ stats["num_transitions"] = stats["num_transitions"].item()
31
+ json.dump(dataset_statistics, f_json, indent=2)
32
+ logger.info(f"Saved dataset statistics file at path {out_path}")
33
+
34
+
35
+
36
+ def build_dataloader(cfg, dataset_py="lerobot_datasets_oxe"):
37
+ # print("########### DATA.__init__.build_dataloader-1")
38
+ # print(dataset_py) # lerobot_datasets
39
+
40
+ # VLA_Dataset
41
+ if dataset_py == "lerobot_datasets":
42
+ from starVLA.dataloader.lerobot_datasets import get_vla_dataset, collate_fn
43
+ vla_dataset_cfg = cfg.datasets.vla_data
44
+ # print(vla_dataset_cfg)
45
+ """
46
+ dataset_py: lerobot_datasets
47
+ data_root_dir: /mnt/workspace/datasets/
48
+ data_mix: robocasa_teleop_ee
49
+ action_type: delta_ee
50
+ CoT_prompt: Your task is {instruction}. To identify the key objects for your task.
51
+ Locate their bounding boxes in [x1,y1,x2,y2] format.
52
+ CoT_answer: bbox
53
+ default_image_resolution:
54
+ - 3
55
+ - 224
56
+ - 224
57
+ per_device_batch_size: 16
58
+ load_all_data_for_training: true
59
+ obs:
60
+ - image_0
61
+ image_size:
62
+ - 224
63
+ - 224
64
+ delete_pause_frame: false
65
+ include_state: true
66
+ """
67
+ vla_dataset = get_vla_dataset(data_cfg=vla_dataset_cfg)
68
+ # print(type(vla_dataset)) # <class 'starVLA.dataloader.gr00t_lerobot.datasets.LeRobotMixtureDataset'>
69
+ # print(cfg.datasets.vla_data.per_device_batch_size) # 16
70
+ # print(collate_fn) # <function collate_fn at 0x7f06995d81f0>
71
+ num_workers = int(getattr(cfg.datasets.vla_data, "num_workers", 8))
72
+ pin_memory = bool(getattr(cfg.datasets.vla_data, "pin_memory", True))
73
+ persistent_workers = bool(getattr(cfg.datasets.vla_data, "persistent_workers", True))
74
+ prefetch_factor = int(getattr(cfg.datasets.vla_data, "prefetch_factor", 2))
75
+
76
+ dataloader_kwargs = {
77
+ "batch_size": cfg.datasets.vla_data.per_device_batch_size,
78
+ "collate_fn": collate_fn,
79
+ "num_workers": num_workers,
80
+ "pin_memory": pin_memory,
81
+ "persistent_workers": persistent_workers if num_workers > 0 else False,
82
+ }
83
+ if num_workers > 0:
84
+ dataloader_kwargs["prefetch_factor"] = prefetch_factor
85
+
86
+ vla_train_dataloader = DataLoader(
87
+ vla_dataset,
88
+ **dataloader_kwargs,
89
+ )
90
+ if dist.get_rank() == 0:
91
+ output_dir = Path(cfg.output_dir)
92
+ vla_dataset.save_dataset_statistics(output_dir / "dataset_statistics.json")
93
+ # print("########### DATA.__init__.build_dataloader-2")
94
+ return vla_train_dataloader
95
+
96
+ # VLM_Dataset
97
+ elif dataset_py == "vlm_datasets":
98
+ vlm_data_module = make_vlm_dataloader(cfg)
99
+ vlm_train_dataloader = vlm_data_module["train_dataloader"]
100
+
101
+ return vlm_train_dataloader
starVLA/dataloader/gr00t_lerobot/README.md ADDED
File without changes
starVLA/dataloader/gr00t_lerobot/__init__.py ADDED
File without changes
starVLA/dataloader/gr00t_lerobot/data_config.py ADDED
@@ -0,0 +1,1208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+
5
+
6
+ from abc import ABC, abstractmethod
7
+
8
+ from starVLA.dataloader.gr00t_lerobot.datasets import ModalityConfig
9
+ from starVLA.dataloader.gr00t_lerobot.transform.base import ComposedModalityTransform, ModalityTransform
10
+ from starVLA.dataloader.gr00t_lerobot.transform.concat import ConcatTransform
11
+ from starVLA.dataloader.gr00t_lerobot.transform.state_action import (
12
+ StateActionSinCosTransform,
13
+ StateActionToTensor,
14
+ StateActionTransform,
15
+ )
16
+ from starVLA.dataloader.gr00t_lerobot.transform.video import (
17
+ VideoColorJitter,
18
+ VideoCrop,
19
+ VideoResize,
20
+ VideoToNumpy,
21
+ VideoToTensor,
22
+ VideoResizePad,
23
+ )
24
+ # from starVLA.dataloader.gr00t_lerobot.transform.gr00ttransform import GR00TTransform
25
+ from starVLA.dataloader.gr00t_lerobot.transform.gr00ttransform_1 import GR00TTransform
26
+
27
+ class BaseDataConfig(ABC):
28
+ @abstractmethod
29
+ def modality_config(self) -> dict[str, ModalityConfig]:
30
+ pass
31
+
32
+ @abstractmethod
33
+ def transform(self) -> ModalityTransform:
34
+ pass
35
+
36
+
37
+ ###########################################################################################
38
+
39
+ class OxeDroidDataConfig:
40
+ video_keys = [
41
+ "video.exterior_image_1",
42
+ "video.exterior_image_2",
43
+ "video.wrist_image",
44
+ ]
45
+ state_keys = [
46
+ "state.eef_position",
47
+ "state.eef_rotation",
48
+ "state.gripper_position",
49
+ ]
50
+ action_keys = [
51
+ "action.eef_position_delta",
52
+ "action.eef_rotation_delta",
53
+ "action.gripper_position",
54
+ ]
55
+ language_keys = ["annotation.language.language_instruction"]
56
+ observation_indices = [0]
57
+ action_indices = list(range(16))
58
+
59
+ def modality_config(self):
60
+ video_modality = ModalityConfig(
61
+ delta_indices=self.observation_indices,
62
+ modality_keys=self.video_keys,
63
+ )
64
+ state_modality = ModalityConfig(
65
+ delta_indices=self.observation_indices,
66
+ modality_keys=self.state_keys,
67
+ )
68
+ action_modality = ModalityConfig(
69
+ delta_indices=self.action_indices,
70
+ modality_keys=self.action_keys,
71
+ )
72
+ language_modality = ModalityConfig(
73
+ delta_indices=self.observation_indices,
74
+ modality_keys=self.language_keys,
75
+ )
76
+ modality_configs = {
77
+ "video": video_modality,
78
+ "state": state_modality,
79
+ "action": action_modality,
80
+ "language": language_modality,
81
+ }
82
+ return modality_configs
83
+
84
+ def transform(self):
85
+ transforms = [
86
+ # video transforms
87
+ VideoToTensor(apply_to=self.video_keys),
88
+ VideoCrop(apply_to=self.video_keys, scale=0.95),
89
+ VideoResize(apply_to=self.video_keys, height=224, width=224, interpolation="linear"),
90
+ VideoColorJitter(
91
+ apply_to=self.video_keys,
92
+ brightness=0.3,
93
+ contrast=0.4,
94
+ saturation=0.5,
95
+ hue=0.08,
96
+ ),
97
+ VideoToNumpy(apply_to=self.video_keys),
98
+ # state transforms
99
+ StateActionToTensor(apply_to=self.state_keys),
100
+ StateActionTransform(
101
+ apply_to=self.state_keys,
102
+ normalization_modes={
103
+ "state.eef_position": "min_max",
104
+ "state.gripper_position": "min_max",
105
+ },
106
+ target_rotations={
107
+ "state.eef_rotation": "rotation_6d",
108
+ },
109
+ ),
110
+ # action transforms
111
+ StateActionToTensor(apply_to=self.action_keys),
112
+ StateActionTransform(
113
+ apply_to=self.action_keys,
114
+ normalization_modes={
115
+ "action.gripper_position": "binary",
116
+ },
117
+ target_rotations={"action.eef_rotation_delta": "axis_angle"},
118
+ ),
119
+ # concat transforms
120
+ ConcatTransform(
121
+ video_concat_order=self.video_keys,
122
+ state_concat_order=self.state_keys,
123
+ action_concat_order=self.action_keys,
124
+ ),
125
+ GR00TTransform(
126
+ state_horizon=len(self.observation_indices),
127
+ action_horizon=len(self.action_indices),
128
+ max_state_dim=64,
129
+ max_action_dim=32,
130
+ ),
131
+ ]
132
+
133
+ return ComposedModalityTransform(transforms=transforms)
134
+
135
+ class AgibotGenie1DataConfig(BaseDataConfig):
136
+ video_keys = [
137
+ "video.image_head_color",
138
+ "video.image_hand_left",
139
+ "video.image_hand_right",
140
+ ]
141
+ state_keys = [
142
+ # "state.camera_position",
143
+ "state.left_arm",
144
+ "state.left_gripper",
145
+ "state.right_arm",
146
+ "state.right_gripper",
147
+ "state.original_state_head_position",
148
+ "state.original_state_waist_position",
149
+ ]
150
+ action_keys = [
151
+ # "action.camera_position",
152
+ "action.left_arm",
153
+ "action.left_gripper",
154
+ "action.right_arm",
155
+ "action.right_gripper",
156
+ "action.original_action_head_position",
157
+ "action.original_action_waist_position",
158
+ ]
159
+ language_keys = ["annotation.human.task_description", "annotation.human.subtask_description"]
160
+ observation_indices = [0]
161
+ # action_indices = list(range(30))
162
+ action_indices = list(range(16))
163
+
164
+ def modality_config(self):
165
+ video_modality = ModalityConfig(
166
+ delta_indices=self.observation_indices,
167
+ modality_keys=self.video_keys,
168
+ )
169
+ state_modality = ModalityConfig(
170
+ delta_indices=self.observation_indices,
171
+ modality_keys=self.state_keys,
172
+ )
173
+ action_modality = ModalityConfig(
174
+ delta_indices=self.action_indices,
175
+ modality_keys=self.action_keys,
176
+ )
177
+ language_modality = ModalityConfig(
178
+ delta_indices=self.observation_indices,
179
+ modality_keys=self.language_keys,
180
+ )
181
+ modality_configs = {
182
+ "video": video_modality,
183
+ "state": state_modality,
184
+ "action": action_modality,
185
+ "language": language_modality,
186
+ }
187
+ return modality_configs
188
+
189
+ def transform(self):
190
+ transforms = [
191
+ # video transforms - 为每个视角分别应用,避免不同尺寸的 concatenation 错误
192
+ # 第一个视角:image_head_color
193
+ # VideoToTensor(apply_to=[self.video_keys[0]]),
194
+ # VideoResizePad(apply_to=[self.video_keys[0]], size=224, interpolation="linear", fill_value=0.0),
195
+ # VideoColorJitter(
196
+ # apply_to=[self.video_keys[0]],
197
+ # brightness=0.3,
198
+ # contrast=0.4,
199
+ # saturation=0.5,
200
+ # hue=0.08,
201
+ # ),
202
+ # VideoToNumpy(apply_to=[self.video_keys[0]]),
203
+
204
+ # 第二个视角:image_hand_left
205
+ # VideoToTensor(apply_to=[self.video_keys[1]]),
206
+ # VideoResizePad(apply_to=[self.video_keys[1]], size=224, interpolation="linear", fill_value=0.0),
207
+ # VideoColorJitter(
208
+ # apply_to=[self.video_keys[1]],
209
+ # brightness=0.3,
210
+ # contrast=0.4,
211
+ # saturation=0.5,
212
+ # hue=0.08,
213
+ # ),
214
+ # VideoToNumpy(apply_to=[self.video_keys[1]]),
215
+
216
+ # 第三个视角:image_hand_right
217
+ # VideoToTensor(apply_to=[self.video_keys[2]]),
218
+ # VideoResizePad(apply_to=[self.video_keys[2]], size=224, interpolation="linear", fill_value=0.0),
219
+ # VideoColorJitter(
220
+ # apply_to=[self.video_keys[2]],
221
+ # brightness=0.3,
222
+ # contrast=0.4,
223
+ # saturation=0.5,
224
+ # hue=0.08,
225
+ # ),
226
+ # VideoToNumpy(apply_to=[self.video_keys[2]]),
227
+
228
+ # state transforms
229
+ StateActionToTensor(apply_to=self.state_keys),
230
+ StateActionTransform(apply_to=self.state_keys,
231
+ normalization_modes={key: "min_max" for key in self.state_keys}),
232
+ # action transforms
233
+ StateActionToTensor(apply_to=self.action_keys),
234
+ StateActionTransform(
235
+ apply_to=self.action_keys,
236
+ normalization_modes={key: "min_max" for key in self.action_keys},
237
+ ),
238
+ # concat transforms - 现在所有视角都是 224x224,可以安全 concatenate
239
+ # ConcatTransform(
240
+ # video_concat_order=self.video_keys,
241
+ # state_concat_order=self.state_keys,
242
+ # action_concat_order=self.action_keys,
243
+ # ),
244
+ GR00TTransform(
245
+ state_horizon=len(self.observation_indices),
246
+ action_horizon=len(self.action_indices),
247
+ max_state_dim=64,
248
+ max_action_dim=32,
249
+ ),
250
+ ]
251
+
252
+ return ComposedModalityTransform(transforms=transforms)
253
+
254
+ # class EgoDexDataConfig(BaseDataConfig):
255
+ # video_keys = [
256
+ # "video.image"
257
+ # ]
258
+ # state_keys = [
259
+ # "state.right_pose",
260
+ # "state.right_hand",
261
+ # "state.left_pose",
262
+ # "state.left_hand"
263
+ # ]
264
+ # action_keys = [
265
+ # "action.right_pose",
266
+ # "action.right_hand",
267
+ # "action.left_pose",
268
+ # "action.left_hand"
269
+ # ]
270
+
271
+ # language_keys = ["annotation.human.task_description"]
272
+ # observation_indices = [0]
273
+ # # action_indices = list(range(16))
274
+ # action_indices = list(range(30))
275
+
276
+ # def modality_config(self):
277
+ # video_modality = ModalityConfig(
278
+ # delta_indices=self.observation_indices,
279
+ # modality_keys=self.video_keys,
280
+ # )
281
+ # state_modality = ModalityConfig(
282
+ # delta_indices=self.observation_indices,
283
+ # modality_keys=self.state_keys,
284
+ # )
285
+ # action_modality = ModalityConfig(
286
+ # delta_indices=self.action_indices,
287
+ # modality_keys=self.action_keys,
288
+ # )
289
+ # language_modality = ModalityConfig(
290
+ # delta_indices=self.observation_indices,
291
+ # modality_keys=self.language_keys,
292
+ # )
293
+ # modality_configs = {
294
+ # "video": video_modality,
295
+ # "state": state_modality,
296
+ # "action": action_modality,
297
+ # "language": language_modality,
298
+ # }
299
+ # return modality_configs
300
+
301
+ # def transform(self):
302
+ # transforms = [
303
+ # # video transforms
304
+ # VideoToTensor(apply_to=self.video_keys),
305
+ # # VideoCrop(apply_to=self.video_keys, scale=0.95),
306
+ # # VideoResize(apply_to=self.video_keys, height=224, width=224, interpolation="linear"),
307
+ # VideoResizePad(apply_to=self.video_keys, size=224, interpolation="linear", fill_value=0.0),
308
+ # VideoColorJitter(
309
+ # apply_to=self.video_keys,
310
+ # brightness=0.3,
311
+ # contrast=0.4,
312
+ # saturation=0.5,
313
+ # hue=0.08,
314
+ # ),
315
+ # VideoToNumpy(apply_to=self.video_keys),
316
+ # # state transforms
317
+ # StateActionToTensor(apply_to=self.state_keys),
318
+ # StateActionTransform(
319
+ # apply_to=self.state_keys,
320
+ # normalization_modes={
321
+ # "state.right_pose": "mean_std",
322
+ # "state.left_pose": "mean_std",
323
+ # "state.right_hand": "min_max",
324
+ # "state.left_hand": "min_max",
325
+ # },
326
+ # # normalization_modes={key: "min_max" for key in self.state_keys},
327
+ # ),
328
+ # # action transforms
329
+ # StateActionToTensor(apply_to=self.action_keys),
330
+ # StateActionTransform(
331
+ # apply_to=self.action_keys,
332
+ # normalization_modes={
333
+ # "action.right_pose": "mean_std",
334
+ # "action.left_pose": "mean_std",
335
+ # "action.right_hand": "min_max",
336
+ # "action.left_hand": "min_max",
337
+ # },
338
+ # # normalization_modes={key: "min_max" for key in self.action_keys},
339
+ # ),
340
+ # # concat transforms
341
+ # ConcatTransform(
342
+ # video_concat_order=self.video_keys,
343
+ # state_concat_order=self.state_keys,
344
+ # action_concat_order=self.action_keys,
345
+ # ),
346
+ # GR00TTransform(
347
+ # state_horizon=len(self.observation_indices),
348
+ # action_horizon=len(self.action_indices),
349
+ # max_state_dim=64,
350
+ # max_action_dim=32,
351
+ # ),
352
+ # ]
353
+
354
+ # return ComposedModalityTransform(transforms=transforms)
355
+
356
+ ###########################################################################################
357
+
358
+
359
+ class OxeBridgeDataConfig:
360
+ video_keys = [
361
+ "video.image_0",
362
+ ]
363
+ state_keys = [
364
+ "state.x",
365
+ "state.y",
366
+ "state.z",
367
+ "state.roll",
368
+ "state.pitch",
369
+ "state.yaw",
370
+ "state.pad",
371
+ "state.gripper",
372
+ ]
373
+ action_keys = [
374
+ "action.x",
375
+ "action.y",
376
+ "action.z",
377
+ "action.roll",
378
+ "action.pitch",
379
+ "action.yaw",
380
+ "action.gripper",
381
+ ]
382
+ language_keys = ["annotation.human.action.task_description"]
383
+ observation_indices = [0]
384
+ action_indices = list(range(16))
385
+
386
+ def modality_config(self):
387
+ video_modality = ModalityConfig(
388
+ delta_indices=self.observation_indices,
389
+ modality_keys=self.video_keys,
390
+ )
391
+ state_modality = ModalityConfig(
392
+ delta_indices=self.observation_indices,
393
+ modality_keys=self.state_keys,
394
+ )
395
+ action_modality = ModalityConfig(
396
+ delta_indices=self.action_indices,
397
+ modality_keys=self.action_keys,
398
+ )
399
+ language_modality = ModalityConfig(
400
+ delta_indices=self.observation_indices,
401
+ modality_keys=self.language_keys,
402
+ )
403
+ modality_configs = {
404
+ "video": video_modality,
405
+ "state": state_modality,
406
+ "action": action_modality,
407
+ "language": language_modality,
408
+ }
409
+ return modality_configs
410
+
411
+ def transform(self):
412
+ transforms = [
413
+ # video transforms
414
+ # VideoToTensor(apply_to=self.video_keys),
415
+ # VideoCrop(apply_to=self.video_keys, scale=0.95),
416
+ # VideoResize(apply_to=self.video_keys, height=224, width=224, interpolation="linear"),
417
+ # VideoColorJitter(
418
+ # apply_to=self.video_keys,
419
+ # brightness=0.3,
420
+ # contrast=0.4,
421
+ # saturation=0.5,
422
+ # hue=0.08,
423
+ # ),
424
+ # VideoToNumpy(apply_to=self.video_keys),
425
+ # state transforms
426
+ StateActionToTensor(apply_to=self.state_keys),
427
+ StateActionTransform(
428
+ apply_to=self.state_keys,
429
+ normalization_modes={
430
+ "state.x": "q99",
431
+ "state.y": "q99",
432
+ "state.z": "q99",
433
+ "state.roll": "q99",
434
+ "state.pitch": "q99",
435
+ "state.yaw": "q99",
436
+ "state.pad": "q99",
437
+ "state.gripper": "binary",
438
+ },
439
+ ),
440
+ # action transforms
441
+ StateActionToTensor(apply_to=self.action_keys),
442
+ StateActionTransform(
443
+ apply_to=self.action_keys,
444
+ normalization_modes={
445
+ "action.x": "q99",
446
+ "action.y": "q99",
447
+ "action.z": "q99",
448
+ "action.roll": "q99",
449
+ "action.pitch": "q99",
450
+ "action.yaw": "q99",
451
+ "action.gripper": "binary",
452
+ },
453
+ ),
454
+ # concat transforms
455
+ # ConcatTransform(
456
+ # # video_concat_order=self.video_keys,
457
+ # state_concat_order=self.state_keys,
458
+ # action_concat_order=self.action_keys,
459
+ # ),
460
+ # GR00TTransform(
461
+ # state_horizon=len(self.observation_indices),
462
+ # action_horizon=len(self.action_indices),
463
+ # max_state_dim=64,
464
+ # max_action_dim=32,
465
+ # ),
466
+ ]
467
+
468
+ return ComposedModalityTransform(transforms=transforms)
469
+
470
+
471
+ ###########################################################################################
472
+
473
+ class OxeRT1DataConfig:
474
+ video_keys = [
475
+ "video.image",
476
+ ]
477
+ state_keys = [
478
+ "state.x",
479
+ "state.y",
480
+ "state.z",
481
+ "state.rx",
482
+ "state.ry",
483
+ "state.rz",
484
+ "state.rw",
485
+ "state.gripper",
486
+ ]
487
+ action_keys = [
488
+ "action.x",
489
+ "action.y",
490
+ "action.z",
491
+ "action.roll",
492
+ "action.pitch",
493
+ "action.yaw",
494
+ "action.gripper",
495
+ ]
496
+ language_keys = ["annotation.human.action.task_description"]
497
+ observation_indices = [0]
498
+ action_indices = list(range(16))
499
+
500
+ def modality_config(self):
501
+ video_modality = ModalityConfig(
502
+ delta_indices=self.observation_indices,
503
+ modality_keys=self.video_keys,
504
+ )
505
+ state_modality = ModalityConfig(
506
+ delta_indices=self.observation_indices,
507
+ modality_keys=self.state_keys,
508
+ )
509
+ action_modality = ModalityConfig(
510
+ delta_indices=self.action_indices,
511
+ modality_keys=self.action_keys,
512
+ )
513
+ language_modality = ModalityConfig(
514
+ delta_indices=self.observation_indices,
515
+ modality_keys=self.language_keys,
516
+ )
517
+ modality_configs = {
518
+ "video": video_modality,
519
+ "state": state_modality,
520
+ "action": action_modality,
521
+ "language": language_modality,
522
+ }
523
+ return modality_configs
524
+
525
+ def transform(self):
526
+ transforms = [
527
+ # video transforms
528
+ # VideoToTensor(apply_to=self.video_keys),
529
+ # VideoCrop(apply_to=self.video_keys, scale=0.95),
530
+ # VideoResize(apply_to=self.video_keys, height=224, width=224, interpolation="linear"),
531
+ # VideoColorJitter(
532
+ # apply_to=self.video_keys,
533
+ # brightness=0.3,
534
+ # contrast=0.4,
535
+ # saturation=0.5,
536
+ # hue=0.08,
537
+ # ),
538
+ # VideoToNumpy(apply_to=self.video_keys),
539
+ # state transforms
540
+ StateActionToTensor(apply_to=self.state_keys),
541
+ StateActionTransform(
542
+ apply_to=self.state_keys,
543
+ normalization_modes={
544
+ "state.x": "q99",
545
+ "state.y": "q99",
546
+ "state.z": "q99",
547
+ "state.rx": "q99",
548
+ "state.ry": "q99",
549
+ "state.rz": "q99",
550
+ "state.rw": "q99",
551
+ "state.gripper": "binary",
552
+ },
553
+ ),
554
+ # action transforms
555
+ StateActionToTensor(apply_to=self.action_keys),
556
+ StateActionTransform(
557
+ apply_to=self.action_keys,
558
+ normalization_modes={
559
+ "action.x": "q99",
560
+ "action.y": "q99",
561
+ "action.z": "q99",
562
+ "action.roll": "q99",
563
+ "action.pitch": "q99",
564
+ "action.yaw": "q99",
565
+ "action.gripper": "binary",
566
+ },
567
+ ),
568
+ # concat transforms
569
+ # ConcatTransform(
570
+ # # video_concat_order=self.video_keys,
571
+ # state_concat_order=self.state_keys,
572
+ # action_concat_order=self.action_keys,
573
+ # ),
574
+ # GR00TTransform(
575
+ # state_horizon=len(self.observation_indices),
576
+ # action_horizon=len(self.action_indices),
577
+ # max_state_dim=64,
578
+ # max_action_dim=32,
579
+ # ),
580
+ ]
581
+
582
+ return ComposedModalityTransform(transforms=transforms)
583
+
584
+
585
+ ###########################################################################################
586
+
587
+
588
+ class SingleFrankaRobotiqDeltaEefDataConfig:
589
+ video_keys = [
590
+ "video.base_view",
591
+ "video.ego_view",
592
+ ]
593
+ state_keys = [
594
+ "state.eef_position",
595
+ "state.eef_rotation",
596
+ ]
597
+ action_keys = [
598
+ "action.delta_eef_position",
599
+ "action.delta_eef_rotation",
600
+ "action.gripper_close",
601
+ ]
602
+
603
+ language_keys = ["annotation.human.action.task_description"]
604
+ observation_indices = [0]
605
+ action_indices = list(range(16))
606
+
607
+ def modality_config(self):
608
+ video_modality = ModalityConfig(
609
+ delta_indices=self.observation_indices,
610
+ modality_keys=self.video_keys,
611
+ )
612
+ state_modality = ModalityConfig(
613
+ delta_indices=self.observation_indices,
614
+ modality_keys=self.state_keys,
615
+ )
616
+ action_modality = ModalityConfig(
617
+ delta_indices=self.action_indices,
618
+ modality_keys=self.action_keys,
619
+ )
620
+ language_modality = ModalityConfig(
621
+ delta_indices=self.observation_indices,
622
+ modality_keys=self.language_keys,
623
+ )
624
+ modality_configs = {
625
+ "video": video_modality,
626
+ "state": state_modality,
627
+ "action": action_modality,
628
+ "language": language_modality,
629
+ }
630
+ return modality_configs
631
+
632
+ def transform(self):
633
+ transforms = [
634
+ # state transforms
635
+ StateActionToTensor(apply_to=self.state_keys),
636
+ StateActionTransform(
637
+ apply_to=self.state_keys,
638
+ normalization_modes={
639
+ "state.eef_position": "min_max",
640
+ "state.eef_rotation": "min_max",
641
+ },
642
+ ),
643
+ # action transforms
644
+ StateActionToTensor(apply_to=self.action_keys),
645
+ StateActionTransform(
646
+ apply_to=self.action_keys,
647
+ normalization_modes={
648
+ "action.delta_eef_position": "min_max",
649
+ "action.delta_eef_rotation": "min_max",
650
+ "action.gripper_close": "binary",
651
+ },
652
+ ),
653
+ ]
654
+
655
+ return ComposedModalityTransform(transforms=transforms)
656
+
657
+ ###########################################################################################
658
+
659
+ class Libero4in1DataConfig:
660
+ video_keys = [
661
+ "video.primary_image",
662
+ "video.wrist_image",
663
+ ]
664
+
665
+ state_keys = [
666
+ "state.x",
667
+ "state.y",
668
+ "state.z",
669
+ "state.roll",
670
+ "state.pitch",
671
+ "state.yaw",
672
+ "state.pad",
673
+ "state.gripper",
674
+ ]
675
+ action_keys = [
676
+ "action.x",
677
+ "action.y",
678
+ "action.z",
679
+ "action.roll",
680
+ "action.pitch",
681
+ "action.yaw",
682
+ "action.gripper",
683
+ ]
684
+
685
+ language_keys = ["annotation.human.action.task_description"]
686
+
687
+ observation_indices = [0]
688
+ action_indices = list(range(8))
689
+
690
+
691
+ def modality_config(self):
692
+ video_modality = ModalityConfig(
693
+ delta_indices=self.observation_indices,
694
+ modality_keys=self.video_keys,
695
+ )
696
+ state_modality = ModalityConfig(
697
+ delta_indices=self.observation_indices,
698
+ modality_keys=self.state_keys,
699
+ )
700
+ action_modality = ModalityConfig(
701
+ delta_indices=self.action_indices,
702
+ modality_keys=self.action_keys,
703
+ )
704
+ language_modality = ModalityConfig(
705
+ delta_indices=self.observation_indices,
706
+ modality_keys=self.language_keys,
707
+ )
708
+ modality_configs = {
709
+ "video": video_modality,
710
+ "state": state_modality,
711
+ "action": action_modality,
712
+ "language": language_modality,
713
+ }
714
+ return modality_configs
715
+
716
+ def transform(self):
717
+ transforms = [
718
+ # action transforms
719
+ StateActionToTensor(apply_to=self.action_keys),
720
+ StateActionTransform(
721
+ apply_to=self.action_keys,
722
+ normalization_modes={
723
+ "action.x": "min_max",
724
+ "action.y": "min_max",
725
+ "action.z": "min_max",
726
+ "action.roll": "min_max",
727
+ "action.pitch": "min_max",
728
+ "action.yaw": "min_max",
729
+ },
730
+ ),
731
+ ]
732
+
733
+ return ComposedModalityTransform(transforms=transforms)
734
+
735
+ ###########################################################################################
736
+
737
+
738
+ class SingleFrankaRobotiqDeltaJointsDataConfig:
739
+ video_keys = [
740
+ "video.base_view",
741
+ "video.ego_view",
742
+ ]
743
+ state_keys = [
744
+ "state.joints",
745
+ ]
746
+ action_keys = [
747
+ "action.delta_joints",
748
+ "action.gripper_close",
749
+ ]
750
+
751
+ language_keys = ["annotation.human.action.task_description"]
752
+ observation_indices = [0]
753
+ action_indices = list(range(16))
754
+
755
+ def modality_config(self):
756
+ video_modality = ModalityConfig(
757
+ delta_indices=self.observation_indices,
758
+ modality_keys=self.video_keys,
759
+ )
760
+ state_modality = ModalityConfig(
761
+ delta_indices=self.observation_indices,
762
+ modality_keys=self.state_keys,
763
+ )
764
+ action_modality = ModalityConfig(
765
+ delta_indices=self.action_indices,
766
+ modality_keys=self.action_keys,
767
+ )
768
+ language_modality = ModalityConfig(
769
+ delta_indices=self.observation_indices,
770
+ modality_keys=self.language_keys,
771
+ )
772
+ modality_configs = {
773
+ "video": video_modality,
774
+ "state": state_modality,
775
+ "action": action_modality,
776
+ "language": language_modality,
777
+ }
778
+ return modality_configs
779
+
780
+ def transform(self):
781
+ transforms = [
782
+ # state transforms
783
+ StateActionToTensor(apply_to=self.state_keys),
784
+ StateActionTransform(
785
+ apply_to=self.state_keys,
786
+ normalization_modes={
787
+ "state.joints": "min_max",
788
+ },
789
+ ),
790
+ # action transforms
791
+ StateActionToTensor(apply_to=self.action_keys),
792
+ StateActionTransform(
793
+ apply_to=self.action_keys,
794
+ normalization_modes={
795
+ "action.delta_joints": "min_max",
796
+ "action.gripper_close": "binary",
797
+ },
798
+ ),
799
+ ]
800
+
801
+ return ComposedModalityTransform(transforms=transforms)
802
+
803
+
804
+ ###########################################################################################
805
+
806
+ class FourierGr1ArmsWaistDataConfig:
807
+ video_keys = ["video.ego_view"]
808
+ state_keys = [
809
+ "state.left_arm",
810
+ "state.right_arm",
811
+ "state.left_hand",
812
+ "state.right_hand",
813
+ "state.waist",
814
+ ]
815
+ action_keys = [
816
+ "action.left_arm",
817
+ "action.right_arm",
818
+ "action.left_hand",
819
+ "action.right_hand",
820
+ "action.waist",
821
+ ]
822
+ language_keys = ["annotation.human.coarse_action"]
823
+ observation_indices = [0]
824
+ action_indices = list(range(16))
825
+
826
+
827
+ def modality_config(self):
828
+ video_modality = ModalityConfig(
829
+ delta_indices=self.observation_indices,
830
+ modality_keys=self.video_keys,
831
+ )
832
+ state_modality = ModalityConfig(
833
+ delta_indices=self.observation_indices,
834
+ modality_keys=self.state_keys,
835
+ )
836
+ action_modality = ModalityConfig(
837
+ delta_indices=self.action_indices,
838
+ modality_keys=self.action_keys,
839
+ )
840
+ language_modality = ModalityConfig(
841
+ delta_indices=self.observation_indices,
842
+ modality_keys=self.language_keys,
843
+ )
844
+ modality_configs = {
845
+ "video": video_modality,
846
+ "state": state_modality,
847
+ "action": action_modality,
848
+ "language": language_modality,
849
+ }
850
+ return modality_configs
851
+
852
+ def transform(self) -> ModalityTransform:
853
+ transforms = [
854
+ # video transforms
855
+ # VideoToTensor(apply_to=self.video_keys),
856
+ # VideoCrop(apply_to=self.video_keys, scale=0.95),
857
+ # VideoResize(apply_to=self.video_keys, height=224, width=224, interpolation="linear"),
858
+ # VideoResizePad(apply_to=self.video_keys, size=224, interpolation="linear", fill_value=0.0),
859
+ # VideoColorJitter(
860
+ # apply_to=self.video_keys,
861
+ # brightness=0.3,
862
+ # contrast=0.4,
863
+ # saturation=0.5,
864
+ # hue=0.08,
865
+ # ),
866
+ # VideoToNumpy(apply_to=self.video_keys),
867
+ # state transforms
868
+ StateActionToTensor(apply_to=self.state_keys),
869
+ # StateActionSinCosTransform(apply_to=self.state_keys),
870
+ StateActionTransform(
871
+ apply_to=self.state_keys,
872
+ normalization_modes={key: "min_max" for key in self.state_keys},
873
+ ),
874
+
875
+ # action transforms
876
+ StateActionToTensor(apply_to=self.action_keys),
877
+ StateActionTransform(
878
+ apply_to=self.action_keys,
879
+ normalization_modes={key: "min_max" for key in self.action_keys},
880
+ ),
881
+ # concat transforms
882
+ # ConcatTransform(
883
+ # video_concat_order=self.video_keys,
884
+ # state_concat_order=self.state_keys,
885
+ # action_concat_order=self.action_keys,
886
+ # ),
887
+ # concat transforms
888
+ # ConcatTransform(
889
+ # video_concat_order=self.video_keys,
890
+ # state_concat_order=self.state_keys,
891
+ # action_concat_order=self.action_keys,
892
+ # ),
893
+ GR00TTransform(
894
+ state_horizon=len(self.observation_indices),
895
+ action_horizon=len(self.action_indices),
896
+ max_state_dim=64,
897
+ max_action_dim=32,
898
+ ),
899
+ ]
900
+ return ComposedModalityTransform(transforms=transforms)
901
+
902
+
903
+ ###########################################################################################
904
+
905
+ class EgoDexDataConfig(FourierGr1ArmsWaistDataConfig):
906
+ video_keys = [
907
+ "video.image"
908
+ ]
909
+ state_keys = [
910
+ "state.right_pose",
911
+ "state.right_hand",
912
+ "state.left_pose",
913
+ "state.left_hand"
914
+ ]
915
+ action_keys = [
916
+ "action.right_pose",
917
+ "action.right_hand",
918
+ "action.left_pose",
919
+ "action.left_hand"
920
+ ]
921
+
922
+ language_keys = ["annotation.human.task_description"]
923
+ observation_indices = [0]
924
+ action_indices = list(range(16))
925
+ # action_indices = list(range(30))
926
+
927
+
928
+ class NvwaDataConfig(EgoDexDataConfig):
929
+ language_keys = ["annotation.human.task_description", "annotation.human.subtask_description"]
930
+
931
+
932
+ class RoboTwinDataConfig(AgibotGenie1DataConfig):
933
+ video_keys = ["video.image_high", "video.image_left_wrist", "video.image_right_wrist"]
934
+ state_keys = [
935
+ "state.left_arm",
936
+ "state.left_gripper",
937
+ "state.right_arm",
938
+ "state.right_gripper",
939
+ ]
940
+ action_keys = [
941
+ "action.left_arm",
942
+ "action.left_gripper",
943
+ "action.right_arm",
944
+ "action.right_gripper",
945
+ ]
946
+ language_keys = ["annotation.human.task_description"]
947
+ observation_indices = [0]
948
+ action_indices = list(range(50))
949
+
950
+
951
+ ###########################################################################################
952
+
953
+ class SO101Config:
954
+ #input
955
+ video_keys = [
956
+ "video.primary_image",
957
+ "video.wrist_image",
958
+ ]
959
+
960
+ state_keys = [
961
+ "state.shoulder_pan.pos",
962
+ "state.shoulder_lift.pos",
963
+ "state.elbow_flex.pos",
964
+ "state.wrist_flex.pos",
965
+ "state.wrist_roll.pos",
966
+ "state.gripper.pos",
967
+ ]
968
+ language_keys = ["annotation.human.action.task_description"]
969
+
970
+ # output
971
+ action_keys = [
972
+ "action.shoulder_pan.pos",
973
+ "action.shoulder_lift.pos",
974
+ "action.elbow_flex.pos",
975
+ "action.wrist_flex.pos",
976
+ "action.wrist_roll.pos",
977
+ "action.gripper.pos",
978
+ ]
979
+
980
+
981
+ observation_indices = [0]
982
+ action_indices = list(range(16))
983
+
984
+
985
+ def modality_config(self):
986
+ video_modality = ModalityConfig(
987
+ delta_indices=self.observation_indices,
988
+ modality_keys=self.video_keys,
989
+ )
990
+ state_modality = ModalityConfig(
991
+ delta_indices=self.observation_indices,
992
+ modality_keys=self.state_keys,
993
+ )
994
+ action_modality = ModalityConfig(
995
+ delta_indices=self.action_indices,
996
+ modality_keys=self.action_keys,
997
+ )
998
+ language_modality = ModalityConfig(
999
+ delta_indices=self.observation_indices,
1000
+ modality_keys=self.language_keys,
1001
+ )
1002
+ modality_configs = {
1003
+ "video": video_modality,
1004
+ "state": state_modality,
1005
+ "action": action_modality,
1006
+ "language": language_modality,
1007
+ }
1008
+ return modality_configs
1009
+
1010
+ def transform(self):
1011
+ transforms = [
1012
+ # state transforms
1013
+ StateActionToTensor(apply_to=self.state_keys),
1014
+ StateActionTransform(
1015
+ apply_to=self.state_keys,
1016
+ normalization_modes={
1017
+ key: "min_max" for key in self.state_keys
1018
+ },
1019
+ ),
1020
+ # action transforms
1021
+ StateActionToTensor(apply_to=self.action_keys),
1022
+ StateActionTransform(
1023
+ apply_to=self.action_keys,
1024
+ normalization_modes={
1025
+ key: "min_max" for key in self.action_keys
1026
+ },
1027
+ ),
1028
+ ]
1029
+
1030
+ return ComposedModalityTransform(transforms=transforms)
1031
+
1032
+
1033
+
1034
+ class ArxX5DataConfig:
1035
+ video_keys = [
1036
+ "video.cam_high",
1037
+ "video.cam_left_wrist",
1038
+ "video.cam_right_wrist",
1039
+ ]
1040
+ state_keys = [
1041
+ "state.left_joints",
1042
+ "state.right_joints",
1043
+ "state.left_gripper",
1044
+ "state.right_gripper",
1045
+ ]
1046
+ action_keys = [
1047
+ "action.left_joints",
1048
+ "action.right_joints",
1049
+ "action.left_gripper",
1050
+ "action.right_gripper",
1051
+ ]
1052
+
1053
+ language_keys = ["annotation.human.action.task_description"]
1054
+ observation_indices = [0]
1055
+ action_indices = list(range(16))
1056
+
1057
+ def modality_config(self):
1058
+ video_modality = ModalityConfig(
1059
+ delta_indices=self.observation_indices,
1060
+ modality_keys=self.video_keys,
1061
+ )
1062
+ state_modality = ModalityConfig(
1063
+ delta_indices=self.observation_indices,
1064
+ modality_keys=self.state_keys,
1065
+ )
1066
+ action_modality = ModalityConfig(
1067
+ delta_indices=self.action_indices,
1068
+ modality_keys=self.action_keys,
1069
+ )
1070
+ language_modality = ModalityConfig(
1071
+ delta_indices=self.observation_indices,
1072
+ modality_keys=self.language_keys,
1073
+ )
1074
+ modality_configs = {
1075
+ "video": video_modality,
1076
+ "state": state_modality,
1077
+ "action": action_modality,
1078
+ "language": language_modality,
1079
+ }
1080
+ return modality_configs
1081
+
1082
+ def transform(self):
1083
+ transforms = [
1084
+ # state transforms
1085
+ StateActionToTensor(apply_to=self.state_keys),
1086
+ StateActionTransform(
1087
+ apply_to=self.state_keys,
1088
+ normalization_modes={
1089
+ "state.left_joints": "min_max",
1090
+ "state.right_joints": "min_max",
1091
+ "state.left_gripper": "binary",
1092
+ "state.right_gripper": "binary",
1093
+ },
1094
+ ),
1095
+ # action transforms
1096
+ StateActionToTensor(apply_to=self.action_keys),
1097
+ StateActionTransform(
1098
+ apply_to=self.action_keys,
1099
+ normalization_modes={
1100
+ "action.left_joints": "min_max",
1101
+ "action.right_joints": "min_max",
1102
+ "action.left_gripper": "binary",
1103
+ "action.right_gripper": "binary",
1104
+ },
1105
+ ),
1106
+ ]
1107
+
1108
+ return ComposedModalityTransform(transforms=transforms)
1109
+
1110
+ ###########################################################################################
1111
+
1112
+
1113
+ class AgilexDataConfig:
1114
+ video_keys = [
1115
+ "video.cam_high",
1116
+ "video.cam_left_wrist",
1117
+ "video.cam_right_wrist",
1118
+ ]
1119
+ state_keys = [
1120
+ "state.left_joints",
1121
+ "state.right_joints",
1122
+ "state.left_gripper",
1123
+ "state.right_gripper",
1124
+ ]
1125
+ action_keys = [
1126
+ "action.left_joints",
1127
+ "action.right_joints", #@JinhuiYE this order is different from Dataset
1128
+ "action.left_gripper",
1129
+ "action.right_gripper",
1130
+ ]
1131
+
1132
+ language_keys = ["annotation.human.action.task_description"]
1133
+ observation_indices = [0]
1134
+ action_indices = list(range(16))
1135
+
1136
+ def modality_config(self):
1137
+ video_modality = ModalityConfig(
1138
+ delta_indices=self.observation_indices,
1139
+ modality_keys=self.video_keys,
1140
+ )
1141
+ state_modality = ModalityConfig(
1142
+ delta_indices=self.observation_indices,
1143
+ modality_keys=self.state_keys,
1144
+ )
1145
+ action_modality = ModalityConfig(
1146
+ delta_indices=self.action_indices,
1147
+ modality_keys=self.action_keys,
1148
+ )
1149
+ language_modality = ModalityConfig(
1150
+ delta_indices=self.observation_indices,
1151
+ modality_keys=self.language_keys,
1152
+ )
1153
+ modality_configs = {
1154
+ "video": video_modality,
1155
+ "state": state_modality,
1156
+ "action": action_modality,
1157
+ "language": language_modality,
1158
+ }
1159
+ return modality_configs
1160
+
1161
+ def transform(self):
1162
+ transforms = [
1163
+ # state transforms
1164
+ StateActionToTensor(apply_to=self.state_keys),
1165
+ StateActionTransform(
1166
+ apply_to=self.state_keys,
1167
+ normalization_modes={
1168
+ "state.left_joints": "min_max",
1169
+ "state.right_joints": "min_max",
1170
+ "state.left_gripper": "binary",
1171
+ "state.right_gripper": "binary",
1172
+ },
1173
+ ),
1174
+ # action transforms
1175
+ StateActionToTensor(apply_to=self.action_keys),
1176
+ StateActionTransform(
1177
+ apply_to=self.action_keys,
1178
+ normalization_modes={
1179
+ "action.left_joints": "min_max",
1180
+ "action.right_joints": "min_max",
1181
+ "action.left_gripper": "binary",
1182
+ "action.right_gripper": "binary",
1183
+ },
1184
+ ),
1185
+ ]
1186
+
1187
+ return ComposedModalityTransform(transforms=transforms)
1188
+
1189
+ ###########################################################################################
1190
+
1191
+
1192
+ ROBOT_TYPE_CONFIG_MAP = {
1193
+ "libero_franka": Libero4in1DataConfig(),
1194
+ "oxe_droid": OxeDroidDataConfig(),
1195
+ "oxe_bridge": OxeBridgeDataConfig(),
1196
+ "oxe_rt1": OxeRT1DataConfig(),
1197
+ "SO101": SO101Config(),
1198
+ "demo_sim_franka_delta_joints": SingleFrankaRobotiqDeltaJointsDataConfig(),
1199
+ "arx_x5": ArxX5DataConfig(),
1200
+ "robotwin": RoboTwinDataConfig(),
1201
+ "fourier_gr1_arms_waist": FourierGr1ArmsWaistDataConfig(),
1202
+ "fourier_gr1_arms_waist2": FourierGr1ArmsWaistDataConfig(),
1203
+ "agibot_genie1": AgibotGenie1DataConfig(),
1204
+ "agibot_beta": AgibotGenie1DataConfig(),
1205
+ "egodex": EgoDexDataConfig(),
1206
+ "nvwa_f": NvwaDataConfig(),
1207
+ "custom_robot_config": SingleFrankaRobotiqDeltaEefDataConfig(),
1208
+ }
starVLA/dataloader/gr00t_lerobot/datasets.py ADDED
The diff for this file is too large to render. See raw diff
 
starVLA/dataloader/gr00t_lerobot/embodiment_tags.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from enum import Enum
17
+
18
+
19
+ class EmbodimentTag(Enum):
20
+ GR1 = "gr1"
21
+ """
22
+ The GR1 dataset.
23
+ """
24
+
25
+ ActionNet = "action_net"
26
+ """
27
+ The ActionNet dataset.
28
+ """
29
+
30
+ OXE_DROID = "oxe_droid"
31
+ """
32
+ The OxE Droid dataset.
33
+ """
34
+
35
+ OXE_BRIDGE = "oxe_bridge"
36
+ """
37
+ The OxE Bridge dataset.
38
+ """
39
+
40
+ OXE_RT1 = "oxe_rt1"
41
+ """
42
+ The OxE RT-1 dataset.
43
+ """
44
+
45
+ AGIBOT_GENIE1 = "agibot_genie1"
46
+ """
47
+ The AgiBot Genie-1 with gripper dataset.
48
+ """
49
+
50
+ AGIBOT_BETA = "agibot_beta"
51
+ """
52
+ The AgiBot Genie-1 with gripper dataset.
53
+ """
54
+
55
+ EGODEX = "egodex"
56
+ """
57
+ The AgiBot Genie-1 with gripper dataset.
58
+ """
59
+
60
+ NVWA_F = "nvwa_f"
61
+ """
62
+ The AgiBot Genie-1 with gripper dataset.
63
+ """
64
+
65
+ ROBOTWIN = "robotwin"
66
+ """
67
+ The AgiBot Genie-1 with gripper dataset.
68
+ """
69
+
70
+ NEW_EMBODIMENT = "new_embodiment"
71
+ """
72
+ Any new embodiment for finetuning.
73
+ """
74
+
75
+ FRANKA = 'franka'
76
+ """
77
+ The Franka Emika Panda robot.
78
+ """
79
+
80
+ # Embodiment tag string: to projector index in the Action Expert Module
81
+ EMBODIMENT_TAG_MAPPING = {
82
+ EmbodimentTag.NEW_EMBODIMENT.value: 31,
83
+ EmbodimentTag.OXE_DROID.value: 17,
84
+ EmbodimentTag.OXE_BRIDGE.value: 18,
85
+ EmbodimentTag.OXE_RT1.value: 19,
86
+ EmbodimentTag.AGIBOT_GENIE1.value: 26,
87
+ EmbodimentTag.GR1.value: 24,
88
+ EmbodimentTag.FRANKA.value: 25,
89
+ EmbodimentTag.ActionNet.value: 27,
90
+ EmbodimentTag.AGIBOT_BETA.value: 28,
91
+ EmbodimentTag.EGODEX.value: 29,
92
+ EmbodimentTag.NVWA_F.value: 30,
93
+ EmbodimentTag.ROBOTWIN.value: 32
94
+ }
95
+
96
+ # Robot type to embodiment tag mapping
97
+ ROBOT_TYPE_TO_EMBODIMENT_TAG = {
98
+ "libero_franka": EmbodimentTag.FRANKA,
99
+ "oxe_droid": EmbodimentTag.OXE_DROID,
100
+ "oxe_bridge": EmbodimentTag.OXE_BRIDGE,
101
+ "oxe_rt1": EmbodimentTag.OXE_RT1,
102
+ "demo_sim_franka_delta_joints": EmbodimentTag.FRANKA,
103
+ "custom_robot_config": EmbodimentTag.NEW_EMBODIMENT,
104
+ "egodex": EmbodimentTag.EGODEX,
105
+ "fourier_gr1_arms_waist": EmbodimentTag.GR1,
106
+ "fourier_gr1_arms_waist2": EmbodimentTag.ActionNet,
107
+ "agibot_genie1": EmbodimentTag.AGIBOT_GENIE1,
108
+ "agibot_beta": EmbodimentTag.AGIBOT_BETA,
109
+ "nvwa_f": EmbodimentTag.NVWA_F,
110
+ "robotwin": EmbodimentTag.ROBOTWIN
111
+ }
starVLA/dataloader/gr00t_lerobot/mixtures.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ mixtures.py
3
+
4
+ Defines a registry of dataset mixtures and weights for the Open-X Embodiment Datasets. Each dataset is associated with
5
+ a float "sampling weight"
6
+ """
7
+
8
+ from typing import Dict, List, Tuple
9
+
10
+ # Dataset mixture name mapped to a list of tuples containing:
11
+ ## {nakename: [(data_name, sampling_weight, robot_type)] }
12
+ DATASET_NAMED_MIXTURES = {
13
+ "suqian_test": [("lerobot_subtask_full_modified_split_test_modified", 1.0, "agibot_genie1"),],
14
+ "suqian_train": [("task_170_modified", 1.0, "agibot_genie1"),],
15
+ "robocasa_300_ee": [("robocasa_24tasks_datasets/pick_and_place_lerobot_task24_sampled_300_epose_merged", 1.0, "fourier_gr1_arms_waist"),
16
+ ],
17
+ "custom_dataset": [("custom_dataset_name", 1.0, "custom_robot_config"),],
18
+ "custom_dataset_2": [
19
+ ("custom_dataset_name_1", 1.0, "custom_robot_config"),
20
+ ("custom_dataset_name_2", 1.0, "custom_robot_config"),
21
+ ],
22
+ "ego_dex": [("", 1.0, "ego_dex"),],
23
+ "ego_dex_suqian_agi": [
24
+ ("users/chenzengjue/ego30w_f_2kw", 1.0, "ego_dex"),
25
+ ("datasets/suqian_agibot_lerobot_data/task_170_modified", 1.0, "agibot_genie1"),
26
+ ],
27
+ "sq_agi-beta_egodex-f": [
28
+ ("../../workspace1/datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part1", 1.0,
29
+ "agibot_beta"),
30
+ ("../../workspace1/datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part2", 1.0,
31
+ "agibot_beta"),
32
+ ("../../workspace1/datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part3", 1.0,
33
+ "agibot_beta"),
34
+ ("../../workspace1/datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part4", 1.0,
35
+ "agibot_beta"),
36
+ ("../../workspace1/datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part5", 1.0,
37
+ "agibot_beta"),
38
+ # ("../../workspace1/datasets/G1_task_all_merged-new/datasets-G1_task_all", 1.0, "agibot_genie1"),
39
+ ("egodex30w_datasets/egodex_merge30w_fourier", 1.0, "egodex"),
40
+ # ('../../workspace1/datasets/PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose_merged', 1.0, 'fourier_gr1_arms_waist'),
41
+ # ("robotwin_dataset/dataset_lerobot/aloha-agilex_550_single_task_eepose_merged", 1.0, "robotwin"),
42
+ ],
43
+ "sq_robocasa": [
44
+ ("datasets/G1_task_all_merged-new_0508/datasets-G1_task_all_0508", 1.0, "agibot_genie1"),
45
+ # ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part1", 1.0, "agibot_beta"),
46
+ # ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part2", 1.0, "agibot_beta"),
47
+ # ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part3", 1.0, "agibot_beta"),
48
+ # ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part4", 1.0, "agibot_beta"),
49
+ # ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part5", 1.0, "agibot_beta"),
50
+ # ("../../workspace1/datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part5", 1.0,
51
+ # "agibot_beta"),
52
+ # ("../../workspace1/datasets/G1_task_all_merged-new/datasets-G1_task_all", 1.0, "agibot_genie1"),
53
+ # ("egodex30w_datasets/egodex_merge30w_fourier", 1.0, "egodex"),
54
+ ('datasets/PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose_merged', 1.0, 'fourier_gr1_arms_waist'),
55
+ # ("robotwin_dataset/dataset_lerobot/aloha-agilex_550_single_task_eepose_merged", 1.0, "robotwin"),
56
+ ],
57
+ "sq_agi-beta_robocasa": [
58
+ ("datasets/G1_task_all_merged-new_0508/datasets-G1_task_all_0508", 1.0, "agibot_genie1"),
59
+ ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part1", 1.0, "agibot_beta"),
60
+ ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part2", 1.0, "agibot_beta"),
61
+ ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part3", 1.0, "agibot_beta"),
62
+ ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part4", 1.0, "agibot_beta"),
63
+ ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part5", 1.0, "agibot_beta"),
64
+ # ("../../workspace1/datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part5", 1.0,
65
+ # "agibot_beta"),
66
+ # ("../../workspace1/datasets/G1_task_all_merged-new/datasets-G1_task_all", 1.0, "agibot_genie1"),
67
+ # ("egodex30w_datasets/egodex_merge30w_fourier", 1.0, "egodex"),
68
+ ('datasets/PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose_merged', 1.0, 'fourier_gr1_arms_waist'),
69
+ # ("robotwin_dataset/dataset_lerobot/aloha-agilex_550_single_task_eepose_merged", 1.0, "robotwin"),
70
+ ],
71
+ "robocasa_merge": [
72
+ ('../../workspace1/datasets/PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose_merged', 1.0, 'fourier_gr1_arms_waist'),
73
+ ],
74
+ "sq_egodex-f_robotwin_robocasa": [
75
+ ("egodex30w_datasets/egodex_merge30w_fourier", 1.0, "egodex"),
76
+ ("suqian_agibot_lerobot_data/task_170_modified_yzh", 1.0, "agibot_genie1"),
77
+ # ("AgiBotWorld-Beta-LeRobot", 1.0, "agibot_beta"),
78
+ ('../../workspace1/datasets/PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose_merged', 1.0, 'fourier_gr1_arms_waist'),
79
+ ("robotwin_dataset/dataset_lerobot/aloha-agilex_550_single_task_eepose_merged", 1.0, "robotwin"),
80
+ ],
81
+ "sq_agi-beta_egodex-f_robotwin_robocasa": [
82
+ ("egodex30w_datasets/egodex_merge30w_fourier", 1.0, "egodex"),
83
+ ("suqian_agibot_lerobot_data/task_170_modified_yzh", 1.0, "agibot_genie1"),
84
+ ("AgiBotWorld-Beta-LeRobot", 1.0, "agibot_beta"),
85
+ ('../../workspace1/datasets/PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose_merged', 1.0, 'fourier_gr1_arms_waist'),
86
+ ("robotwin_dataset/dataset_lerobot/aloha-agilex_550_single_task_eepose_merged", 1.0, "robotwin"),
87
+ ],
88
+ "sq_agi-beta_egodex-f_nvwa-f_robotwin_robocasa": [
89
+ ("datasets/G1_task_all_merged-new_0508/datasets-G1_task_all_0508", 1.0, "agibot_genie1"),
90
+ ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part1", 1.0, "agibot_beta"),
91
+ ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part2", 1.0, "agibot_beta"),
92
+ ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part3", 1.0, "agibot_beta"),
93
+ ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part4", 1.0, "agibot_beta"),
94
+ ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part5", 1.0, "agibot_beta"),
95
+ ("../workspace/datasets/egodex30w_datasets/egodex_merge30w_fourier", 1.0, "egodex"),
96
+ ('datasets/PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose_merged', 1.0, 'fourier_gr1_arms_waist'),
97
+ ("../workspace/datasets/robotwin_dataset/dataset_lerobot/aloha-agilex_550_single_task_eepose_merged", 1.0, "robotwin"),
98
+ ("../workspace/users/liyihang/nvwa2lerobot2/retarget_fourier_20260318_890h_re/lerobot_data", 0.1, "nvwa_f"),
99
+ ("../workspace/users/liyihang/nvwa2lerobot2/retarget_fourier_1000h_re/lerobot_data", 0.1, "nvwa_f"),
100
+ # ("users/jinshibo/nvwa2lerobot/retarget_fourier_20260408_658h/lerobot_data", 0.1, "nvwa_f"),
101
+ ],
102
+ "robotwin_ee": [
103
+ ("robotwin_dataset/dataset_lerobot/aloha-agilex_550_single_task_eepose_merged", 1.0, "robotwin"),
104
+ ],
105
+ "robotwin_robocasa": [
106
+ ('../../workspace1/datasets/PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose_merged', 1.0, 'fourier_gr1_arms_waist'),
107
+ ("robotwin_dataset/dataset_lerobot/aloha-agilex_550_single_task_eepose_merged", 1.0, "robotwin"),
108
+ ],
109
+ "libero_all": [
110
+ ("libero_object_no_noops_1.0.0_lerobot", 1.0, "libero_franka"),
111
+ ("libero_goal_no_noops_1.0.0_lerobot", 1.0, "libero_franka"),
112
+ ("libero_spatial_no_noops_1.0.0_lerobot", 1.0, "libero_franka"),
113
+ ("libero_10_no_noops_1.0.0_lerobot", 1.0, "libero_franka"),
114
+ # ("libero_90_no_noops_lerobot", 1.0, "libero_franka"),
115
+ ],
116
+ "bridge": [("bridge_orig_1.0.0_lerobot", 1.0, "oxe_bridge"),],
117
+ "bridge_rt_1": [
118
+ ("bridge_orig_1.0.0_lerobot", 1.0, "oxe_bridge"),
119
+ ("fractal20220817_data_0.1.0_lerobot", 1.0, "oxe_rt1"),
120
+ ],
121
+ "demo_sim_pick_place": [("sim_pick_place", 1.0, "demo_sim_franka_delta_joints"),],
122
+ "custom_dataset": [("custom_dataset_name", 1.0, "custom_robot_config"),],
123
+ "custom_dataset_2": [
124
+ ("custom_dataset_name_1", 1.0, "custom_robot_config"),
125
+ ("custom_dataset_name_2", 1.0, "custom_robot_config"),
126
+ ],
127
+ "fourier_gr1_unified_1000": [
128
+ ("gr1_unified.PnPBottleToCabinetClose_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"),
129
+ ("gr1_unified.PnPCanToDrawerClose_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"),
130
+ ("gr1_unified.PnPCupToDrawerClose_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"),
131
+ ("gr1_unified.PnPMilkToMicrowaveClose_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"),
132
+ ("gr1_unified.PnPPotatoToMicrowaveClose_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"),
133
+ ("gr1_unified.PnPWineToCabinetClose_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"),
134
+ ("gr1_unified.PosttrainPnPNovelFromCuttingboardToBasketSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"),
135
+ ("gr1_unified.PosttrainPnPNovelFromCuttingboardToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0,
136
+ "fourier_gr1_arms_waist"),
137
+ ("gr1_unified.PosttrainPnPNovelFromCuttingboardToPanSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"),
138
+ ("gr1_unified.PosttrainPnPNovelFromCuttingboardToPotSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"),
139
+ ("gr1_unified.PosttrainPnPNovelFromCuttingboardToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0,
140
+ "fourier_gr1_arms_waist"),
141
+ ("gr1_unified.PosttrainPnPNovelFromPlacematToBasketSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"),
142
+ ("gr1_unified.PosttrainPnPNovelFromPlacematToBowlSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"),
143
+ ("gr1_unified.PosttrainPnPNovelFromPlacematToPlateSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"),
144
+ ("gr1_unified.PosttrainPnPNovelFromPlacematToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"),
145
+ ("gr1_unified.PosttrainPnPNovelFromPlateToBowlSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"),
146
+ ("gr1_unified.PosttrainPnPNovelFromPlateToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"),
147
+ ("gr1_unified.PosttrainPnPNovelFromPlateToPanSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"),
148
+ ("gr1_unified.PosttrainPnPNovelFromPlateToPlateSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"),
149
+ ("gr1_unified.PosttrainPnPNovelFromTrayToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"),
150
+ ("gr1_unified.PosttrainPnPNovelFromTrayToPlateSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"),
151
+ ("gr1_unified.PosttrainPnPNovelFromTrayToPotSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"),
152
+ ("gr1_unified.PosttrainPnPNovelFromTrayToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"),
153
+ ("gr1_unified.PosttrainPnPNovelFromTrayToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"),
154
+ ],
155
+ "robocasa_teleop": [
156
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PnPBottleToCabinetClose', 1.0, 'fourier_gr1_arms_waist'),
157
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PnPCanToDrawerClose', 1.0, 'fourier_gr1_arms_waist'),
158
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PnPCupToDrawerClose', 1.0, 'fourier_gr1_arms_waist'),
159
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PnPMilkToMicrowaveClose', 1.0, 'fourier_gr1_arms_waist'),
160
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PnPPotatoToMicrowaveClose', 1.0, 'fourier_gr1_arms_waist'),
161
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PnPWineToCabinetClose', 1.0, 'fourier_gr1_arms_waist'),
162
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromCuttingboardToBasketSplitA', 1.0,
163
+ 'fourier_gr1_arms_waist'),
164
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromCuttingboardToCardboardboxSplitA', 1.0,
165
+ 'fourier_gr1_arms_waist'),
166
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromCuttingboardToPanSplitA', 1.0,
167
+ 'fourier_gr1_arms_waist'),
168
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromCuttingboardToPotSplitA', 1.0,
169
+ 'fourier_gr1_arms_waist'),
170
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromCuttingboardToTieredbasketSplitA', 1.0,
171
+ 'fourier_gr1_arms_waist'),
172
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromPlacematToBasketSplitA', 1.0,
173
+ 'fourier_gr1_arms_waist'),
174
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromPlacematToBowlSplitA', 1.0,
175
+ 'fourier_gr1_arms_waist'),
176
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromPlacematToPlateSplitA', 1.0,
177
+ 'fourier_gr1_arms_waist'),
178
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromPlacematToTieredshelfSplitA', 1.0,
179
+ 'fourier_gr1_arms_waist'),
180
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromPlateToBowlSplitA', 1.0, 'fourier_gr1_arms_waist'),
181
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromPlateToCardboardboxSplitA', 1.0,
182
+ 'fourier_gr1_arms_waist'),
183
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromPlateToPanSplitA', 1.0, 'fourier_gr1_arms_waist'),
184
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromPlateToPlateSplitA', 1.0, 'fourier_gr1_arms_waist'),
185
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromTrayToCardboardboxSplitA', 1.0,
186
+ 'fourier_gr1_arms_waist'),
187
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromTrayToPlateSplitA', 1.0, 'fourier_gr1_arms_waist'),
188
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromTrayToPotSplitA', 1.0, 'fourier_gr1_arms_waist'),
189
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromTrayToTieredbasketSplitA', 1.0,
190
+ 'fourier_gr1_arms_waist'),
191
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromTrayToTieredshelfSplitA', 1.0,
192
+ 'fourier_gr1_arms_waist')
193
+ ],
194
+ "robocasa_teleop_ee": [
195
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PnPBottleToCabinetClose_ee', 1.0, 'fourier_gr1_arms_waist'),
196
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PnPCanToDrawerClose_ee', 1.0, 'fourier_gr1_arms_waist'),
197
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PnPCupToDrawerClose_ee', 1.0, 'fourier_gr1_arms_waist'),
198
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PnPMilkToMicrowaveClose_ee', 1.0, 'fourier_gr1_arms_waist'),
199
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PnPPotatoToMicrowaveClose_ee', 1.0, 'fourier_gr1_arms_waist'),
200
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PnPWineToCabinetClose_ee', 1.0, 'fourier_gr1_arms_waist'),
201
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromCuttingboardToBasketSplitA_ee', 1.0,
202
+ 'fourier_gr1_arms_waist'),
203
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromCuttingboardToCardboardboxSplitA_ee', 1.0,
204
+ 'fourier_gr1_arms_waist'),
205
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromCuttingboardToPanSplitA_ee', 1.0,
206
+ 'fourier_gr1_arms_waist'),
207
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromCuttingboardToPotSplitA_ee', 1.0,
208
+ 'fourier_gr1_arms_waist'),
209
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromCuttingboardToTieredbasketSplitA_ee', 1.0,
210
+ 'fourier_gr1_arms_waist'),
211
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlacematToBasketSplitA_ee', 1.0,
212
+ 'fourier_gr1_arms_waist'),
213
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlacematToBowlSplitA_ee', 1.0,
214
+ 'fourier_gr1_arms_waist'),
215
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlacematToPlateSplitA_ee', 1.0,
216
+ 'fourier_gr1_arms_waist'),
217
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlacematToTieredshelfSplitA_ee', 1.0,
218
+ 'fourier_gr1_arms_waist'),
219
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlateToBowlSplitA_ee', 1.0,
220
+ 'fourier_gr1_arms_waist'),
221
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlateToCardboardboxSplitA_ee', 1.0,
222
+ 'fourier_gr1_arms_waist'),
223
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlateToPanSplitA_ee', 1.0,
224
+ 'fourier_gr1_arms_waist'),
225
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlateToPlateSplitA_ee', 1.0,
226
+ 'fourier_gr1_arms_waist'),
227
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromTrayToCardboardboxSplitA_ee', 1.0,
228
+ 'fourier_gr1_arms_waist'),
229
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromTrayToPlateSplitA_ee', 1.0,
230
+ 'fourier_gr1_arms_waist'),
231
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromTrayToPotSplitA_ee', 1.0,
232
+ 'fourier_gr1_arms_waist'),
233
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromTrayToTieredbasketSplitA_ee', 1.0,
234
+ 'fourier_gr1_arms_waist'),
235
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromTrayToTieredshelfSplitA_ee', 1.0,
236
+ 'fourier_gr1_arms_waist')
237
+ ],
238
+ "BEHAVIOR_challenge": [("BEHAVIOR_challenge", 1.0, "R1Pro"),],
239
+ "SO101_pick": [("pick_dataset_name", 1.0, "SO101"),],
240
+ "arx_x5": [("arx_x5", 1.0, "arx_x5"),],
241
+ "robotwin": [
242
+ ("adjust_bottle", 1.0, "robotwin"),
243
+ ("beat_block_hammer", 1.0, "robotwin"),
244
+ ("blocks_ranking_rgb", 1.0, "robotwin"),
245
+ ("blocks_ranking_size", 1.0, "robotwin"),
246
+ ("click_alarmclock", 1.0, "robotwin"),
247
+ ("click_bell", 1.0, "robotwin"),
248
+ ("dump_bin_bigbin", 1.0, "robotwin"),
249
+ ("grab_roller", 1.0, "robotwin"),
250
+ ("handover_block", 1.0, "robotwin"),
251
+ ("handover_mic", 1.0, "robotwin"),
252
+ ("hanging_mug", 1.0, "robotwin"),
253
+ ("lift_pot", 1.0, "robotwin"),
254
+ ("move_can_pot", 1.0, "robotwin"),
255
+ ("move_pillbottle_pad", 1.0, "robotwin"),
256
+ ("move_playingcard_away", 1.0, "robotwin"),
257
+ ("move_stapler_pad", 1.0, "robotwin"),
258
+ ("open_laptop", 1.0, "robotwin"),
259
+ ("open_microwave", 1.0, "robotwin"),
260
+ ("pick_diverse_bottles", 1.0, "robotwin"),
261
+ ("pick_dual_bottles", 1.0, "robotwin"),
262
+ ("place_a2b_left", 1.0, "robotwin"),
263
+ ("place_a2b_right", 1.0, "robotwin"),
264
+ ("place_bread_basket", 1.0, "robotwin"),
265
+ ("place_bread_skillet", 1.0, "robotwin"),
266
+ ("place_burger_fries", 1.0, "robotwin"),
267
+ ("place_can_basket", 1.0, "robotwin"),
268
+ ("place_cans_plasticbox", 1.0, "robotwin"),
269
+ ("place_container_plate", 1.0, "robotwin"),
270
+ ("place_dual_shoes", 1.0, "robotwin"),
271
+ ("place_empty_cup", 1.0, "robotwin"),
272
+ ("place_fan", 1.0, "robotwin"),
273
+ ("place_mouse_pad", 1.0, "robotwin"),
274
+ ("place_object_basket", 1.0, "robotwin"),
275
+ ("place_object_scale", 1.0, "robotwin"),
276
+ ("place_object_stand", 1.0, "robotwin"),
277
+ ("place_phone_stand", 1.0, "robotwin"),
278
+ ("place_shoe", 1.0, "robotwin"),
279
+ ("press_stapler", 1.0, "robotwin"),
280
+ ("put_bottles_dustbin", 1.0, "robotwin"),
281
+ ("put_object_cabinet", 1.0, "robotwin"),
282
+ ("rotate_qrcode", 1.0, "robotwin"),
283
+ ("scan_object", 1.0, "robotwin"),
284
+ ("shake_bottle", 1.0, "robotwin"),
285
+ ("shake_bottle_horizontally", 1.0, "robotwin"),
286
+ ("stack_blocks_three", 1.0, "robotwin"),
287
+ ("stack_blocks_two", 1.0, "robotwin"),
288
+ ("stack_bowls_three", 1.0, "robotwin"),
289
+ ("stack_bowls_two", 1.0, "robotwin"),
290
+ ("stamp_seal", 1.0, "robotwin"),
291
+ ("turn_switch", 1.0, "robotwin"),
292
+ ],
293
+ "robotwin_task1": [("adjust_bottle", 1.0, "robotwin"),],
294
+ "robotwin_task2": [
295
+ ("place_a2b_left", 1.0, "robotwin"),
296
+ ("place_a2b_right", 1.0, "robotwin"),
297
+ ],
298
+ "multi_robot": [("LEROBOT_LIBERO_DATA/libero_10_no_noops_1.0.0_lerobot", 1.0, "libero_franka"),
299
+ # ("OXE_LEROBOT_DATASET/bridge_orig_1.0.0_lerobot", 1.0, "oxe_bridge"),
300
+ ],
301
+ }
starVLA/dataloader/gr00t_lerobot/schema.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from enum import Enum
17
+ from typing import Optional
18
+
19
+ from numpydantic import NDArray
20
+ from pydantic import BaseModel, Field, field_serializer
21
+
22
+ from .embodiment_tags import EmbodimentTag
23
+
24
+ # Common schema
25
+
26
+
27
+ class RotationType(Enum):
28
+ """Type of rotation representation"""
29
+
30
+ AXIS_ANGLE = "axis_angle"
31
+ QUATERNION = "quaternion"
32
+ ROTATION_6D = "rotation_6d"
33
+ MATRIX = "matrix"
34
+ EULER_ANGLES_RPY = "euler_angles_rpy"
35
+ EULER_ANGLES_RYP = "euler_angles_ryp"
36
+ EULER_ANGLES_PRY = "euler_angles_pry"
37
+ EULER_ANGLES_PYR = "euler_angles_pyr"
38
+ EULER_ANGLES_YRP = "euler_angles_yrp"
39
+ EULER_ANGLES_YPR = "euler_angles_ypr"
40
+
41
+
42
+ # LeRobot schema
43
+
44
+
45
+ class LeRobotModalityField(BaseModel):
46
+ """Metadata for a LeRobot modality field."""
47
+
48
+ original_key: Optional[str] = Field(
49
+ default=None,
50
+ description="The original key of the modality in the LeRobot dataset",
51
+ )
52
+
53
+
54
+ class LeRobotStateActionMetadata(LeRobotModalityField):
55
+ """Metadata for a LeRobot modality."""
56
+
57
+ start: int = Field(
58
+ ...,
59
+ description="The start index of the modality in the concatenated state/action vector",
60
+ )
61
+ end: int = Field(
62
+ ...,
63
+ description="The end index of the modality in the concatenated state/action vector",
64
+ )
65
+ rotation_type: Optional[RotationType] = Field(
66
+ default=None, description="The type of rotation for the modality"
67
+ )
68
+ absolute: bool = Field(default=True, description="Whether the modality is absolute")
69
+ dtype: str = Field(
70
+ default="float64",
71
+ description="The data type of the modality. Defaults to float64.",
72
+ )
73
+ range: Optional[tuple[float, float]] = Field(
74
+ default=None,
75
+ description="The range of the modality, if applicable. Defaults to None.",
76
+ )
77
+ original_key: Optional[str] = Field(
78
+ default=None,
79
+ description="The original key of the modality in the LeRobot dataset.",
80
+ )
81
+
82
+
83
+ class LeRobotStateMetadata(LeRobotStateActionMetadata):
84
+ """Metadata for a LeRobot state modality."""
85
+
86
+ original_key: Optional[str] = Field(
87
+ default="observation.state", # LeRobot convention for states
88
+ description="The original key of the state modality in the LeRobot dataset",
89
+ )
90
+
91
+
92
+ class LeRobotActionMetadata(LeRobotStateActionMetadata):
93
+ """Metadata for a LeRobot action modality."""
94
+
95
+ original_key: Optional[str] = Field(
96
+ default="action", # LeRobot convention for actions
97
+ description="The original key of the action modality in the LeRobot dataset",
98
+ )
99
+
100
+
101
+ class LeRobotModalityMetadata(BaseModel):
102
+ """Metadata for a LeRobot modality."""
103
+
104
+ state: dict[str, LeRobotStateMetadata] = Field(
105
+ ...,
106
+ description="The metadata for the state modality. The keys are the names of each split of the state vector.",
107
+ )
108
+ action: dict[str, LeRobotActionMetadata] = Field(
109
+ ...,
110
+ description="The metadata for the action modality. The keys are the names of each split of the action vector.",
111
+ )
112
+ video: dict[str, LeRobotModalityField] = Field(
113
+ ...,
114
+ description="The metadata for the video modality. The keys are the new names of each video modality.",
115
+ )
116
+ annotation: Optional[dict[str, LeRobotModalityField]] = Field(
117
+ default=None,
118
+ description="The metadata for the annotation modality. The keys are the new names of each annotation modality.",
119
+ )
120
+
121
+ def get_key_meta(self, key: str) -> LeRobotModalityField:
122
+ """Get the metadata for a key in the LeRobot modality metadata.
123
+
124
+ Args:
125
+ key (str): The key to get the metadata for.
126
+
127
+ Returns:
128
+ LeRobotModalityField: The metadata for the key.
129
+
130
+ Example:
131
+ lerobot_modality_meta = LeRobotModalityMetadata.model_validate(U.load_json(modality_meta_path))
132
+ lerobot_modality_meta.get_key_meta("state.joint_shoulder_y")
133
+ lerobot_modality_meta.get_key_meta("video.main_camera")
134
+ lerobot_modality_meta.get_key_meta("annotation.human.action.task_description")
135
+ """
136
+ split_key = key.split(".")
137
+ modality = split_key[0]
138
+ subkey = ".".join(split_key[1:])
139
+ if modality == "state":
140
+ if subkey not in self.state:
141
+ raise ValueError(
142
+ f"Key: {key}, state key {subkey} not found in metadata, available state keys: {self.state.keys()}"
143
+ )
144
+ return self.state[subkey]
145
+ elif modality == "action":
146
+ if subkey not in self.action:
147
+ raise ValueError(
148
+ f"Key: {key}, action key {subkey} not found in metadata, available action keys: {self.action.keys()}"
149
+ )
150
+ return self.action[subkey]
151
+ elif modality == "video":
152
+ if subkey not in self.video:
153
+ raise ValueError(
154
+ f"Key: {key}, video key {subkey} not found in metadata, available video keys: {self.video.keys()}"
155
+ )
156
+ return self.video[subkey]
157
+ elif modality == "annotation":
158
+ assert (
159
+ self.annotation is not None
160
+ ), "Trying to get annotation metadata for a dataset with no annotations"
161
+ if subkey not in self.annotation:
162
+ raise ValueError(
163
+ f"Key: {key}, annotation key {subkey} not found in metadata, available annotation keys: {self.annotation.keys()}"
164
+ )
165
+ return self.annotation[subkey]
166
+ else:
167
+ raise ValueError(f"Key: {key}, unexpected modality: {modality}")
168
+
169
+
170
+ # Dataset schema (parsed from LeRobot schema and simplified)
171
+
172
+
173
+ class DatasetStatisticalValues(BaseModel):
174
+ max: NDArray = Field(..., description="Maximum values")
175
+ min: NDArray = Field(..., description="Minimum values")
176
+ mean: NDArray = Field(..., description="Mean values")
177
+ std: NDArray = Field(..., description="Standard deviation")
178
+ q01: NDArray = Field(..., description="1st percentile values")
179
+ q99: NDArray = Field(..., description="99th percentile values")
180
+
181
+ @field_serializer("*", when_used="json")
182
+ def serialize_ndarray(self, v: NDArray) -> list[float]:
183
+ return v.tolist() # type: ignore
184
+
185
+
186
+ class DatasetStatistics(BaseModel):
187
+ state: dict[str, DatasetStatisticalValues] = Field(..., description="Statistics of the state")
188
+ action: dict[str, DatasetStatisticalValues] = Field(..., description="Statistics of the action")
189
+
190
+
191
+ class VideoMetadata(BaseModel):
192
+ """Metadata of the video modality"""
193
+
194
+ resolution: tuple[int, int] = Field(..., description="Resolution of the video")
195
+ channels: int = Field(..., description="Number of channels in the video", gt=0)
196
+ fps: float = Field(..., description="Frames per second", gt=0)
197
+
198
+
199
+ class StateActionMetadata(BaseModel):
200
+ absolute: bool = Field(..., description="Whether the state or action is absolute")
201
+ rotation_type: Optional[RotationType] = Field(None, description="Type of rotation, if any")
202
+ shape: tuple[int, ...] = Field(..., description="Shape of the state or action")
203
+ continuous: bool = Field(..., description="Whether the state or action is continuous")
204
+
205
+
206
+ class DatasetModalities(BaseModel):
207
+ video: dict[str, VideoMetadata] = Field(..., description="Metadata of the video")
208
+ state: dict[str, StateActionMetadata] = Field(..., description="Metadata of the state")
209
+ action: dict[str, StateActionMetadata] = Field(..., description="Metadata of the action")
210
+
211
+
212
+ class DatasetMetadata(BaseModel):
213
+ """Metadata of the trainable dataset
214
+
215
+ Changes:
216
+ - Update to use the new RawCommitHashMetadataMetadata_V1_2
217
+ """
218
+
219
+ statistics: DatasetStatistics = Field(..., description="Statistics of the dataset")
220
+ modalities: DatasetModalities = Field(..., description="Metadata of the modalities")
221
+ embodiment_tag: EmbodimentTag = Field(..., description="Embodiment tag of the dataset")
starVLA/dataloader/gr00t_lerobot/transform/__init__.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from .base import (
17
+ ComposedModalityTransform,
18
+ InvertibleModalityTransform,
19
+ ModalityTransform,
20
+ )
21
+ from .concat import ConcatTransform
22
+ # from .state_action import (
23
+ # StateActionDropout,
24
+ # StateActionPerturbation,
25
+ # StateActionSinCosTransform,
26
+ # StateActionToTensor,
27
+ # StateActionTransform,
28
+ # )
29
+ from .video import (
30
+ VideoColorJitter,
31
+ VideoCrop,
32
+ VideoGrayscale,
33
+ VideoHorizontalFlip,
34
+ VideoRandomGrayscale,
35
+ VideoRandomPosterize,
36
+ VideoRandomRotation,
37
+ VideoResize,
38
+ VideoToNumpy,
39
+ VideoToTensor,
40
+ VideoTransform,
41
+ )
starVLA/dataloader/gr00t_lerobot/transform/base.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from abc import ABC, abstractmethod
17
+ from typing import Any
18
+
19
+ from pydantic import BaseModel, ConfigDict, Field, PrivateAttr
20
+
21
+ from ..schema import DatasetMetadata
22
+
23
+
24
+ class ModalityTransform(BaseModel, ABC):
25
+ """
26
+ Abstract class for transforming data modalities, e.g. video frame augmentation or action normalization.
27
+ """
28
+
29
+ apply_to: list[str] = Field(..., description="The keys to apply the transform to.")
30
+ training: bool = Field(
31
+ default=True, description="Whether to apply the transform in training mode."
32
+ )
33
+ _dataset_metadata: DatasetMetadata | None = PrivateAttr(default=None)
34
+
35
+ model_config = ConfigDict(arbitrary_types_allowed=True)
36
+
37
+ @property
38
+ def dataset_metadata(self) -> DatasetMetadata:
39
+ assert (
40
+ self._dataset_metadata is not None
41
+ ), "Dataset metadata is not set. Please call set_metadata() before calling apply()."
42
+ return self._dataset_metadata
43
+
44
+ @dataset_metadata.setter
45
+ def dataset_metadata(self, value: DatasetMetadata):
46
+ self._dataset_metadata = value
47
+
48
+ def set_metadata(self, dataset_metadata: DatasetMetadata):
49
+ """
50
+ Set the dataset metadata. This is useful for transforms that need to know the dataset metadata, e.g. to normalize actions.
51
+ Subclasses can override this method if they need to do something more complex.
52
+ """
53
+ self.dataset_metadata = dataset_metadata
54
+
55
+ def __call__(self, data: dict[str, Any]) -> dict[str, Any]:
56
+ """Apply the transformation to the data corresponding to target_keys and return the processed data.
57
+
58
+ Args:
59
+ data (dict[str, Any]): The data to transform.
60
+ example: data = {
61
+ "video.image_side_0": np.ndarray,
62
+ "action.eef_position": np.ndarray,
63
+ ...
64
+ }
65
+
66
+ Returns:
67
+ dict[str, Any]: The transformed data.
68
+ example: transformed_data = {
69
+ "video.image_side_0": np.ndarray,
70
+ "action.eef_position": torch.Tensor, # Normalized and converted to tensor
71
+ ...
72
+ }
73
+ """
74
+ return self.apply(data)
75
+
76
+ @abstractmethod
77
+ def apply(self, data: dict[str, Any]) -> dict[str, Any]:
78
+ """Apply the transformation to the data corresponding to keys matching the `apply_to` regular expression and return the processed data."""
79
+
80
+ def train(self):
81
+ self.training = True
82
+
83
+ def eval(self):
84
+ self.training = False
85
+
86
+
87
+ class InvertibleModalityTransform(ModalityTransform):
88
+ @abstractmethod
89
+ def unapply(self, data: dict[str, Any]) -> dict[str, Any]:
90
+ """Reverse the transformation to the data corresponding to keys matching the `apply_to` regular expression and return the processed data."""
91
+
92
+
93
+ class ComposedModalityTransform(ModalityTransform):
94
+ """Compose multiple modality transforms."""
95
+
96
+ transforms: list[ModalityTransform] = Field(..., description="The transforms to compose.")
97
+ apply_to: list[str] = Field(
98
+ default_factory=list, description="Will be ignored for composed transforms."
99
+ )
100
+ training: bool = Field(
101
+ default=True, description="Whether to apply the transform in training mode."
102
+ )
103
+
104
+ model_config = ConfigDict(arbitrary_types_allowed=True, from_attributes=True)
105
+
106
+ def set_metadata(self, dataset_metadata: DatasetMetadata):
107
+ for transform in self.transforms:
108
+ transform.set_metadata(dataset_metadata)
109
+
110
+ def apply(self, data: dict[str, Any]) -> dict[str, Any]:
111
+ for i, transform in enumerate(self.transforms):
112
+ try:
113
+ data = transform(data)
114
+ except Exception as e:
115
+ raise ValueError(f"Error applying transform {i} to data: {e}") from e
116
+ return data
117
+
118
+ def unapply(self, data: dict[str, Any]) -> dict[str, Any]:
119
+ for i, transform in enumerate(reversed(self.transforms)):
120
+ if isinstance(transform, InvertibleModalityTransform):
121
+ try:
122
+ data = transform.unapply(data)
123
+ except Exception as e:
124
+ step = len(self.transforms) - i - 1
125
+ raise ValueError(f"Error unapplying transform {step} to data: {e}") from e
126
+ return data
127
+
128
+ def train(self):
129
+ for transform in self.transforms:
130
+ transform.train()
131
+
132
+ def eval(self):
133
+ for transform in self.transforms:
134
+ transform.eval()
starVLA/dataloader/gr00t_lerobot/transform/concat.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import Optional
17
+
18
+ import numpy as np
19
+ import torch
20
+ from pydantic import Field
21
+
22
+ from ..schema import DatasetMetadata, StateActionMetadata
23
+ from .base import InvertibleModalityTransform
24
+
25
+
26
+ class ConcatTransform(InvertibleModalityTransform):
27
+ """
28
+ Concatenate the keys according to specified order.
29
+ """
30
+
31
+ # -- We inherit from ModalityTransform, so we keep apply_to as well --
32
+ apply_to: list[str] = Field(
33
+ default_factory=list, description="Not used in this transform, kept for compatibility."
34
+ )
35
+
36
+ video_concat_order: list[str] = Field(
37
+ ...,
38
+ description="Concatenation order for each video modality. "
39
+ "Format: ['video.ego_view_pad_res224_freq20', ...]",
40
+ )
41
+
42
+ state_concat_order: Optional[list[str]] = Field(
43
+ default=None,
44
+ description="Concatenation order for each state modality. "
45
+ "Format: ['state.position', 'state.velocity', ...].",
46
+ )
47
+
48
+ action_concat_order: Optional[list[str]] = Field(
49
+ default=None,
50
+ description="Concatenation order for each action modality. "
51
+ "Format: ['action.position', 'action.velocity', ...].",
52
+ )
53
+
54
+ action_dims: dict[str, int] = Field(
55
+ default_factory=dict,
56
+ description="The dimensions of the action keys.",
57
+ )
58
+ state_dims: dict[str, int] = Field(
59
+ default_factory=dict,
60
+ description="The dimensions of the state keys.",
61
+ )
62
+
63
+ def model_dump(self, *args, **kwargs):
64
+ if kwargs.get("mode", "python") == "json":
65
+ include = {
66
+ "apply_to",
67
+ "video_concat_order",
68
+ "state_concat_order",
69
+ "action_concat_order",
70
+ }
71
+ else:
72
+ include = kwargs.pop("include", None)
73
+
74
+ return super().model_dump(*args, include=include, **kwargs)
75
+
76
+ def apply(self, data: dict) -> dict:
77
+ grouped_keys = {}
78
+ for key in data.keys():
79
+ try:
80
+ modality, _ = key.split(".")
81
+ except: # noqa: E722
82
+ ### Handle language annotation special case
83
+ if "annotation" in key:
84
+ modality = "language"
85
+ else:
86
+ modality = "others"
87
+ if modality not in grouped_keys:
88
+ grouped_keys[modality] = []
89
+ grouped_keys[modality].append(key)
90
+
91
+ if "video" in grouped_keys:
92
+ # Check if keys in video_concat_order, state_concat_order, action_concat_order are
93
+ # ineed contained in the data. If not, then the keys are misspecified
94
+ video_keys = grouped_keys["video"]
95
+ assert self.video_concat_order is not None, f"{self.video_concat_order=}, {video_keys=}"
96
+ assert all(
97
+ item in video_keys for item in self.video_concat_order
98
+ ), f"keys in video_concat_order are misspecified, \n{video_keys=}, \n{self.video_concat_order=}"
99
+
100
+ # Process each video view
101
+ unsqueezed_videos = []
102
+ for video_key in self.video_concat_order:
103
+ video_data = data.pop(video_key)
104
+ unsqueezed_video = np.expand_dims(
105
+ video_data, axis=-4
106
+ ) # [..., H, W, C] -> [..., 1, H, W, C]
107
+ unsqueezed_videos.append(unsqueezed_video)
108
+ # Concatenate along the new axis
109
+ unsqueezed_video = np.concatenate(unsqueezed_videos, axis=-4) # [..., V, H, W, C]
110
+
111
+ # Video
112
+ data["video"] = unsqueezed_video
113
+
114
+ # "state"
115
+ if "state" in grouped_keys:
116
+ state_keys = grouped_keys["state"]
117
+ assert self.state_concat_order is not None, f"{self.state_concat_order=}"
118
+ assert all(
119
+ item in state_keys for item in self.state_concat_order
120
+ ), f"keys in state_concat_order are misspecified, \n{state_keys=}, \n{self.state_concat_order=}"
121
+ # Check the state dims
122
+ for key in self.state_concat_order:
123
+ target_shapes = [self.state_dims[key]]
124
+ if self.is_rotation_key(key):
125
+ target_shapes.append(6) # Allow for rotation_6d
126
+ # if key in ["state.right_arm", "state.right_hand"]:
127
+ target_shapes.append(self.state_dims[key] * 2) # Allow for sin-cos transform
128
+ assert (
129
+ data[key].shape[-1] in target_shapes
130
+ ), f"State dim mismatch for {key=}, {data[key].shape[-1]=}, {target_shapes=}"
131
+ # Concatenate the state keys
132
+ # We'll have StateActionToTensor before this transform, so here we use torch.cat
133
+ data["state"] = torch.cat(
134
+ [data.pop(key) for key in self.state_concat_order], dim=-1
135
+ ) # [T, D_state]
136
+
137
+ if "action" in grouped_keys:
138
+ action_keys = grouped_keys["action"]
139
+ assert self.action_concat_order is not None, f"{self.action_concat_order=}"
140
+ # Check if all keys in concat_order are present
141
+ assert set(self.action_concat_order) == set(
142
+ action_keys
143
+ ), f"{set(self.action_concat_order)=}, {set(action_keys)=}"
144
+ # Record the action dims
145
+ for key in self.action_concat_order:
146
+ target_shapes = [self.action_dims[key]]
147
+ if self.is_rotation_key(key):
148
+ target_shapes.append(3) # Allow for axis angle
149
+ assert (
150
+ self.action_dims[key] == data[key].shape[-1]
151
+ ), f"Action dim mismatch for {key=}, {self.action_dims[key]=}, {data[key].shape[-1]=}"
152
+ # Concatenate the action keys
153
+ # We'll have StateActionToTensor before this transform, so here we use torch.cat
154
+ data["action"] = torch.cat(
155
+ [data.pop(key) for key in self.action_concat_order], dim=-1
156
+ ) # [T, D_action]
157
+
158
+ return data
159
+
160
+ def unapply(self, data: dict) -> dict:
161
+ start_dim = 0
162
+ assert "action" in data, f"{data.keys()=}"
163
+ # For those dataset without actions (LAPA), we'll never run unapply
164
+ assert self.action_concat_order is not None, f"{self.action_concat_order=}"
165
+ action_tensor = data.pop("action")
166
+ for key in self.action_concat_order:
167
+ if key not in self.action_dims:
168
+ raise ValueError(f"Action dim {key} not found in action_dims.")
169
+ end_dim = start_dim + self.action_dims[key]
170
+ data[key] = action_tensor[..., start_dim:end_dim]
171
+ start_dim = end_dim
172
+ if "state" in data:
173
+ assert self.state_concat_order is not None, f"{self.state_concat_order=}"
174
+ start_dim = 0
175
+ state_tensor = data.pop("state")
176
+ for key in self.state_concat_order:
177
+ end_dim = start_dim + self.state_dims[key]
178
+ data[key] = state_tensor[..., start_dim:end_dim]
179
+ start_dim = end_dim
180
+ return data
181
+
182
+ def __call__(self, data: dict) -> dict:
183
+ return self.apply(data)
184
+
185
+ def get_modality_metadata(self, key: str) -> StateActionMetadata:
186
+ modality, subkey = key.split(".")
187
+ assert self.dataset_metadata is not None, "Metadata not set"
188
+ modality_config = getattr(self.dataset_metadata.modalities, modality)
189
+ assert subkey in modality_config, f"{subkey=} not found in {modality_config=}"
190
+ assert isinstance(
191
+ modality_config[subkey], StateActionMetadata
192
+ ), f"Expected {StateActionMetadata} for {subkey=}, got {type(modality_config[subkey])=}"
193
+ return modality_config[subkey]
194
+
195
+ def get_state_action_dims(self, key: str) -> int:
196
+ """Get the dimension of a state or action key from the dataset metadata."""
197
+ modality_config = self.get_modality_metadata(key)
198
+ shape = modality_config.shape
199
+ assert len(shape) == 1, f"{shape=}"
200
+ return shape[0]
201
+
202
+ def is_rotation_key(self, key: str) -> bool:
203
+ modality_config = self.get_modality_metadata(key)
204
+ return modality_config.rotation_type is not None
205
+
206
+ def set_metadata(self, dataset_metadata: DatasetMetadata):
207
+ """Set the metadata and compute the dimensions of the state and action keys."""
208
+ super().set_metadata(dataset_metadata)
209
+ # Pre-compute the dimensions of the state and action keys
210
+ if self.action_concat_order is not None:
211
+ for key in self.action_concat_order:
212
+ self.action_dims[key] = self.get_state_action_dims(key)
213
+ if self.state_concat_order is not None:
214
+ for key in self.state_concat_order:
215
+ self.state_dims[key] = self.get_state_action_dims(key)
starVLA/dataloader/gr00t_lerobot/transform/gr00ttransform.py ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import os
18
+ import random
19
+ import re
20
+ from typing import Any, Dict, List, Optional
21
+
22
+ import numpy as np
23
+ import torch
24
+ import tree
25
+ from einops import rearrange
26
+ from PIL import Image
27
+ from pydantic import Field, PrivateAttr
28
+ from transformers import AutoProcessor, ProcessorMixin
29
+ from transformers.data.data_collator import DataCollatorMixin
30
+ from transformers.feature_extraction_utils import BatchFeature
31
+
32
+ from starVLA.dataloader.gr00t_lerobot.embodiment_tags import EMBODIMENT_TAG_MAPPING, EmbodimentTag
33
+ from starVLA.dataloader.gr00t_lerobot.schema import DatasetMetadata
34
+ from starVLA.dataloader.gr00t_lerobot.transform.base import InvertibleModalityTransform
35
+
36
+ # from starVLA.dataloader.gr00t_lerobot.backbone.eagle_backbone import DEFAULT_EAGLE_PATH
37
+ # from starVLA.dataloader.gr00t_lerobot.backbone.qwen_vl_utils import process_vision_info
38
+
39
+ # from starVLA.dataloader.gr00t_lerobot.fusevla.models.dinov3_vit.image_processing_dinov3_vit_fast import DINOv3ViTImageProcessorFast
40
+
41
+ # def formalize_language(language: str) -> str:
42
+ # """
43
+ # 1. Force lowercase
44
+ # 2. Remove all punctuations
45
+ # """
46
+ # language = language.lower()
47
+ # language = re.sub(r"[^\w\s]", "", language)
48
+ # return language
49
+
50
+
51
+ # def build_eagle_processor(eagle_path: str) -> ProcessorMixin:
52
+ # eagle_processor = AutoProcessor.from_pretrained(
53
+ # eagle_path, trust_remote_code=True, use_fast=True
54
+ # )
55
+ # eagle_processor.tokenizer.padding_side = "left"
56
+ # return eagle_processor
57
+
58
+ # def build_dino_processor(pretrained_path: str):
59
+ # processor = DINOv3ViTImageProcessorFast.from_pretrained(
60
+ # pretrained_path, trust_remote_code=True, use_fast=True
61
+ # )
62
+ # return processor
63
+
64
+ def collate(features: List[dict]) -> dict:
65
+ batch = {}
66
+ keys = features[0].keys()
67
+
68
+ for key in keys:
69
+ values = [elem[key] for elem in features]
70
+
71
+ # if key == "eagle_content":
72
+ # text_list = []
73
+ # image_inputs = []
74
+ # for v in values:
75
+ # curr_text_list = v["text_list"]
76
+ # curr_image_inputs = v["image_inputs"]
77
+ # text_list += curr_text_list
78
+ # image_inputs += curr_image_inputs
79
+ # eagle_inputs = eagle_processor(
80
+ # text=text_list, images=image_inputs, return_tensors="pt", padding=True
81
+ # )
82
+
83
+ # if dino_processor is not None:
84
+ # vit_inputs = dino_processor(images=image_inputs, return_tensors="pt")
85
+ # #import pdb; pdb.set_trace()
86
+ # batch['vit_inputs'] = vit_inputs['pixel_values']
87
+
88
+ # for k, v in eagle_inputs.items():
89
+ # k = "eagle_" + k
90
+ # batch[k] = v
91
+ # if 'future_image_inputs' in values[0]:
92
+ # # enable_latent_embedding
93
+ # future_image_inputs = []
94
+ # for v in values:
95
+ # future_image = v["future_image_inputs"]
96
+ # future_image_inputs += future_image
97
+ # future_inputs = eagle_processor(
98
+ # text=text_list, images=future_image_inputs, return_tensors="pt", padding=True
99
+ # )
100
+ # batch['future_pixel_values'] = future_inputs['pixel_values']
101
+ if key in ("pixel_values", "image_grid_thw", "attention_mask", "input_ids"):
102
+ # Concat in existing batch dimension.
103
+ batch[key] = torch.cat(values)
104
+ else:
105
+ # state, state_mask, action and action_mask.
106
+ # Stack to form the batch dimension.
107
+ batch[key] = torch.from_numpy(np.stack(values))
108
+ return batch
109
+
110
+
111
+ class DefaultDataCollator(DataCollatorMixin):
112
+ def __init__(self):
113
+ super().__init__()
114
+ # self.eagle_processor = build_eagle_processor(eagle_path)
115
+ # if dino_path is not None:
116
+ # self.dino_processor = build_dino_processor(dino_path)
117
+ # else:
118
+ # self.dino_processor = None
119
+
120
+ def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]:
121
+ return collate(features)
122
+
123
+
124
+ class GR00TTransform(InvertibleModalityTransform):
125
+
126
+ # -- We inherit from ModalityTransform, so we keep apply_to as well --
127
+ apply_to: list[str] = Field(
128
+ default_factory=list, description="Not used in this transform, kept for compatibility."
129
+ )
130
+ training: bool = Field(
131
+ default=True, description="Whether to apply the transform in training mode."
132
+ )
133
+ # formalize_language: bool = Field(default=False, description="Formalize language if True.")
134
+ embodiment_tag_mapping: dict[str, int] = Field(
135
+ description="The projector index of each embodiment tag.",
136
+ default=EMBODIMENT_TAG_MAPPING,
137
+ )
138
+ language_dropout_prob: float = Field(
139
+ default=0.0,
140
+ description="Dropout probability for language.",
141
+ )
142
+
143
+ # # Private attributes to keep track of shapes/dimensions across apply/unapply
144
+ # _language_key: Optional[list[str]] = PrivateAttr(default=None)
145
+
146
+ # eagle_processor: ProcessorMixin = Field(default=build_eagle_processor(DEFAULT_EAGLE_PATH))
147
+ # dino_processor: Optional[Any] = Field(default=None, description="DINO processor for LWA inference")
148
+
149
+ # XEmbDiT arguments
150
+ default_instruction: str = Field(default="Perform the default behavior.")
151
+ max_state_dim: int
152
+ max_action_dim: int
153
+ state_horizon: int
154
+ action_horizon: int
155
+
156
+ max_length: int = 512
157
+ embodiment_tag: EmbodimentTag | None = None
158
+
159
+ def set_metadata(self, dataset_metadata: DatasetMetadata):
160
+ """Set the metadata for the transform."""
161
+ super().set_metadata(dataset_metadata)
162
+ self.embodiment_tag = dataset_metadata.embodiment_tag
163
+
164
+ def get_embodiment_tag(self) -> int:
165
+ """Get the embodiment tag from the data."""
166
+ assert (
167
+ self.embodiment_tag is not None
168
+ ), "Embodiment tag not set. Please call set_metadata first."
169
+ return self.embodiment_tag_mapping[self.embodiment_tag.value]
170
+
171
+ def check_keys_and_batch_size(self, data):
172
+ grouped_keys = {}
173
+ for key in data.keys():
174
+ if "annotation" in key:
175
+ modality = "language"
176
+ else:
177
+ try:
178
+ modality, _ = key.split(".")
179
+ except: # noqa: E722
180
+ modality = "others" # will contain the video, state, and action
181
+ if modality not in grouped_keys:
182
+ grouped_keys[modality] = []
183
+ grouped_keys[modality].append(key)
184
+ # Use video key to determine batch size.
185
+ video_ndim = data["video"].ndim
186
+ if video_ndim == 5: # Interpret as [T, V, H, W, C]
187
+ is_batched = False
188
+ batch_size = 1
189
+ elif video_ndim == 6: # Interpret as [B, T, V, H, W, C]
190
+ is_batched = True
191
+ batch_size = data["video"].shape[0]
192
+ else:
193
+ raise ValueError(f"Unsupported video number of dimensions: {video_ndim}")
194
+
195
+ # Handle language
196
+ # if "language" in grouped_keys:
197
+ # language_keys = grouped_keys["language"]
198
+ # assert len(language_keys) == 1, f"{language_keys=}"
199
+ # self._language_key = language_keys[0]
200
+ return is_batched, batch_size
201
+
202
+ # def _apply_vlm_processing(self, batch: dict) -> BatchFeature:
203
+ # """
204
+ # Args:
205
+ # batch:
206
+ # video: [V, T, C, H, W]
207
+ # Returns: required input with the format `BatchFeature`
208
+ # """
209
+ # # TODO(YL, FH): check if this is correct
210
+ # images = batch["images"] # [V, T, C, H, W]
211
+ # images.shape[0]
212
+
213
+ # np_images = rearrange(images, "v t c h w -> (t v) c h w")
214
+ # text_content = []
215
+
216
+ # # handle language
217
+ # lang = batch["language"]
218
+ # if isinstance(lang, list):
219
+ # lang = lang[0]
220
+ # text_content.append({"type": "text", "text": lang})
221
+
222
+ # eagle_images = [Image.fromarray(np.transpose(v, (1, 2, 0))) for v in np_images]
223
+ # eagle_image = [{"type": "image", "image": img} for img in eagle_images]
224
+ # eagle_conversation = [
225
+ # {
226
+ # "role": "user",
227
+ # "content": eagle_image + text_content,
228
+ # }
229
+ # ]
230
+
231
+ # text_list = [
232
+ # self.eagle_processor.apply_chat_template(
233
+ # eagle_conversation, tokenize=False, add_generation_prompt=True
234
+ # )
235
+ # ]
236
+ # image_inputs, video_inputs = self._process_vision_info(eagle_conversation)
237
+ # eagle_content = {
238
+ # "image_inputs": image_inputs,
239
+ # "video_inputs": video_inputs,
240
+ # "text_list": text_list,
241
+ # }
242
+ # inputs = {}
243
+ # inputs["eagle_content"] = eagle_content
244
+ # return inputs
245
+
246
+ # def _process_vision_info(self, eagle_conversation):
247
+ # # TODO
248
+ # if "eagle" in DEFAULT_EAGLE_PATH.lower():
249
+ # # Use the eagle processor to process the vision info
250
+ # return self.eagle_processor.process_vision_info(eagle_conversation)
251
+ # return process_vision_info(eagle_conversation)
252
+
253
+ # def _prepare_video(self, data: dict):
254
+ # """Process, stack, and pad images from data['video']."""
255
+ # ## TODO(YL, FH): check if this is correct
256
+ # images = rearrange(
257
+ # data["video"],
258
+ # "t v h w c -> v t c h w",
259
+ # )
260
+ # return images
261
+
262
+ # def _prepare_language(self, data: dict):
263
+ # """Tokenize data['language'] (or default_instruction if missing)."""
264
+ # if self._language_key is not None:
265
+ # raw_language = data[self._language_key]
266
+ # if isinstance(raw_language, list):
267
+ # raw_language = raw_language[0]
268
+
269
+ # # Language dropout
270
+ # if self.training and self.language_dropout_prob > 1e-9:
271
+ # if random.random() < self.language_dropout_prob:
272
+ # raw_language = self.default_instruction
273
+ # else:
274
+ # raw_language = self.default_instruction
275
+ # return raw_language
276
+
277
+ def _prepare_state(self, data: dict):
278
+ """
279
+ Gathers final state from data['state'], then pads to max_state_dim.
280
+ Return (state, state_mask, n_state_tokens).
281
+ """
282
+ if "state" not in data:
283
+ state = np.zeros((self.state_horizon, self.max_state_dim))
284
+ state_mask = np.zeros((self.state_horizon, self.max_state_dim), dtype=bool)
285
+ n_state_tokens = self.state_horizon
286
+ return state, state_mask, n_state_tokens
287
+
288
+ state = data["state"]
289
+ assert state.shape[0] == self.state_horizon, f"{state.shape=}, {self.state_horizon=}"
290
+
291
+ n_state_dims = state.shape[-1]
292
+
293
+ # Instead of asserting, just take the first max_state_dim dimensions if needed
294
+ if n_state_dims > self.max_state_dim:
295
+ state = state[:, : self.max_state_dim]
296
+ n_state_dims = self.max_state_dim
297
+ else:
298
+ # Pad up to max_state_dim if smaller
299
+ state = np.pad(state, ((0, 0), (0, self.max_state_dim - n_state_dims)), "constant")
300
+
301
+ # Create mask for real state dims
302
+ state_mask = np.zeros_like(state).astype(bool)
303
+ state_mask[:, :n_state_dims] = True
304
+
305
+ # We only have 1 "proprio" token to represent the entire state
306
+ n_state_tokens = state.shape[0]
307
+ return state, state_mask, n_state_tokens
308
+
309
+
310
+ #action horizon padding
311
+ # def _prepare_action(self, data: dict):
312
+ # """
313
+ # Pad/truncate to action_horizon and max_action_dim, return masks.
314
+ # Supports mixed datasets with different action horizons.
315
+ # """
316
+ # if "action" not in data:
317
+ # actions = np.zeros((self.action_horizon, self.max_action_dim))
318
+ # actions_mask = np.zeros((self.action_horizon, self.max_action_dim), dtype=bool)
319
+ # n_action_tokens = self.action_horizon
320
+ # return actions, actions_mask, n_action_tokens
321
+
322
+ # actions = data["action"]
323
+ # actual_horizon = actions.shape[0] # T
324
+ # print('actual_horizon',actual_horizon)
325
+ # n_action_dims = actions.shape[1] # D
326
+
327
+ # assert (
328
+ # n_action_dims <= self.max_action_dim
329
+ # ), f"Action dim {n_action_dims} exceeds max allowed {self.max_action_dim}."
330
+
331
+ # # Handle action horizon mismatch: pad or truncate
332
+ # if actual_horizon < self.action_horizon:
333
+ # # Pad temporal dimension with zeros
334
+ # pad_length = self.action_horizon - actual_horizon
335
+ # actions = np.pad(actions, ((0, pad_length), (0, 0)), mode='constant', constant_values=0)
336
+ # # Create temporal mask (True for real data, False for padding)
337
+ # temporal_mask = np.concatenate([
338
+ # np.ones(actual_horizon, dtype=bool),
339
+ # np.zeros(pad_length, dtype=bool)
340
+ # ])
341
+ # elif actual_horizon > self.action_horizon:
342
+ # # Truncate to target horizon (take first action_horizon steps)
343
+ # actions = actions[:self.action_horizon]
344
+ # temporal_mask = np.ones(self.action_horizon, dtype=bool)
345
+ # else:
346
+ # temporal_mask = np.ones(self.action_horizon, dtype=bool)
347
+
348
+ # # Pad the action dimension
349
+ # actions = np.pad(actions, ((0, 0), (0, self.max_action_dim - n_action_dims)), mode='constant', constant_values=0)
350
+
351
+ # # Create mask: [action_horizon, max_action_dim]
352
+ # # True only for valid (temporal, dimension) pairs
353
+ # actions_mask = np.zeros((self.action_horizon, self.max_action_dim), dtype=bool)
354
+ # actions_mask[:, :n_action_dims] = True
355
+ # # Apply temporal mask: set padded timesteps to False
356
+ # actions_mask = actions_mask & temporal_mask[:, np.newaxis]
357
+ # # print('actions masks',actions_mask.shape)
358
+ # n_action_tokens = self.action_horizon
359
+ # return actions, actions_mask, n_action_tokens
360
+
361
+ def _prepare_action(self, data: dict):
362
+ """
363
+ Pad to max_action_dim, return masks.
364
+ """
365
+ if "action" not in data:
366
+ actions = np.zeros((self.action_horizon, self.max_action_dim))
367
+ actions_mask = np.zeros((self.action_horizon, self.max_action_dim), dtype=bool)
368
+ n_action_tokens = self.action_horizon
369
+ return actions, actions_mask, n_action_tokens
370
+
371
+ actions = data["action"]
372
+
373
+ assert actions.shape[0] == self.action_horizon, f"{actions.shape=}, {self.action_horizon=}"
374
+
375
+ n_action_tokens = actions.shape[0] # T
376
+ n_action_dims = actions.shape[1]
377
+
378
+ assert (
379
+ n_action_dims <= self.max_action_dim
380
+ ), f"Action dim {n_action_dims} exceeds max allowed {self.max_action_dim}."
381
+
382
+ # Pad the channel dimension
383
+ actions = np.pad(actions, ((0, 0), (0, self.max_action_dim - n_action_dims)), "constant")
384
+
385
+ # Create mask: [T, max_action_dim]
386
+ actions_mask = np.zeros((n_action_tokens, self.max_action_dim), dtype=bool)
387
+ actions_mask[:, :n_action_dims] = True
388
+
389
+ return actions, actions_mask, n_action_tokens
390
+
391
+ def apply_single(self, data: dict) -> dict:
392
+ # Keep all original data and only update/add new fields
393
+ transformed_data = data.copy()
394
+
395
+ # # 1) Prepare video and language with vlm processing.
396
+ # images = self._prepare_video(data)
397
+ # images = images.astype(np.uint8)
398
+ # language = self._prepare_language(data)
399
+ # batch_data = {"images": images, "language": language}
400
+ # vlm_outputs = self._apply_vlm_processing(batch_data)
401
+
402
+ # Initialize vlm_outputs as empty dict since VLM processing is commented out
403
+ vlm_outputs = {}
404
+
405
+ # 2) Prepare state and update/add to transformed_data
406
+ state, state_mask, _ = self._prepare_state(data)
407
+ transformed_data["state"] = state
408
+ transformed_data["state_mask"] = state_mask
409
+
410
+ if self.training:
411
+ # 3) Prepare actions and add to transformed_data
412
+ transformed_data["segmentation_target"] = np.zeros((2,))
413
+ transformed_data["segmentation_target_mask"] = np.zeros((1,))
414
+ transformed_data["has_real_action"] = np.ones((), dtype=bool)
415
+ actions, actions_mask, _ = self._prepare_action(data)
416
+ transformed_data["action"] = actions
417
+ transformed_data["action_mask"] = actions_mask
418
+
419
+ # Add VLM outputs to transformed data (currently empty)
420
+ for k, v in vlm_outputs.items():
421
+ assert k not in transformed_data, f"Key {k} already exists in transformed_data."
422
+ transformed_data[k] = v
423
+
424
+ transformed_data["embodiment_id"] = self.get_embodiment_tag()
425
+
426
+ if self.training:
427
+ action_and_mask_keys = ["action", "action_mask"]
428
+ assert all(
429
+ transformed_data[key].shape == transformed_data["action"].shape
430
+ for key in action_and_mask_keys
431
+ ), f"Shape mismatch: {[(key, transformed_data[key].shape) for key in action_and_mask_keys]}"
432
+
433
+ return transformed_data
434
+
435
+ #####训练的时候不会调用这个batch方法,只有在推理的时候会调用#######
436
+
437
+ def apply_batch(self, data: dict, batch_size: int) -> dict:
438
+ # Split on batch dimension.
439
+ data_split = [tree.map_structure(lambda x: x[i], data) for i in range(batch_size)]
440
+ # Process each element.
441
+ data_split_processed = [self.apply_single(elem) for elem in data_split]
442
+
443
+ #import pdb; pdb.set_trace()
444
+ return collate(data_split_processed)
445
+
446
+
447
+ def apply(self, data: dict) -> dict:
448
+ is_batched, batch_size = self.check_keys_and_batch_size(data)
449
+ if is_batched:
450
+ return self.apply_batch(data, batch_size)
451
+ else:
452
+ return self.apply_single(data)
453
+
454
+ def unapply(self, data: dict) -> dict:
455
+ # Leave as is so that ConcatTransform can split the values
456
+ return data
457
+
458
+ def __call__(self, data: dict) -> dict:
459
+ return self.apply(data)
starVLA/dataloader/gr00t_lerobot/transform/gr00ttransform_1.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and limitations under the License.
13
+ import os
14
+ import random
15
+ import re
16
+ from typing import Any, Dict, List, Optional, Tuple
17
+ import numpy as np
18
+ import torch
19
+ import tree
20
+ from einops import rearrange
21
+ from PIL import Image
22
+ from pydantic import Field, PrivateAttr
23
+ from transformers import AutoProcessor, ProcessorMixin
24
+ from transformers.data.data_collator import DataCollatorMixin
25
+ from transformers.feature_extraction_utils import BatchFeature
26
+ from starVLA.dataloader.gr00t_lerobot.embodiment_tags import EMBODIMENT_TAG_MAPPING, EmbodimentTag
27
+ from starVLA.dataloader.gr00t_lerobot.schema import DatasetMetadata
28
+ from starVLA.dataloader.gr00t_lerobot.transform.base import InvertibleModalityTransform
29
+ # ============================================================
30
+ # Unified schema definition
31
+ # ============================================================
32
+ UNIFIED_STATE_SCHEMA: List[Tuple[str, int]] = [
33
+ ("left_arm", 6),
34
+ ("right_arm", 6),
35
+ ("left_gripper", 1),
36
+ ("right_gripper", 1),
37
+ ("left_hand", 6),
38
+ ("right_hand", 6),
39
+ ("waist", 3),
40
+ ("head", 2),
41
+ ]
42
+ UNIFIED_ACTION_SCHEMA: List[Tuple[str, int]] = [
43
+ ("left_arm", 6),
44
+ ("right_arm", 6),
45
+ ("left_gripper", 1),
46
+ ("right_gripper", 1),
47
+ ("left_hand", 6),
48
+ ("right_hand", 6),
49
+ ("waist", 3),
50
+ ("head", 2),
51
+ ]
52
+ # alias:支持不同数据集字段名映射到统一 canonical block
53
+ DEFAULT_SUFFIX_TO_CANONICAL: Dict[str, str] = {
54
+ "left_arm": "left_arm",
55
+ "right_arm": "right_arm",
56
+ "left_gripper": "left_gripper",
57
+ "right_gripper": "right_gripper",
58
+ "left_hand": "left_hand",
59
+ "right_hand": "right_hand",
60
+ "waist": "waist",
61
+ "head": "head",
62
+ "left_pose": "left_arm",
63
+ "right_pose": "right_arm",
64
+ "original_state_head_position": "head",
65
+ "original_state_waist_position": "waist",
66
+ "original_action_head_position": "head",
67
+ "original_action_waist_position": "waist",
68
+ }
69
+ # 反向:canonical -> 所有可接受的 suffix 候选
70
+ CANONICAL_TO_SUFFIX_CANDIDATES: Dict[str, List[str]] = {}
71
+ for suffix, canonical in DEFAULT_SUFFIX_TO_CANONICAL.items():
72
+ CANONICAL_TO_SUFFIX_CANDIDATES.setdefault(canonical, []).append(suffix)
73
+ def collate(features: List[dict]) -> dict:
74
+ batch = {}
75
+ keys = features[0].keys()
76
+ for key in keys:
77
+ values = [elem[key] for elem in features]
78
+ if key in ("pixel_values", "image_grid_thw", "attention_mask", "input_ids"):
79
+ batch[key] = torch.cat(values)
80
+ else:
81
+ # numpy / torch 都兼容
82
+ if isinstance(values[0], torch.Tensor):
83
+ batch[key] = torch.stack(values, dim=0)
84
+ else:
85
+ batch[key] = torch.from_numpy(np.stack(values))
86
+ return batch
87
+ class DefaultDataCollator(DataCollatorMixin):
88
+ def __init__(self):
89
+ super().__init__()
90
+ def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]:
91
+ return collate(features)
92
+ class GR00TTransform(InvertibleModalityTransform):
93
+ apply_to: list[str] = Field(default_factory=list)
94
+ training: bool = Field(default=True)
95
+ embodiment_tag_mapping: dict[str, int] = Field(default=EMBODIMENT_TAG_MAPPING)
96
+ language_dropout_prob: float = Field(default=0.0)
97
+ default_instruction: str = Field(default="Perform the default behavior.")
98
+ max_state_dim: int
99
+ max_action_dim: int
100
+ state_horizon: int
101
+ action_horizon: int
102
+ max_length: int = 512
103
+ embodiment_tag: EmbodimentTag | None = None
104
+ # 可选:如果某些数据集字段名不标准,可以额外传 alias 覆盖
105
+ # 例如 {"state.ee_pos": "left_arm"}
106
+ extra_suffix_to_canonical: Dict[str, str] = Field(default_factory=dict)
107
+ def set_metadata(self, dataset_metadata: DatasetMetadata):
108
+ super().set_metadata(dataset_metadata)
109
+ self.embodiment_tag = dataset_metadata.embodiment_tag
110
+ def get_embodiment_tag(self) -> int:
111
+ assert self.embodiment_tag is not None, "Embodiment tag not set. Please call set_metadata first."
112
+ return self.embodiment_tag_mapping[self.embodiment_tag.value]
113
+ def check_keys_and_batch_size(self, data):
114
+ # BUG
115
+ video_ndim = data["video"].ndim
116
+ if video_ndim == 5: # [T, V, H, W, C]
117
+ return False, 1
118
+ elif video_ndim == 6: # [B, T, V, H, W, C]
119
+ return True, data["video"].shape[0]
120
+ else:
121
+ raise ValueError(f"Unsupported video number of dimensions: {video_ndim}")
122
+ # ============================================================
123
+ # helpers
124
+ # ============================================================
125
+ def _build_schema_slices(self, schema: List[Tuple[str, int]]):
126
+ slices = {}
127
+ start = 0
128
+ for name, dim in schema:
129
+ slices[name] = slice(start, start + dim)
130
+ start += dim
131
+ return slices, start
132
+ def _to_tensor_2d(self, x, horizon: int, name: str) -> torch.Tensor:
133
+ """
134
+ 把输入转成 [T, D] 的 torch.Tensor。
135
+ 支持 list / np.ndarray / torch.Tensor。
136
+ """
137
+ if isinstance(x, torch.Tensor):
138
+ t = x
139
+ else:
140
+ t = torch.as_tensor(x)
141
+ if t.ndim == 1:
142
+ # [T] -> [T, 1]
143
+ if t.shape[0] != horizon:
144
+ raise ValueError(
145
+ f"{name} has shape {tuple(t.shape)}, expected first dim == horizon={horizon}"
146
+ )
147
+ t = t.unsqueeze(-1)
148
+ elif t.ndim == 2:
149
+ if t.shape[0] != horizon:
150
+ raise ValueError(
151
+ f"{name} has shape {tuple(t.shape)}, expected first dim == horizon={horizon}"
152
+ )
153
+ else:
154
+ raise ValueError(
155
+ f"{name} must be 1D or 2D ([T] or [T, D]), but got shape {tuple(t.shape)}"
156
+ )
157
+ return t.float()
158
+ def _merged_suffix_to_canonical(self) -> Dict[str, str]:
159
+ merged = dict(DEFAULT_SUFFIX_TO_CANONICAL)
160
+ merged.update(self.extra_suffix_to_canonical)
161
+ return merged
162
+ def _merged_canonical_to_candidates(self) -> Dict[str, List[str]]:
163
+ suffix_to_canonical = self._merged_suffix_to_canonical()
164
+ canonical_to_candidates: Dict[str, List[str]] = {}
165
+ for suffix, canonical in suffix_to_canonical.items():
166
+ canonical_to_candidates.setdefault(canonical, []).append(suffix)
167
+ return canonical_to_candidates
168
+ def _get_block_from_data(
169
+ self,
170
+ data: dict,
171
+ prefix: str, # "state" or "action"
172
+ canonical_name: str, # e.g. "left_arm"
173
+ horizon: int,
174
+ ) -> Optional[torch.Tensor]:
175
+ """
176
+ 从 data 里找一个 block。
177
+ 支持:
178
+ 1) data["state.left_arm"]
179
+ 2) data["state"]["left_arm"]
180
+ 3) alias, 例如 left_pose -> left_arm
181
+ """
182
+ canonical_to_candidates = self._merged_canonical_to_candidates()
183
+ candidate_suffixes = canonical_to_candidates.get(canonical_name, [canonical_name])
184
+ # 先查扁平 key:data["state.left_arm"]
185
+ for suffix in candidate_suffixes:
186
+ flat_key = f"{prefix}.{suffix}"
187
+ if flat_key in data:
188
+ return self._to_tensor_2d(data[flat_key], horizon=horizon, name=flat_key)
189
+ # 再查嵌套 key:data["state"]["left_arm"]
190
+ if prefix in data and isinstance(data[prefix], dict):
191
+ subdict = data[prefix]
192
+ for suffix in candidate_suffixes:
193
+ if suffix in subdict:
194
+ return self._to_tensor_2d(subdict[suffix], horizon=horizon, name=f"{prefix}.{suffix}")
195
+ return None
196
+ def _assemble_from_blocks(
197
+ self,
198
+ data: dict,
199
+ prefix: str, # "state" or "action"
200
+ schema: List[Tuple[str, int]],
201
+ horizon: int,
202
+ max_dim: int,
203
+ ):
204
+ schema_slices, schema_total_dim = self._build_schema_slices(schema)
205
+ if max_dim < schema_total_dim:
206
+ raise ValueError(
207
+ f"{prefix}: max_dim={max_dim} is smaller than schema_total_dim={schema_total_dim}"
208
+ )
209
+ out = torch.zeros((horizon, max_dim), dtype=torch.float32)
210
+ mask = torch.zeros((horizon, max_dim), dtype=torch.bool)
211
+ for canonical_name, dst_dim in schema:
212
+ dst_slice = schema_slices[canonical_name]
213
+ block = self._get_block_from_data(
214
+ data=data,
215
+ prefix=prefix,
216
+ canonical_name=canonical_name,
217
+ horizon=horizon,
218
+ )
219
+ if block is None:
220
+ continue
221
+ src_dim = block.shape[1]
222
+ copy_dim = min(src_dim, dst_dim)
223
+ out[:, dst_slice.start: dst_slice.start + copy_dim] = block[:, :copy_dim]
224
+ mask[:, dst_slice.start: dst_slice.start + copy_dim] = True
225
+ if canonical_name == "waist" and src_dim == 2 and dst_dim == 3:
226
+ continue
227
+ # 如果原始维度和 schema 不一致,给出提示
228
+ if src_dim != dst_dim:
229
+ print(
230
+ f"[GR00TTransform][{prefix}] block '{canonical_name}' dim mismatch: "
231
+ f"input={src_dim}, schema={dst_dim}, copy_dim={copy_dim}"
232
+ )
233
+ return out, mask
234
+ # ============================================================
235
+ # prepare state / action
236
+ # ============================================================
237
+ def _prepare_state(self, data: dict):
238
+ """
239
+ 不再依赖 data["state"] 是预先 concat 好的矩阵。
240
+ 直接从:
241
+ data["state.left_arm"], data["state.right_arm"], ...
242
+ 或:
243
+ data["state"]["left_arm"], ...
244
+ 中组装。
245
+ """
246
+ state, state_mask = self._assemble_from_blocks(
247
+ data=data,
248
+ prefix="state",
249
+ schema=UNIFIED_STATE_SCHEMA,
250
+ horizon=self.state_horizon,
251
+ max_dim=self.max_state_dim,
252
+ )
253
+ return state, state_mask, self.state_horizon
254
+ def _prepare_action(self, data: dict):
255
+ """
256
+ 不再依赖 data["action"] 是预先 concat 好的矩阵。
257
+ """
258
+ action, action_mask = self._assemble_from_blocks(
259
+ data=data,
260
+ prefix="action",
261
+ schema=UNIFIED_ACTION_SCHEMA,
262
+ horizon=self.action_horizon,
263
+ max_dim=self.max_action_dim,
264
+ )
265
+ return action, action_mask, self.action_horizon
266
+ # ============================================================
267
+ # main apply
268
+ # ============================================================
269
+ def apply_single(self, data: dict) -> dict:
270
+ transformed_data = data.copy()
271
+ vlm_outputs = {}
272
+ state, state_mask, _ = self._prepare_state(data)
273
+ transformed_data["state"] = state.numpy()
274
+ transformed_data["state_mask"] = state_mask.numpy()
275
+ if self.training:
276
+ transformed_data["segmentation_target"] = np.zeros((2,), dtype=np.float32)
277
+ transformed_data["segmentation_target_mask"] = np.zeros((1,), dtype=bool)
278
+ transformed_data["has_real_action"] = np.ones((), dtype=bool)
279
+ action, action_mask, _ = self._prepare_action(data)
280
+ transformed_data["action"] = action.numpy()
281
+ transformed_data["action_mask"] = action_mask.numpy()
282
+ for k, v in vlm_outputs.items():
283
+ assert k not in transformed_data, f"Key {k} already exists in transformed_data."
284
+ transformed_data[k] = v
285
+ transformed_data["embodiment_id"] = self.get_embodiment_tag()
286
+ if self.training:
287
+ assert transformed_data["action"].shape == transformed_data["action_mask"].shape, (
288
+ transformed_data["action"].shape,
289
+ transformed_data["action_mask"].shape,
290
+ )
291
+ return transformed_data
292
+ def apply_batch(self, data: dict, batch_size: int) -> dict:
293
+ data_split = [tree.map_structure(lambda x: x[i], data) for i in range(batch_size)]
294
+ data_split_processed = [self.apply_single(elem) for elem in data_split]
295
+ return collate(data_split_processed)
296
+ def apply(self, data: dict) -> dict:
297
+ return self.apply_single(data)
298
+ def unapply(self, data: dict) -> dict:
299
+ return data
300
+ def __call__(self, data: dict) -> dict:
301
+ return self.apply(data)
starVLA/dataloader/gr00t_lerobot/transform/state_action.py ADDED
@@ -0,0 +1,606 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import functools
17
+ import random
18
+ from typing import Any, ClassVar
19
+
20
+ import numpy as np
21
+ # import pytorch3d.transforms as pt
22
+ import torch
23
+ from pydantic import Field, PrivateAttr, field_validator, model_validator
24
+
25
+ from ..schema import DatasetMetadata, RotationType, StateActionMetadata
26
+ from .base import InvertibleModalityTransform, ModalityTransform
27
+
28
+
29
+ class RotationTransform:
30
+ """Adapted from https://github.com/real-stanford/diffusion_policy/blob/548a52bbb105518058e27bf34dcf90bf6f73681a/diffusion_policy/model/common/rotation_transformer.py"""
31
+
32
+ valid_reps = ["axis_angle", "euler_angles", "quaternion", "rotation_6d", "matrix"]
33
+
34
+ def __init__(self, from_rep="axis_angle", to_rep="rotation_6d"):
35
+ """
36
+ Valid representations
37
+
38
+ Always use matrix as intermediate representation.
39
+ """
40
+ if from_rep.startswith("euler_angles"):
41
+ from_convention = from_rep.split("_")[-1]
42
+ from_rep = "euler_angles"
43
+ from_convention = from_convention.replace("r", "X").replace("p", "Y").replace("y", "Z")
44
+ else:
45
+ from_convention = None
46
+ if to_rep.startswith("euler_angles"):
47
+ to_convention = to_rep.split("_")[-1]
48
+ to_rep = "euler_angles"
49
+ to_convention = to_convention.replace("r", "X").replace("p", "Y").replace("y", "Z")
50
+ else:
51
+ to_convention = None
52
+ assert from_rep != to_rep, f"from_rep and to_rep cannot be the same: {from_rep}"
53
+ assert from_rep in self.valid_reps, f"Invalid from_rep: {from_rep}"
54
+ assert to_rep in self.valid_reps, f"Invalid to_rep: {to_rep}"
55
+
56
+ forward_funcs = list()
57
+ inverse_funcs = list()
58
+
59
+ if from_rep != "matrix":
60
+ funcs = [getattr(pt, f"{from_rep}_to_matrix"), getattr(pt, f"matrix_to_{from_rep}")]
61
+ if from_convention is not None:
62
+ funcs = [functools.partial(func, convention=from_convention) for func in funcs]
63
+ forward_funcs.append(funcs[0])
64
+ inverse_funcs.append(funcs[1])
65
+
66
+ if to_rep != "matrix":
67
+ funcs = [getattr(pt, f"matrix_to_{to_rep}"), getattr(pt, f"{to_rep}_to_matrix")]
68
+ if to_convention is not None:
69
+ funcs = [functools.partial(func, convention=to_convention) for func in funcs]
70
+ forward_funcs.append(funcs[0])
71
+ inverse_funcs.append(funcs[1])
72
+
73
+ inverse_funcs = inverse_funcs[::-1]
74
+
75
+ self.forward_funcs = forward_funcs
76
+ self.inverse_funcs = inverse_funcs
77
+
78
+ @staticmethod
79
+ def _apply_funcs(x: torch.Tensor, funcs: list) -> torch.Tensor:
80
+ assert isinstance(x, torch.Tensor)
81
+ for func in funcs:
82
+ x = func(x)
83
+ return x
84
+
85
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
86
+ assert isinstance(
87
+ x, torch.Tensor
88
+ ), f"Unexpected input type: {type(x)}. Expected type: {torch.Tensor}"
89
+ return self._apply_funcs(x, self.forward_funcs)
90
+
91
+ def inverse(self, x: torch.Tensor) -> torch.Tensor:
92
+ assert isinstance(
93
+ x, torch.Tensor
94
+ ), f"Unexpected input type: {type(x)}. Expected type: {torch.Tensor}"
95
+ return self._apply_funcs(x, self.inverse_funcs)
96
+
97
+
98
+ class Normalizer:
99
+ valid_modes = ["q99", "mean_std", "min_max", "binary"]
100
+
101
+ def __init__(self, mode: str, statistics: dict):
102
+ self.mode = mode
103
+ self.statistics = statistics
104
+ for key, value in self.statistics.items():
105
+ self.statistics[key] = torch.tensor(value)
106
+
107
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
108
+ assert isinstance(
109
+ x, torch.Tensor
110
+ ), f"Unexpected input type: {type(x)}. Expected type: {torch.Tensor}"
111
+
112
+ # Normalize the tensor
113
+ if self.mode == "q99":
114
+ # Range of q99 is [-1, 1]
115
+ q01 = self.statistics["q01"].to(x.dtype)
116
+ q99 = self.statistics["q99"].to(x.dtype)
117
+
118
+ # In the case of q01 == q99, the normalization will be undefined
119
+ # So we set the normalized values to the original values
120
+ mask = q01 != q99
121
+ normalized = torch.zeros_like(x)
122
+
123
+ # Normalize the values where q01 != q99
124
+ # Formula: 2 * (x - q01) / (q99 - q01) - 1
125
+ normalized[..., mask] = (x[..., mask] - q01[..., mask]) / (
126
+ q99[..., mask] - q01[..., mask]
127
+ )
128
+ normalized[..., mask] = 2 * normalized[..., mask] - 1
129
+
130
+ # Set the normalized values to the original values where q01 == q99
131
+ normalized[..., ~mask] = x[..., ~mask].to(x.dtype)
132
+
133
+ # Clip the normalized values to be between -1 and 1
134
+ normalized = torch.clamp(normalized, -1, 1)
135
+
136
+ elif self.mode == "mean_std":
137
+ # Range of mean_std is not fixed, but can be positive or negative
138
+ mean = self.statistics["mean"].to(x.dtype)
139
+ std = self.statistics["std"].to(x.dtype)
140
+
141
+ # In the case of std == 0, the normalization will be undefined
142
+ # So we set the normalized values to the original values
143
+ mask = std != 0
144
+ normalized = torch.zeros_like(x)
145
+
146
+ # Normalize the values where std != 0
147
+ # Formula: (x - mean) / std
148
+ normalized[..., mask] = (x[..., mask] - mean[..., mask]) / std[..., mask]
149
+
150
+ # Set the normalized values to the original values where std == 0
151
+ normalized[..., ~mask] = x[..., ~mask].to(x.dtype)
152
+
153
+ elif self.mode == "min_max":
154
+ # Range of min_max is [-1, 1]
155
+ min = self.statistics["min"].to(x.dtype)
156
+ max = self.statistics["max"].to(x.dtype)
157
+
158
+ # In the case of min == max, the normalization will be undefined
159
+ # So we set the normalized values to the original values
160
+ mask = min != max
161
+ normalized = torch.zeros_like(x)
162
+
163
+ # Normalize the values where min != max
164
+ # Formula: 2 * (x - min) / (max - min) - 1
165
+ normalized[..., mask] = (x[..., mask] - min[..., mask]) / (
166
+ max[..., mask] - min[..., mask]
167
+ )
168
+ normalized[..., mask] = 2 * normalized[..., mask] - 1
169
+
170
+ # Set the normalized values to the original values where min == max
171
+ # normalized[..., ~mask] = x[..., ~mask].to(x.dtype)
172
+ # Set the normalized values to 0 where min == max
173
+ normalized[..., ~mask] = 0
174
+
175
+ elif self.mode == "scale":
176
+ # Range of scale is [0, 1]
177
+ min = self.statistics["min"].to(x.dtype)
178
+ max = self.statistics["max"].to(x.dtype)
179
+ abs_max = torch.max(torch.abs(min), torch.abs(max))
180
+ mask = abs_max != 0
181
+ normalized = torch.zeros_like(x)
182
+ normalized[..., mask] = x[..., mask] / abs_max[..., mask]
183
+ normalized[..., ~mask] = 0
184
+
185
+ elif self.mode == "binary":
186
+ # Range of binary is [0, 1]
187
+ normalized = (x > 0.5).to(x.dtype)
188
+ else:
189
+ raise ValueError(f"Invalid normalization mode: {self.mode}")
190
+
191
+ return normalized
192
+
193
+ def inverse(self, x: torch.Tensor) -> torch.Tensor:
194
+ assert isinstance(
195
+ x, torch.Tensor
196
+ ), f"Unexpected input type: {type(x)}. Expected type: {torch.Tensor}"
197
+ if self.mode == "q99":
198
+ q01 = self.statistics["q01"].to(x.dtype)
199
+ q99 = self.statistics["q99"].to(x.dtype)
200
+ return (x + 1) / 2 * (q99 - q01) + q01
201
+ elif self.mode == "mean_std":
202
+ mean = self.statistics["mean"].to(x.dtype)
203
+ std = self.statistics["std"].to(x.dtype)
204
+ return x * std + mean
205
+ elif self.mode == "min_max":
206
+ min = self.statistics["min"].to(x.dtype)
207
+ max = self.statistics["max"].to(x.dtype)
208
+ return (x + 1) / 2 * (max - min) + min
209
+ elif self.mode == "binary":
210
+ return (x > 0.5).to(x.dtype)
211
+ else:
212
+ raise ValueError(f"Invalid normalization mode: {self.mode}")
213
+
214
+
215
+ class StateActionToTensor(InvertibleModalityTransform):
216
+ """
217
+ Transforms states and actions to tensors.
218
+ """
219
+
220
+ input_dtypes: dict[str, np.dtype] = Field(
221
+ default_factory=dict, description="The input dtypes for each state key."
222
+ )
223
+ output_dtypes: dict[str, torch.dtype] = Field(
224
+ default_factory=dict, description="The output dtypes for each state key."
225
+ )
226
+
227
+ def model_dump(self, *args, **kwargs):
228
+ if kwargs.get("mode", "python") == "json":
229
+ include = {"apply_to"}
230
+ else:
231
+ include = kwargs.pop("include", None)
232
+
233
+ return super().model_dump(*args, include=include, **kwargs)
234
+
235
+ @field_validator("input_dtypes", "output_dtypes", mode="before")
236
+ def validate_dtypes(cls, v):
237
+ for key, dtype in v.items():
238
+ if isinstance(dtype, str):
239
+ if dtype.startswith("torch."):
240
+ dtype_split = dtype.split(".")[-1]
241
+ v[key] = getattr(torch, dtype_split)
242
+ elif dtype.startswith("np.") or dtype.startswith("numpy."):
243
+ dtype_split = dtype.split(".")[-1]
244
+ v[key] = np.dtype(dtype_split)
245
+ else:
246
+ raise ValueError(f"Invalid dtype: {dtype}")
247
+ return v
248
+
249
+ def apply(self, data: dict[str, Any]) -> dict[str, Any]:
250
+ for key in self.apply_to:
251
+ if key not in data:
252
+ continue
253
+ value = data[key]
254
+ assert isinstance(
255
+ value, np.ndarray
256
+ ), f"Unexpected input type: {type(value)}. Expected type: {np.ndarray}"
257
+ data[key] = torch.from_numpy(value)
258
+ if key in self.output_dtypes:
259
+ data[key] = data[key].to(self.output_dtypes[key])
260
+ return data
261
+
262
+ def unapply(self, data: dict[str, Any]) -> dict[str, Any]:
263
+ for key in self.apply_to:
264
+ if key not in data:
265
+ continue
266
+ value = data[key]
267
+ assert isinstance(
268
+ value, torch.Tensor
269
+ ), f"Unexpected input type: {type(value)}. Expected type: {torch.Tensor}"
270
+ data[key] = value.numpy()
271
+ if key in self.input_dtypes:
272
+ data[key] = data[key].astype(self.input_dtypes[key])
273
+ return data
274
+
275
+
276
+ class StateActionTransform(InvertibleModalityTransform):
277
+ """
278
+ Class for state or action transform.
279
+
280
+ Args:
281
+ apply_to (list[str]): The keys in the modality to load and transform.
282
+ normalization_modes (dict[str, str]): The normalization modes for each state key.
283
+ If a state key in apply_to is not present in the dictionary, it will not be normalized.
284
+ target_rotations (dict[str, str]): The target representations for each state key.
285
+ If a state key in apply_to is not present in the dictionary, it will not be rotated.
286
+ """
287
+
288
+ # Configurable attributes
289
+ apply_to: list[str] = Field(..., description="The keys in the modality to load and transform.")
290
+ normalization_modes: dict[str, str] = Field(
291
+ default_factory=dict, description="The normalization modes for each state key."
292
+ )
293
+ target_rotations: dict[str, str] = Field(
294
+ default_factory=dict, description="The target representations for each state key."
295
+ )
296
+ normalization_statistics: dict[str, dict] = Field(
297
+ default_factory=dict, description="The statistics for each state key."
298
+ )
299
+ modality_metadata: dict[str, StateActionMetadata] = Field(
300
+ default_factory=dict, description="The modality metadata for each state key."
301
+ )
302
+
303
+ # Model variables
304
+ _rotation_transformers: dict[str, RotationTransform] = PrivateAttr(default_factory=dict)
305
+ _normalizers: dict[str, Normalizer] = PrivateAttr(default_factory=dict)
306
+ _input_dtypes: dict[str, np.dtype | torch.dtype] = PrivateAttr(default_factory=dict)
307
+
308
+ # Model constants
309
+ _DEFAULT_MIN_MAX_STATISTICS: ClassVar[dict] = {
310
+ "rotation_6d": {
311
+ "min": [-1, -1, -1, -1, -1, -1],
312
+ "max": [1, 1, 1, 1, 1, 1],
313
+ },
314
+ "euler_angles": {
315
+ "min": [-np.pi, -np.pi, -np.pi],
316
+ "max": [np.pi, np.pi, np.pi],
317
+ },
318
+ "quaternion": {
319
+ "min": [-1, -1, -1, -1],
320
+ "max": [1, 1, 1, 1],
321
+ },
322
+ "axis_angle": {
323
+ "min": [-np.pi, -np.pi, -np.pi],
324
+ "max": [np.pi, np.pi, np.pi],
325
+ },
326
+ }
327
+
328
+ def model_dump(self, *args, **kwargs):
329
+ if kwargs.get("mode", "python") == "json":
330
+ include = {"apply_to", "normalization_modes", "target_rotations"}
331
+ else:
332
+ include = kwargs.pop("include", None)
333
+
334
+ return super().model_dump(*args, include=include, **kwargs)
335
+
336
+ @field_validator("modality_metadata", mode="before")
337
+ def validate_modality_metadata(cls, v):
338
+ for modality_key, config in v.items():
339
+ if isinstance(config, dict):
340
+ config = StateActionMetadata.model_validate(config)
341
+ else:
342
+ assert isinstance(
343
+ config, StateActionMetadata
344
+ ), f"Invalid source rotation config: {config}"
345
+ v[modality_key] = config
346
+ return v
347
+
348
+ @model_validator(mode="after")
349
+ def validate_normalization_statistics(self):
350
+ for modality_key, normalization_statistics in self.normalization_statistics.items():
351
+ if modality_key in self.normalization_modes:
352
+ normalization_mode = self.normalization_modes[modality_key]
353
+ if normalization_mode == "min_max":
354
+ assert (
355
+ "min" in normalization_statistics and "max" in normalization_statistics
356
+ ), f"Min and max statistics are required for min_max normalization, but got {normalization_statistics}"
357
+ assert len(normalization_statistics["min"]) == len(
358
+ normalization_statistics["max"]
359
+ ), f"Min and max statistics must have the same length, but got {normalization_statistics['min']} and {normalization_statistics['max']}"
360
+ elif normalization_mode == "mean_std":
361
+ assert (
362
+ "mean" in normalization_statistics and "std" in normalization_statistics
363
+ ), f"Mean and std statistics are required for mean_std normalization, but got {normalization_statistics}"
364
+ assert len(normalization_statistics["mean"]) == len(
365
+ normalization_statistics["std"]
366
+ ), f"Mean and std statistics must have the same length, but got {normalization_statistics['mean']} and {normalization_statistics['std']}"
367
+ elif normalization_mode == "q99":
368
+ assert (
369
+ "q01" in normalization_statistics and "q99" in normalization_statistics
370
+ ), f"q01 and q99 statistics are required for q99 normalization, but got {normalization_statistics}"
371
+ assert len(normalization_statistics["q01"]) == len(
372
+ normalization_statistics["q99"]
373
+ ), f"q01 and q99 statistics must have the same length, but got {normalization_statistics['q01']} and {normalization_statistics['q99']}"
374
+ elif normalization_mode == "binary":
375
+ assert (
376
+ len(normalization_statistics) == 1
377
+ ), f"Binary normalization should only have one value, but got {normalization_statistics}"
378
+ assert normalization_statistics[0] in [
379
+ 0,
380
+ 1,
381
+ ], f"Binary normalization should only have 0 or 1, but got {normalization_statistics[0]}"
382
+ else:
383
+ raise ValueError(f"Invalid normalization mode: {normalization_mode}")
384
+ return self
385
+
386
+ def set_metadata(self, dataset_metadata: DatasetMetadata):
387
+ dataset_statistics = dataset_metadata.statistics
388
+ modality_metadata = dataset_metadata.modalities
389
+
390
+ # Check that all state keys specified in apply_to have their modality_metadata
391
+ for key in self.apply_to:
392
+ split_key = key.split(".", 1)
393
+ assert len(split_key) == 2, "State keys should have two parts: 'modality.key'"
394
+ if key not in self.modality_metadata:
395
+ modality, state_key = split_key
396
+ assert hasattr(modality_metadata, modality), f"{modality} config not found"
397
+ assert state_key in getattr(
398
+ modality_metadata, modality
399
+ ), f"{state_key} config not found"
400
+ self.modality_metadata[key] = getattr(modality_metadata, modality)[state_key]
401
+
402
+ # Check that all state keys specified in normalization_modes have their statistics in state_statistics
403
+ for key in self.normalization_modes:
404
+ split_key = key.split(".", 1)
405
+ assert len(split_key) == 2, "State keys should have two parts: 'modality.key'"
406
+ modality, state_key = split_key
407
+ assert hasattr(dataset_statistics, modality), f"{modality} statistics not found"
408
+ assert state_key in getattr(
409
+ dataset_statistics, modality
410
+ ), f"{state_key} statistics not found"
411
+ assert (
412
+ len(getattr(modality_metadata, modality)[state_key].shape) == 1
413
+ ), f"{getattr(modality_metadata, modality)[state_key].shape=}"
414
+ self.normalization_statistics[key] = getattr(dataset_statistics, modality)[
415
+ state_key
416
+ ].model_dump()
417
+
418
+ # Initialize the rotation transformers
419
+ for key in self.target_rotations:
420
+ # Get the original representation of the state
421
+ from_rep = self.modality_metadata[key].rotation_type
422
+ assert from_rep is not None, f"Source rotation type not found for {key}"
423
+
424
+ # Get the target representation of the state, will raise an error if the target representation is not valid
425
+ to_rep = RotationType(self.target_rotations[key])
426
+
427
+ # If the original representation is not the same as the target representation, initialize the rotation transformer
428
+ if from_rep != to_rep:
429
+ self._rotation_transformers[key] = RotationTransform(
430
+ from_rep=from_rep.value, to_rep=to_rep.value
431
+ )
432
+
433
+ # Initialize the normalizers
434
+ for key in self.normalization_modes:
435
+ modality, state_key = key.split(".", 1)
436
+ # If the state has a nontrivial rotation, we need to handle it more carefully
437
+ # For absolute rotations, we need to convert them to the target representation and normalize them using min_max mode,
438
+ # since we can infer the bounds by the representation
439
+ # For relative rotations, we cannot normalize them as we don't know the bounds
440
+ if key in self._rotation_transformers:
441
+ # Case 1: Absolute rotation
442
+ if self.modality_metadata[key].absolute:
443
+ # Check that the normalization mode is valid
444
+ assert (
445
+ self.normalization_modes[key] == "min_max"
446
+ ), "Absolute rotations that are converted to other formats must be normalized using `min_max` mode"
447
+ rotation_type = RotationType(self.target_rotations[key]).value
448
+ # If the target representation is euler angles, we need to parse the convention
449
+ if rotation_type.startswith("euler_angles"):
450
+ rotation_type = "euler_angles"
451
+ # Get the statistics for the target representation
452
+ statistics = self._DEFAULT_MIN_MAX_STATISTICS[rotation_type]
453
+ # Case 2: Relative rotation
454
+ else:
455
+ raise ValueError(
456
+ f"Cannot normalize relative rotations: {key} that's converted to {self.target_rotations[key]}"
457
+ )
458
+ # If the state is not continuous, we should not use normalization modes other than binary
459
+ elif (
460
+ not self.modality_metadata[key].continuous
461
+ and self.normalization_modes[key] != "binary"
462
+ ):
463
+ raise ValueError(
464
+ f"{key} is not continuous, so it should be normalized using `binary` mode"
465
+ )
466
+ # Initialize the normalizer
467
+ else:
468
+ statistics = self.normalization_statistics[key]
469
+ self._normalizers[key] = Normalizer(
470
+ mode=self.normalization_modes[key], statistics=statistics
471
+ )
472
+
473
+ def apply(self, data: dict[str, Any]) -> dict[str, Any]:
474
+ for key in self.apply_to:
475
+ if key not in data:
476
+ # We allow some keys to be missing in the data, and only process the keys that are present
477
+ continue
478
+ if key not in self._input_dtypes:
479
+ input_dtype = data[key].dtype
480
+ assert isinstance(
481
+ input_dtype, torch.dtype
482
+ ), f"Unexpected input dtype: {input_dtype}. Expected type: {torch.dtype}"
483
+ self._input_dtypes[key] = input_dtype
484
+ else:
485
+ assert (
486
+ data[key].dtype == self._input_dtypes[key]
487
+ ), f"All states corresponding to the same key must be of the same dtype, input dtype: {data[key].dtype}, expected dtype: {self._input_dtypes[key]}"
488
+ # Rotate the state
489
+ state = data[key]
490
+ if key in self._rotation_transformers:
491
+ state = self._rotation_transformers[key].forward(state)
492
+ # Normalize the state
493
+ if key in self._normalizers:
494
+ state = self._normalizers[key].forward(state)
495
+ data[key] = state
496
+ return data
497
+
498
+ def unapply(self, data: dict[str, Any]) -> dict[str, Any]:
499
+ for key in self.apply_to:
500
+ if key not in data:
501
+ continue
502
+ state = data[key]
503
+ assert isinstance(
504
+ state, torch.Tensor
505
+ ), f"Unexpected state type: {type(state)}. Expected type: {torch.Tensor}"
506
+ # Unnormalize the state
507
+ if key in self._normalizers:
508
+ state = self._normalizers[key].inverse(state)
509
+ # Change the state back to its original representation
510
+ if key in self._rotation_transformers:
511
+ state = self._rotation_transformers[key].inverse(state)
512
+ assert isinstance(
513
+ state, torch.Tensor
514
+ ), f"State should be tensor after unapplying transformations, but got {type(state)}"
515
+ # Only convert back to the original dtype if it's known, i.e. `apply` was called before
516
+ # If not, we don't know the original dtype, so we don't convert
517
+ if key in self._input_dtypes:
518
+ original_dtype = self._input_dtypes[key]
519
+ if isinstance(original_dtype, np.dtype):
520
+ state = state.numpy().astype(original_dtype)
521
+ elif isinstance(original_dtype, torch.dtype):
522
+ state = state.to(original_dtype)
523
+ else:
524
+ raise ValueError(f"Invalid input dtype: {original_dtype}")
525
+ data[key] = state
526
+ return data
527
+
528
+
529
+ class StateActionPerturbation(ModalityTransform):
530
+ """
531
+ Class for state or action perturbation.
532
+
533
+ Args:
534
+ apply_to (list[str]): The keys in the modality to load and transform.
535
+ std (float): Standard deviation of the noise to be added to the state or action.
536
+ """
537
+
538
+ # Configurable attributes
539
+ std: float = Field(
540
+ ..., description="Standard deviation of the noise to be added to the state or action."
541
+ )
542
+
543
+ def apply(self, data: dict[str, Any]) -> dict[str, Any]:
544
+ if not self.training:
545
+ # Don't perturb the data in eval mode
546
+ return data
547
+ if self.std < 0:
548
+ # If the std is negative, we don't add any noise
549
+ return data
550
+ for key in self.apply_to:
551
+ state = data[key]
552
+ assert isinstance(state, torch.Tensor)
553
+ transformed_data_min = torch.min(state)
554
+ transformed_data_max = torch.max(state)
555
+ noise = torch.randn_like(state) * self.std
556
+ state += noise
557
+ # Clip to the original range
558
+ state = torch.clamp(state, transformed_data_min, transformed_data_max)
559
+ data[key] = state
560
+ return data
561
+
562
+
563
+ class StateActionDropout(ModalityTransform):
564
+ """
565
+ Class for state or action dropout.
566
+
567
+ Args:
568
+ apply_to (list[str]): The keys in the modality to load and transform.
569
+ dropout_prob (float): Probability of dropping out a state or action.
570
+ """
571
+
572
+ # Configurable attributes
573
+ dropout_prob: float = Field(..., description="Probability of dropping out a state or action.")
574
+
575
+ def apply(self, data: dict[str, Any]) -> dict[str, Any]:
576
+ if not self.training:
577
+ # Don't drop out the data in eval mode
578
+ return data
579
+ if self.dropout_prob < 0:
580
+ # If the dropout probability is negative, we don't drop out any states
581
+ return data
582
+ if self.dropout_prob > 1e-9 and random.random() < self.dropout_prob:
583
+ for key in self.apply_to:
584
+ state = data[key]
585
+ assert isinstance(state, torch.Tensor)
586
+ state = torch.zeros_like(state)
587
+ data[key] = state
588
+ return data
589
+
590
+
591
+ class StateActionSinCosTransform(ModalityTransform):
592
+ """
593
+ Class for state or action sin-cos transform.
594
+
595
+ Args:
596
+ apply_to (list[str]): The keys in the modality to load and transform.
597
+ """
598
+
599
+ def apply(self, data: dict[str, Any]) -> dict[str, Any]:
600
+ for key in self.apply_to:
601
+ state = data[key]
602
+ assert isinstance(state, torch.Tensor)
603
+ sin_state = torch.sin(state)
604
+ cos_state = torch.cos(state)
605
+ data[key] = torch.cat([sin_state, cos_state], dim=-1)
606
+ return data
starVLA/dataloader/gr00t_lerobot/transform/video.py ADDED
@@ -0,0 +1,683 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import Any, Callable, ClassVar, Literal
17
+
18
+ import albumentations as A
19
+ import cv2
20
+ import numpy as np
21
+ import torch
22
+ import torchvision.transforms.v2 as T
23
+ from einops import rearrange
24
+ from pydantic import Field, PrivateAttr, field_validator
25
+ from PIL import Image
26
+
27
+ from ..schema import DatasetMetadata
28
+ from .base import ModalityTransform
29
+
30
+
31
+ class VideoTransform(ModalityTransform):
32
+ # Configurable attributes
33
+ backend: str = Field(
34
+ default="torchvision", description="The backend to use for the transformations"
35
+ )
36
+
37
+ # Model variables
38
+ _train_transform: Callable | None = PrivateAttr(default=None)
39
+ _eval_transform: Callable | None = PrivateAttr(default=None)
40
+ _original_resolutions: dict[str, tuple[int, int]] = PrivateAttr(default_factory=dict)
41
+
42
+ # Model constants
43
+ _INTERPOLATION_MAP: ClassVar[dict[str, dict[str, Any]]] = PrivateAttr(
44
+ {
45
+ "nearest": {
46
+ "albumentations": cv2.INTER_NEAREST,
47
+ "torchvision": T.InterpolationMode.NEAREST,
48
+ },
49
+ "linear": {
50
+ "albumentations": cv2.INTER_LINEAR,
51
+ "torchvision": T.InterpolationMode.BILINEAR,
52
+ },
53
+ "cubic": {
54
+ "albumentations": cv2.INTER_CUBIC,
55
+ "torchvision": T.InterpolationMode.BICUBIC,
56
+ },
57
+ "area": {
58
+ "albumentations": cv2.INTER_AREA,
59
+ "torchvision": None, # Torchvision does not support this interpolation mode
60
+ },
61
+ "lanczos4": {
62
+ "albumentations": cv2.INTER_LANCZOS4, # Lanczos with a 4x4 filter
63
+ "torchvision": T.InterpolationMode.LANCZOS, # Torchvision does not specify filter size, might be different from 4x4
64
+ },
65
+ "linear_exact": {
66
+ "albumentations": cv2.INTER_LINEAR_EXACT,
67
+ "torchvision": None, # Torchvision does not support this interpolation mode
68
+ },
69
+ "nearest_exact": {
70
+ "albumentations": cv2.INTER_NEAREST_EXACT,
71
+ "torchvision": T.InterpolationMode.NEAREST_EXACT,
72
+ },
73
+ "max": {
74
+ "albumentations": cv2.INTER_MAX,
75
+ "torchvision": None,
76
+ },
77
+ }
78
+ )
79
+
80
+ @property
81
+ def train_transform(self) -> Callable:
82
+ assert (
83
+ self._train_transform is not None
84
+ ), "Transform is not set. Please call set_metadata() before calling apply()."
85
+ return self._train_transform
86
+
87
+ @train_transform.setter
88
+ def train_transform(self, value: Callable):
89
+ self._train_transform = value
90
+
91
+ @property
92
+ def eval_transform(self) -> Callable | None:
93
+ return self._eval_transform
94
+
95
+ @eval_transform.setter
96
+ def eval_transform(self, value: Callable | None):
97
+ self._eval_transform = value
98
+
99
+ @property
100
+ def original_resolutions(self) -> dict[str, tuple[int, int]]:
101
+ assert (
102
+ self._original_resolutions is not None
103
+ ), "Original resolutions are not set. Please call set_metadata() before calling apply()."
104
+ return self._original_resolutions
105
+
106
+ @original_resolutions.setter
107
+ def original_resolutions(self, value: dict[str, tuple[int, int]]):
108
+ self._original_resolutions = value
109
+
110
+ def check_input(self, data: dict[str, Any]):
111
+ if self.backend == "torchvision":
112
+ for key in self.apply_to:
113
+ assert isinstance(data[key], torch.Tensor), f"Video {key} is not a torch tensor"
114
+ assert data[key].ndim in [
115
+ 4,
116
+ 5,
117
+ ], f"Expected video {key} to have 4 or 5 dimensions (T, C, H, W or T, B, C, H, W), got {data[key].ndim}"
118
+ elif self.backend == "albumentations":
119
+ for key in self.apply_to:
120
+ assert isinstance(data[key], np.ndarray), f"Video {key} is not a numpy array"
121
+ assert data[key].ndim in [
122
+ 4,
123
+ 5,
124
+ ], f"Expected video {key} to have 4 or 5 dimensions (T, C, H, W or T, B, C, H, W), got {data[key].ndim}"
125
+ else:
126
+ raise ValueError(f"Backend {self.backend} not supported")
127
+
128
+ def set_metadata(self, dataset_metadata: DatasetMetadata):
129
+ super().set_metadata(dataset_metadata)
130
+ self.original_resolutions = {}
131
+ for key in self.apply_to:
132
+ split_keys = key.split(".")
133
+ assert len(split_keys) == 2, f"Invalid key: {key}. Expected format: modality.key"
134
+ sub_key = split_keys[1]
135
+ if sub_key in dataset_metadata.modalities.video:
136
+ self.original_resolutions[key] = dataset_metadata.modalities.video[
137
+ sub_key
138
+ ].resolution
139
+ else:
140
+ raise ValueError(
141
+ f"Video key {sub_key} not found in dataset metadata. Available keys: {dataset_metadata.modalities.video.keys()}"
142
+ )
143
+ train_transform = self.get_transform(mode="train")
144
+ eval_transform = self.get_transform(mode="eval")
145
+ if self.backend == "albumentations":
146
+ self.train_transform = A.ReplayCompose(transforms=[train_transform]) # type: ignore
147
+ if eval_transform is not None:
148
+ self.eval_transform = A.ReplayCompose(transforms=[eval_transform]) # type: ignore
149
+ else:
150
+ assert train_transform is not None, "Train transform must be set"
151
+ self.train_transform = train_transform
152
+ self.eval_transform = eval_transform
153
+
154
+ def apply(self, data: dict[str, Any]) -> dict[str, Any]:
155
+ if self.training:
156
+ transform = self.train_transform
157
+ else:
158
+ transform = self.eval_transform
159
+ if transform is None:
160
+ return data
161
+ assert (
162
+ transform is not None
163
+ ), "Transform is not set. Please call set_metadata() before calling apply()."
164
+ try:
165
+ self.check_input(data)
166
+ except AssertionError as e:
167
+ raise ValueError(
168
+ f"Input data does not match the expected format for {self.__class__.__name__}: {e}"
169
+ ) from e
170
+
171
+ # Concatenate views
172
+ views = [data[key] for key in self.apply_to]
173
+ num_views = len(views)
174
+ is_batched = views[0].ndim == 5
175
+ bs = views[0].shape[0] if is_batched else 1
176
+ if isinstance(views[0], torch.Tensor):
177
+ views = torch.cat(views, 0)
178
+ elif isinstance(views[0], np.ndarray):
179
+ views = np.concatenate(views, 0)
180
+ else:
181
+ raise ValueError(f"Unsupported view type: {type(views[0])}")
182
+ if is_batched:
183
+ views = rearrange(views, "(v b) t c h w -> (v b t) c h w", v=num_views, b=bs)
184
+ # Apply the transform
185
+ if self.backend == "torchvision":
186
+ views = transform(views)
187
+ elif self.backend == "albumentations":
188
+ assert isinstance(transform, A.ReplayCompose), "Transform must be a ReplayCompose"
189
+ first_frame = views[0]
190
+ transformed = transform(image=first_frame)
191
+ replay_data = transformed["replay"]
192
+ transformed_first_frame = transformed["image"]
193
+
194
+ if len(views) > 1:
195
+ # Apply the same transformations to the rest of the frames
196
+ transformed_frames = [
197
+ transform.replay(replay_data, image=frame)["image"] for frame in views[1:]
198
+ ]
199
+ # Add the first frame back
200
+ transformed_frames = [transformed_first_frame] + transformed_frames
201
+ else:
202
+ # If there is only one frame, just make a list with one frame
203
+ transformed_frames = [transformed_first_frame]
204
+
205
+ # Delete the replay data to save memory
206
+ del replay_data
207
+ views = np.stack(transformed_frames, 0)
208
+
209
+ else:
210
+ raise ValueError(f"Backend {self.backend} not supported")
211
+ # Split views
212
+ if is_batched:
213
+ views = rearrange(views, "(v b t) c h w -> v b t c h w", v=num_views, b=bs)
214
+ else:
215
+ views = rearrange(views, "(v t) c h w -> v t c h w", v=num_views)
216
+ for key, view in zip(self.apply_to, views):
217
+ data[key] = view
218
+ return data
219
+
220
+ @classmethod
221
+ def _validate_interpolation(cls, interpolation: str):
222
+ if interpolation not in cls._INTERPOLATION_MAP:
223
+ raise ValueError(f"Interpolation mode {interpolation} not supported")
224
+
225
+ def _get_interpolation(self, interpolation: str, backend: str = "torchvision"):
226
+ """
227
+ Get the interpolation mode for the given backend.
228
+
229
+ Args:
230
+ interpolation (str): The interpolation mode.
231
+ backend (str): The backend to use.
232
+
233
+ Returns:
234
+ Any: The interpolation mode for the given backend.
235
+ """
236
+ return self._INTERPOLATION_MAP[interpolation][backend]
237
+
238
+ def get_transform(self, mode: Literal["train", "eval"] = "train") -> Callable | None:
239
+ raise NotImplementedError(
240
+ "set_transform is not implemented for VideoTransform. Please implement this function to set the transforms."
241
+ )
242
+
243
+
244
+ class VideoCrop(VideoTransform):
245
+ height: int | None = Field(default=None, description="The height of the input image")
246
+ width: int | None = Field(default=None, description="The width of the input image")
247
+ scale: float = Field(
248
+ ...,
249
+ description="The scale of the crop. The crop size is (width * scale, height * scale)",
250
+ )
251
+
252
+ def get_transform(self, mode: Literal["train", "eval"] = "train") -> Callable:
253
+ """Get the transform for the given mode.
254
+
255
+ Args:
256
+ mode (Literal["train", "eval"]): The mode to get the transform for.
257
+
258
+ Returns:
259
+ Callable: If mode is "train", return a random crop transform. If mode is "eval", return a center crop transform.
260
+ """
261
+ # 1. Check the input resolution
262
+ assert (
263
+ len(set(self.original_resolutions.values())) == 1
264
+ ), f"All video keys must have the same resolution, got: {self.original_resolutions}"
265
+ if self.height is None:
266
+ assert self.width is None, "Height and width must be either both provided or both None"
267
+ self.width, self.height = self.original_resolutions[self.apply_to[0]]
268
+ else:
269
+ assert (
270
+ self.width is not None
271
+ ), "Height and width must be either both provided or both None"
272
+ # 2. Create the transform
273
+ size = (int(self.height * self.scale), int(self.width * self.scale))
274
+ if self.backend == "torchvision":
275
+ if mode == "train":
276
+ return T.RandomCrop(size)
277
+ elif mode == "eval":
278
+ return T.CenterCrop(size)
279
+ else:
280
+ raise ValueError(f"Crop mode {mode} not supported")
281
+ elif self.backend == "albumentations":
282
+ if mode == "train":
283
+ return A.RandomCrop(height=size[0], width=size[1], p=1)
284
+ elif mode == "eval":
285
+ return A.CenterCrop(height=size[0], width=size[1], p=1)
286
+ else:
287
+ raise ValueError(f"Crop mode {mode} not supported")
288
+ else:
289
+ raise ValueError(f"Backend {self.backend} not supported")
290
+
291
+ def check_input(self, data: dict[str, Any]):
292
+ super().check_input(data)
293
+ # Check the input resolution
294
+ for key in self.apply_to:
295
+ if self.backend == "torchvision":
296
+ height, width = data[key].shape[-2:]
297
+ elif self.backend == "albumentations":
298
+ height, width = data[key].shape[-3:-1]
299
+ else:
300
+ raise ValueError(f"Backend {self.backend} not supported")
301
+ assert (
302
+ height == self.height and width == self.width
303
+ ), f"Video {key} has invalid shape {height, width}, expected {self.height, self.width}"
304
+
305
+ class VideoResizePad(VideoTransform):
306
+ size: int = Field(..., description="The target size (both height and width will be this value)")
307
+ interpolation: str = Field(default="linear", description="The interpolation mode")
308
+ antialias: bool = Field(default=True, description="Whether to apply antialiasing")
309
+ fill_value: float = Field(default=0.0, description="The value to fill the padding (0.0 for black)")
310
+
311
+ @field_validator("interpolation")
312
+ def validate_interpolation(cls, v):
313
+ cls._validate_interpolation(v)
314
+ return v
315
+
316
+ def get_transform(self, mode: Literal["train", "eval"] = "train") -> Callable:
317
+ """Get the resize and pad transform that keeps aspect ratio.
318
+
319
+ Args:
320
+ mode (Literal["train", "eval"]): The mode to get the transform for.
321
+
322
+ Returns:
323
+ Callable: The resize and pad transform that resizes the longest edge to target size and pads the rest.
324
+ """
325
+ if self.backend == "torchvision":
326
+ return self._torchvision_resize_pad
327
+ elif self.backend == "albumentations":
328
+ # For albumentations, use LongestMaxSize + PadIfNeeded
329
+ interpolation = self._get_interpolation(self.interpolation, self.backend)
330
+ return A.Compose([
331
+ A.LongestMaxSize(max_size=self.size, interpolation=interpolation, p=1),
332
+ A.PadIfNeeded(
333
+ min_height=self.size,
334
+ min_width=self.size,
335
+ border_mode=cv2.BORDER_CONSTANT,
336
+ value=int(self.fill_value * 255), # Convert to uint8 range for numpy arrays
337
+ position=A.PadIfNeeded.PositionType.CENTER, # Center the image
338
+ p=1
339
+ )
340
+ ])
341
+ else:
342
+ raise ValueError(f"Backend {self.backend} not supported")
343
+
344
+ def _torchvision_resize_pad(self, frames: torch.Tensor) -> torch.Tensor:
345
+ """Resize and pad frames using torchvision.
346
+
347
+ Args:
348
+ frames: tensor of shape [N, C, H, W] where N could be batch*time
349
+
350
+ Returns:
351
+ tensor of shape [N, C, target_size, target_size]
352
+ """
353
+ interpolation = self._get_interpolation(self.interpolation, self.backend)
354
+ N, C, H, W = frames.shape
355
+
356
+ # Calculate scaling factor (scale longest edge to target size)
357
+ scale = self.size / max(H, W)
358
+ new_h = int(H * scale)
359
+ new_w = int(W * scale)
360
+
361
+ # Resize
362
+ resized = T.Resize((new_h, new_w), interpolation=interpolation, antialias=self.antialias)(frames)
363
+
364
+ # Calculate padding
365
+ pad_h = self.size - new_h
366
+ pad_w = self.size - new_w
367
+ pad_top = pad_h // 2
368
+ pad_bottom = pad_h - pad_top
369
+ pad_left = pad_w // 2
370
+ pad_right = pad_w - pad_left
371
+
372
+ # Pad (pad order is: left, right, top, bottom)
373
+ padded = T.Pad([pad_left, pad_top, pad_right, pad_bottom], fill=self.fill_value)(resized)
374
+
375
+ return padded
376
+
377
+ class VideoResize(VideoTransform):
378
+ height: int = Field(..., description="The height of the resize")
379
+ width: int = Field(..., description="The width of the resize")
380
+ interpolation: str = Field(default="linear", description="The interpolation mode")
381
+ antialias: bool = Field(default=True, description="Whether to apply antialiasing")
382
+
383
+ @field_validator("interpolation")
384
+ def validate_interpolation(cls, v):
385
+ cls._validate_interpolation(v)
386
+ return v
387
+
388
+ def get_transform(self, mode: Literal["train", "eval"] = "train") -> Callable:
389
+ """Get the resize transform. Same transform for both train and eval.
390
+
391
+ Args:
392
+ mode (Literal["train", "eval"]): The mode to get the transform for.
393
+
394
+ Returns:
395
+ Callable: The resize transform.
396
+ """
397
+ interpolation = self._get_interpolation(self.interpolation, self.backend)
398
+ if interpolation is None:
399
+ raise ValueError(
400
+ f"Interpolation mode {self.interpolation} not supported for torchvision"
401
+ )
402
+ if self.backend == "torchvision":
403
+ size = (self.height, self.width)
404
+ return T.Resize(size, interpolation=interpolation, antialias=self.antialias)
405
+ elif self.backend == "albumentations":
406
+ return A.Resize(
407
+ height=self.height,
408
+ width=self.width,
409
+ interpolation=interpolation,
410
+ p=1,
411
+ )
412
+ else:
413
+ raise ValueError(f"Backend {self.backend} not supported")
414
+
415
+
416
+ class VideoRandomRotation(VideoTransform):
417
+ degrees: float | tuple[float, float] = Field(
418
+ ..., description="The degrees of the random rotation"
419
+ )
420
+ interpolation: str = Field("linear", description="The interpolation mode")
421
+
422
+ @field_validator("interpolation")
423
+ def validate_interpolation(cls, v):
424
+ cls._validate_interpolation(v)
425
+ return v
426
+
427
+ def get_transform(self, mode: Literal["train", "eval"] = "train") -> Callable | None:
428
+ """Get the random rotation transform, only used in train mode.
429
+
430
+ Args:
431
+ mode (Literal["train", "eval"]): The mode to get the transform for.
432
+
433
+ Returns:
434
+ Callable | None: The random rotation transform. None for eval mode.
435
+ """
436
+ if mode == "eval":
437
+ return None
438
+ interpolation = self._get_interpolation(self.interpolation, self.backend)
439
+ if interpolation is None:
440
+ raise ValueError(
441
+ f"Interpolation mode {self.interpolation} not supported for torchvision"
442
+ )
443
+ if self.backend == "torchvision":
444
+ return T.RandomRotation(self.degrees, interpolation=interpolation) # type: ignore
445
+ elif self.backend == "albumentations":
446
+ return A.Rotate(limit=self.degrees, interpolation=interpolation, p=1)
447
+ else:
448
+ raise ValueError(f"Backend {self.backend} not supported")
449
+
450
+
451
+ class VideoHorizontalFlip(VideoTransform):
452
+ p: float = Field(..., description="The probability of the horizontal flip")
453
+
454
+ def get_transform(self, mode: Literal["train", "eval"] = "train") -> Callable | None:
455
+ """Get the horizontal flip transform, only used in train mode.
456
+
457
+ Args:
458
+ mode (Literal["train", "eval"]): The mode to get the transform for.
459
+
460
+ Returns:
461
+ Callable | None: If mode is "train", return a horizontal flip transform. If mode is "eval", return None.
462
+ """
463
+ if mode == "eval":
464
+ return None
465
+ if self.backend == "torchvision":
466
+ return T.RandomHorizontalFlip(self.p)
467
+ elif self.backend == "albumentations":
468
+ return A.HorizontalFlip(p=self.p)
469
+ else:
470
+ raise ValueError(f"Backend {self.backend} not supported")
471
+
472
+
473
+ class VideoGrayscale(VideoTransform):
474
+ p: float = Field(..., description="The probability of the grayscale transformation")
475
+
476
+ def get_transform(self, mode: Literal["train", "eval"] = "train") -> Callable | None:
477
+ """Get the grayscale transform, only used in train mode.
478
+
479
+ Args:
480
+ mode (Literal["train", "eval"]): The mode to get the transform for.
481
+
482
+ Returns:
483
+ Callable | None: If mode is "train", return a grayscale transform. If mode is "eval", return None.
484
+ """
485
+ if mode == "eval":
486
+ return None
487
+ if self.backend == "torchvision":
488
+ return T.RandomGrayscale(self.p)
489
+ elif self.backend == "albumentations":
490
+ return A.ToGray(p=self.p)
491
+ else:
492
+ raise ValueError(f"Backend {self.backend} not supported")
493
+
494
+
495
+ class VideoColorJitter(VideoTransform):
496
+ brightness: float | tuple[float, float] = Field(
497
+ ..., description="The brightness of the color jitter"
498
+ )
499
+ contrast: float | tuple[float, float] = Field(
500
+ ..., description="The contrast of the color jitter"
501
+ )
502
+ saturation: float | tuple[float, float] = Field(
503
+ ..., description="The saturation of the color jitter"
504
+ )
505
+ hue: float | tuple[float, float] = Field(..., description="The hue of the color jitter")
506
+
507
+ def get_transform(self, mode: Literal["train", "eval"] = "train") -> Callable | None:
508
+ """Get the color jitter transform, only used in train mode.
509
+
510
+ Args:
511
+ mode (Literal["train", "eval"]): The mode to get the transform for.
512
+
513
+ Returns:
514
+ Callable | None: If mode is "train", return a color jitter transform. If mode is "eval", return None.
515
+ """
516
+ if mode == "eval":
517
+ return None
518
+ if self.backend == "torchvision":
519
+ return T.ColorJitter(
520
+ brightness=self.brightness,
521
+ contrast=self.contrast,
522
+ saturation=self.saturation,
523
+ hue=self.hue,
524
+ )
525
+ elif self.backend == "albumentations":
526
+ return A.ColorJitter(
527
+ brightness=self.brightness,
528
+ contrast=self.contrast,
529
+ saturation=self.saturation,
530
+ hue=self.hue,
531
+ p=1,
532
+ )
533
+ else:
534
+ raise ValueError(f"Backend {self.backend} not supported")
535
+
536
+
537
+ class VideoRandomGrayscale(VideoTransform):
538
+ p: float = Field(..., description="The probability of the grayscale transformation")
539
+
540
+ def get_transform(self, mode: Literal["train", "eval"] = "train") -> Callable | None:
541
+ """Get the grayscale transform, only used in train mode.
542
+
543
+ Args:
544
+ mode (Literal["train", "eval"]): The mode to get the transform for.
545
+
546
+ Returns:
547
+ Callable | None: If mode is "train", return a grayscale transform. If mode is "eval", return None.
548
+ """
549
+ if mode == "eval":
550
+ return None
551
+ if self.backend == "torchvision":
552
+ return T.RandomGrayscale(self.p)
553
+ elif self.backend == "albumentations":
554
+ return A.ToGray(p=self.p)
555
+ else:
556
+ raise ValueError(f"Backend {self.backend} not supported")
557
+
558
+
559
+ class VideoRandomPosterize(VideoTransform):
560
+ bits: int = Field(..., description="The number of bits to posterize the image")
561
+ p: float = Field(..., description="The probability of the posterize transformation")
562
+
563
+ def get_transform(self, mode: Literal["train", "eval"] = "train") -> Callable | None:
564
+ """Get the posterize transform, only used in train mode.
565
+
566
+ Args:
567
+ mode (Literal["train", "eval"]): The mode to get the transform for.
568
+
569
+ Returns:
570
+ Callable | None: If mode is "train", return a posterize transform. If mode is "eval", return None.
571
+ """
572
+ if mode == "eval":
573
+ return None
574
+ if self.backend == "torchvision":
575
+ return T.RandomPosterize(bits=self.bits, p=self.p)
576
+ elif self.backend == "albumentations":
577
+ return A.Posterize(num_bits=self.bits, p=self.p)
578
+ else:
579
+ raise ValueError(f"Backend {self.backend} not supported")
580
+
581
+
582
+ class VideoToTensor(VideoTransform):
583
+ def get_transform(self, mode: Literal["train", "eval"] = "train") -> Callable:
584
+ """Get the to tensor transform. Same transform for both train and eval.
585
+
586
+ Args:
587
+ mode (Literal["train", "eval"]): The mode to get the transform for.
588
+
589
+ Returns:
590
+ Callable: The to tensor transform.
591
+ """
592
+ if self.backend == "torchvision":
593
+ return self.__class__.to_tensor
594
+ else:
595
+ raise ValueError(f"Backend {self.backend} not supported")
596
+
597
+ def check_input(self, data: dict):
598
+ """Check if the input data has the correct shape.
599
+ Expected video shape: [T, H, W, C], dtype np.uint8
600
+ """
601
+ for key in self.apply_to:
602
+ assert key in data, f"Key {key} not found in data. Available keys: {data.keys()}"
603
+ assert data[key].ndim in [
604
+ 4,
605
+ 5,
606
+ ], f"Video {key} must have 4 or 5 dimensions, got {data[key].ndim}"
607
+ assert (
608
+ data[key].dtype == np.uint8
609
+ ), f"Video {key} must have dtype uint8, got {data[key].dtype}"
610
+ input_resolution = data[key].shape[-3:-1][::-1]
611
+ if key in self.original_resolutions:
612
+ expected_resolution = self.original_resolutions[key]
613
+ else:
614
+ expected_resolution = input_resolution
615
+ assert (
616
+ input_resolution == expected_resolution
617
+ ), f"Video {key} has invalid resolution {input_resolution}, expected {expected_resolution}. Full shape: {data[key].shape}"
618
+
619
+ @staticmethod
620
+ def to_tensor(frames: np.ndarray) -> torch.Tensor:
621
+ """Convert numpy array to tensor efficiently.
622
+
623
+ Args:
624
+ frames: numpy array of shape [T, H, W, C] in uint8 format
625
+ Returns:
626
+ tensor of shape [T, C, H, W] in range [0, 1]
627
+ """
628
+ frames_tensor = torch.from_numpy(frames).to(torch.float32) / 255.0
629
+ return frames_tensor.permute(0, 3, 1, 2) # [T, C, H, W]
630
+
631
+
632
+ class VideoToNumpy(VideoTransform):
633
+ def get_transform(self, mode: Literal["train", "eval"] = "train") -> Callable:
634
+ """Get the to numpy transform. Same transform for both train and eval.
635
+
636
+ Args:
637
+ mode (Literal["train", "eval"]): The mode to get the transform for.
638
+
639
+ Returns:
640
+ Callable: The to numpy transform.
641
+ """
642
+ if self.backend == "torchvision":
643
+ return self.__class__.to_numpy
644
+ else:
645
+ raise ValueError(f"Backend {self.backend} not supported")
646
+
647
+ @staticmethod
648
+ def to_numpy(frames: torch.Tensor) -> np.ndarray:
649
+ """Convert tensor back to numpy array efficiently.
650
+
651
+ Args:
652
+ frames: tensor of shape [T, C, H, W] in range [0, 1]
653
+ Returns:
654
+ numpy array of shape [T, H, W, C] in uint8 format
655
+ """
656
+ return (frames.permute(0, 2, 3, 1) * 255).to(torch.uint8).cpu().numpy()
657
+
658
+ class VideoToPIL(VideoTransform):
659
+ def get_transform(self, mode: Literal["train", "eval"] = "train") -> Callable:
660
+ """Get the to PIL transform. Same transform for both train and eval.
661
+
662
+ Args:
663
+ mode (Literal["train", "eval"]): The mode to get the transform for.
664
+
665
+ Returns:
666
+ Callable: The to PIL transform.
667
+ """
668
+ if self.backend == "torchvision":
669
+ return self.__class__.to_pil
670
+ else:
671
+ raise ValueError(f"Backend {self.backend} not supported")
672
+
673
+ @staticmethod
674
+ def to_pil(frames: torch.Tensor) -> Image.Image:
675
+ """Convert tensor back to PIL Image.
676
+
677
+ Args:
678
+ frames: tensor of shape [T, C, H, W] in range [0, 1]
679
+ Returns:
680
+ PIL Image of shape [T, H, W, C] in uint8 format
681
+ """
682
+ # video PIL format?
683
+ return Image.fromarray((frames.permute(0, 2, 3, 1) * 255).to(torch.uint8).cpu().numpy())
starVLA/dataloader/gr00t_lerobot/video.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import av
17
+ import cv2
18
+ import numpy as np
19
+ import warnings
20
+
21
+ import torch # noqa: F401 # isort: skip
22
+ import torchvision # noqa: F401 # isort: skip
23
+
24
+ # Suppress torchvision video deprecation warning
25
+ warnings.filterwarnings("ignore", category=UserWarning, module="torchvision.io._video_deprecation_warning")
26
+
27
+ # Import decord with graceful fallback
28
+ try:
29
+ import decord # noqa: F401
30
+
31
+ DECORD_AVAILABLE = True
32
+ except ImportError:
33
+ DECORD_AVAILABLE = False
34
+
35
+ try:
36
+ import torchcodec
37
+
38
+ TORCHCODEC_AVAILABLE = True
39
+ except (ImportError, RuntimeError):
40
+ TORCHCODEC_AVAILABLE = False
41
+
42
+
43
+ def get_frames_by_indices(
44
+ video_path: str,
45
+ indices: list[int] | np.ndarray,
46
+ video_backend: str = "decord",
47
+ video_backend_kwargs: dict = {},
48
+ ) -> np.ndarray:
49
+ if video_backend == "decord":
50
+ if not DECORD_AVAILABLE:
51
+ raise ImportError("decord is not available.")
52
+ vr = decord.VideoReader(video_path, **video_backend_kwargs)
53
+ frames = vr.get_batch(indices)
54
+ return frames.asnumpy()
55
+ elif video_backend == "torchcodec":
56
+ if not TORCHCODEC_AVAILABLE:
57
+ raise ImportError("torchcodec is not available.")
58
+ decoder = torchcodec.decoders.VideoDecoder(video_path, device="cpu", dimension_order="NHWC", num_ffmpeg_threads=0)
59
+ return decoder.get_frames_at(indices=indices).data.numpy()
60
+ elif video_backend == "opencv":
61
+ frames = []
62
+ cap = cv2.VideoCapture(video_path, **video_backend_kwargs)
63
+ for idx in indices:
64
+ cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
65
+ ret, frame = cap.read()
66
+ if not ret:
67
+ raise ValueError(f"Unable to read frame at index {idx}")
68
+ frames.append(frame)
69
+ cap.release()
70
+ frames = np.array(frames)
71
+ return frames
72
+ elif video_backend == "torchvision_av":
73
+ # Optimized version using PyAV directly for better performance
74
+ container = av.open(video_path)
75
+ video_stream = container.streams.video[0]
76
+ fps = float(video_stream.average_rate)
77
+
78
+ # Convert frame indices to timestamps
79
+ timestamps = np.array(indices) / fps
80
+
81
+ # Sort indices to optimize seeking
82
+ sorted_order = np.argsort(timestamps)
83
+ sorted_timestamps = timestamps[sorted_order]
84
+
85
+ loaded_frames = [None] * len(indices)
86
+
87
+ try:
88
+ last_seek_pos = -1
89
+ for i, target_ts in zip(sorted_order, sorted_timestamps):
90
+ # Only seek if we're going backwards or far ahead
91
+ if target_ts < last_seek_pos or target_ts - last_seek_pos > 2.0:
92
+ # Seek to slightly before target to ensure we don't miss it
93
+ seek_ts = max(0, target_ts - 0.5)
94
+ container.seek(
95
+ int(seek_ts / float(video_stream.time_base)),
96
+ stream=video_stream,
97
+ backward=True,
98
+ any_frame=False,
99
+ )
100
+
101
+ closest_frame = None
102
+ closest_ts_diff = float('inf')
103
+
104
+ # Read frames until we pass the target timestamp
105
+ for frame in container.decode(video=0):
106
+ current_ts = frame.pts * video_stream.time_base
107
+ current_diff = abs(current_ts - target_ts)
108
+
109
+ if current_diff < closest_ts_diff:
110
+ closest_ts_diff = current_diff
111
+ closest_frame = frame
112
+ else:
113
+ # Timestamps are increasing, we've passed the target
114
+ break
115
+
116
+ # If we're very close, stop early
117
+ if current_diff < 0.001:
118
+ break
119
+
120
+ if closest_frame is not None:
121
+ frame_array = closest_frame.to_ndarray(format="rgb24")
122
+ loaded_frames[i] = frame_array
123
+ last_seek_pos = target_ts
124
+
125
+ finally:
126
+ container.close()
127
+
128
+ # Filter out any None values (shouldn't happen, but safety check)
129
+ loaded_frames = [f for f in loaded_frames if f is not None]
130
+
131
+ if len(loaded_frames) == 0:
132
+ raise ValueError(f"No frames could be loaded from {video_path}")
133
+
134
+ return np.array(loaded_frames)
135
+ else:
136
+ raise NotImplementedError
137
+
138
+
139
+ def get_frames_by_timestamps(
140
+ video_path: str,
141
+ timestamps: list[float] | np.ndarray,
142
+ video_backend: str = "decord",
143
+ video_backend_kwargs: dict = {},
144
+ ) -> np.ndarray:
145
+ """Get frames from a video at specified timestamps.
146
+ Args:
147
+ video_path (str): Path to the video file.
148
+ timestamps (list[int] | np.ndarray): Timestamps to retrieve frames for, in seconds.
149
+ video_backend (str, optional): Video backend to use. Defaults to "decord".
150
+ Returns:
151
+ np.ndarray: Frames at the specified timestamps.
152
+ """
153
+ if video_backend == "decord":
154
+ # For some GPUs, AV format data cannot be read
155
+ if not DECORD_AVAILABLE:
156
+ raise ImportError("decord is not available.")
157
+ vr = decord.VideoReader(video_path, **video_backend_kwargs)
158
+ num_frames = len(vr)
159
+ # Retrieve the timestamps for each frame in the video
160
+ frame_ts: np.ndarray = vr.get_frame_timestamp(range(num_frames))
161
+ # Map each requested timestamp to the closest frame index
162
+ # Only take the first element of the frame_ts array which corresponds to start_seconds
163
+ indices = np.abs(frame_ts[:, :1] - timestamps).argmin(axis=0)
164
+ frames = vr.get_batch(indices)
165
+ return frames.asnumpy()
166
+ elif video_backend == "torchcodec":
167
+ if not TORCHCODEC_AVAILABLE:
168
+ raise ImportError("torchcodec is not available.")
169
+ decoder = torchcodec.decoders.VideoDecoder(video_path, device="cpu", dimension_order="NHWC", num_ffmpeg_threads=0)
170
+ return decoder.get_frames_played_at(seconds=timestamps).data.numpy()
171
+ elif video_backend == "opencv":
172
+ # Open the video file
173
+ cap = cv2.VideoCapture(video_path, **video_backend_kwargs)
174
+ if not cap.isOpened():
175
+ raise ValueError(f"Unable to open video file: {video_path}")
176
+ # Retrieve the total number of frames
177
+ num_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
178
+ # Calculate timestamps for each frame
179
+ fps = cap.get(cv2.CAP_PROP_FPS)
180
+ frame_ts = np.arange(num_frames) / fps
181
+ frame_ts = frame_ts[:, np.newaxis] # Reshape to (num_frames, 1) for broadcasting
182
+ # Map each requested timestamp to the closest frame index
183
+ indices = np.abs(frame_ts - timestamps).argmin(axis=0)
184
+ frames = []
185
+ for idx in indices:
186
+ cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
187
+ ret, frame = cap.read()
188
+ if not ret:
189
+ raise ValueError(f"Unable to read frame at index {idx}")
190
+ frames.append(frame)
191
+ cap.release()
192
+ frames = np.array(frames)
193
+ return frames
194
+ elif video_backend == "torchvision_av":
195
+ # PyAV 单次 decode 版本:避免反复 decode 导致 dav1d-worker 线程暴涨
196
+ ts = np.asarray(timestamps, dtype=np.float64)
197
+ if ts.ndim != 1:
198
+ ts = ts.reshape(-1)
199
+
200
+ order = np.argsort(ts)
201
+ ts_sorted = ts[order]
202
+
203
+ container = av.open(video_path, options={"threads": "1"})
204
+ stream = container.streams.video[0]
205
+
206
+ # 更强的“钉死线程”措施(不同版本可能有差异,try/except 保守)
207
+ try:
208
+ stream.thread_type = "NONE"
209
+ except Exception:
210
+ pass
211
+ try:
212
+ stream.codec_context.thread_count = 1
213
+ except Exception:
214
+ pass
215
+
216
+ out_sorted = [None] * len(ts_sorted)
217
+
218
+ try:
219
+ # seek 到最早 timestamp 之前一点
220
+ start_ts = max(0.0, float(ts_sorted[0]) - 0.5)
221
+ try:
222
+ container.seek(
223
+ int(start_ts / float(stream.time_base)),
224
+ stream=stream,
225
+ backward=True,
226
+ any_frame=False,
227
+ )
228
+ except Exception:
229
+ # seek 不可靠就从头开始
230
+ container.seek(0)
231
+
232
+ j = 0
233
+ last_frame_arr = None
234
+
235
+ # 一次 decode 顺序扫过去
236
+ for frame in container.decode(video=0):
237
+ if frame.pts is None:
238
+ continue
239
+ t = float(frame.pts * stream.time_base)
240
+
241
+ # 如果还没到下一个目标,继续 decode
242
+ if t + 1e-6 < ts_sorted[j]:
243
+ last_frame_arr = frame.to_ndarray(format="rgb24")
244
+ continue
245
+
246
+ # 到达/超过目标:把当前帧作为该目标的匹配帧
247
+ frame_arr = frame.to_ndarray(format="rgb24")
248
+ last_frame_arr = frame_arr
249
+
250
+ while j < len(ts_sorted) and t + 1e-6 >= ts_sorted[j]:
251
+ out_sorted[j] = frame_arr
252
+ j += 1
253
+ if j >= len(ts_sorted):
254
+ break
255
+
256
+ if j >= len(ts_sorted):
257
+ break
258
+
259
+ # 如果尾部还有没填的,用最后一帧补(或你也可以 raise���
260
+ for k in range(len(out_sorted)):
261
+ if out_sorted[k] is None:
262
+ out_sorted[k] = last_frame_arr
263
+
264
+ finally:
265
+ container.close()
266
+
267
+ if out_sorted[0] is None:
268
+ raise ValueError(f"No frames could be loaded from {video_path}")
269
+
270
+ frames_sorted = np.stack(out_sorted, axis=0)
271
+
272
+ # 还原到原 timestamps 顺序
273
+ inv = np.empty_like(order)
274
+ inv[order] = np.arange(len(order))
275
+ return frames_sorted[inv]
276
+
277
+ else:
278
+ raise NotImplementedError
279
+
280
+
281
+ def get_all_frames(
282
+ video_path: str,
283
+ video_backend: str = "decord",
284
+ video_backend_kwargs: dict = {},
285
+ resize_size: tuple[int, int] | None = None,
286
+ ) -> np.ndarray:
287
+ """Get all frames from a video.
288
+ Args:
289
+ video_path (str): Path to the video file.
290
+ video_backend (str, optional): Video backend to use. Defaults to "decord".
291
+ video_backend_kwargs (dict, optional): Keyword arguments for the video backend.
292
+ resize_size (tuple[int, int], optional): Resize size for the frames. Defaults to None.
293
+ """
294
+ if video_backend == "decord":
295
+ if not DECORD_AVAILABLE:
296
+ raise ImportError("decord is not available.")
297
+ vr = decord.VideoReader(video_path, **video_backend_kwargs)
298
+ frames = vr.get_batch(range(len(vr))).asnumpy()
299
+ elif video_backend == "torchcodec":
300
+ if not TORCHCODEC_AVAILABLE:
301
+ raise ImportError("torchcodec is not available.")
302
+ decoder = torchcodec.decoders.VideoDecoder(video_path, device="cpu", dimension_order="NHWC", num_ffmpeg_threads=0)
303
+ frames = decoder.get_frames_at(indices=range(len(decoder)))
304
+ return frames.data.numpy(), frames.pts_seconds.numpy()
305
+ elif video_backend == "pyav":
306
+ container = av.open(video_path)
307
+ frames = []
308
+ for frame in container.decode(video=0):
309
+ frame = frame.to_ndarray(format="rgb24")
310
+ frames.append(frame)
311
+ frames = np.array(frames)
312
+ elif video_backend == "torchvision_av":
313
+ # 全局 backend 只设一次(避免反复改全局状态)
314
+ if getattr(get_all_frames, "_tv_backend_set", False) is False:
315
+ torchvision.set_video_backend("pyav")
316
+ setattr(get_all_frames, "_tv_backend_set", True)
317
+
318
+ reader = torchvision.io.VideoReader(video_path, "video")
319
+ try:
320
+ frames = [f["data"].numpy() for f in reader]
321
+ finally:
322
+ # 不同 torchvision 版本行为不同,尽量显式释放
323
+ if hasattr(reader, "close"):
324
+ try:
325
+ reader.close()
326
+ except Exception:
327
+ pass
328
+ del reader
329
+
330
+ frames = np.array(frames)
331
+ frames = frames.transpose(0, 2, 3, 1)
332
+ else:
333
+ raise NotImplementedError(f"Video backend {video_backend} not implemented")
334
+ # resize frames if specified
335
+ if resize_size is not None:
336
+ frames = [cv2.resize(frame, resize_size) for frame in frames]
337
+ frames = np.array(frames)
338
+ return frames
starVLA/dataloader/lerobot_datasets.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 NVIDIA Corp. and affiliates. All rights reserved.
2
+ # Modified by [Fangjing Wang/ SUST University] in [2025].
3
+ # Modification: [return raw data and suport multi-dataset mixture].
4
+ # Modified by [Jinhui YE/ HKUST University] in [2025].
5
+ # Modification: [suport topdowm processing, suport param from config].
6
+
7
+ from pathlib import Path
8
+ from typing import Sequence
9
+ from omegaconf import OmegaConf
10
+
11
+ from starVLA.dataloader.gr00t_lerobot.datasets import LeRobotSingleDataset, LeRobotMixtureDataset
12
+ from starVLA.dataloader.gr00t_lerobot.mixtures import DATASET_NAMED_MIXTURES
13
+ from starVLA.dataloader.gr00t_lerobot.data_config import ROBOT_TYPE_CONFIG_MAP
14
+ from starVLA.dataloader.gr00t_lerobot.embodiment_tags import ROBOT_TYPE_TO_EMBODIMENT_TAG, EmbodimentTag
15
+
16
+ def collate_fn(batch):
17
+ return batch
18
+
19
+ def make_LeRobotSingleDataset(
20
+ data_root_dir: Path | str,
21
+ data_name: str,
22
+ robot_type: str,
23
+ delete_pause_frame: bool = False,
24
+ data_cfg: dict | None = None,
25
+ ) -> LeRobotSingleDataset:
26
+ """
27
+ param data_root_dir 数据集的根目录。
28
+ param data_name 数据集的名称。
29
+ param robot_type 要使用的机器人类型配置。
30
+ param delete_pause_frame 是否删除暂停帧。
31
+ param data_cfg 数据配置, 包含可选的视频后端设置。
32
+ """
33
+
34
+ # print("########### DATA.lerobot_datasets.make_LeRobotSingleDataset-1")
35
+ data_config = ROBOT_TYPE_CONFIG_MAP[robot_type]
36
+ modality_config = data_config.modality_config()
37
+ transforms = data_config.transform()
38
+ dataset_path = data_root_dir / data_name
39
+ # print(robot_type) # fourier_gr1_arms_waist
40
+ # print(data_config)
41
+ """
42
+ <starVLA.dataloader.gr00t_lerobot.data_config.FourierGr1ArmsWaistDataConfig object at 0x7efbe15b4b80>
43
+ """
44
+ # print(modality_config)
45
+ """
46
+ {
47
+ 'video': ModalityConfig(
48
+ delta_indices=[0],
49
+ modality_keys=['video.ego_view']
50
+ ),
51
+ 'state': ModalityConfig(
52
+ delta_indices=[0],
53
+ modality_keys=['state.left_arm', 'state.right_arm', 'state.left_hand', 'state.right_hand', 'state.waist']
54
+ ),
55
+ 'action': ModalityConfig(
56
+ delta_indices=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
57
+ modality_keys=['action.left_arm', 'action.right_arm', 'action.left_hand', 'action.right_hand', 'action.waist']
58
+ ),
59
+ 'language': ModalityConfig(
60
+ delta_indices=[0],
61
+ modality_keys=['annotation.human.coarse_action']
62
+ )
63
+ }
64
+ """
65
+ # print(transforms)
66
+ """
67
+ apply_to=[]
68
+ training=True
69
+ transforms=[
70
+ StateActionToTensor(
71
+ apply_to=['state.left_arm', 'state.right_arm', 'state.left_hand', 'state.right_hand', 'state.waist'],
72
+ training=True,
73
+ input_dtypes={},
74
+ output_dtypes={}
75
+ ),
76
+ StateActionTransform(
77
+ apply_to=['state.left_arm', 'state.right_arm', 'state.left_hand', 'state.right_hand', 'state.waist'],
78
+ training=True,
79
+ normalization_modes={
80
+ 'state.left_arm': 'min_max',
81
+ 'state.right_arm': 'min_max',
82
+ 'state.left_hand': 'min_max',
83
+ 'state.right_hand': 'min_max',
84
+ 'state.waist': 'min_max'
85
+ },
86
+ target_rotations={},
87
+ normalization_statistics={},
88
+ modality_metadata={}
89
+ ),
90
+ StateActionToTensor(
91
+ apply_to=['action.left_arm', 'action.right_arm', 'action.left_hand', 'action.right_hand', 'action.waist'],
92
+ training=True,
93
+ input_dtypes={},
94
+ output_dtypes={}
95
+ ),
96
+ StateActionTransform(
97
+ apply_to=['action.left_arm', 'action.right_arm', 'action.left_hand', 'action.right_hand', 'action.waist'],
98
+ training=True,
99
+ normalization_modes={
100
+ 'action.left_arm': 'min_max',
101
+ 'action.right_arm': 'min_max',
102
+ 'action.left_hand': 'min_max',
103
+ 'action.right_hand': 'min_max',
104
+ 'action.waist': 'min_max'
105
+ },
106
+ target_rotations={},
107
+ normalization_statistics={},
108
+ modality_metadata={}
109
+ ),
110
+ GR00TTransform(
111
+ apply_to=[],
112
+ training=True,
113
+ embodiment_tag_mapping={
114
+ 'new_embodiment': 31,
115
+ 'oxe_droid': 17,
116
+ 'oxe_bridge': 18,
117
+ 'oxe_rt1': 19,
118
+ 'agibot_genie1': 26,
119
+ 'gr1': 24,
120
+ 'franka': 25,
121
+ 'action_net': 27,
122
+ 'agibot_beta': 28,
123
+ 'egodex': 29,
124
+ 'nvwa_f': 30,
125
+ 'robotwin': 32
126
+ },
127
+ language_dropout_prob=0.0,
128
+ default_instruction='Perform the default behavior.',
129
+ max_state_dim=64,
130
+ max_action_dim=32,
131
+ state_horizon=1,
132
+ action_horizon=16,
133
+ max_length=512,
134
+ embodiment_tag=None,
135
+ extra_suffix_to_canonical={}
136
+ )
137
+ ]
138
+ """
139
+ # print(dataset_path)
140
+ """
141
+ /mnt/workspace/datasets/PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PnPBottleToCabinetClose_ee
142
+ """
143
+
144
+ if robot_type not in ROBOT_TYPE_TO_EMBODIMENT_TAG:
145
+ print(f"Warning: Robot type {robot_type} not found in ROBOT_TYPE_TO_EMBODIMENT_TAG, using {EmbodimentTag.NEW_EMBODIMENT} as default")
146
+ embodiment_tag = EmbodimentTag.NEW_EMBODIMENT
147
+ else:
148
+ embodiment_tag = ROBOT_TYPE_TO_EMBODIMENT_TAG[robot_type]
149
+
150
+ video_backend = data_cfg.get("video_backend", "decord") if data_cfg else "decord"
151
+ dataset = LeRobotSingleDataset(
152
+ dataset_path=dataset_path,
153
+ modality_configs=modality_config,
154
+ transforms=transforms,
155
+ embodiment_tag=embodiment_tag,
156
+ video_backend=video_backend, # decord is more efficiency | torchvision_av for video.av1
157
+ delete_pause_frame=delete_pause_frame,
158
+ data_cfg=data_cfg,
159
+ )
160
+ # print("########### DATA.lerobot_datasets.make_LeRobotSingleDataset-2")
161
+ return dataset
162
+
163
+ def get_vla_dataset(
164
+ data_cfg: dict,
165
+ mode: str = "train",
166
+ balance_dataset_weights: bool = True,
167
+ balance_trajectory_weights: bool = False,
168
+ seed: int = 42,
169
+ **kwargs: dict,
170
+ ) -> LeRobotMixtureDataset:
171
+ # print("########### DATA.lerobot_datasets.get_vla_dataset-1")
172
+ data_root_dir = data_cfg.data_root_dir
173
+ data_mix = data_cfg.data_mix
174
+ delete_pause_frame = data_cfg.get("delete_pause_frame", False)
175
+ mixture_spec = DATASET_NAMED_MIXTURES[data_mix]
176
+ # print(data_cfg.data_root_dir) # /mnt/workspace/datasets/
177
+ # print(data_cfg.data_mix) # robocasa_teleop_ee
178
+ # print(delete_pause_frame) # False
179
+ # print(data_mix) # robocasa_teleop_ee
180
+ # print(mixture_spec)
181
+ """
182
+ [
183
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PnPBottleToCabinetClose_ee', 1.0, 'fourier_gr1_arms_waist'),
184
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PnPCanToDrawerClose_ee', 1.0, 'fourier_gr1_arms_waist'),
185
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PnPCupToDrawerClose_ee', 1.0, 'fourier_gr1_arms_waist'),
186
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PnPMilkToMicrowaveClose_ee', 1.0, 'fourier_gr1_arms_waist'),
187
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PnPPotatoToMicrowaveClose_ee', 1.0, 'fourier_gr1_arms_waist'),
188
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PnPWineToCabinetClose_ee', 1.0, 'fourier_gr1_arms_waist'),
189
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromCuttingboardToBasketSplitA_ee', 1.0, 'fourier_gr1_arms_waist'),
190
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromCuttingboardToCardboardboxSplitA_ee', 1.0, 'fourier_gr1_arms_waist'),
191
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromCuttingboardToPanSplitA_ee', 1.0, 'fourier_gr1_arms_waist'),
192
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromCuttingboardToPotSplitA_ee', 1.0, 'fourier_gr1_arms_waist'),
193
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromCuttingboardToTieredbasketSplitA_ee', 1.0, 'fourier_gr1_arms_waist'),
194
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlacematToBasketSplitA_ee', 1.0, 'fourier_gr1_arms_waist'),
195
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlacematToBowlSplitA_ee', 1.0, 'fourier_gr1_arms_waist'),
196
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlacematToPlateSplitA_ee', 1.0, 'fourier_gr1_arms_waist'),
197
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlacematToTieredshelfSplitA_ee', 1.0, 'fourier_gr1_arms_waist'),
198
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlateToBowlSplitA_ee', 1.0, 'fourier_gr1_arms_waist'),
199
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlateToCardboardboxSplitA_ee', 1.0, 'fourier_gr1_arms_waist'),
200
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlateToPanSplitA_ee', 1.0, 'fourier_gr1_arms_waist'),
201
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlateToPlateSplitA_ee', 1.0, 'fourier_gr1_arms_waist'),
202
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromTrayToCardboardboxSplitA_ee', 1.0, 'fourier_gr1_arms_waist'),
203
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromTrayToPlateSplitA_ee', 1.0, 'fourier_gr1_arms_waist'),
204
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromTrayToPotSplitA_ee', 1.0, 'fourier_gr1_arms_waist'),
205
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromTrayToTieredbasketSplitA_ee', 1.0, 'fourier_gr1_arms_waist'),
206
+ ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromTrayToTieredshelfSplitA_ee', 1.0, 'fourier_gr1_arms_waist')
207
+ ]
208
+ """
209
+
210
+ included_datasets, filtered_mixture_spec = set(), []
211
+ for d_name, d_weight, robot_type in mixture_spec:
212
+ dataset_key = (d_name, robot_type)
213
+ if dataset_key in included_datasets:
214
+ print(f"Skipping Duplicate Dataset: `{(d_name, d_weight, robot_type)}`")
215
+ continue
216
+ included_datasets.add(dataset_key)
217
+ filtered_mixture_spec.append((d_name, d_weight, robot_type))
218
+ # print(len(included_datasets)) # 24
219
+ # print(len(filtered_mixture_spec)) # 24
220
+
221
+ dataset_mixture = []
222
+ for d_name, d_weight, robot_type in filtered_mixture_spec:
223
+ single_dataset = make_LeRobotSingleDataset(
224
+ Path(data_root_dir),
225
+ d_name,
226
+ robot_type,
227
+ delete_pause_frame=delete_pause_frame,
228
+ data_cfg=data_cfg
229
+ )
230
+ # print(type(single_dataset)) # <class 'starVLA.dataloader.gr00t_lerobot.datasets.LeRobotSingleDataset'>
231
+ dataset_mixture.append((single_dataset, d_weight))
232
+
233
+ dataset = LeRobotMixtureDataset(
234
+ dataset_mixture,
235
+ mode=mode,
236
+ balance_dataset_weights=balance_dataset_weights,
237
+ balance_trajectory_weights=balance_trajectory_weights,
238
+ seed=seed,
239
+ data_cfg=data_cfg,
240
+ **kwargs,
241
+ )
242
+ # print(mode) # train
243
+ # print(balance_dataset_weights) # True
244
+ # print(balance_trajectory_weights) # False
245
+ # print("########### DATA.lerobot_datasets.get_vla_dataset-2")
246
+ return dataset
247
+
248
+
249
+
250
+ if __name__ == "__main__":
251
+
252
+ # import debugpy
253
+ import argparse
254
+ parser = argparse.ArgumentParser()
255
+ parser.add_argument("--config_yaml", type=str, default="./examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml", help="Path to YAML config")
256
+ args, clipargs = parser.parse_known_args()
257
+
258
+ # debugpy.listen(("0.0.0.0", 10092))
259
+ # print("🔍 Rank 0 waiting for debugger attach on port 10092...")
260
+ # debugpy.wait_for_client()
261
+ # args.config_yaml = "./examples/Suqian_agibot/train_files/starvla_cotrain_robocasa_gr1.yaml"
262
+ cfg = OmegaConf.load(args.config_yaml)
263
+ cfg.datasets.vla_data.data_mix = "sq_egodex-f_agi_beta"
264
+ vla_dataset_cfg = cfg.datasets.vla_data
265
+ # cfg.datasets.vla_data.include_state = True
266
+ vla_dataset_cfg.task_id = 1
267
+ for task_id in ["all"]:
268
+ vla_dataset_cfg.task_id = task_id
269
+ print(f"Testing Task ID: {task_id}")
270
+ dataset = get_vla_dataset(data_cfg=vla_dataset_cfg)
271
+ # dataset
272
+ from torch.utils.data import DataLoader
273
+ train_dataloader = DataLoader(
274
+ dataset,
275
+ batch_size=2,
276
+ num_workers=1, # For Debug
277
+ collate_fn=collate_fn,
278
+ )
279
+
280
+ cfg.output_dir = "./output/debug"
281
+ output_dir = Path(cfg.output_dir)
282
+ dataset.save_dataset_statistics(output_dir / "dataset_statistics.json")
283
+
284
+ from tqdm import tqdm
285
+ count = 0
286
+ for batch in tqdm(train_dataloader, desc="Processing Batches"):
287
+ # print(batch[0].keys())
288
+ action = batch[0]['action']
289
+ print('action', action[0])
290
+ print('action_mask', batch[0]['action_mask'][0])
291
+ # print(1)
292
+ if count > 100:
293
+ break
294
+ count += 1
295
+ pass
starVLA/dataloader/qwenvl_llavajson/qwen_data_config.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ from pathlib import Path
4
+
5
+ # You can add multimodal datasets here and register a short nickname to ${data_dict}.
6
+ # The data format should follow the general multimodal VLM format, for example:
7
+ # https://github.com/QwenLM/Qwen2.5-VL/blob/main/qwen-vl-finetune/README.md
8
+
9
+ json_root = f"/mnt/workspace/users/chidafeng/jsons"
10
+ # json_root = f"/mnt/workspace/datasets/Cambrian-10M/jsons"
11
+ image_root = f"/mnt/workspace/datasets"
12
+
13
+ ############# VLM Pretrain #############
14
+ CAMBRAIN_300K = {
15
+ "annotation_path": f"/mnt/workspace/users/chidafeng/jsons/Cambrian300k_withsystemprompt.jsonl",
16
+ "data_path": f"{image_root}/Cambrian-10M/",
17
+ }
18
+
19
+ REFSPATIAL_2D_100K = {
20
+ "annotation_path": f"/mnt/workspace/users/chidafeng/jsons/refspatial/refspatial_2d_100k.json",
21
+ "data_path": f"{image_root}/RefSpatial/2D/image/",
22
+ }
23
+
24
+ REFSPATIAL_3D_150K = {
25
+ "annotation_path": f"/mnt/workspace/users/chidafeng/jsons/refspatial/refspatial_3d_150k.json",
26
+ "data_path": f"{image_root}/RefSpatial/3D/image/",
27
+ }
28
+
29
+ REFSPATIAL_3D_VISUAL_50K = {
30
+ "annotation_path": f"/mnt/workspace/users/chidafeng/jsons/refspatial/refspatial_3d_visual_50k.json",
31
+ "data_path": f"{image_root}/RefSpatial/3D/image_visual_choice/",
32
+ }
33
+
34
+ ROBOVQA_300K = {
35
+ "annotation_path": f"/mnt/workspace/users/chidafeng/jsons/robovqa_300k.json",
36
+ "data_path": f"/mnt/workspace/users/chidafeng/datasets/robovqa/",
37
+ }
38
+
39
+ GAL_SUBTASK_110K = {
40
+ "annotation_path": f"/mnt/workspace/users/chidafeng/datasets/Galaxea_subtask/llava_jsons/galaxea_subtask_110k.json",
41
+ "data_path": f"/mnt/workspace/users/chidafeng/datasets/Galaxea_subtask",
42
+ }
43
+
44
+ AGIBOT_SUBTASK = {
45
+ "annotation_path": "/mnt/workspace1/datasets/Agibot-Beta-Transformation/Subtask_QA/all_data.jsonl",
46
+ "data_path": "/mnt/workspace1/datasets/Agibot-Beta-Transformation/Subtask_QA/images"
47
+ }
48
+
49
+ SQ_SUBTASK = {
50
+ "annotation_path": "/mnt/workspace1/Suqian_subtask_qa/all_data.jsonl",
51
+ "data_path": "/mnt/workspace1/Suqian_subtask_qa/images"
52
+ }
53
+
54
+ ############# VLA Pretrain #############
55
+ CAMBRAIN_300K_VLAPT = {
56
+ "annotation_path": f"/mnt/workspace/users/chidafeng/jsons/Cambrian300k_withsystemprompt_vlapretrain.jsonl",
57
+ "data_path": f"{image_root}/Cambrian-10M/",
58
+ }
59
+
60
+ REFSPATIAL_2D_100K_VLAPT = {
61
+ "annotation_path": f"/mnt/workspace/users/chidafeng/jsons/refspatial/refspatial_2d_100k_vlapretrain.json",
62
+ "data_path": f"{image_root}/RefSpatial/2D/image/",
63
+ }
64
+
65
+ REFSPATIAL_3D_150K_VLAPT = {
66
+ "annotation_path": f"/mnt/workspace/users/chidafeng/jsons/refspatial/refspatial_3d_150k_vlapretrain.json",
67
+ "data_path": f"{image_root}/RefSpatial/3D/image/",
68
+ }
69
+
70
+ REFSPATIAL_3D_VISUAL_50K_VLAPT = {
71
+ "annotation_path": f"/mnt/workspace/users/chidafeng/jsons/refspatial/refspatial_3d_visual_50k_vlapretrain.json",
72
+ "data_path": f"{image_root}/RefSpatial/3D/image_visual_choice/",
73
+ }
74
+
75
+ ROBOVQA_300K_VLAPT = {
76
+ "annotation_path": f"/mnt/workspace/users/chidafeng/jsons/robovqa_300k_vlapretrain.json",
77
+ "data_path": f"/mnt/workspace/users/chidafeng/datasets/robovqa/",
78
+ }
79
+
80
+ data_dict = {
81
+ "cambrain_300k": CAMBRAIN_300K,
82
+ "refspatial_2d_100k": REFSPATIAL_2D_100K,
83
+ "refspatial_3d_150k": REFSPATIAL_3D_150K,
84
+ "refspatial_3d_visual_50k": REFSPATIAL_3D_VISUAL_50K,
85
+ "robovqa_300k": ROBOVQA_300K,
86
+ "gal_subtask_110k": GAL_SUBTASK_110K,
87
+ "cambrain_300k_vlapt": CAMBRAIN_300K_VLAPT,
88
+ "refspatial_2d_100k_vlapt": REFSPATIAL_2D_100K_VLAPT,
89
+ "refspatial_3d_150k_vlapt": REFSPATIAL_3D_150K_VLAPT,
90
+ "refspatial_3d_visual_50k_vlapt": REFSPATIAL_3D_VISUAL_50K_VLAPT,
91
+ "robovqa_300k_vlapt": ROBOVQA_300K_VLAPT,
92
+ "agibot_subtask": AGIBOT_SUBTASK,
93
+ "sq_subtask": SQ_SUBTASK,
94
+ }
95
+
96
+
97
+ def parse_sampling_rate(dataset_name):
98
+ match = re.search(r"%(\d+)$", dataset_name)
99
+ if match:
100
+ return int(match.group(1)) / 100.0
101
+ return 1.0
102
+
103
+
104
+ def data_list(dataset_names):
105
+ if dataset_names == ["all"]:
106
+ dataset_names = list(data_dict.keys())
107
+ config_list = []
108
+ for dataset_name in dataset_names:
109
+ sampling_rate = parse_sampling_rate(dataset_name)
110
+ dataset_name = re.sub(r"%(\d+)$", "", dataset_name)
111
+ if dataset_name in data_dict.keys():
112
+ config = data_dict[dataset_name].copy()
113
+ config["sampling_rate"] = sampling_rate
114
+ config_list.append(config)
115
+ else:
116
+ raise ValueError(f"do not find {dataset_name}")
117
+ return config_list
118
+
119
+
120
+ if __name__ == "__main__":
121
+ print(data_list)
starVLA/dataloader/qwenvl_llavajson/rope2d.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import copy
3
+ import json
4
+ import random
5
+ import logging
6
+ import re
7
+ import time
8
+ import math
9
+ import ast
10
+ from dataclasses import dataclass, field
11
+ from typing import Dict, Optional, Sequence, List, Tuple
12
+ from io import BytesIO
13
+ import base64
14
+
15
+ import numpy as np
16
+ import torch
17
+ from torch.utils.data import Dataset
18
+ from PIL import Image
19
+ from decord import VideoReader
20
+ import transformers
21
+
22
+
23
+ def get_rope_index_25(
24
+ spatial_merge_size: Optional[int] = 2,
25
+ input_ids: Optional[torch.LongTensor] = None,
26
+ image_grid_thw: Optional[torch.LongTensor] = None,
27
+ video_grid_thw: Optional[torch.LongTensor] = None,
28
+ second_per_grid_ts: Optional[torch.Tensor] = None,
29
+ attention_mask: Optional[torch.Tensor] = None,
30
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
31
+ """
32
+ Calculate the 3D rope index based on image and video's temporal, height and width in LLM.
33
+
34
+ Explanation:
35
+ Each embedding sequence contains vision embedding and text embedding or just contains text embedding.
36
+
37
+ For pure text embedding sequence, the rotary position embedding has no difference with modern LLMs.
38
+ Examples:
39
+ input_ids: [T T T T T], here T is for text.
40
+ temporal position_ids: [0, 1, 2, 3, 4]
41
+ height position_ids: [0, 1, 2, 3, 4]
42
+ width position_ids: [0, 1, 2, 3, 4]
43
+
44
+ For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part
45
+ and 1D rotary position embedding for text part.
46
+ Examples:
47
+ Temporal (Time): 3 patches, representing different segments of the video in time.
48
+ Height: 2 patches, dividing each frame vertically.
49
+ Width: 2 patches, dividing each frame horizontally.
50
+ We also have some important parameters:
51
+ fps (Frames Per Second): The video's frame rate, set to 1. This means one frame is processed each second.
52
+ tokens_per_second: This is a crucial parameter. It dictates how many "time-steps" or "temporal tokens" are conceptually packed into a one-second interval of the video. In this case, we have 25 tokens per second. So each second of the video will be represented with 25 separate time points. It essentially defines the temporal granularity.
53
+ temporal_patch_size: The number of frames that compose one temporal patch. Here, it's 2 frames.
54
+ interval: The step size for the temporal position IDs, calculated as tokens_per_second * temporal_patch_size / fps. In this case, 25 * 2 / 1 = 50. This means that each temporal patch will be have a difference of 50 in the temporal position IDs.
55
+ input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision.
56
+ vision temporal position_ids: [0, 0, 0, 0, 50, 50, 50, 50, 100, 100, 100, 100]
57
+ vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1]
58
+ vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
59
+ text temporal position_ids: [101, 102, 103, 104, 105]
60
+ text height position_ids: [101, 102, 103, 104, 105]
61
+ text width position_ids: [101, 102, 103, 104, 105]
62
+ Here we calculate the text start position_ids as the max vision position_ids plus 1.
63
+
64
+ Args:
65
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
66
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
67
+ it.
68
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
69
+ The temporal, height and width of feature shape of each image in LLM.
70
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
71
+ The temporal, height and width of feature shape of each video in LLM.
72
+ second_per_grid_ts (`torch.Tensor` of shape `(num_videos)`, *optional*):
73
+ The time interval (in seconds) for each grid along the temporal dimension in the 3D position IDs.
74
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
75
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
76
+
77
+ - 1 for tokens that are **not masked**,
78
+ - 0 for tokens that are **masked**.
79
+
80
+ Returns:
81
+ position_ids (`torch.LongTensor` of shape `(3, batch_size, sequence_length)`)
82
+ mrope_position_deltas (`torch.Tensor` of shape `(batch_size)`)
83
+ """
84
+ image_token_id = 151655
85
+ video_token_id = 151656
86
+ vision_start_token_id = 151652
87
+ mrope_position_deltas = []
88
+ if input_ids is not None and (image_grid_thw is not None or video_grid_thw is not None):
89
+ total_input_ids = input_ids
90
+ if attention_mask is None:
91
+ attention_mask = torch.ones_like(total_input_ids)
92
+ position_ids = torch.ones(
93
+ 3,
94
+ input_ids.shape[0],
95
+ input_ids.shape[1],
96
+ dtype=input_ids.dtype,
97
+ device=input_ids.device,
98
+ )
99
+ image_index, video_index = 0, 0
100
+ attention_mask = attention_mask.to(total_input_ids.device)
101
+ for i, input_ids in enumerate(total_input_ids):
102
+ input_ids = input_ids[attention_mask[i] == 1]
103
+ image_nums, video_nums = 0, 0
104
+ vision_start_indices = torch.argwhere(input_ids == vision_start_token_id).squeeze(1)
105
+ vision_tokens = input_ids[vision_start_indices + 1]
106
+ image_nums = (vision_tokens == image_token_id).sum()
107
+ video_nums = (vision_tokens == video_token_id).sum()
108
+ input_tokens = input_ids.tolist()
109
+ llm_pos_ids_list: list = []
110
+ st = 0
111
+ remain_images, remain_videos = image_nums, video_nums
112
+ for _ in range(image_nums + video_nums):
113
+ if image_token_id in input_tokens and remain_images > 0:
114
+ ed_image = input_tokens.index(image_token_id, st)
115
+ else:
116
+ ed_image = len(input_tokens) + 1
117
+ if video_token_id in input_tokens and remain_videos > 0:
118
+ ed_video = input_tokens.index(video_token_id, st)
119
+ else:
120
+ ed_video = len(input_tokens) + 1
121
+ if ed_image < ed_video:
122
+ t, h, w = (
123
+ image_grid_thw[image_index][0],
124
+ image_grid_thw[image_index][1],
125
+ image_grid_thw[image_index][2],
126
+ )
127
+ second_per_grid_t = 0
128
+ image_index += 1
129
+ remain_images -= 1
130
+ ed = ed_image
131
+
132
+ else:
133
+ t, h, w = (
134
+ video_grid_thw[video_index][0],
135
+ video_grid_thw[video_index][1],
136
+ video_grid_thw[video_index][2],
137
+ )
138
+ if second_per_grid_ts is not None:
139
+ second_per_grid_t = second_per_grid_ts[video_index]
140
+ else:
141
+ second_per_grid_t = 1.0
142
+ video_index += 1
143
+ remain_videos -= 1
144
+ ed = ed_video
145
+ llm_grid_t, llm_grid_h, llm_grid_w = (
146
+ t.item(),
147
+ h.item() // spatial_merge_size,
148
+ w.item() // spatial_merge_size,
149
+ )
150
+ text_len = ed - st
151
+
152
+ st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
153
+ llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)
154
+
155
+ range_tensor = torch.arange(llm_grid_t).view(-1, 1)
156
+ expanded_range = range_tensor.expand(-1, llm_grid_h * llm_grid_w)
157
+
158
+ time_tensor = expanded_range * second_per_grid_t * 2
159
+
160
+ time_tensor_long = time_tensor.long()
161
+ t_index = time_tensor_long.flatten()
162
+
163
+ h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten()
164
+ w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten()
165
+ llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + text_len + st_idx)
166
+ st = ed + llm_grid_t * llm_grid_h * llm_grid_w
167
+
168
+ if st < len(input_tokens):
169
+ st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
170
+ text_len = len(input_tokens) - st
171
+ llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)
172
+
173
+ llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1)
174
+ position_ids[..., i, attention_mask[i] == 1] = llm_positions.to(position_ids.device)
175
+ mrope_position_deltas.append(llm_positions.max() + 1 - len(total_input_ids[i]))
176
+ mrope_position_deltas = torch.tensor(mrope_position_deltas, device=input_ids.device).unsqueeze(1)
177
+ return position_ids, mrope_position_deltas
178
+ else:
179
+ if attention_mask is not None:
180
+ position_ids = attention_mask.long().cumsum(-1) - 1
181
+ position_ids.masked_fill_(attention_mask == 0, 1)
182
+ position_ids = position_ids.unsqueeze(0).expand(3, -1, -1).to(attention_mask.device)
183
+ max_position_ids = position_ids.max(0, keepdim=False)[0].max(-1, keepdim=True)[0]
184
+ mrope_position_deltas = max_position_ids + 1 - attention_mask.shape[-1]
185
+ else:
186
+ position_ids = (
187
+ torch.arange(input_ids.shape[1], device=input_ids.device)
188
+ .view(1, 1, -1)
189
+ .expand(3, input_ids.shape[0], -1)
190
+ )
191
+ mrope_position_deltas = torch.zeros(
192
+ [input_ids.shape[0], 1],
193
+ device=input_ids.device,
194
+ dtype=input_ids.dtype,
195
+ )
196
+
197
+ return position_ids, mrope_position_deltas
198
+
199
+
200
+ def get_rope_index_2(
201
+ spatial_merge_size: Optional[int] = 2,
202
+ input_ids: Optional[torch.LongTensor] = None,
203
+ image_grid_thw: Optional[torch.LongTensor] = None,
204
+ video_grid_thw: Optional[torch.LongTensor] = None,
205
+ second_per_grid_ts: Optional[torch.Tensor] = None,
206
+ attention_mask: Optional[torch.Tensor] = None,
207
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
208
+ """
209
+ Calculate the 3D rope index based on image and video's temporal, height and width in LLM.
210
+
211
+ Explanation:
212
+ Each embedding sequence contains vision embedding and text embedding or just contains text embedding.
213
+
214
+ For pure text embedding sequence, the rotary position embedding has no difference with mordern LLMs.
215
+ Examples:
216
+ input_ids: [T T T T T], here T is for text.
217
+ temporal position_ids: [0, 1, 2, 3, 4]
218
+ height position_ids: [0, 1, 2, 3, 4]
219
+ width position_ids: [0, 1, 2, 3, 4]
220
+
221
+ For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part
222
+ and 1D rotary position embeddin for text part.
223
+ Examples:
224
+ Assume we have a video input with 3 temporal patches, 2 height patches and 2 width patches.
225
+ input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision.
226
+ vision temporal position_ids: [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2]
227
+ vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1]
228
+ vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
229
+ text temporal position_ids: [3, 4, 5, 6, 7]
230
+ text height position_ids: [3, 4, 5, 6, 7]
231
+ text width position_ids: [3, 4, 5, 6, 7]
232
+ Here we calculate the text start position_ids as the max vision position_ids plus 1.
233
+
234
+ Args:
235
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
236
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
237
+ it.
238
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
239
+ The temporal, height and width of feature shape of each image in LLM.
240
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
241
+ The temporal, height and width of feature shape of each video in LLM.
242
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
243
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
244
+
245
+ - 1 for tokens that are **not masked**,
246
+ - 0 for tokens that are **masked**.
247
+
248
+ Returns:
249
+ position_ids (`torch.LongTensor` of shape `(3, batch_size, sequence_length)`)
250
+ mrope_position_deltas (`torch.Tensor` of shape `(batch_size)`)
251
+ """
252
+ image_token_id = 151655
253
+ video_token_id = 151656
254
+ vision_start_token_id = 151652
255
+ mrope_position_deltas = []
256
+ if input_ids is not None and (image_grid_thw is not None or video_grid_thw is not None):
257
+ total_input_ids = input_ids
258
+ if attention_mask is None:
259
+ attention_mask = torch.ones_like(total_input_ids)
260
+ position_ids = torch.ones(
261
+ 3,
262
+ input_ids.shape[0],
263
+ input_ids.shape[1],
264
+ dtype=input_ids.dtype,
265
+ device=input_ids.device,
266
+ )
267
+ image_index, video_index = 0, 0
268
+ for i, input_ids in enumerate(total_input_ids):
269
+ input_ids = input_ids[attention_mask[i] == 1]
270
+ image_nums, video_nums = 0, 0
271
+ vision_start_indices = torch.argwhere(input_ids == vision_start_token_id).squeeze(1)
272
+ vision_tokens = input_ids[vision_start_indices + 1]
273
+ image_nums = (vision_tokens == image_token_id).sum()
274
+ video_nums = (vision_tokens == video_token_id).sum()
275
+ input_tokens = input_ids.tolist()
276
+ llm_pos_ids_list: list = []
277
+ st = 0
278
+ remain_images, remain_videos = image_nums, video_nums
279
+ for _ in range(image_nums + video_nums):
280
+ if image_token_id in input_tokens and remain_images > 0:
281
+ ed_image = input_tokens.index(image_token_id, st)
282
+ else:
283
+ ed_image = len(input_tokens) + 1
284
+ if video_token_id in input_tokens and remain_videos > 0:
285
+ ed_video = input_tokens.index(video_token_id, st)
286
+ else:
287
+ ed_video = len(input_tokens) + 1
288
+ if ed_image < ed_video:
289
+ t, h, w = (
290
+ image_grid_thw[image_index][0],
291
+ image_grid_thw[image_index][1],
292
+ image_grid_thw[image_index][2],
293
+ )
294
+ image_index += 1
295
+ remain_images -= 1
296
+ ed = ed_image
297
+ else:
298
+ t, h, w = (
299
+ video_grid_thw[video_index][0],
300
+ video_grid_thw[video_index][1],
301
+ video_grid_thw[video_index][2],
302
+ )
303
+ video_index += 1
304
+ remain_videos -= 1
305
+ ed = ed_video
306
+ llm_grid_t, llm_grid_h, llm_grid_w = (
307
+ t.item(),
308
+ h.item() // spatial_merge_size,
309
+ w.item() // spatial_merge_size,
310
+ )
311
+ text_len = ed - st
312
+
313
+ st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
314
+ llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)
315
+
316
+ t_index = torch.arange(llm_grid_t).view(-1, 1).expand(-1, llm_grid_h * llm_grid_w).flatten()
317
+ h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten()
318
+ w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten()
319
+ llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + text_len + st_idx)
320
+ st = ed + llm_grid_t * llm_grid_h * llm_grid_w
321
+
322
+ if st < len(input_tokens):
323
+ st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
324
+ text_len = len(input_tokens) - st
325
+ llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)
326
+
327
+ llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1)
328
+ position_ids[..., i, attention_mask[i] == 1] = llm_positions.to(position_ids.device)
329
+ mrope_position_deltas.append(llm_positions.max() + 1 - len(total_input_ids[i]))
330
+ mrope_position_deltas = torch.tensor(mrope_position_deltas, device=input_ids.device).unsqueeze(1)
331
+ return position_ids, mrope_position_deltas
332
+ else:
333
+ if attention_mask is not None:
334
+ position_ids = attention_mask.long().cumsum(-1) - 1
335
+ position_ids.masked_fill_(attention_mask == 0, 1)
336
+ position_ids = position_ids.unsqueeze(0).expand(3, -1, -1).to(attention_mask.device)
337
+ max_position_ids = position_ids.max(0, keepdim=False)[0].max(-1, keepdim=True)[0]
338
+ mrope_position_deltas = max_position_ids + 1 - attention_mask.shape[-1]
339
+ else:
340
+ position_ids = (
341
+ torch.arange(input_ids.shape[1], device=input_ids.device)
342
+ .view(1, 1, -1)
343
+ .expand(3, input_ids.shape[0], -1)
344
+ )
345
+ mrope_position_deltas = torch.zeros(
346
+ [input_ids.shape[0], 1],
347
+ device=input_ids.device,
348
+ dtype=input_ids.dtype,
349
+ )
350
+
351
+ return position_ids, mrope_position_deltas
starVLA/dataloader/vlm_datasets.py ADDED
@@ -0,0 +1,946 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import copy
3
+ import json
4
+ import random
5
+ import logging
6
+ import re
7
+ import time
8
+ import math
9
+ import itertools
10
+ import ast
11
+ from dataclasses import dataclass
12
+ from typing import Dict, Optional, Sequence, List, Tuple
13
+ from io import BytesIO
14
+ import base64
15
+ from collections.abc import Sequence
16
+ from types import SimpleNamespace
17
+ import numpy as np
18
+ import torch
19
+ from torch.utils.data import Dataset
20
+ from PIL import Image
21
+ from PIL import ImageDraw
22
+ from PIL import ImageFont
23
+ from decord import VideoReader
24
+ import transformers
25
+ from omegaconf import OmegaConf
26
+ from starVLA.dataloader.qwenvl_llavajson.qwen_data_config import data_list
27
+ from starVLA.dataloader.qwenvl_llavajson.rope2d import get_rope_index_25, get_rope_index_2
28
+
29
+ IGNORE_INDEX = -100
30
+ IMAGE_TOKEN_INDEX = 151655
31
+ VIDEO_TOKEN_INDEX = 151656
32
+ DEFAULT_IMAGE_TOKEN = "<image>\n"
33
+ DEFAULT_VIDEO_TOKEN = "<video>\n"
34
+
35
+ local_rank = None
36
+
37
+
38
+ def rank0_print(*args):
39
+ if local_rank == 0:
40
+ print(*args)
41
+
42
+
43
+ def read_jsonl(path):
44
+ with open(path, "r") as f:
45
+ return [json.loads(line) for line in f]
46
+
47
+
48
+ def _extract_input_ids(encoded):
49
+ if isinstance(encoded, dict):
50
+ encoded = encoded["input_ids"]
51
+ elif hasattr(encoded, "input_ids"):
52
+ encoded = encoded.input_ids
53
+
54
+ if isinstance(encoded, torch.Tensor):
55
+ encoded = encoded.tolist()
56
+ elif hasattr(encoded, "tolist") and not isinstance(encoded, list):
57
+ encoded = encoded.tolist()
58
+
59
+ if len(encoded) > 0 and isinstance(encoded[0], list):
60
+ if len(encoded) != 1:
61
+ raise ValueError(f"Expected a single sequence from chat template, but got batch size {len(encoded)}.")
62
+ encoded = encoded[0]
63
+
64
+ return list(encoded)
65
+
66
+
67
+ def preprocess_qwen_2_visual(
68
+ sources,
69
+ tokenizer: transformers.PreTrainedTokenizer,
70
+ grid_thw: Optional[List] = None,
71
+ visual_type: str = "image",
72
+ ) -> Dict:
73
+ roles = {"human": "user", "gpt": "assistant"}
74
+ system_message = "You are a helpful assistant."
75
+ if visual_type not in ["image", "video"]:
76
+ raise ValueError("visual_type must be either 'image' or 'video'")
77
+
78
+ tokenizer = copy.deepcopy(tokenizer)
79
+ chat_template = "{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}"
80
+ tokenizer.chat_template = chat_template
81
+
82
+ visual_replicate_index = 0
83
+ input_ids, targets = [], []
84
+
85
+ for i, source in enumerate(sources):
86
+ try:
87
+ if roles[source[0]["from"]] != roles["human"]:
88
+ source = source[1:]
89
+ except:
90
+ print(sources)
91
+
92
+ input_id, target = [], []
93
+
94
+ system_ids = _extract_input_ids(
95
+ tokenizer.apply_chat_template(
96
+ [{"role": "system", "content": system_message}],
97
+ tokenize=True,
98
+ )
99
+ )
100
+ input_id += system_ids
101
+ target += [IGNORE_INDEX] * len(system_ids)
102
+
103
+ for conv in source:
104
+ try:
105
+ role = conv["role"]
106
+ content = conv["content"]
107
+ except:
108
+ role = conv["from"]
109
+ content = conv["value"]
110
+
111
+ role = roles.get(role, role)
112
+ if role == "user":
113
+ visual_tag = f"<{visual_type}>"
114
+ if visual_tag in content:
115
+ if grid_thw is None:
116
+ raise ValueError(f"Found {visual_tag} in conversation, but no {visual_type} input was provided.")
117
+ parts = content.split(visual_tag)
118
+ new_parts = []
119
+ for i in range(len(parts) - 1):
120
+ if visual_replicate_index >= len(grid_thw):
121
+ raise ValueError(
122
+ f"Found more {visual_tag} placeholders than provided {visual_type} inputs."
123
+ )
124
+ new_parts.append(parts[i])
125
+ replacement = ("<|vision_start|>" + f"<|{visual_type}_pad|>" * grid_thw[visual_replicate_index] + "<|vision_end|>")
126
+ new_parts.append(replacement)
127
+ visual_replicate_index += 1
128
+ new_parts.append(parts[-1])
129
+ content = "".join(new_parts)
130
+
131
+ conv = [{"role": role, "content": content}]
132
+ encode_id = _extract_input_ids(tokenizer.apply_chat_template(conv, tokenize=True))
133
+ input_id += encode_id
134
+ if role in ["user", "system"]:
135
+ target += [IGNORE_INDEX] * len(encode_id)
136
+ else:
137
+ target_mask = encode_id.copy()
138
+ target_mask[:3] = [IGNORE_INDEX] * 3
139
+ target += target_mask
140
+
141
+ assert len(input_id) == len(target), f"{len(input_id)} != {len(target)}"
142
+ input_ids.append(input_id)
143
+ targets.append(target)
144
+
145
+ input_ids = torch.tensor(input_ids, dtype=torch.long)
146
+ targets = torch.tensor(targets, dtype=torch.long)
147
+
148
+ return dict(
149
+ input_ids=input_ids,
150
+ labels=targets,
151
+ )
152
+
153
+
154
+ class LazySupervisedDataset(Dataset):
155
+ """Dataset for supervised fine-tuning."""
156
+
157
+ def __init__(self, tokenizer: transformers.PreTrainedTokenizer, data_args):
158
+ super(LazySupervisedDataset, self).__init__()
159
+
160
+ dataset = data_args.dataset_use.split(",")
161
+ dataset_list = data_list(dataset)
162
+ rank0_print(f"Loading datasets: {dataset_list}")
163
+ self.video_max_total_pixels = getattr(data_args, "video_max_total_pixels", 1664 * 28 * 28)
164
+ self.video_min_total_pixels = getattr(data_args, "video_min_total_pixels", 256 * 28 * 28)
165
+ self.model_type = data_args.model_type
166
+ if data_args.model_type == "qwen2.5vl":
167
+ self.get_rope_index = get_rope_index_25
168
+ else:
169
+ self.get_rope_index = get_rope_index_2
170
+
171
+ list_data_dict = []
172
+
173
+ for data in dataset_list:
174
+ file_format = data["annotation_path"].split(".")[-1]
175
+ if file_format == "jsonl":
176
+ annotations = read_jsonl(data["annotation_path"])
177
+ else:
178
+ annotations = json.load(open(data["annotation_path"], "r"))
179
+ sampling_rate = data.get("sampling_rate", 1.0)
180
+ if sampling_rate < 1.0:
181
+ annotations = random.sample(annotations, int(len(annotations) * sampling_rate))
182
+ print(f"sampling {len(annotations)} examples from dataset {data}")
183
+ else:
184
+ rank0_print(f"dataset name: {data}")
185
+ for ann in annotations:
186
+ if data["data_path"] != "":
187
+ ann["data_path"] = data["data_path"]
188
+ elif "raw_data" in ann.keys():
189
+ ann["data_path"] = ann["raw_data"]["data_root"]
190
+ list_data_dict += annotations
191
+
192
+ list_data_dict = self.pre_filter_long_case(list_data_dict, max_words=tokenizer.max_len_single_sentence)
193
+ random.shuffle(list_data_dict) # Randomly shuffle the data for training
194
+
195
+ self.tokenizer = tokenizer
196
+ self.list_data_dict = list_data_dict
197
+ self.data_args = data_args
198
+
199
+ rank0_print(f"Total training samples: {len(self.list_data_dict)}")
200
+ rank0_print("Formatting inputs...Skip in lazy mode")
201
+
202
+ # self.data_args.image_processor.max_pixels = data_args.max_pixels
203
+ # self.data_args.image_processor.min_pixels = data_args.min_pixels
204
+ # self.data_args.image_processor.size["longest_edge"] = data_args.max_pixels
205
+ # self.data_args.image_processor.size["shortest_edge"] = data_args.min_pixels
206
+
207
+ def __len__(self):
208
+ return len(self.list_data_dict)
209
+
210
+ def pre_filter_long_case(self, list_data_dict, max_words=1024):
211
+ """filter out conversations with total words exceeding max_words"""
212
+
213
+ def count_total_words(convs):
214
+ total = 0
215
+ for entry in convs:
216
+ value = entry.get("value", "")
217
+ total += len(value.strip().split())
218
+ return total
219
+
220
+ return [item for item in list_data_dict if count_total_words(item.get("conversations", [])) <= max_words]
221
+
222
+ @property
223
+ def lengths(self):
224
+ length_list = []
225
+ for sample in self.list_data_dict:
226
+ img_tokens = 128 if "image" in sample else 0
227
+ length_list.append(sum(len(conv["value"].split()) for conv in sample["conversations"]) + img_tokens)
228
+ return length_list
229
+
230
+ @property
231
+ def modality_lengths(self):
232
+ length_list = []
233
+ for sample in self.list_data_dict:
234
+ cur_len = sum(len(conv["value"].split()) for conv in sample["conversations"])
235
+ cur_len = cur_len if ("image" in sample) or ("video" in sample) else -cur_len
236
+ length_list.append(cur_len)
237
+ return length_list
238
+
239
+ @property
240
+ def pre_calculated_length(self):
241
+ if "num_tokens" in self.list_data_dict[0]:
242
+ length_list = [sample["num_tokens"] for sample in self.list_data_dict]
243
+ return np.array(length_list)
244
+ else:
245
+ print("No pre-calculated length available.")
246
+ return np.array([1] * len(self.list_data_dict))
247
+
248
+ def process_image_unified(self, image_file):
249
+ processor = copy.deepcopy(self.data_args.image_processor)
250
+ image = Image.open(image_file).convert("RGB")
251
+ # if fix image size?
252
+ if getattr(self.data_args, "fix_image_size", None) is not None:
253
+ image = image.resize(
254
+ self.data_args.fix_image_size,
255
+ resample=Image.BICUBIC,
256
+ )
257
+ visual_processed = processor.preprocess(image, return_tensors="pt")
258
+ image_tensor = visual_processed["pixel_values"]
259
+ if isinstance(image_tensor, List):
260
+ image_tensor = image_tensor[0]
261
+ grid_thw = visual_processed["image_grid_thw"][0]
262
+ return image_tensor, grid_thw
263
+
264
+ def process_video(self, video_file):
265
+ if not os.path.exists(video_file):
266
+ print(f"File not exist: {video_file}")
267
+ vr = VideoReader(video_file, num_threads=4)
268
+ total_frames = len(vr)
269
+ avg_fps = vr.get_avg_fps()
270
+ video_length = total_frames / avg_fps
271
+ interval = getattr(self.data_args, "base_interval", 4)
272
+
273
+ num_frames_to_sample = round(video_length / interval)
274
+ video_min_frames = getattr(self.data_args, "video_min_frames", 4)
275
+ video_max_frames = getattr(self.data_args, "video_max_frames", 8)
276
+
277
+ target_frames = min(max(num_frames_to_sample, video_min_frames), video_max_frames)
278
+ frame_idx = np.linspace(0, total_frames - 1, target_frames, dtype=int)
279
+ frame_idx = np.unique(frame_idx)
280
+ video = vr.get_batch(frame_idx).asnumpy()
281
+ fps = len(frame_idx) / video_length
282
+ processor = copy.deepcopy(self.data_args.image_processor)
283
+ self.data_args.video_max_frame_pixels = self.video_max_total_pixels
284
+ self.data_args.video_min_frame_pixels = self.video_min_total_pixels
285
+ processor.max_pixels = self.data_args.video_max_frame_pixels
286
+ processor.min_pixels = self.data_args.video_min_frame_pixels
287
+ processor.size["longest_edge"] = processor.max_pixels
288
+ processor.size["shortest_edge"] = processor.min_pixels
289
+ processor_valid_kwargs = getattr(processor, "valid_kwargs", None)
290
+ processor_valid_keys = None
291
+ if processor_valid_kwargs is not None:
292
+ if isinstance(processor_valid_kwargs, dict):
293
+ processor_valid_keys = set(processor_valid_kwargs.keys())
294
+ elif hasattr(processor_valid_kwargs, "__annotations__"):
295
+ processor_valid_keys = set(processor_valid_kwargs.__annotations__.keys())
296
+ else:
297
+ try:
298
+ processor_valid_keys = set(processor_valid_kwargs)
299
+ except TypeError:
300
+ processor_valid_keys = None
301
+
302
+ supports_video_kwarg = processor_valid_keys is None or "video" in processor_valid_keys
303
+ supports_videos_kwarg = processor_valid_keys is None or "videos" in processor_valid_keys
304
+
305
+ if supports_videos_kwarg:
306
+ video_processed = processor.preprocess(images=None, videos=video, return_tensors="pt")
307
+ video_tensor = video_processed["pixel_values_videos"]
308
+ grid_thw = video_processed["video_grid_thw"][0]
309
+ elif supports_video_kwarg:
310
+ video_processed = processor.preprocess(images=None, video=video, return_tensors="pt")
311
+ video_tensor = video_processed["pixel_values_videos"]
312
+ grid_thw = video_processed["video_grid_thw"][0]
313
+ else:
314
+ video_processed = processor.preprocess(list(video), return_tensors="pt")
315
+ video_tensor = video_processed["pixel_values"]
316
+ image_grid_thw = video_processed["image_grid_thw"]
317
+ if len(image_grid_thw) == 1:
318
+ grid_thw = image_grid_thw[0]
319
+ else:
320
+ grid_thw = image_grid_thw[0].clone()
321
+ grid_thw[0] = image_grid_thw[:, 0].sum()
322
+ second_per_grid_ts = [self.data_args.image_processor.temporal_patch_size / fps]
323
+ return video_tensor, grid_thw, second_per_grid_ts
324
+
325
+ def __getitem__(self, i) -> Dict[str, torch.Tensor]:
326
+ num_base_retries = 3
327
+ num_final_retries = 30
328
+
329
+ # try the current sample first
330
+ for attempt_idx in range(num_base_retries):
331
+ try:
332
+ sample = self._get_item(i)
333
+ sample["_debug_dataset_index"] = i
334
+ return sample
335
+ except Exception as e:
336
+ # sleep 1s in case it is a cloud disk issue
337
+ print(f"[Try #{attempt_idx}] Failed to fetch sample {i}. Exception:", e)
338
+ time.sleep(1)
339
+
340
+ # try other samples, in case it is file corruption issue
341
+ for attempt_idx in range(num_base_retries):
342
+ try:
343
+ next_index = min(i + 1, len(self.list_data_dict) - 1)
344
+ # sample_idx = random.choice(range(len(self)))
345
+ sample = self._get_item(next_index)
346
+ sample["_debug_dataset_index"] = next_index
347
+ return sample
348
+ except Exception as e:
349
+ # no need to sleep
350
+ print(
351
+ f"[Try other #{attempt_idx}] Failed to fetch sample {next_index}. Exception:",
352
+ e,
353
+ )
354
+ pass
355
+
356
+ try:
357
+ sample = self._get_item(i)
358
+ sample["_debug_dataset_index"] = i
359
+ return sample
360
+ except Exception as e:
361
+ raise e
362
+
363
+ def _get_item(self, i) -> Dict[str, torch.Tensor]:
364
+ sources = self.list_data_dict[i]
365
+ if isinstance(i, int):
366
+ sources = [sources]
367
+ assert len(sources) == 1, "Don't know why it is wrapped to a list" # FIXME
368
+ video = None
369
+ if "image" in sources[0] and len(sources[0]["image"]):
370
+ image_folder = self.list_data_dict[i]["data_path"]
371
+ image_file = self.list_data_dict[i]["image"]
372
+ if isinstance(image_file, List):
373
+ if len(image_file) > 1:
374
+ image_file = [os.path.join(image_folder, file) for file in image_file]
375
+ results = [self.process_image_unified(file) for file in image_file]
376
+ image, grid_thw = zip(*results)
377
+ else:
378
+ image_file = image_file[0]
379
+ image_file = os.path.join(image_folder, image_file)
380
+ image, grid_thw = self.process_image_unified(image_file)
381
+ image = [image]
382
+ else:
383
+ image_file = os.path.join(image_folder, image_file)
384
+ image, grid_thw = self.process_image_unified(image_file)
385
+ image = [image]
386
+ grid_thw_merged = copy.deepcopy(grid_thw)
387
+ if not isinstance(grid_thw, Sequence):
388
+ grid_thw_merged = [grid_thw_merged]
389
+ grid_thw = [grid_thw]
390
+ grid_thw_merged = [merged_thw.prod() // self.data_args.image_processor.merge_size**2 for merged_thw in grid_thw_merged]
391
+ sources = copy.deepcopy([e["conversations"] for e in sources])
392
+ data_dict = preprocess_qwen_2_visual(sources, self.tokenizer, grid_thw=grid_thw_merged, visual_type="image")
393
+ position_ids, _ = self.get_rope_index(
394
+ self.data_args.image_processor.merge_size,
395
+ data_dict["input_ids"],
396
+ torch.stack(grid_thw, dim=0), # (1,16,16)
397
+ )
398
+ elif "video" in sources[0] and len(sources[0]["video"]):
399
+ video_file = self.list_data_dict[i]["video"]
400
+ video_folder = self.list_data_dict[i]["data_path"]
401
+ if isinstance(video_file, List):
402
+ if len(video_file) > 1:
403
+ video_file = [os.path.join(video_folder, file) for file in video_file]
404
+ results = [self.process_video(file) for file in video_file]
405
+ video, grid_thw, second_per_grid_ts = zip(*results)
406
+ second_per_grid_ts = list(itertools.chain.from_iterable(second_per_grid_ts))
407
+ else:
408
+ video_file = video_file[0]
409
+ video_file = os.path.join(video_folder, video_file)
410
+ video, grid_thw, second_per_grid_ts = self.process_video(video_file)
411
+ video = [video]
412
+ else:
413
+ video_file = os.path.join(video_folder, video_file)
414
+ video, grid_thw, second_per_grid_ts = self.process_video(video_file)
415
+ video = [video]
416
+ grid_thw_merged = copy.deepcopy(grid_thw)
417
+ if not isinstance(grid_thw, Sequence):
418
+ grid_thw_merged = [grid_thw_merged]
419
+ grid_thw = [grid_thw]
420
+ grid_thw_merged = [merged_thw.prod() // self.data_args.image_processor.merge_size**2 for merged_thw in grid_thw_merged]
421
+ sources = copy.deepcopy([e["conversations"] for e in sources])
422
+ data_dict = preprocess_qwen_2_visual(sources, self.tokenizer, grid_thw=grid_thw_merged, visual_type="video")
423
+ position_ids, _ = self.get_rope_index(
424
+ self.data_args.image_processor.merge_size,
425
+ data_dict["input_ids"],
426
+ video_grid_thw=torch.stack(grid_thw, dim=0),
427
+ second_per_grid_ts=second_per_grid_ts,
428
+ )
429
+ else:
430
+ grid_thw_merged = None
431
+ sources = copy.deepcopy([e["conversations"] for e in sources])
432
+ data_dict = preprocess_qwen_2_visual(sources, self.tokenizer, grid_thw=grid_thw_merged)
433
+ position_ids = torch.arange(0, data_dict["input_ids"].size(1)).view(1, -1).unsqueeze(0).expand(3, -1, -1)
434
+
435
+ if isinstance(i, int):
436
+ data_dict = dict(
437
+ input_ids=data_dict["input_ids"][0],
438
+ labels=data_dict["labels"][0],
439
+ position_ids=position_ids,
440
+ )
441
+ if "image" in self.list_data_dict[i]:
442
+ data_dict["pixel_values"] = image
443
+ data_dict["image_grid_thw"] = grid_thw
444
+ # video exist in the data
445
+ elif "video" in self.list_data_dict[i]:
446
+ data_dict["pixel_values_videos"] = video
447
+ data_dict["video_grid_thw"] = grid_thw
448
+
449
+ max_len = self.tokenizer.max_len_single_sentence
450
+ if data_dict["input_ids"].shape[0] > max_len:
451
+ truncated_input_ids = data_dict["input_ids"][:max_len]
452
+ image_tokens_before = int((data_dict["input_ids"] == IMAGE_TOKEN_INDEX).sum().item())
453
+ image_tokens_after = int((truncated_input_ids == IMAGE_TOKEN_INDEX).sum().item())
454
+ video_tokens_before = int((data_dict["input_ids"] == VIDEO_TOKEN_INDEX).sum().item())
455
+ video_tokens_after = int((truncated_input_ids == VIDEO_TOKEN_INDEX).sum().item())
456
+
457
+ if image_tokens_before != image_tokens_after or video_tokens_before != video_tokens_after:
458
+ raw_sample = self.list_data_dict[i]
459
+ debug_message = _format_raw_sample_debug(raw_sample)
460
+ raise ValueError(
461
+ "Sequence truncation would drop visual placeholder tokens: "
462
+ f"image {image_tokens_before}->{image_tokens_after}, "
463
+ f"video {video_tokens_before}->{video_tokens_after}, "
464
+ f"max_len={max_len}.\n"
465
+ "Raw sample debug:\n"
466
+ f"{debug_message}"
467
+ )
468
+
469
+ data_dict["input_ids"] = data_dict["input_ids"][:max_len]
470
+ data_dict["labels"] = data_dict["labels"][:max_len]
471
+ data_dict["position_ids"] = position_ids[:, :, :max_len]
472
+
473
+ return data_dict
474
+
475
+
476
+ def pad_and_cat(tensor_list):
477
+ max_length = max(tensor.shape[2] for tensor in tensor_list)
478
+
479
+ padded_tensors = []
480
+ for tensor in tensor_list:
481
+ pad_length = max_length - tensor.shape[2]
482
+ padded_tensor = torch.nn.functional.pad(tensor, (0, pad_length), "constant", 1)
483
+ padded_tensors.append(padded_tensor)
484
+
485
+ stacked_tensor = torch.cat(padded_tensors, dim=1)
486
+
487
+ return stacked_tensor
488
+
489
+
490
+ @dataclass
491
+ class DataCollatorForSupervisedDataset(object):
492
+ """Collate examples for supervised fine-tuning."""
493
+
494
+ tokenizer: transformers.PreTrainedTokenizer
495
+
496
+ def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]:
497
+ input_ids, labels, position_ids = tuple(
498
+ [instance[key] for instance in instances] for key in ("input_ids", "labels", "position_ids"))
499
+ input_ids = torch.nn.utils.rnn.pad_sequence(
500
+ input_ids,
501
+ batch_first=True,
502
+ padding_value=self.tokenizer.pad_token_id,
503
+ padding_side=self.tokenizer.padding_side,
504
+ )
505
+ labels = torch.nn.utils.rnn.pad_sequence(labels,
506
+ batch_first=True,
507
+ padding_value=IGNORE_INDEX,
508
+ padding_side=self.tokenizer.padding_side)
509
+ position_ids = pad_and_cat(position_ids)
510
+
511
+ input_ids = input_ids[:, :self.tokenizer.model_max_length]
512
+ labels = labels[:, :self.tokenizer.model_max_length]
513
+ position_ids = position_ids[..., :self.tokenizer.model_max_length] # 3,bs,length
514
+
515
+ batch = dict(
516
+ input_ids=input_ids,
517
+ labels=labels,
518
+ attention_mask=input_ids.ne(self.tokenizer.pad_token_id),
519
+ )
520
+ images = list(itertools.chain(*(instance["pixel_values"] for instance in instances if "pixel_values" in instance)))
521
+ videos = list(itertools.chain(*(instance["pixel_values_videos"] for instance in instances if "pixel_values_videos" in instance)))
522
+ if len(images) != 0:
523
+ concat_images = torch.cat([image for image in images], dim=0)
524
+ grid_thw = list(itertools.chain(*(instance["image_grid_thw"] for instance in instances if "image_grid_thw" in instance)))
525
+ grid_thw = torch.stack(grid_thw, dim=0)
526
+ else:
527
+ concat_images = None
528
+ grid_thw = None
529
+
530
+ if len(videos) != 0:
531
+ concat_videos = torch.cat([video for video in videos], dim=0)
532
+ video_grid_thw = list(itertools.chain(*(instance["video_grid_thw"] for instance in instances if "video_grid_thw" in instance)))
533
+ video_grid_thw = torch.stack(video_grid_thw, dim=0)
534
+ else:
535
+ concat_videos = None
536
+ video_grid_thw = None
537
+
538
+ batch["pixel_values"] = concat_images
539
+ batch["image_grid_thw"] = grid_thw
540
+ batch["pixel_values_videos"] = concat_videos
541
+ batch["video_grid_thw"] = video_grid_thw
542
+ batch["position_ids"] = position_ids
543
+ batch["_debug_dataset_index"] = [instance.get("_debug_dataset_index") for instance in instances]
544
+ return batch
545
+
546
+
547
+ @dataclass
548
+ class FlattenedDataCollatorForSupervisedDataset(DataCollatorForSupervisedDataset):
549
+ """Collate examples into packed sequence with multi-modal support."""
550
+
551
+ tokenizer: transformers.PreTrainedTokenizer
552
+
553
+ def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]:
554
+ input_ids, labels, position_ids = tuple(
555
+ [instance[key] for instance in instances] for key in ("input_ids", "labels", "position_ids"))
556
+
557
+ seq_lens = torch.tensor([0] + [len(seq) for seq in input_ids], dtype=torch.int32)
558
+ cumsum_seq_lens = torch.cumsum(seq_lens, dim=0, dtype=torch.int32)
559
+ input_ids = torch.cat(input_ids, dim=0)
560
+ labels = torch.cat(labels, dim=0)
561
+ position_ids = torch.cat(position_ids, dim=2)
562
+
563
+ batch = dict(
564
+ input_ids=input_ids.unsqueeze(0),
565
+ labels=labels.unsqueeze(0),
566
+ attention_mask=cumsum_seq_lens,
567
+ position_ids=position_ids,
568
+ )
569
+ images = list(itertools.chain(*(instance["pixel_values"] for instance in instances if "pixel_values" in instance)))
570
+ videos = list(itertools.chain(*(instance["pixel_values_videos"] for instance in instances if "pixel_values_videos" in instance)))
571
+ if len(images) != 0:
572
+ concat_images = torch.cat([image for image in images], dim=0)
573
+ grid_thw = list(itertools.chain(*(instance["image_grid_thw"] for instance in instances if "image_grid_thw" in instance)))
574
+ grid_thw = torch.stack(grid_thw, dim=0)
575
+ else:
576
+ concat_images = None
577
+ grid_thw = None
578
+
579
+ if len(videos) != 0:
580
+ concat_videos = torch.cat([video for video in videos], dim=0)
581
+ video_grid_thw = list(itertools.chain(*(instance["video_grid_thw"] for instance in instances if "video_grid_thw" in instance)))
582
+ video_grid_thw = torch.stack(video_grid_thw, dim=0)
583
+ else:
584
+ concat_videos = None
585
+ video_grid_thw = None
586
+
587
+ batch["pixel_values"] = concat_images
588
+ batch["image_grid_thw"] = grid_thw
589
+ batch["pixel_values_videos"] = concat_videos
590
+ batch["video_grid_thw"] = video_grid_thw
591
+ batch["_debug_dataset_index"] = [instance.get("_debug_dataset_index") for instance in instances]
592
+
593
+ return batch
594
+
595
+
596
+ def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer, data_args) -> Dict:
597
+ """Make dataset and collator for supervised fine-tuning."""
598
+ # load training dataset
599
+ train_dataset = LazySupervisedDataset(tokenizer=tokenizer, data_args=data_args)
600
+
601
+ # load evaluation dataset (if specified eval dataset path)
602
+ eval_dataset = None
603
+ if hasattr(data_args, "eval_dataset") and data_args.eval_dataset:
604
+ eval_data_args = copy.deepcopy(data_args)
605
+ eval_data_args.dataset_use = data_args.eval_dataset
606
+ eval_dataset = LazySupervisedDataset(tokenizer=tokenizer, data_args=eval_data_args)
607
+
608
+ # select appropriate collator based on whether data needs to be flattened
609
+ if data_args.data_flatten:
610
+ data_collator = FlattenedDataCollatorForSupervisedDataset(tokenizer=tokenizer)
611
+ else:
612
+ data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer)
613
+
614
+ return dict(
615
+ train_dataset=train_dataset,
616
+ eval_dataset=eval_dataset,
617
+ data_collator=data_collator,
618
+ )
619
+
620
+
621
+ def make_vlm_dataloader(cfg):
622
+ data_args = cfg.datasets.vlm_data
623
+ image_processor = AutoProcessor.from_pretrained(cfg.framework.qwenvl.base_vlm,).image_processor
624
+
625
+ tokenizer = transformers.AutoTokenizer.from_pretrained(
626
+ cfg.framework.qwenvl.base_vlm,
627
+ model_max_length=data_args.model_max_length,
628
+ padding_side=
629
+ "left", # flash Attention version of Qwen2.5_VL. Make sure to call `tokenizer.padding_side = 'left'` before tokenizing the input.
630
+ use_fast=False,
631
+ )
632
+
633
+ # avoid processing these in dataset
634
+ image_processor.max_pixels = int(data_args.max_pixels)
635
+ image_processor.min_pixels = int(data_args.min_pixels)
636
+ image_processor.size["longest_edge"] = int(data_args.max_pixels)
637
+ image_processor.size["shortest_edge"] = int(data_args.min_pixels)
638
+ data_args_ns = SimpleNamespace(**OmegaConf.to_container(data_args, resolve=True))
639
+ data_args_ns.image_processor = image_processor # TODO later remove the logic bound to model
640
+ data_module = make_supervised_data_module(tokenizer=tokenizer, data_args=data_args_ns)
641
+
642
+ #
643
+ train_dataset = data_module["train_dataset"]
644
+ data_collator = data_module["data_collator"]
645
+ from torch.utils.data import DataLoader
646
+
647
+ train_dataloader = DataLoader(
648
+ train_dataset,
649
+ batch_size=cfg.datasets.vlm_data.per_device_batch_size,
650
+ collate_fn=data_collator,
651
+ num_workers=4,
652
+ )
653
+
654
+ eval_dataloader = None
655
+ eval_dataset = data_module["eval_dataset"]
656
+ if eval_dataset is not None:
657
+ eval_dataloader = DataLoader(
658
+ eval_dataset,
659
+ batch_size=cfg.datasets.vlm_data.per_device_batch_size,
660
+ collate_fn=data_collator,
661
+ num_workers=4,
662
+ )
663
+
664
+ return {
665
+ "train_dataloader": train_dataloader,
666
+ "eval_dataloader": eval_dataloader,
667
+ }
668
+
669
+
670
+ from transformers import AutoTokenizer, AutoProcessor
671
+
672
+
673
+ def _safe_shape(x):
674
+ if x is None:
675
+ return None
676
+ if hasattr(x, "shape"):
677
+ return tuple(x.shape)
678
+ if isinstance(x, (list, tuple)):
679
+ return f"len={len(x)}"
680
+ return type(x).__name__
681
+
682
+
683
+ def _print_sample_debug(dataset, sample_index):
684
+ raw_sample = dataset.list_data_dict[sample_index]
685
+ print(f"=== Raw sample[{sample_index}] ===")
686
+ print(f"keys: {sorted(raw_sample.keys())}")
687
+ if "conversations" in raw_sample:
688
+ print(f"num_conversations: {len(raw_sample['conversations'])}")
689
+ for idx, conv in enumerate(raw_sample["conversations"][:4]):
690
+ role = conv.get("role", conv.get("from"))
691
+ text = conv.get("content", conv.get("value", ""))
692
+ text = text.replace("\n", "\\n")
693
+ print(f"conv[{idx}] role={role} text[:160]={text[:160]}")
694
+ image_files = raw_sample.get("image", raw_sample.get("images"))
695
+ video_files = raw_sample.get("video", raw_sample.get("videos"))
696
+ print(f"image field: {image_files}")
697
+ print(f"video field: {video_files}")
698
+ print(f"data_path: {raw_sample.get('data_path')}")
699
+ print()
700
+
701
+ try:
702
+ sample = dataset[sample_index]
703
+ except Exception as e:
704
+ print(f"=== dataset[{sample_index}] failed ===")
705
+ print(repr(e))
706
+ return
707
+
708
+ print(f"=== Processed sample[{sample_index}] ===")
709
+ for key, value in sample.items():
710
+ if isinstance(value, torch.Tensor):
711
+ print(f"{key}: shape={tuple(value.shape)} dtype={value.dtype}")
712
+ elif isinstance(value, list):
713
+ child_shapes = [_safe_shape(v) for v in value[:4]]
714
+ print(f"{key}: list_len={len(value)} first_items={child_shapes}")
715
+ else:
716
+ print(f"{key}: {value}")
717
+
718
+ input_ids = sample["input_ids"]
719
+ print(f"num_image_tokens: {int((input_ids == IMAGE_TOKEN_INDEX).sum().item())}")
720
+ print(f"num_video_tokens: {int((input_ids == VIDEO_TOKEN_INDEX).sum().item())}")
721
+ if "video_grid_thw" in sample:
722
+ print(f"video_grid_thw: {sample['video_grid_thw']}")
723
+ if "image_grid_thw" in sample:
724
+ print(f"image_grid_thw: {sample['image_grid_thw']}")
725
+
726
+
727
+ def _format_raw_sample_debug(raw_sample):
728
+ lines = []
729
+ lines.append(f"keys: {sorted(raw_sample.keys())}")
730
+ if "id" in raw_sample:
731
+ lines.append(f"id: {raw_sample['id']}")
732
+ lines.append(f"data_path: {raw_sample.get('data_path')}")
733
+ lines.append(f"image field: {raw_sample.get('image', raw_sample.get('images'))}")
734
+ lines.append(f"video field: {raw_sample.get('video', raw_sample.get('videos'))}")
735
+ conversations = raw_sample.get("conversations", [])
736
+ lines.append(f"num_conversations: {len(conversations)}")
737
+ for idx, conv in enumerate(conversations[:4]):
738
+ role = conv.get("role", conv.get("from"))
739
+ text = conv.get("content", conv.get("value", ""))
740
+ text = text.replace("\n", "\\n")
741
+ lines.append(f"conv[{idx}] role={role} text[:160]={text[:160]}")
742
+ return "\n".join(lines)
743
+
744
+
745
+ def _print_batch_debug(batch, batch_index):
746
+ print(f"=== Batch[{batch_index}] ===")
747
+ for key, value in batch.items():
748
+ if isinstance(value, torch.Tensor):
749
+ print(f"{key}: shape={tuple(value.shape)} dtype={value.dtype}")
750
+ else:
751
+ print(f"{key}: {_safe_shape(value)}")
752
+ input_ids = batch["input_ids"]
753
+ print(f"batch_image_tokens: {int((input_ids == IMAGE_TOKEN_INDEX).sum().item())}")
754
+ print(f"batch_video_tokens: {int((input_ids == VIDEO_TOKEN_INDEX).sum().item())}")
755
+ print()
756
+
757
+
758
+ def _print_batch_qa_debug(dataset, batch, batch_index, batch_size):
759
+ sample_indices = batch.get("_debug_dataset_index")
760
+ if sample_indices is None:
761
+ start = batch_index * batch_size
762
+ end = min(start + batch_size, len(dataset.list_data_dict))
763
+ sample_indices = list(range(start, end))
764
+ print(f"=== Batch[{batch_index}] QA ===")
765
+ for sample_index in sample_indices:
766
+ if sample_index is None:
767
+ continue
768
+ raw_sample = dataset.list_data_dict[sample_index]
769
+ sample_id = raw_sample.get("id", "<no-id>")
770
+ print(f"-- sample[{sample_index}] id={sample_id}")
771
+ conversations = raw_sample.get("conversations", [])
772
+ for conv_idx, conv in enumerate(conversations):
773
+ role = conv.get("role", conv.get("from"))
774
+ text = conv.get("content", conv.get("value", ""))
775
+ text = text.replace("\n", "\\n")
776
+ print(f" [{conv_idx}] {role}: {text[:300]}")
777
+ print()
778
+
779
+
780
+ def _sanitize_filename(name):
781
+ return re.sub(r"[^A-Za-z0-9._-]+", "_", str(name))
782
+
783
+
784
+ def _wrap_text_for_width(draw, text, font, max_width):
785
+ words = text.split()
786
+ if not words:
787
+ return [""]
788
+ lines = []
789
+ current = words[0]
790
+ for word in words[1:]:
791
+ candidate = f"{current} {word}"
792
+ if draw.textbbox((0, 0), candidate, font=font)[2] <= max_width:
793
+ current = candidate
794
+ else:
795
+ lines.append(current)
796
+ current = word
797
+ lines.append(current)
798
+ return lines
799
+
800
+
801
+ def _save_annotated_debug_image(image, conversations, save_path):
802
+ font = ImageFont.load_default()
803
+ image = image.convert("RGB")
804
+ panel_width = image.width
805
+ padding = 12
806
+ line_gap = 6
807
+
808
+ dummy = Image.new("RGB", (panel_width, 10), "white")
809
+ draw = ImageDraw.Draw(dummy)
810
+
811
+ wrapped_lines = []
812
+ for conv_idx, conv in enumerate(conversations):
813
+ role = conv.get("role", conv.get("from", "unknown"))
814
+ text = conv.get("content", conv.get("value", ""))
815
+ text = text.replace("\n", " ")
816
+ prefix = f"[{conv_idx}] {role}: "
817
+ body_lines = _wrap_text_for_width(draw, text, font, panel_width - padding * 2)
818
+ if body_lines:
819
+ wrapped_lines.append(prefix + body_lines[0])
820
+ wrapped_lines.extend(body_lines[1:])
821
+ else:
822
+ wrapped_lines.append(prefix)
823
+ wrapped_lines.append("")
824
+
825
+ line_height = draw.textbbox((0, 0), "Ag", font=font)[3] + line_gap
826
+ text_height = padding * 2 + max(1, len(wrapped_lines)) * line_height
827
+ canvas = Image.new("RGB", (panel_width, image.height + text_height), "white")
828
+ canvas.paste(image, (0, 0))
829
+
830
+ draw = ImageDraw.Draw(canvas)
831
+ y = image.height + padding
832
+ for line in wrapped_lines:
833
+ draw.text((padding, y), line, fill="black", font=font)
834
+ y += line_height
835
+
836
+ canvas.save(save_path)
837
+
838
+
839
+ def _save_debug_media(dataset, batch, batch_index, batch_size, output_dir):
840
+ os.makedirs(output_dir, exist_ok=True)
841
+ sample_indices = batch.get("_debug_dataset_index")
842
+ if sample_indices is None:
843
+ start = batch_index * batch_size
844
+ end = min(start + batch_size, len(dataset.list_data_dict))
845
+ sample_indices = list(range(start, end))
846
+ print(f"=== Batch[{batch_index}] media saved to {output_dir} ===")
847
+
848
+ for sample_index in sample_indices:
849
+ if sample_index is None:
850
+ continue
851
+ raw_sample = dataset.list_data_dict[sample_index]
852
+ sample_id = _sanitize_filename(raw_sample.get("id", f"sample_{sample_index}"))
853
+ data_path = raw_sample.get("data_path", "")
854
+ conversations = raw_sample.get("conversations", [])
855
+
856
+ image_files = raw_sample.get("image", raw_sample.get("images"))
857
+ if image_files is not None:
858
+ if not isinstance(image_files, (list, tuple)):
859
+ image_files = [image_files]
860
+ for media_idx, image_file in enumerate(image_files):
861
+ image_path = os.path.join(data_path, image_file)
862
+ try:
863
+ image = Image.open(image_path).convert("RGB")
864
+ annotated_path = os.path.join(output_dir, f"batch{batch_index}_sample{sample_index}_{sample_id}_image{media_idx}_qa.jpg")
865
+ _save_annotated_debug_image(image, conversations, annotated_path)
866
+ print(f"saved image+qa: {annotated_path}")
867
+ except Exception as e:
868
+ print(f"failed to save image {image_path}: {e}")
869
+
870
+ video_files = raw_sample.get("video", raw_sample.get("videos"))
871
+ if video_files is not None:
872
+ if not isinstance(video_files, (list, tuple)):
873
+ video_files = [video_files]
874
+ for media_idx, video_file in enumerate(video_files):
875
+ video_path = os.path.join(data_path, video_file)
876
+ try:
877
+ vr = VideoReader(video_path, num_threads=1)
878
+ frame = vr[0].asnumpy()
879
+ image = Image.fromarray(frame).convert("RGB")
880
+ annotated_path = os.path.join(output_dir, f"batch{batch_index}_sample{sample_index}_{sample_id}_video{media_idx}_frame0_qa.jpg")
881
+ _save_annotated_debug_image(image, conversations, annotated_path)
882
+ print(f"saved video preview+qa: {annotated_path}")
883
+ except Exception as e:
884
+ print(f"failed to save video preview {video_path}: {e}")
885
+
886
+ if __name__ == "__main__":
887
+ # import debugpy
888
+ import argparse
889
+ parser = argparse.ArgumentParser()
890
+ parser.add_argument("--config_yaml",
891
+ type=str,
892
+ default="./examples/Suqian_agibot/train_files/starvla_cotrain_robocasa_gr1.yaml",
893
+ help="Path to YAML config")
894
+ parser.add_argument("--sample_index", type=int, default=None, help="Inspect a single dataset sample by index")
895
+ parser.add_argument("--max_batches", type=int, default=100, help="Number of batches to iterate for debugging")
896
+ parser.add_argument("--save_debug_media_dir", type=str, default=None, help="Optional directory to save raw images and video previews for each debug batch")
897
+ args, clipargs = parser.parse_known_args()
898
+
899
+ # debugpy.listen(("0.0.0.0", 10092))
900
+ # print("🔍 Rank 0 waiting for debugger attach on port 10092...")
901
+ # debugpy.wait_for_client()
902
+
903
+ cfg = OmegaConf.load(args.config_yaml)
904
+
905
+ data_args = cfg.datasets.vlm_data
906
+ image_processor = AutoProcessor.from_pretrained(cfg.framework.qwenvl.base_vlm,).image_processor
907
+
908
+ tokenizer = transformers.AutoTokenizer.from_pretrained(
909
+ cfg.framework.qwenvl.base_vlm,
910
+ model_max_length=data_args.model_max_length,
911
+ padding_side="left",
912
+ use_fast=False,
913
+ )
914
+
915
+ # avoid processing these in dataset
916
+ image_processor.max_pixels = data_args.max_pixels
917
+ image_processor.min_pixels = data_args.min_pixels
918
+ image_processor.size["longest_edge"] = data_args.max_pixels
919
+ image_processor.size["shortest_edge"] = data_args.min_pixels
920
+
921
+ data_args_ns = SimpleNamespace(**OmegaConf.to_container(data_args, resolve=True))
922
+ data_args_ns.image_processor = image_processor
923
+ data_module = make_supervised_data_module(tokenizer=tokenizer, data_args=data_args_ns)
924
+
925
+ #
926
+ train_dataset = data_module["train_dataset"]
927
+ data_collator = data_module["data_collator"]
928
+ from torch.utils.data import DataLoader
929
+
930
+ train_dataloader = DataLoader(
931
+ train_dataset,
932
+ batch_size=cfg.datasets.vlm_data.per_device_batch_size,
933
+ collate_fn=data_collator,
934
+ )
935
+ if args.sample_index is not None:
936
+ _print_sample_debug(train_dataset, args.sample_index)
937
+ else:
938
+ batchs = iter(train_dataloader)
939
+ count = 0
940
+ while count < args.max_batches:
941
+ batch_samples = next(batchs)
942
+ _print_batch_debug(batch_samples, count)
943
+ _print_batch_qa_debug(train_dataset, batch_samples, count, cfg.datasets.vlm_data.per_device_batch_size)
944
+ if args.save_debug_media_dir is not None:
945
+ _save_debug_media(train_dataset, batch_samples, count, cfg.datasets.vlm_data.per_device_batch_size, args.save_debug_media_dir)
946
+ count += 1