diff --git a/script/add_annotation.py b/script/add_annotation.py new file mode 100644 index 0000000000000000000000000000000000000000..d8cd6444ca6a9d64435522cf74010ed1bf6db1f7 --- /dev/null +++ b/script/add_annotation.py @@ -0,0 +1,379 @@ +import ast +import tokenize +import io +import re + + +def remove_comments_and_docstrings(source): + """ + 删除 Python 源码中的注释和文档字符串。 + """ + src = io.StringIO(source) + out = [] + prev_tok_type = tokenize.INDENT + last_lineno = -1 + last_col = 0 + + for tok in tokenize.generate_tokens(src.readline): + token_type = tok.type + token_string = tok.string + start_line, start_col = tok.start + end_line, end_col = tok.end + + if start_line > last_lineno: + out.append("\n" * (start_line - last_lineno - 1)) + last_col = 0 + elif start_col > last_col: + out.append(" " * (start_col - last_col)) + + if token_type == tokenize.COMMENT: + pass + elif token_type == tokenize.STRING: + if prev_tok_type not in (tokenize.INDENT, tokenize.NEWLINE): + # 判断是否为 docstring + if re.match(r'^\s*"""(?:[^"]|"{1,2})*"""$', token_string) or re.match( + r"^\s*'''(?:[^']|'{1,2})*'''$", token_string): + continue + else: + out.append(token_string) + else: + continue + else: + out.append(token_string) + + prev_tok_type = token_type + last_col = end_col + last_lineno = end_line + + return "".join([i for i in out if i.strip() != ""]).strip() + + +def get_method_source(filename, method_name): + """ + 提取指定类中的方法源码。 + """ + with open(filename, "r", encoding="utf-8") as f: + source = f.read() + tree = ast.parse(source) + + for node in ast.walk(tree): + if isinstance(node, ast.ClassDef): + # 遍历类中的所有方法 + for item in node.body: + if isinstance(item, ast.FunctionDef) and item.name == method_name: + lines = source.splitlines(keepends=True) + start_line = item.lineno - 1 + end_line = _get_function_end_line(item, lines) + method_source = "".join(lines[start_line:end_line]) + return method_source + + raise ValueError(f"Method '{method_name}' not found.") + + +def _get_function_end_line(node, lines): + last_child = None + for child in ast.walk(node): + if hasattr(child, "lineno"): + if last_child is None or child.lineno > last_child.lineno: + last_child = child + if last_child: + return last_child.lineno + return node.lineno + + +def save_to_tmp(method_source, tmp_file="tmp.txt"): + with open(tmp_file, "w", encoding="utf-8") as f: + f.write(method_source) + + +def read_from_new(new_file="new.txt"): + with open(new_file, "r", encoding="utf-8") as f: + return f.read() + + +def normalize_code(code): + code_no_comments = remove_comments_and_docstrings(code) + return code_no_comments + + +def compare_functions(code1, code2): + normalized1 = normalize_code(code1) + normalized2 = normalize_code(code2) + return normalized1 == normalized2 + + +def replace_method_in_file_with_comments(filename, method_name, new_method_source): + """ + 将指定类中的方法替换为新内容(保留注释等原始结构)。 + """ + with open(filename, "r", encoding="utf-8") as f: + lines = f.readlines() + + with open(filename, "r", encoding="utf-8") as f: + source = f.read() + + tree = ast.parse(source) + + for node in ast.walk(tree): + if isinstance(node, ast.ClassDef): + for item in node.body: + if isinstance(item, ast.FunctionDef) and item.name == method_name: + start_line = item.lineno - 1 # lineno 是 1-based + end_line = _get_function_end_line(item, lines) + + # 新方法内容按行分割,并保留缩进结构 + # 注意:new_method_source 应当是 new.txt 的原始字符串 + new_lines = new_method_source.splitlines(keepends=True) + + # 替换对应行区间 + lines[start_line:end_line] = new_lines + + # 写回文件 + with open(filename, "w", encoding="utf-8") as f: + f.writelines(lines) + return + + raise ValueError(f"Method '{method_name}' not found.") + + +system_prompt = """ +角色:你是一个专业的程序员,具有深厚的 Python 编程能力,能够快速理解和修改代码。你会根据我的要求来为代码添加相应的解释。 +任务:我会给你一段 Python 代码,你需要根据我的要求添加注释。注意,你不能对代码内容进行任何修改,只能添加注释。 +- 在 play_once 中: + - 你需要理解下面这些可用的函数调用: + - 我定义了 self.move() 函数,可以传递至多两个参数,分别是 actions_by_arm1, actions_by_arm2。 + - 以下函数会返回 actions(即一个动作序列): + - self.grasp_actor(actor, arm_tag:ArmTag, **args) + - self.place_actor(actor, arm_tag:ArmTag, target_pose, **args) + - self.move_to_pose(arm_tag:ArmTag, target_pose) + - self.move_by_displacement(arm_tag:ArmTag, x, y, z) + - self.close_gripper(arm_tag:ArmTag, **args) + - self.open_gripper(arm_tag:ArmTag, **args) + - self.back_to_origin(arm_tag:ArmTag) + - 你需要对每一个 self.move 进行注释,说明这个动作/组合动作是做什么的,这里的注释要**使用英文**。 + +举例: +- 没加注释前: +def play_once(self): + arm_tag = ArmTag('right' if self.object.get_pose().p[0] > 0 else 'left') + + self.move(self.grasp_actor(self.object, arm_tag=arm_tag, pre_grasp_dis=0.1)) + self.move(self.move_by_displacement(arm_tag=arm_tag, z=0.06)) + + displaystand_pose = self.displaystand.get_functional_point(0) + + self.move(self.place_actor(self.object, arm_tag=arm_tag, target_pose=displaystand_pose, constrain='free', pre_dis=0.07)) + + 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}'} + return self.info + +- 加注释后: +```python +def play_once(self): + arm_tag = ArmTag('right' if self.object.get_pose().p[0] > 0 else 'left') + + # Grasp the object + self.move(self.grasp_actor(self.object, arm_tag=arm_tag, pre_grasp_dis=0.1)) + # Move up + self.move(self.move_by_displacement(arm_tag=arm_tag, z=0.06)) + + # Get display stand's functional point as target pose + displaystand_pose = self.displaystand.get_functional_point(0) + + # Place the object on the display stand + self.move(self.place_actor(self.object, arm_tag=arm_tag, target_pose=displaystand_pose, constrain='free', pre_dis=0.07)) + + 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}'} + return self.info +``` + +约束:你不能对代码内容进行任何修改,只需要添加注释即可。 + +现在,开始你的工作!你只需要输出代码块即可。 +""" + +import os +import time +import traceback +from openai import OpenAI + + +def parse(source, max_try=5, verbose=True): + """AI 解析代码""" + os.environ["all_proxy"] = "" + os.environ["http_proxy"] = "" + os.environ["https_proxy"] = "" + client = OpenAI(api_key="", base_url="") + start, try_times = time.time(), 0 + while try_times < max_try: + try_times += 1 + try: + response = client.chat.completions.create( + model="deepseek-v3-250324", + messages=[ + { + "role": "system", + "content": system_prompt + }, + { + "role": "user", + "content": source + }, + ], + stream=True, + ) + on_thinking, thinking, answering = False, "", "" + process_count, process = 0, ["|", "/", "-", "\\"] + for chunk in response: + content = chunk.choices[0].delta.content + if content is None: + continue + if hasattr(chunk.choices[0].delta, "reasoning_content"): + thinking += chunk.choices[0].delta.reasoning_content + else: + if content == "": + on_thinking = True + elif content == "": + on_thinking = False + elif on_thinking: + thinking += content + else: + answering += content + + if verbose: + process_count = (process_count + 1) % 4 + process_show = (thinking + answering)[-50:].replace("\n", "") + print(f'\r {" "*100}', end="") + print(f"\r{process[process_count]} {process_show}", end="", flush=True) + except SyntaxError: + print(traceback.format_exc()) + break + except: + print(traceback.format_exc()) + continue + + result = re.search(r"```python\n([\s\S]*?)\n```", answering, re.S) + if result is not None: + if verbose: + print( + f"cost {time.time()-start:.2f}s, try {try_times} time(s)", + flush=True, + ) + return result.group(1) + return None + + +def main(file_path, max_try=5, verbose=True): + try_count = 0 + while try_count < max_try: + try_count += 1 + # Step 1: 提取类中的方法 + method_source = get_method_source(file_path, "play_once") + + # Step 2: 调用 AI 解析代码 + processed_source = parse(method_source, max_try=5, verbose=verbose) + + # Step 3: 比较两个方法 + if compare_functions(method_source, processed_source): + replace_method_in_file_with_comments(file_path, "play_once", processed_source) + break + + if try_count >= max_try: + with open("error.log", "a", encoding="utf-8") as f: + f.write(f"Error processing {file_path}: Exceeded maximum retries.\n") + + +from threading import Thread +from pathlib import Path + + +def batch(batch_size=5, root="./envs"): + name_list = [ + "beat_block_hammer", + "blocks_ranking_rgb", + "blocks_ranking_size", + "dump_bin_bigbin", + "grab_roller", + "lift_pot", + "move_can_pot", + "move_playingcard_away", + "move_stapler_pad", + "place_a2b_left", + "place_a2b_right", + "place_bread_basket", + "place_bread_skillet", + "place_can_basket", + "place_cylinder_box", + "place_fan", + "place_medicine_spot", + "place_mouse_pad", + "place_object_scale", + "place_object_stand", + "place_phone_stand", + "place_remote_storage", + "place_object_basket", + "put_bottles_dustbin", + "rotate_qrcode", + "shake_bottle", + "shake_bottle_horizontally", + "place_shoe", + "slide_mouse_pad", + "stamp_seal", + "handover_block", + "stack_blocks_three", + "stack_blocks_two", + "adjust_bottle", + "stack_bowls_three", + "stack_bowls_two", + "click_alarmclock", + "click_bell", + "place_container_plate", + "pick_diverse_bottles", + "pick_dual_bottles", + "place_dual_shoes", + "place_empty_cup", + "place_object_into_plasticbox", + ] + process_list = [] + for file in name_list: + file = Path(root) / f"{file}.py" + if file.exists(): + process_list.append(file) + else: + print(f"WARNNING: {file.name} not exists!") + + # Create and start a thread for each file + threads = [] + finish_count, total_count = 0, len(process_list) + for file in process_list: + thread = Thread(target=main, args=(file, 5, False)) + thread.start() + threads.append([file, thread]) + while len(threads) >= batch_size: + for t in threads: + if not t[1].is_alive(): + threads.remove(t) + finish_count += 1 + print( + f"[{finish_count:>3d}/{total_count:03d}] files processed. new finish:", + t[0].name, + flush=True, + ) + time.sleep(0.1) + + # Wait for all threads to complete + while len(threads) > 0: + for t in threads: + if not t[1].is_alive(): + threads.remove(t) + finish_count += 1 + print( + f"[{finish_count:>3d}/{total_count:03d}] files processed. new finish:", + t[0].name, + flush=True, + ) + time.sleep(0.1) + + +if __name__ == "__main__": + batch() diff --git a/script/collect_data.py b/script/collect_data.py new file mode 100644 index 0000000000000000000000000000000000000000..6bd9206f44d01992c68130258fad5342e6555280 --- /dev/null +++ b/script/collect_data.py @@ -0,0 +1,250 @@ +import sys + +sys.path.append("./") + +import sapien.core as sapien +from sapien.render import clear_cache +from collections import OrderedDict +import pdb +from envs import * +import yaml +import importlib +import json +import traceback +import os +import time +from argparse import ArgumentParser + +current_file_path = os.path.abspath(__file__) +parent_directory = os.path.dirname(current_file_path) + + +def class_decorator(task_name): + envs_module = importlib.import_module(f"envs.{task_name}") + try: + env_class = getattr(envs_module, task_name) + env_instance = env_class() + except: + raise SystemExit("No such task") + return env_instance + + +def get_embodiment_config(robot_file): + robot_config_file = os.path.join(robot_file, "config.yml") + with open(robot_config_file, "r", encoding="utf-8") as f: + embodiment_args = yaml.load(f.read(), Loader=yaml.FullLoader) + return embodiment_args + + +def main(task_name=None, task_config=None): + + task = class_decorator(task_name) + config_path = f"./task_config/{task_config}.yml" + + with open(config_path, "r", encoding="utf-8") as f: + args = yaml.load(f.read(), Loader=yaml.FullLoader) + + args['task_name'] = task_name + + embodiment_type = args.get("embodiment") + embodiment_config_path = os.path.join(CONFIGS_PATH, "_embodiment_config.yml") + + with open(embodiment_config_path, "r", encoding="utf-8") as f: + _embodiment_types = yaml.load(f.read(), Loader=yaml.FullLoader) + + def get_embodiment_file(embodiment_type): + robot_file = _embodiment_types[embodiment_type]["file_path"] + if robot_file is None: + raise "missing embodiment files" + return robot_file + + if len(embodiment_type) == 1: + args["left_robot_file"] = get_embodiment_file(embodiment_type[0]) + args["right_robot_file"] = get_embodiment_file(embodiment_type[0]) + args["dual_arm_embodied"] = True + elif len(embodiment_type) == 3: + args["left_robot_file"] = get_embodiment_file(embodiment_type[0]) + args["right_robot_file"] = get_embodiment_file(embodiment_type[1]) + args["embodiment_dis"] = embodiment_type[2] + args["dual_arm_embodied"] = False + else: + raise "number of embodiment config parameters should be 1 or 3" + + args["left_embodiment_config"] = get_embodiment_config(args["left_robot_file"]) + args["right_embodiment_config"] = get_embodiment_config(args["right_robot_file"]) + + if len(embodiment_type) == 1: + embodiment_name = str(embodiment_type[0]) + else: + embodiment_name = str(embodiment_type[0]) + "+" + str(embodiment_type[1]) + + # show config + print("============= Config =============\n") + print("\033[95mMessy Table:\033[0m " + str(args["domain_randomization"]["cluttered_table"])) + print("\033[95mRandom Background:\033[0m " + str(args["domain_randomization"]["random_background"])) + if args["domain_randomization"]["random_background"]: + print(" - Clean Background Rate: " + str(args["domain_randomization"]["clean_background_rate"])) + print("\033[95mRandom Light:\033[0m " + str(args["domain_randomization"]["random_light"])) + if args["domain_randomization"]["random_light"]: + print(" - Crazy Random Light Rate: " + str(args["domain_randomization"]["crazy_random_light_rate"])) + print("\033[95mRandom Table Height:\033[0m " + str(args["domain_randomization"]["random_table_height"])) + print("\033[95mRandom Head Camera Distance:\033[0m " + str(args["domain_randomization"]["random_head_camera_dis"])) + + print("\033[94mHead Camera Config:\033[0m " + str(args["camera"]["head_camera_type"]) + f", " + + str(args["camera"]["collect_head_camera"])) + print("\033[94mWrist Camera Config:\033[0m " + str(args["camera"]["wrist_camera_type"]) + f", " + + str(args["camera"]["collect_wrist_camera"])) + print("\033[94mEmbodiment Config:\033[0m " + embodiment_name) + print("\n==================================") + + args["embodiment_name"] = embodiment_name + args['task_config'] = task_config + args["save_path"] = os.path.join(args["save_path"], str(args["task_name"]), args["task_config"]) + run(task, args) + + +def run(TASK_ENV, args): + epid, suc_num, fail_num, seed_list = 0, 0, 0, [] + + print(f"Task Name: \033[34m{args['task_name']}\033[0m") + + # =========== Collect Seed =========== + os.makedirs(args["save_path"], exist_ok=True) + + if not args["use_seed"]: + print("\033[93m" + "[Start Seed and Pre Motion Data Collection]" + "\033[0m") + args["need_plan"] = True + + if os.path.exists(os.path.join(args["save_path"], "seed.txt")): + with open(os.path.join(args["save_path"], "seed.txt"), "r") as file: + seed_list = file.read().split() + if len(seed_list) != 0: + seed_list = [int(i) for i in seed_list] + suc_num = len(seed_list) + epid = max(seed_list) + 1 + print(f"Exist seed file, Start from: {epid} / {suc_num}") + + while suc_num < args["episode_num"]: + try: + TASK_ENV.setup_demo(now_ep_num=suc_num, seed=epid, **args) + TASK_ENV.play_once() + + if TASK_ENV.plan_success and TASK_ENV.check_success(): + print(f"simulate data episode {suc_num} success! (seed = {epid})") + seed_list.append(epid) + TASK_ENV.save_traj_data(suc_num) + suc_num += 1 + else: + print(f"simulate data episode {suc_num} fail! (seed = {epid})") + fail_num += 1 + + TASK_ENV.close_env() + + if args["render_freq"]: + TASK_ENV.viewer.close() + except UnStableError as e: + print(" -------------") + print(f"simulate data episode {suc_num} fail! (seed = {epid})") + print("Error: ", e) + print(" -------------") + fail_num += 1 + TASK_ENV.close_env() + + if args["render_freq"]: + TASK_ENV.viewer.close() + time.sleep(0.3) + except Exception as e: + # stack_trace = traceback.format_exc() + print(" -------------") + print(f"simulate data episode {suc_num} fail! (seed = {epid})") + print("Error: ", e) + print(" -------------") + fail_num += 1 + TASK_ENV.close_env() + + if args["render_freq"]: + TASK_ENV.viewer.close() + time.sleep(1) + + epid += 1 + + with open(os.path.join(args["save_path"], "seed.txt"), "w") as file: + for sed in seed_list: + file.write("%s " % sed) + + print(f"\nComplete simulation, failed \033[91m{fail_num}\033[0m times / {epid} tries \n") + else: + print("\033[93m" + "Use Saved Seeds List".center(30, "-") + "\033[0m") + with open(os.path.join(args["save_path"], "seed.txt"), "r") as file: + seed_list = file.read().split() + seed_list = [int(i) for i in seed_list] + + # =========== Collect Data =========== + + if args["collect_data"]: + print("\033[93m" + "[Start Data Collection]" + "\033[0m") + + args["need_plan"] = False + args["render_freq"] = 0 + args["save_data"] = True + + clear_cache_freq = args["clear_cache_freq"] + + st_idx = 0 + + def exist_hdf5(idx): + file_path = os.path.join(args["save_path"], 'data', f'episode{idx}.hdf5') + return os.path.exists(file_path) + + while exist_hdf5(st_idx): + st_idx += 1 + + for episode_idx in range(st_idx, args["episode_num"]): + print(f"\033[34mTask name: {args['task_name']}\033[0m") + + TASK_ENV.setup_demo(now_ep_num=episode_idx, seed=seed_list[episode_idx], **args) + + traj_data = TASK_ENV.load_tran_data(episode_idx) + args["left_joint_path"] = traj_data["left_joint_path"] + args["right_joint_path"] = traj_data["right_joint_path"] + TASK_ENV.set_path_lst(args) + + info_file_path = os.path.join(args["save_path"], "scene_info.json") + + if not os.path.exists(info_file_path): + with open(info_file_path, "w", encoding="utf-8") as file: + json.dump({}, file, ensure_ascii=False) + + with open(info_file_path, "r", encoding="utf-8") as file: + info_db = json.load(file) + + info = TASK_ENV.play_once() + info_db[f"episode_{episode_idx}"] = info + + with open(info_file_path, "w", encoding="utf-8") as file: + json.dump(info_db, file, ensure_ascii=False, indent=4) + + TASK_ENV.close_env(clear_cache=((episode_idx + 1) % clear_cache_freq == 0)) + TASK_ENV.merge_pkl_to_hdf5_video() + TASK_ENV.remove_data_cache() + assert TASK_ENV.check_success(), "Collect Error" + + command = f"cd description && bash gen_episode_instructions.sh {args['task_name']} {args['task_config']} {args['language_num']}" + os.system(command) + + +if __name__ == "__main__": + from test_render import Sapien_TEST + Sapien_TEST() + + import torch.multiprocessing as mp + mp.set_start_method("spawn", force=True) + + parser = ArgumentParser() + parser.add_argument("task_name", type=str) + parser.add_argument("task_config", type=str) + parser = parser.parse_args() + task_name = parser.task_name + task_config = parser.task_config + + main(task_name=task_name, task_config=task_config) diff --git a/script/create_messy_data.py b/script/create_messy_data.py new file mode 100644 index 0000000000000000000000000000000000000000..530443c7340bab9acbe969e601bc3a24ac6a0ca3 --- /dev/null +++ b/script/create_messy_data.py @@ -0,0 +1,1078 @@ +import trimesh +import importlib +import numpy as np +from pathlib import Path +from copy import deepcopy +import transforms3d as t3d +from threading import Thread +import readline + +import sys + +import trimesh.bounds + +sys.path.append(".") +from envs.utils import * +import sapien.core as sapien +from sapien.utils.viewer import Viewer +from tqdm import tqdm +from PIL import Image + +import re +import time +from typing import List, Literal + +from sapien import Pose + +# obj square +CAMERA_POSE = Pose([0, 0.134123, 0.96], [0.684988, 0.174248, 0.173926, -0.685696]) +# main graph +# CAMERA_POSE = Pose([0.0293144, -1.12261, 1.52599], [0.665553, 0.233024, 0.231257, -0.670268]) + +class Helper: + POINTS = [ + ("target_pose", "target"), + ("contact_points_pose", "contact"), + ("functional_matrix", "functional"), + ("orientation_point", "orientation"), + ] + + def create_scene(self, viewer=True, **kwargs): + """ + Set the scene + - Set up the basic scene: light source, viewer. + """ + self.engine = sapien.Engine() + # declare sapien renderer + from sapien.render import set_global_config + + set_global_config(max_num_materials=50000, max_num_textures=50000) + self.renderer = sapien.SapienRenderer() + # give renderer to sapien sim + self.engine.set_renderer(self.renderer) + + sapien.render.set_camera_shader_dir("rt") + sapien.render.set_ray_tracing_samples_per_pixel(32) + sapien.render.set_ray_tracing_path_depth(8) + sapien.render.set_ray_tracing_denoiser("oidn") + + # declare sapien scene + scene_config = sapien.SceneConfig() + self.scene = self.engine.create_scene(scene_config) + # set simulation timestep + self.scene.set_timestep(kwargs.get("timestep", 1 / 250)) + + # initialize viewer with camera position and orientation + if viewer: + self.viewer = Viewer(self.renderer) + self.viewer.set_scene(self.scene) + self.viewer.set_camera_xyz( + x=kwargs.get("camera_xyz_x", 0.4), + y=kwargs.get("camera_xyz_y", 0.22), + z=kwargs.get("camera_xyz_z", 1.5), + ) + self.viewer.set_camera_rpy( + r=kwargs.get("camera_rpy_r", 0), + p=kwargs.get("camera_rpy_p", -0.8), + y=kwargs.get("camera_rpy_y", 2.45), + ) + else: + self.viewer = None + self.camera = self.scene.add_camera("camera", 2390, 1000, 1.57, 0.1, 1000) + self.camera.set_pose(CAMERA_POSE) + # scale = 1 + # self.camera = self.scene.add_camera(name="", width=2560*scale, height=1600*scale, fovy=1.57, near=0.1, far=1e+03) + # self.camera.set_local_pose(sapien.Pose([-0.893507, -0.358009, 0.983116], [0.869079, 0.128192, 0.298895, -0.372735])) + + def create_table_and_wall(self): + # add ground to scene + # self.scene.add_ground(0) + # set default physical material + self.scene.default_physical_material = self.scene.create_physical_material(0.5, 0.5, 0) + # give some white ambient light of moderate intensity + self.scene.set_ambient_light([0.5, 0.5, 0.5]) + # default enable shadow unless specified otherwise + shadow = False + # default spotlight angle and intensity + direction_lights = [[[0, 0.5, -1], [0.5, 0.5, 0.5]]] + self.direction_light_lst = [] + for direction_light in direction_lights: + self.direction_light_lst.append(self.scene.add_directional_light(direction_light[0], direction_light[1], shadow=shadow)) + # default point lights position and intensity + point_lights = [ + [[1, 0, 1.8], [1, 1, 1]], + [[-1, 0, 1.8], [1, 1, 1]], + [[2.6, -1.7, 0.76], [1, 1, 1]], + [[-2.6, -1.7, 0.76], [1, 1, 1]], + [[-1.2, -4.4, 0.76], [1, 1, 1]], + [[1.2, -4.4, 0.76], [1, 1, 1]], + ] + self.point_light_lst = [] + for point_light in point_lights: + self.point_light_lst.append(self.scene.add_point_light(point_light[0], point_light[1], shadow=shadow)) + + # creat wall + wall_texture, table_texture = None, None + # self.wall_texture, self.table_texture = 0, 0 + # self.wall = create_box( + # self.scene, + # sapien.Pose(p=[0, 1, 1.5]), + # half_size=[3, 0.6, 1.5], + # color=(1, 0.9, 0.9), + # name='wall', + # texture_id=wall_texture + # ) + + # self.table_z_bias = np.random.random()*0.3 - 0.15 + # print('bias:', self.table_z_bias) + # self.table_z_bias = 0 + # table_height = self.table_z_bias + 0.74 + + # creat table + # self.table = create_table( + # self.scene, + # sapien.Pose(p = [0, 0, table_height]), + # length=2, + # width=4, + # height=table_height, + # thickness=0.05, + # is_static=True, + # texture_id=table_texture + # ) + + def init_messy(self): + with open("./assets/objects/objaverse/list.json", "r") as file: + self.messy_item_info = json.load(file) + self.obj_names = self.messy_item_info["item_names"] + self.size_dict = [] + self.obj_list = [] + self.max_obj_num = 1 + + def add_messy_obj(self, name, idx, xlim=[-0.3, 0.3], ylim=[-0.2, 0.2], zlim=[0.741]): + tyrs, max_try = 0, 100 + success_count, messy_obj = 0, None + while tyrs < max_try: + obj_str = f"{name}_{idx}" + obj_radius = self.messy_item_info["radius"][obj_str] + obj_offset = self.messy_item_info["z_offset"][obj_str] + obj_maxz = self.messy_item_info["z_max"][obj_str] + + success, messy_obj = rand_create_cluttered_actor( + self.scene, + xlim=xlim, + ylim=ylim, + zlim=np.array(zlim), + modelname=obj_str, + rotate_rand=True, + rotate_lim=[0, 0, np.pi], + size_dict=self.size_dict, + obj_radius=obj_radius, + z_offset=obj_offset, + z_max=obj_maxz, + prohibited_area=[], + ) + if not success: + continue + # self.viewer.paused = True + # while self.viewer.paused: + # self.scene.update_render() + # self.viewer.render() + messy_obj: sapien.Entity = messy_obj[0] + messy_obj.set_name(obj_str) + messy_obj.find_component_by_type(sapien.physx.PhysxRigidDynamicComponent).mass = 0.01 + success_count += 1 + + pose = sapien.pysapien.Entity.get_pose(messy_obj).p.tolist() + pose.append(obj_radius) + self.size_dict.append(pose) + self.obj_list.append(messy_obj) + + if len(self.obj_list) > self.max_obj_num: + obj = self.obj_list.pop(0) + self.size_dict.pop(0) + self.scene.remove_actor(obj) + self.scene.update_render() + self.viewer.render() + + break + return success_count == 1, messy_obj + + def check_urdf(self, name, idx, d_range=50, pose=None): + if pose is None: + success, obj = self.add_messy_obj(name, idx) + if not success: + return False + + def to_array(pose: sapien.Pose) -> np.ndarray: + return np.array(pose.p.tolist() + pose.q.tolist()) + + is_step, max_step = 0, 200 + pose_list = [to_array(obj.get_pose())] + while is_step < max_step: + self.scene.step() + self.scene.update_render() + self.viewer.render() + + new_pose = obj.get_pose() + pose_list.append(to_array(new_pose)) + + if len(pose_list) > d_range: + check_succ = True + for i in range(-d_range, 0): + if not np.allclose(pose_list[i], pose_list[-d_range], 1e-4): + check_succ = False + break + if check_succ: + break + is_step += 1 + + if is_step > 0 and is_step < max_step: + success = True + elif is_step >= max_step: + success = False + + # self.viewer.paused = True + # while self.viewer.paused: + # self.scene.update_render() + # self.viewer.render() + return success + else: + modeldir = f"./assets/objects/objaverse/{name}/{idx}/" + loader: sapien.URDFLoader = self.scene.create_urdf_loader() + + loader.fix_root_link = True + loader.load_multiple_collisions_from_file = False + object = loader.load_multiple(modeldir + "model.urdf")[1][0] + + object.set_pose(sapien.Pose(pose, [1, 0, 0, 0])) + object.set_name(name) + + return True + + def test_messy(self): + self.create_scene() + self.create_table_and_wall() + self.init_messy() + + self.result = [] + + test_list = [] + for name in self.obj_names: + for idx in self.messy_item_info["list_of_items"][name]: + test_list.append((name, idx)) + + # test_list = test_list[19:] + for cnt, (name, idx) in enumerate(tqdm(test_list)): + if name != "ramen_package": + continue + # if cnt > 0 and cnt % 100 == 0: + # time.sleep(3) + # self.scene.clear() + # self.create_table_and_wall() + success = self.check_urdf(name, idx) + self.result.append({"name": name, "idx": idx, "success": success}) + with open("result.jsonl", "a", encoding="utf-8") as f: + f.write(json.dumps(self.result[-1]) + "\n") + + while len(self.obj_list) > 0: + obj = self.obj_list.pop(0) + self.size_dict.pop(0) + self.scene.remove_actor(obj) + self.scene.update_render() + self.viewer.render() + + @staticmethod + def trans_mat(to_mat: np.ndarray, from_mat: np.ndarray): + to_rot = to_mat[:3, :3] + from_rot = from_mat[:3, :3] + rot_mat = to_rot @ from_rot.T + + trans_mat = to_mat[:3, 3] - from_mat[:3, 3] + + result = np.eye(4) + result[:3, :3] = rot_mat + result[:3, 3] = trans_mat + result = np.where(np.abs(result) < 1e-5, 0, result) + return result + + @staticmethod + def trans_base( + init_pose_mat: np.ndarray, + now_base_mat: np.ndarray, + init_base_mat: np.ndarray = np.eye(4), + ): + now_pose_mat = np.eye(4) + base_trans_mat = Helper.trans_mat(now_base_mat, init_base_mat) + now_pose_mat[:3, :3] = (base_trans_mat[:3, :3] @ init_pose_mat[:3, :3] @ base_trans_mat[:3, :3].T) + now_pose_mat[:3, 3] = base_trans_mat[:3, :3] @ init_pose_mat[:3, 3] + + # 转化为世界坐标 + p = now_pose_mat[:3, 3] + now_base_mat[:3, 3] + q_mat = now_pose_mat[:3, :3] @ now_base_mat[:3, :3] + return sapien.Pose(p, t3d.quaternions.mat2quat(q_mat)) + + def add_visual_box(self, pose: sapien.Pose, name: str = "box"): + box, _ = create_obj( + scene=self.scene, + pose=pose, + modelname="vis_box", + # modelname="cube", + is_static=True, + scale=[0.025, 0.025, 0.025], + no_collision=True, + ) + box.set_name(name) + + def check_obj(self, name, idx, mid, d_range=50, pose=None, anno=None): + if pose is None: + obj, config = rand_create_actor( + self.scene, + xlim=[0, 0], + ylim=[0, 0], + zlim=[0.743], + modelname=f"{idx}_{name}", + model_id=mid, + convex=True, + qpos=[0, 0, 0.707107, 0.707107], + scale=(0.1, 0.1, 0.1), + ) + else: + obj = create_actor( + self.scene, + pose=sapien.Pose(pose[:3], [0, 0, 0.707107, 0.707107]), + modelname=f"{idx}_{name}", + model_id=mid, + convex=True, + is_static=True, + ) + if obj is None: + print(f"create obj[{idx}_{name}/{mid}] failed") + return False + if anno is not None and (anno is True or (anno[0] <= pose[0] <= anno[1] and anno[2] <= pose[1] <= anno[3])): + try: + scale = config["scale"] + base_mat = obj.get_pose().to_transformation_matrix() + for key, name in self.POINTS: + if key == "orientation_point": + if len(config.get(key, [])) <= 1: + continue + points = [config.get(key, [])] + else: + points = config.get(key, []) + + for idx, mat in enumerate(points): + mat = np.array(mat) + mat[:3, 3] *= scale + pose = self.trans_base(mat, base_mat) + self.add_visual_box(pose, name=f"{name}_{idx}") + except: + return False + + # def to_array(pose:sapien.Pose) -> np.ndarray: + # return np.array(pose.p.tolist()+pose.q.tolist()) + + # is_step, max_step = 0, 200 + # pose_list = [to_array(obj.get_pose())] + # while is_step < max_step: + # self.scene.step() + # self.scene.update_render() + # self.viewer.render() + + # new_pose = obj.get_pose() + # pose_list.append(to_array(new_pose)) + + # if len(pose_list) > d_range: + # check_succ = True + # for i in range(-d_range, 0): + # if not np.allclose(pose_list[i], pose_list[-d_range], 1e-4): + # check_succ = False + # break + # if check_succ: + # break + # is_step += 1 + + # if is_step > 0 and is_step < max_step: + # success = True + # elif is_step >= max_step: + # success = False + + # self.scene.remove_actor(obj) + # self.scene.update_render() + # self.viewer.render() + # return success + + def add_robot(self): + + def init_joints(entity: sapien.physx.PhysxArticulation, config): + # set joints + active_joints = entity.get_active_joints() + arm_joints = [entity.find_joint_by_name(i) for i in config["arm_joints_name"][0]] + + def get_gripper_joints(find, gripper_name: str): + gripper = [(find(gripper_name["base"]), 1.0, 0.0)] + for g in gripper_name["mimic"]: + gripper.append((find(g[0]), g[1], g[2])) + return gripper + + gripper = get_gripper_joints(entity.find_joint_by_name, config["gripper_name"][0]) + + for i, joint in enumerate(active_joints): + joint.set_drive_property( + stiffness=config.get("joint_stiffness", 1000), + damping=config.get("joint_damping", 200), + ) + for joint in gripper: + joint[0].set_drive_property( + stiffness=config.get("gripper_stiffness", 1000), + damping=config.get("gripper_damping", 200), + ) + for i, joint in enumerate(active_joints): + joint.set_drive_target(config["joints"][0][i]) + for i, joint in enumerate(gripper): + real_joint: sapien.physx.PhysxArticulationJoint = joint[0] + drive_target = config["gripper_scale"][1] * joint[1] + joint[2] + drive_velocity_target = (np.clip(drive_target - real_joint.drive_target, -1.0, 1.0) * 0.05) + real_joint.set_drive_target(drive_target) + real_joint.set_drive_velocity_target(drive_velocity_target) + + radius = 2.5 + count, max_count = 0, 13 + emb = Path("./assets/embodiments") + + joint_dict = { + "ARX-X5": [-6.155617, 1.1425792, 1.4179262, -0.97225964, -1.4429708e-05, -3.082031e-06, 0.044, 0.044], + # "ARX-X5": [ + # -6.155634, + # 0.816421, + # 1.0468683, + # -0.9384637, + # -3.4565306e-05, + # -8.612996e-06, + # 0.044, + # 0.044, + # ], + "piper": [ + -0.34990656, + 1.2450953, + -1.5324507, + 0.10282991, + 1.22, + 0.00065908127, + 0.039999943, + 0.03997663, + ], + "franka-panda": [ + -0.00021794076, + 0.041278794, + -0.0013123713, + -1.8957008, + 0.009215873, + 2.0166128, + 0.8549956, + 0.04, + 0.04, + ], + "aloha-agilex": [ + 0.0, + 0.0, + -2.5302018e-14, + -2.5302018e-14, + -2.5302018e-14, + -2.5302018e-14, + 1.1234251e-05, + 1.0832736e-05, + -0.00048545605, + 1.5486969e-05, + -2.5418809e-17, + -2.5418809e-17, + -2.5418809e-17, + -2.5418809e-17, + 0.002626635, + 0.002626792, + 0.0027120241, + 0.0021979488, + -0.0399116, + -0.03991316, + -0.031362604, + -0.031362318, + -0.0021148901, + -0.002130989, + -0.0031363545, + -0.0031357573, + -0.00090792944, + -0.0009686581, + -1.6246497e-06, + -1.6584742e-06, + -6.803319e-05, + -6.932296e-05, + 1.0387723e-06, + 1.125215e-06, + 0.044976402, + 0.044976484, + 0.04762502, + 0.047625143, + ], + "ur5-wsg": [-1.5452573, -1.7434453, -1.3246999, -1.75, 1.5422482, -3.1415927, -0.055, 0.055], + "z1": [ + 0.2046731, + 1.5261446, + -1.7666384, + 1.1484289, + 8.120951e-06, + -7.348934e-05, + -7.787227e-08, + 0.040000536, + 0.040000137, + ], + "ufactory_lite6": [ + -0.16042127, + 0.53086734, + 2.0658371, + 0.006172284, + 0.92715985, + 1.5044298, + 3.7193262e-05, + 0.040008515, + 0.03999608, + ], + # 'ARX-X5': [-6.1558957, 0.81342375, 1.0558599, -0.937343, -3.2896776e-05, -7.4935256e-06, 0.044, 0.044], + # 'ufactory_lite6': [-0.25563017, 0.35529876, 2.0722473, 0.005538411, 0.9270778, 1.5045198, 3.138106e-05, 0.040005907, 0.03998957], + # 'franka-panda': [-0.00016283647, 0.0074461037, -0.0010076275, -1.8719686, 0.008220577, 2.018346, 0.85500133, 0.04, 0.04], + # '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], + # 'ur5-wsg-gripper': [-1.5494769, -1.5602797, -1.3733442, -1.7500004, 1.5424018, -0.000120613506, -0.055, 0.055], + # 'z1': [0.20469421, 1.5193493, -1.7742655, 1.1475929, 7.234784e-06, -5.6515753e-05, -1.4886399e-07, 0.039999034, 0.039998993], + # 'piper': [-0.23096707, 1.2409755, -1.4549325, 0.10388685, 1.2199999, 0.000500452, 0.039999936, 0.03997564], + # 'ur5-wsg-gripper': [-1.57, -0.78, -1.33, -1.70, 1.56, 3.14, 0, 0], + # 'franka-panda': [-2.89, 1.03, 2.89, -1.93, -0.21, 1.27, 0.78, 0, 0], + } + + pose_dict = { + "ARX-X5": sapien.Pose([-0.821443, -1.6714, 0.781873], [0.999601, 5.86649e-08, -7.04128e-07, -0.0282362]), + "piper": sapien.Pose([0.846021, -1.70083, 0.731933], [-0.0329616, 4.47035e-08, -1.49012e-08, 0.999457]), + "franka-panda": sapien.Pose( + [0.880834, -2.30439, 0.75], + [0.4564, 4.47035e-08, -1.16415e-10, 0.889775], + ), + "aloha-agilex": sapien.Pose( + [1.75423e-08, -2.39183, 0.465], + [0.709881, 8.9407e-08, -4.74683e-08, 0.704321], + ), + "ur5-wsg": sapien.Pose( + [-0.907954, -2.31459, 0.77098], + [0.956935, -2.55658e-08, -1.0741e-07, -0.290302], + ), + # "z1": sapien.Pose( + # [-1.08728, -1.74981, 0.743286], + # [0.999384, -5.50994e-07, 4.56203e-09, 0.035102], + # ), + # "ufactory_lite6": sapien.Pose([-1.14082, -1.26895, 0.654833], [1, 0, 0, 8.66251e-07]), + # 'ARX-X5': sapien.Pose([0.97715, -1.28326, 0.783988], [-9.09963e-07, 6.85768e-07, 9.68444e-08, 1]), + # 'ufactory_lite6': sapien.Pose([1.11059, -1.72772, 0.654833], [-9.09963e-07, 0, 0, 1]), + # 'franka-panda': sapien.Pose([0.880834, -2.30439, 0.75], [0.4564, 4.47035e-08, -1.16415e-10, 0.889775]), + # 'aloha-agilex-1': sapien.Pose([8.77117e-09, -2.39183, 0.315], [0.709881, 8.9407e-08, -4.74683e-08, 0.704321]), + # 'ur5-wsg-gripper': sapien.Pose([-0.907954, -2.31459, 0.77098], [0.956935, -2.55658e-08, -1.0741e-07, -0.290302]), + # 'z1': sapien.Pose([-1.08728, -1.74981, 0.743286], [0.999384, -5.50994e-07, 8.28732e-09, 0.035102]), + # 'piper': sapien.Pose([-1.02042, -1.22711, 0.731933], [1, 0, 0, 0]), + # 'piper': sapien.Pose([-1.08728, -1.28692, 0.743286], [-0.99999, 5.36442e-07, 4.47035e-08, -0.00445333]), + # 'ur5-wsg-gripper': sapien.Pose([1.11433, -2.06679, 0.75], [0.935868, 3.53431e-08, -1.04601e-07, 0.35235]), + # 'z1': sapien.Pose([-1.08376, -0.879804, 0.75], [0.999983, 8.50705e-08, -2.12434e-07, 0.00582502]), + # 'ufactory_lite6': sapien.Pose([1.10847, -0.967647, 0.6], [0.0313626, 0, 0, 0.999508]), + # 'ARX-X5': sapien.Pose([1.072, -1.29, 0.783988], [0.0159038, 6.87222e-07, 8.59252e-08, 0.999874]), + # 'franka-wsg': sapien.Pose([0.622937, -2.38999, 0.750243], [0.710587, 9.08971e-07, 9.36911e-07, 0.703609]), + # 'ur5-robotic85-gripper': sapien.Pose([-1.38769, -1.8014, 0.75], [-0.879306, 5.93055e-08, 8.07258e-08, 0.476258]), + # 'RM65B-EG24C2': sapien.Pose([1.02471, -1.10745, 0.85], [0.999792, 3.72529e-08, 2.26079e-07, -0.0204]), + # 'ufactory_xarm7': sapien.Pose([-1.09916, -1.35288, 0.72], [0.998108, -4.47035e-08, -2.98023e-08, 0.0614921]), + # 'piper': sapien.Pose([-1.08728, -0.786483, 0.743286], [0.99999, -2.98023e-08, 7.45058e-08, 0.00445369]), + # 'z1': sapien.Pose([-1.08376, -0.536377, 0.75], [0.999983, 8.58563e-08, -2.12394e-07, 0.00582501]), + # 'ufactory_lite6': sapien.Pose([1.10847, -0.601613, 0.6], [0.0313626, 0, 0, 0.999508]), + # 'ARX-X5': sapien.Pose([1.072, -0.884706, 0.783988], [0.0159033, 6.87222e-07, 8.59257e-08, 0.999874]), + # 'kinova': sapien.Pose([-1.29571, -1.1639, 0.618725], [0.999138, -2.0683e-06, 0.000454868, 0.0415031]), + # 'rethink_robotics_sawyer': sapien.Pose([1.40007, -1.41166, 0.7], [0.0748435, -7.82311e-08, -4.47035e-08, 0.997195]), + } + name_list = list(pose_dict.keys()) + + for robot in emb.iterdir(): + if not robot.is_dir(): + continue + cfg_path = robot / "config.yml" + if robot.name not in name_list: + continue + if not cfg_path.exists(): + continue + + cfg = yaml.load(open(cfg_path, "r", encoding="utf-8"), Loader=yaml.FullLoader) + urdf_path = robot / cfg["urdf_path"] + loader: sapien.URDFLoader = self.scene.create_urdf_loader() + loader.fix_root_link = True + entity: sapien.physx.PhysxArticulation = loader.load(str(urdf_path)) + entity.set_name(robot.name) + print(f"load {robot.name} from {urdf_path}") + # x = 0.1 - radius * np.cos(np.pi/12+(np.pi*5/6)/max_count*count) + # entity.set_pose(sapien.Pose([ + # x, + # -radius * np.sin(np.pi/12+(np.pi*5/6)/max_count*count), + # cfg['robot_pose'][0][2] + # ], t3d.quaternions.axangle2quat([0, 0, 1], np.pi/max_count*count) + # )) + cfg["joints"] = [joint_dict[robot.name]] + entity.set_pose(pose_dict[robot.name]) + init_joints(entity, cfg) + count += 1 + + def block(self): + if self.viewer is None: + return + while True: + self.scene.step() + self.scene.update_render() + self.viewer.render() + + def run(self, step=200, no_step=False): + if no_step: + self.scene.update_render() + if self.viewer is not None: + self.viewer.render() + return + for _ in tqdm(range(step), desc="running"): + if not no_step: + self.scene.step() + self.scene.update_render() + if self.viewer is not None: + self.viewer.render() + + def take_picture(self, name="camera.png"): + print("start taking picture") + self.camera.take_picture() + camera_rgba = self.camera.get_picture("Color") + position = self.camera.get_picture("Position") + depth = -position[..., 2] + + camera_rgba_img = (camera_rgba * 255).clip(0, 255).astype("uint8")[:, :, :3] + camera_rgba_img = Image.fromarray(camera_rgba_img) + camera_rgba_img.save(name) + np.save("depth_data.npy", depth) + print("picture saved:", name) + + def generate_in( + self, + obj_list, + x_min, + x_max, + y_min, + y_max, + z=0.74, + padding=0.05, + anno=None, + table=True, + max_z_stack=1, + logo=False, + ): + max_z_count = 0 + + def create_table(): + nonlocal max_z_count, table + max_z_count += 1 + if max_z_count > max_z_stack: + return False + if not table: + return True + builder = self.scene.create_actor_builder() + builder.set_physx_body_type("static") + + length, width, thickness = x_max - x_min, y_max - y_min, 0.02 + tabletop_pose = sapien.Pose([0.0, 0.0, -thickness / 2]) # Center the tabletop at z=0 + tabletop_half_size = [length / 2, width / 2, thickness / 2] + builder.add_box_collision( + pose=tabletop_pose, + half_size=tabletop_half_size, + material=self.scene.default_physical_material, + ) + + builder.add_box_visual( + pose=tabletop_pose, + half_size=tabletop_half_size, + material=(1, 1, 1), + ) + table = builder.build("table") + table.set_pose(sapien.Pose(p=[(x_min + x_max) / 2, (y_min + y_max) / 2, z], q=[0, 0, 0, 1])) + return True + + def load_logo(): + name = "rbt.glb" + scale = (0.6, ) * 3 + builder = self.scene.create_actor_builder() + builder.set_physx_body_type("static") + builder.add_multiple_convex_collisions_from_file(filename=name, scale=scale) + builder.add_visual_from_file(filename=name, scale=scale) + mesh = builder.build(name="logo") + mesh.set_pose(sapien.Pose([0, -1.37182, 0.991556], [-4.88642e-06, 4.02623e-06, 0.348843, 0.937181])) + + create_table() + + if logo: + load_logo() + y_max -= 0.5 + + sum_x, sum_y, max_y, max_z = x_min, y_max - padding, 0, 0 + batch = [] + for cnt, (name, idx, mid, tagged, t, height) in enumerate(tqdm(obj_list)): + if t == "obj": + cfg = Path(f"./assets/objects/{idx}_{name}/model_data{mid}.json") + if not cfg.exists(): + print(f"WARNING: {idx}_{name}/{mid} not found") + continue + with open(cfg, "r", encoding="utf-8") as f: + cfg = json.load(f) + w, h, tall = ( + cfg["extents"][0] * cfg["scale"][0], + cfg["extents"][2] * cfg["scale"][2], + cfg["extents"][1] * cfg["scale"][1], + ) + else: + w, h, tall, z_off = ( + self.messy_item_info["radius"][f"{name}_{idx}"] * 2, + self.messy_item_info["radius"][f"{name}_{idx}"] * 2, + self.messy_item_info["z_max"][f"{name}_{idx}"] - self.messy_item_info["z_offset"][f"{name}_{idx}"], + self.messy_item_info["z_offset"][f"{name}_{idx}"], + ) + if sum_y - padding - h < y_min or sum_x + padding > x_max or cnt == len(obj_list) - 1: + for x, y, zz, (n, i, m, tg, tp, h) in tqdm(batch): + if tp == "obj": + success = self.check_obj(n, i, m, pose=[x, sum_y - max_y / 2, zz], anno=anno) + else: + success = self.check_urdf(n, i, d_range=50, pose=[x, sum_y - max_y / 2, zz]) + batch = [] + sum_y -= max_y + padding + max_y = 0 + + if sum_y - padding - h < y_min: + sum_y = y_max - padding + # z += max_z + 0.01 + # z += 0.3 + # z -= 0.3 + z -= 0.3 + x_min -= 0.25 + x_max += 0.25 + if not create_table(): + return obj_list[cnt:] + max_z = 0 + sum_x = x_min + + if t == "obj": + batch.append((sum_x + padding + w / 2, h, z, (name, idx, mid, tagged, t, h))) + else: + batch.append(( + sum_x + padding + w / 2, + h, + z - z_off, + (name, idx, mid, tagged, t, h), + )) + + sum_x += w + padding + max_y = max(max_y, h) + max_z = max(tall, max_z) + return [] + + def test_obj(self): + try: + self.create_scene(viewer=True) + self.rendered = True + except: + self.create_scene(viewer=False) + self.rendered = False + self.create_table_and_wall() + + if self.viewer is not None: + self.viewer.set_camera_pose(self.camera.get_pose()) + + self.result = [] + test_list_1, test_list_2 = [], [] + for root_path in Path("./assets/objects").iterdir(): + if not root_path.is_dir(): + continue + if re.search(r"^(\d+)_(.*)$", root_path.name) is None: + continue + + new_list = [] + try: + idx, name = root_path.name.split("_", 1) + if name in ["dustbin", "tabletrashbin"]: + continue + collision = [i.name for i in (root_path / "collision").iterdir()] + visual = [i.name for i in (root_path / "visual").iterdir()] + config = [i.name for i in (root_path).iterdir() if i.name.endswith(".json")] + models = set(collision) & set(visual) + for model in models: + modelid = re.search(r"(\d+)", model) + minz = 999.9 + if modelid is not None: + modelid = int(modelid.group(1)) + cfg = Path(f"./assets/objects/{idx}_{name}/model_data{modelid}.json") + if not cfg.exists(): + print(f"WARNING: {idx}_{name}/{modelid} not found") + continue + with open(cfg, "r", encoding="utf-8") as f: + cfg = json.load(f) + # cfg["scale"] = cfg.get("scale", [0.1, 0.1, 0.1]) + size = np.array(cfg["extents"]) * np.array(cfg["scale"]) + 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] + new_list.append([ + name, + idx, + modelid, + f"model_data{modelid}.json" in config, + "obj", + 0.0 + ]) + new_list.sort(key=lambda x: x[2]) + for i in new_list: i[5] = minz + + if name in ['sauce-can', 'french-fries', 'hamburg', 'stapler', 'tea-box', 'coffee-box', 'tissue-box', 'bread', 'toycar', 'playingcards', 'small-speaker', 'cup']: + test_list_1 += new_list + else: + test_list_2 += new_list + # test_list += new_list + except Exception as e: + print(f"WARNING: [{name}_{idx}] failed:", e) + + # self.init_messy() + # for name in self.obj_names: + # for idx in self.messy_item_info["list_of_items"][name]: + # test_list_2.append(( + # name, + # idx, + # "", + # "", + # "urdf", + # self.messy_item_info["z_max"][f"{name}_{idx}"], + # )) + + # test_list_1.sort(key=lambda x: x[5]) + # np.random.seed(42) + # np.random.shuffle(test_list_2) + # test_list_2.sort(key=lambda x: x[5][1]) + # test_list_1 = test_list_1 + # test_list_2 = test_list_2 + + # self.add_robot() + # self.run(500) + # self.block() + print(f"{len(test_list_1)=}, {len(test_list_2)=}") + # test_list_1 = test_list_1 + test_list_2 + test_list_1 = test_list_1 + test_list_2 + test_list_1.sort(key=lambda x: x[5]) + # np.random.shuffle(test_list_1) + # test_list_1_idx = np.random.choice(np.arange(len(test_list_1)), size=250, replace=False) + # test_list_1 = [i for idx, i in enumerate(test_list_1) if idx in test_list_1_idx] + # test_list_1, test_list_2 = [], [] + + # self.generate_in(test_list_1, -0.5, 0.5, -2.2, -1.1, z=1.0, logo=True) + if self.rendered: + test_list_1 = test_list_1[:50] + print(test_list_1) + # res = self.generate_in(test_list_1, -1.25, 1.25, -1.8, -0.4, table=False, max_z_stack=5) + res = self.generate_in(test_list_1, -1.2, 1.2, -1.8, -0.4, table=False, max_z_stack=5) + print('rest', len(res)) + # self.block() + # list_2 = self.generate_in(test_list_2, 1.7, 2.4, -3, -0.5, 0.2, max_z_stack=5) + # list_2 = self.generate_in(list_2, -2.4, -1.7, -3, -0.5, 0.2, max_z_stack=5) + # list_2 = self.generate_in(list_2, -2.4, 2.4, -4, -3.5, 0.4, max_z_stack=5) + + # list_2 = self.generate_in(test_list_2[:2], 1.7, 2.4, -3, -0.5, 0.2, max_z_stack=1) + # list_2 = self.generate_in(test_list_2[:2], -2.4, -1.7, -3, -0.5, 0.2, max_z_stack=1) + # list_2 = self.generate_in(test_list_2[:2], -2.4, 2.4, -4, -3.5, 0.4, max_z_stack=1) + # self.block() + # x_max = 1 + # sum_x = -x_max + # sum_y, max_y = -0.2, 0 + # padding = 0.05 + # for cnt, (name, idx, mid, tagged) in enumerate(tqdm(test_list_1)): + # cfg = Path(f'./assets/objects/{idx}_{name}/model_data{mid}.json') + # if not cfg.exists(): + # print(f'WARNING: {idx}_{name}/{mid} not found') + # continue + # with open(cfg, 'r', encoding='utf-8') as f: + # cfg = json.load(f) + # w, h = cfg['extents'][0] * cfg['scale'][0], cfg['extents'][2] * cfg['scale'][2] + # if sum_x + padding + w > x_max: + # sum_x = -x_max + # sum_y -= max_y + padding + # max_y = 0 + + # success = self.check_obj(name, idx, mid, pose=[sum_x+padding+w/2, sum_y-h/2, 0.743]) + # sum_x += w + padding + # max_y = max(max_y, h) + + # self.result.append({ + # 'name': f'{idx}_{name}', + # 'id': mid, + # 'tagged': tagged, + # 'stable': success + # }) + # with open('result.jsonl', 'a', encoding='utf-8') as f: + # f.write(json.dumps(self.result[-1]) + '\n') + # with open('success.txt', 'a', encoding='utf-8') as f: + # f.write( + # f'{idx}_{name:<15}/{mid:2d} 标定:{"是" if tagged else "否"} 稳定:{"是" if success else "否"}\n') + + # if cnt > 0 and cnt % 20 == 0: + # self.scene.clear() + # time.sleep(2) + # self.create_table_and_wall() + # self.block() + self.run(no_step=True) + self.take_picture('./script/camera.png') + self.block() + + +import os + + +def cpy(): + models = [] + with open("./success.txt", "r", encoding="utf-8") as f: + lines = [i.strip() for i in f.readlines()] + for i in lines: + i_split = i.split("_") + models.append(("_".join(i_split[:-1]), i_split[-1], i)) + + for name, idx, original_name in tqdm(models): + from_path = Path(f"./assets/messy_objects/{original_name}") + to_path = Path(f"./assets/messy_objects_stable/{original_name}") + os.system(f"cp -r {from_path} {to_path}") + + with open("./assets/messy_objects/list.json", "r", encoding="utf-8") as f: + metadata = json.load(f) + + list_of_items = {} + for name, idx, original_name in models: + if name not in list_of_items: + list_of_items[name] = [] + list_of_items[name].append(idx) + + new_metadata = { + "item_names": list(set([n[0] for n in models])), + "list_of_items": list_of_items, + "radius": { + n[2]: metadata["radius"][n[2]] + for n in models + }, + "z_offset": { + n[2]: metadata["z_offset"][n[2]] + for n in models + }, + "z_max": { + n[2]: metadata["z_max"][n[2]] + for n in models + }, + } + + with open("./assets/messy_objects_stable/list.json", "w", encoding="utf-8") as f: + json.dump(new_metadata, f, ensure_ascii=False, indent=4) + + +def cfg(): + result = [] + with open("result.jsonl", "r", encoding="utf-8") as f: + for i in f.readlines(): + result.append(json.loads(i.strip())) + root_path = Path("./assets/objects") + for res in result: + res_cfg = root_path / res["name"] / f'model_data{res["id"]}.json' + if res_cfg.exists(): + with open(res_cfg, "r", encoding="utf-8") as f: + cfg = json.load(f) + cfg["stable"] = res["stable"] + with open(res_cfg, "w", encoding="utf-8") as f: + json.dump(cfg, f, ensure_ascii=False, indent=4) + else: + print(f'WARNING: {res["name"]}/{res["id"]} not found') + +if __name__ == "__main__": + helper = Helper() + helper.test_obj() + # cpy() + # cfg() +# pass + +# all_items = [ +# "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", + +# "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" +# ] + +# # # Stricter groups based on high visual/shape similarity +# strict_groups = [ +# # Groups from the user's example +# ["plate", "003_plate"], +# ["toy_car", "057_toycars"], +# ["remote", "079_remotecontrol"], +# ["marker", "058_markpen", "pencil"], +# ["can", "071_cans"], +# ["mug", "039_mug"], + +# # Additional groups based on clear, direct similarities, +# # trying to match the style and granularity of the examples. + +# # Direct L1 to L2 counterparts or very similar items +# ["bottle", "001_bottle"], +# ["bowl", "002_bowl"], +# ["brush", "083_brush"], +# ["clock", "046_alarm-clock"], # "alarm-clock" is a type of clock +# ["hammer", "020_hammer"], +# ["notebook", "092_notebook"], # L1 "notebook" matches L2 "notebook" +# ["pot", "060_kitchenpot"], # "kitchenpot" is a type of pot +# ["tissue", "023_tissue-box"], # "tissue" and "tissue-box" are directly related + +# # Small groups of highly similar items from L1 and/or L2 +# ["chip_can", "025_chips-tub"], # Both are tube-shaped snack containers +# ["slipper", "sneaker", "041_shoe"], # All are types of footwear +# ["spoon", "033_fork", "034_knife"], # Cutlery items +# ["steel_tape", "tape"], # Types of tape +# ["drinkbox", "068_boxdrink"], # Drinks in boxes +# ["091_kettle", "009_kettle"], # Both are kettles +# ["055_small-speaker", "098_speaker"], # Types of speakers +# ["035_apple", "103_fruits"], # Fruits +# ["054_baguette", "075_bread"], # Types of bread +# ["050_bell", "111_callbell"], # Types of bells +# ["004_fluted-block", "086_woodenblock", "108_block"], # Types of blocks + +# # Grouping L2 items that are similar concepts, or direct matches not yet covered +# ["021_cup", "022_cup-with-liquid"], # Cups +# ["112_tea-box", "113_coffee-box"], # Specific types of boxes +# ["037_box", "042_wooden_box", "062_plasticbox", "007_shoe_box"], # General boxes + +# ["019_coaster", "008_tray"], +# ["036_cabinet", "040_rack", "014_bookcase", "013_dumbbell-rack"], # Furniture/storage units +# ["063_tabletrashbin", "011_dustbin"], # Trash receptacles +# ["074_displaystand", "078_phonestand"], +# ["110_basket", "076_breadbasket"], +# ] + +# similar_items_dict = {item: set() for item in all_items} + +# for group in strict_groups: +# # Ensure all items in defined groups are known (they should be from all_items) +# for item_in_group in group: +# if item_in_group not in similar_items_dict: +# # This case should ideally not happen if groups only contain items from all_items +# print(f"Warning: Item '{item_in_group}' in a group is not in the master list of all_items.") +# continue # Skip if item not in master list, or handle as error + +# for item_in_group in group: +# if item_in_group in similar_items_dict: # Process only if item is in master list +# # Add all other items from this specific group as similar +# for other_item_in_group in group: +# if item_in_group != other_item_in_group: +# similar_items_dict[item_in_group].add(other_item_in_group) + +# # Convert sets to sorted lists for consistent output +# final_strict_dict = {item: sorted(list(similar_set)) for item, similar_set in similar_items_dict.items()} + +# # Example of how to print the resulting dictionary (optional) +# # import json +# # print(json.dumps(final_strict_dict, indent=2)) + +# # To display the dictionary (optional, for verification) +# import json +# json.dump(final_strict_dict, open('similar_items.json', 'w'), indent=4) diff --git a/script/create_object_data.py b/script/create_object_data.py new file mode 100644 index 0000000000000000000000000000000000000000..c4a168896f804f4eb7f808649bb27b0f1c18bbdf --- /dev/null +++ b/script/create_object_data.py @@ -0,0 +1,1093 @@ +import logging +import argparse +import readline +import importlib +import numpy as np +from pathlib import Path +from copy import deepcopy +import transforms3d as t3d +from threading import Thread, Lock +import trimesh +import trimesh.bounds + +import sys + +sys.path.append(".") +from envs.utils import * + +import sapien +from sapien.render import set_global_config + +render_pause = False + + +class BaseViewer: + scene: sapien.Scene + viewer: sapien.utils.Viewer + + actor: Actor + modelid: str + modelname: str + config_path: Path + EMPTY_CONFIG: dict + POINTS: list[tuple[str, str]] + + def __init__(self): + # create scene and viewer + set_global_config(max_num_materials=50000, max_num_textures=50000) + self.scene = sapien.Scene() + self.scene.set_timestep(1 / 250) + + # initialize viewer with camera position and orientation + self.viewer = None + self.reset() + + def open_viewer(self): + if self.viewer is not None and not self.viewer.closed: + return + self.viewer = self.scene.create_viewer() + self.viewer.set_scene(self.scene) + self.viewer.set_camera_pose(pose=sapien.Pose( + [-0.0096987, -0.19846, 0.0955636], + [0.71241, -0.118063, 0.123576, 0.680634], + )) + + def reset(self): + self.scene.clear() + self.open_viewer() + + # ground + self.scene.add_ground(0) + + # lights + self.scene.set_ambient_light([0.5, 0.5, 0.5]) + shadow = True + # default spotlight angle and intensity + direction_lights = [[[0, 0.5, -1], [0.5, 0.5, 0.5]]] + for direction_light in direction_lights: + self.scene.add_directional_light(direction_light[0], direction_light[1], shadow=shadow) + # default point lights position and intensity + point_lights = [[[1, 0, 1.8], [1, 1, 1]], [[-1, 0, 1.8], [1, 1, 1]]] + for point_light in point_lights: + self.scene.add_point_light(point_light[0], point_light[1], shadow=shadow) + + self.update_render() + + @staticmethod + def trans_mat(to_mat: np.ndarray, from_mat: np.ndarray): + to_rot = to_mat[:3, :3] + from_rot = from_mat[:3, :3] + rot_mat = to_rot @ from_rot.T + + trans_mat = to_mat[:3, 3] - from_mat[:3, 3] + + result = np.eye(4) + result[:3, :3] = rot_mat + result[:3, 3] = trans_mat + result = np.where(np.abs(result) < 1e-5, 0, result) + return result + + @staticmethod + def trans_base( + init_pose_mat: np.ndarray, + now_base_mat: np.ndarray, + init_base_mat: np.ndarray = np.eye(4), + ): + now_pose_mat = np.eye(4) + base_trans_mat = BaseViewer.trans_mat(now_base_mat, init_base_mat) + now_pose_mat[:3, :3] = (base_trans_mat[:3, :3] @ init_pose_mat[:3, :3] @ base_trans_mat[:3, :3].T) + now_pose_mat[:3, 3] = base_trans_mat[:3, :3] @ init_pose_mat[:3, 3] + + p = now_pose_mat[:3, 3] + now_base_mat[:3, 3] + q_mat = now_pose_mat[:3, :3] @ now_base_mat[:3, :3] + return sapien.Pose(p, t3d.quaternions.mat2quat(q_mat)) + + def add_visual_box(self, pose: sapien.Pose, name: str = "box", type: str = "cube"): + global render_pause + modelname = { + # 'functional': 'functional.glb', + # 'contact': 'gripper.glb' + }.get(type, 'base.glb') + modelpath = Path("assets/objects/vis_box") / modelname + + builder = self.scene.create_actor_builder() + builder.set_physx_body_type("static") + builder.add_visual_from_file(filename=str(modelpath)) + builder.set_initial_pose(pose) + builder.set_name(name) + render_pause = True + builder.build() + render_pause = False + + def clear_scene(self): + global render_pause + render_pause = True + self.scene.clear() + render_pause = False + self.update_render() + + def update_render(self): + global render_pause + if not render_pause and not self.viewer.closed: + self.scene.update_render() + self.viewer.render() + + def save_config(self): + with open(self.config_path, "w", encoding="utf-8") as f: + json.dump(self.actor.config, f, ensure_ascii=False, indent=4) + logging.info(f"Config saved to {self.config_path}") + + def main(self, pose, modelname, modelid, inherit_config: dict = None): + ... + + def load_actor(self, pose, inherit_config): + ... + + def update_config(self): + ... + + def visualize(self): + ... + + +class ObjectViewer(BaseViewer): + EMPTY_CONFIG = { + "center": [], # Center Point + "extents": [], # Bounding Box Extents + "scale": [1.0, 1.0, 1.0], # Scale + "transform_matrix": np.eye(4).tolist(), # Model to Axis Rotation Matrix, fixed as Identity Matrix + + # Target Point Matrix (multiple), special points that can be obtained during planning (e.g., cup handle) + "target_pose": [], + # Grasping Point Matrix (multiple), grasping points are the positions where the robotic arm grasps the object (e.g., cup mouth) + "contact_points_pose": [], + # Functional Point Matrix (multiple), functional points are the positions where the object interacts with other objects (e.g., hammer head) + "functional_matrix": [], + # Orientation Point Matrix (single), orientation points specify the orientation of the object (e.g., shoe head facing left) + "orientation_point": [], + # Grasping Point Groups (same group should have the same position, different directions) + "contact_points_group": [], + # The number should be the same as the number of groups, should be set to true + "contact_points_mask": [], + + "target_point_description": [], # Target Point Description + "contact_points_description": [], # Grasping Point Description + "functional_point_description": [], # Functional Point Description + "orientation_point_description": [], # Orientation Point Description + } + POINTS = [ + ("target_pose", "target"), + ("contact_points_pose", "contact"), + ("functional_matrix", "functional"), + ("orientation_point", "orientation"), + ] + + def __init__(self): + super().__init__() + + def main(self, pose, modelname, modelid, inherit_config: dict = None): + global render_pause + self.modelid = modelid + self.modelname = modelname + self.reset() + self.load_actor(pose, inherit_config) + self.visualize() + + self.active = True + + def render(): + while self.active: + self.update_render() + self.clear_scene() + + self.render = Thread(target=render) + self.render.start() + self.console() + self.active = False + self.render.join() + + def __del__(self): + self.active = False + if hasattr(self, 'render'): + self.render.join() + self.scene.clear() + if self.viewer is not None and not self.viewer.closed: + self.viewer.close() + + def load_actor(self, pose, inherit_config=None, inherit_type: Literal['force', 'advice'] = 'advice'): + modeldir = Path("assets/objects") / self.modelname + modelid = '' if self.modelid is None else self.modelid + self.config_path = modeldir / f"model_data{modelid}.json" + + # try to load as glb + collision = modeldir / "collision" / f"base{modelid}.glb" + visual = modeldir / "visual" / f"base{modelid}.glb" + if not collision.exists() or not visual.exists(): + # try to load as obj + collision = modeldir / "collision" / f"textured{modelid}.obj" + visual = modeldir / "visual" / f"textured{modelid}.obj" + + if not collision.exists() or not visual.exists(): + logging.error( + f"Model files not found in {modeldir}({modelid}): " + f"collision {collision.exists()}, visual {visual.exists()}" + ) + return False + + if self.config_path.exists(): + try: + actor_config = json.load(open(self.config_path, "r", encoding="utf-8")) + if len(actor_config['orientation_point']) > 1: + actor_config['orientation_point'] = [actor_config['orientation_point']] + except json.JSONDecodeError: + logging.warning(f"Invalid JSON in {self.config_path}, using empty config.") + actor_config = None + else: + actor_config = None + + if actor_config is None: + if inherit_config is None: + actor_config = deepcopy(self.EMPTY_CONFIG) + else: + actor_config = deepcopy(inherit_config) + else: + if inherit_config is not None and inherit_type == 'force': + actor_config = deepcopy(inherit_config) + else: + actor_config = actor_config + actor_config.update(self.get_shape_data(collision)) + + scale = actor_config['scale'] + builder = self.scene.create_actor_builder() + builder.set_physx_body_type("dynamic") + builder.add_multiple_convex_collisions_from_file(filename=str(collision), scale=scale) + builder.add_visual_from_file(filename=str(visual), scale=scale) + builder.set_initial_pose(pose) + mesh = builder.build(name=f'{self.modelname}({self.modelid})') + self.actor = Actor(mesh, actor_config) + return True + + def get_shape_data(self, modelpath: Path): + with open(modelpath, "rb") as file_obj: + mesh: trimesh.Geometry = trimesh.load( + file_obj, file_type=modelpath.suffix.strip(".")) + + box: trimesh.primitives.Box = mesh.bounding_box_oriented + return { + "center": box.centroid.tolist(), # Center Point + "extents": box.extents.tolist(), # Bounding Box Extents + } + + def visualize(self): + for key, name in self.POINTS: + for idx in range(len(self.actor.config.get(key, []))): + self.add_visual_box(pose=self.actor.get_point(name, idx, 'pose'), name=f"{name}_{idx}", type=name) + self.update_render() + + def update_config(self, save: bool = False): + config = deepcopy(self.EMPTY_CONFIG) + config.update(self.actor.config) + for key, _ in self.POINTS: + config[key] = [] + + actor_mat = self.actor.get_pose().to_transformation_matrix() + + def get_mat(entity: sapien.Entity): + nonlocal config, actor_mat + mat = entity.get_pose().to_transformation_matrix() + p = actor_mat[:3, :3].T @ (mat[:3, 3] - actor_mat[:3, 3]) + mat[:3, 3] = p / config["scale"] + mat[:3, :3] = actor_mat[:3, :3].T @ mat[:3, :3] + return np.around(mat, 5) + + for entity in self.scene.get_all_actors(): + for key, name in self.POINTS: + if entity.get_name().startswith(name): + config[key].append(get_mat(entity).tolist()) + + self.actor.config = config + if save: + self.save_config() + + def reset_scale(self, scale): + if len(scale) != 3: + scale = [scale[0], scale[0], scale[0]] + self.actor.config["scale"] = scale + self.update_config() + logging.info("Reloading scene, please wait for about 10 seconds...") + self.reset() + self.load_actor(self.actor.get_pose(), self.actor.config) + self.visualize() + + @staticmethod + def parse_point(cmd: str, req_id: bool = True): + parse_map = { + 'c': 'contact', + 't': 'target', + 'f': 'functional', + 'o': 'orientation', + 'contact': 'contact', + 'target': 'target', + 'functional': 'functional', + 'orientation': 'orientation' + } + if cmd.strip() == '': + cmd = input(" >> (t)arget, (c)ontact, (f)unctional, (o)rientation:") + cmd = cmd.strip().split(" ") + if req_id: + try: + type, pid = parse_map[cmd[0]], int(cmd[1]) + except (IndexError, ValueError, KeyError): + return None, None + return type, pid + else: + if len(cmd) != 1: + return None + return parse_map.get(cmd[0], None) + + def get_points(self, type: str) -> list[sapien.Entity]: + points = [] + for entity in self.scene.get_all_actors(): + if entity.get_name().startswith(type): + points.append(entity) + return points + + def get_next_id(self, type: str): + points = self.get_points(type) + max_id = -1 + for p in points: + max_id = max(max_id, int(p.get_name().split("_")[-1])) + return max_id + 1 + + def console(self): + global render_pause + modified = 0 + try: + while not self.viewer.closed: + cmd = input("Input command: ") + if self.viewer.closed: + logging.warning("Viewer has been closed manually.") + cmd = input("Please choose to reopen, exit with save or exit without save: (r/s/e) ") + cmd = cmd.strip().lower() + if cmd in ['r', 'reopen']: + self.open_viewer() + if cmd in ['s', 'save']: + self.update_config(True) + break + if cmd in ['e', 'exit']: + break + + modified += 1 + if cmd == "save": + self.update_config(True) + modified = 0 + elif cmd[:6] == "resize": + """ + Usage: + resize : Set scaling along x, y, z axes + resize : Uniformly scale all three axes + Example: + resize 0.1 + """ + args = cmd[7:].strip().split(" ") + if len(args) == 1: + size = float(args[0]) + self.reset_scale((size, size, size)) + elif len(args) == 3: + x_size = float(args[0]) + y_size = float(args[1]) + z_size = float(args[2]) + self.reset_scale((x_size, y_size, z_size)) + modified = 0 + elif cmd[:6] == "create": + """ + Usage: + create : Create (t)arget, (c)ontact, (f)unctional, (o)rientation point + create: Waits for input of point name + Example: + create t + create f + """ + type = self.parse_point(cmd[6:], req_id=False) + if type is None: + logging.warning("Invalid type.") + continue + pid = self.get_next_id(type) + if type == "orientation" and pid > 0: + logging.warning("The orientation point is unique, please modify the existing one.") + else: + self.add_visual_box(self.actor.get_pose(), name=f"{type}_{pid}", type=type) + logging.info(f"Successfully created {type}_{pid}") + elif cmd[:5] == "clone": + """ + Usage: + clone : Clone a specified type and ID point in place + clone: Waits for input of point type and ID + Example: + clone t 1: Clones target_1 to create a new target point (e.g., target_2) + """ + type, idx = self.parse_point(cmd[5:], req_id=True) + if type is None or idx is None: + logging.warning("Invalid type or id.") + continue + for entity in self.scene.get_all_actors(): + if entity.get_name() == cmd and "_" in cmd: + type = cmd.split("_")[0] + if type == "orientation": + logging.warning("Orientation point is unique, cloning not supported!") + else: + pid = self.get_next_id(type) + self.add_visual_box(entity.get_pose(), name=f"{type}_{pid}", type=type) + logging.info(f"Successfully cloned {type}_{idx} to {type}_{pid}") + elif cmd[:6] == "rotate": + """ + Usage: + rotate : Rotate a specified contact point around its own axis by a given interval, generating points belonging to the same group + Example: + 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 + """ + cmd = cmd[6:].strip().split(" ") + if len(cmd) != 3: + continue + + name, axis, interval = cmd + if not name.isdigit(): + logging.warning("Invalid id, must be a number.") + continue + name = int(name) + + axis = { + "x": [1, 0, 0], + "y": [0, 1, 0], + "z": [0, 0, 1], + "r": [1, 0, 0], + "g": [0, 1, 0], + "b": [0, 0, 1], + }.get(axis, None) + if axis is None: + continue + axis = np.array(axis) + + interval = int(interval) + for entity in self.scene.get_all_actors(): + if entity.get_name() == f"contact_{name}": + pos_mat = entity.get_pose().to_transformation_matrix() + group_list = [name] + for i in range(interval, 360, interval): + pid = self.get_next_id("contact") + new_mat = np.eye(4) + new_mat[:3, 3] = pos_mat[:3, 3] + + new_rot = axis * np.radians(i) + rot_mat = t3d.euler.euler2mat(new_rot[0], new_rot[1], new_rot[2]) + new_mat[:3, :3] = pos_mat[:3, :3] @ rot_mat + + pose = sapien.Pose( + new_mat[:3, 3], + t3d.quaternions.mat2quat(new_mat[:3, :3]), + ) + self.add_visual_box(pose, name=f"contact_{pid}", type="contact") + group_list.append(pid) + self.actor.config["contact_points_group"].append(group_list) + self.actor.config["contact_points_mask"].append(True) + logging.info(f"Successfully rotated contact_{name} group, created {len(group_list)} points") + break + elif cmd[:5] == "align": + """ + Usage: + align: Aligns all group points' positions to the first point in the group + """ + concat_points = {int(i.get_name().split("_")[-1]): i for i in self.get_points("contact")} + for group in self.actor.config["contact_points_group"]: + base = concat_points[group[0]] + base_p = base.get_pose().p + for pt in group[1:]: + concat_points[pt].set_pose(sapien.Pose(base_p, concat_points[pt].get_pose().q)) + logging.info(f"Aligning group with {', '.join([str(i) for i in group[1:]])} to {group[0]}") + elif cmd[:6] == "remove": + """ + Usage: + remove : Removes a point with the specified name + remove: Waits for input of point name + Example: + remove t 0 + """ + type, idx = self.parse_point(cmd[6:], req_id=True) + if type is None or idx is None: + logging.warning("Invalid type or id.") + continue + + for entity in self.scene.get_all_actors(): + if entity.get_name() == f'{type}_{idx}': + render_pause = True + self.scene.remove_actor(entity) + render_pause = False + logging.info(f"Successfully removed {type}_{idx}") + break + elif cmd == "exit": + if modified > 1: + cmd = input( + f'You have made {modified-1} changes without save, do you want to save them? (y/n/others to abort)' + ) + if cmd.strip().lower() == 'y': + self.update_config(True) + break + elif cmd.strip().lower() == 'n': + break + else: + logging.info("Operation has been aborted.") + else: + break + else: + modified -= 1 + except KeyboardInterrupt: + pass + + +class URDFViewer(BaseViewer): + EMPTY_CONFIG = { + "scale": 1.0, # Scale + "transform_matrix": np.eye(4).tolist(), + # Expected loading position to model actual pose transformation matrix, for example: + # transform_matrix @ cube's bottom center point pose = cube pose + "init_qpos": [], # Initial joint state + # Marker point matrix (multiple), marker points are special points that can be accessed during planning (e.g., cup handle) + "target_points": [], + # Grasping point matrix (multiple), grasping points are the positions where the robotic arm grasps the object (e.g., cup mouth) + "contact_points": [], + # Functional point matrix (multiple), functional points are the positions where the object interacts with other objects (e.g., hammer head) + "functional_points": [], + # Orientation point matrix (single), orientation points specify the orientation of the object (e.g., shoe head facing left) + "orientation_point": [], + # Grasping point groups (same group should have the same position, different directions) + "contact_points_group": [], + # The number should be the same as the number of groups, should be set to true + "contact_points_mask": [], + + "target_points_description": [], # Marker point description + "contact_points_description": [], # Grasping point description + "functional_points_description": [], # Functional point description + "orientation_point_description": [], # Orientation point description + } + """ + For each point: + { + "matrix": np.eye(4) # 4x4 transformation matrix + "base" : "base_name" # Base link name + } + """ + POINTS = [ + ("target_points", "target"), + ("contact_points", "contact"), + ("functional_points", "functional"), + ("orientation_point", "orientation"), + ] + + def __init__(self): + super().__init__() + + def main(self, pose, modelname, modelid, inherit_config: dict = None): + self.modelid = modelid + self.modelname = modelname + self.reset() + self.load_actor(pose, inherit_config) + self.visualize() + + self.active = True + + def render(): + while self.active and not self.viewer.closed: + self.update_render() + self.clear_scene() + + self.render = Thread(target=render) + self.render.start() + self.console() + self.active = False + self.render.join() + + def __del__(self): + self.active = False + if hasattr(self, 'render'): + self.render.join() + self.scene.clear() + if self.viewer is not None and not self.viewer.closed: + self.viewer.close() + + def load_actor(self, pose, inherit_config=None, inherit_type: Literal['force', 'advice'] = 'advice'): + modeldir = Path("assets/objects") / self.modelname / str(self.modelid) + self.config_path = modeldir / f"model_data.json" + + if self.config_path.exists(): + try: + actor_config = json.load(open(self.config_path, "r", encoding="utf-8")) + except json.JSONDecodeError: + logging.warning(f"Invalid JSON in {self.config_path}, using empty config.") + actor_config = None + else: + actor_config = None + + if actor_config is None: + if inherit_config is None: + actor_config = deepcopy(self.EMPTY_CONFIG) + else: + actor_config = deepcopy(inherit_config) + else: + if inherit_config is not None and inherit_type == 'force': + actor_config = deepcopy(inherit_config) + else: + actor_config = actor_config + + loader: sapien.URDFLoader = self.scene.create_urdf_loader() + loader.scale = actor_config["scale"] + loader.fix_root_link = False + loader.load_multiple_collisions_from_file = True + actor: sapien.physx.PhysxArticulation = loader.load_multiple(str(modeldir / "mobility.urdf"))[0][0] + actor.set_name(f"{self.modelname}({self.modelid})") + actor.set_pose(self.get_real_pose(pose, np.array(actor_config.get("transform_matrix", np.eye(4))))) + + self.actor = ArticulationActor(actor, actor_config) + for joint in self.actor.actor.get_joints(): + joint.set_drive_properties( + damping=1000, + stiffness=0, + ) + if (self.actor.config.get("init_qpos") is not None and len(self.actor.config["init_qpos"]) > 0): + self.actor.set_qpos(np.array(self.actor.config["init_qpos"])) + return True + + def get_real_pose(self, pose: sapien.Pose, trans_matrix): + pose_matrix = pose.to_transformation_matrix() + return sapien.Pose( + p=pose_matrix[:3, 3] + trans_matrix[:3, 3], + q=t3d.quaternions.mat2quat(trans_matrix[:3, :3] @ pose_matrix[:3, :3]), + ) + + def visualize(self): + for key, name in self.POINTS: + for idx in range(len(self.actor.config.get(key, []))): + self.add_visual_box(pose=self.actor.get_point(name, idx, 'pose'), + name=f"{name}_{idx}<{self.actor.config[key][idx]['base']}>", + type=name) + self.update_render() + + def get_link(self, link_name: str): + for link in self.actor.actor.get_links(): + if link.get_name() == link_name: + return link + return self.actor.actor + + def get_link_dict(self): + link_dict = {} + for link in self.actor.actor.get_links(): + link_dict[link.get_name()] = link + return link_dict + + def get_base_name(self, point_name: str): + res = re.search(r'(.*?)<(.*?)>', point_name) + return res.group(2) if res else None + + def get_id(self, point_name: str): + res = re.search(r'_(\d+)', point_name) + return int(res.group(1)) if res else None + + def update_config(self, save: bool = False): + config = deepcopy(self.EMPTY_CONFIG) + config.update(self.actor.config) + for key, _ in self.POINTS: + config[key] = [] + + link_dict = self.get_link_dict() + + def get_mat(entity: sapien.Entity, base: str): + nonlocal config, link_dict + mat = entity.get_pose().to_transformation_matrix() + base_link = link_dict.get(base, self.actor) + base_mat = base_link.get_pose().to_transformation_matrix() + + p = base_mat[:3, :3].T @ (mat[:3, 3] - base_mat[:3, 3]) + mat[:3, 3] = p / config["scale"] + mat[:3, :3] = base_mat[:3, :3].T @ mat[:3, :3] + return np.around(mat, 5) + + for entity in self.scene.get_all_actors(): + e_name = entity.get_name() + for key, name in self.POINTS: + if e_name.startswith(name): + base_name = self.get_base_name(e_name) + config[key].append({ + "matrix": get_mat(entity, base_name).tolist(), + "base": base_name, + }) + + self.actor.config = config + if save: + self.save_config() + + def reset_scale(self, scale): + if not isinstance(scale, float) \ + and not isinstance(scale, int): + scale = float(scale[0]) + self.actor.config["scale"] = scale + self.update_config() + logging.info("Reloading scene, please wait for about 10 seconds...") + self.reset() + self.load_actor(self.actor.get_pose(), self.actor.config) + self.visualize() + + @staticmethod + def parse_point(cmd: str, req_id: bool = True): + parse_map = { + 'c': 'contact', + 't': 'target', + 'f': 'functional', + 'o': 'orientation', + 'contact': 'contact', + 'target': 'target', + 'functional': 'functional', + 'orientation': 'orientation' + } + if cmd.strip() == '': + cmd = input(" >> (t)arget, (c)ontact, (f)unctional, (o)rientation:") + cmd = cmd.strip().split(" ") + + if req_id: + try: + if len(cmd) == 2: + type, pid, base = parse_map[cmd[0]], int(cmd[1]), None + else: + type, pid, base = parse_map[cmd[0]], int(cmd[1]), cmd[2] + except (IndexError, ValueError, KeyError): + return None, None, None + return type, pid, base + else: + if len(cmd) != 2: + return None, None + return parse_map.get(cmd[0], None), cmd[1] + + def get_points(self, type: str) -> list[sapien.Entity]: + points = [] + for entity in self.scene.get_all_actors(): + if entity.get_name().startswith(type): + points.append(entity) + return points + + def get_next_id(self, type: str): + points = self.get_points(type) + max_id = -1 + for p in points: + res = re.search('_(\d+)<(.*?)>', p.get_name()) + max_id = max(max_id, int(res.group(1))) + return max_id + 1 + + def console(self): + global render_pause + modified = 0 + try: + while not self.viewer.closed: + cmd = input("Input command: ") + if self.viewer.closed: + logging.warning("Viewer has been closed manually.") + cmd = input("Please choose to reopen, exit with save or exit without save: (r/s/e) ") + cmd = cmd.strip().lower() + if cmd in ['r', 'reopen']: + self.open_viewer() + if cmd in ['s', 'save']: + self.update_config(True) + break + if cmd in ['e', 'exit']: + break + + modified += 1 + if cmd == "save": + self.update_config(True) + modified = 0 + elif cmd[:6] == "resize": + """ + Usage: + resize : Synchronize the scaling of all three axes of the object + Example: + resize 0.1 + """ + args = cmd[7:].strip().split(" ") + size = float(args[0]) + self.reset_scale(size) + modified = 0 + elif cmd == "run": + """ + Get stable points through steps, press Ctrl+C to stop + """ + try: + self.run = True + while True: + pass + except KeyboardInterrupt: + self.run = False + self.actor.config["transform_matrix"] = ( + self.actor.get_pose().to_transformation_matrix().tolist()) + self.actor.config["transform_matrix"][0][3] = 0 + self.actor.config["transform_matrix"][1][3] = 0 + self.update_config(True) + except Exception as e: + logging.warning(f"Error: {e}") + elif cmd == "qpos": + """ + Get current joint state + """ + qpos = self.actor.get_qpos() + self.actor.config["init_qpos"] = qpos.tolist() + self.update_config(True) + elif cmd[:4] == "mass": + ''' + Set joint mass + ''' + mass = cmd[5:].split(' ') + links = [(link.get_name(), link) for link in self.actor.actor.get_links()] + if len(mass) != len(links): + logging.warning(f"Mass list length({len(mass)}) does not match link count({len(links)}).") + continue + links.sort(key=lambda x: x[0]) + self.actor.config['mass'] = {} + idx = 0 + for name, link in links: + if name == 'base': continue + self.actor.config['mass'][name] = float(mass[idx]) + idx += 1 + self.save_config() + elif cmd[:6] == "create": + """ + Usage: + create : Create (t)arget, (c)ontact, (f)unctional, (o)rientation points + create: Wait for point name input + Example: + create t link_1 + """ + type, base = self.parse_point(cmd[6:], req_id=False) + if type is None or base is None: + logging.warning("Invalid type or base.") + continue + + pid = self.get_next_id(type) + if type == "orientation" and pid > 0: + logging.warning("Orientation point is unique, please modify the existing one.") + continue + + base_link = self.get_link(base) + if base_link is None: + logging.warning(f"Base link '{base}' not found.") + else: + self.add_visual_box(self.actor.get_pose(), name=f"{type}_{pid}<{base}>", type=type) + logging.info(f"Successfully created {type}_{pid}") + elif cmd[:6] == "rebase": + """ + Usage: + rebase : Modify the base link of the specified point + Example: + rebase c 0 link1 + """ + type, pid, base = self.parse_point(cmd[6:], req_id=True) + if type is None or pid is None or base is None: + logging.warning("Invalid type, id or base link.") + continue + + for entity in self.get_points(type): + name = entity.get_name() + if name.startswith(f"{type}_{pid}"): + new_name = f"{type}_{pid}<{base}>" + entity.set_name(new_name) + logging.info(f"Successfully rebased {name} to {new_name}") + elif cmd[:5] == "clone": + """ + Usage: + clone : Clone a specified type and ID point in place + clone: Wait for input of point type and ID + Example: + clone t 1: Clone target_1 to create a new target point (e.g., target_2) + """ + type, pid, base = self.parse_point(cmd[5:], req_id=True) + if type is None or pid is None: + logging.warning("Invalid type or id.") + continue + if type == "orientation": + logging.warning("Orientation point is unique, cloning not supported!") + continue + + name = f"{type}_{pid}" + for entity in self.scene.get_all_actors(): + if entity.get_name().startswith(name): + pid = self.get_next_id(type) + base = self.get_base_name(entity.get_name()) + self.add_visual_box(entity.get_pose(), name=f"{type}_{pid}<{base}>", type=type) + logging.info(f"Successfully cloned {name}<{base}> to {type}_{pid}<{base}>") + elif cmd[:6] == "rotate": + """ + Usage: + rotate : Rotate a specified contact point around its own axis by a given interval, generating points belonging to the same group + Example: + 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 + """ + cmd = cmd[7:].strip().split(" ") + if len(cmd) != 3: + continue + + name, axis, interval = cmd + if not name.isdigit(): + logging.warning("Invalid id, must be a number.") + continue + name = int(name) + + axis = { + "x": [1, 0, 0], + "y": [0, 1, 0], + "z": [0, 0, 1], + "r": [1, 0, 0], + "g": [0, 1, 0], + "b": [0, 0, 1], + }.get(axis, None) + if axis is None: + continue + axis = np.array(axis) + + interval = int(interval) + for entity in self.scene.get_all_actors(): + e_name = entity.get_name() + if e_name.startswith(f"contact_{name}"): + pos_mat = entity.get_pose().to_transformation_matrix() + base_name = self.get_base_name(e_name) + group_list = [name] + for i in range(interval, 360, interval): + pid = self.get_next_id("contact") + new_mat = np.eye(4) + new_mat[:3, 3] = pos_mat[:3, 3] + + new_rot = axis * np.radians(i) + rot_mat = t3d.euler.euler2mat(new_rot[0], new_rot[1], new_rot[2]) + new_mat[:3, :3] = pos_mat[:3, :3] @ rot_mat + + pose = sapien.Pose( + new_mat[:3, 3], + t3d.quaternions.mat2quat(new_mat[:3, :3]), + ) + self.add_visual_box(pose, name=f"contact_{pid}<{base_name}>", type="contact") + group_list.append(pid) + self.actor.config["contact_points_group"].append(group_list) + self.actor.config["contact_points_mask"].append(True) + logging.info(f"Successfully rotated {e_name} group, created {len(group_list)} points") + elif cmd[:5] == "align": + """ + Usage: + align: Align all group points' positions to the first point in the group + """ + concat_points = {self.get_id(i.get_name()): i for i in self.get_points("contact")} + for group in self.actor.config["contact_points_group"]: + base = concat_points[group[0]] + base_p = base.get_pose().p + for pt in group[1:]: + concat_points[pt].set_pose(sapien.Pose(base_p, concat_points[pt].get_pose().q)) + logging.info(f"Aligning group with {', '.join([str(i) for i in group[1:]])} to {group[0]}") + elif cmd[:6] == "remove": + """ + Usage: + remove : Remove a point with the specified name + remove: Wait for input of point name + Example: + remove t 0 + """ + type, idx, _ = self.parse_point(cmd[6:], req_id=True) + if type is None or idx is None: + logging.warning("Invalid type or id.") + continue + + for entity in self.get_points(type): + name = entity.get_name() + if name.startswith(f"{type}_{idx}"): + render_pause = True + self.scene.remove_actor(entity) + render_pause = False + logging.info(f"Successfully removed {name}") + break + elif cmd == "exit": + if modified > 1: + cmd = input( + f'You have made {modified-1} changes without save, do you want to save them? (y/n/others to abort)' + ) + if cmd.strip().lower() == 'y': + self.update_config(True) + break + elif cmd.strip().lower() == 'n': + break + else: + logging.info("Operation has been aborted.") + else: + break + else: + modified -= 1 + if cmd != 'help': + logging.info(f"Unknown command: {cmd}") + help_info = "" + except KeyboardInterrupt: + pass + +def auto_loader(model_name: str): + model_dir = Path("./assets/objects/") / model_name + collision = model_dir / "collision" + visual = model_dir / "visual" + + if not collision.exists(): + # URDF + id_list = [ + int(i.name) for i in list(model_dir.iterdir()) \ + if i.is_dir() and i.name != 'visual' + ] + logging.info(f" Found {len(id_list)} valid models: {id_list}") + return URDFViewer(), id_list, sapien.Pose([0, 0, 0], [1, 0, 0, 0]) + else: + collision_list = [ + int(re.search(r'\d+', i.name).group()) \ + for i in list(collision.iterdir()) \ + if i.suffix in ['.obj', '.glb'] + ] + visual_list = [ + int(re.search(r'\d+', i.name).group()) \ + for i in list(visual.iterdir()) \ + if i.suffix in ['.obj', '.glb'] + ] + id_list = list( + set(visual_list) & set(collision_list)) + logging.info(f" Found {len(id_list)} valid models: {id_list}") + return ObjectViewer(), id_list, sapien.Pose([0, 0, 0], [0.707, 0.707, 0, 0]) + + +def main(model_name: str, start: int = 0): + try: + viewer, id_list, init_pose = auto_loader(model_name) + except Exception as e: + logging.error(f"Failed to load model {model_name}: {e}") + return + + for oid in id_list: + if oid < start: + continue + os.environ["MODEL_NAME"] = f"{model_name}/{oid}" + os.environ["MODEL_ID"] = "None" + + inherit_config = None + try: + logging.info(f'Annotating {model_name}({oid})') + viewer.main( + pose=init_pose, + modelname=f'{model_name}', + modelid=oid, + inherit_config=inherit_config) + inherit_config = viewer.actor.config + except KeyboardInterrupt: + break + + +if __name__ == '__main__': + logging.basicConfig(level=logging.INFO, format='[{levelname:^8}] {message}', style="{") + parser = argparse.ArgumentParser(description="Annotation Tool") + parser.add_argument("model_name", type=str, help="Model Name") + parser.add_argument("-s", "--start", type=int, default=0, help="Start ID") + args = parser.parse_args() + main(args.model_name, args.start) \ No newline at end of file diff --git a/script/eval_groot.sh b/script/eval_groot.sh new file mode 100644 index 0000000000000000000000000000000000000000..371c00c8e1fd0b5a10e415426a10ef73453f5d65 --- /dev/null +++ b/script/eval_groot.sh @@ -0,0 +1,40 @@ +#!/bin/bash + +export XLA_PYTHON_CLIENT_MEM_FRACTION=0.4 # ensure GPU < 24G +# 禁用 CUDA,因为 GR00T client 不需要本地 GPU(推理在服务器端) + +# # 简化的参数定义 +# task_name=${1} +# task_config=${2} +# seed=${3} + +# GR00T server 连接参数(可选,有默认值) +# GROOT_HOST=${4:-localhost} # 默认 localhost +# GROOT_PORT=${5:-8811} # 默认 8811(匹配服务端端口) + +# instruction_type(可选,默认是 "unseen") +# INSTRUCTION_TYPE=${6:-unseen} + +gpu_id="${GPU_ID:-0}" # 允许用环境变量 GPU_ID 覆盖 +export CUDA_VISIBLE_DEVICES="${gpu_id}" +echo -e "\033[33mgpu id (to use): ${gpu_id}\033[0m" + +# source .venv/bin/activate +# cd ../.. # move to root +source /mnt/workspace/users/zhangtianle/RoboTwin_utils/RoboTwin/policy/pi0/.venv/bin/activate + +# source .venv/bin/activate +cd /mnt/workspace/users/zhangtianle/RoboTwin_utils/RoboTwin + +which python + +# 注意:GR00T client 不需要本地 GPU(推理在服务器端) + +TORCH_USE_CUDA_DSA=1 CUDA_LAUNCH_BLOCKING=1 PYTHONWARNINGS=ignore::UserWarning \ +python script/groot_simulation_client.py \ + --task_name adjust_bottle \ + --task_config demo_clean \ + --seed 0 \ + --host localhost \ + --port 8811 \ + --save_dir /mnt/workspace/users/lijiayi/GR00T_QwenVLA/outputs_robotwin/eval_result_eepose \ No newline at end of file diff --git a/script/eval_policy.py b/script/eval_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..d1c889590ecea9e4e26a272980386a9c70ee5026 --- /dev/null +++ b/script/eval_policy.py @@ -0,0 +1,389 @@ +# /RoboTwin/script/eval_policy.py +import sys +import os +import subprocess + +sys.path.append("./") +sys.path.append(f"./policy") +sys.path.append("./description/utils") +from envs import CONFIGS_PATH +from envs.utils.create_actor import UnStableError + +import numpy as np +from pathlib import Path +from collections import deque +import traceback + +import yaml +from datetime import datetime +import importlib +import argparse +import pdb + +from generate_episode_instructions import * + +current_file_path = os.path.abspath(__file__) +parent_directory = os.path.dirname(current_file_path) + + +def class_decorator(task_name): + envs_module = importlib.import_module(f"envs.{task_name}") + try: + env_class = getattr(envs_module, task_name) + env_instance = env_class() + except: + raise SystemExit("No Task") + return env_instance + + +def eval_function_decorator(policy_name, model_name): + try: + policy_model = importlib.import_module(policy_name) + return getattr(policy_model, model_name) + except ImportError as e: + raise e + +def get_camera_config(camera_type): + camera_config_path = os.path.join(parent_directory, "../task_config/_camera_config.yml") + + assert os.path.isfile(camera_config_path), "task config file is missing" + + with open(camera_config_path, "r", encoding="utf-8") as f: + args = yaml.load(f.read(), Loader=yaml.FullLoader) + + assert camera_type in args, f"camera {camera_type} is not defined" + return args[camera_type] + + +def get_embodiment_config(robot_file): + robot_config_file = os.path.join(robot_file, "config.yml") + with open(robot_config_file, "r", encoding="utf-8") as f: + embodiment_args = yaml.load(f.read(), Loader=yaml.FullLoader) + return embodiment_args + + +def main(usr_args): + current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + task_name = usr_args["task_name"] + task_config = usr_args["task_config"] + ckpt_setting = usr_args["ckpt_setting"] + # checkpoint_num = usr_args['checkpoint_num'] + policy_name = usr_args["policy_name"] + instruction_type = usr_args["instruction_type"] + save_dir = None + video_save_dir = None + video_size = None + + get_model = eval_function_decorator(policy_name, "get_model") + + with open(f"./task_config/{task_config}.yml", "r", encoding="utf-8") as f: + args = yaml.load(f.read(), Loader=yaml.FullLoader) + + args['task_name'] = task_name + args["task_config"] = task_config + args["ckpt_setting"] = ckpt_setting + + embodiment_type = args.get("embodiment") + embodiment_config_path = os.path.join(CONFIGS_PATH, "_embodiment_config.yml") + + with open(embodiment_config_path, "r", encoding="utf-8") as f: + _embodiment_types = yaml.load(f.read(), Loader=yaml.FullLoader) + + def get_embodiment_file(embodiment_type): + robot_file = _embodiment_types[embodiment_type]["file_path"] + if robot_file is None: + raise "No embodiment files" + return robot_file + + with open(CONFIGS_PATH + "_camera_config.yml", "r", encoding="utf-8") as f: + _camera_config = yaml.load(f.read(), Loader=yaml.FullLoader) + + head_camera_type = args["camera"]["head_camera_type"] + args["head_camera_h"] = _camera_config[head_camera_type]["h"] + args["head_camera_w"] = _camera_config[head_camera_type]["w"] + + if len(embodiment_type) == 1: + args["left_robot_file"] = get_embodiment_file(embodiment_type[0]) + args["right_robot_file"] = get_embodiment_file(embodiment_type[0]) + args["dual_arm_embodied"] = True + elif len(embodiment_type) == 3: + args["left_robot_file"] = get_embodiment_file(embodiment_type[0]) + args["right_robot_file"] = get_embodiment_file(embodiment_type[1]) + args["embodiment_dis"] = embodiment_type[2] + args["dual_arm_embodied"] = False + else: + raise "embodiment items should be 1 or 3" + + args["left_embodiment_config"] = get_embodiment_config(args["left_robot_file"]) + args["right_embodiment_config"] = get_embodiment_config(args["right_robot_file"]) + + if len(embodiment_type) == 1: + embodiment_name = str(embodiment_type[0]) + else: + embodiment_name = str(embodiment_type[0]) + "+" + str(embodiment_type[1]) + + save_dir = Path(f"eval_result/{task_name}/{policy_name}/{task_config}/{ckpt_setting}/{current_time}") + save_dir.mkdir(parents=True, exist_ok=True) + + if args["eval_video_log"]: + video_save_dir = save_dir + camera_config = get_camera_config(args["camera"]["head_camera_type"]) + video_size = str(camera_config["w"]) + "x" + str(camera_config["h"]) + video_save_dir.mkdir(parents=True, exist_ok=True) + args["eval_video_save_dir"] = video_save_dir + + # output camera config + print("============= Config =============\n") + print("\033[95mMessy Table:\033[0m " + str(args["domain_randomization"]["cluttered_table"])) + print("\033[95mRandom Background:\033[0m " + str(args["domain_randomization"]["random_background"])) + if args["domain_randomization"]["random_background"]: + print(" - Clean Background Rate: " + str(args["domain_randomization"]["clean_background_rate"])) + print("\033[95mRandom Light:\033[0m " + str(args["domain_randomization"]["random_light"])) + if args["domain_randomization"]["random_light"]: + print(" - Crazy Random Light Rate: " + str(args["domain_randomization"]["crazy_random_light_rate"])) + print("\033[95mRandom Table Height:\033[0m " + str(args["domain_randomization"]["random_table_height"])) + print("\033[95mRandom Head Camera Distance:\033[0m " + str(args["domain_randomization"]["random_head_camera_dis"])) + + print("\033[94mHead Camera Config:\033[0m " + str(args["camera"]["head_camera_type"]) + f", " + + str(args["camera"]["collect_head_camera"])) + print("\033[94mWrist Camera Config:\033[0m " + str(args["camera"]["wrist_camera_type"]) + f", " + + str(args["camera"]["collect_wrist_camera"])) + print("\033[94mEmbodiment Config:\033[0m " + embodiment_name) + print("\n==================================") + + TASK_ENV = class_decorator(args["task_name"]) + args["policy_name"] = policy_name + usr_args["left_arm_dim"] = len(args["left_embodiment_config"]["arm_joints_name"][0]) + usr_args["right_arm_dim"] = len(args["right_embodiment_config"]["arm_joints_name"][1]) + + seed = usr_args["seed"] + + # Use start_seed from scheduler if provided, otherwise compute from seed + if "start_seed" in usr_args and usr_args["start_seed"] is not None: + st_seed = int(usr_args["start_seed"]) + else: + st_seed = 100000 * (1 + seed) + + # Use test_num from scheduler if provided, otherwise default to 100 + if "test_num" in usr_args and usr_args["test_num"] is not None: + test_num = int(usr_args["test_num"]) + else: + test_num = 100 + + suc_nums = [] + topk = 1 + + # Write FINAL_RESULT for scheduler to parse + worker_id = usr_args.get("worker_id", 0) + num_workers = usr_args.get("num_workers", 1) + + model = get_model(usr_args) + st_seed, suc_num = eval_policy(task_name, + TASK_ENV, + args, + model, + st_seed, + test_num=test_num, + video_size=video_size, + instruction_type=instruction_type) + suc_nums.append(suc_num) + + # Print FINAL_RESULT for scheduler to parse + print(f"FINAL_RESULT task={task_name} success={suc_num} total={test_num} worker={worker_id}/{num_workers}") + + topk_success_rate = sorted(suc_nums, reverse=True)[:topk] + + file_path = os.path.join(save_dir, f"_result.txt") + with open(file_path, "w") as file: + file.write(f"Timestamp: {current_time}\n\n") + file.write(f"Instruction Type: {instruction_type}\n\n") + # file.write(str(task_reward) + '\n') + file.write("\n".join(map(str, np.array(suc_nums) / test_num))) + + print(f"Data has been saved to {file_path}") + # return task_reward + + +def eval_policy(task_name, + TASK_ENV, + args, + model, + st_seed, + test_num=100, + video_size=None, + instruction_type=None): + print(f"\033[34mTask Name: {args['task_name']}\033[0m") + print(f"\033[34mPolicy Name: {args['policy_name']}\033[0m") + + expert_check = True + TASK_ENV.suc = 0 + TASK_ENV.test_num = 0 + + now_id = 0 + succ_seed = 0 + suc_test_seed_list = [] + + policy_name = args["policy_name"] + eval_func = eval_function_decorator(policy_name, "eval") + reset_func = eval_function_decorator(policy_name, "reset_model") + + now_seed = st_seed + task_total_reward = 0 + clear_cache_freq = args["clear_cache_freq"] + + args["eval_mode"] = True + + while succ_seed < test_num: + render_freq = args["render_freq"] + args["render_freq"] = 0 + + if expert_check: + try: + TASK_ENV.setup_demo(now_ep_num=now_id, seed=now_seed, is_test=True, **args) + episode_info = TASK_ENV.play_once() + TASK_ENV.close_env() + except UnStableError as e: + # print(" -------------") + # print("Error: ", e) + # print(" -------------") + TASK_ENV.close_env() + now_seed += 1 + args["render_freq"] = render_freq + continue + except Exception as e: + # stack_trace = traceback.format_exc() + # print(" -------------") + # print("Error: ", e) + # print(" -------------") + TASK_ENV.close_env() + now_seed += 1 + args["render_freq"] = render_freq + print("error occurs !") + continue + + if (not expert_check) or (TASK_ENV.plan_success and TASK_ENV.check_success()): + succ_seed += 1 + suc_test_seed_list.append(now_seed) + else: + now_seed += 1 + args["render_freq"] = render_freq + continue + + args["render_freq"] = render_freq + + TASK_ENV.setup_demo(now_ep_num=now_id, seed=now_seed, is_test=True, **args) + episode_info_list = [episode_info["info"]] + results = generate_episode_descriptions(args["task_name"], episode_info_list, test_num) + instruction = np.random.choice(results[0][instruction_type]) + TASK_ENV.set_instruction(instruction=instruction) # set language instruction + + if TASK_ENV.eval_video_path is not None: + ffmpeg = subprocess.Popen( + [ + "ffmpeg", + "-y", + "-loglevel", + "error", + "-f", + "rawvideo", + "-pixel_format", + "rgb24", + "-video_size", + video_size, + "-framerate", + "30", + "-i", + "-", + "-pix_fmt", + "yuv420p", + "-vcodec", + "libx264", + "-crf", + "23", + f"{TASK_ENV.eval_video_path}/episode{TASK_ENV.test_num}.mp4", + ], + stdin=subprocess.PIPE, + ) + TASK_ENV._set_eval_video_ffmpeg(ffmpeg) + + succ = False + reset_func(model) + while TASK_ENV.take_action_cnt < TASK_ENV.step_lim: + observation = TASK_ENV.get_obs() + eval_func(TASK_ENV, model, observation) + if TASK_ENV.eval_success: + succ = True + break + # task_total_reward += TASK_ENV.episode_score + if TASK_ENV.eval_video_path is not None: + TASK_ENV._del_eval_video_ffmpeg() + + # Print final progress bar showing the step at which episode ended + _steps = TASK_ENV.take_action_cnt + _lim = TASK_ENV.step_lim + _pct = _steps / _lim + _bar_width = 30 + _filled = int(_bar_width * _pct) + _bar = "#" * _filled + "-" * (_bar_width - _filled) + print(f"[{_bar}] {_steps}/{_lim} ({_pct*100:.0f}%)") + + if succ: + TASK_ENV.suc += 1 + print("\033[92mSuccess!\033[0m") + else: + print("\033[91mFail!\033[0m") + + now_id += 1 + TASK_ENV.close_env(clear_cache=((succ_seed + 1) % clear_cache_freq == 0)) + + if TASK_ENV.render_freq: + TASK_ENV.viewer.close() + + TASK_ENV.test_num += 1 + + print( + 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" + 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" + ) + # TASK_ENV._take_picture() + now_seed += 1 + + return now_seed, TASK_ENV.suc + + +def parse_args_and_config(): + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=str, required=True) + parser.add_argument("--overrides", nargs=argparse.REMAINDER) + args = parser.parse_args() + + with open(args.config, "r", encoding="utf-8") as f: + config = yaml.safe_load(f) + + # Parse overrides + def parse_override_pairs(pairs): + override_dict = {} + for i in range(0, len(pairs), 2): + key = pairs[i].lstrip("--") + value = pairs[i + 1] + try: + value = eval(value) + except: + pass + override_dict[key] = value + return override_dict + + if args.overrides: + overrides = parse_override_pairs(args.overrides) + config.update(overrides) + + return config + + +if __name__ == "__main__": + from test_render import Sapien_TEST + Sapien_TEST() + + usr_args = parse_args_and_config() + + main(usr_args) diff --git a/script/eval_policy_client.py b/script/eval_policy_client.py new file mode 100644 index 0000000000000000000000000000000000000000..c487d7b8f190d028dbc2b53c360942577ba306c2 --- /dev/null +++ b/script/eval_policy_client.py @@ -0,0 +1,535 @@ +import sys +import os +import subprocess + +sys.path.append("./") +sys.path.append(f"./policy") +sys.path.append("./description/utils") +from envs import CONFIGS_PATH +from envs.utils.create_actor import UnStableError + +import numpy as np +from pathlib import Path +from collections import deque +import traceback + +import yaml +from datetime import datetime +import importlib +import argparse +import pdb + +from generate_episode_instructions import * + + +import sys +import os +import subprocess +import socket +import json +import threading +import time +import random +import traceback +import yaml +from datetime import datetime +import importlib +import argparse +from pathlib import Path +from collections import deque + +import numpy as np +import json +from typing import Any + +current_file_path = os.path.abspath(__file__) +parent_directory = os.path.dirname(current_file_path) + +import numpy as np +import json +from typing import Any +import base64 + +class NumpyEncoder(json.JSONEncoder): + """Enhanced json encoder for numpy types with array reconstruction info""" + def default(self, obj): + if isinstance(obj, np.ndarray): + if obj.dtype == np.float32: + dtype = 'float32' + elif obj.dtype == np.float64: + dtype = 'float64' + elif obj.dtype == np.int32: + dtype = 'int32' + elif obj.dtype == np.int64: + dtype = 'int64' + else: + dtype = str(obj.dtype) + + return { + '__numpy_array__': True, + 'data': base64.b64encode(obj.tobytes()).decode('ascii'), + 'dtype': dtype, + 'shape': obj.shape + } + elif isinstance(obj, np.integer): + return int(obj) + elif isinstance(obj, np.floating): + return float(obj) + elif isinstance(obj, np.bool_): + return bool(obj) + return super().default(obj) + +def numpy_to_json(data: Any) -> str: + """Convert numpy-containing data to JSON string with reconstruction info""" + return json.dumps(data, cls=NumpyEncoder) + +def json_to_numpy(json_str: str) -> Any: + """Convert JSON string back to Python objects with numpy arrays""" + def object_hook(dct): + if '__numpy_array__' in dct: + data = base64.b64decode(dct['data']) + return np.frombuffer(data, dtype=dct['dtype']).reshape(dct['shape']) + return dct + + return json.loads(json_str, object_hook=object_hook) + +def class_decorator(task_name): + envs_module = importlib.import_module(f"envs.{task_name}") + try: + env_class = getattr(envs_module, task_name) + env_instance = env_class() + except: + raise SystemExit("No Task") + return env_instance + + +def eval_function_decorator(policy_name, model_name, conda_env=None): + # conda_env is abandoned + try: + policy_model = importlib.import_module(policy_name) + return getattr(policy_model, model_name) + except ImportError as e: + raise e + + +def get_camera_config(camera_type): + camera_config_path = os.path.join(parent_directory, "../task_config/_camera_config.yml") + + assert os.path.isfile(camera_config_path), "task config file is missing" + + with open(camera_config_path, "r", encoding="utf-8") as f: + args = yaml.load(f.read(), Loader=yaml.FullLoader) + + assert camera_type in args, f"camera {camera_type} is not defined" + return args[camera_type] + + +def get_embodiment_config(robot_file): + robot_config_file = os.path.join(robot_file, "config.yml") + with open(robot_config_file, "r", encoding="utf-8") as f: + embodiment_args = yaml.load(f.read(), Loader=yaml.FullLoader) + return embodiment_args + +class ModelClient: + def __init__(self, host='localhost', port=9999, timeout=30): + self.host = host + self.port = port + self.timeout = timeout + self.sock = None + self._connect() + + def _connect(self): + attempts = 0 + max_attempts = 1000 + retry_delay = 5 + + while attempts < max_attempts: + try: + self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.sock.settimeout(self.timeout) + self.sock.connect((self.host, self.port)) + print(f"🔗 Connected to model server at {self.host}:{self.port}") + return + except Exception as e: + attempts += 1 + if self.sock: + self.sock.close() + if attempts < max_attempts: + print(f"⚠️ Connection attempt {attempts} failed: {str(e)}") + print(f"🔄 Retrying in {retry_delay} seconds...") + time.sleep(retry_delay) + else: + raise ConnectionError( + f"Failed to connect to server after {max_attempts} attempts: {str(e)}" + ) + + def _send_recv(self, data): + """Send request and receive response with numpy array support""" + try: + # Serialize with numpy support + json_data = numpy_to_json(data).encode('utf-8') + + # Send data length and data + self.sock.sendall(len(json_data).to_bytes(4, 'big')) + self.sock.sendall(json_data) + + # Receive and deserialize response + response = self._recv_response() + return response + + except Exception as e: + self.close() + raise ConnectionError(f"Communication error: {str(e)}") + + def _recv_response(self): + """Receive response with numpy array reconstruction""" + # Read response length + len_data = self.sock.recv(4) + if not len_data: + raise ConnectionError("Connection closed by server") + + size = int.from_bytes(len_data, 'big') + + # Read complete response + chunks = [] + received = 0 + while received < size: + chunk = self.sock.recv(min(size - received, 4096)) + if not chunk: + raise ConnectionError("Incomplete response received") + chunks.append(chunk) + received += len(chunk) + + # Deserialize with numpy reconstruction + return json_to_numpy(b''.join(chunks).decode('utf-8')) + + def call(self, func_name=None, obs=None): + response = self._send_recv({"cmd": func_name, "obs": obs}) + return response['res'] + + def close(self): + """Close the connection""" + if self.sock: + try: + self.sock.close() + except: + pass + finally: + self.sock = None + print("🔌 Connection closed") + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + + +def main(usr_args): + current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + task_name = usr_args["task_name"] + task_config = usr_args["task_config"] + ckpt_setting = usr_args["ckpt_setting"] + # checkpoint_num = usr_args['checkpoint_num'] + policy_name = usr_args["policy_name"] + instruction_type = usr_args["instruction_type"] + port = usr_args["port"] + save_dir = None + video_save_dir = None + video_size = None + + policy_conda_env = usr_args.get("policy_conda_env", None) + + get_model = eval_function_decorator(policy_name, "get_model", conda_env=policy_conda_env) + + with open(f"./task_config/{task_config}.yml", "r", encoding="utf-8") as f: + args = yaml.load(f.read(), Loader=yaml.FullLoader) + + args['task_name'] = task_name + args["task_config"] = task_config + args["ckpt_setting"] = ckpt_setting + + embodiment_type = args.get("embodiment") + embodiment_config_path = os.path.join(CONFIGS_PATH, "_embodiment_config.yml") + + with open(embodiment_config_path, "r", encoding="utf-8") as f: + _embodiment_types = yaml.load(f.read(), Loader=yaml.FullLoader) + + def get_embodiment_file(embodiment_type): + robot_file = _embodiment_types[embodiment_type]["file_path"] + if robot_file is None: + raise "No embodiment files" + return robot_file + + with open(CONFIGS_PATH + "_camera_config.yml", "r", encoding="utf-8") as f: + _camera_config = yaml.load(f.read(), Loader=yaml.FullLoader) + + head_camera_type = args["camera"]["head_camera_type"] + args["head_camera_h"] = _camera_config[head_camera_type]["h"] + args["head_camera_w"] = _camera_config[head_camera_type]["w"] + + if len(embodiment_type) == 1: + args["left_robot_file"] = get_embodiment_file(embodiment_type[0]) + args["right_robot_file"] = get_embodiment_file(embodiment_type[0]) + args["dual_arm_embodied"] = True + elif len(embodiment_type) == 3: + args["left_robot_file"] = get_embodiment_file(embodiment_type[0]) + args["right_robot_file"] = get_embodiment_file(embodiment_type[1]) + args["embodiment_dis"] = embodiment_type[2] + args["dual_arm_embodied"] = False + else: + raise "embodiment items should be 1 or 3" + + args["left_embodiment_config"] = get_embodiment_config(args["left_robot_file"]) + args["right_embodiment_config"] = get_embodiment_config(args["right_robot_file"]) + + if len(embodiment_type) == 1: + embodiment_name = str(embodiment_type[0]) + else: + embodiment_name = str(embodiment_type[0]) + "+" + str(embodiment_type[1]) + + save_dir = Path(f"eval_result/{task_name}/{policy_name}/{task_config}/{ckpt_setting}/{current_time}") + save_dir.mkdir(parents=True, exist_ok=True) + + if args["eval_video_log"]: + video_save_dir = save_dir + camera_config = get_camera_config(args["camera"]["head_camera_type"]) + video_size = str(camera_config["w"]) + "x" + str(camera_config["h"]) + video_save_dir.mkdir(parents=True, exist_ok=True) + args["eval_video_save_dir"] = video_save_dir + + # output camera config + print("============= Config =============\n") + print("\033[95mMessy Table:\033[0m " + str(args["domain_randomization"]["cluttered_table"])) + print("\033[95mRandom Background:\033[0m " + str(args["domain_randomization"]["random_background"])) + if args["domain_randomization"]["random_background"]: + print(" - Clean Background Rate: " + str(args["domain_randomization"]["clean_background_rate"])) + print("\033[95mRandom Light:\033[0m " + str(args["domain_randomization"]["random_light"])) + if args["domain_randomization"]["random_light"]: + print(" - Crazy Random Light Rate: " + str(args["domain_randomization"]["crazy_random_light_rate"])) + print("\033[95mRandom Table Height:\033[0m " + str(args["domain_randomization"]["random_table_height"])) + print("\033[95mRandom Head Camera Distance:\033[0m " + str(args["domain_randomization"]["random_head_camera_dis"])) + + print("\033[94mHead Camera Config:\033[0m " + str(args["camera"]["head_camera_type"]) + f", " + + str(args["camera"]["collect_head_camera"])) + print("\033[94mWrist Camera Config:\033[0m " + str(args["camera"]["wrist_camera_type"]) + f", " + + str(args["camera"]["collect_wrist_camera"])) + print("\033[94mEmbodiment Config:\033[0m " + embodiment_name) + print("\n==================================") + + TASK_ENV = class_decorator(args["task_name"]) + args["policy_name"] = policy_name + usr_args["left_arm_dim"] = len(args["left_embodiment_config"]["arm_joints_name"][0]) + usr_args["right_arm_dim"] = len(args["right_embodiment_config"]["arm_joints_name"][1]) + + seed = usr_args["seed"] + + st_seed = 100000 * (1 + seed) + suc_nums = [] + test_num = 100 + topk = 1 + + # model = get_model(usr_args) + model = ModelClient(port=port) + st_seed, suc_num = eval_policy(task_name, + TASK_ENV, + args, + model, + st_seed, + test_num=test_num, + video_size=video_size, + instruction_type=instruction_type, + policy_conda_env=policy_conda_env) + suc_nums.append(suc_num) + + topk_success_rate = sorted(suc_nums, reverse=True)[:topk] + + file_path = os.path.join(save_dir, f"_result.txt") + with open(file_path, "w") as file: + file.write(f"Timestamp: {current_time}\n\n") + file.write(f"Instruction Type: {instruction_type}\n\n") + # file.write(str(task_reward) + '\n') + file.write("\n".join(map(str, np.array(suc_nums) / test_num))) + + print(f"Data has been saved to {file_path}") + # return task_reward + + +def eval_policy(task_name, + TASK_ENV, + args, + model, + st_seed, + test_num=100, + video_size=None, + instruction_type=None, + policy_conda_env=None): + print(f"\033[34mTask Name: {args['task_name']}\033[0m") + print(f"\033[34mPolicy Name: {args['policy_name']}\033[0m") + + expert_check = True + TASK_ENV.suc = 0 + TASK_ENV.test_num = 0 + + now_id = 0 + succ_seed = 0 + suc_test_seed_list = [] + + policy_name = args["policy_name"] + eval_func = eval_function_decorator(policy_name, "eval", conda_env=policy_conda_env) + + now_seed = st_seed + task_total_reward = 0 + clear_cache_freq = args["clear_cache_freq"] + + args["eval_mode"] = True + + while succ_seed < test_num: + render_freq = args["render_freq"] + args["render_freq"] = 0 + + if expert_check: + try: + TASK_ENV.setup_demo(now_ep_num=now_id, seed=now_seed, is_test=True, **args) + episode_info = TASK_ENV.play_once() + TASK_ENV.close_env() + except UnStableError as e: + print(" -------------") + print("Error: ", e) + print(" -------------") + TASK_ENV.close_env() + now_seed += 1 + args["render_freq"] = render_freq + continue + except Exception as e: + stack_trace = traceback.format_exc() + print(" -------------") + print("Error: ", stack_trace) + print(" -------------") + TASK_ENV.close_env() + now_seed += 1 + args["render_freq"] = render_freq + print("error occurs !") + continue + + if (not expert_check) or (TASK_ENV.plan_success and TASK_ENV.check_success()): + succ_seed += 1 + suc_test_seed_list.append(now_seed) + else: + now_seed += 1 + args["render_freq"] = render_freq + continue + + args["render_freq"] = render_freq + + TASK_ENV.setup_demo(now_ep_num=now_id, seed=now_seed, is_test=True, **args) + episode_info_list = [episode_info["info"]] + results = generate_episode_descriptions(args["task_name"], episode_info_list, test_num) + instruction = np.random.choice(results[0][instruction_type]) + TASK_ENV.set_instruction(instruction=instruction) # set language instruction + + if TASK_ENV.eval_video_path is not None: + ffmpeg = subprocess.Popen( + [ + "ffmpeg", + "-y", + "-loglevel", + "error", + "-f", + "rawvideo", + "-pixel_format", + "rgb24", + "-video_size", + video_size, + "-framerate", + "10", + "-i", + "-", + "-pix_fmt", + "yuv420p", + "-vcodec", + "libx264", + "-crf", + "23", + f"{TASK_ENV.eval_video_path}/episode{TASK_ENV.test_num}.mp4", + ], + stdin=subprocess.PIPE, + ) + TASK_ENV._set_eval_video_ffmpeg(ffmpeg) + + succ = False + model.call(func_name='reset_model') + while TASK_ENV.take_action_cnt < TASK_ENV.step_lim: + observation = TASK_ENV.get_obs() + eval_func(TASK_ENV, model, observation) + if TASK_ENV.eval_success: + succ = True + break + # task_total_reward += TASK_ENV.episode_score + if TASK_ENV.eval_video_path is not None: + TASK_ENV._del_eval_video_ffmpeg() + + if succ: + TASK_ENV.suc += 1 + print("\033[92mSuccess!\033[0m") + else: + print("\033[91mFail!\033[0m") + + now_id += 1 + TASK_ENV.close_env(clear_cache=((succ_seed + 1) % clear_cache_freq == 0)) + + if TASK_ENV.render_freq: + TASK_ENV.viewer.close() + + TASK_ENV.test_num += 1 + + print( + 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" + 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" + ) + # TASK_ENV._take_picture() + now_seed += 1 + + return now_seed, TASK_ENV.suc + + +def parse_args_and_config(): + parser = argparse.ArgumentParser() + parser.add_argument("--port", type=int) + parser.add_argument("--config", type=str, required=True) + parser.add_argument("--overrides", nargs=argparse.REMAINDER) + args = parser.parse_args() + + with open(args.config, "r", encoding="utf-8") as f: + config = yaml.safe_load(f) + + config['port'] = args.port + + # Parse overrides + def parse_override_pairs(pairs): + override_dict = {} + for i in range(0, len(pairs), 2): + key = pairs[i].lstrip("--") + value = pairs[i + 1] + try: + value = eval(value) + except: + pass + override_dict[key] = value + return override_dict + + if args.overrides: + overrides = parse_override_pairs(args.overrides) + config.update(overrides) + + return config + + +if __name__ == "__main__": + if os.environ.get("SKIP_RENDER_TEST", "0") != "1": + from test_render import Sapien_TEST + Sapien_TEST() + + usr_args = parse_args_and_config() + + main(usr_args) diff --git a/script/groot_simulation_client.py b/script/groot_simulation_client.py new file mode 100644 index 0000000000000000000000000000000000000000..d6b85c51094ccdcf87ca67d08c66b1441690c47c --- /dev/null +++ b/script/groot_simulation_client.py @@ -0,0 +1,638 @@ + + +import sys +import os +import subprocess +import traceback +from pathlib import Path +from datetime import datetime +from collections import deque +import importlib +import argparse + +import numpy as np +import yaml + +import cv2 + + +# 让 Python 能找到 RoboTwin 的包 +sys.path.append("./") +sys.path.append("./policy") +sys.path.append("./description/utils") + +from envs import CONFIGS_PATH +from envs.utils.create_actor import UnStableError +from generate_episode_instructions import * + +# 引入你在 RoboTwin 里 cp 的 GR00T client 协议实现 +from groot_client_config.service import BaseInferenceClient + + +# ========================= 环境与配置相关工具函数 ========================= + + +current_file_path = os.path.abspath(__file__) +parent_directory = os.path.dirname(current_file_path) + +def class_decorator(task_name): + """根据 task_name 实例化对应 env 类(沿用原 eval_policy_client 逻辑)""" + envs_module = importlib.import_module(f"envs.{task_name}") + try: + env_class = getattr(envs_module, task_name) + env_instance = env_class() + except Exception: + raise SystemExit("No Task") + return env_instance + + +def get_camera_config(camera_type): + """读取 task_config/_camera_config.yml 中的相机配置""" + camera_config_path = os.path.join(parent_directory, "../task_config/_camera_config.yml") + + assert os.path.isfile(camera_config_path), "task config file is missing" + + with open(camera_config_path, "r", encoding="utf-8") as f: + args = yaml.load(f.read(), Loader=yaml.FullLoader) + + assert camera_type in args, f"camera {camera_type} is not defined" + return args[camera_type] + + +def get_embodiment_config(robot_file): + """读取 robot embodiment 的 config.yml""" + robot_config_file = os.path.join(robot_file, "config.yml") + with open(robot_config_file, "r", encoding="utf-8") as f: + embodiment_args = yaml.load(f.read(), Loader=yaml.FullLoader) + return embodiment_args + + +# ========================= 与 GR00T server 通讯的 client ========================= + +class GrootPolicyClient(BaseInferenceClient): + """ + 用 GR00T 的 ZMQ 协议与远程 policy server 通讯的 client。 + + 对应 GR00T 侧的 RobotInferenceServer: + - endpoint "get_action" + - endpoint "get_modality_config" + """ + + def __init__( + self, + host: str = "localhost", + port: int = 5555, + api_token: str | None = None, + use_msgpack: bool = True, + ): + super().__init__(host=host, port=port, api_token=api_token, use_msgpack=use_msgpack) + + def get_action(self, observations: dict) -> dict: + return self.call_endpoint("get_action", observations) + + def get_modality_config(self) -> dict: + return self.call_endpoint("get_modality_config", requires_input=False) + + +# ========================= RoboTwin <-> GR00T 适配函数 ========================= + +def robottwin_obs_to_groot_obs(TASK_ENV, raw_obs: dict) -> dict: + """ + 将 RoboTwin 的 TASK_ENV.get_obs() 输出转成 GR00T policy 期望的 obs 字典。 + """ + obs = {} + obs_dict = raw_obs.get("observation", {}) + + # 统一目标分辨率:与 GR00T robotwin 训练时记录的 original_resolutions 对齐 + TARGET_W, TARGET_H = 640, 480 # (width, height) + + # ====================== 1. 头部相机 ====================== + if "head_camera" in obs_dict and "rgb" in obs_dict["head_camera"]: + head_rgb = obs_dict["head_camera"]["rgb"] # (H, W, 3),当前一般为 (240, 320, 3) + + # 转为 uint8 + if head_rgb.dtype != np.uint8: + head_rgb = (head_rgb * 255).clip(0, 255).astype(np.uint8) + + # 如果分辨率不是 640x480,则先 resize 到 640x480 + h, w = head_rgb.shape[:2] + if (w, h) != (TARGET_W, TARGET_H): + head_rgb = cv2.resize(head_rgb, (TARGET_W, TARGET_H), interpolation=cv2.INTER_LINEAR) + + # 添加时间维度 T=1 -> (1, H, W, 3) + if head_rgb.ndim == 3: + head_rgb = head_rgb[None, ...] + obs["video.image_high"] = head_rgb + else: + raise KeyError( + f"head_camera.rgb not found in observation keys: {list(obs_dict.keys())}" + ) + + # ====================== 2. 手腕相机:兼容两种命名 ====================== + # - 旧:cam_left_wrist / cam_right_wrist(离线数据) + # - 现:left_camera / right_camera(在线 RoboTwin 相机) + left_cam_key = "cam_left_wrist" if "cam_left_wrist" in obs_dict else "left_camera" + right_cam_key = "cam_right_wrist" if "cam_right_wrist" in obs_dict else "right_camera" + + if left_cam_key in obs_dict and "rgb" in obs_dict[left_cam_key]: + left_rgb = obs_dict[left_cam_key]["rgb"] + + if left_rgb.dtype != np.uint8: + left_rgb = (left_rgb * 255).clip(0, 255).astype(np.uint8) + + h, w = left_rgb.shape[:2] + if (w, h) != (TARGET_W, TARGET_H): + left_rgb = cv2.resize(left_rgb, (TARGET_W, TARGET_H), interpolation=cv2.INTER_LINEAR) + + if left_rgb.ndim == 3: + left_rgb = left_rgb[None, ...] + obs["video.image_left_wrist"] = left_rgb + else: + print( + f"[WARN] left wrist camera '{left_cam_key}' not found in observation; " + f"skip sending to GR00T." + ) + + if right_cam_key in obs_dict and "rgb" in obs_dict[right_cam_key]: + right_rgb = obs_dict[right_cam_key]["rgb"] + + if right_rgb.dtype != np.uint8: + right_rgb = (right_rgb * 255).clip(0, 255).astype(np.uint8) + + h, w = right_rgb.shape[:2] + if (w, h) != (TARGET_W, TARGET_H): + right_rgb = cv2.resize(right_rgb, (TARGET_W, TARGET_H), interpolation=cv2.INTER_LINEAR) + + if right_rgb.ndim == 3: + right_rgb = right_rgb[None, ...] + obs["video.image_right_wrist"] = right_rgb + else: + print( + f"[WARN] right wrist camera '{right_cam_key}' not found in observation; " + f"skip sending to GR00T." + ) + + # ====================== 3. 关节状态 ====================== + joint_vec = raw_obs["joint_action"]["vector"] # 例如 (14,) + obs["state.left_arm"] = joint_vec[0:6][None, ...] + obs["state.left_gripper"] = joint_vec[6:7][None, ...] + obs["state.right_arm"] = joint_vec[7:13][None, ...] + obs["state.right_gripper"] = joint_vec[13:14][None, ...] + + # ====================== 4. 文本指令 ====================== + if hasattr(TASK_ENV, "get_instruction"): + instruction = TASK_ENV.get_instruction() + else: + instruction = "do your thing!" + obs["annotation.human.task_description"] = [instruction] + + return obs + +def apply_groot_action_to_env(TASK_ENV, action_dict: dict, n_action_steps: int): + """ + 将 GR00T policy 返回的 action_dict 转换为 RoboTwin env 的动作,并执行若干步。 + + !!! 重要: + - GR00T policy 返回的格式是字典:{"action.left_arm": (H, D1), "action.left_gripper": (H, D2), ...} + - 需要将这些动作合并成 joint vector 格式 + """ + # GR00T 返回的 action 格式:{"action.left_arm": (H, 6), "action.left_gripper": (H, 1), ...} + # 需要合并成完整的 joint vector: (H, 14) + + if "action.left_arm" in action_dict and "action.right_arm" in action_dict: + + left_arm = np.asarray(action_dict["action.left_arm"]) + left_gripper = np.asarray(action_dict["action.left_gripper"]) + right_arm = np.asarray(action_dict["action.right_arm"]) + right_gripper = np.asarray(action_dict["action.right_gripper"]) + + # 新增:处理 (B,H,D) -> (H,D)(单环境 B=1) + if left_arm.ndim == 3 and left_arm.shape[0] == 1: + left_arm = left_arm[0] + if right_arm.ndim == 3 and right_arm.shape[0] == 1: + right_arm = right_arm[0] + if left_gripper.ndim == 3 and left_gripper.shape[0] == 1: + left_gripper = left_gripper[0] + if right_gripper.ndim == 3 and right_gripper.shape[0] == 1: + right_gripper = right_gripper[0] + + # 保持 gripper 是 (H,1) + if left_gripper.ndim == 1: + left_gripper = left_gripper[:, None] + if right_gripper.ndim == 1: + right_gripper = right_gripper[:, None] + + traj = np.concatenate([left_arm, left_gripper, right_arm, right_gripper], axis=-1) # (H,14) + + H = min(n_action_steps, traj.shape[0]) + for t in range(H): + action_vec = traj[t] # (14,) + TASK_ENV.take_action(action_vec) + return + + elif "actions" in action_dict: + # 情况 2:如果返回的是统一的 "actions" 数组(向后兼容) + traj = np.asarray(action_dict["actions"]) # (H, D) + H = min(n_action_steps, traj.shape[0]) + for t in range(H): + action_vec = traj[t] + TASK_ENV.take_action(action_vec) + return + + else: + raise ValueError(f"Unknown action format: {action_dict.keys()}") + + +# ========================= 评测主逻辑(替代原 eval_policy_client 的 eval_policy) ========================= + +def eval_policy_with_groot( + task_name, + TASK_ENV, + args, + st_seed, + test_num=100, + video_size=None, + instruction_type=None, + groot_host: str = "localhost", + groot_port: int = 5555, + groot_api_token: str | None = None, + n_action_steps: int = 4, +): + print(f"\033[34mTask Name: {args['task_name']}\033[0m") + print(f"\033[34mPolicy: GR00T Remote Policy ({groot_host}:{groot_port})\033[0m") + + expert_check = True + TASK_ENV.suc = 0 + TASK_ENV.test_num = 0 + + now_id = 0 + succ_seed = 0 + suc_test_seed_list = [] + + now_seed = st_seed + clear_cache_freq = args["clear_cache_freq"] + + args["eval_mode"] = True + + # 创建 GR00T 的 ZMQ 客户端 + groot_client = GrootPolicyClient( + host=groot_host, + port=groot_port, + api_token=groot_api_token, + use_msgpack=True, + ) + + while succ_seed < test_num: + render_freq = args["render_freq"] + args["render_freq"] = 0 + + # ========== 1. 先跑一次 expert_check(完全复用原逻辑) ========== + if expert_check: + try: + TASK_ENV.setup_demo(now_ep_num=now_id, seed=now_seed, is_test=True, **args) + episode_info = TASK_ENV.play_once() + TASK_ENV.close_env() + except UnStableError as e: + print(" -------------") + print("Error: ", e) + print(" -------------") + TASK_ENV.close_env() + now_seed += 1 + args["render_freq"] = render_freq + continue + except Exception as e: + stack_trace = traceback.format_exc() + print(" -------------") + print("Error: ", stack_trace) + print(" -------------") + TASK_ENV.close_env() + now_seed += 1 + args["render_freq"] = render_freq + print("error occurs !") + continue + + if (not expert_check) or (TASK_ENV.plan_success and TASK_ENV.check_success()): + succ_seed += 1 + suc_test_seed_list.append(now_seed) + else: + now_seed += 1 + args["render_freq"] = render_freq + continue + + args["render_freq"] = render_freq + + # ========== 2. 正式评测 episode:设置 demo + 指令 ========== + TASK_ENV.setup_demo(now_ep_num=now_id, seed=now_seed, is_test=True, **args) + episode_info_list = [episode_info["info"]] + results = generate_episode_descriptions(args["task_name"], episode_info_list, test_num) + instruction = np.random.choice(results[0][instruction_type]) + TASK_ENV.set_instruction(instruction=instruction) # set language instruction + + # ========== 3. 如果需要,打开 ffmpeg 录制 ========== + if TASK_ENV.eval_video_path is not None: + ffmpeg = subprocess.Popen( + [ + "ffmpeg", + "-y", + "-loglevel", + "error", + "-f", + "rawvideo", + "-pixel_format", + "rgb24", + "-video_size", + video_size, + "-framerate", + "10", + "-i", + "-", + "-pix_fmt", + "yuv420p", + "-vcodec", + "libx264", + "-crf", + "23", + f"{TASK_ENV.eval_video_path}/episode{TASK_ENV.test_num}.mp4", + ], + stdin=subprocess.PIPE, + ) + TASK_ENV._set_eval_video_ffmpeg(ffmpeg) + + # ========== 4. 主循环:get_obs -> 调 GR00T get_action -> 多步执行 ========== + succ = False + first_step_of_episode = True # 用于标记是否是episode的第一步 + + while TASK_ENV.take_action_cnt < TASK_ENV.step_lim: + raw_obs = TASK_ENV.get_obs() + groot_obs = robottwin_obs_to_groot_obs(TASK_ENV, raw_obs) + + # 第一次 rollout:强制让 server 清掉所有 env slot 的 IK 历史缓存 + if first_step_of_episode: + print("[RobotwinClient] send meta.reset_mask=True", flush=True) + groot_obs["meta.reset_mask"] = True + first_step_of_episode = False + + action_dict = groot_client.get_action(groot_obs) + apply_groot_action_to_env(TASK_ENV, action_dict, n_action_steps=n_action_steps) + + if TASK_ENV.eval_success: + succ = True + break + + # ========== 5. 清理视频录制 ========== + if TASK_ENV.eval_video_path is not None: + TASK_ENV._del_eval_video_ffmpeg() + + # ========== 6. 统计成功/失败 & 打印 ========== + if succ: + TASK_ENV.suc += 1 + print("\033[92mSuccess!\033[0m") + else: + print("\033[91mFail!\033[0m") + + now_id += 1 + TASK_ENV.close_env(clear_cache=((succ_seed + 1) % clear_cache_freq == 0)) + + if TASK_ENV.render_freq: + TASK_ENV.viewer.close() + + TASK_ENV.test_num += 1 + + print( + f"\033[93m{task_name}\033[0m | " + f"\033[92m{args['task_config']}\033[0m | " + f"Success rate: \033[96m{TASK_ENV.suc}/{TASK_ENV.test_num}\033[0m" + f" => \033[95m{round(TASK_ENV.suc / TASK_ENV.test_num * 100, 1)}%\033[0m," + f" current seed: \033[90m{now_seed}\033[0m\n" + ) + now_seed += 1 + + return now_seed, TASK_ENV.suc + + +# ========================= main + 配置解析(基本沿用原 eval_policy_client) ========================= + +def main(usr_args): + current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + task_name = usr_args["task_name"] + task_config = usr_args["task_config"] + instruction_type = usr_args["instruction_type"] + + # GR00T server 相关参数(可以放在 config 里) + groot_host = usr_args.get("host", "localhost") + groot_port = usr_args.get("port", 5555) + groot_api_token = usr_args.get("api_token", None) + groot_n_action_steps = usr_args.get("n_action_steps", 4) + + save_dir = usr_args.get("save_dir", None) + video_size = None + + with open(f"./task_config/{task_config}.yml", "r", encoding="utf-8") as f: + args = yaml.load(f.read(), Loader=yaml.FullLoader) + + + args["task_name"] = task_name + args["task_config"] = task_config + + embodiment_type = args.get("embodiment") + embodiment_config_path = os.path.join(CONFIGS_PATH, "_embodiment_config.yml") + + with open(embodiment_config_path, "r", encoding="utf-8") as f: + _embodiment_types = yaml.load(f.read(), Loader=yaml.FullLoader) + + def get_embodiment_file(embodiment_type_item): + robot_file = _embodiment_types[embodiment_type_item]["file_path"] + if robot_file is None: + raise "No embodiment files" + return robot_file + + with open(CONFIGS_PATH + "_camera_config.yml", "r", encoding="utf-8") as f: + _camera_config = yaml.load(f.read(), Loader=yaml.FullLoader) + + head_camera_type = args["camera"]["head_camera_type"] + args["head_camera_h"] = _camera_config[head_camera_type]["h"] + args["head_camera_w"] = _camera_config[head_camera_type]["w"] + + if len(embodiment_type) == 1: + args["left_robot_file"] = get_embodiment_file(embodiment_type[0]) + args["right_robot_file"] = get_embodiment_file(embodiment_type[0]) + args["dual_arm_embodied"] = True + elif len(embodiment_type) == 3: + args["left_robot_file"] = get_embodiment_file(embodiment_type[0]) + args["right_robot_file"] = get_embodiment_file(embodiment_type[1]) + args["embodiment_dis"] = embodiment_type[2] + args["dual_arm_embodied"] = False + else: + raise "embodiment items should be 1 or 3" + + args["left_embodiment_config"] = get_embodiment_config(args["left_robot_file"]) + args["right_embodiment_config"] = get_embodiment_config(args["right_robot_file"]) + + if len(embodiment_type) == 1: + embodiment_name = str(embodiment_type[0]) + else: + embodiment_name = str(embodiment_type[0]) + "+" + str(embodiment_type[1]) + + # 简化 save_dir 路径,不再包含 ckpt_setting + if save_dir is None: + raise ValueError("save_dir is required") + else: + save_dir = Path(save_dir) + save_dir = save_dir / current_time + save_dir.mkdir(parents=True, exist_ok=True) + + if args["eval_video_log"]: + video_save_dir = save_dir + camera_config = get_camera_config(args["camera"]["head_camera_type"]) + video_size = str(camera_config["w"]) + "x" + str(camera_config["h"]) + video_save_dir.mkdir(parents=True, exist_ok=True) + args["eval_video_save_dir"] = video_save_dir + + # 输出当前配置,完全沿用原 eval_policy_client + print("============= Config =============\n") + print("\033[95mMessy Table:\033[0m " + str(args["domain_randomization"]["cluttered_table"])) + print( + "\033[95mRandom Background:\033[0m " + + str(args["domain_randomization"]["random_background"]) + ) + if args["domain_randomization"]["random_background"]: + print( + " - Clean Background Rate: " + + str(args["domain_randomization"]["clean_background_rate"]) + ) + print("\033[95mRandom Light:\033[0m " + str(args["domain_randomization"]["random_light"])) + if args["domain_randomization"]["random_light"]: + print( + " - Crazy Random Light Rate: " + + str(args["domain_randomization"]["crazy_random_light_rate"]) + ) + print( + "\033[95mRandom Table Height:\033[0m " + + str(args["domain_randomization"]["random_table_height"]) + ) + print( + "\033[95mRandom Head Camera Distance:\033[0m " + + str(args["domain_randomization"]["random_head_camera_dis"]) + ) + + print( + "\033[94mHead Camera Config:\033[0m " + + str(args["camera"]["head_camera_type"]) + + f", " + + str(args["camera"]["collect_head_camera"]) + ) + print( + "\033[94mWrist Camera Config:\033[0m " + + str(args["camera"]["wrist_camera_type"]) + + f", " + + str(args["camera"]["collect_wrist_camera"]) + ) + print("\033[94mEmbodiment Config:\033[0m " + embodiment_name) + print("\n==================================") + + TASK_ENV = class_decorator(args["task_name"]) + usr_args["left_arm_dim"] = len(args["left_embodiment_config"]["arm_joints_name"][0]) + usr_args["right_arm_dim"] = len(args["right_embodiment_config"]["arm_joints_name"][1]) + + seed = usr_args["seed"] + + st_seed = 100000 * (1 + seed) + suc_nums = [] + test_num = usr_args["test_num"] + topk = 1 + + st_seed, suc_num = eval_policy_with_groot( + task_name, + TASK_ENV, + args, + st_seed, + test_num=test_num, + video_size=video_size, + instruction_type=instruction_type, + groot_host=groot_host, + groot_port=groot_port, + groot_api_token=groot_api_token, + n_action_steps=groot_n_action_steps, + ) + suc_nums.append(suc_num) + + topk_success_rate = sorted(suc_nums, reverse=True)[:topk] + + file_path = os.path.join(save_dir, f"_result.txt") + with open(file_path, "w") as file: + file.write(f"Timestamp: {current_time}\n\n") + file.write(f"Task: {task_name}\n") + file.write(f"Task Config: {task_config}\n") + file.write(f"GR00T Server: {groot_host}:{groot_port}\n") + file.write(f"Instruction Type: {instruction_type}\n\n") + file.write(f"Success Rate: {suc_num}/{test_num} = {suc_num/test_num*100:.2f}%\n") + file.write("\n".join(map(str, np.array(suc_nums) / test_num))) + + # 在终端打印最终的成功率统计 + print("\n" + "="*60) + print("\033[1m========== Evaluation Results ==========\033[0m") + print("="*60) + print(f"\033[93mTask Name:\033[0m {task_name}") + print(f"\033[93mTask Config:\033[0m {task_config}") + print(f"\033[93mGR00T Server:\033[0m {groot_host}:{groot_port}") + print(f"\033[93mInstruction Type:\033[0m {instruction_type}") + print(f"\033[93mTotal Episodes:\033[0m {test_num}") + print(f"\033[93mSuccessful Episodes:\033[0m {suc_num}") + print(f"\033[93mSuccess Rate:\033[0m \033[92m{suc_num}/{test_num} = {suc_num/test_num*100:.2f}%\033[0m") + print("="*60) + print(f"\033[94mResults saved to:\033[0m {file_path}") + print("="*60 + "\n") + + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="GR00T Simulation Client for RoboTwin") + + # ========== 必需的任务参数 ========== + parser.add_argument("--task_name", type=str, required=True, + help="Task name (e.g., beat_block_hammer)") + parser.add_argument("--task_config", type=str, required=True, + help="Task config file name (e.g., demo_clean)") + parser.add_argument("--instruction_type", type=str, default="unseen", # 添加默认值 + help="Instruction type (e.g., language, unseen, default: unseen)") + parser.add_argument("--seed", type=int, required=True, + help="Random seed") + + # ========== GR00T server 连接参数 ========== + parser.add_argument("--host", type=str, default="localhost", + help="GR00T server host (default: localhost)") + parser.add_argument("--port", type=int, default=8811, + help="GR00T server port (default: 8811)") + parser.add_argument("--api_token", type=str, default=None, + help="API token for GR00T server (optional)") + parser.add_argument("--n_action_steps", type=int, default=4, + help="Number of action steps per inference (default: 4)") + + # ========== 可选的保存路径 ========== + parser.add_argument("--save_dir", type=str, default=None, + help="Directory to save evaluation results (default: eval_result/...)") + + # ========== 可选的测试数量 ========== + parser.add_argument("--test_num", type=int, default=100, + help="Number of episodes to test (default: 100)") + + args = parser.parse_args() + + from test_render import Sapien_TEST + Sapien_TEST() + + # 转换为字典格式供 main() 使用 + usr_args = { + "task_name": args.task_name, + "task_config": args.task_config, + "instruction_type": args.instruction_type, + "seed": args.seed, + "host": args.host, + "port": args.port, + "api_token": args.api_token, + "n_action_steps": args.n_action_steps, + "save_dir": args.save_dir, + "test_num": args.test_num, + } + + main(usr_args) \ No newline at end of file diff --git a/script/policy_model_server.py b/script/policy_model_server.py new file mode 100644 index 0000000000000000000000000000000000000000..bf4be63bb30acdef78d58df910a160ba275d9c7f --- /dev/null +++ b/script/policy_model_server.py @@ -0,0 +1,268 @@ +import sys +import os +import subprocess +import socket +import json +import threading +import time +import random +import traceback +import yaml +from datetime import datetime +import importlib +import argparse +from pathlib import Path +from collections import deque + +sys.path.append("./") +sys.path.append(f"./policy") +sys.path.append("./description/utils") +from envs._GLOBAL_CONFIGS import CONFIGS_PATH + +import numpy as np +from typing import Any +import base64 + + +class NumpyEncoder(json.JSONEncoder): + """JSON encoder extension for numpy types, includes reconstruction metadata""" + def default(self, obj): + if isinstance(obj, np.ndarray): + # Determine dtype for reconstruction + if obj.dtype == np.float32: + dtype = 'float32' + elif obj.dtype == np.float64: + dtype = 'float64' + elif obj.dtype == np.int32: + dtype = 'int32' + elif obj.dtype == np.int64: + dtype = 'int64' + else: + dtype = str(obj.dtype) + # Encode array bytes as base64 + return { + '__numpy_array__': True, + 'data': base64.b64encode(obj.tobytes()).decode('ascii'), + 'dtype': dtype, + 'shape': obj.shape + } + elif isinstance(obj, np.integer): + return int(obj) + elif isinstance(obj, np.floating): + return float(obj) + elif isinstance(obj, np.bool_): + return bool(obj) + return super().default(obj) + + +def numpy_to_json(data: Any) -> str: + """Serialize Python data (including numpy arrays) to JSON string""" + return json.dumps(data, cls=NumpyEncoder) + + +def json_to_numpy(json_str: str) -> Any: + """Deserialize JSON string back to Python objects, reconstructing numpy arrays""" + def object_hook(dct): + if '__numpy_array__' in dct: + raw = base64.b64decode(dct['data']) + return np.frombuffer(raw, dtype=dct['dtype']).reshape(dct['shape']) + return dct + return json.loads(json_str, object_hook=object_hook) + + +# --------------------- Model Server Implementation --------------------- +class ModelServer: + def __init__(self, model, host='localhost', port=None): + self.model = model + self.host = host + self.port = port + self.server_socket = None + self.running = False + self.wait_interval = 10 + self.client_threads = [] + + def start(self): + """Start the model server and listen for incoming client connections""" + self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.server_socket.bind((self.host, self.port)) + self.server_socket.settimeout(self.wait_interval) + self.server_socket.listen(5) + self.running = True + + print(f"🚀 Model server started on {self.host}:{self.port}") + print("🔄 Server is waiting for client connections...") + + self._accept_connections() + + def stop(self): + """Stop the server and clean up resources gracefully""" + self.running = False + if self.server_socket: + try: + self.server_socket.close() + except: + pass + for t in self.client_threads: + t.join(timeout=1) + print("🛑 Server has been stopped") + + def _accept_connections(self): + """Accept and handle new client connections""" + while self.running: + try: + client_socket, addr = self.server_socket.accept() + print(f"✅ Client connected from {addr}") + # Handle each client in a separate thread + t = threading.Thread(target=self._handle_client, + args=(client_socket,), daemon=True) + t.start() + self.client_threads.append(t) + except socket.timeout: + continue + except Exception as e: + if self.running: + print(f"⚠️ Error accepting connection: {e}") + break + + def _handle_client(self, client_socket): + """Process requests from a single client""" + with client_socket: + while self.running: + try: + # Read message length header (4 bytes, big-endian) + len_bytes = client_socket.recv(4) + if not len_bytes: + print("🔌 Client disconnected") + break + msg_length = int.from_bytes(len_bytes, 'big') + + # Read the full message based on length + chunks = [] + remaining = msg_length + while remaining > 0: + chunk = client_socket.recv(min(remaining, 4096)) + if not chunk: + raise ConnectionError("Incomplete data received") + chunks.append(chunk) + remaining -= len(chunk) + raw_msg = b''.join(chunks).decode('utf-8') + + # Deserialize JSON to Python, reconstruct any numpy arrays + data = json_to_numpy(raw_msg) + + # Extract command and observation + cmd = data.get("cmd") + obs = data.get("obs") # None if not provided + + # Find corresponding model method + method = getattr(self.model, cmd, None) + if not callable(method): + raise AttributeError(f"No model method named '{cmd}'") + + # Call method with or without obs + result = method(obs) if obs is not None else method() + response = {"res": result} + + # Serialize response and send back with length header + resp_bytes = numpy_to_json(response).encode('utf-8') + client_socket.sendall(len(resp_bytes).to_bytes(4, 'big')) + client_socket.sendall(resp_bytes) + + except (ConnectionResetError, BrokenPipeError): + print("🔌 Client connection lost") + break + except Exception as e: + err = f"Error handling request: {e}" + print(f"⚠️ {err}") + tb = traceback.format_exc() + error_resp = numpy_to_json({"error": err, "traceback": tb}).encode('utf-8') + client_socket.sendall(len(error_resp).to_bytes(4, 'big')) + client_socket.sendall(error_resp) + break + + +# --------------------- Utility Decorators --------------------- +def class_decorator(task_name): + """Instantiate environment class for given task""" + envs_module = importlib.import_module(f"envs.{task_name}") + if not hasattr(envs_module, task_name): + raise SystemExit("Task not found") + return getattr(envs_module, task_name)() + + +def eval_function_decorator(policy_name, model_name, conda_env=None): + """Load a specified function (e.g., get_model) from a policy module""" + module = importlib.import_module(policy_name) + return getattr(module, model_name) + + +def get_camera_config(camera_type): + """Load camera configuration from YAML file""" + cfg_path = os.path.join(os.path.dirname(__file__), "../task_config/_camera_config.yml") + if not os.path.isfile(cfg_path): + raise FileNotFoundError("Camera config file not found") + with open(cfg_path, 'r', encoding='utf-8') as f: + cfg = yaml.safe_load(f) + if camera_type not in cfg: + raise KeyError(f"Camera type '{camera_type}' is not defined") + return cfg[camera_type] + + +def get_embodiment_config(robot_file): + """Load robot embodiment configuration from YAML""" + path = os.path.join(robot_file, "config.yml") + with open(path, 'r', encoding='utf-8') as f: + return yaml.safe_load(f) + + +def main(usr_args): + """Main entry: load model, start server, run indefinitely""" + # Extract basic arguments + policy_name = usr_args['policy_name'] + port = usr_args.get('port') + + # Instantiate model + get_model = eval_function_decorator(policy_name, 'get_model') + model = get_model(usr_args) + + # Start server in background thread + server = ModelServer(model, port=port) + thread = threading.Thread(target=server.start, daemon=True) + thread.start() + + # Keep main thread alive until KeyboardInterrupt + try: + while True: + time.sleep(1) + except KeyboardInterrupt: + print("\n🛑 Shutting down server...") + server.stop() + thread.join() + + +def parse_args_and_config(): + """Parse CLI args and YAML config, merge overrides""" + parser = argparse.ArgumentParser() + parser.add_argument('--port', type=int, help='Port for ModelServer (optional)') + parser.add_argument('--config', type=str, required=True, help='Path to config YAML') + parser.add_argument('--overrides', nargs=argparse.REMAINDER, + help='Override config values') + args = parser.parse_args() + + # Load base config + with open(args.config, 'r', encoding='utf-8') as f: + cfg = yaml.safe_load(f) + cfg['port'] = args.port + + # Parse overrides: --key value pairs + if args.overrides: + it = iter(args.overrides) + for key in it: + val = next(it) + cfg[key.lstrip('--')] = eval(val) if val.isnumeric() else val + return cfg + + +if __name__ == '__main__': + usr_args = parse_args_and_config() + main(usr_args) diff --git a/script/requirements.txt b/script/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..f279ebc0c519199abd558cf5a7de839f325ae6ae --- /dev/null +++ b/script/requirements.txt @@ -0,0 +1,26 @@ +torch==2.4.1 +torchvision +transforms3d==0.4.2 +sapien==3.0.0b1 +scipy==1.10.1 +mplib==0.2.1 +gymnasium==0.29.1 +trimesh==4.4.3 +open3d==0.18.0 +imageio==2.34.2 +pydantic +zarr +openai +huggingface_hub==0.25.0 +h5py +# For Description Generation +azure==4.0.0 +azure-ai-inference +pyglet<2 +wandb +moviepy +imageio +termcolor +av +matplotlib +ffmpeg diff --git a/script/set_log.py b/script/set_log.py new file mode 100644 index 0000000000000000000000000000000000000000..33aae34cf04f3316af7a9210ee5cb53f53a690a6 --- /dev/null +++ b/script/set_log.py @@ -0,0 +1,51 @@ +import os +import sys +import time +import argparse +import logging +from datetime import datetime + + +def setup_logging(output_path: str, log_level=logging.INFO): + """ + 设置日志记录,同时输出到控制台和文件 + + Args: + output_path: 输出目录路径,日志文件将保存在此目录下 + log_level: 日志级别,默认为 INFO + + Returns: + logger: 日志记录器 + log_file: 日志文件路径 + """ + # 创建日志目录 + log_dir = os.path.join(output_path, 'logs') + os.makedirs(log_dir, exist_ok=True) + + # 生成日志文件名(带时间戳) + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") + log_file = os.path.join(log_dir, f"batch_eval_{timestamp}.log") + + # 配置日志格式 + log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' + date_format = '%Y-%m-%d %H:%M:%S' + + # 配置根日志记录器 + logging.basicConfig( + level=log_level, + format=log_format, + datefmt=date_format, + handlers=[ + # 文件处理器 - 记录所有级别的日志 + logging.FileHandler(log_file, encoding='utf-8'), + # 控制台处理器 - 只显示 INFO 及以上级别 + logging.StreamHandler(sys.stdout) + ], + force=True # 强制重新配置,避免重复配置问题 + ) + + logger = logging.getLogger(__name__) + logger.info(f"日志文件已创建: {log_file}") + logger.info(f"日志级别: {logging.getLevelName(log_level)}") + + return logger, log_file \ No newline at end of file diff --git a/script/test_render.py b/script/test_render.py new file mode 100644 index 0000000000000000000000000000000000000000..e36257221bfb7a092561dc93d914f699e4df8113 --- /dev/null +++ b/script/test_render.py @@ -0,0 +1,64 @@ +import sys +import warnings +import os + +warnings.simplefilter(action="ignore", category=FutureWarning) +warnings.simplefilter(action="ignore", category=UserWarning) +current_file_path = os.path.abspath(__file__) +parent_dir = os.path.dirname(current_file_path) + +sys.path.append(os.path.join(parent_dir, "../../tools")) +import numpy as np +import pdb +import json +import torch +import sapien.core as sapien +from sapien.utils.viewer import Viewer +import gymnasium as gym +import toppra as ta +import transforms3d as t3d +from collections import OrderedDict + + +class Sapien_TEST(gym.Env): + + def __init__(self): + super().__init__() + ta.setup_logging("CRITICAL") + try: + self.setup_scene() + print("\033[32mRender Well\033[0m") + except Exception as e: + import traceback + print("\033[31mRender Error\033[0m", e) + traceback.print_exc() + raise + + def setup_scene(self, **kwargs): + """ + Set the scene + - Set up the basic scene: light source, viewer. + """ + self.engine = sapien.Engine() + # declare sapien renderer + from sapien.render import set_global_config + + set_global_config(max_num_materials=50000, max_num_textures=50000) + self.renderer = sapien.SapienRenderer() + # give renderer to sapien sim + self.engine.set_renderer(self.renderer) + + sapien.render.set_camera_shader_dir("rt") + sapien.render.set_ray_tracing_samples_per_pixel(32) + sapien.render.set_ray_tracing_path_depth(8) + sapien.render.set_ray_tracing_denoiser("oidn") + + # declare sapien scene + scene_config = sapien.SceneConfig() + self.scene = self.engine.create_scene(scene_config) + + +if __name__ == "__main__": + a = Sapien_TEST() + + diff --git a/script/update_embodiment_config_path.py b/script/update_embodiment_config_path.py new file mode 100644 index 0000000000000000000000000000000000000000..bf62165597df152077d276f07b6bd74290e5bc3b --- /dev/null +++ b/script/update_embodiment_config_path.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +import os +import sys +import glob + +def print_color(message, color_code): + NC = '\033[0m' + print(f"{color_code}{message}{NC}") + +BLUE = '\033[0;34m' +YELLOW = '\033[0;33m' +GREEN = '\033[0;32m' + + +def prompt_path(): + answer = input("Do you want to manually specify the absolute path to the assets directory? (y/n): ") + if answer.lower() != 'y': + sys.exit(1) + return input("Please enter the absolute path: ") + + +def main(): + # Get current directory + assets_path = os.getcwd() + print_color(f"Current path: {assets_path}", BLUE) + + # Check ./assets/embodiments + if not os.path.isdir(os.path.join(assets_path, 'assets', 'embodiments')): + print_color("Warning: ./assets/embodiments directory not found", YELLOW) + parent = os.path.abspath(os.path.join(assets_path, '..')) + if os.path.isdir(os.path.join(parent, 'assets', 'embodiments')): + print("Found assets/embodiments in parent directory, switching...") + assets_path = parent + os.chdir(assets_path) + print_color(f"Updated path: {assets_path}", BLUE) + else: + print_color("Please ensure you're running this script in the correct directory", YELLOW) + print("Script should be run in the repository root directory containing assets/embodiments") + assets_path = prompt_path() + if not os.path.isdir(os.path.join(assets_path, 'assets', 'embodiments')): + print_color("Error: Cannot find assets/embodiments directory at the specified path", YELLOW) + sys.exit(1) + os.chdir(assets_path) + print_color(f"Switched to: {assets_path}", BLUE) + + # Export environment variable + os.environ['ASSETS_PATH'] = assets_path + print_color(f"Setting environment variable: ASSETS_PATH={assets_path}", BLUE) + + # Counters + count_total = count_updated = count_error = 0 + + # Find *_tmp.yml files + print_color("Searching for configuration template files...", BLUE) + pattern = os.path.join(assets_path, 'assets', 'embodiments', '**', '*_tmp.yml') + config_files = glob.glob(pattern, recursive=True) + + if not config_files: + print_color("No *_tmp.yml files found", YELLOW) + sys.exit(1) + + print_color("Starting to process configuration files...", BLUE) + for tmp_file in config_files: + count_total += 1 + target_file = tmp_file.replace('_tmp.yml', '.yml') + print(f"Processing [{count_total}]: {tmp_file} -> {target_file}") + + try: + with open(tmp_file, 'r') as f: + content = f.read() + + new_content = content.replace('${ASSETS_PATH}', assets_path) + new_content = new_content.replace('$ASSETS_PATH', assets_path) + + with open(target_file, 'w') as f: + f.write(new_content) + + print_color(f" ✓ Successfully replaced ${{ASSETS_PATH}} -> {assets_path}", GREEN) + count_updated += 1 + + if '${ASSETS_PATH}' in content and assets_path in new_content: + print_color(" ✓ Confirmed path was correctly replaced", GREEN) + elif '${ASSETS_PATH}' in content: + print_color(" ! Warning: Could not confirm if path was correctly replaced", YELLOW) + + except Exception as e: + print_color(f" ✗ Replacement failed: {e}", YELLOW) + count_error += 1 + + # Summary + print() + print_color("Processing complete!", BLUE) + print(f"Total processed: {count_total} files") + print_color(f"Successfully updated: {count_updated} files", GREEN) + if count_error > 0: + print_color(f"Failed to process: {count_error} files", YELLOW) + + print() + print_color("All template files have been processed!", GREEN) + print("To use in a new environment, run this script again") + + +if __name__ == '__main__': + main() diff --git a/scripts/check_agibot_future_video_motion.py b/scripts/check_agibot_future_video_motion.py new file mode 100644 index 0000000000000000000000000000000000000000..65320c4882168f8e0056459950af5b472d1fe9da --- /dev/null +++ b/scripts/check_agibot_future_video_motion.py @@ -0,0 +1,642 @@ +#!/usr/bin/env python3 +"""Check whether AgiBot GT future video frames are static. + +This script reads LeRobot samples through the same starVLA dataset code used by +cosmos25_perceiver_pretrain.sh, then compares frames at: + + t, t + future_video_delta_indices[0], ..., t + future_video_delta_indices[-1] + +It reports pixel-difference metrics per camera view and writes contact sheets so +you can visually confirm whether the GT future frames actually move. +""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +import random +import sys +from collections import defaultdict +from pathlib import Path +from typing import Any + +import numpy as np +import av +from omegaconf import OmegaConf +from PIL import Image, ImageDraw + + +REPO_ROOT = Path(__file__).resolve().parents[1] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from starVLA.dataloader.gr00t_lerobot.mixtures import DATASET_NAMED_MIXTURES +from starVLA.dataloader.gr00t_lerobot.video import get_frames_by_timestamps +from starVLA.dataloader.lerobot_datasets import make_LeRobotSingleDataset + + +DEFAULT_CONFIG_YAML = REPO_ROOT / "examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml" +DEFAULT_DATA_ROOT_DIR = "/mnt/workspace1/" +DEFAULT_DATA_MIX = "sq_agi-beta_robocasa" +DEFAULT_FUTURE_OFFSETS = [2, 4, 6, 8, 10, 12, 14, 16] +DEFAULT_ROBOT_TYPES = ["agibot_beta", "agibot_genie1"] + + +def parse_int_list(value: str) -> list[int]: + text = value.strip() + if text.startswith("["): + parsed = json.loads(text) + return [int(item) for item in parsed] + return [int(item) for item in text.split(",") if item.strip()] + + +def parse_str_list(value: str) -> list[str]: + return [item.strip() for item in value.split(",") if item.strip()] + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config-yaml", default=str(DEFAULT_CONFIG_YAML)) + parser.add_argument("--data-root-dir", default=DEFAULT_DATA_ROOT_DIR) + parser.add_argument("--data-mix", default=DEFAULT_DATA_MIX) + parser.add_argument("--video-backend", default="torchvision_av") + parser.add_argument( + "--compare-video-backends", + default="", + help="Comma-separated extra backends to read with the same timestamps, e.g. decord,torchvision_av.", + ) + parser.add_argument("--future-video-delta-indices", default=json.dumps(DEFAULT_FUTURE_OFFSETS)) + parser.add_argument( + "--robot-types", + default=",".join(DEFAULT_ROBOT_TYPES), + help="Comma-separated robot types to inspect from the mixture.", + ) + parser.add_argument("--samples-per-dataset", type=int, default=16) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--out-dir", default="outputs/agibot_future_video_debug") + parser.add_argument( + "--changed-pixel-threshold", + type=float, + default=3.0, + help="A pixel is treated as changed if any RGB channel differs by more than this value.", + ) + parser.add_argument( + "--frozen-ratio-threshold", + type=float, + default=0.001, + help="Frame pairs below this changed-pixel ratio are flagged as frozen.", + ) + parser.add_argument("--max-contact-sheets", type=int, default=64) + parser.add_argument("--skip-video-timestamp-map", action="store_true") + parser.add_argument( + "--show-all-frames", + action="store_true", + help="Save all sampled frames in contact sheets. Default saves only first and last frames for easier inspection.", + ) + return parser.parse_args() + + +def image_to_uint8_rgb(frame: Any) -> np.ndarray: + array = np.asarray(frame) + if array.ndim == 4: + array = array[0] + if array.ndim != 3: + raise ValueError(f"Expected HWC image or THWC video with T=1, got shape {array.shape}") + if array.shape[-1] == 4: + array = array[..., :3] + if array.shape[-1] != 3: + raise ValueError(f"Expected RGB/RGBA image, got shape {array.shape}") + if array.dtype != np.uint8: + if np.issubdtype(array.dtype, np.floating): + max_value = float(np.nanmax(array)) if array.size else 1.0 + if max_value <= 1.0: + array = array * 255.0 + array = np.clip(array, 0, 255).astype(np.uint8) + return np.ascontiguousarray(array) + + +def resize_for_metrics(a: np.ndarray, b: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + if a.shape[:2] == b.shape[:2]: + return a, b + image = Image.fromarray(b).resize((a.shape[1], a.shape[0]), Image.Resampling.BILINEAR) + return a, np.asarray(image, dtype=np.uint8) + + +def frame_diff_metrics(a: np.ndarray, b: np.ndarray, changed_threshold: float) -> dict[str, float]: + a, b = resize_for_metrics(a, b) + diff = np.abs(a.astype(np.float32) - b.astype(np.float32)) + mse = float(np.mean(diff * diff)) + psnr = float("inf") if mse == 0.0 else 20.0 * math.log10(255.0 / math.sqrt(mse)) + changed = np.any(diff > changed_threshold, axis=-1) + return { + "mae": float(np.mean(diff)), + "rmse": float(math.sqrt(mse)), + "psnr": psnr, + "max_abs": float(np.max(diff)), + "changed_pixel_ratio": float(np.mean(changed)), + } + + +def concat_raw_action(raw_data: dict[str, Any], action_keys: list[str]) -> np.ndarray | None: + chunks = [] + for key in action_keys: + if key not in raw_data: + continue + value = np.asarray(raw_data[key]) + if value.ndim == 1: + value = value[:, None] + chunks.append(value) + if not chunks: + return None + return np.concatenate(chunks, axis=1).astype(np.float32) + + +def get_video_frame_timestamps(video_path: Path) -> np.ndarray: + container = av.open(video_path.as_posix(), options={"threads": "1"}) + stream = container.streams.video[0] + timestamps = [] + try: + for frame in container.decode(video=0): + if frame.pts is None: + continue + timestamps.append(float(frame.pts * stream.time_base)) + finally: + container.close() + if not timestamps: + raise ValueError(f"No decodable frame timestamps in {video_path}") + return np.asarray(timestamps, dtype=np.float64) + + +def get_video_frames_by_indices_pyav(video_path: Path, indices: np.ndarray) -> list[np.ndarray]: + requested = np.asarray(indices, dtype=np.int64) + if requested.ndim != 1: + requested = requested.reshape(-1) + if len(requested) == 0: + return [] + + order = np.argsort(requested) + sorted_indices = requested[order] + frames_sorted: list[np.ndarray | None] = [None] * len(sorted_indices) + container = av.open(video_path.as_posix(), options={"threads": "1"}) + try: + want = 0 + for frame_index, frame in enumerate(container.decode(video=0)): + while want < len(sorted_indices) and sorted_indices[want] < frame_index: + want += 1 + if want >= len(sorted_indices): + break + if frame_index == sorted_indices[want]: + frame_array = frame.to_ndarray(format="rgb24") + while want < len(sorted_indices) and sorted_indices[want] == frame_index: + frames_sorted[want] = frame_array + want += 1 + if want >= len(sorted_indices): + break + finally: + container.close() + + if any(frame is None for frame in frames_sorted): + missing = [int(sorted_indices[idx]) for idx, frame in enumerate(frames_sorted) if frame is None] + raise ValueError(f"Missing video frame indices {missing[:8]} from {video_path}") + + restored: list[np.ndarray | None] = [None] * len(requested) + for sorted_pos, original_pos in enumerate(order): + restored[int(original_pos)] = frames_sorted[sorted_pos] + return [image_to_uint8_rgb(frame) for frame in restored if frame is not None] + + +def nearest_video_frame_indices(video_timestamps: np.ndarray, target_timestamps: np.ndarray) -> np.ndarray: + positions = np.searchsorted(video_timestamps, target_timestamps) + positions = np.clip(positions, 0, len(video_timestamps) - 1) + prev_positions = np.clip(positions - 1, 0, len(video_timestamps) - 1) + use_prev = np.abs(video_timestamps[prev_positions] - target_timestamps) <= np.abs( + video_timestamps[positions] - target_timestamps + ) + return np.where(use_prev, prev_positions, positions).astype(np.int64) + + +def proportional_video_indices(step_indices: list[int], trajectory_length: int, num_video_frames: int) -> np.ndarray: + if trajectory_length <= 1 or num_video_frames <= 1: + return np.zeros(len(step_indices), dtype=np.int64) + ratio = np.asarray(step_indices, dtype=np.float64) / float(trajectory_length - 1) + ratio = np.clip(ratio, 0.0, 1.0) + return np.rint(ratio * float(num_video_frames - 1)).astype(np.int64) + + +def save_contact_sheet( + frames: list[np.ndarray], + labels: list[str], + output_path: Path, + cell_width: int = 224, + label_height: int = 24, +) -> None: + if not frames: + return + resample = getattr(Image, "Resampling", Image).BILINEAR + resized = [ + Image.fromarray(frame).convert("RGB").resize((cell_width, int(cell_width * frame.shape[0] / frame.shape[1])), resample) + for frame in frames + ] + cell_height = max(image.height for image in resized) + sheet = Image.new("RGB", (cell_width * len(resized), cell_height + label_height), "white") + draw = ImageDraw.Draw(sheet) + for idx, image in enumerate(resized): + x = idx * cell_width + y = label_height + sheet.paste(image, (x, y)) + draw.text((x + 4, 4), labels[idx], fill=(0, 0, 0)) + output_path.parent.mkdir(parents=True, exist_ok=True) + sheet.save(output_path) + + +def save_comparison_contact_sheet( + rows: list[tuple[str, list[np.ndarray]]], + labels: list[str], + output_path: Path, + cell_width: int = 224, + label_height: int = 24, + row_label_width: int = 92, +) -> None: + rows = [(name, frames) for name, frames in rows if frames] + if not rows: + return + resample = getattr(Image, "Resampling", Image).BILINEAR + resized_rows = [] + max_cell_height = 1 + for row_name, frames in rows: + resized = [ + Image.fromarray(frame) + .convert("RGB") + .resize((cell_width, int(cell_width * frame.shape[0] / frame.shape[1])), resample) + for frame in frames + ] + max_cell_height = max(max_cell_height, *(image.height for image in resized)) + resized_rows.append((row_name, resized)) + + row_height = max_cell_height + label_height + sheet = Image.new("RGB", (row_label_width + cell_width * len(labels), row_height * len(resized_rows)), "white") + draw = ImageDraw.Draw(sheet) + for row_idx, (row_name, images) in enumerate(resized_rows): + y0 = row_idx * row_height + draw.text((4, y0 + label_height + 4), row_name, fill=(0, 0, 0)) + for col_idx, image in enumerate(images): + x = row_label_width + col_idx * cell_width + if row_idx == 0: + draw.text((x + 4, y0 + 4), labels[col_idx], fill=(0, 0, 0)) + sheet.paste(image, (x, y0 + label_height)) + output_path.parent.mkdir(parents=True, exist_ok=True) + sheet.save(output_path) + + +def select_visual_frames(frames: list[np.ndarray], labels: list[str], show_all_frames: bool) -> tuple[list[np.ndarray], list[str]]: + if show_all_frames or len(frames) <= 2: + return frames, labels + return [frames[0], frames[-1]], [labels[0], labels[-1]] + + +def build_data_cfg(args: argparse.Namespace, future_offsets: list[int]): + cfg = OmegaConf.load(args.config_yaml) + data_cfg = cfg.datasets.vla_data + data_cfg.data_root_dir = args.data_root_dir + data_cfg.data_mix = args.data_mix + data_cfg.include_state = True + data_cfg.video_backend = args.video_backend + data_cfg.future_video_delta_indices = future_offsets + return data_cfg + + +def choose_steps(dataset, count: int, rng: random.Random) -> list[tuple[int, int]]: + all_steps = [(int(traj), int(step)) for traj, step in np.asarray(dataset.all_steps)] + if len(all_steps) <= count: + return all_steps + return rng.sample(all_steps, count) + + +def inspect_dataset( + data_cfg, + data_name: str, + robot_type: str, + args: argparse.Namespace, + future_offsets: list[int], + rng: random.Random, + csv_writer, +) -> dict[str, Any]: + dataset = make_LeRobotSingleDataset( + Path(args.data_root_dir), + data_name, + robot_type, + delete_pause_frame=data_cfg.get("delete_pause_frame", False), + data_cfg=data_cfg, + ) + chosen_steps = choose_steps(dataset, args.samples_per_dataset, rng) + dataset_summary: dict[str, Any] = { + "data_name": data_name, + "robot_type": robot_type, + "dataset_path": str(dataset.dataset_path), + "num_trajectories": int(len(dataset.trajectory_ids)), + "num_valid_steps": int(len(dataset.all_steps)), + "num_checked_steps": int(len(chosen_steps)), + "views": {}, + } + view_stats: dict[str, dict[str, list[float]]] = defaultdict(lambda: defaultdict(list)) + frozen_counts: dict[str, int] = defaultdict(int) + pair_counts: dict[str, int] = defaultdict(int) + out_dir = Path(args.out_dir) + saved_sheets = 0 + video_timestamp_cache: dict[Path, np.ndarray] = {} + video_ratio_frame_cache: dict[tuple[Path, tuple[int, ...]], list[np.ndarray]] = {} + + for sample_idx, (trajectory_id, step) in enumerate(chosen_steps): + raw_data = dataset.get_step_data(trajectory_id, step) + trajectory_index = dataset.get_trajectory_index(trajectory_id) + trajectory_length = int(dataset.trajectory_lengths[trajectory_index]) + action = concat_raw_action(raw_data, dataset.modality_keys.get("action", [])) + action_mean_l2 = float(np.mean(np.linalg.norm(action, axis=1))) if action is not None else float("nan") + action_max_l2 = float(np.max(np.linalg.norm(action, axis=1))) if action is not None else float("nan") + + for video_key in dataset.modality_keys["video"]: + frames = [] + offsets = [0] + future_offsets + frame_indices = [step + offset for offset in offsets] + timestamps = dataset.curr_traj_data["timestamp"].to_numpy()[frame_indices] + video_path = dataset.get_video_path(trajectory_id, video_key.replace("video.", "")) + mapped_video_indices = None + mapped_video_timestamps = None + ratio_video_indices = None + ratio_frames = None + video_num_frames = None + video_duration = None + timestamps_in_video_range = None + if not args.skip_video_timestamp_map: + try: + if video_path not in video_timestamp_cache: + video_timestamp_cache[video_path] = get_video_frame_timestamps(video_path) + video_timestamps = video_timestamp_cache[video_path] + video_num_frames = int(len(video_timestamps)) + video_duration = float(video_timestamps[-1] - video_timestamps[0]) if len(video_timestamps) > 1 else 0.0 + timestamps_in_video_range = bool( + np.min(timestamps) >= video_timestamps[0] and np.max(timestamps) <= video_timestamps[-1] + ) + mapped_video_indices = nearest_video_frame_indices(video_timestamps, timestamps) + mapped_video_timestamps = video_timestamps[mapped_video_indices] + ratio_video_indices = proportional_video_indices(frame_indices, trajectory_length, len(video_timestamps)) + ratio_key = (video_path, tuple(int(index) for index in ratio_video_indices)) + if ratio_key not in video_ratio_frame_cache: + video_ratio_frame_cache[ratio_key] = get_video_frames_by_indices_pyav(video_path, ratio_video_indices) + ratio_frames = video_ratio_frame_cache[ratio_key] + except Exception as exc: + print( + f"Warning: video index diagnosis failed for {data_name} " + f"traj={trajectory_id} step={step} {video_key}: {exc}", + flush=True, + ) + labels = [] + for offset in offsets: + frame = dataset.get_video(trajectory_id, video_key, step + offset) + frames.append(image_to_uint8_rgb(frame)) + labels.append(f"t+{offset}") + backend_compare_frames: dict[str, list[np.ndarray]] = {} + for compare_backend in parse_str_list(args.compare_video_backends): + try: + compare_frames = get_frames_by_timestamps( + video_path.as_posix(), + timestamps, + video_backend=compare_backend, + video_backend_kwargs={}, + ) + backend_compare_frames[compare_backend] = [image_to_uint8_rgb(frame) for frame in compare_frames] + except Exception as exc: + print( + f"Warning: backend compare failed for {compare_backend} on {data_name} " + f"traj={trajectory_id} step={step} {video_key}: {exc}", + flush=True, + ) + + metrics_vs_prev = [] + metrics_vs_t0 = [] + for pair_idx in range(1, len(frames)): + prev_metrics = frame_diff_metrics(frames[pair_idx - 1], frames[pair_idx], args.changed_pixel_threshold) + t0_metrics = frame_diff_metrics(frames[0], frames[pair_idx], args.changed_pixel_threshold) + ratio_prev_metrics = None + ratio_t0_metrics = None + if ratio_frames is not None and pair_idx < len(ratio_frames): + ratio_prev_metrics = frame_diff_metrics( + ratio_frames[pair_idx - 1], ratio_frames[pair_idx], args.changed_pixel_threshold + ) + ratio_t0_metrics = frame_diff_metrics(ratio_frames[0], ratio_frames[pair_idx], args.changed_pixel_threshold) + metrics_vs_prev.append(prev_metrics) + metrics_vs_t0.append(t0_metrics) + pair_counts[video_key] += 1 + for name, value in prev_metrics.items(): + view_stats[video_key][f"prev_{name}"].append(value) + for name, value in t0_metrics.items(): + view_stats[video_key][f"t0_{name}"].append(value) + if prev_metrics["changed_pixel_ratio"] < args.frozen_ratio_threshold: + frozen_counts[video_key] += 1 + + csv_writer.writerow( + { + "dataset": data_name, + "robot_type": robot_type, + "trajectory_id": trajectory_id, + "step": step, + "video_key": video_key, + "offset_from": offsets[pair_idx - 1], + "offset_to": offsets[pair_idx], + "frame_index_from": frame_indices[pair_idx - 1], + "frame_index_to": frame_indices[pair_idx], + "trajectory_length": trajectory_length, + "timestamp_from": float(timestamps[pair_idx - 1]), + "timestamp_to": float(timestamps[pair_idx]), + "timestamp_delta": float(timestamps[pair_idx] - timestamps[pair_idx - 1]), + "video_path": str(video_path), + "video_num_frames": video_num_frames if video_num_frames is not None else "", + "video_duration": video_duration if video_duration is not None else "", + "timestamps_in_video_range": timestamps_in_video_range if timestamps_in_video_range is not None else "", + "video_frame_index_from": int(mapped_video_indices[pair_idx - 1]) + if mapped_video_indices is not None + else "", + "video_frame_index_to": int(mapped_video_indices[pair_idx]) + if mapped_video_indices is not None + else "", + "video_timestamp_from": float(mapped_video_timestamps[pair_idx - 1]) + if mapped_video_timestamps is not None + else "", + "video_timestamp_to": float(mapped_video_timestamps[pair_idx]) + if mapped_video_timestamps is not None + else "", + "video_frame_index_delta": int(mapped_video_indices[pair_idx] - mapped_video_indices[pair_idx - 1]) + if mapped_video_indices is not None + else "", + "ratio_video_frame_index_from": int(ratio_video_indices[pair_idx - 1]) + if ratio_video_indices is not None + else "", + "ratio_video_frame_index_to": int(ratio_video_indices[pair_idx]) + if ratio_video_indices is not None + else "", + "ratio_video_frame_index_delta": int(ratio_video_indices[pair_idx] - ratio_video_indices[pair_idx - 1]) + if ratio_video_indices is not None + else "", + "prev_mae": prev_metrics["mae"], + "prev_changed_pixel_ratio": prev_metrics["changed_pixel_ratio"], + "t0_mae": t0_metrics["mae"], + "t0_changed_pixel_ratio": t0_metrics["changed_pixel_ratio"], + "ratio_prev_mae": ratio_prev_metrics["mae"] if ratio_prev_metrics is not None else "", + "ratio_prev_changed_pixel_ratio": ratio_prev_metrics["changed_pixel_ratio"] + if ratio_prev_metrics is not None + else "", + "ratio_t0_mae": ratio_t0_metrics["mae"] if ratio_t0_metrics is not None else "", + "ratio_t0_changed_pixel_ratio": ratio_t0_metrics["changed_pixel_ratio"] + if ratio_t0_metrics is not None + else "", + "action_mean_l2": action_mean_l2, + "action_max_l2": action_max_l2, + } + ) + + if saved_sheets < args.max_contact_sheets: + safe_name = data_name.replace("/", "__").replace("..", "dotdot") + safe_view = video_key.replace(".", "_").replace("/", "_") + visual_frames, visual_labels = select_visual_frames(frames, labels, args.show_all_frames) + sheet_path = out_dir / "contact_sheets" / safe_name / ( + f"{sample_idx:04d}_traj{trajectory_id}_step{step}_{safe_view}.jpg" + ) + save_contact_sheet(visual_frames, visual_labels, sheet_path) + compare_rows = [(f"loader_{args.video_backend}", visual_frames)] + for compare_backend, compare_frames in backend_compare_frames.items(): + compare_visual_frames, _ = select_visual_frames(compare_frames, labels, args.show_all_frames) + compare_rows.append((f"backend_{compare_backend}", compare_visual_frames)) + if ratio_frames is not None: + ratio_visual_frames, _ = select_visual_frames(ratio_frames, labels, args.show_all_frames) + compare_rows.append(("ratio_idx", ratio_visual_frames)) + compare_sheet_path = out_dir / "contact_sheets_compare" / safe_name / ( + f"{sample_idx:04d}_traj{trajectory_id}_step{step}_{safe_view}.jpg" + ) + save_comparison_contact_sheet(compare_rows, visual_labels, compare_sheet_path) + saved_sheets += 1 + + for video_key, stats in view_stats.items(): + frozen_pairs = frozen_counts[video_key] + total_pairs = pair_counts[video_key] + dataset_summary["views"][video_key] = { + "pair_count": total_pairs, + "frozen_pair_count": frozen_pairs, + "frozen_pair_ratio": float(frozen_pairs / total_pairs) if total_pairs else None, + "mean_prev_changed_pixel_ratio": float(np.mean(stats["prev_changed_pixel_ratio"])) + if stats["prev_changed_pixel_ratio"] + else None, + "median_prev_changed_pixel_ratio": float(np.median(stats["prev_changed_pixel_ratio"])) + if stats["prev_changed_pixel_ratio"] + else None, + "mean_t0_changed_pixel_ratio": float(np.mean(stats["t0_changed_pixel_ratio"])) + if stats["t0_changed_pixel_ratio"] + else None, + "median_t0_changed_pixel_ratio": float(np.median(stats["t0_changed_pixel_ratio"])) + if stats["t0_changed_pixel_ratio"] + else None, + "mean_prev_mae": float(np.mean(stats["prev_mae"])) if stats["prev_mae"] else None, + "median_prev_mae": float(np.median(stats["prev_mae"])) if stats["prev_mae"] else None, + "mean_t0_mae": float(np.mean(stats["t0_mae"])) if stats["t0_mae"] else None, + "median_t0_mae": float(np.median(stats["t0_mae"])) if stats["t0_mae"] else None, + } + return dataset_summary + + +def main() -> None: + args = parse_args() + future_offsets = parse_int_list(args.future_video_delta_indices) + robot_types = {item.strip() for item in args.robot_types.split(",") if item.strip()} + if not future_offsets: + raise ValueError("--future-video-delta-indices must not be empty") + if args.data_mix not in DATASET_NAMED_MIXTURES: + raise KeyError(f"Unknown data mix {args.data_mix!r}. Available keys include: {list(DATASET_NAMED_MIXTURES)[:10]}") + + data_cfg = build_data_cfg(args, future_offsets) + rng = random.Random(args.seed) + out_dir = Path(args.out_dir) + out_dir.mkdir(parents=True, exist_ok=True) + + mixture_entries = [ + (data_name, weight, robot_type) + for data_name, weight, robot_type in DATASET_NAMED_MIXTURES[args.data_mix] + if "all" in robot_types or robot_type in robot_types + ] + if not mixture_entries: + raise ValueError(f"No entries in data_mix={args.data_mix!r} matched robot_types={sorted(robot_types)}") + + summary = { + "config_yaml": str(args.config_yaml), + "data_root_dir": args.data_root_dir, + "data_mix": args.data_mix, + "video_backend": args.video_backend, + "future_video_delta_indices": future_offsets, + "changed_pixel_threshold": args.changed_pixel_threshold, + "frozen_ratio_threshold": args.frozen_ratio_threshold, + "datasets": [], + } + + csv_path = out_dir / "frame_diff_rows.csv" + with csv_path.open("w", newline="") as csv_file: + fieldnames = [ + "dataset", + "robot_type", + "trajectory_id", + "step", + "video_key", + "offset_from", + "offset_to", + "frame_index_from", + "frame_index_to", + "trajectory_length", + "timestamp_from", + "timestamp_to", + "timestamp_delta", + "video_path", + "video_num_frames", + "video_duration", + "timestamps_in_video_range", + "video_frame_index_from", + "video_frame_index_to", + "video_timestamp_from", + "video_timestamp_to", + "video_frame_index_delta", + "ratio_video_frame_index_from", + "ratio_video_frame_index_to", + "ratio_video_frame_index_delta", + "prev_mae", + "prev_changed_pixel_ratio", + "t0_mae", + "t0_changed_pixel_ratio", + "ratio_prev_mae", + "ratio_prev_changed_pixel_ratio", + "ratio_t0_mae", + "ratio_t0_changed_pixel_ratio", + "action_mean_l2", + "action_max_l2", + ] + writer = csv.DictWriter(csv_file, fieldnames=fieldnames) + writer.writeheader() + for data_name, _weight, robot_type in mixture_entries: + print(f"\n=== Checking {robot_type}: {data_name} ===", flush=True) + dataset_summary = inspect_dataset(data_cfg, data_name, robot_type, args, future_offsets, rng, writer) + summary["datasets"].append(dataset_summary) + for view_key, view_summary in dataset_summary["views"].items(): + print( + f"{view_key}: frozen_pair_ratio={view_summary['frozen_pair_ratio']:.4f}, " + f"mean_prev_changed={view_summary['mean_prev_changed_pixel_ratio']:.4f}, " + f"mean_t0_changed={view_summary['mean_t0_changed_pixel_ratio']:.4f}", + flush=True, + ) + + summary_path = out_dir / "summary.json" + summary_path.write_text(json.dumps(summary, indent=2), encoding="utf-8") + print(f"\nWrote summary: {summary_path}") + print(f"Wrote per-pair rows: {csv_path}") + print(f"Wrote contact sheets under: {out_dir / 'contact_sheets'}") + print(f"Wrote loader-vs-index contact sheets under: {out_dir / 'contact_sheets_compare'}") + + +if __name__ == "__main__": + main() diff --git a/scripts/cosmos25_image_to_video_compare.py b/scripts/cosmos25_image_to_video_compare.py new file mode 100644 index 0000000000000000000000000000000000000000..5adef9faa0ccaeb6231932a47fcbefc62fd66537 --- /dev/null +++ b/scripts/cosmos25_image_to_video_compare.py @@ -0,0 +1,353 @@ +#!/usr/bin/env python3 +"""Generate a Cosmos-Predict2.5 video from current image(s) and compare with GT. + +Example: + python scripts/cosmos25_image_to_video_compare.py \ + --model-path /path/to/Cosmos-Predict2.5-2B-Post-Trained \ + --image current.png \ + --instruction "pick up the mug and place it on the plate" \ + --gt gt.mp4 \ + --out-dir outputs/cosmos25_debug +""" + +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +from typing import Iterable + + +class _DisabledCosmosSafetyChecker: + """No-op safety checker for local robot data visualization.""" + + def to(self, *args, **kwargs): + return self + + def check_text_safety(self, *args, **kwargs): + return True + + def check_video_safety(self, video, *args, **kwargs): + return video + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--model-path", required=True, help="HF repo id or local diffusers-format Cosmos2.5 checkpoint.") + parser.add_argument("--revision", default="diffusers/base/post-trained", help="HF revision. Ignored for local paths.") + parser.add_argument("--image", nargs="+", required=True, help="Current image path(s). One image uses image conditioning; multiple images use video conditioning.") + parser.add_argument("--instruction", required=True, help="Language instruction, or @path/to/file.txt.") + parser.add_argument("--gt", default=None, help="Optional GT image/video path for side-by-side comparison.") + parser.add_argument("--out-dir", default="outputs/cosmos25_image_to_video_compare", help="Directory for generated artifacts.") + parser.add_argument("--height", type=int, default=704) + parser.add_argument("--width", type=int, default=1280) + parser.add_argument("--num-frames", type=int, default=93) + parser.add_argument("--num-inference-steps", type=int, default=36) + parser.add_argument("--guidance-scale", type=float, default=7.0) + parser.add_argument("--fps", type=int, default=16) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--negative-prompt", default=None) + parser.add_argument("--max-sequence-length", type=int, default=512) + parser.add_argument("--conditional-frame-timestep", type=float, default=0.1) + parser.add_argument("--num-latent-conditional-frames", type=int, default=2) + parser.add_argument("--dtype", choices=("bf16", "fp16", "fp32"), default="bf16") + parser.add_argument("--device", default="cuda", help="Usually cuda. Use cpu only for very small smoke tests.") + parser.add_argument("--cpu-offload", action="store_true", help="Use diffusers CPU offload instead of moving the full pipe to CUDA.") + parser.add_argument("--enable-safety-checker", action="store_true", help="Keep the Cosmos text/video safety checker enabled.") + return parser.parse_args() + + +def read_instruction(value: str) -> str: + if value.startswith("@"): + return Path(value[1:]).read_text(encoding="utf-8").strip() + return value + + +def load_image(path: str) -> Image.Image: + Image, _, _ = require_pil() + return Image.open(path).convert("RGB") + + +def require_torch(): + try: + import torch + except ImportError as exc: + raise ImportError("This script needs torch installed to run Cosmos generation.") from exc + return torch + + +def maybe_torch(): + try: + import torch + except ImportError: + return None + return torch + + +def require_av(): + try: + import av + except ImportError as exc: + raise ImportError("This script needs av installed to read/write videos. Install requirements.txt first.") from exc + return av + + +def require_numpy(): + try: + import numpy as np + except ImportError as exc: + raise ImportError("This script needs numpy installed. Install requirements.txt first.") from exc + return np + + +def require_pil(): + try: + from PIL import Image, ImageDraw, ImageFont + except ImportError as exc: + raise ImportError("This script needs pillow installed. Install requirements.txt first.") from exc + return Image, ImageDraw, ImageFont + + +def to_uint8_image(frame) -> Image.Image: + Image, _, _ = require_pil() + if isinstance(frame, Image.Image): + return frame.convert("RGB") + + np = require_numpy() + torch = maybe_torch() + if torch is not None and torch.is_tensor(frame): + array = frame.detach().float().cpu().numpy() + else: + array = np.asarray(frame) + + if array.ndim == 3 and array.shape[0] in (1, 3) and array.shape[-1] not in (1, 3): + array = np.transpose(array, (1, 2, 0)) + if array.dtype != np.uint8: + if array.size and array.min() >= -1.0 and array.max() <= 1.0: + array = (array + 1.0) * 127.5 + elif array.size and array.min() >= 0.0 and array.max() <= 1.0: + array = array * 255.0 + array = np.clip(array, 0, 255).astype(np.uint8) + if array.ndim == 2: + array = np.repeat(array[..., None], 3, axis=-1) + if array.shape[-1] == 1: + array = np.repeat(array, 3, axis=-1) + return Image.fromarray(array[..., :3]).convert("RGB") + + +def normalize_generated_frames(output) -> list[Image.Image]: + np = require_numpy() + torch = maybe_torch() + videos = getattr(output, "frames", None) + if videos is None: + videos = getattr(output, "videos", None) + if videos is None: + videos = getattr(output, "images", None) + if videos is None and isinstance(output, tuple): + videos = output[0] + if videos is None: + videos = output + + if torch is not None and torch.is_tensor(videos): + videos = videos.detach().cpu() + if videos.ndim == 5: + videos = videos[0] + return [to_uint8_image(frame) for frame in videos] + + if isinstance(videos, np.ndarray): + if videos.ndim == 5: + videos = videos[0] + return [to_uint8_image(frame) for frame in videos] + + if isinstance(videos, (list, tuple)) and videos: + first = videos[0] + if isinstance(first, (list, tuple)): + return [to_uint8_image(frame) for frame in first] + if torch is not None and torch.is_tensor(first) and first.ndim >= 4: + return [to_uint8_image(frame) for frame in first] + if isinstance(first, np.ndarray) and first.ndim >= 4: + return [to_uint8_image(frame) for frame in first] + return [to_uint8_image(frame) for frame in videos] + + raise ValueError("Could not extract frames from Cosmos generation output.") + + +def read_video(path: Path) -> list[Image.Image]: + Image, _, _ = require_pil() + av = require_av() + frames: list[Image.Image] = [] + with av.open(str(path)) as container: + stream = container.streams.video[0] + for frame in container.decode(stream): + frames.append(frame.to_image().convert("RGB")) + if not frames: + raise ValueError(f"No video frames decoded from {path}.") + return frames + + +def read_gt(path: str, target_len: int) -> list[Image.Image]: + np = require_numpy() + gt_path = Path(path) + suffix = gt_path.suffix.lower() + if suffix in {".png", ".jpg", ".jpeg", ".bmp", ".webp"}: + frame = load_image(str(gt_path)) + return [frame.copy() for _ in range(target_len)] + + frames = read_video(gt_path) + if len(frames) == target_len: + return frames + if len(frames) == 1: + return [frames[0].copy() for _ in range(target_len)] + + # Resample by nearest index so comparison stays aligned even when FPS/count differs. + indices = np.linspace(0, len(frames) - 1, target_len).round().astype(int) + return [frames[int(i)] for i in indices] + + +def save_video(frames: Iterable[Image.Image], path: Path, fps: int) -> None: + require_av() + frames = [frame.convert("RGB") for frame in frames] + if not frames: + raise ValueError(f"No frames to save for {path}.") + + width, height = frames[0].size + encoded_width = width + (width % 2) + encoded_height = height + (height % 2) + path.parent.mkdir(parents=True, exist_ok=True) + try: + _save_video_with_codec(frames, path, fps, "h264", encoded_width, encoded_height) + except Exception: + _save_video_with_codec(frames, path, fps, "mpeg4", encoded_width, encoded_height) + + +def _save_video_with_codec( + frames: list[Image.Image], + path: Path, + fps: int, + codec: str, + encoded_width: int, + encoded_height: int, +) -> None: + av = require_av() + with av.open(str(path), mode="w") as container: + stream = container.add_stream(codec, rate=fps) + stream.width = encoded_width + stream.height = encoded_height + stream.pix_fmt = "yuv420p" + for frame in frames: + if frame.size != (encoded_width, encoded_height): + canvas = Image.new("RGB", (encoded_width, encoded_height)) + canvas.paste(frame, (0, 0)) + frame = canvas + video_frame = av.VideoFrame.from_image(frame) + for packet in stream.encode(video_frame): + container.mux(packet) + for packet in stream.encode(): + container.mux(packet) + + +def labelled(frame: Image.Image, label: str) -> Image.Image: + _, ImageDraw, ImageFont = require_pil() + frame = frame.convert("RGB") + draw = ImageDraw.Draw(frame) + font = ImageFont.load_default() + try: + bbox = draw.textbbox((0, 0), label, font=font) + text_w, text_h = bbox[2] - bbox[0], bbox[3] - bbox[1] + except AttributeError: + text_w, text_h = draw.textsize(label, font=font) + pad = 8 + draw.rectangle((0, 0, text_w + pad * 2, text_h + pad * 2), fill=(0, 0, 0)) + draw.text((pad, pad), label, fill=(255, 255, 255), font=font) + return frame + + +def make_compare_frames(pred_frames: list[Image.Image], gt_frames: list[Image.Image] | None) -> list[Image.Image]: + Image, _, _ = require_pil() + if gt_frames is None: + return pred_frames + + compare_frames = [] + for pred, gt in zip(pred_frames, gt_frames): + gt = gt.resize(pred.size, Image.BILINEAR) + canvas = Image.new("RGB", (pred.width * 2, pred.height)) + canvas.paste(labelled(gt.copy(), "GT"), (0, 0)) + canvas.paste(labelled(pred.copy(), "Cosmos"), (pred.width, 0)) + compare_frames.append(canvas) + return compare_frames + + +def main() -> None: + args = parse_args() + out_dir = Path(args.out_dir) + out_dir.mkdir(parents=True, exist_ok=True) + + if not args.enable_safety_checker: + from diffusers.pipelines.cosmos import pipeline_cosmos2_5_predict + + pipeline_cosmos2_5_predict.CosmosSafetyChecker = _DisabledCosmosSafetyChecker + + from diffusers import Cosmos2_5_PredictBasePipeline + + torch = require_torch() + dtype = {"bf16": torch.bfloat16, "fp16": torch.float16, "fp32": torch.float32}[args.dtype] + load_kwargs = {"torch_dtype": dtype} + if args.revision and not os.path.isdir(args.model_path): + load_kwargs["revision"] = args.revision + + pipe = Cosmos2_5_PredictBasePipeline.from_pretrained(args.model_path, **load_kwargs) + if args.cpu_offload: + pipe.enable_model_cpu_offload() + else: + pipe.to(args.device) + + images = [load_image(path) for path in args.image] + instruction = read_instruction(args.instruction) + generator = torch.Generator(device=args.device if args.device.startswith("cuda") else "cpu").manual_seed(args.seed) + + generation_kwargs = { + "prompt": instruction, + "height": args.height, + "width": args.width, + "num_frames": args.num_frames, + "num_inference_steps": args.num_inference_steps, + "guidance_scale": args.guidance_scale, + "return_dict": True, + "output_type": "pil", + "max_sequence_length": args.max_sequence_length, + "conditional_frame_timestep": args.conditional_frame_timestep, + "num_latent_conditional_frames": args.num_latent_conditional_frames, + "generator": generator, + } + if args.negative_prompt: + generation_kwargs["negative_prompt"] = args.negative_prompt + if len(images) == 1: + generation_kwargs["image"] = images[0] + else: + generation_kwargs["video"] = images + + with torch.inference_mode(): + output = pipe(**generation_kwargs) + + pred_frames = normalize_generated_frames(output) + gt_frames = read_gt(args.gt, len(pred_frames)) if args.gt else None + compare_frames = make_compare_frames(pred_frames, gt_frames) + + pred_path = out_dir / "pred.mp4" + compare_path = out_dir / "compare.mp4" + last_path = out_dir / "last_frame_compare.png" + meta_path = out_dir / "run_args.json" + + save_video(pred_frames, pred_path, args.fps) + save_video(compare_frames, compare_path, args.fps) + compare_frames[-1].save(last_path) + meta_path.write_text(json.dumps(vars(args), indent=2, ensure_ascii=False), encoding="utf-8") + + print(f"Saved prediction video: {pred_path}") + print(f"Saved comparison video: {compare_path}") + print(f"Saved last-frame comparison: {last_path}") + + +if __name__ == "__main__": + main() diff --git a/scripts/rsync_push.sh b/scripts/rsync_push.sh new file mode 100644 index 0000000000000000000000000000000000000000..d678630c2d539b5777c1f40c7fbdd71cb207a319 --- /dev/null +++ b/scripts/rsync_push.sh @@ -0,0 +1,101 @@ +#!/bin/bash + +# 固定远程主机地址 +REMOTE_HOST="root@6.178.134.136" + +# 固定远程 W&B 根目录;传入第二个参数可覆盖该默认值。 +DEFAULT_REMOTE_ROOT="/mnt/workspace/users/yuanzhihao/wandb" + +# 固定 W&B API key;运行前设置 WANDB_API_KEY 可覆盖该默认值。 +DEFAULT_WANDB_API_KEY="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" + +# 检查参数数量 +if [ $# -lt 1 ] || [ $# -gt 2 ]; then + echo "用法: $0 <本地wandb run路径> [远程wandb根目录]" + echo "示例: $0 outputs/exp_name/task_name/wandb/wandb/latest-run/" + echo "示例: $0 outputs/exp_name/task_name/wandb/wandb/latest-run/ /mnt/workspace/users/yuanzhihao/wandb/" + exit 1 +fi + +# 提取参数 +LOCAL_SOURCE="$1" +REMOTE_ROOT="${2:-$DEFAULT_REMOTE_ROOT}" +REMOTE_ROOT="${REMOTE_ROOT%/}" + +# 如果传入的是 latest-run 软链接目录,自动补上末尾 /,同步真实目录内容而不是链接本身。 +if [ -L "$LOCAL_SOURCE" ] && [ -d "$LOCAL_SOURCE" ] && [[ "$LOCAL_SOURCE" != */ ]]; then + LOCAL_SOURCE="${LOCAL_SOURCE}/" +fi + +# 从 outputs/exp/task/wandb/wandb/latest-run/ 自动推导远程目录: +# /remote/wandb/exp/task/ +REMOTE_SUBDIR="" +SOURCE_PREFIX="${LOCAL_SOURCE%%/wandb/wandb/*}" +if [[ "$SOURCE_PREFIX" != "$LOCAL_SOURCE" ]]; then + REMOTE_SUBDIR="${SOURCE_PREFIX#outputs/}" + REMOTE_SUBDIR="${REMOTE_SUBDIR#/}" +fi + +if [ -n "$REMOTE_SUBDIR" ]; then + REMOTE_DEST="${REMOTE_ROOT}/${REMOTE_SUBDIR}/" +else + REMOTE_DEST="${REMOTE_ROOT}/" +fi + +# 执行rsync命令 +echo "开始传输:${LOCAL_SOURCE} -> ${REMOTE_HOST}:${REMOTE_DEST}" +rsync -avz --progress --rsync-path="mkdir -p '${REMOTE_DEST}' && rsync" "${LOCAL_SOURCE}" "${REMOTE_HOST}:${REMOTE_DEST}" + +# 检查传输结果 +if [ $? -eq 0 ]; then + echo "传输成功!" +else + echo "传输失败!" + exit 1 +fi + +# 检查 W&B 登录状态。优先使用当前环境里的 WANDB_API_KEY,否则使用脚本内置 key。 +echo "检查远程wandb登录状态:${REMOTE_HOST}" +if [ -n "${WANDB_API_KEY:-}" ] || [ -n "${DEFAULT_WANDB_API_KEY}" ]; then + EFFECTIVE_WANDB_API_KEY="${WANDB_API_KEY:-$DEFAULT_WANDB_API_KEY}" + REMOTE_WANDB_ENV="WANDB_API_KEY='${EFFECTIVE_WANDB_API_KEY}'" +elif ssh "${REMOTE_HOST}" "wandb status | grep -q '\"api_key\": null'"; then + echo "远程wandb未登录,请先在远程机器执行:wandb login --relogin" + echo "或在本机运行:WANDB_API_KEY=<你的key> $0 <本地wandb run路径> <远程wandb根目录>" + exit 1 +else + REMOTE_WANDB_ENV="" +fi + +# 在远程机器上同步到 W&B +echo "开始同步wandb:${REMOTE_HOST}:${REMOTE_DEST}" +SYNC_OUTPUT=$(ssh "${REMOTE_HOST}" "${REMOTE_WANDB_ENV} REMOTE_DEST='${REMOTE_DEST}' bash -lc ' +set -e +shopt -s nullglob +sync_targets=() + +for run_dir in \"\${REMOTE_DEST}\"/offline-run-* \"\${REMOTE_DEST}\"/run-*; do + if [ -d \"\${run_dir}\" ]; then + sync_targets+=(\"\${run_dir}\") + fi +done + +if [ \${#sync_targets[@]} -eq 0 ]; then + sync_targets=(\"\${REMOTE_DEST}\") +fi + +for sync_target in \"\${sync_targets[@]}\"; do + echo \"wandb sync \${sync_target}\" + wandb sync \"\${sync_target}\" +done +'" 2>&1) +SYNC_STATUS=$? +echo "${SYNC_OUTPUT}" + +# 检查同步结果 +if [ $SYNC_STATUS -eq 0 ] && ! echo "${SYNC_OUTPUT}" | grep -Eq "wandb: ERROR|Traceback|Exception|AssertionError|RuntimeError"; then + echo "wandb同步成功!" +else + echo "wandb同步失败!" + exit 1 +fi diff --git a/scripts/run_scripts/Robocasa/run_lerobot_datasets_qwenGR00T.sh b/scripts/run_scripts/Robocasa/run_lerobot_datasets_qwenGR00T.sh new file mode 100644 index 0000000000000000000000000000000000000000..5c6945ec4c1edc68fb18c8cf2b764e71682d1b2b --- /dev/null +++ b/scripts/run_scripts/Robocasa/run_lerobot_datasets_qwenGR00T.sh @@ -0,0 +1,57 @@ +export NCCL_SOCKET_IFNAME=bond0 +export NCCL_IB_HCA=mlx5_2,mlx5_3 + +# used for check save when communication +export NCCL_BLOCKING_WAIT=1 +export NCCL_ASYNC_ERROR_HANDLING=1 +export NCCL_TIMEOUT=1000 # timeout set to 1 hour (unit: seconds) + + +Framework_name=QwenGR00T +base_vlm=./playground/Pretrained_models/Qwen3-VL-4B-Instruct + +freeze_module_list='' # just for fast debug, sota is under fully FT, i.g., freeze_module_list="" +DIT_TYPE="DiT-B" +# 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="" + +llavadata="asv2_conversation_en,asv2_detailed_description_en" +# data_root_dir=/mnt/petrelfs/wangfangjing/p_ceph/datasets/PhysicalAI-Robotics-GR00T-X-Embodiment-Sim +data_root_dir=./playground/Datasets/PhysicalAI-Robotics-GR00T-X-Embodiment-Sim +data_mix=fourier_gr1_unified_1000 +# data_mix=fourier_gr1_unified_1000_PnPMilkToMicrowaveClose +# data_mix=fourier_gr1_10K_pretrain + +run_root_dir=./playground/Checkpoints +run_id=starvla_qwenGR00T_fourier_gr1_unified_1000_withState + +export WANDB_MODE=disabled + +output_dir=${run_root_dir}/${run_id} +mkdir -p ${output_dir} +# mv this script to the output dir +cp $0 ${output_dir}/ + +accelerate launch \ + --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \ + --num_processes 8 \ + starVLA/training/train_starvla.py \ + --config_yaml ./starVLA/config/training/internvla_cotrain_robocasa_gr1.yaml \ + --framework.name ${Framework_name} \ + --framework.qwenvl.base_vlm ${base_vlm} \ + --framework.action_model.action_model_type ${DIT_TYPE} \ + --datasets.vla_data.data_root_dir ${data_root_dir} \ + --datasets.vla_data.data_mix ${data_mix} \ + --datasets.vla_data.per_device_batch_size 16 \ + --trainer.freeze_modules ${freeze_module_list} \ + --trainer.max_train_steps 100000 \ + --trainer.save_interval 10000 \ + --trainer.logging_frequency 10 \ + --trainer.eval_interval 100 \ + --trainer.learning_rate.base 4e-5 \ + --run_root_dir ${run_root_dir} \ + --run_id ${run_id} \ + --wandb_project starVLA \ + --wandb_entity ailab-manipulation \ + --is_debug True + + diff --git a/scripts/run_scripts/run_lerobot_datasets_qwenGR00T.sh b/scripts/run_scripts/run_lerobot_datasets_qwenGR00T.sh new file mode 100644 index 0000000000000000000000000000000000000000..68cffb734f23da8ab1acedf627fe471d2b976631 --- /dev/null +++ b/scripts/run_scripts/run_lerobot_datasets_qwenGR00T.sh @@ -0,0 +1,72 @@ +export NCCL_SOCKET_IFNAME=bond0 +export NCCL_IB_HCA=mlx5_2,mlx5_3 + +# used for check save when communication +export NCCL_BLOCKING_WAIT=1 +export NCCL_ASYNC_ERROR_HANDLING=1 +export NCCL_TIMEOUT=1000 # timeout set to 1 hour (unit: seconds) + + +# === Please modify the following paths according to your environment === +########################################################################################### + +Framework_name=QwenGR00T +base_vlm=StarVLA/Qwen3-VL-4B-Instruct-Action +action_input_dim=2560 +DIT_TYPE="DiT-B" +oxe_data_root=playground/Datasets/OXE_LEROBOT +data_mix=bridge_rt_1 +run_root_dir=./playground/Checkpoints +run_id=1004_starvla_qwengroot_oxe +# === End of environment variable configuration === +########################################################################################### + +output_dir=${run_root_dir}/${run_id} +mkdir -p ${output_dir} +cp $0 ${output_dir}/ +export WANDB_MODE=disabled + +accelerate launch \ + --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \ + --num_processes 8 \ + starVLA/training/train_starvla.py \ + --config_yaml ./starVLA/config/training/starvla_cotrain_oxe.yaml \ + --framework.name ${Framework_name} \ + --framework.qwenvl.base_vlm ${base_vlm} \ + --framework.action_model.action_hidden_dim ${action_input_dim} \ + --framework.action_model.action_model_type ${DIT_TYPE} \ + --datasets.vla_data.data_root_dir ${oxe_data_root}\ + --datasets.vla_data.data_mix ${data_mix} \ + --datasets.vla_data.per_device_batch_size 16 \ + --trainer.freeze_modules ${freeze_module_list} \ + --trainer.max_train_steps 100000 \ + --trainer.save_interval 20000 \ + --trainer.logging_frequency 10 \ + --trainer.eval_interval 100 \ + --run_root_dir ${run_root_dir} \ + --run_id ${run_id} \ + --wandb_project starVLA \ + --wandb_entity jinhuiye \ + # --is_debug True + + + + +# multi-node launch example + +# accelerate launch \ +# --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \ +# --main_process_ip $MASTER_ADDR \ +# --main_process_port $MASTER_PORT \ +# --machine_rank $SLURM_PROCID \ +# --num_machines $SLURM_NNODES \ +# --num_processes=${TOTAL_GPUS} \ +# starVLA/training/train_starvla.py \ +# --config_yaml ./starVLA/config/training/starvla_cotrain_oxe.yaml \ +# --framework.framework_py QwenGR00T \ +# --framework.qwenvl.base_vlm microsoft/Florence-2-large \ +# --run_root_dir ${run_root_dir} \ +# --run_id ${run_id} \ +# --wandb_project your_project \ +# --wandb_entity your_name + diff --git a/scripts/run_scripts/run_lerobot_datasets_qwenfast.sh b/scripts/run_scripts/run_lerobot_datasets_qwenfast.sh new file mode 100644 index 0000000000000000000000000000000000000000..3ffdc4ad9091d3443ff6eb647ef1a139f6ebdb03 --- /dev/null +++ b/scripts/run_scripts/run_lerobot_datasets_qwenfast.sh @@ -0,0 +1,75 @@ + + +export NCCL_SOCKET_IFNAME=bond0 +export NCCL_IB_HCA=mlx5_2,mlx5_3 + +# used for check save when communication +export NCCL_BLOCKING_WAIT=1 +export NCCL_ASYNC_ERROR_HANDLING=1 +export NCCL_TIMEOUT=1000 # timeout set to 1 hour (unit: seconds) + +########################################################################################### +# === Please modify the following paths according to your environment === +## Model +Framework_name=QwenFast +base_vlm=StarVLA/Qwen3-VL-4B-Instruct-Action +action_input_dim=2048 +## Data +oxe_data_root=playground/Datasets/OXE_LEROBOT +data_mix=bridge_rt_1 +# To save +run_root_dir=./playground/Checkpoints +run_id=1004_starvla_qwenoft_oxe +output_dir=${run_root_dir}/${run_id} +mkdir -p ${output_dir} +cp $0 ${output_dir}/ +# === End of environment variable configuration === +########################################################################################### + + + + +# mv this script to the output dir +export WANDB_MODE=disableds + +accelerate launch \ + --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \ + --num_processes 8 \ + starVLA/training/train_starvla.py \ + --config_yaml ./starVLA/config/training/starvla_cotrain_oxe.yaml \ + --framework.name ${Framework_name} \ + --framework.qwenvl.base_vlm ${base_vlm} \ + --framework.action_model.action_hidden_dim ${action_input_dim} \ + --datasets.vla_data.data_root_dir ${oxe_data_root}\ + --datasets.vla_data.data_mix ${data_mix} \ + --datasets.vla_data.per_device_batch_size 16 \ + --trainer.freeze_modules ${freeze_module_list} \ + --trainer.max_train_steps 100000 \ + --trainer.save_interval 20000 \ + --trainer.logging_frequency 10 \ + --trainer.eval_interval 1000 \ + --run_root_dir ${run_root_dir} \ + --run_id ${run_id} \ + --wandb_project starVLA \ + --wandb_entity jinhuiye \ + # --is_debug True + + +# multi-node launch example + +# accelerate launch \ +# --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \ +# --main_process_ip $MASTER_ADDR \ +# --main_process_port $MASTER_PORT \ +# --machine_rank $SLURM_PROCID \ +# --num_machines $SLURM_NNODES \ +# --num_processes=${TOTAL_GPUS} \ +# starVLA/training/train_starvla.py \ +# --config_yaml ./starVLA/config/training/starvla_cotrain_oxe.yaml \ +# --framework.framework_py QwenGR00T \ +# --framework.qwenvl.base_vlm microsoft/Florence-2-large \ +# --run_root_dir ${run_root_dir} \ +# --run_id ${run_id} \ +# --wandb_project your_project \ +# --wandb_entity your_name + diff --git a/scripts/run_scripts/run_lerobot_datasets_qwenoft.sh b/scripts/run_scripts/run_lerobot_datasets_qwenoft.sh new file mode 100644 index 0000000000000000000000000000000000000000..6807427e44583cb8462fa567a76b0c0abaf08661 --- /dev/null +++ b/scripts/run_scripts/run_lerobot_datasets_qwenoft.sh @@ -0,0 +1,74 @@ +export NCCL_SOCKET_IFNAME=bond0 +export NCCL_IB_HCA=mlx5_2,mlx5_3 + +# used for check save when communication +export NCCL_BLOCKING_WAIT=1 +export NCCL_ASYNC_ERROR_HANDLING=1 +export NCCL_TIMEOUT=1000 # timeout set to 1 hour (unit: seconds) + + +# === Please modify the following paths according to your environment === +########################################################################################### + +Framework_name=QwenOFT +base_vlm=StarVLA/Qwen3-VL-4B-Instruct-Action +action_input_dim=2560 +oxe_data_root=playground/Datasets/OXE_LEROBOT +data_mix=bridge_rt_1 +run_root_dir=./playground/Checkpoints +run_id=1004_starvla_qwenoft_oxe +# === End of environment variable configuration === +########################################################################################### + +export WANDB_MODE=disabled + +output_dir=${run_root_dir}/${run_id} +mkdir -p ${output_dir} +# mv this script to the output dir +cp $0 ${output_dir}/ + + +accelerate launch \ + --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \ + --num_processes 8 \ + starVLA/training/train_starvla.py \ + --config_yaml ./starVLA/config/training/starvla_cotrain_oxe.yaml \ + --framework.name ${Framework_name} \ + --framework.qwenvl.base_vlm ${base_vlm} \ + --framework.action_model.action_hidden_dim ${action_input_dim} \ + --datasets.vla_data.data_root_dir ${oxe_data_root}\ + --datasets.vla_data.data_mix ${data_mix} \ + --datasets.vla_data.per_device_batch_size 16 \ + --trainer.freeze_modules ${freeze_module_list} \ + --trainer.max_train_steps 100000 \ + --trainer.save_interval 20000 \ + --trainer.logging_frequency 10 \ + --trainer.eval_interval 100 \ + --run_root_dir ${run_root_dir} \ + --run_id ${run_id} \ + --wandb_project starVLA \ + --wandb_entity jinhuiye \ + # --is_debug True + + + +########################################################################################### +####### multi-node launch example ####### +########################################################################################### + +# accelerate launch \ +# --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \ +# --main_process_ip $MASTER_ADDR \ +# --main_process_port $MASTER_PORT \ +# --machine_rank $SLURM_PROCID \ +# --num_machines $SLURM_NNODES \ +# --num_processes=${TOTAL_GPUS} \ +# starVLA/training/train_starvla.py \ +# --config_yaml ./starVLA/config/training/starvla_cotrain_oxe.yaml \ +# --framework.framework_py QwenGR00T \ +# --framework.qwenvl.base_vlm microsoft/Florence-2-large \ +# --run_root_dir ${run_root_dir} \ +# --run_id ${run_id} \ +# --wandb_project your_project \ +# --wandb_entity your_name + diff --git a/scripts/run_scripts/run_lerobot_datasets_qwenpi.sh b/scripts/run_scripts/run_lerobot_datasets_qwenpi.sh new file mode 100644 index 0000000000000000000000000000000000000000..d9b8485289187dd1cad7bdaf7d8369990dbff679 --- /dev/null +++ b/scripts/run_scripts/run_lerobot_datasets_qwenpi.sh @@ -0,0 +1,72 @@ +export NCCL_SOCKET_IFNAME=bond0 +export NCCL_IB_HCA=mlx5_2,mlx5_3 + +export NCCL_BLOCKING_WAIT=1 +export NCCL_ASYNC_ERROR_HANDLING=1 +export NCCL_TIMEOUT=1000 # timeout set to 1 hour (unit: seconds) + + +# === Please modify the following paths according to your environment === +########################################################################################### + +Framework_name=QwenPI +base_vlm=StarVLA/Qwen2.5-VL-3B-Instruct-Action +DIT_TYPE="DiT-B" +oxe_data_root=playground/Datasets/OXE_LEROBOT +data_mix=bridge_rt_1 +run_root_dir=./playground/Checkpoints +run_id=1011_starvla_qwenpi +export action_input_dim=2048 +########################################################################################### + + +output_dir=${run_root_dir}/${run_id} +mkdir -p ${output_dir} +# mv this script to the output dir +cp $0 ${output_dir}/ + + +accelerate launch \ + --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \ + --num_processes 8 \ + starVLA/training/train_starvla.py \ + --config_yaml ./starVLA/config/training/starvla_cotrain_oxe.yaml \ + --framework.name ${Framework_name} \ + --framework.qwenvl.base_vlm ${base_vlm} \ + --framework.action_model.action_hidden_dim ${action_input_dim} \ + --framework.action_model.action_model_type ${DIT_TYPE} \ + --datasets.vla_data.data_root_dir ${oxe_data_root}\ + --datasets.vla_data.data_mix ${data_mix} \ + --datasets.vla_data.per_device_batch_size 16 \ + --trainer.freeze_modules ${freeze_module_list} \ + --trainer.max_train_steps 100000 \ + --trainer.save_interval 10000 \ + --trainer.logging_frequency 10 \ + --trainer.eval_interval 100 \ + --run_root_dir ${run_root_dir} \ + --run_id ${run_id} \ + --wandb_project starVLA \ + --wandb_entity jinhuiye \ + # --is_debug True + + + + +# multi-node launch example + +# accelerate launch \ +# --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \ +# --main_process_ip $MASTER_ADDR \ +# --main_process_port $MASTER_PORT \ +# --machine_rank $SLURM_PROCID \ +# --num_machines $SLURM_NNODES \ +# --num_processes=${TOTAL_GPUS} \ +# starVLA/training/train_starvla.py \ +# --config_yaml ./starVLA/config/training/starvla_cotrain_oxe.yaml \ +# --framework.framework_py QwenGR00T \ +# --framework.qwenvl.base_vlm microsoft/Florence-2-large \ +# --run_root_dir ${run_root_dir} \ +# --run_id ${run_id} \ +# --wandb_project your_project \ +# --wandb_entity your_name + diff --git a/starVLA/__init__.py b/starVLA/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/starVLA/config/deepseeds/deepspeed_zero2.yaml b/starVLA/config/deepseeds/deepspeed_zero2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7ccb145ffa7a8995655e497b356ecfec8e416027 --- /dev/null +++ b/starVLA/config/deepseeds/deepspeed_zero2.yaml @@ -0,0 +1,9 @@ +compute_environment: LOCAL_MACHINE +debug: false +deepspeed_config: + deepspeed_config_file: "./starVLA/config/deepseeds/ds_config.yaml" + deepspeed_multinode_launcher: standard + zero3_init_flag: false +distributed_type: DEEPSPEED +num_machines: 1 +num_processes: 8 \ No newline at end of file diff --git a/starVLA/config/deepseeds/deepspeed_zero3.yaml b/starVLA/config/deepseeds/deepspeed_zero3.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c1b7cca733e95616507bca81fe71a4c96530c19d --- /dev/null +++ b/starVLA/config/deepseeds/deepspeed_zero3.yaml @@ -0,0 +1,7 @@ +compute_environment: LOCAL_MACHINE +debug: false +deepspeed_config: + deepspeed_config_file: "./starVLA/config/deepseeds/zero3.yaml" + deepspeed_multinode_launcher: standard + zero3_init_flag: false +distributed_type: DEEPSPEED \ No newline at end of file diff --git a/starVLA/config/deepseeds/ds_config.yaml b/starVLA/config/deepseeds/ds_config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2d461f95290fe6574255262ead9e7dcbb81a245e --- /dev/null +++ b/starVLA/config/deepseeds/ds_config.yaml @@ -0,0 +1,23 @@ +{ + "fp16": { + "enabled": false + }, + "bf16": { + "enabled": true + }, + "train_micro_batch_size_per_gpu": "auto", + "train_batch_size": "auto", + "gradient_accumulation_steps": 1, + "zero_optimization": { + "stage": 2, + "allgather_partitions": true, + "allgather_bucket_size": 5e8, + "reduce_scatter": true, + "reduce_bucket_size": 5e8, + "overlap_comm": true, + "contiguous_gradients": true, + "cpu_offload": false + }, + "gradient_clipping": 1.0, + "steps_per_print": 10 +} \ No newline at end of file diff --git a/starVLA/config/deepseeds/zero2.yaml b/starVLA/config/deepseeds/zero2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4df9d409dfc682961b2e9e970721a75cdd3667f --- /dev/null +++ b/starVLA/config/deepseeds/zero2.yaml @@ -0,0 +1,21 @@ +compute_environment: LOCAL_MACHINE +debug: false +deepspeed_config: + deepspeed_multinode_launcher: standard + offload_optimizer_device: none + offload_param_device: none + zero3_init_flag: false + zero_stage: 2 +distributed_type: DEEPSPEED +downcast_bf16: 'no' +machine_rank: 0 +main_training_function: main +mixed_precision: bf16 +num_machines: 1 +num_processes: 8 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false \ No newline at end of file diff --git a/starVLA/config/deepseeds/zero3.yaml b/starVLA/config/deepseeds/zero3.yaml new file mode 100644 index 0000000000000000000000000000000000000000..90a219f8070df25ee448e7d0f6a850c1963644a6 --- /dev/null +++ b/starVLA/config/deepseeds/zero3.yaml @@ -0,0 +1,28 @@ +{ + "fp16": { + "enabled": "auto", + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "bf16": { + "enabled": "auto" + }, + "train_micro_batch_size_per_gpu": "auto", + "train_batch_size": "auto", + "gradient_accumulation_steps": "auto", + "zero_optimization": { + "stage": 3, + "overlap_comm": true, + "contiguous_gradients": true, + "sub_group_size": 1e9, + "reduce_bucket_size": 5e8, + "stage3_prefetch_bucket_size": 5e8, + "stage3_param_persistence_threshold": 1e6, + "stage3_max_live_parameters": 1e9, + "stage3_max_reuse_distance": 1e9, + "stage3_gather_16bit_weights_on_model_save": true + } +} \ No newline at end of file diff --git a/starVLA/config/training/starvla_cotrain_libero.yaml b/starVLA/config/training/starvla_cotrain_libero.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c64dd4c3d8cb7d84b8b0ff4fa9acefb234f098ff --- /dev/null +++ b/starVLA/config/training/starvla_cotrain_libero.yaml @@ -0,0 +1,111 @@ +run_id: starvla +run_root_dir: results/Checkpoints +seed: 42 +trackers: [jsonl, wandb] +wandb_entity: your_wandb_entity +wandb_project: llavavla +is_debug: false + + +framework: + name: QwenGR00T + qwenvl: + base_vlm: ./playground/Pretrained_models/Qwen2.5-VL-3B-Instruct + attn_implementation: flash_attention_2 + vl_hidden_dim: 2048 + dino: + dino_backbone: dinov2_vits14 + action_model: + action_model_type: DiT-B + action_hidden_dim: 1024 # TODO merge with hidden_size, in config v2 + hidden_size: 1024 + add_pos_embed: True + max_seq_len: 1024 + action_dim: 7 + state_dim: 7 + future_action_window_size: 7 + action_horizon: 8 # need merge with future_action_window_size + past_action_window_size: 0 + repeated_diffusion_steps: 8 + noise_beta_alpha: 1.5 + noise_beta_beta: 1.0 + noise_s: 0.999 + num_timestep_buckets: 1000 + num_inference_timesteps: 4 + num_target_vision_tokens: 32 + diffusion_model_cfg: # DiT Transformers 的参数 + cross_attention_dim: 2048 # VLM 的 dim + dropout: 0.2 + final_dropout: true + interleave_self_attention: true + norm_type: "ada_norm" + num_layers: 16 + output_dim: 1024 + positional_embeddings: null + + reduce_in_full_precision: true + + +datasets: + vlm_data: + dataset_py: vlm_datasets + dataformat: llava_json + 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 + eval_dataset: aokvqa_cauldron_llava_format + data_flatten: false + base_interval: 2 + max_pixels: 12845056 + min_pixels: 3136 + model_max_length: 2048 + model_type: qwen2.5vl + per_device_batch_size: 4 + + vla_data: + dataset_py: lerobot_datasets + data_root_dir: playground/Datasets/LEROBOT_LIBERO_DATA + data_mix: libero_goal # libero_goal + action_type: delta_qpos + CoT_prompt: "Your task is {instruction}. To identify the key objects for your task. Locate their bounding boxes in [x1,y1,x2,y2] format." + CoT_answer: bbox + default_image_resolution: [3, 224, 224] + per_device_batch_size: 16 + load_all_data_for_training: true + obs: ["image_0"] + + +trainer: + epochs: 100 + max_train_steps: 100000 + num_warmup_steps: 5000 + save_interval: 5000 + eval_interval: 100 + learning_rate: + base: 2.5e-05 + qwen_vl_interface: 1.0e-05 + action_model: 1.0e-04 + lr_scheduler_type: cosine_with_min_lr + scheduler_specific_kwargs: + min_lr: 1.0e-06 + freeze_modules: '' + loss_scale: + vla: 1.0 + vlm: 0.1 + max_grad_norm: 1.0 + warmup_ratio: 0.1 + weight_decay: 0.0 + logging_frequency: 10 + gradient_clipping: 1.0 + gradient_accumulation_steps: 1 + + optimizer: + name: AdamW + betas: [0.9, 0.95] + eps: 1.0e-08 + weight_decay: 1.0e-08 + + # parameters to be determined + is_resume: false + resume_epoch: null + resume_step: null + enable_gradient_checkpointing: true + enable_mixed_precision_training: true diff --git a/starVLA/config/training/starvla_cotrain_oxe.yaml b/starVLA/config/training/starvla_cotrain_oxe.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0dc2f794c7723c8409921c3b1603b5a7c50d19a8 --- /dev/null +++ b/starVLA/config/training/starvla_cotrain_oxe.yaml @@ -0,0 +1,112 @@ +run_id: qwenact +run_root_dir: results/Checkpoints +seed: 42 +trackers: [jsonl, wandb] +wandb_entity: your_wandb_entity +wandb_project: llavavla +is_debug: false + +framework: + name: QwenFM + qwenvl: + base_vlm: ./playground/Pretrained_models/Qwen2.5-VL-3B-Instruct + attn_implementation: flash_attention_2 + vl_hidden_dim: 2048 + dino: + dino_backbone: dinov2_vits14 + + action_model: + action_model_type: DiT-B + hidden_size: 1024 # 和 DiT 最后的 projection 对应,用于 ActionDecoder + add_pos_embed: True + max_seq_len: 1024 + action_dim: 7 + state_dim: 7 + future_action_window_size: 15 + action_horizon: 16 + past_action_window_size: 0 + repeated_diffusion_steps: 8 + noise_beta_alpha: 1.5 + noise_beta_beta: 1.0 + noise_s: 0.999 + num_timestep_buckets: 1000 + num_inference_timesteps: 4 + num_target_vision_tokens: 32 + diffusion_model_cfg: # DiT Transformers 的参数 + cross_attention_dim: 2048 # VLM 的 dim + dropout: 0.2 + final_dropout: true + interleave_self_attention: true + norm_type: "ada_norm" + num_layers: 16 + output_dim: 2560 + positional_embeddings: null + + + +datasets: + vlm_data: + dataset_py: vlm_datasets + dataformat: llava_json + 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 + eval_dataset: aokvqa_cauldron_llava_format + data_flatten: false + base_interval: 2 + max_pixels: 50176 + min_pixels: 784 + model_max_length: 2048 + model_type: qwen2.5vl + per_device_batch_size: 4 + + vla_data: + dataset_py: lerobot_datasets + data_root_dir: playground/Datasets/OXE_LEROBOT_DATASET + data_mix: bridge_rt_1 # bridge_rt_1 + action_type: delta_ee + CoT_prompt: "Your task is {instruction}. To identify the key objects for your task. Locate their bounding boxes in [x1,y1,x2,y2] format." + CoT_answer: bbox + default_image_resolution: [3, 224, 224] + per_device_batch_size: 16 + load_all_data_for_training: true + obs: ["image_0"] + image_size: [224,224] + +trainer: + epochs: 100 + max_train_steps: 100000 + num_warmup_steps: 5000 + save_interval: 5000 + eval_interval: 100 + learning_rate: + base: 1e-05 + qwen_vl_interface: 1.0e-05 + action_model: 1.0e-04 + lr_scheduler_type: cosine_with_min_lr + scheduler_specific_kwargs: + min_lr: 5.0e-07 + freeze_modules: '' + loss_scale: + vla: 1.0 + vlm: 0.1 + # pretrained_checkpoint: ./results/Checkpoints/1_need/0601_qwenact_fixqwen_32gpus_lr_1e-3_qformer_36_37/steps_100000/pytorch_model.pt + # reload_modules: 'action_model,layer_qformer' # warning: this may cause model to not converge + repeated_diffusion_steps: 4 + max_grad_norm: 1.0 + warmup_ratio: 0.1 + weight_decay: 0.0 + logging_frequency: 10 + gradient_clipping: 1.0 + gradient_accumulation_steps: 1 + + optimizer: + name: AdamW + betas: [0.9, 0.95] + eps: 1.0e-08 + weight_decay: 1.0e-08 + + # parameters to be determined + is_resume: false + resume_epoch: null + resume_step: null + enable_gradient_checkpointing: true + enable_mixed_precision_training: true diff --git a/starVLA/config/training/starvla_train_adapter.yaml b/starVLA/config/training/starvla_train_adapter.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5ab740263e345541613b65e06a9c761877733aca --- /dev/null +++ b/starVLA/config/training/starvla_train_adapter.yaml @@ -0,0 +1,73 @@ +run_id: starvla +run_root_dir: path/to/result +seed: 42 +trackers: [jsonl, wandb] +wandb_entity: your-wandb-entity +wandb_project: your-wandb-project +is_debug: false + +framework: + name: QwenAdapter + qwenvl: + base_vlm: /path/to/your/qwen_vl_base_checkpoint + attn_implementation: flash_attention_2 + vl_hidden_dim: 2048 + action_model: + action_model_type: VLA-Adapter + hidden_dim: 2048 + action_dim: 14 + state_dim: 14 + action_query_num: 64 + use_pro_version: true # use the pro version of MLPResNet + use_proprio: false + phase: Training + num_actions_chunk: 16 + + +datasets: + vla_data: + dataset_py: lerobot_datasets + data_root_dir: path/to/train_data + data_mix: train_data + per_device_batch_size: 16 + num_workers: 16 + action_type: delta_qpos + + +trainer: + epochs: 100 + max_train_steps: 100000 + num_warmup_steps: 5000 + save_interval: 5000 + # save_interval: 5 + eval_interval: 100 + learning_rate: + base: 2.5e-05 + qwen_vl_interface: 1.0e-05 + action_model: 1.0e-04 + lr_scheduler_type: cosine_with_min_lr + scheduler_specific_kwargs: + min_lr: 1.0e-06 + freeze_modules: '' + loss_scale: + vla: 1.0 + vlm: 0.1 + max_grad_norm: 1.0 + warmup_ratio: 0.1 + weight_decay: 0.0 + logging_frequency: 10 + gradient_clipping: 1.0 + gradient_accumulation_steps: 1 + pretrained_checkpoint: "your pretrained checkpoint path" + optimizer: + name: AdamW + betas: [0.9, 0.95] + eps: 1.0e-08 + weight_decay: 1.0e-08 + + # parameters to be determined + is_resume: false + resume_epoch: null + resume_step: null + enable_gradient_checkpointing: true + enable_mixed_precision_training: true diff --git a/starVLA/dataloader/__init__.py b/starVLA/dataloader/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ef3f1b37dc255a6e81caffe2877bcd91a6a0f15b --- /dev/null +++ b/starVLA/dataloader/__init__.py @@ -0,0 +1,101 @@ +import json +import os +from accelerate.logging import get_logger +import numpy as np +from torch.utils.data import DataLoader +import numpy as np +import torch.distributed as dist +from pathlib import Path +from starVLA.dataloader.vlm_datasets import make_vlm_dataloader + +logger = get_logger(__name__) + +def save_dataset_statistics(dataset_statistics, run_dir): + """Saves a `dataset_statistics.json` file.""" + out_path = run_dir / "dataset_statistics.json" + with open(out_path, "w") as f_json: + for _, stats in dataset_statistics.items(): + for k in stats["action"].keys(): + if isinstance(stats["action"][k], np.ndarray): + stats["action"][k] = stats["action"][k].tolist() + if "proprio" in stats: + for k in stats["proprio"].keys(): + if isinstance(stats["proprio"][k], np.ndarray): + stats["proprio"][k] = stats["proprio"][k].tolist() + if "num_trajectories" in stats: + if isinstance(stats["num_trajectories"], np.ndarray): + stats["num_trajectories"] = stats["num_trajectories"].item() + if "num_transitions" in stats: + if isinstance(stats["num_transitions"], np.ndarray): + stats["num_transitions"] = stats["num_transitions"].item() + json.dump(dataset_statistics, f_json, indent=2) + logger.info(f"Saved dataset statistics file at path {out_path}") + + + +def build_dataloader(cfg, dataset_py="lerobot_datasets_oxe"): + # print("########### DATA.__init__.build_dataloader-1") + # print(dataset_py) # lerobot_datasets + + # VLA_Dataset + if dataset_py == "lerobot_datasets": + from starVLA.dataloader.lerobot_datasets import get_vla_dataset, collate_fn + vla_dataset_cfg = cfg.datasets.vla_data + # print(vla_dataset_cfg) + """ + dataset_py: lerobot_datasets + data_root_dir: /mnt/workspace/datasets/ + data_mix: robocasa_teleop_ee + action_type: delta_ee + CoT_prompt: Your task is {instruction}. To identify the key objects for your task. + Locate their bounding boxes in [x1,y1,x2,y2] format. + CoT_answer: bbox + default_image_resolution: + - 3 + - 224 + - 224 + per_device_batch_size: 16 + load_all_data_for_training: true + obs: + - image_0 + image_size: + - 224 + - 224 + delete_pause_frame: false + include_state: true + """ + vla_dataset = get_vla_dataset(data_cfg=vla_dataset_cfg) + # print(type(vla_dataset)) # + # print(cfg.datasets.vla_data.per_device_batch_size) # 16 + # print(collate_fn) # + num_workers = int(getattr(cfg.datasets.vla_data, "num_workers", 8)) + pin_memory = bool(getattr(cfg.datasets.vla_data, "pin_memory", True)) + persistent_workers = bool(getattr(cfg.datasets.vla_data, "persistent_workers", True)) + prefetch_factor = int(getattr(cfg.datasets.vla_data, "prefetch_factor", 2)) + + dataloader_kwargs = { + "batch_size": cfg.datasets.vla_data.per_device_batch_size, + "collate_fn": collate_fn, + "num_workers": num_workers, + "pin_memory": pin_memory, + "persistent_workers": persistent_workers if num_workers > 0 else False, + } + if num_workers > 0: + dataloader_kwargs["prefetch_factor"] = prefetch_factor + + vla_train_dataloader = DataLoader( + vla_dataset, + **dataloader_kwargs, + ) + if dist.get_rank() == 0: + output_dir = Path(cfg.output_dir) + vla_dataset.save_dataset_statistics(output_dir / "dataset_statistics.json") + # print("########### DATA.__init__.build_dataloader-2") + return vla_train_dataloader + + # VLM_Dataset + elif dataset_py == "vlm_datasets": + vlm_data_module = make_vlm_dataloader(cfg) + vlm_train_dataloader = vlm_data_module["train_dataloader"] + + return vlm_train_dataloader diff --git a/starVLA/dataloader/gr00t_lerobot/README.md b/starVLA/dataloader/gr00t_lerobot/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/starVLA/dataloader/gr00t_lerobot/__init__.py b/starVLA/dataloader/gr00t_lerobot/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/starVLA/dataloader/gr00t_lerobot/data_config.py b/starVLA/dataloader/gr00t_lerobot/data_config.py new file mode 100644 index 0000000000000000000000000000000000000000..dd807714c4a6a58e1ff143af808b9a04e5e8488e --- /dev/null +++ b/starVLA/dataloader/gr00t_lerobot/data_config.py @@ -0,0 +1,1208 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# + + +from abc import ABC, abstractmethod + +from starVLA.dataloader.gr00t_lerobot.datasets import ModalityConfig +from starVLA.dataloader.gr00t_lerobot.transform.base import ComposedModalityTransform, ModalityTransform +from starVLA.dataloader.gr00t_lerobot.transform.concat import ConcatTransform +from starVLA.dataloader.gr00t_lerobot.transform.state_action import ( + StateActionSinCosTransform, + StateActionToTensor, + StateActionTransform, +) +from starVLA.dataloader.gr00t_lerobot.transform.video import ( + VideoColorJitter, + VideoCrop, + VideoResize, + VideoToNumpy, + VideoToTensor, + VideoResizePad, +) +# from starVLA.dataloader.gr00t_lerobot.transform.gr00ttransform import GR00TTransform +from starVLA.dataloader.gr00t_lerobot.transform.gr00ttransform_1 import GR00TTransform + +class BaseDataConfig(ABC): + @abstractmethod + def modality_config(self) -> dict[str, ModalityConfig]: + pass + + @abstractmethod + def transform(self) -> ModalityTransform: + pass + + +########################################################################################### + +class OxeDroidDataConfig: + video_keys = [ + "video.exterior_image_1", + "video.exterior_image_2", + "video.wrist_image", + ] + state_keys = [ + "state.eef_position", + "state.eef_rotation", + "state.gripper_position", + ] + action_keys = [ + "action.eef_position_delta", + "action.eef_rotation_delta", + "action.gripper_position", + ] + language_keys = ["annotation.language.language_instruction"] + observation_indices = [0] + action_indices = list(range(16)) + + def modality_config(self): + video_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.video_keys, + ) + state_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.state_keys, + ) + action_modality = ModalityConfig( + delta_indices=self.action_indices, + modality_keys=self.action_keys, + ) + language_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.language_keys, + ) + modality_configs = { + "video": video_modality, + "state": state_modality, + "action": action_modality, + "language": language_modality, + } + return modality_configs + + def transform(self): + transforms = [ + # video transforms + VideoToTensor(apply_to=self.video_keys), + VideoCrop(apply_to=self.video_keys, scale=0.95), + VideoResize(apply_to=self.video_keys, height=224, width=224, interpolation="linear"), + VideoColorJitter( + apply_to=self.video_keys, + brightness=0.3, + contrast=0.4, + saturation=0.5, + hue=0.08, + ), + VideoToNumpy(apply_to=self.video_keys), + # state transforms + StateActionToTensor(apply_to=self.state_keys), + StateActionTransform( + apply_to=self.state_keys, + normalization_modes={ + "state.eef_position": "min_max", + "state.gripper_position": "min_max", + }, + target_rotations={ + "state.eef_rotation": "rotation_6d", + }, + ), + # action transforms + StateActionToTensor(apply_to=self.action_keys), + StateActionTransform( + apply_to=self.action_keys, + normalization_modes={ + "action.gripper_position": "binary", + }, + target_rotations={"action.eef_rotation_delta": "axis_angle"}, + ), + # concat transforms + ConcatTransform( + video_concat_order=self.video_keys, + state_concat_order=self.state_keys, + action_concat_order=self.action_keys, + ), + GR00TTransform( + state_horizon=len(self.observation_indices), + action_horizon=len(self.action_indices), + max_state_dim=64, + max_action_dim=32, + ), + ] + + return ComposedModalityTransform(transforms=transforms) + +class AgibotGenie1DataConfig(BaseDataConfig): + video_keys = [ + "video.image_head_color", + "video.image_hand_left", + "video.image_hand_right", + ] + state_keys = [ + # "state.camera_position", + "state.left_arm", + "state.left_gripper", + "state.right_arm", + "state.right_gripper", + "state.original_state_head_position", + "state.original_state_waist_position", + ] + action_keys = [ + # "action.camera_position", + "action.left_arm", + "action.left_gripper", + "action.right_arm", + "action.right_gripper", + "action.original_action_head_position", + "action.original_action_waist_position", + ] + language_keys = ["annotation.human.task_description", "annotation.human.subtask_description"] + observation_indices = [0] + # action_indices = list(range(30)) + action_indices = list(range(16)) + + def modality_config(self): + video_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.video_keys, + ) + state_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.state_keys, + ) + action_modality = ModalityConfig( + delta_indices=self.action_indices, + modality_keys=self.action_keys, + ) + language_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.language_keys, + ) + modality_configs = { + "video": video_modality, + "state": state_modality, + "action": action_modality, + "language": language_modality, + } + return modality_configs + + def transform(self): + transforms = [ + # video transforms - 为每个视角分别应用,避免不同尺寸的 concatenation 错误 + # 第一个视角:image_head_color + # VideoToTensor(apply_to=[self.video_keys[0]]), + # VideoResizePad(apply_to=[self.video_keys[0]], size=224, interpolation="linear", fill_value=0.0), + # VideoColorJitter( + # apply_to=[self.video_keys[0]], + # brightness=0.3, + # contrast=0.4, + # saturation=0.5, + # hue=0.08, + # ), + # VideoToNumpy(apply_to=[self.video_keys[0]]), + + # 第二个视角:image_hand_left + # VideoToTensor(apply_to=[self.video_keys[1]]), + # VideoResizePad(apply_to=[self.video_keys[1]], size=224, interpolation="linear", fill_value=0.0), + # VideoColorJitter( + # apply_to=[self.video_keys[1]], + # brightness=0.3, + # contrast=0.4, + # saturation=0.5, + # hue=0.08, + # ), + # VideoToNumpy(apply_to=[self.video_keys[1]]), + + # 第三个视角:image_hand_right + # VideoToTensor(apply_to=[self.video_keys[2]]), + # VideoResizePad(apply_to=[self.video_keys[2]], size=224, interpolation="linear", fill_value=0.0), + # VideoColorJitter( + # apply_to=[self.video_keys[2]], + # brightness=0.3, + # contrast=0.4, + # saturation=0.5, + # hue=0.08, + # ), + # VideoToNumpy(apply_to=[self.video_keys[2]]), + + # state transforms + StateActionToTensor(apply_to=self.state_keys), + StateActionTransform(apply_to=self.state_keys, + normalization_modes={key: "min_max" for key in self.state_keys}), + # action transforms + StateActionToTensor(apply_to=self.action_keys), + StateActionTransform( + apply_to=self.action_keys, + normalization_modes={key: "min_max" for key in self.action_keys}, + ), + # concat transforms - 现在所有视角都是 224x224,可以安全 concatenate + # ConcatTransform( + # video_concat_order=self.video_keys, + # state_concat_order=self.state_keys, + # action_concat_order=self.action_keys, + # ), + GR00TTransform( + state_horizon=len(self.observation_indices), + action_horizon=len(self.action_indices), + max_state_dim=64, + max_action_dim=32, + ), + ] + + return ComposedModalityTransform(transforms=transforms) + +# class EgoDexDataConfig(BaseDataConfig): +# video_keys = [ +# "video.image" +# ] +# state_keys = [ +# "state.right_pose", +# "state.right_hand", +# "state.left_pose", +# "state.left_hand" +# ] +# action_keys = [ +# "action.right_pose", +# "action.right_hand", +# "action.left_pose", +# "action.left_hand" +# ] + +# language_keys = ["annotation.human.task_description"] +# observation_indices = [0] +# # action_indices = list(range(16)) +# action_indices = list(range(30)) + +# def modality_config(self): +# video_modality = ModalityConfig( +# delta_indices=self.observation_indices, +# modality_keys=self.video_keys, +# ) +# state_modality = ModalityConfig( +# delta_indices=self.observation_indices, +# modality_keys=self.state_keys, +# ) +# action_modality = ModalityConfig( +# delta_indices=self.action_indices, +# modality_keys=self.action_keys, +# ) +# language_modality = ModalityConfig( +# delta_indices=self.observation_indices, +# modality_keys=self.language_keys, +# ) +# modality_configs = { +# "video": video_modality, +# "state": state_modality, +# "action": action_modality, +# "language": language_modality, +# } +# return modality_configs + +# def transform(self): +# transforms = [ +# # video transforms +# VideoToTensor(apply_to=self.video_keys), +# # VideoCrop(apply_to=self.video_keys, scale=0.95), +# # VideoResize(apply_to=self.video_keys, height=224, width=224, interpolation="linear"), +# VideoResizePad(apply_to=self.video_keys, size=224, interpolation="linear", fill_value=0.0), +# VideoColorJitter( +# apply_to=self.video_keys, +# brightness=0.3, +# contrast=0.4, +# saturation=0.5, +# hue=0.08, +# ), +# VideoToNumpy(apply_to=self.video_keys), +# # state transforms +# StateActionToTensor(apply_to=self.state_keys), +# StateActionTransform( +# apply_to=self.state_keys, +# normalization_modes={ +# "state.right_pose": "mean_std", +# "state.left_pose": "mean_std", +# "state.right_hand": "min_max", +# "state.left_hand": "min_max", +# }, +# # normalization_modes={key: "min_max" for key in self.state_keys}, +# ), +# # action transforms +# StateActionToTensor(apply_to=self.action_keys), +# StateActionTransform( +# apply_to=self.action_keys, +# normalization_modes={ +# "action.right_pose": "mean_std", +# "action.left_pose": "mean_std", +# "action.right_hand": "min_max", +# "action.left_hand": "min_max", +# }, +# # normalization_modes={key: "min_max" for key in self.action_keys}, +# ), +# # concat transforms +# ConcatTransform( +# video_concat_order=self.video_keys, +# state_concat_order=self.state_keys, +# action_concat_order=self.action_keys, +# ), +# GR00TTransform( +# state_horizon=len(self.observation_indices), +# action_horizon=len(self.action_indices), +# max_state_dim=64, +# max_action_dim=32, +# ), +# ] + +# return ComposedModalityTransform(transforms=transforms) + +########################################################################################### + + +class OxeBridgeDataConfig: + video_keys = [ + "video.image_0", + ] + state_keys = [ + "state.x", + "state.y", + "state.z", + "state.roll", + "state.pitch", + "state.yaw", + "state.pad", + "state.gripper", + ] + action_keys = [ + "action.x", + "action.y", + "action.z", + "action.roll", + "action.pitch", + "action.yaw", + "action.gripper", + ] + language_keys = ["annotation.human.action.task_description"] + observation_indices = [0] + action_indices = list(range(16)) + + def modality_config(self): + video_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.video_keys, + ) + state_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.state_keys, + ) + action_modality = ModalityConfig( + delta_indices=self.action_indices, + modality_keys=self.action_keys, + ) + language_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.language_keys, + ) + modality_configs = { + "video": video_modality, + "state": state_modality, + "action": action_modality, + "language": language_modality, + } + return modality_configs + + def transform(self): + transforms = [ + # video transforms + # VideoToTensor(apply_to=self.video_keys), + # VideoCrop(apply_to=self.video_keys, scale=0.95), + # VideoResize(apply_to=self.video_keys, height=224, width=224, interpolation="linear"), + # VideoColorJitter( + # apply_to=self.video_keys, + # brightness=0.3, + # contrast=0.4, + # saturation=0.5, + # hue=0.08, + # ), + # VideoToNumpy(apply_to=self.video_keys), + # state transforms + StateActionToTensor(apply_to=self.state_keys), + StateActionTransform( + apply_to=self.state_keys, + normalization_modes={ + "state.x": "q99", + "state.y": "q99", + "state.z": "q99", + "state.roll": "q99", + "state.pitch": "q99", + "state.yaw": "q99", + "state.pad": "q99", + "state.gripper": "binary", + }, + ), + # action transforms + StateActionToTensor(apply_to=self.action_keys), + StateActionTransform( + apply_to=self.action_keys, + normalization_modes={ + "action.x": "q99", + "action.y": "q99", + "action.z": "q99", + "action.roll": "q99", + "action.pitch": "q99", + "action.yaw": "q99", + "action.gripper": "binary", + }, + ), + # concat transforms + # ConcatTransform( + # # video_concat_order=self.video_keys, + # state_concat_order=self.state_keys, + # action_concat_order=self.action_keys, + # ), + # GR00TTransform( + # state_horizon=len(self.observation_indices), + # action_horizon=len(self.action_indices), + # max_state_dim=64, + # max_action_dim=32, + # ), + ] + + return ComposedModalityTransform(transforms=transforms) + + +########################################################################################### + +class OxeRT1DataConfig: + video_keys = [ + "video.image", + ] + state_keys = [ + "state.x", + "state.y", + "state.z", + "state.rx", + "state.ry", + "state.rz", + "state.rw", + "state.gripper", + ] + action_keys = [ + "action.x", + "action.y", + "action.z", + "action.roll", + "action.pitch", + "action.yaw", + "action.gripper", + ] + language_keys = ["annotation.human.action.task_description"] + observation_indices = [0] + action_indices = list(range(16)) + + def modality_config(self): + video_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.video_keys, + ) + state_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.state_keys, + ) + action_modality = ModalityConfig( + delta_indices=self.action_indices, + modality_keys=self.action_keys, + ) + language_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.language_keys, + ) + modality_configs = { + "video": video_modality, + "state": state_modality, + "action": action_modality, + "language": language_modality, + } + return modality_configs + + def transform(self): + transforms = [ + # video transforms + # VideoToTensor(apply_to=self.video_keys), + # VideoCrop(apply_to=self.video_keys, scale=0.95), + # VideoResize(apply_to=self.video_keys, height=224, width=224, interpolation="linear"), + # VideoColorJitter( + # apply_to=self.video_keys, + # brightness=0.3, + # contrast=0.4, + # saturation=0.5, + # hue=0.08, + # ), + # VideoToNumpy(apply_to=self.video_keys), + # state transforms + StateActionToTensor(apply_to=self.state_keys), + StateActionTransform( + apply_to=self.state_keys, + normalization_modes={ + "state.x": "q99", + "state.y": "q99", + "state.z": "q99", + "state.rx": "q99", + "state.ry": "q99", + "state.rz": "q99", + "state.rw": "q99", + "state.gripper": "binary", + }, + ), + # action transforms + StateActionToTensor(apply_to=self.action_keys), + StateActionTransform( + apply_to=self.action_keys, + normalization_modes={ + "action.x": "q99", + "action.y": "q99", + "action.z": "q99", + "action.roll": "q99", + "action.pitch": "q99", + "action.yaw": "q99", + "action.gripper": "binary", + }, + ), + # concat transforms + # ConcatTransform( + # # video_concat_order=self.video_keys, + # state_concat_order=self.state_keys, + # action_concat_order=self.action_keys, + # ), + # GR00TTransform( + # state_horizon=len(self.observation_indices), + # action_horizon=len(self.action_indices), + # max_state_dim=64, + # max_action_dim=32, + # ), + ] + + return ComposedModalityTransform(transforms=transforms) + + +########################################################################################### + + +class SingleFrankaRobotiqDeltaEefDataConfig: + video_keys = [ + "video.base_view", + "video.ego_view", + ] + state_keys = [ + "state.eef_position", + "state.eef_rotation", + ] + action_keys = [ + "action.delta_eef_position", + "action.delta_eef_rotation", + "action.gripper_close", + ] + + language_keys = ["annotation.human.action.task_description"] + observation_indices = [0] + action_indices = list(range(16)) + + def modality_config(self): + video_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.video_keys, + ) + state_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.state_keys, + ) + action_modality = ModalityConfig( + delta_indices=self.action_indices, + modality_keys=self.action_keys, + ) + language_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.language_keys, + ) + modality_configs = { + "video": video_modality, + "state": state_modality, + "action": action_modality, + "language": language_modality, + } + return modality_configs + + def transform(self): + transforms = [ + # state transforms + StateActionToTensor(apply_to=self.state_keys), + StateActionTransform( + apply_to=self.state_keys, + normalization_modes={ + "state.eef_position": "min_max", + "state.eef_rotation": "min_max", + }, + ), + # action transforms + StateActionToTensor(apply_to=self.action_keys), + StateActionTransform( + apply_to=self.action_keys, + normalization_modes={ + "action.delta_eef_position": "min_max", + "action.delta_eef_rotation": "min_max", + "action.gripper_close": "binary", + }, + ), + ] + + return ComposedModalityTransform(transforms=transforms) + +########################################################################################### + +class Libero4in1DataConfig: + video_keys = [ + "video.primary_image", + "video.wrist_image", + ] + + state_keys = [ + "state.x", + "state.y", + "state.z", + "state.roll", + "state.pitch", + "state.yaw", + "state.pad", + "state.gripper", + ] + action_keys = [ + "action.x", + "action.y", + "action.z", + "action.roll", + "action.pitch", + "action.yaw", + "action.gripper", + ] + + language_keys = ["annotation.human.action.task_description"] + + observation_indices = [0] + action_indices = list(range(8)) + + + def modality_config(self): + video_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.video_keys, + ) + state_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.state_keys, + ) + action_modality = ModalityConfig( + delta_indices=self.action_indices, + modality_keys=self.action_keys, + ) + language_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.language_keys, + ) + modality_configs = { + "video": video_modality, + "state": state_modality, + "action": action_modality, + "language": language_modality, + } + return modality_configs + + def transform(self): + transforms = [ + # action transforms + StateActionToTensor(apply_to=self.action_keys), + StateActionTransform( + apply_to=self.action_keys, + normalization_modes={ + "action.x": "min_max", + "action.y": "min_max", + "action.z": "min_max", + "action.roll": "min_max", + "action.pitch": "min_max", + "action.yaw": "min_max", + }, + ), + ] + + return ComposedModalityTransform(transforms=transforms) + +########################################################################################### + + +class SingleFrankaRobotiqDeltaJointsDataConfig: + video_keys = [ + "video.base_view", + "video.ego_view", + ] + state_keys = [ + "state.joints", + ] + action_keys = [ + "action.delta_joints", + "action.gripper_close", + ] + + language_keys = ["annotation.human.action.task_description"] + observation_indices = [0] + action_indices = list(range(16)) + + def modality_config(self): + video_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.video_keys, + ) + state_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.state_keys, + ) + action_modality = ModalityConfig( + delta_indices=self.action_indices, + modality_keys=self.action_keys, + ) + language_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.language_keys, + ) + modality_configs = { + "video": video_modality, + "state": state_modality, + "action": action_modality, + "language": language_modality, + } + return modality_configs + + def transform(self): + transforms = [ + # state transforms + StateActionToTensor(apply_to=self.state_keys), + StateActionTransform( + apply_to=self.state_keys, + normalization_modes={ + "state.joints": "min_max", + }, + ), + # action transforms + StateActionToTensor(apply_to=self.action_keys), + StateActionTransform( + apply_to=self.action_keys, + normalization_modes={ + "action.delta_joints": "min_max", + "action.gripper_close": "binary", + }, + ), + ] + + return ComposedModalityTransform(transforms=transforms) + + +########################################################################################### + +class FourierGr1ArmsWaistDataConfig: + video_keys = ["video.ego_view"] + state_keys = [ + "state.left_arm", + "state.right_arm", + "state.left_hand", + "state.right_hand", + "state.waist", + ] + action_keys = [ + "action.left_arm", + "action.right_arm", + "action.left_hand", + "action.right_hand", + "action.waist", + ] + language_keys = ["annotation.human.coarse_action"] + observation_indices = [0] + action_indices = list(range(16)) + + + def modality_config(self): + video_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.video_keys, + ) + state_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.state_keys, + ) + action_modality = ModalityConfig( + delta_indices=self.action_indices, + modality_keys=self.action_keys, + ) + language_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.language_keys, + ) + modality_configs = { + "video": video_modality, + "state": state_modality, + "action": action_modality, + "language": language_modality, + } + return modality_configs + + def transform(self) -> ModalityTransform: + transforms = [ + # video transforms + # VideoToTensor(apply_to=self.video_keys), + # VideoCrop(apply_to=self.video_keys, scale=0.95), + # VideoResize(apply_to=self.video_keys, height=224, width=224, interpolation="linear"), + # VideoResizePad(apply_to=self.video_keys, size=224, interpolation="linear", fill_value=0.0), + # VideoColorJitter( + # apply_to=self.video_keys, + # brightness=0.3, + # contrast=0.4, + # saturation=0.5, + # hue=0.08, + # ), + # VideoToNumpy(apply_to=self.video_keys), + # state transforms + StateActionToTensor(apply_to=self.state_keys), + # StateActionSinCosTransform(apply_to=self.state_keys), + StateActionTransform( + apply_to=self.state_keys, + normalization_modes={key: "min_max" for key in self.state_keys}, + ), + + # action transforms + StateActionToTensor(apply_to=self.action_keys), + StateActionTransform( + apply_to=self.action_keys, + normalization_modes={key: "min_max" for key in self.action_keys}, + ), + # concat transforms + # ConcatTransform( + # video_concat_order=self.video_keys, + # state_concat_order=self.state_keys, + # action_concat_order=self.action_keys, + # ), + # concat transforms + # ConcatTransform( + # video_concat_order=self.video_keys, + # state_concat_order=self.state_keys, + # action_concat_order=self.action_keys, + # ), + GR00TTransform( + state_horizon=len(self.observation_indices), + action_horizon=len(self.action_indices), + max_state_dim=64, + max_action_dim=32, + ), + ] + return ComposedModalityTransform(transforms=transforms) + + +########################################################################################### + +class EgoDexDataConfig(FourierGr1ArmsWaistDataConfig): + video_keys = [ + "video.image" + ] + state_keys = [ + "state.right_pose", + "state.right_hand", + "state.left_pose", + "state.left_hand" + ] + action_keys = [ + "action.right_pose", + "action.right_hand", + "action.left_pose", + "action.left_hand" + ] + + language_keys = ["annotation.human.task_description"] + observation_indices = [0] + action_indices = list(range(16)) + # action_indices = list(range(30)) + + +class NvwaDataConfig(EgoDexDataConfig): + language_keys = ["annotation.human.task_description", "annotation.human.subtask_description"] + + +class RoboTwinDataConfig(AgibotGenie1DataConfig): + video_keys = ["video.image_high", "video.image_left_wrist", "video.image_right_wrist"] + state_keys = [ + "state.left_arm", + "state.left_gripper", + "state.right_arm", + "state.right_gripper", + ] + action_keys = [ + "action.left_arm", + "action.left_gripper", + "action.right_arm", + "action.right_gripper", + ] + language_keys = ["annotation.human.task_description"] + observation_indices = [0] + action_indices = list(range(50)) + + +########################################################################################### + +class SO101Config: + #input + video_keys = [ + "video.primary_image", + "video.wrist_image", + ] + + state_keys = [ + "state.shoulder_pan.pos", + "state.shoulder_lift.pos", + "state.elbow_flex.pos", + "state.wrist_flex.pos", + "state.wrist_roll.pos", + "state.gripper.pos", + ] + language_keys = ["annotation.human.action.task_description"] + + # output + action_keys = [ + "action.shoulder_pan.pos", + "action.shoulder_lift.pos", + "action.elbow_flex.pos", + "action.wrist_flex.pos", + "action.wrist_roll.pos", + "action.gripper.pos", + ] + + + observation_indices = [0] + action_indices = list(range(16)) + + + def modality_config(self): + video_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.video_keys, + ) + state_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.state_keys, + ) + action_modality = ModalityConfig( + delta_indices=self.action_indices, + modality_keys=self.action_keys, + ) + language_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.language_keys, + ) + modality_configs = { + "video": video_modality, + "state": state_modality, + "action": action_modality, + "language": language_modality, + } + return modality_configs + + def transform(self): + transforms = [ + # state transforms + StateActionToTensor(apply_to=self.state_keys), + StateActionTransform( + apply_to=self.state_keys, + normalization_modes={ + key: "min_max" for key in self.state_keys + }, + ), + # action transforms + StateActionToTensor(apply_to=self.action_keys), + StateActionTransform( + apply_to=self.action_keys, + normalization_modes={ + key: "min_max" for key in self.action_keys + }, + ), + ] + + return ComposedModalityTransform(transforms=transforms) + + + +class ArxX5DataConfig: + video_keys = [ + "video.cam_high", + "video.cam_left_wrist", + "video.cam_right_wrist", + ] + state_keys = [ + "state.left_joints", + "state.right_joints", + "state.left_gripper", + "state.right_gripper", + ] + action_keys = [ + "action.left_joints", + "action.right_joints", + "action.left_gripper", + "action.right_gripper", + ] + + language_keys = ["annotation.human.action.task_description"] + observation_indices = [0] + action_indices = list(range(16)) + + def modality_config(self): + video_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.video_keys, + ) + state_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.state_keys, + ) + action_modality = ModalityConfig( + delta_indices=self.action_indices, + modality_keys=self.action_keys, + ) + language_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.language_keys, + ) + modality_configs = { + "video": video_modality, + "state": state_modality, + "action": action_modality, + "language": language_modality, + } + return modality_configs + + def transform(self): + transforms = [ + # state transforms + StateActionToTensor(apply_to=self.state_keys), + StateActionTransform( + apply_to=self.state_keys, + normalization_modes={ + "state.left_joints": "min_max", + "state.right_joints": "min_max", + "state.left_gripper": "binary", + "state.right_gripper": "binary", + }, + ), + # action transforms + StateActionToTensor(apply_to=self.action_keys), + StateActionTransform( + apply_to=self.action_keys, + normalization_modes={ + "action.left_joints": "min_max", + "action.right_joints": "min_max", + "action.left_gripper": "binary", + "action.right_gripper": "binary", + }, + ), + ] + + return ComposedModalityTransform(transforms=transforms) + +########################################################################################### + + +class AgilexDataConfig: + video_keys = [ + "video.cam_high", + "video.cam_left_wrist", + "video.cam_right_wrist", + ] + state_keys = [ + "state.left_joints", + "state.right_joints", + "state.left_gripper", + "state.right_gripper", + ] + action_keys = [ + "action.left_joints", + "action.right_joints", #@JinhuiYE this order is different from Dataset + "action.left_gripper", + "action.right_gripper", + ] + + language_keys = ["annotation.human.action.task_description"] + observation_indices = [0] + action_indices = list(range(16)) + + def modality_config(self): + video_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.video_keys, + ) + state_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.state_keys, + ) + action_modality = ModalityConfig( + delta_indices=self.action_indices, + modality_keys=self.action_keys, + ) + language_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.language_keys, + ) + modality_configs = { + "video": video_modality, + "state": state_modality, + "action": action_modality, + "language": language_modality, + } + return modality_configs + + def transform(self): + transforms = [ + # state transforms + StateActionToTensor(apply_to=self.state_keys), + StateActionTransform( + apply_to=self.state_keys, + normalization_modes={ + "state.left_joints": "min_max", + "state.right_joints": "min_max", + "state.left_gripper": "binary", + "state.right_gripper": "binary", + }, + ), + # action transforms + StateActionToTensor(apply_to=self.action_keys), + StateActionTransform( + apply_to=self.action_keys, + normalization_modes={ + "action.left_joints": "min_max", + "action.right_joints": "min_max", + "action.left_gripper": "binary", + "action.right_gripper": "binary", + }, + ), + ] + + return ComposedModalityTransform(transforms=transforms) + +########################################################################################### + + +ROBOT_TYPE_CONFIG_MAP = { + "libero_franka": Libero4in1DataConfig(), + "oxe_droid": OxeDroidDataConfig(), + "oxe_bridge": OxeBridgeDataConfig(), + "oxe_rt1": OxeRT1DataConfig(), + "SO101": SO101Config(), + "demo_sim_franka_delta_joints": SingleFrankaRobotiqDeltaJointsDataConfig(), + "arx_x5": ArxX5DataConfig(), + "robotwin": RoboTwinDataConfig(), + "fourier_gr1_arms_waist": FourierGr1ArmsWaistDataConfig(), + "fourier_gr1_arms_waist2": FourierGr1ArmsWaistDataConfig(), + "agibot_genie1": AgibotGenie1DataConfig(), + "agibot_beta": AgibotGenie1DataConfig(), + "egodex": EgoDexDataConfig(), + "nvwa_f": NvwaDataConfig(), + "custom_robot_config": SingleFrankaRobotiqDeltaEefDataConfig(), +} diff --git a/starVLA/dataloader/gr00t_lerobot/datasets.py b/starVLA/dataloader/gr00t_lerobot/datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..c30ceac36e981249a58ada844edff30ba991d830 --- /dev/null +++ b/starVLA/dataloader/gr00t_lerobot/datasets.py @@ -0,0 +1,2838 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +""" +In this file, we define 3 types of datasets: +1. LeRobotSingleDataset: a single dataset for a given embodiment tag +2. LeRobotMixtureDataset: a mixture of datasets for a given list of embodiment tags +3. CachedLeRobotSingleDataset: a single dataset for a given embodiment tag, + with caching for the video frames + +See `scripts/load_dataset.py` for examples on how to use these datasets. +""" +import os +import hashlib +import json, torch +from collections import defaultdict +from pathlib import Path +from typing import Sequence +import os, random +import numpy as np +import pandas as pd +from pydantic import BaseModel, Field, ValidationError +from torch.utils.data import Dataset +from tqdm import tqdm +from PIL import Image + +from starVLA.dataloader.gr00t_lerobot.video import get_all_frames, get_frames_by_timestamps + +from starVLA.dataloader.gr00t_lerobot.embodiment_tags import EmbodimentTag, EMBODIMENT_TAG_MAPPING +from starVLA.dataloader.gr00t_lerobot.schema import ( + DatasetMetadata, + DatasetStatisticalValues, + LeRobotModalityMetadata, + LeRobotStateActionMetadata, +) +from starVLA.dataloader.gr00t_lerobot.transform import ComposedModalityTransform + +from functools import partial +from typing import Tuple, List +import pickle +import gc +from concurrent.futures import ThreadPoolExecutor, as_completed + +# LeRobot v2.0 dataset file names +LE_ROBOT_MODALITY_FILENAME = "meta/modality.json" +LE_ROBOT_EPISODE_FILENAME = "meta/episodes.jsonl" +LE_ROBOT_TASKS_FILENAME = "meta/tasks.jsonl" +LE_ROBOT_INFO_FILENAME = "meta/info.json" +LE_ROBOT_STATS_FILENAME = "meta/stats_gr00t_old.json" +LE_ROBOT_DATA_FILENAME = "data/*/*.parquet" +LE_ROBOT_STEPS_FILENAME = "meta/steps.pkl" +LE_ROBOT_SUBTASKS_FILENAME = "meta/subtasks.jsonl" +EPSILON = 5e-4 + +# LeRobot v3.0 dataset file names +LE_ROBOT3_TASKS_FILENAME = "meta/tasks.parquet" +LE_ROBOT3_EPISODE_FILENAME = "meta/episodes/*/*.parquet" + + +# def calculate_dataset_statistics(parquet_paths: list[Path]) -> dict: +# """Calculate the dataset statistics of all columns for a list of parquet files.""" +# # Dataset statistics +# all_low_dim_data_list = [] +# # Collect all the data +# # parquet_paths = parquet_paths[:3] +# for parquet_path in tqdm( +# sorted(list(parquet_paths)), +# desc="Collecting all parquet files...", +# ): +# # Load the parquet file +# parquet_data = pd.read_parquet(parquet_path) +# parquet_data = parquet_data +# all_low_dim_data_list.append(parquet_data) + +# all_low_dim_data = pd.concat(all_low_dim_data_list, axis=0) +# # Compute dataset statistics +# dataset_statistics = {} +# for le_modality in tqdm(all_low_dim_data.columns, desc="Processing modalities"): +# print(le_modality) +# if "task_info" in le_modality: +# continue +# print(f"Computing statistics for {le_modality}...") +# # 检查数据是否为空或无效 +# try: +# np_data = np.vstack( +# [np.asarray(x, dtype=np.float32) for x in all_low_dim_data[le_modality]] +# ) +# except Exception as e: +# print(f"Warning: Failed to process modality {le_modality} due to error: {e}") +# continue + +# dataset_statistics[le_modality] = { +# "mean": np.mean(np_data, axis=0).tolist(), +# "std": np.std(np_data, axis=0).tolist(), +# "min": np.min(np_data, axis=0).tolist(), +# "max": np.max(np_data, axis=0).tolist(), +# "q01": np.quantile(np_data, 0.01, axis=0).tolist(), +# "q99": np.quantile(np_data, 0.99, axis=0).tolist(), +# } +# return dataset_statistics + + +def _read_parquet_batch(paths: list[Path]) -> pd.DataFrame: + """Read a batch of parquet files and concatenate. Used for parallel loading.""" + dfs = [pd.read_parquet(p) for p in paths] + return pd.concat(dfs, axis=0) if dfs else pd.DataFrame() + + +def _merge_rank_stats(rank_stats_list: list[dict]) -> dict: + """Merge per-rank stats (n, sum, sum_sq, min, max, q01, q99) into one dataset_statistics dict. + Key order follows the first rank's keys (same as pandas column order), then any extra keys from other ranks sorted. + """ + if not rank_stats_list: + return {} + # Preserve order: first rank's keys (matches single-rank / pandas column order), then sorted union of rest + order = list(rank_stats_list[0].keys()) + seen = set(order) + for r in rank_stats_list[1:]: + for k in r: + if k not in seen: + seen.add(k) + order.append(k) + out = {} + for mod in order: + # Only merge ranks that have this modality + ranks_with_mod = [r for r in rank_stats_list if mod in r] + if not ranks_with_mod: + continue + n_total = sum(r[mod]["n"] for r in ranks_with_mod) + if n_total == 0: + continue + sum_ = sum(r[mod]["sum"] for r in ranks_with_mod) + sum_sq = sum(r[mod]["sum_sq"] for r in ranks_with_mod) + mins = np.array([r[mod]["min"] for r in ranks_with_mod]) + maxs = np.array([r[mod]["max"] for r in ranks_with_mod]) + q01s = np.array([r[mod]["q01"] for r in ranks_with_mod]) + q99s = np.array([r[mod]["q99"] for r in ranks_with_mod]) + ns = np.array([r[mod]["n"] for r in ranks_with_mod], dtype=np.float64) + + mean = sum_ / n_total + var = np.maximum((sum_sq / n_total) - (mean**2), 0.0) + std = np.sqrt(var) + q01 = np.average(q01s, axis=0, weights=ns).tolist() + q99 = np.average(q99s, axis=0, weights=ns).tolist() + + out[mod] = { + "mean": (mean if isinstance(mean, np.ndarray) else np.array(mean)).tolist(), + "std": (std if isinstance(std, np.ndarray) else np.array(std)).tolist(), + "min": np.min(mins, axis=0).tolist(), + "max": np.max(maxs, axis=0).tolist(), + "q01": q01, + "q99": q99, + } + return out + + +def _stack_column_to_array(series: pd.Series) -> np.ndarray: + """Stack series of array-like to (N, dim) float64.""" + n = len(series) + it = iter(series) + first = np.asarray(next(it), dtype=np.float64) + d = first.size + out = np.empty((n, d), dtype=np.float64) + out[0] = first + for i in range(1, n): + out[i] = np.asarray(next(it), dtype=np.float64) + return out + + +def _compute_local_stats( + sorted_paths: list[Path], + batch_size: int, + n_workers: int, + parallel_modalities: int, + max_paths: int | None, + tqdm_desc: str = "Loading & streaming stats...", +) -> dict: + """Compute per-modality (n, sum, sum_sq, min, max, q01, q99) on the given paths. Used by single-rank and per-rank in multi-rank.""" + if not sorted_paths: + return {} + paths = sorted_paths[:max_paths] if max_paths is not None else sorted_paths + sample_df = pd.read_parquet(paths[0]) + modalities = [c for c in sample_df.columns if "task_info" not in c] + del sample_df + + running = {} + modality_arrays = defaultdict(list) + n_batches = (len(paths) + batch_size - 1) // batch_size + + def _read_batch(batch_paths: list, executor: ThreadPoolExecutor | None) -> pd.DataFrame: + if n_workers <= 1 or executor is None: + return _read_parquet_batch(batch_paths) + dfs = list(executor.map(pd.read_parquet, batch_paths)) + return pd.concat(dfs, axis=0) if dfs else pd.DataFrame() + + executor_ctx = ThreadPoolExecutor(max_workers=n_workers) if n_workers > 1 else None + try: + for batch_start in tqdm(range(0, len(paths), batch_size), desc=tqdm_desc, total=n_batches): + batch_paths = paths[batch_start:batch_start + batch_size] + batch_df = _read_batch(batch_paths, executor_ctx) + + for le_modality in modalities: + if le_modality not in batch_df.columns: + continue + try: + np_data = _stack_column_to_array(batch_df[le_modality]) + except Exception as e: + print(f"Warning: Failed to process modality {le_modality} due to error: {e}") + continue + n = np_data.shape[0] + s = np_data.sum(axis=0) + s_sq = (np_data.astype(np.float64)**2).sum(axis=0) + mn, mx = np_data.min(axis=0), np_data.max(axis=0) + if le_modality not in running: + running[le_modality] = {"n": n, "sum": s, "sum_sq": s_sq, "min": mn.copy(), "max": mx.copy()} + else: + r = running[le_modality] + r["n"] += n + r["sum"] += s + r["sum_sq"] += s_sq + r["min"] = np.minimum(r["min"], mn) + r["max"] = np.maximum(r["max"], mx) + modality_arrays[le_modality].append(np_data) + del batch_df + finally: + if executor_ctx is not None: + executor_ctx.shutdown(wait=True) + + # Build local stats: n, sum, sum_sq, min, max, q01, q99 (for merge) + local = {} + for le_modality, r in running.items(): + if r["n"] == 0: + continue + arrs = modality_arrays.get(le_modality, []) + if arrs: + full = np.concatenate(arrs, axis=0) if len(arrs) > 1 else arrs[0] + q01 = np.quantile(full, 0.01, axis=0) + q99 = np.quantile(full, 0.99, axis=0) + else: + q01 = r["min"].copy() + q99 = r["max"].copy() + local[le_modality] = { + "n": r["n"], + "sum": r["sum"], + "sum_sq": r["sum_sq"], + "min": r["min"], + "max": r["max"], + "q01": q01, + "q99": q99, + } + return local + + +def calculate_dataset_statistics( + parquet_paths: list[Path], + batch_size: int = 3000, + n_workers: int = 16, + parallel_modalities: int = 0, + stats_output_path: Path | str | None = None, +) -> dict: + """Calculate the dataset statistics of all columns for a list of parquet files. + + Optimizations: + - Single pass, stream batch-by-batch; merge mean/std/min/max incrementally. + - One shared ThreadPoolExecutor per run; parallel parquet read per batch (n_workers). + - Multi-rank: when torch.distributed is initialized and stats_output_path is set, + paths are split across ranks, each rank computes on its subset, then rank 0 merges + and writes; all ranks load the result. Speeds up proportionally to world_size. + """ + sorted_paths = sorted(list(parquet_paths)) + + if not sorted_paths: + return {} + + dist = torch.distributed + use_multi_rank = (dist.is_initialized() and dist.get_world_size() > 1 and stats_output_path is not None) + stats_output_path = Path(stats_output_path) if stats_output_path else None + + if use_multi_rank: + rank = dist.get_rank() + world_size = dist.get_world_size() + # Interleaved split for better load balance when file sizes vary + my_paths = [p for i, p in enumerate(sorted_paths) if i % world_size == rank] + if not my_paths: + local_stats = {} + else: + local_stats = _compute_local_stats( + my_paths, + batch_size=batch_size, + n_workers=n_workers, + parallel_modalities=0, + max_paths=None, + tqdm_desc=f"Rank {rank} stats", + ) + # Serialize for rank 0 to gather (n, sum, sum_sq, min, max, q01, q99 are numpy/list) + tmp_dir = stats_output_path.parent + tmp_dir.mkdir(parents=True, exist_ok=True) + rank_pkl = tmp_dir / f".stats_rank_{rank}.pkl" + with open(rank_pkl, "wb") as f: + pickle.dump(local_stats, f, protocol=pickle.HIGHEST_PROTOCOL) + + dist.barrier() + + if rank == 0: + all_stats = [] + for r in range(world_size): + pkl_path = tmp_dir / f".stats_rank_{r}.pkl" + with open(pkl_path, "rb") as f: + all_stats.append(pickle.load(f)) + try: + pkl_path.unlink() + except OSError: + pass + dataset_statistics = _merge_rank_stats(all_stats) + with open(stats_output_path, "w", encoding="utf-8") as f: + json.dump(dataset_statistics, f, indent=4, ensure_ascii=False) + + dist.barrier() + + with open(stats_output_path, "r", encoding="utf-8") as f: + return json.load(f) + + # Single process or no stats_output_path + local = _compute_local_stats( + sorted_paths, + batch_size=batch_size, + n_workers=n_workers, + parallel_modalities=parallel_modalities, + max_paths=None, + ) + return _merge_rank_stats([local]) + + +class ModalityConfig(BaseModel): + """Configuration for a modality.""" + + delta_indices: list[int] + """Delta indices to sample relative to the current index. The returned data will correspond to the original data at a sampled base index + delta indices.""" + modality_keys: list[str] + """The keys to load for the modality in the dataset.""" + + +class LeRobotSingleDataset(Dataset): + """ + Base dataset class for LeRobot that supports sharding. + """ + def __init__( + self, + dataset_path: Path | str, + modality_configs: dict[str, ModalityConfig], + embodiment_tag: str | EmbodimentTag, + video_backend: str = "decord", + video_backend_kwargs: dict | None = None, + transforms: ComposedModalityTransform | None = None, + delete_pause_frame: bool = False, + data_cfg = None, + **kwargs, + ): + """ + Initialize the dataset. + + Args: + dataset_path (Path | str): The path to the dataset. + modality_configs (dict[str, ModalityConfig]): The configuration for each modality. The keys are the modality names, and the values are the modality configurations. + See `ModalityConfig` for more details. + video_backend (str): Backend for video reading. + video_backend_kwargs (dict): Keyword arguments for the video backend when initializing the video reader. + transforms (ComposedModalityTransform): The transforms to apply to the dataset. + embodiment_tag (EmbodimentTag): Overload the embodiment tag for the dataset. e.g. define it as "new_embodiment" + """ + # first check if the path directory exists + self.data_cfg = data_cfg + if not Path(dataset_path).exists(): + raise FileNotFoundError(f"Dataset path {dataset_path} does not exist") + # indict letobot version + self._lerobot_version = self.data_cfg.get("lerobot_version", "v2.0") #self._indict_lerobot_version(**kwargs) + + self.delete_pause_frame = delete_pause_frame + + self.modality_configs = modality_configs + self.video_backend = video_backend + self.video_backend_kwargs = video_backend_kwargs if video_backend_kwargs is not None else {} + self.transforms = ( + transforms if transforms is not None else ComposedModalityTransform(transforms=[]) + ) + + self._dataset_path = Path(dataset_path) + self._dataset_name = self._dataset_path.name + if isinstance(embodiment_tag, EmbodimentTag): + self.tag = embodiment_tag.value + self.tag_index = EMBODIMENT_TAG_MAPPING[self.tag] + else: + self.tag = embodiment_tag + self.tag_index = EMBODIMENT_TAG_MAPPING[EmbodimentTag.NEW_EMBODIMENT.value] + + + self._metadata = self._get_metadata(EmbodimentTag(self.tag)) + + # LeRobot-specific config + self._lerobot_modality_meta = self._get_lerobot_modality_meta() + self._lerobot_info_meta = self._get_lerobot_info_meta() + self._data_path_pattern = self._get_data_path_pattern() + self._video_path_pattern = self._get_video_path_pattern() + self._chunk_size = self._get_chunk_size() + self._tasks = self._get_tasks() + self._subtasks = self._get_subtasks() + # self._episodes = self._get_episode_info() # TODO why we need this func + self.curr_traj_data = None + self.curr_traj_id = None + + self._trajectory_ids, self._trajectory_lengths = self._get_trajectories() + self._modality_keys = self._get_modality_keys() + self._delta_indices = self._get_delta_indices() + self._all_steps = self._get_all_steps() + self.set_transforms_metadata(self.metadata) + self.set_epoch(0) + + print(f"Initialized dataset {self.dataset_name} with {embodiment_tag}") + + + # Check if the dataset is valid + self._check_integrity() + + @property + def dataset_path(self) -> Path: + """The path to the dataset that contains the METADATA_FILENAME file.""" + return self._dataset_path + + @property + def metadata(self) -> DatasetMetadata: + """The metadata for the dataset, loaded from metadata.json in the dataset directory""" + return self._metadata + + @property + def trajectory_ids(self) -> np.ndarray: + """The trajectory IDs in the dataset, stored as a 1D numpy array of strings.""" + return self._trajectory_ids + + @property + def trajectory_lengths(self) -> np.ndarray: + """The trajectory lengths in the dataset, stored as a 1D numpy array of integers. + The order of the lengths is the same as the order of the trajectory IDs. + """ + return self._trajectory_lengths + + @property + def all_steps(self) -> np.ndarray: + """The trajectory IDs and base indices for all steps in the dataset. + Example: + self.trajectory_ids: [0, 1, 2] + self.trajectory_lengths: [3, 2, 4] + return: + np.array([ + [0, 0], [0, 1], [0, 2], + [1, 0], [1, 1], + [2, 0], [2, 1], [2, 2], [2, 3], + ], dtype=np.int64) + """ + return self._all_steps + + @property + def modality_keys(self) -> dict: + """The modality keys for the dataset. The keys are the modality names, and the values are the keys for each modality. + + Example: { + "video": ["video.image_side_0", "video.image_side_1"], + "state": ["state.eef_position", "state.eef_rotation"], + "action": ["action.eef_position", "action.eef_rotation"], + "language": ["language.human.task"], + "timestamp": ["timestamp"], + "reward": ["reward"], + } + """ + return self._modality_keys + + @property + def delta_indices(self) -> dict[str, np.ndarray]: + """The delta indices for the dataset. The keys are the modality.key, and the values are the delta indices for each modality.key.""" + return self._delta_indices + + @property + def dataset_name(self) -> str: + """The name of the dataset.""" + return self._dataset_name + + @property + def lerobot_modality_meta(self) -> LeRobotModalityMetadata: + """The metadata for the LeRobot dataset.""" + return self._lerobot_modality_meta + + @property + def lerobot_info_meta(self) -> dict: + """The metadata for the LeRobot dataset.""" + return self._lerobot_info_meta + + @property + def data_path_pattern(self) -> str: + """The path pattern for the LeRobot dataset.""" + return self._data_path_pattern + + @property + def video_path_pattern(self) -> str: + """The path pattern for the LeRobot dataset.""" + return self._video_path_pattern + + @property + def chunk_size(self) -> int: + """The chunk size for the LeRobot dataset.""" + return self._chunk_size + + @property + def tasks(self) -> pd.DataFrame: + """The tasks for the dataset.""" + return self._tasks + + @property + def subtasks(self) -> dict: + """The subtasks for the dataset.""" + return self._subtasks + + def _get_metadata(self, embodiment_tag: EmbodimentTag) -> DatasetMetadata: + """Get the metadata for the dataset. + + Returns: + dict: The metadata for the dataset. + """ + + # 1. Modality metadata + modality_meta_path = self.dataset_path / LE_ROBOT_MODALITY_FILENAME + assert ( + modality_meta_path.exists() + ), f"Please provide a {LE_ROBOT_MODALITY_FILENAME} file in {self.dataset_path}" + # 1.1. State and action modalities + simplified_modality_meta: dict[str, dict] = {} + with open(modality_meta_path, "r") as f: + le_modality_meta = LeRobotModalityMetadata.model_validate(json.load(f)) + for modality in ["state", "action"]: + simplified_modality_meta[modality] = {} + le_state_action_meta: dict[str, LeRobotStateActionMetadata] = getattr( + le_modality_meta, modality + ) + for subkey in le_state_action_meta: + state_action_dtype = np.dtype(le_state_action_meta[subkey].dtype) + if np.issubdtype(state_action_dtype, np.floating): + continuous = True + else: + continuous = False + simplified_modality_meta[modality][subkey] = { + "absolute": le_state_action_meta[subkey].absolute, + "rotation_type": le_state_action_meta[subkey].rotation_type, + "shape": [ + le_state_action_meta[subkey].end - le_state_action_meta[subkey].start + ], + "continuous": continuous, + } + + # 1.2. Video modalities + le_info_path = self.dataset_path / LE_ROBOT_INFO_FILENAME + assert ( + le_info_path.exists() + ), f"Please provide a {LE_ROBOT_INFO_FILENAME} file in {self.dataset_path}" + with open(le_info_path, "r") as f: + le_info = json.load(f) + simplified_modality_meta["video"] = {} + for new_key in le_modality_meta.video: + original_key = le_modality_meta.video[new_key].original_key + if original_key is None: + original_key = new_key + le_video_meta = le_info["features"][original_key] + height = le_video_meta["shape"][le_video_meta["names"].index("height")] + width = le_video_meta["shape"][le_video_meta["names"].index("width")] + # NOTE(FH): different lerobot dataset versions have different keys for the number of channels and fps + try: + channels = le_video_meta["shape"][le_video_meta["names"].index("channel")] + fps = le_video_meta["video_info"]["video.fps"] + except (ValueError, KeyError): + # channels = le_video_meta["shape"][le_video_meta["names"].index("channels")] + channels = le_video_meta["info"]["video.channels"] + fps = le_video_meta["info"]["video.fps"] + simplified_modality_meta["video"][new_key] = { + "resolution": [width, height], + "channels": channels, + "fps": fps, + } + + # 2. Dataset statistics + stats_path = self.dataset_path / LE_ROBOT_STATS_FILENAME + try: + print(f"Loading stats from {stats_path}") + with open(stats_path, "r") as f: + le_statistics = json.load(f) + for stat in le_statistics.values(): + DatasetStatisticalValues.model_validate(stat) + + except (FileNotFoundError, ValidationError) as e: + print(f"Failed to load dataset statistics: {e}",stats_path) + print(f"Calculating dataset statistics for {self.dataset_name}") + # assert False + # Get all parquet files in the dataset paths + parquet_files = list((self.dataset_path).glob(LE_ROBOT_DATA_FILENAME)) + parquet_files_filtered = [] + # parquet_files[0].name = "episode_033675.parquet" is broken file + for pf in parquet_files: + if "episode_033675.parquet" in pf.name: + continue + parquet_files_filtered.append(pf) + + stats_path.parent.mkdir(parents=True, exist_ok=True) + # Multi-rank: all ranks call; paths are split by rank, rank 0 merges and writes. + # Single-process: compute then write here. + if torch.distributed.is_initialized(): + le_statistics = calculate_dataset_statistics( + parquet_files_filtered, + stats_output_path=stats_path, + ) + else: + le_statistics = calculate_dataset_statistics(parquet_files_filtered) + tmp_path = stats_path.with_suffix(stats_path.suffix + f".tmp.{os.getpid()}") + with open(tmp_path, "w") as f: + json.dump(le_statistics, f, indent=4) + os.replace(tmp_path, stats_path) + + dataset_statistics = {} + for our_modality in ["state", "action"]: + dataset_statistics[our_modality] = {} + for subkey in simplified_modality_meta[our_modality]: + dataset_statistics[our_modality][subkey] = {} + state_action_meta = le_modality_meta.get_key_meta(f"{our_modality}.{subkey}") + assert isinstance(state_action_meta, LeRobotStateActionMetadata) + le_modality = state_action_meta.original_key + for stat_name in le_statistics[le_modality]: + indices = np.arange( + state_action_meta.start, + state_action_meta.end, + ) + stat = np.array(le_statistics[le_modality][stat_name]) + dataset_statistics[our_modality][subkey][stat_name] = stat[indices].tolist() + + # 3. Full dataset metadata + metadata = DatasetMetadata( + statistics=dataset_statistics, # type: ignore + modalities=simplified_modality_meta, # type: ignore + embodiment_tag=embodiment_tag, + ) + + return metadata + + def _get_trajectories(self) -> tuple[np.ndarray, np.ndarray]: + """Get the trajectories in the dataset.""" + # Get trajectory lengths, IDs, and whitelist from dataset metadata + # v2.0 + if self._lerobot_version == "v2.0": + file_path = self.dataset_path / LE_ROBOT_EPISODE_FILENAME + with open(file_path, "r") as f: + episode_metadata = [json.loads(line) for line in f] + trajectory_ids = [] + trajectory_lengths = [] + for episode in episode_metadata: + trajectory_ids.append(episode["episode_index"]) + trajectory_lengths.append(episode["length"]) + return np.array(trajectory_ids), np.array(trajectory_lengths) + # v3.0 + elif self._lerobot_version == "v3.0": + file_paths = list((self.dataset_path).glob(LE_ROBOT3_EPISODE_FILENAME)) + trajectory_ids = [] + trajectory_lengths = [] + # data_chunck_index = [] + # data_file_index = [] + # vido_from_index = [] + self.trajectory_ids_to_metadata = {} + for file_path in file_paths: + episodes_data = pd.read_parquet(file_path) + for index, episode in episodes_data.iterrows(): + trajectory_ids.append(episode["episode_index"]) + trajectory_lengths.append(episode["length"]) + + # TODO auto map key? just map to file_path and file_from_index + episode_meta = { + "data/chunk_index": episode["data/chunk_index"], + "data/file_index": episode["data/file_index"], + "data/file_from_index": index, + "videos/observation.images.wrist/from_timestamp": episode["videos/observation.images.wrist/from_timestamp"], + } + self.trajectory_ids_to_metadata[trajectory_ids[-1]] = episode_meta + + # 这里应该可以直接读取到 save index 信息 + return np.array(trajectory_ids), np.array(trajectory_lengths) + + def _get_all_steps(self) -> np.ndarray: + """Get the trajectory IDs and base indices for all steps in the dataset. + + Returns: + np.ndarray: Shape [N, 2], where each row is [trajectory_id, base_index]. + """ + # Create a hash key based on configuration to ensure cache validity + config_key = self._get_steps_config_key() + + # Create a unique filename based on config_key + steps_filename = f"steps_{config_key}.pkl" + steps_path = self.dataset_path / "meta" / steps_filename + + # Try to load cached steps first + try: + if steps_path.exists(): + with open(steps_path, "rb") as f: + cached_data = pickle.load(f) + if cached_data.get("config_key") != config_key: + raise KeyError("cached steps config_key mismatch") + cached_steps = cached_data["steps"] + if isinstance(cached_steps, np.ndarray): + return cached_steps.astype(np.int64, copy=False) + return np.asarray(cached_steps, dtype=np.int64) + except (EOFError, FileNotFoundError, pickle.PickleError, KeyError) as e: + print(f"Failed to load cached steps: {e}") + print("Computing steps from scratch...") + + # Compute steps using single process + all_steps = self._get_all_steps_single_process() + + # Cache the computed steps with unique filename + try: + cache_data = { + "config_key": config_key, + "steps": all_steps, + "num_trajectories": len(self.trajectory_ids), + "total_steps": len(all_steps), + "computed_timestamp": pd.Timestamp.now().isoformat(), + "delete_pause_frame": self.delete_pause_frame, + } + + # Ensure the meta directory exists + steps_path.parent.mkdir(parents=True, exist_ok=True) + + tmp_steps_path = steps_path.with_suffix(f"{steps_path.suffix}.tmp.{os.getpid()}") + with open(tmp_steps_path, "wb") as f: + pickle.dump(cache_data, f, protocol=pickle.HIGHEST_PROTOCOL) + os.replace(tmp_steps_path, steps_path) + print(f"Cached steps saved to {steps_path}") + except Exception as e: + print(f"Failed to cache steps: {e}") + + return all_steps + + def _get_steps_config_key(self) -> str: + """Generate a configuration key for steps caching.""" + future_video_delta_indices = None + if self.data_cfg is not None: + future_video_delta_indices = self.data_cfg.get("future_video_delta_indices", None) + config_dict = { + "steps_filter_version": 2, + "positive_offset_policy": "pad_or_clamp", + "delete_pause_frame": self.delete_pause_frame, + "dataset_name": self.dataset_name, + "action_delta_indices": { + key: self.delta_indices[key].tolist() + for key in self.modality_keys.get("action", []) + }, + "future_video_delta_indices": ( + list(future_video_delta_indices) + if future_video_delta_indices is not None + else None + ), + } + # Create a hash of the configuration + config_str = str(sorted(config_dict.items())) + return hashlib.md5(config_str.encode()).hexdigest()[:12] # + + def _min_valid_index_offset(self) -> int: + """Return the minimum relative offset that must be valid before sampling. + Positive offsets are intentionally not treated as hard bounds: action/state + chunks already pad at the end, and video retrieval clamps to the last frame. + Keeping those samples lets the final action chunk of each trajectory train. + """ + min_offset = 0 + for action_key in self.modality_keys.get("action", []): + action_offsets = self.delta_indices[action_key] + if len(action_offsets) > 0: + min_offset = min(min_offset, int(np.min(action_offsets))) + + future_video_delta_indices = None + if self.data_cfg is not None: + future_video_delta_indices = self.data_cfg.get("future_video_delta_indices", None) + if future_video_delta_indices is not None: + future_offsets = [int(offset) for offset in future_video_delta_indices] + if future_offsets: + min_offset = min(min_offset, min(future_offsets)) + + return min_offset + + + def _get_all_steps_single_process(self) -> np.ndarray: + """Original single-process implementation as fallback.""" + all_steps: list[tuple[int, int]] = [] + skipped_trajectories = 0 + processed_trajectories = 0 + skipped_steps = 0 + min_required_offset = self._min_valid_index_offset() + + # Check if language modality is configured + has_language_modality = 'language' in self.modality_keys and len(self.modality_keys['language']) > 0 + # TODO why trajectory_length here, why not use data length? + for trajectory_id, trajectory_length in tqdm(zip(self.trajectory_ids, self.trajectory_lengths), total=len(self.trajectory_ids), desc="Getting All Step"): + try: + if self._lerobot_version == "v2.0": + data = self.get_trajectory_data(trajectory_id) + elif self._lerobot_version == "v3.0": + data = self.get_trajectory_data_lerobot_v3(trajectory_id) + + trajectory_skipped = False + + # Check if trajectory has valid language instruction (if language modality is configured) + if has_language_modality: + self.curr_traj_data = data # Set current trajectory data for get_language to work + + language_instruction = self.get_language(trajectory_id, self.modality_keys['language'][0], 0) + if not language_instruction or language_instruction[0] == "": + print(f"Skipping trajectory {trajectory_id} due to empty language instruction") + skipped_trajectories += 1 + trajectory_skipped = True + continue + + except Exception as e: + print(f"Skipping trajectory {trajectory_id} due to read error: {e}") + skipped_trajectories += 1 + trajectory_skipped = True + continue + + if not trajectory_skipped: + processed_trajectories += 1 + + for base_index in range(trajectory_length): + if base_index + min_required_offset < 0: + skipped_steps += 1 + continue + all_steps.append((trajectory_id, base_index)) + + # Print summary statistics + print(f"Single-process summary: Processed {processed_trajectories} trajectories, skipped {skipped_trajectories} empty trajectories") + if skipped_steps: + print( + f"Skipped {skipped_steps} front boundary steps requiring " + f"min offset {min_required_offset} without padding" + ) + print(f"Total steps: {len(all_steps)} from {len(self.trajectory_ids)} trajectories") + + if not all_steps: + return np.empty((0, 2), dtype=np.int64) + return np.asarray(all_steps, dtype=np.int64) + + def _get_position_and_gripper_values(self, data: pd.DataFrame) -> tuple[list, list]: + """Get position and gripper values based on available columns in the dataset.""" + # Get action keys from modality_keys + action_keys = self.modality_keys.get('action', []) + + # Extract position data + delta_position_values = None + position_candidates = ['delta_eef_position'] + coordinate_candidates = ['x', 'y', 'z'] + + # First try combined position fields + for pos_key in position_candidates: + full_key = f"action.{pos_key}" + if full_key in action_keys: + try: + # Get the lerobot key for this modality + le_action_cfg = self.lerobot_modality_meta.action + subkey = pos_key + if subkey in le_action_cfg: + le_key = le_action_cfg[subkey].original_key or subkey + if le_key in data.columns: + data_array = np.stack(data[le_key]) + le_indices = np.arange(le_action_cfg[subkey].start, le_action_cfg[subkey].end) + filtered_data = data_array[:, le_indices] + delta_position_values = filtered_data.tolist() + break + except Exception: + continue + + # If combined fields not found, try individual x,y,z coordinates + if delta_position_values is None: + x_data, y_data, z_data = None, None, None + for coord in coordinate_candidates: + full_key = f"action.{coord}" + if full_key in action_keys: + try: + le_action_cfg = self.lerobot_modality_meta.action + if coord in le_action_cfg: + le_key = le_action_cfg[coord].original_key or coord + if le_key in data.columns: + data_array = np.stack(data[le_key]) + le_indices = np.arange(le_action_cfg[coord].start, le_action_cfg[coord].end) + coord_data = data_array[:, le_indices].flatten() + if coord == 'x': + x_data = coord_data + elif coord == 'y': + y_data = coord_data + elif coord == 'z': + z_data = coord_data + except Exception: + continue + + if x_data is not None and y_data is not None and z_data is not None: + delta_position_values = np.column_stack((x_data, y_data, z_data)).tolist() + + if delta_position_values is None: + # Fallback to the old hardcoded approach if metadata approach fails + if 'action.delta_eef_position' in data.columns: + delta_position_values = data['action.delta_eef_position'].to_numpy().tolist() + elif all(col in data.columns for col in ['action.x', 'action.y', 'action.z']): + x_vals = data['action.x'].to_numpy() + y_vals = data['action.y'].to_numpy() + z_vals = data['action.z'].to_numpy() + delta_position_values = np.column_stack((x_vals, y_vals, z_vals)).tolist() + else: + raise ValueError(f"No suitable position columns found. Available columns: {data.columns.tolist()}") + + # Extract gripper data + gripper_values = None + gripper_candidates = ['gripper_close', 'gripper'] + + for grip_key in gripper_candidates: + full_key = f"action.{grip_key}" + if full_key in action_keys: + try: + le_action_cfg = self.lerobot_modality_meta.action + if grip_key in le_action_cfg: + le_key = le_action_cfg[grip_key].original_key or grip_key + if le_key in data.columns: + data_array = np.stack(data[le_key]) + le_indices = np.arange(le_action_cfg[grip_key].start, le_action_cfg[grip_key].end) + gripper_data = data_array[:, le_indices].flatten() + gripper_values = gripper_data.tolist() + break + except Exception: + continue + + if gripper_values is None: + # Fallback to the old hardcoded approach if metadata approach fails + if 'action.gripper_close' in data.columns: + gripper_values = data['action.gripper_close'].to_numpy().tolist() + elif 'action.gripper' in data.columns: + gripper_values = data['action.gripper'].to_numpy().tolist() + else: + raise ValueError(f"No suitable gripper columns found. Available columns: {data.columns.tolist()}") + + return delta_position_values, gripper_values + + def _get_modality_keys(self) -> dict: + """Get the modality keys for the dataset. + The keys are the modality names, and the values are the keys for each modality. + See property `modality_keys` for the expected format. + """ + modality_keys = defaultdict(list) + for modality, config in self.modality_configs.items(): + modality_keys[modality] = config.modality_keys + return modality_keys + + def _get_delta_indices(self) -> dict[str, np.ndarray]: + """Restructure the delta indices to use modality.key as keys instead of just the modalities.""" + delta_indices: dict[str, np.ndarray] = {} + for config in self.modality_configs.values(): + for key in config.modality_keys: + delta_indices[key] = np.array(config.delta_indices) + return delta_indices + + def _get_lerobot_modality_meta(self) -> LeRobotModalityMetadata: + """Get the metadata for the LeRobot dataset.""" + modality_meta_path = self.dataset_path / LE_ROBOT_MODALITY_FILENAME + assert ( + modality_meta_path.exists() + ), f"Please provide a {LE_ROBOT_MODALITY_FILENAME} file in {self.dataset_path}" + with open(modality_meta_path, "r") as f: + modality_meta = LeRobotModalityMetadata.model_validate(json.load(f)) + return modality_meta + + def _get_lerobot_info_meta(self) -> dict: + """Get the metadata for the LeRobot dataset.""" + info_meta_path = self.dataset_path / LE_ROBOT_INFO_FILENAME + with open(info_meta_path, "r") as f: + info_meta = json.load(f) + return info_meta + + def _get_data_path_pattern(self) -> str: + """Get the data path pattern for the LeRobot dataset.""" + return self.lerobot_info_meta["data_path"] + + def _get_video_path_pattern(self) -> str: + """Get the video path pattern for the LeRobot dataset.""" + return self.lerobot_info_meta["video_path"] + + def _get_chunk_size(self) -> int: + """Get the chunk size for the LeRobot dataset.""" + return self.lerobot_info_meta["chunks_size"] + + def _process_task_text(self, task_text: str) -> str: + """Process task text to extract English part after @ and validate. + + Args: + task_text: Original task text, may contain Chinese and English separated by @ + + Returns: + Processed task text (English part only), or None if invalid + """ + if not isinstance(task_text, str): + return None + + # Extract English part after @ + if "@" in task_text: + parts = task_text.split("@", 1) + if len(parts) > 1: + english_part = parts[1].strip() + else: + english_part = task_text.strip() + else: + # If no @, use the whole text + english_part = task_text.strip() + + # Filter out invalid instructions + invalid_keywords = ["null", "unqualified", "qualified"] + if english_part.lower() in invalid_keywords: + return None + + # Return empty string if result is empty + if not english_part: + return None + + return english_part + + def _get_tasks(self) -> pd.DataFrame: + """Get the tasks for the dataset.""" + if self._lerobot_version == "v2.0": + tasks_path = self.dataset_path / LE_ROBOT_TASKS_FILENAME + with open(tasks_path, "r") as f: + tasks = [json.loads(line) for line in f] + df = pd.DataFrame(tasks) + # Process task text: extract English part and filter invalid ones + df["task"] = df["task"].apply(self._process_task_text) + return df.set_index("task_index") + + elif self._lerobot_version == "v3.0": + tasks_path = self.dataset_path / LE_ROBOT3_TASKS_FILENAME + df = pd.read_parquet(tasks_path) + df = df.reset_index() # 把索引变成一列,列名通常为 'index' + df = df.rename(columns={'index': 'task'}) # 把 'index' 列重命名为 'task' + df = df[['task_index', 'task']] # 调整列顺序 + return df + + def _get_subtasks(self) -> dict: + """Get the subtasks for the dataset.""" + subtasks_path = self.dataset_path / LE_ROBOT_SUBTASKS_FILENAME + # check if the file exists, if not, return None + if not subtasks_path.exists(): + # check if subtask in episodes.json + episodes_path = self.dataset_path / LE_ROBOT_EPISODE_FILENAME + with open(episodes_path, "r") as f: + episodes = [json.loads(line) for line in f] + if "subtask" in episodes[0]: + print(f"Subtask not found in {subtasks_path}, extracting from {episodes_path}") + self._extract_subtasks(episodes_path, subtasks_path) + else: + return None + with open(subtasks_path, "r") as f: + subtasks = [json.loads(line) for line in f] + df = pd.DataFrame(subtasks) + df["task"] = df["task"].apply(self._process_task_text) + return df.set_index("subtask_index") + + def _extract_subtasks(self, input_path, output_path): + """Extract all subtasks from episodes.jsonl and write them to output_path in subtask_index order.""" + all_subtasks = [] + + with open(input_path, 'r', encoding='utf-8') as f: + for idx, line in enumerate(f): + line = line.strip() + if not line: + continue + try: + episode = json.loads(line) + except json.JSONDecodeError as e: + print(f"警告:第 {idx + 1} 行解析失败,已跳过 - {e}") + continue + + subtask_list = episode.get('subtask', []) + for st in subtask_list: + subtask_index = st.get('subtask_index') + task = st.get('task', '') + all_subtasks.append({"subtask_index": subtask_index, "task": task}) + + # 按 subtask_index 排序(应对可能的乱序) + all_subtasks.sort(key=lambda x: x['subtask_index']) + + with open(output_path, 'w', encoding='utf-8') as f: + for item in all_subtasks: + f.write(json.dumps(item, ensure_ascii=False) + '\n') + + print(f"已从 {input_path} 提取 {len(all_subtasks)} 条 subtask,写入 {output_path}") + + + def _check_integrity(self): + """Use the config to check if the keys are valid and detect silent data corruption.""" + ERROR_MSG_HEADER = f"Error occurred in initializing dataset {self.dataset_name}:\n" + + for modality_config in self.modality_configs.values(): + for key in modality_config.modality_keys: + if key == "lapa_action" or key == "dream_actions": + continue # no need for any metadata for lapa actions because it comes normalized + # Check if the key is valid + try: + self.lerobot_modality_meta.get_key_meta(key) + except Exception as e: + raise ValueError( + ERROR_MSG_HEADER + f"Unable to find key {key} in modality metadata:\n{e}" + ) + + def set_transforms_metadata(self, metadata: DatasetMetadata): + """Set the metadata for the transforms. This is useful for transforms that need to know the metadata, such as the normalization values.""" + self.transforms.set_metadata(metadata) + + def set_epoch(self, epoch: int): + """Set the epoch for the dataset. + + Args: + epoch (int): The epoch to set. + """ + self.epoch = epoch + + def __len__(self) -> int: + """Get the total number of data points in the dataset. + + Returns: + int: the total number of data points in the dataset. + """ + return len(self.all_steps) + + def __str__(self) -> str: + """Get the description of the dataset.""" + return f"{self.dataset_name} ({len(self)} steps)" + + + def __getitem__(self, index: int) -> dict: + """Get the data for a single step in a trajectory. + + Args: + index (int): The index of the step to get. + + Returns: + dict: The data for the step. + """ + trajectory_id, base_index = self.all_steps[index] + trajectory_id, base_index = int(trajectory_id), int(base_index) + data = self.get_step_data(trajectory_id, base_index) + + # Process all video keys dynamically + images = [] + for video_key in self.modality_keys["video"]: + image = data[video_key][0] + + # Apply image cropping if enabled and the video key is base_view + # Note: crop_obs_camera functionality has been removed + + image = Image.fromarray(image).resize((224, 224)) + images.append(image) + + # Get language and action data + language = data[self.modality_keys["language"][0]][0] + action = [] + for action_key in self.modality_keys["action"]: + action.append(data[action_key]) + action = np.concatenate(action, axis=1) + + return dict(action=action, image=images, language=language) + + def get_step_data(self, trajectory_id: int, base_index: int) -> dict: + """Get the RAW data for a single step in a trajectory. No transforms are applied. + + Args: + trajectory_id (int): The name of the trajectory. + base_index (int): The base step index in the trajectory. + + Returns: + dict: The RAW data for the step. + + Example return: + { + "video": { + "video.image_side_0": [B, T, H, W, C], + "video.image_side_1": [B, T, H, W, C], + }, + "state": { + "state.eef_position": [B, T, state_dim], + "state.eef_rotation": [B, T, state_dim], + }, + "action": { + "action.eef_position": [B, T, action_dim], + "action.eef_rotation": [B, T, action_dim], + }, + } + """ + data = {} + # Get the data for all modalities # just for action base data + self.curr_traj_data = self.get_trajectory_data(trajectory_id) + # TODO @JinhuiYE The logic below is poorly implemented. Data reading should be directly based on curr_traj_data. + for modality in self.modality_keys: + # Get the data corresponding to each key in the modality + for key in self.modality_keys[modality]: + data[key] = self.get_data_by_modality(trajectory_id, modality, key, base_index) + return data + + def get_trajectory_data(self, trajectory_id: int) -> pd.DataFrame: + """Get the data for a trajectory.""" + if self._lerobot_version == "v2.0": + + if self.curr_traj_id == trajectory_id and self.curr_traj_data is not None: + return self.curr_traj_data + else: + chunk_index = self.get_episode_chunk(trajectory_id) + parquet_path = self.dataset_path / self.data_path_pattern.format( + episode_chunk=chunk_index, episode_index=trajectory_id + ) + assert parquet_path.exists(), f"Parquet file not found at {parquet_path}" + return pd.read_parquet(parquet_path) + elif self._lerobot_version == "v3.0": + return self.get_trajectory_data_lerobot_v3(trajectory_id) + + def get_trajectory_data_lerobot_v3(self, trajectory_id: int) -> pd.DataFrame: + """Get the data for a trajectory from lerobot v3.""" + if self.curr_traj_id == trajectory_id and self.curr_traj_data is not None: + return self.curr_traj_data + else: #TODO check detail later + chunk_index = self.get_episode_chunk(trajectory_id) + + file_index = self.get_episode_file_index(trajectory_id) + # file_from_index = self.get_episode_file_from_index(trajectory_id) + + + parquet_path = self.dataset_path / self.data_path_pattern.format( + chunk_index=chunk_index, file_index=file_index + ) + assert parquet_path.exists(), f"Parquet file not found at {parquet_path}" + file_data = pd.read_parquet(parquet_path) + + # filter by trajectory_id + episode_data = file_data.loc[file_data["episode_index"] == trajectory_id].copy() + + # fix timestamp from epis index to file index + from_timestamp = self.trajectory_ids_to_metadata[trajectory_id]["videos/observation.images.wrist/from_timestamp"] + episode_data["timestamp"] = episode_data["timestamp"] + from_timestamp + + return episode_data + + + def get_trajectory_index(self, trajectory_id: int) -> int: + """Get the index of the trajectory in the dataset by the trajectory ID. + This is useful when you need to get the trajectory length or sampling weight corresponding to the trajectory ID. + + Args: + trajectory_id (str): The ID of the trajectory. + + Returns: + int: The index of the trajectory in the dataset. + """ + trajectory_indices = np.where(self.trajectory_ids == trajectory_id)[0] + if len(trajectory_indices) != 1: + raise ValueError( + f"Error finding trajectory index for {trajectory_id}, found {trajectory_indices=}" + ) + return trajectory_indices[0] + + def get_episode_chunk(self, ep_index: int) -> int: + """Get the chunk index for an episode index.""" + return ep_index // self.chunk_size + def get_episode_file_index(self, ep_index: int) -> int: + """Get the file index for an episode index.""" + episode_meta = self.trajectory_ids_to_metadata[ep_index] + return episode_meta["data/file_index"] + + def get_episode_file_from_index(self, ep_index: int) -> int: + """Get the file from index for an episode index.""" + episode_meta = self.trajectory_ids_to_metadata[ep_index] + return episode_meta["data/file_from_index"] + + + def retrieve_data_and_pad( + self, + array: np.ndarray, + step_indices: np.ndarray, + max_length: int, + padding_strategy: str = "first_last", + ) -> np.ndarray: + """Retrieve the data from the dataset and pad it if necessary. + Args: + array (np.ndarray): The array to retrieve the data from. + step_indices (np.ndarray): The step indices to retrieve the data for. + max_length (int): The maximum length of the data. + padding_strategy (str): The padding strategy, either "first" or "last". + """ + # Get the padding indices + front_padding_indices = step_indices < 0 + end_padding_indices = step_indices >= max_length + padding_positions = np.logical_or(front_padding_indices, end_padding_indices) + # Retrieve the data with the non-padding indices + # If there exists some padding, Given T step_indices, the shape of the retrieved data will be (T', ...) where T' < T + raw_data = array[step_indices[~padding_positions]] + assert isinstance(raw_data, np.ndarray), f"{type(raw_data)=}" + # This is the shape of the output, (T, ...) + if raw_data.ndim == 1: + expected_shape = (len(step_indices),) + else: + expected_shape = (len(step_indices), *array.shape[1:]) + + # Pad the data + output = np.zeros(expected_shape) + # Assign the non-padded data + output[~padding_positions] = raw_data + # If there exists some padding, pad the data + if padding_positions.any(): + if padding_strategy == "first_last": + # Use first / last step data to pad + front_padding_data = array[0] + end_padding_data = array[-1] + output[front_padding_indices] = front_padding_data + output[end_padding_indices] = end_padding_data + elif padding_strategy == "zero": + # Use zero padding + output[padding_positions] = 0 + else: + raise ValueError(f"Invalid padding strategy: {padding_strategy}") + return output + + def get_video_path(self, trajectory_id: int, key: str) -> Path: + chunk_index = self.get_episode_chunk(trajectory_id) + original_key = self.lerobot_modality_meta.video[key].original_key + if original_key is None: + original_key = key + if self._lerobot_version == "v2.0": + video_filename = self.video_path_pattern.format( + episode_chunk=chunk_index, episode_index=trajectory_id, video_key=original_key + ) + elif self._lerobot_version == "v3.0": + episode_meta = self.trajectory_ids_to_metadata[trajectory_id] + video_filename = self.video_path_pattern.format( + video_key=original_key, + chunk_index=episode_meta["data/chunk_index"], + file_index=episode_meta["data/file_index"], + ) + return self.dataset_path / video_filename + + def get_video( + self, + trajectory_id: int, + key: str, + base_index: int, + ) -> np.ndarray: + """Get the video frames for a trajectory by a base index. + + Args: + dataset (BaseSingleDataset): The dataset to retrieve the data from. + trajectory_id (str): The ID of the trajectory. + key (str): The key of the video. + base_index (int): The base index of the trajectory. + + Returns: + np.ndarray: The video frames for the trajectory and frame indices. Shape: (T, H, W, C) + """ + # Get the step indices + step_indices = self.delta_indices[key] + base_index + # print(f"{step_indices=}") + # Get the trajectory index + trajectory_index = self.get_trajectory_index(trajectory_id) + # Ensure the indices are within the valid range + # This is equivalent to padding the video with extra frames at the beginning and end + step_indices = np.maximum(step_indices, 0) + step_indices = np.minimum(step_indices, self.trajectory_lengths[trajectory_index] - 1) + assert key.startswith("video."), f"Video key must start with 'video.', got {key}" + # Get the sub-key + key = key.replace("video.", "") + video_path = self.get_video_path(trajectory_id, key) + # Get the action/state timestamps for each frame in the video + assert self.curr_traj_data is not None, f"No data found for {trajectory_id=}" + assert "timestamp" in self.curr_traj_data.columns, f"No timestamp found in {trajectory_id=}" + timestamp: np.ndarray = self.curr_traj_data["timestamp"].to_numpy() + # Get the corresponding video timestamps from the step indices + video_timestamp = timestamp[step_indices] + + return get_frames_by_timestamps( + video_path.as_posix(), + video_timestamp, + video_backend=self.video_backend, # TODO + video_backend_kwargs=self.video_backend_kwargs, + ) + + def get_state_or_action( + self, + trajectory_id: int, + modality: str, + key: str, + base_index: int, + ) -> np.ndarray: + """Get the state or action data for a trajectory by a base index. + If the step indices are out of range, pad with the data: + if the data is stored in absolute format, pad with the first or last step data; + otherwise, pad with zero. + + Args: + dataset (BaseSingleDataset): The dataset to retrieve the data from. + trajectory_id (int): The ID of the trajectory. + modality (str): The modality of the data. + key (str): The key of the data. + base_index (int): The base index of the trajectory. + + Returns: + np.ndarray: The data for the trajectory and step indices. + """ + # Get the step indices + step_indices = self.delta_indices[key] + base_index + # Get the trajectory index + trajectory_index = self.get_trajectory_index(trajectory_id) + # Get the maximum length of the trajectory + max_length = self.trajectory_lengths[trajectory_index] + assert key.startswith(modality + "."), f"{key} must start with {modality + '.'}, got {key}" + # Get the sub-key, e.g. state.joint_angles -> joint_angles + key = key.replace(modality + ".", "") + # Get the lerobot key + le_state_or_action_cfg = getattr(self.lerobot_modality_meta, modality) + le_key = le_state_or_action_cfg[key].original_key + if le_key is None: + le_key = key + # Get the data array, shape: (T, D) + assert self.curr_traj_data is not None, f"No data found for {trajectory_id=}" + assert le_key in self.curr_traj_data.columns, f"No {le_key} found in {trajectory_id=}" + data_array: np.ndarray = np.stack(self.curr_traj_data[le_key]) # type: ignore + assert data_array.ndim == 2, f"Expected 2D array, got key {le_key} is{data_array.shape} array" + le_indices = np.arange( + le_state_or_action_cfg[key].start, + le_state_or_action_cfg[key].end, + ) + data_array = data_array[:, le_indices] + # Get the state or action configuration + state_or_action_cfg = getattr(self.metadata.modalities, modality)[key] + + # Pad the data + return self.retrieve_data_and_pad( + array=data_array, + step_indices=step_indices, + max_length=max_length, + padding_strategy="first_last" if state_or_action_cfg.absolute else "zero", + # padding_strategy="zero", # HACK for realdata + ) + + def get_language( + self, + trajectory_id: int, + key: str, + base_index: int, + ) -> list[str]: + """Get the language annotation data for a trajectory by step indices. + + Args: + dataset (BaseSingleDataset): The dataset to retrieve the data from. + trajectory_id (int): The ID of the trajectory. + key (str): The key of the annotation. + base_index (int): The base index of the trajectory. + + Returns: + list[str]: The annotation data for the trajectory and step indices. If no matching data is found, return empty strings. + """ + assert self.curr_traj_data is not None, f"No data found for {trajectory_id=}" + # Get the step indices + step_indices = self.delta_indices[key] + base_index + # Get the trajectory index + trajectory_index = self.get_trajectory_index(trajectory_id) + # Get the maximum length of the trajectory + max_length = self.trajectory_lengths[trajectory_index] + # Get the end times corresponding to the closest indices + step_indices = np.maximum(step_indices, 0) + step_indices = np.minimum(step_indices, max_length - 1) + # Get the annotations + task_indices: list[int] = [] + assert key.startswith( + "annotation." + ), f"Language key must start with 'annotation.', got {key}" + subkey = key.replace("annotation.", "") + annotation_meta = self.lerobot_modality_meta.annotation + assert annotation_meta is not None, f"Annotation metadata is None for {subkey}" + assert ( + subkey in annotation_meta + ), f"Annotation key {subkey} not found in metadata, available annotation keys: {annotation_meta.keys()}" + subkey_meta = annotation_meta[subkey] + original_key = subkey_meta.original_key + if original_key is None: + original_key = key + for i in range(len(step_indices)): # + # task_indices.append(self.curr_traj_data[original_key][step_indices[i]].item()) + value = self.curr_traj_data[original_key].iloc[step_indices[i]] # TODO check v2.0 + task_indices.append(value if isinstance(value, (int, float)) else value.item()) + + # Get language instructions and filter out None values (invalid instructions) + if original_key == "subtask_index": + language_list = self.subtasks.loc[task_indices]["task"].tolist() + else: + language_list = self.tasks.loc[task_indices]["task"].tolist() + # Filter out None values (invalid instructions that were filtered in _process_task_text) + language_list = [lang for lang in language_list if lang is not None] + + return language_list + + def get_data_by_modality( + self, + trajectory_id: int, + modality: str, + key: str, + base_index: int, + ): + """Get the data corresponding to the modality for a trajectory by a base index. + This method will call the corresponding helper method based on the modality. + See the helper methods for more details. + NOTE: For the language modality, the data is padded with empty strings if no matching data is found. + + Args: + dataset (BaseSingleDataset): The dataset to retrieve the data from. + trajectory_id (int): The ID of the trajectory. + modality (str): The modality of the data. + key (str): The key of the data. + base_index (int): The base index of the trajectory. + """ + if modality == "video": + return self.get_video(trajectory_id, key, base_index) + elif modality == "state" or modality == "action": + return self.get_state_or_action(trajectory_id, modality, key, base_index) + elif modality == "language": + return self.get_language(trajectory_id, key, base_index) + else: + raise ValueError(f"Invalid modality: {modality}") + + def _save_dataset_statistics_(self, save_path: Path | str, format: str = "json") -> None: + """ + Save dataset statistics to specified path in the required format. + Only includes statistics for keys that are actually used in the dataset. + Gripper-related keys will be placed at the end. + + Args: + save_path (Path | str): Path to save the statistics file + format (str): Save format, currently only supports "json" + """ + save_path = Path(save_path) + save_path.parent.mkdir(parents=True, exist_ok=True) + + # Build the data structure to save + statistics_data = {} + + # Get used modality keys + used_action_keys, used_state_keys = get_used_modality_keys(self.modality_keys) + + # Organize statistics by tag + tag = self.tag + tag_stats = {} + + # Process action statistics (only for used keys) + if hasattr(self.metadata.statistics, 'action') and self.metadata.statistics.action: + action_stats = self.metadata.statistics.action + + # Filter to only include used action keys and reorder: non-gripper first, gripper last + non_gripper_keys = [] + gripper_keys = [] + + for key in action_stats.keys(): + if key in used_action_keys: + if "gripper" in key.lower(): + gripper_keys.append(key) + else: + non_gripper_keys.append(key) + + # Reorder: non-gripper first, gripper last + reordered_keys = non_gripper_keys + gripper_keys + + filtered_action_stats = {} + for key in reordered_keys: + filtered_action_stats[key] = action_stats[key] + + if filtered_action_stats: + # Combine statistics from filtered action sub-keys + combined_action_stats = combine_modality_stats(filtered_action_stats) + + # Add mask field based on whether it's gripper or not + mask = generate_action_mask_for_used_keys( + self.metadata.modalities.action, filtered_action_stats.keys() + ) + combined_action_stats["mask"] = mask + + tag_stats["action"] = combined_action_stats + + # Process state statistics (only for used keys) + if hasattr(self.metadata.statistics, 'state') and self.metadata.statistics.state: + state_stats = self.metadata.statistics.state + + # Filter to only include used state keys, optionally reorder gripper to end + non_gripper_keys = [] + gripper_keys = [] + + for key in state_stats.keys(): + if key in used_state_keys: + if "gripper" in key.lower(): + gripper_keys.append(key) + else: + non_gripper_keys.append(key) + + # Reorder: non-gripper first, gripper last + reordered_keys = non_gripper_keys + gripper_keys + + filtered_state_stats = {} + for key in reordered_keys: + filtered_state_stats[key] = state_stats[key] + + if filtered_state_stats: + combined_state_stats = combine_modality_stats(filtered_state_stats) + tag_stats["state"] = combined_state_stats + + # Add dataset counts + tag_stats["num_transitions"] = len(self) + tag_stats["num_trajectories"] = len(self.trajectory_ids) + + statistics_data[tag] = tag_stats + + # Save as JSON file + if format.lower() == "json": + if not str(save_path).endswith('.json'): + save_path = save_path.with_suffix('.json') + with open(save_path, 'w', encoding='utf-8') as f: + json.dump(statistics_data, f, indent=2, ensure_ascii=False) + else: + raise ValueError(f"Unsupported format: {format}. Currently only 'json' is supported.") + + print(f"Single dataset statistics saved to: {save_path}") + print(f"Used action keys (reordered): {list(used_action_keys)}") + print(f"Used state keys (reordered): {list(used_state_keys)}") + + +class CachedLeRobotSingleDataset(LeRobotSingleDataset): + def __init__(self, img_resize: tuple[int, int] | None = None, *args, **kwargs): + """ + This class caches the video frames for each trajectory and key. + It is recommended to use this class if the video frames need to be accessed multiple times. + + Args: + resize_img (tuple[int, int], optional): The size to resize the video frames to reduce memory usage. + """ + # Convert img_resize to tuple if it is not already + if img_resize is not None and not isinstance(img_resize, tuple): + img_resize = tuple(img_resize) + assert len(img_resize) == 2, f"Expected tuple of length 2, got {img_resize}" + self.img_resize = img_resize + + # Initialize img_resize attribute first to ensure it exists + super().__init__(*args, **kwargs) + cached_frames: dict[str, np.ndarray] = {} + + for key in self.modality_keys["video"]: + all_frames = [] + original_key = key + key = key.replace("video.", "") + for trajectory_id, trajectory_length in tqdm( + zip(self.trajectory_ids, self.trajectory_lengths), + total=len(self.trajectory_ids), + desc=f"Caching {key} frames", + ): + video_path = self.get_video_path(trajectory_id, key) + frames = get_all_frames( + video_path.as_posix(), + video_backend=self.video_backend, + video_backend_kwargs=self.video_backend_kwargs, + resize_size=img_resize, + ) + assert frames.ndim == 4, f"Expected 4D array, got {frames.shape} array" + assert frames.shape[3] == 3, f"Expected 3 channels, got {frames.shape[3]} channels" + + # Apply image cropping if enabled and the video key is base_view + # Note: crop_obs_camera functionality has been removed + + # assert ( + # frames.shape[0] == trajectory_length + # ), f"Expected {trajectory_length} frames, got {frames.shape[0]} frames" + all_frames.append(frames) + cached_frames[key] = np.concatenate(all_frames, axis=0) + print(f"{key}: {cached_frames[key].shape}") + self.cached_frames = cached_frames + self.start_indices = np.cumsum(self.trajectory_lengths) - self.trajectory_lengths + + def get_video(self, trajectory_id: int, key: str, base_index: int) -> np.ndarray: + step_indices = self.delta_indices[key] + base_index + # Get the trajectory index + trajectory_index = self.get_trajectory_index(trajectory_id) + # Ensure the indices are within the valid range + # This is equivalent to padding the video with extra frames at the beginning and end + step_indices = np.maximum(step_indices, 0) + step_indices = np.minimum(step_indices, self.trajectory_lengths[trajectory_index] - 1) + assert key.startswith("video."), f"Video key must start with 'video.', got {key}" + # Get the sub-key + key = key.replace("video.", "") + # Calculate the absolute indices + absolute_indices = self.start_indices[trajectory_index] + step_indices + return self.cached_frames[key][absolute_indices] + + def get_step_data(self, trajectory_id: int, base_index: int) -> dict: + """Get the RAW data for a single step. No transforms are applied. + + Args: + trajectory_id (str): The ID of the trajectory. + base_index (int): The base index of the step. + + Returns: + dict: The data for the step. + """ + data = {} + self.curr_traj_data = self.get_trajectory_data(trajectory_id) + # Get the data for all modalities + for modality in self.modality_keys: + # Get the data corresponding to each key in the modality + for key in self.modality_keys[modality]: + data[key] = self.get_data_by_modality(trajectory_id, modality, key, base_index) + return data + + def set_transforms_metadata(self, metadata: DatasetMetadata): + """Set the metadata for the transforms. This is useful for transforms that need to know the metadata, such as the normalization values.""" + if self.img_resize is not None: + all_video_keys = [key for key in self.modality_keys["video"]] + for key in metadata.modalities.video: + if key in all_video_keys: + metadata.modalities.video[key].resolution = self.img_resize + super().set_transforms_metadata(metadata) + + +def safe_hash(input_tuple): + # keep 128 bits of the hash + tuple_string = repr(input_tuple).encode("utf-8") + sha256 = hashlib.sha256() + sha256.update(tuple_string) + + seed = int(sha256.hexdigest(), 16) + + return seed & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF + + +class MixtureSpecElement(BaseModel): + dataset_path: list[Path] | Path = Field(..., description="The path to the dataset.") + dataset_weight: float = Field(..., description="The weight of the dataset in the mixture.") + distribute_weights: bool = Field( + default=False, + description="Whether to distribute the weights of the dataset across all the paths. If True, the weights will be evenly distributed across all the paths.", + ) + + +# Helper functions for dataset statistics + +def combine_modality_stats(modality_stats: dict) -> dict: + """ + Combine statistics from all sub-keys under a modality. + + Args: + modality_stats (dict): Statistics for a modality, containing multiple sub-keys. + Each sub-key contains DatasetStatisticalValues object. + + Returns: + dict: Combined statistics + """ + combined_stats = { + "mean": [], + "std": [], + "max": [], + "min": [], + "q01": [], + "q99": [] + } + + # Combine statistics in sub-key order + for subkey in modality_stats.keys(): + subkey_stats = modality_stats[subkey] # This is a DatasetStatisticalValues object + + # Convert DatasetStatisticalValues to dict-like access + for stat_name in ["mean", "std", "max", "min", "q01", "q99"]: + stat_value = getattr(subkey_stats, stat_name) + if isinstance(stat_value, (list, tuple)): + combined_stats[stat_name].extend(stat_value) + else: + # Handle NDArray case - convert to list + if hasattr(stat_value, 'tolist'): + combined_stats[stat_name].extend(stat_value.tolist()) + else: + combined_stats[stat_name].append(float(stat_value)) + + return combined_stats + +def generate_action_mask_for_used_keys(action_modalities: dict, used_action_keys_ordered) -> list[bool]: + """ + Generate mask based on action modalities, but only for used keys. + Gripper-related are False, others are True. + + Args: + action_modalities (dict): Configuration information for action modalities. + used_action_keys_ordered: Iterable of actually used action keys in the correct order. + + Returns: + list[bool]: List of mask values + """ + mask = [] + + # Generate mask in the same order as the statistics were combined + for subkey in used_action_keys_ordered: + if subkey in action_modalities: + subkey_config = action_modalities[subkey] + + # Get dimension count from shape + if hasattr(subkey_config, 'shape') and len(subkey_config.shape) > 0: + dim_count = subkey_config.shape[0] + else: + dim_count = 1 + + # Check if it's gripper-related + is_gripper = "gripper" in subkey.lower() + + # Generate mask value for each dimension + for _ in range(dim_count): + mask.append(not is_gripper) # gripper is False, others are True + + return mask + +def get_used_modality_keys(modality_keys: dict) -> tuple[list, list]: + """Extract used action and state keys from modality configuration.""" + used_action_keys = [] + used_state_keys = [] + + # Extract action keys (remove "action." prefix) + for action_key in modality_keys.get("action", []): + if action_key.startswith("action."): + clean_key = action_key.replace("action.", "") + used_action_keys.append(clean_key) + + # Extract state keys (remove "state." prefix) + for state_key in modality_keys.get("state", []): + if state_key.startswith("state."): + clean_key = state_key.replace("state.", "") + used_state_keys.append(clean_key) + + return used_action_keys, used_state_keys + +class LeRobotMixtureDataset(Dataset): + """ + A mixture of multiple datasets. This class samples a single dataset based on the dataset weights and then calls the `__getitem__` method of the sampled dataset. + It is recommended to modify the single dataset class instead of this class. + """ + + def __init__( + self, + data_mixture: Sequence[tuple[LeRobotSingleDataset, float]], + mode: str, + balance_dataset_weights: bool = True, + balance_trajectory_weights: bool = True, + seed: int = 42, + metadata_config: dict = { + "percentile_mixing_method": "min_max", + }, + **kwargs, + ): + """ + Initialize the mixture dataset. + + Args: + data_mixture (list[tuple[LeRobotSingleDataset, float]]): Datasets and their corresponding weights. + mode (str): If "train", __getitem__ will return different samples every epoch; if "val" or "test", __getitem__ will return the same sample every epoch. + balance_dataset_weights (bool): If True, the weight of dataset will be multiplied by the total trajectory length of each dataset. + balance_trajectory_weights (bool): If True, sample trajectories within a dataset weighted by their length; otherwise, use equal weighting. + seed (int): Random seed for sampling. + """ + datasets: list[LeRobotSingleDataset] = [] + dataset_sampling_weights: list[float] = [] + for dataset, weight in data_mixture: + # Check if dataset is valid and has data + if len(dataset) == 0: + print(f"Warning: Skipping empty dataset {dataset.dataset_name}") + continue + datasets.append(dataset) + dataset_sampling_weights.append(weight) + + if len(datasets) == 0: + raise ValueError("No valid datasets found in the mixture. All datasets are empty.") + + self.datasets = datasets + self.balance_dataset_weights = balance_dataset_weights + self.balance_trajectory_weights = balance_trajectory_weights + self.seed = seed + self.mode = mode + self.data_cfg = kwargs["data_cfg"] if "data_cfg" in kwargs else None + self._retry_log_counts = defaultdict(int) + + # Set properties for sampling + + # 1. Dataset lengths + self._dataset_lengths = np.array([len(dataset) for dataset in self.datasets]) + print(f"Dataset lengths: {self._dataset_lengths}") + + # 2. Dataset sampling weights + self._dataset_sampling_weights = np.array(dataset_sampling_weights) + print(f"Dataset sampling weights: {self._dataset_sampling_weights}") + print(f"balance_dataset_weights: {self.balance_dataset_weights}") + + if self.balance_dataset_weights: + self._dataset_sampling_weights *= self._dataset_lengths + print(f"After balance_dataset_weights: {self._dataset_sampling_weights}") + + # Check for zero or negative weights before normalization + if np.any(self._dataset_sampling_weights <= 0): + print(f"Warning: Found zero or negative sampling weights: {self._dataset_sampling_weights}") + # Set minimum weight to prevent division issues + self._dataset_sampling_weights = np.maximum(self._dataset_sampling_weights, 1e-8) + + # Normalize weights + weights_sum = self._dataset_sampling_weights.sum() + if weights_sum == 0 or np.isnan(weights_sum): + print(f"Error: Invalid weights sum: {weights_sum}") + # Fallback to equal weights + self._dataset_sampling_weights = np.ones(len(self.datasets)) / len(self.datasets) + print(f"Fallback to equal weights") + else: + self._dataset_sampling_weights /= weights_sum + print(f'After normalize weights: {self._dataset_sampling_weights}') + + # 3. Trajectory sampling weights + self._trajectory_sampling_weights: list[np.ndarray] = [] + for i, dataset in enumerate(self.datasets): + trajectory_sampling_weights = np.ones(len(dataset.trajectory_lengths)) + if self.balance_trajectory_weights: + trajectory_sampling_weights *= dataset.trajectory_lengths + + # Check for zero or negative weights before normalization + if np.any(trajectory_sampling_weights <= 0): + print(f"Warning: Dataset {i} has zero or negative trajectory weights") + trajectory_sampling_weights = np.maximum(trajectory_sampling_weights, 1e-8) + + # Normalize weights + weights_sum = trajectory_sampling_weights.sum() + if weights_sum == 0 or np.isnan(weights_sum): + print(f"Error: Dataset {i} has invalid trajectory weights sum: {weights_sum}") + # Fallback to equal weights + trajectory_sampling_weights = np.ones(len(dataset.trajectory_lengths)) / len(dataset.trajectory_lengths) + else: + trajectory_sampling_weights /= weights_sum + + self._trajectory_sampling_weights.append(trajectory_sampling_weights) + + # 4. Primary dataset indices + self._primary_dataset_indices = np.array(dataset_sampling_weights) == 1.0 + if not np.any(self._primary_dataset_indices): + print(f"Warning: No dataset with weight 1.0 found. Original weights: {dataset_sampling_weights}") + # Fallback: use the dataset(s) with maximum weight as primary + max_weight = max(dataset_sampling_weights) + self._primary_dataset_indices = np.array(dataset_sampling_weights) == max_weight + print(f"Using datasets with maximum weight {max_weight} as primary: {self._primary_dataset_indices}") + + if not np.any(self._primary_dataset_indices): + # This should never happen, but just in case + print("Error: Still no primary dataset found. Using first dataset as primary.") + self._primary_dataset_indices = np.zeros(len(self.datasets), dtype=bool) + self._primary_dataset_indices[0] = True + + # Set the epoch and sample the first epoch + self.set_epoch(0) + + self.update_metadata(metadata_config) + + @property + def dataset_lengths(self) -> np.ndarray: + """The lengths of each dataset.""" + return self._dataset_lengths + + @property + def dataset_sampling_weights(self) -> np.ndarray: + """The sampling weights for each dataset.""" + return self._dataset_sampling_weights + + @property + def trajectory_sampling_weights(self) -> list[np.ndarray]: + """The sampling weights for each trajectory in each dataset.""" + return self._trajectory_sampling_weights + + @property + def primary_dataset_indices(self) -> np.ndarray: + """The indices of the primary datasets.""" + return self._primary_dataset_indices + + def __str__(self) -> str: + dataset_descriptions = [] + for dataset, weight in zip(self.datasets, self.dataset_sampling_weights): + dataset_description = { + "Dataset": str(dataset), + "Sampling weight": float(weight), + } + dataset_descriptions.append(dataset_description) + return json.dumps({"Mixture dataset": dataset_descriptions}, indent=2) + + def set_epoch(self, epoch: int): + """Set the epoch for the dataset. + + Args: + epoch (int): The epoch to set. + """ + self.epoch = epoch + # self.sampled_steps = self.sample_epoch() + + def sample_step(self, index: int) -> tuple[LeRobotSingleDataset, int, int]: + """Sample a single step from the dataset.""" + # return self.sampled_steps[index] + + # Set seed + seed = index if self.mode != "train" else safe_hash((self.epoch, index, self.seed)) + rng = np.random.default_rng(seed) + + # Sample dataset + dataset_index = rng.choice(len(self.datasets), p=self.dataset_sampling_weights) + dataset = self.datasets[dataset_index] + + # Sample trajectory + # trajectory_index = rng.choice( + # len(dataset.trajectory_ids), p=self.trajectory_sampling_weights[dataset_index] + # ) + # trajectory_id = dataset.trajectory_ids[trajectory_index] + + # # Sample step + # base_index = rng.choice(dataset.trajectory_lengths[trajectory_index]) + # return dataset, trajectory_id, base_index + single_step_index = rng.choice(len(dataset.all_steps)) + trajectory_id, base_index = dataset.all_steps[single_step_index] + trajectory_id, base_index = int(trajectory_id), int(base_index) + return dataset, trajectory_id, base_index + + def filter_zero_action(self, dataset, raw_data, step): + # raw_data keys are always "action.xxx" format; collect and concatenate directly + raw_action_list = [raw_data[action_key] for action_key in dataset.modality_keys["action"]] + if isinstance(raw_action_list[0], torch.Tensor): + raw_action = (raw_action_list[0] if len(raw_action_list) == 1 else torch.cat(raw_action_list, dim=1)) + else: + raw_action = (raw_action_list[0] if len(raw_action_list) == 1 else np.concatenate(raw_action_list, axis=1)) + # Only check non-padded frames: delta actions at trajectory boundaries are legitimately zero-padded, + # so filtering on padded frames causes valid end-of-trajectory samples to be incorrectly discarded. + # + # Use curr_traj_data length directly — get_step_data already loaded it, so this is O(1) + # rather than the O(N) np.where scan inside get_trajectory_index. + trajectory_length = len(dataset.curr_traj_data) + first_action_key = dataset.modality_keys["action"][0] + action_delta_indices = dataset.delta_indices[first_action_key] + valid_frame_mask = ((step + action_delta_indices >= 0) & (step + action_delta_indices < trajectory_length)) + if valid_frame_mask.any(): + if isinstance(raw_action, torch.Tensor): + valid_mask_t = torch.from_numpy(valid_frame_mask) + has_zero_action = bool(torch.any(torch.all(raw_action[valid_mask_t] == 0, dim=-1))) + else: + has_zero_action = bool(np.any(np.all(raw_action[valid_frame_mask] == 0, axis=-1))) + if has_zero_action: + raise ValueError(f"Found raw action with all dimensions equal to zero in non-padded action chunk " + f"for tag {dataset.tag_index}") + + def _log_retry_failure(self, exc: Exception, index: int, attempt: int, max_retries: int) -> None: + """Throttle noisy retry logs while keeping failure visibility.""" + error_key = str(exc) + self._retry_log_counts[error_key] += 1 + seen = self._retry_log_counts[error_key] + + should_log = seen <= 3 or seen % 100 == 0 or attempt == max_retries - 1 + if should_log: + print( + f"Attempt {attempt + 1}/{max_retries} failed for index {index}: {exc} " + f"(seen {seen} times)" + ) + if seen == 3: + print("Suppressing repeated retry logs for this error; will report every 100 occurrences.") + + def _build_language_instruction(self, dataset, data: dict, trajectory_length: int) -> str: + """Build hierarchical language like: Task: ... Subtask: ... Speed: ...""" + task = None + subtask = None + speed = int(round(trajectory_length / 500) * 500) + + language_texts = [] + for language_key in dataset.modality_keys["language"]: + language_values = data.get(language_key) + if language_values is None or len(language_values) == 0: + continue + + language_text = str(language_values[0]).strip() + if not language_text: + continue + + language_texts.append(language_text) + + if len(language_texts) == 1: + subtask = language_texts[0] + elif len(language_texts) >= 2: + task = language_texts[0] + subtask = language_texts[1] + + language_parts = [] + if task: + language_parts.append(("Task", task)) + if subtask: + language_parts.append(("Subtask", subtask)) + + # language_parts.append(("Speed", str(speed))) + # language_parts.append(("Mistake", "false")) + # language_parts.append(("Control Mode", "ee")) + + return " ".join( + f"{label}: {text.rstrip('.')}." + for label, text in language_parts + ) + + @staticmethod + def _concat_view_images(images, view_size=(224, 224)): + """Concatenate camera views into one panorama frame.""" + if not images: + return [] + + images = list(images) + resized = [] + for image in images: + if not isinstance(image, Image.Image): + image = Image.fromarray(image) + resized.append(image.convert("RGB").resize(view_size)) + + panorama = Image.new("RGB", (sum(image.width for image in resized), max(image.height for image in resized))) + x_offset = 0 + for image in resized: + panorama.paste(image, (x_offset, 0)) + x_offset += image.width + return panorama + + def __getitem__(self, index: int) -> dict: + """Get the data for a single trajectory and start index. + + Args: + index (int): The index of the trajectory to get. + + Returns: + dict: The data for the trajectory and start index. + """ + max_retries = 10 + last_exception = None + + for attempt in range(max_retries): + try: + while True: # @DUG + dataset, trajectory_id, step = self.sample_step(index) + key = dataset.modality_keys["video"][0].replace("video.", "") + video_path = dataset.get_video_path(trajectory_id, key) + if os.path.exists(video_path): + break + index = random.randint(0, len(self) - 1) + + raw_data = dataset.get_step_data(trajectory_id, step) + self.filter_zero_action(dataset, raw_data, step) + data = dataset.transforms(raw_data) + + # Process video: check if ConcatTransform has been applied + prim_images = [] + wrist_views = [] + + if "video" in data and not any(k.startswith("video.") for k in data.keys()): + # Videos have been concatenated by ConcatTransform + # data["video"] shape: [T, V, H, W, C] where V is number of views + video_data = data["video"] + num_views = video_data.shape[1] # Number of video views + + for view_idx, video_key in enumerate(dataset.modality_keys["video"]): + # Extract the view at view_idx + image = video_data[0, view_idx, :, :, :] # Get first frame [H, W, C] + image = Image.fromarray(image) + + if "wrist" not in video_key and "hand" not in video_key: + prim_images.append(image) + else: + wrist_views.append(image) + else: + # Videos are still individual keys (no ConcatTransform applied) + for video_key in dataset.modality_keys["video"]: + image = data[video_key][0] # Get first frame + image = Image.fromarray(image).resize((224, 224)) + + if "wrist" not in video_key and "hand" not in video_key: + prim_images.append(image) + else: + wrist_views.append(image) + + all_images = prim_images + wrist_views + if len(all_images) > 1: + all_images = [self._concat_view_images(all_images)] + + # Future visual supervision. By default this is one image after + # the action chunk; DiT4DiT-style training can request a full + # future sequence through data_cfg.future_video_delta_indices. + future_images = [] + try: + first_action_key = dataset.modality_keys["action"][0] + future_video_delta_indices = None + if self.data_cfg is not None: + future_video_delta_indices = self.data_cfg.get("future_video_delta_indices", None) + if future_video_delta_indices is None: + future_offsets = [int(np.max(dataset.delta_indices[first_action_key])) + 1] + else: + future_offsets = [int(offset) for offset in future_video_delta_indices] + future_view_mode = "all" + if self.data_cfg is not None: + future_view_mode = str( + self.data_cfg.get( + "future_video_view_mode", + "concat" + if len(dataset.modality_keys["video"]) > 1 + else ("primary" if future_video_delta_indices is not None else "all"), + ) + ).lower() + future_prim_images = [] + future_wrist_views = [] + + if future_view_mode == "concat": + for future_offset in future_offsets: + future_view_images = [] + for video_key in dataset.modality_keys["video"]: + future_video = dataset.get_video(trajectory_id, video_key, step + future_offset) + future_view_images.append(Image.fromarray(future_video[0])) + future_prim_images.append(self._concat_view_images(future_view_images)) + elif "video" in data and not any(k.startswith("video.") for k in data.keys()): + for view_idx, video_key in enumerate(dataset.modality_keys["video"]): + if future_view_mode == "primary" and ("wrist" in video_key or "hand" in video_key): + continue + if future_view_mode == "primary" and future_prim_images: + continue + for future_offset in future_offsets: + future_video = dataset.get_video(trajectory_id, video_key, step + future_offset) + future_image = Image.fromarray(future_video[0]) + if "wrist" not in video_key and "hand" not in video_key: + future_prim_images.append(future_image) + else: + future_wrist_views.append(future_image) + else: + for video_key in dataset.modality_keys["video"]: + if future_view_mode == "primary" and ("wrist" in video_key or "hand" in video_key): + continue + if future_view_mode == "primary" and future_prim_images: + continue + for future_offset in future_offsets: + future_video = dataset.get_video(trajectory_id, video_key, step + future_offset) + future_image = Image.fromarray(future_video[0]).resize((224, 224)) + if "wrist" not in video_key and "hand" not in video_key: + future_prim_images.append(future_image) + else: + future_wrist_views.append(future_image) + future_images = future_prim_images + future_wrist_views + except Exception: + if future_video_delta_indices is not None: + raise + future_images = all_images + + # Get language data. Format as: Task: ... Subtask: ... Speed: ... Mistake: ... Control Mode: ... + trajectory_index = dataset.get_trajectory_index(trajectory_id) + trajectory_length = dataset.trajectory_lengths[trajectory_index] + language = self._build_language_instruction(dataset, data, trajectory_length) + # print(dataset.modality_keys["language"], language) + + # Get action data: check if ConcatTransform has been applied + # if "action" in data and not any(k.startswith("action.") for k in data.keys()): + # Actions have been concatenated + action = data["action"].astype(np.float16) + # else: + # # Individual action keys + # action = [] + # for action_key in dataset.modality_keys["action"]: + # action.append(data[action_key]) + # action = np.concatenate(action, axis=1).astype(np.float16) + + # if "action_mask" in data and not any(k.startswith("action.") for k in data.keys()): + # Actions have been concatenated + action_mask = data["action_mask"].astype(np.float16) + # else: + # # Individual action keys + # action_mask = [] + # for action_key in dataset.modality_keys["action_mask"]: + # action_mask.append(data[action_key]) + # action_mask = np.concatenate(action_mask, axis=1).astype(np.float16) + # Get state data if needed + state = None + if self.data_cfg is not None and self.data_cfg.get("include_state", False) not in ["False", False]: + if "state" in data: + # Prefer the transformed state tensor. GR00TTransform keeps + # raw state.* keys around, but data["state"] is the padded + # unified state consumed by action heads. + state = data["state"].astype(np.float16) + else: + # Individual state keys + state = [] + for state_key in dataset.modality_keys["state"]: + state.append(data[state_key]) + state = np.concatenate(state, axis=1).astype(np.float16) + + return dict( + action=action, + image=all_images, + future_image=future_images, + lang=language, + state=state, + action_mask=action_mask, + embodiment_tag=dataset.tag_index, + ) + + return dict( + action=action, + image=all_images, + future_image=future_images, + lang=language, + action_mask=action_mask, + embodiment_tag=dataset.tag_index, + ) + + except Exception as e: + last_exception = e + if attempt < max_retries - 1: + self._log_retry_failure(e, index, attempt, max_retries) + # For retry, we can use a slightly different index to get a new sample + # This helps avoid getting stuck on the same problematic sample + index = random.randint(0, len(self) - 1) + else: + # All retries exhausted + print(f"All {max_retries} attempts failed for index {index}") + print(f"Last error: {last_exception}") + # Return a dummy sample or re-raise the exception + raise last_exception + + def __len__(self) -> int: + """Get the length of a single epoch in the mixture. + + Returns: + int: The length of a single epoch in the mixture. + """ + # Check for potential issues + if len(self.datasets) == 0: + return 0 + + # Check if any dataset lengths are 0 or NaN + if np.any(self.dataset_lengths == 0) or np.any(np.isnan(self.dataset_lengths)): + print(f"Warning: Found zero or NaN dataset lengths: {self.dataset_lengths}") + # Filter out zero/NaN length datasets + valid_indices = (self.dataset_lengths > 0) & (~np.isnan(self.dataset_lengths)) + if not np.any(valid_indices): + print("Error: All datasets have zero or NaN length") + return 0 + else: + valid_indices = np.ones(len(self.datasets), dtype=bool) + + # Check if any sampling weights are 0 or NaN + if np.any(self.dataset_sampling_weights == 0) or np.any(np.isnan(self.dataset_sampling_weights)): + print(f"Warning: Found zero or NaN sampling weights: {self.dataset_sampling_weights}") + # Use only valid weights + valid_weights = (self.dataset_sampling_weights > 0) & (~np.isnan(self.dataset_sampling_weights)) + valid_indices = valid_indices & valid_weights + if not np.any(valid_indices): + print("Error: All sampling weights are zero or NaN") + return 0 + + # Check primary dataset indices + primary_and_valid = self.primary_dataset_indices & valid_indices + if not np.any(primary_and_valid): + print(f"Warning: No valid primary datasets found. Primary indices: {self.primary_dataset_indices}, Valid indices: {valid_indices}") + # Fallback: use the largest valid dataset + if np.any(valid_indices): + max_length = self.dataset_lengths[valid_indices].max() + print(f"Fallback: Using maximum dataset length: {max_length}") + return int(max_length) + else: + return 0 + + # Calculate the ratio and get max + ratios = (self.dataset_lengths / self.dataset_sampling_weights)[primary_and_valid] + + # Check for NaN or inf in ratios + if np.any(np.isnan(ratios)) or np.any(np.isinf(ratios)): + print(f"Warning: Found NaN or inf in ratios: {ratios}") + print(f"Dataset lengths: {self.dataset_lengths[primary_and_valid]}") + print(f"Sampling weights: {self.dataset_sampling_weights[primary_and_valid]}") + # Filter out invalid ratios + valid_ratios = ratios[~np.isnan(ratios) & ~np.isinf(ratios)] + if len(valid_ratios) == 0: + print("Error: All ratios are NaN or inf") + return 0 + max_ratio = valid_ratios.max() + else: + max_ratio = ratios.max() + + result = int(max_ratio) + if result == 0: + print(f"Warning: Dataset mixture length is 0") + return result + + @staticmethod + def compute_overall_statistics( + per_task_stats: list[dict[str, dict[str, list[float] | np.ndarray]]], + dataset_sampling_weights: list[float] | np.ndarray, + percentile_mixing_method: str = "weighted_average", + ) -> dict[str, dict[str, list[float]]]: + """ + Computes overall statistics from per-task statistics using dataset sample weights. + + Args: + per_task_stats: List of per-task statistics. + Example format of one element in the per-task statistics list: + { + "state.gripper": { + "min": [...], + "max": [...], + "mean": [...], + "std": [...], + "q01": [...], + "q99": [...], + }, + ... + } + dataset_sampling_weights: List of sample weights for each task. + percentile_mixing_method: The method to mix the percentiles, either "weighted_average" or "weighted_std". + + Returns: + A dict of overall statistics per modality. + """ + # Normalize the sample weights to sum to 1 + dataset_sampling_weights = np.array(dataset_sampling_weights) + normalized_weights = dataset_sampling_weights / dataset_sampling_weights.sum() + + # Initialize overall statistics dict + overall_stats: dict[str, dict[str, list[float]]] = {} + + # Get the list of modality keys - use union of all keys from all datasets + all_modality_keys = set() + for task_stats in per_task_stats: + all_modality_keys.update(task_stats.keys()) + + # For each modality key, only include datasets that have this key + for modality in all_modality_keys: + # Find which datasets have this modality + datasets_with_modality = [] + weights_for_modality = [] + + for task_idx, task_stats in enumerate(per_task_stats): + if modality in task_stats: + datasets_with_modality.append(task_idx) + weights_for_modality.append(normalized_weights[task_idx]) + + # Skip if no dataset has this modality (shouldn't happen) + if not datasets_with_modality: + continue + + # Re-normalize weights for this modality + weights_for_modality = np.array(weights_for_modality) + weights_for_modality = weights_for_modality / weights_for_modality.sum() + + # Number of dimensions (from first dataset that has this modality) + num_dims = len(per_task_stats[datasets_with_modality[0]][modality]["mean"]) + + # Initialize accumulators for means and variances + weighted_means = np.zeros(num_dims) + weighted_squares = np.zeros(num_dims) + + # Collect min, max, q01, q99 from all tasks + min_list = [] + max_list = [] + q01_list = [] + q99_list = [] + + for i, task_idx in enumerate(datasets_with_modality): + w_i = weights_for_modality[i] + task_stats = per_task_stats[task_idx] + stats = task_stats[modality] + means = np.array(stats["mean"]) + stds = np.array(stats["std"]) + + # Update weighted sums for mean and variance + weighted_means += w_i * means + weighted_squares += w_i * (stds**2 + means**2) + + # Collect min, max, q01, q99 + min_list.append(stats["min"]) + max_list.append(stats["max"]) + q01_list.append(stats["q01"]) + q99_list.append(stats["q99"]) + + # Compute overall mean + overall_mean = weighted_means.tolist() + + # Compute overall variance and std deviation + overall_variance = weighted_squares - weighted_means**2 + overall_std = np.sqrt(overall_variance).tolist() + + # Compute overall min and max per dimension + overall_min = np.min(np.array(min_list), axis=0).tolist() + overall_max = np.max(np.array(max_list), axis=0).tolist() + + # Compute overall q01 and q99 per dimension + # Use weighted average of per-task quantiles + q01_array = np.array(q01_list) + q99_array = np.array(q99_list) + if percentile_mixing_method == "weighted_average": + weighted_q01 = np.average(q01_array, axis=0, weights=normalized_weights).tolist() + weighted_q99 = np.average(q99_array, axis=0, weights=normalized_weights).tolist() + # std_q01 = np.std(q01_array, axis=0).tolist() + # std_q99 = np.std(q99_array, axis=0).tolist() + # print(modality) + # print(f"{std_q01=}, {std_q99=}") + # print(f"{weighted_q01=}, {weighted_q99=}") + elif percentile_mixing_method == "min_max": + weighted_q01 = np.min(q01_array, axis=0).tolist() + weighted_q99 = np.max(q99_array, axis=0).tolist() + else: + raise ValueError(f"Invalid percentile mixing method: {percentile_mixing_method}") + + # Store the overall statistics for the modality + overall_stats[modality] = { + "min": overall_min, + "max": overall_max, + "mean": overall_mean, + "std": overall_std, + "q01": weighted_q01, + "q99": weighted_q99, + } + + return overall_stats + + @staticmethod + def merge_metadata( + metadatas: list[DatasetMetadata], + dataset_sampling_weights: list[float], + percentile_mixing_method: str, + ) -> DatasetMetadata: + """Merge multiple metadata into one.""" + # Convert to dicts + metadata_dicts = [metadata.model_dump(mode="json") for metadata in metadatas] + # Create a new metadata dict + merged_metadata = {} + + # Check all metadata have the same embodiment tag + assert all( + metadata.embodiment_tag == metadatas[0].embodiment_tag for metadata in metadatas + ), "All metadata must have the same embodiment tag" + merged_metadata["embodiment_tag"] = metadatas[0].embodiment_tag + + # Merge the dataset statistics + dataset_statistics = {} + dataset_statistics["state"] = LeRobotMixtureDataset.compute_overall_statistics( + per_task_stats=[m["statistics"]["state"] for m in metadata_dicts], + dataset_sampling_weights=dataset_sampling_weights, + percentile_mixing_method=percentile_mixing_method, + ) + dataset_statistics["action"] = LeRobotMixtureDataset.compute_overall_statistics( + per_task_stats=[m["statistics"]["action"] for m in metadata_dicts], + dataset_sampling_weights=dataset_sampling_weights, + percentile_mixing_method=percentile_mixing_method, + ) + merged_metadata["statistics"] = dataset_statistics + + # Merge the modality configs + modality_configs = defaultdict(set) + for metadata in metadata_dicts: + for modality, configs in metadata["modalities"].items(): + modality_configs[modality].add(json.dumps(configs)) + merged_metadata["modalities"] = {} + for modality, configs in modality_configs.items(): + # Check that all modality configs correspond to the same tag matches + assert ( + len(configs) == 1 + ), f"Multiple modality configs for modality {modality}: {list(configs)}" + merged_metadata["modalities"][modality] = json.loads(configs.pop()) + + return DatasetMetadata.model_validate(merged_metadata) + + def update_metadata(self, metadata_config: dict, cached_statistics_path: Path | str | None = None) -> None: + """ + Merge multiple metadatas into one and set the transforms with the merged metadata. + + Args: + metadata_config (dict): Configuration for the metadata. + "percentile_mixing_method": The method to mix the percentiles, either "weighted_average" or "min_max". + weighted_average: Use the weighted average of the percentiles using the weight used in sampling the datasets. + min_max: Use the min of the 1st percentile and max of the 99th percentile. + """ + # If cached path is provided, try to load and apply + if cached_statistics_path is not None: + try: + cached_stats = self.load_merged_statistics(cached_statistics_path) + self.apply_cached_statistics(cached_stats) + return + except (FileNotFoundError, KeyError, ValidationError) as e: + print(f"Failed to load cached statistics: {e}") + print("Falling back to computing statistics from scratch...") + + self.tag = EmbodimentTag.NEW_EMBODIMENT.value + self.merged_metadata: dict[str, DatasetMetadata] = {} + # Group metadata by tag + all_metadatas: dict[str, list[DatasetMetadata]] = {} + for dataset in self.datasets: + if dataset.tag not in all_metadatas: + all_metadatas[dataset.tag] = [] + all_metadatas[dataset.tag].append(dataset.metadata) + for tag, metadatas in all_metadatas.items(): + self.merged_metadata[tag] = self.merge_metadata( + metadatas=metadatas, + dataset_sampling_weights=self.dataset_sampling_weights.tolist(), + percentile_mixing_method=metadata_config["percentile_mixing_method"], + ) + for dataset in self.datasets: + dataset.set_transforms_metadata(self.merged_metadata[dataset.tag]) + + def save_dataset_statistics(self, save_path: Path | str, format: str = "json") -> None: + """ + Save merged dataset statistics to specified path in the required format. + Only includes statistics for keys that are actually used in the datasets. + Gripper-related keys will be placed at the end. + + Args: + save_path (Path | str): Path to save the statistics file + format (str): Save format, currently only supports "json" + """ + save_path = Path(save_path) + save_path.parent.mkdir(parents=True, exist_ok=True) + + # Build the data structure to save + statistics_data = {} + + # Collect actually used keys from all datasets + all_used_action_keys = [] + all_used_state_keys = [] + + for dataset in self.datasets: + used_action_keys, used_state_keys = get_used_modality_keys(dataset.modality_keys) + for used_action_key in used_action_keys: + if used_action_key not in all_used_action_keys: + all_used_action_keys.append(used_action_key) + for used_state_key in used_state_keys: + if used_state_key not in all_used_state_keys: + all_used_state_keys.append(used_state_key) + + # Organize statistics by tag + for tag, merged_metadata in self.merged_metadata.items(): + tag_stats = {} + + # Process action statistics + if hasattr(merged_metadata.statistics, 'action') and merged_metadata.statistics.action: + action_stats = merged_metadata.statistics.action + + # Filter and reorder keys - iterate in all_used_action_keys order + non_gripper_keys = [] + gripper_keys = [] + + for key in all_used_action_keys: + if key in action_stats: + non_gripper_keys.append(key) + + reordered_keys = non_gripper_keys + gripper_keys + + filtered_action_stats = {} + for key in reordered_keys: + filtered_action_stats[key] = action_stats[key] + + if filtered_action_stats: + combined_action_stats = combine_modality_stats(filtered_action_stats) + + mask = generate_action_mask_for_used_keys( + merged_metadata.modalities.action, filtered_action_stats.keys() + ) + combined_action_stats["mask"] = mask + + tag_stats["action"] = combined_action_stats + + # Process state statistics + if hasattr(merged_metadata.statistics, 'state') and merged_metadata.statistics.state: + state_stats = merged_metadata.statistics.state + + # Filter and reorder keys - iterate in all_used_state_keys order + # Filter and reorder keys - iterate in all_used_state_keys order + non_gripper_keys = [] + gripper_keys = [] + + for key in all_used_state_keys: + if key in state_stats: + non_gripper_keys.append(key) + + reordered_keys = non_gripper_keys + gripper_keys + + filtered_state_stats = {} + for key in reordered_keys: + filtered_state_stats[key] = state_stats[key] + + if filtered_state_stats: + combined_state_stats = combine_modality_stats(filtered_state_stats) + tag_stats["state"] = combined_state_stats + + # Add dataset counts + tag_stats.update(self._get_dataset_counts(tag)) + + statistics_data[tag] = tag_stats + + # Save file + if format.lower() == "json": + if not str(save_path).endswith('.json'): + save_path = save_path.with_suffix('.json') + with open(save_path, 'w', encoding='utf-8') as f: + json.dump(statistics_data, f, indent=2, ensure_ascii=False) + else: + raise ValueError(f"Unsupported format: {format}. Currently only 'json' is supported.") + + print(f"Merged dataset statistics saved to: {save_path}") + print(f"Used action keys (reordered): {list(all_used_action_keys)}") + print(f"Used state keys (reordered): {list(all_used_state_keys)}") + + + def _combine_modality_stats(self, modality_stats: dict) -> dict: + """Backward compatibility wrapper.""" + return combine_modality_stats(modality_stats) + + def _generate_action_mask_for_used_keys(self, action_modalities: dict, used_action_keys_ordered) -> list[bool]: + """Backward compatibility wrapper.""" + return generate_action_mask_for_used_keys(action_modalities, used_action_keys_ordered) + + def _get_dataset_counts(self, tag: str) -> dict: + """ + Get dataset count information for specified tag. + + Args: + tag (str): embodiment tag + + Returns: + dict: Dictionary containing num_transitions and num_trajectories + """ + num_transitions = 0 + num_trajectories = 0 + + # Count dataset information belonging to this tag + for dataset in self.datasets: + if dataset.tag == tag: + num_transitions += len(dataset) + num_trajectories += len(dataset.trajectory_ids) + + return { + "num_transitions": num_transitions, + "num_trajectories": num_trajectories + } + + @classmethod + def load_merged_statistics(cls, load_path: Path | str) -> dict: + """ + Load merged dataset statistics from file. + + Args: + load_path (Path | str): Path to the statistics file + + Returns: + dict: Dictionary containing merged statistics + """ + load_path = Path(load_path) + if not load_path.exists(): + raise FileNotFoundError(f"Statistics file not found: {load_path}") + + if load_path.suffix.lower() == '.json': + with open(load_path, 'r', encoding='utf-8') as f: + return json.load(f) + elif load_path.suffix.lower() == '.pkl': + import pickle + with open(load_path, 'rb') as f: + return pickle.load(f) + else: + raise ValueError(f"Unsupported file format: {load_path.suffix}") + + def apply_cached_statistics(self, cached_statistics: dict) -> None: + """ + Apply cached statistics to avoid recomputation. + + Args: + cached_statistics (dict): Statistics loaded from file + """ + # Validate that cached statistics match current datasets + if "metadata" in cached_statistics: + cached_dataset_names = set(cached_statistics["metadata"]["dataset_names"]) + current_dataset_names = set(dataset.dataset_name for dataset in self.datasets) + + if cached_dataset_names != current_dataset_names: + print("Warning: Cached statistics dataset names don't match current datasets.") + print(f"Cached: {cached_dataset_names}") + print(f"Current: {current_dataset_names}") + return + + # Apply cached statistics + self.merged_metadata = {} + for tag, stats_data in cached_statistics.items(): + if tag == "metadata": # Skip metadata field + continue + + # Convert back to DatasetMetadata format + metadata_dict = { + "embodiment_tag": tag, + "statistics": { + "action": {}, + "state": {} + }, + "modalities": {} + } + + # Convert action statistics back + if "action" in stats_data: + action_data = stats_data["action"] + # This is simplified - you may need to split back to sub-keys + metadata_dict["statistics"]["action"] = action_data + + # Convert state statistics back + if "state" in stats_data: + state_data = stats_data["state"] + metadata_dict["statistics"]["state"] = state_data + + self.merged_metadata[tag] = DatasetMetadata.model_validate(metadata_dict) + + # Update transforms metadata for each dataset + for dataset in self.datasets: + if dataset.tag in self.merged_metadata: + dataset.set_transforms_metadata(self.merged_metadata[dataset.tag]) + + print(f"Applied cached statistics for {len(self.merged_metadata)} embodiment tags.") diff --git a/starVLA/dataloader/gr00t_lerobot/embodiment_tags.py b/starVLA/dataloader/gr00t_lerobot/embodiment_tags.py new file mode 100644 index 0000000000000000000000000000000000000000..9df6456a03e8bba3e0a8f3cb82d778f5d4855920 --- /dev/null +++ b/starVLA/dataloader/gr00t_lerobot/embodiment_tags.py @@ -0,0 +1,111 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from enum import Enum + + +class EmbodimentTag(Enum): + GR1 = "gr1" + """ + The GR1 dataset. + """ + + ActionNet = "action_net" + """ + The ActionNet dataset. + """ + + OXE_DROID = "oxe_droid" + """ + The OxE Droid dataset. + """ + + OXE_BRIDGE = "oxe_bridge" + """ + The OxE Bridge dataset. + """ + + OXE_RT1 = "oxe_rt1" + """ + The OxE RT-1 dataset. + """ + + AGIBOT_GENIE1 = "agibot_genie1" + """ + The AgiBot Genie-1 with gripper dataset. + """ + + AGIBOT_BETA = "agibot_beta" + """ + The AgiBot Genie-1 with gripper dataset. + """ + + EGODEX = "egodex" + """ + The AgiBot Genie-1 with gripper dataset. + """ + + NVWA_F = "nvwa_f" + """ + The AgiBot Genie-1 with gripper dataset. + """ + + ROBOTWIN = "robotwin" + """ + The AgiBot Genie-1 with gripper dataset. + """ + + NEW_EMBODIMENT = "new_embodiment" + """ + Any new embodiment for finetuning. + """ + + FRANKA = 'franka' + """ + The Franka Emika Panda robot. + """ + +# Embodiment tag string: to projector index in the Action Expert Module +EMBODIMENT_TAG_MAPPING = { + EmbodimentTag.NEW_EMBODIMENT.value: 31, + EmbodimentTag.OXE_DROID.value: 17, + EmbodimentTag.OXE_BRIDGE.value: 18, + EmbodimentTag.OXE_RT1.value: 19, + EmbodimentTag.AGIBOT_GENIE1.value: 26, + EmbodimentTag.GR1.value: 24, + EmbodimentTag.FRANKA.value: 25, + EmbodimentTag.ActionNet.value: 27, + EmbodimentTag.AGIBOT_BETA.value: 28, + EmbodimentTag.EGODEX.value: 29, + EmbodimentTag.NVWA_F.value: 30, + EmbodimentTag.ROBOTWIN.value: 32 +} + +# Robot type to embodiment tag mapping +ROBOT_TYPE_TO_EMBODIMENT_TAG = { + "libero_franka": EmbodimentTag.FRANKA, + "oxe_droid": EmbodimentTag.OXE_DROID, + "oxe_bridge": EmbodimentTag.OXE_BRIDGE, + "oxe_rt1": EmbodimentTag.OXE_RT1, + "demo_sim_franka_delta_joints": EmbodimentTag.FRANKA, + "custom_robot_config": EmbodimentTag.NEW_EMBODIMENT, + "egodex": EmbodimentTag.EGODEX, + "fourier_gr1_arms_waist": EmbodimentTag.GR1, + "fourier_gr1_arms_waist2": EmbodimentTag.ActionNet, + "agibot_genie1": EmbodimentTag.AGIBOT_GENIE1, + "agibot_beta": EmbodimentTag.AGIBOT_BETA, + "nvwa_f": EmbodimentTag.NVWA_F, + "robotwin": EmbodimentTag.ROBOTWIN +} diff --git a/starVLA/dataloader/gr00t_lerobot/mixtures.py b/starVLA/dataloader/gr00t_lerobot/mixtures.py new file mode 100644 index 0000000000000000000000000000000000000000..e7bbacdb2b18ea21f662e83f27daffc75fc67c19 --- /dev/null +++ b/starVLA/dataloader/gr00t_lerobot/mixtures.py @@ -0,0 +1,301 @@ +""" +mixtures.py + +Defines a registry of dataset mixtures and weights for the Open-X Embodiment Datasets. Each dataset is associated with +a float "sampling weight" +""" + +from typing import Dict, List, Tuple + +# Dataset mixture name mapped to a list of tuples containing: +## {nakename: [(data_name, sampling_weight, robot_type)] } +DATASET_NAMED_MIXTURES = { + "suqian_test": [("lerobot_subtask_full_modified_split_test_modified", 1.0, "agibot_genie1"),], + "suqian_train": [("task_170_modified", 1.0, "agibot_genie1"),], + "robocasa_300_ee": [("robocasa_24tasks_datasets/pick_and_place_lerobot_task24_sampled_300_epose_merged", 1.0, "fourier_gr1_arms_waist"), + ], + "custom_dataset": [("custom_dataset_name", 1.0, "custom_robot_config"),], + "custom_dataset_2": [ + ("custom_dataset_name_1", 1.0, "custom_robot_config"), + ("custom_dataset_name_2", 1.0, "custom_robot_config"), + ], + "ego_dex": [("", 1.0, "ego_dex"),], + "ego_dex_suqian_agi": [ + ("users/chenzengjue/ego30w_f_2kw", 1.0, "ego_dex"), + ("datasets/suqian_agibot_lerobot_data/task_170_modified", 1.0, "agibot_genie1"), + ], + "sq_agi-beta_egodex-f": [ + ("../../workspace1/datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part1", 1.0, + "agibot_beta"), + ("../../workspace1/datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part2", 1.0, + "agibot_beta"), + ("../../workspace1/datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part3", 1.0, + "agibot_beta"), + ("../../workspace1/datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part4", 1.0, + "agibot_beta"), + ("../../workspace1/datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part5", 1.0, + "agibot_beta"), + # ("../../workspace1/datasets/G1_task_all_merged-new/datasets-G1_task_all", 1.0, "agibot_genie1"), + ("egodex30w_datasets/egodex_merge30w_fourier", 1.0, "egodex"), + # ('../../workspace1/datasets/PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose_merged', 1.0, 'fourier_gr1_arms_waist'), + # ("robotwin_dataset/dataset_lerobot/aloha-agilex_550_single_task_eepose_merged", 1.0, "robotwin"), + ], + "sq_robocasa": [ + ("datasets/G1_task_all_merged-new_0508/datasets-G1_task_all_0508", 1.0, "agibot_genie1"), + # ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part1", 1.0, "agibot_beta"), + # ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part2", 1.0, "agibot_beta"), + # ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part3", 1.0, "agibot_beta"), + # ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part4", 1.0, "agibot_beta"), + # ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part5", 1.0, "agibot_beta"), + # ("../../workspace1/datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part5", 1.0, + # "agibot_beta"), + # ("../../workspace1/datasets/G1_task_all_merged-new/datasets-G1_task_all", 1.0, "agibot_genie1"), + # ("egodex30w_datasets/egodex_merge30w_fourier", 1.0, "egodex"), + ('datasets/PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose_merged', 1.0, 'fourier_gr1_arms_waist'), + # ("robotwin_dataset/dataset_lerobot/aloha-agilex_550_single_task_eepose_merged", 1.0, "robotwin"), + ], + "sq_agi-beta_robocasa": [ + ("datasets/G1_task_all_merged-new_0508/datasets-G1_task_all_0508", 1.0, "agibot_genie1"), + ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part1", 1.0, "agibot_beta"), + ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part2", 1.0, "agibot_beta"), + ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part3", 1.0, "agibot_beta"), + ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part4", 1.0, "agibot_beta"), + ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part5", 1.0, "agibot_beta"), + # ("../../workspace1/datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part5", 1.0, + # "agibot_beta"), + # ("../../workspace1/datasets/G1_task_all_merged-new/datasets-G1_task_all", 1.0, "agibot_genie1"), + # ("egodex30w_datasets/egodex_merge30w_fourier", 1.0, "egodex"), + ('datasets/PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose_merged', 1.0, 'fourier_gr1_arms_waist'), + # ("robotwin_dataset/dataset_lerobot/aloha-agilex_550_single_task_eepose_merged", 1.0, "robotwin"), + ], + "robocasa_merge": [ + ('../../workspace1/datasets/PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose_merged', 1.0, 'fourier_gr1_arms_waist'), + ], + "sq_egodex-f_robotwin_robocasa": [ + ("egodex30w_datasets/egodex_merge30w_fourier", 1.0, "egodex"), + ("suqian_agibot_lerobot_data/task_170_modified_yzh", 1.0, "agibot_genie1"), + # ("AgiBotWorld-Beta-LeRobot", 1.0, "agibot_beta"), + ('../../workspace1/datasets/PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose_merged', 1.0, 'fourier_gr1_arms_waist'), + ("robotwin_dataset/dataset_lerobot/aloha-agilex_550_single_task_eepose_merged", 1.0, "robotwin"), + ], + "sq_agi-beta_egodex-f_robotwin_robocasa": [ + ("egodex30w_datasets/egodex_merge30w_fourier", 1.0, "egodex"), + ("suqian_agibot_lerobot_data/task_170_modified_yzh", 1.0, "agibot_genie1"), + ("AgiBotWorld-Beta-LeRobot", 1.0, "agibot_beta"), + ('../../workspace1/datasets/PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose_merged', 1.0, 'fourier_gr1_arms_waist'), + ("robotwin_dataset/dataset_lerobot/aloha-agilex_550_single_task_eepose_merged", 1.0, "robotwin"), + ], + "sq_agi-beta_egodex-f_nvwa-f_robotwin_robocasa": [ + ("datasets/G1_task_all_merged-new_0508/datasets-G1_task_all_0508", 1.0, "agibot_genie1"), + ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part1", 1.0, "agibot_beta"), + ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part2", 1.0, "agibot_beta"), + ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part3", 1.0, "agibot_beta"), + ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part4", 1.0, "agibot_beta"), + ("datasets/Agibot-Beta-Transformation/New_Full_merged-new/Agibot-Beta-Transformation-New_Full-split_part5", 1.0, "agibot_beta"), + ("../workspace/datasets/egodex30w_datasets/egodex_merge30w_fourier", 1.0, "egodex"), + ('datasets/PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose_merged', 1.0, 'fourier_gr1_arms_waist'), + ("../workspace/datasets/robotwin_dataset/dataset_lerobot/aloha-agilex_550_single_task_eepose_merged", 1.0, "robotwin"), + ("../workspace/users/liyihang/nvwa2lerobot2/retarget_fourier_20260318_890h_re/lerobot_data", 0.1, "nvwa_f"), + ("../workspace/users/liyihang/nvwa2lerobot2/retarget_fourier_1000h_re/lerobot_data", 0.1, "nvwa_f"), + # ("users/jinshibo/nvwa2lerobot/retarget_fourier_20260408_658h/lerobot_data", 0.1, "nvwa_f"), + ], + "robotwin_ee": [ + ("robotwin_dataset/dataset_lerobot/aloha-agilex_550_single_task_eepose_merged", 1.0, "robotwin"), + ], + "robotwin_robocasa": [ + ('../../workspace1/datasets/PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose_merged', 1.0, 'fourier_gr1_arms_waist'), + ("robotwin_dataset/dataset_lerobot/aloha-agilex_550_single_task_eepose_merged", 1.0, "robotwin"), + ], + "libero_all": [ + ("libero_object_no_noops_1.0.0_lerobot", 1.0, "libero_franka"), + ("libero_goal_no_noops_1.0.0_lerobot", 1.0, "libero_franka"), + ("libero_spatial_no_noops_1.0.0_lerobot", 1.0, "libero_franka"), + ("libero_10_no_noops_1.0.0_lerobot", 1.0, "libero_franka"), + # ("libero_90_no_noops_lerobot", 1.0, "libero_franka"), + ], + "bridge": [("bridge_orig_1.0.0_lerobot", 1.0, "oxe_bridge"),], + "bridge_rt_1": [ + ("bridge_orig_1.0.0_lerobot", 1.0, "oxe_bridge"), + ("fractal20220817_data_0.1.0_lerobot", 1.0, "oxe_rt1"), + ], + "demo_sim_pick_place": [("sim_pick_place", 1.0, "demo_sim_franka_delta_joints"),], + "custom_dataset": [("custom_dataset_name", 1.0, "custom_robot_config"),], + "custom_dataset_2": [ + ("custom_dataset_name_1", 1.0, "custom_robot_config"), + ("custom_dataset_name_2", 1.0, "custom_robot_config"), + ], + "fourier_gr1_unified_1000": [ + ("gr1_unified.PnPBottleToCabinetClose_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"), + ("gr1_unified.PnPCanToDrawerClose_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"), + ("gr1_unified.PnPCupToDrawerClose_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"), + ("gr1_unified.PnPMilkToMicrowaveClose_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"), + ("gr1_unified.PnPPotatoToMicrowaveClose_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"), + ("gr1_unified.PnPWineToCabinetClose_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"), + ("gr1_unified.PosttrainPnPNovelFromCuttingboardToBasketSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"), + ("gr1_unified.PosttrainPnPNovelFromCuttingboardToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, + "fourier_gr1_arms_waist"), + ("gr1_unified.PosttrainPnPNovelFromCuttingboardToPanSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"), + ("gr1_unified.PosttrainPnPNovelFromCuttingboardToPotSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"), + ("gr1_unified.PosttrainPnPNovelFromCuttingboardToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, + "fourier_gr1_arms_waist"), + ("gr1_unified.PosttrainPnPNovelFromPlacematToBasketSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"), + ("gr1_unified.PosttrainPnPNovelFromPlacematToBowlSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"), + ("gr1_unified.PosttrainPnPNovelFromPlacematToPlateSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"), + ("gr1_unified.PosttrainPnPNovelFromPlacematToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"), + ("gr1_unified.PosttrainPnPNovelFromPlateToBowlSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"), + ("gr1_unified.PosttrainPnPNovelFromPlateToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"), + ("gr1_unified.PosttrainPnPNovelFromPlateToPanSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"), + ("gr1_unified.PosttrainPnPNovelFromPlateToPlateSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"), + ("gr1_unified.PosttrainPnPNovelFromTrayToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"), + ("gr1_unified.PosttrainPnPNovelFromTrayToPlateSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"), + ("gr1_unified.PosttrainPnPNovelFromTrayToPotSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"), + ("gr1_unified.PosttrainPnPNovelFromTrayToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"), + ("gr1_unified.PosttrainPnPNovelFromTrayToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_1000", 1.0, "fourier_gr1_arms_waist"), + ], + "robocasa_teleop": [ + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PnPBottleToCabinetClose', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PnPCanToDrawerClose', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PnPCupToDrawerClose', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PnPMilkToMicrowaveClose', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PnPPotatoToMicrowaveClose', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PnPWineToCabinetClose', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromCuttingboardToBasketSplitA', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromCuttingboardToCardboardboxSplitA', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromCuttingboardToPanSplitA', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromCuttingboardToPotSplitA', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromCuttingboardToTieredbasketSplitA', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromPlacematToBasketSplitA', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromPlacematToBowlSplitA', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromPlacematToPlateSplitA', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromPlacematToTieredshelfSplitA', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromPlateToBowlSplitA', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromPlateToCardboardboxSplitA', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromPlateToPanSplitA', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromPlateToPlateSplitA', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromTrayToCardboardboxSplitA', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromTrayToPlateSplitA', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromTrayToPotSplitA', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromTrayToTieredbasketSplitA', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot/gr1_unified.PosttrainPnPNovelFromTrayToTieredshelfSplitA', 1.0, + 'fourier_gr1_arms_waist') + ], + "robocasa_teleop_ee": [ + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PnPBottleToCabinetClose_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PnPCanToDrawerClose_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PnPCupToDrawerClose_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PnPMilkToMicrowaveClose_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PnPPotatoToMicrowaveClose_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PnPWineToCabinetClose_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromCuttingboardToBasketSplitA_ee', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromCuttingboardToCardboardboxSplitA_ee', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromCuttingboardToPanSplitA_ee', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromCuttingboardToPotSplitA_ee', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromCuttingboardToTieredbasketSplitA_ee', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlacematToBasketSplitA_ee', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlacematToBowlSplitA_ee', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlacematToPlateSplitA_ee', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlacematToTieredshelfSplitA_ee', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlateToBowlSplitA_ee', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlateToCardboardboxSplitA_ee', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlateToPanSplitA_ee', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlateToPlateSplitA_ee', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromTrayToCardboardboxSplitA_ee', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromTrayToPlateSplitA_ee', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromTrayToPotSplitA_ee', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromTrayToTieredbasketSplitA_ee', 1.0, + 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromTrayToTieredshelfSplitA_ee', 1.0, + 'fourier_gr1_arms_waist') + ], + "BEHAVIOR_challenge": [("BEHAVIOR_challenge", 1.0, "R1Pro"),], + "SO101_pick": [("pick_dataset_name", 1.0, "SO101"),], + "arx_x5": [("arx_x5", 1.0, "arx_x5"),], + "robotwin": [ + ("adjust_bottle", 1.0, "robotwin"), + ("beat_block_hammer", 1.0, "robotwin"), + ("blocks_ranking_rgb", 1.0, "robotwin"), + ("blocks_ranking_size", 1.0, "robotwin"), + ("click_alarmclock", 1.0, "robotwin"), + ("click_bell", 1.0, "robotwin"), + ("dump_bin_bigbin", 1.0, "robotwin"), + ("grab_roller", 1.0, "robotwin"), + ("handover_block", 1.0, "robotwin"), + ("handover_mic", 1.0, "robotwin"), + ("hanging_mug", 1.0, "robotwin"), + ("lift_pot", 1.0, "robotwin"), + ("move_can_pot", 1.0, "robotwin"), + ("move_pillbottle_pad", 1.0, "robotwin"), + ("move_playingcard_away", 1.0, "robotwin"), + ("move_stapler_pad", 1.0, "robotwin"), + ("open_laptop", 1.0, "robotwin"), + ("open_microwave", 1.0, "robotwin"), + ("pick_diverse_bottles", 1.0, "robotwin"), + ("pick_dual_bottles", 1.0, "robotwin"), + ("place_a2b_left", 1.0, "robotwin"), + ("place_a2b_right", 1.0, "robotwin"), + ("place_bread_basket", 1.0, "robotwin"), + ("place_bread_skillet", 1.0, "robotwin"), + ("place_burger_fries", 1.0, "robotwin"), + ("place_can_basket", 1.0, "robotwin"), + ("place_cans_plasticbox", 1.0, "robotwin"), + ("place_container_plate", 1.0, "robotwin"), + ("place_dual_shoes", 1.0, "robotwin"), + ("place_empty_cup", 1.0, "robotwin"), + ("place_fan", 1.0, "robotwin"), + ("place_mouse_pad", 1.0, "robotwin"), + ("place_object_basket", 1.0, "robotwin"), + ("place_object_scale", 1.0, "robotwin"), + ("place_object_stand", 1.0, "robotwin"), + ("place_phone_stand", 1.0, "robotwin"), + ("place_shoe", 1.0, "robotwin"), + ("press_stapler", 1.0, "robotwin"), + ("put_bottles_dustbin", 1.0, "robotwin"), + ("put_object_cabinet", 1.0, "robotwin"), + ("rotate_qrcode", 1.0, "robotwin"), + ("scan_object", 1.0, "robotwin"), + ("shake_bottle", 1.0, "robotwin"), + ("shake_bottle_horizontally", 1.0, "robotwin"), + ("stack_blocks_three", 1.0, "robotwin"), + ("stack_blocks_two", 1.0, "robotwin"), + ("stack_bowls_three", 1.0, "robotwin"), + ("stack_bowls_two", 1.0, "robotwin"), + ("stamp_seal", 1.0, "robotwin"), + ("turn_switch", 1.0, "robotwin"), + ], + "robotwin_task1": [("adjust_bottle", 1.0, "robotwin"),], + "robotwin_task2": [ + ("place_a2b_left", 1.0, "robotwin"), + ("place_a2b_right", 1.0, "robotwin"), + ], + "multi_robot": [("LEROBOT_LIBERO_DATA/libero_10_no_noops_1.0.0_lerobot", 1.0, "libero_franka"), + # ("OXE_LEROBOT_DATASET/bridge_orig_1.0.0_lerobot", 1.0, "oxe_bridge"), + ], +} diff --git a/starVLA/dataloader/gr00t_lerobot/schema.py b/starVLA/dataloader/gr00t_lerobot/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..64519e56a3c59e5d08c8f8f6370f640061859b4d --- /dev/null +++ b/starVLA/dataloader/gr00t_lerobot/schema.py @@ -0,0 +1,221 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from enum import Enum +from typing import Optional + +from numpydantic import NDArray +from pydantic import BaseModel, Field, field_serializer + +from .embodiment_tags import EmbodimentTag + +# Common schema + + +class RotationType(Enum): + """Type of rotation representation""" + + AXIS_ANGLE = "axis_angle" + QUATERNION = "quaternion" + ROTATION_6D = "rotation_6d" + MATRIX = "matrix" + EULER_ANGLES_RPY = "euler_angles_rpy" + EULER_ANGLES_RYP = "euler_angles_ryp" + EULER_ANGLES_PRY = "euler_angles_pry" + EULER_ANGLES_PYR = "euler_angles_pyr" + EULER_ANGLES_YRP = "euler_angles_yrp" + EULER_ANGLES_YPR = "euler_angles_ypr" + + +# LeRobot schema + + +class LeRobotModalityField(BaseModel): + """Metadata for a LeRobot modality field.""" + + original_key: Optional[str] = Field( + default=None, + description="The original key of the modality in the LeRobot dataset", + ) + + +class LeRobotStateActionMetadata(LeRobotModalityField): + """Metadata for a LeRobot modality.""" + + start: int = Field( + ..., + description="The start index of the modality in the concatenated state/action vector", + ) + end: int = Field( + ..., + description="The end index of the modality in the concatenated state/action vector", + ) + rotation_type: Optional[RotationType] = Field( + default=None, description="The type of rotation for the modality" + ) + absolute: bool = Field(default=True, description="Whether the modality is absolute") + dtype: str = Field( + default="float64", + description="The data type of the modality. Defaults to float64.", + ) + range: Optional[tuple[float, float]] = Field( + default=None, + description="The range of the modality, if applicable. Defaults to None.", + ) + original_key: Optional[str] = Field( + default=None, + description="The original key of the modality in the LeRobot dataset.", + ) + + +class LeRobotStateMetadata(LeRobotStateActionMetadata): + """Metadata for a LeRobot state modality.""" + + original_key: Optional[str] = Field( + default="observation.state", # LeRobot convention for states + description="The original key of the state modality in the LeRobot dataset", + ) + + +class LeRobotActionMetadata(LeRobotStateActionMetadata): + """Metadata for a LeRobot action modality.""" + + original_key: Optional[str] = Field( + default="action", # LeRobot convention for actions + description="The original key of the action modality in the LeRobot dataset", + ) + + +class LeRobotModalityMetadata(BaseModel): + """Metadata for a LeRobot modality.""" + + state: dict[str, LeRobotStateMetadata] = Field( + ..., + description="The metadata for the state modality. The keys are the names of each split of the state vector.", + ) + action: dict[str, LeRobotActionMetadata] = Field( + ..., + description="The metadata for the action modality. The keys are the names of each split of the action vector.", + ) + video: dict[str, LeRobotModalityField] = Field( + ..., + description="The metadata for the video modality. The keys are the new names of each video modality.", + ) + annotation: Optional[dict[str, LeRobotModalityField]] = Field( + default=None, + description="The metadata for the annotation modality. The keys are the new names of each annotation modality.", + ) + + def get_key_meta(self, key: str) -> LeRobotModalityField: + """Get the metadata for a key in the LeRobot modality metadata. + + Args: + key (str): The key to get the metadata for. + + Returns: + LeRobotModalityField: The metadata for the key. + + Example: + lerobot_modality_meta = LeRobotModalityMetadata.model_validate(U.load_json(modality_meta_path)) + lerobot_modality_meta.get_key_meta("state.joint_shoulder_y") + lerobot_modality_meta.get_key_meta("video.main_camera") + lerobot_modality_meta.get_key_meta("annotation.human.action.task_description") + """ + split_key = key.split(".") + modality = split_key[0] + subkey = ".".join(split_key[1:]) + if modality == "state": + if subkey not in self.state: + raise ValueError( + f"Key: {key}, state key {subkey} not found in metadata, available state keys: {self.state.keys()}" + ) + return self.state[subkey] + elif modality == "action": + if subkey not in self.action: + raise ValueError( + f"Key: {key}, action key {subkey} not found in metadata, available action keys: {self.action.keys()}" + ) + return self.action[subkey] + elif modality == "video": + if subkey not in self.video: + raise ValueError( + f"Key: {key}, video key {subkey} not found in metadata, available video keys: {self.video.keys()}" + ) + return self.video[subkey] + elif modality == "annotation": + assert ( + self.annotation is not None + ), "Trying to get annotation metadata for a dataset with no annotations" + if subkey not in self.annotation: + raise ValueError( + f"Key: {key}, annotation key {subkey} not found in metadata, available annotation keys: {self.annotation.keys()}" + ) + return self.annotation[subkey] + else: + raise ValueError(f"Key: {key}, unexpected modality: {modality}") + + +# Dataset schema (parsed from LeRobot schema and simplified) + + +class DatasetStatisticalValues(BaseModel): + max: NDArray = Field(..., description="Maximum values") + min: NDArray = Field(..., description="Minimum values") + mean: NDArray = Field(..., description="Mean values") + std: NDArray = Field(..., description="Standard deviation") + q01: NDArray = Field(..., description="1st percentile values") + q99: NDArray = Field(..., description="99th percentile values") + + @field_serializer("*", when_used="json") + def serialize_ndarray(self, v: NDArray) -> list[float]: + return v.tolist() # type: ignore + + +class DatasetStatistics(BaseModel): + state: dict[str, DatasetStatisticalValues] = Field(..., description="Statistics of the state") + action: dict[str, DatasetStatisticalValues] = Field(..., description="Statistics of the action") + + +class VideoMetadata(BaseModel): + """Metadata of the video modality""" + + resolution: tuple[int, int] = Field(..., description="Resolution of the video") + channels: int = Field(..., description="Number of channels in the video", gt=0) + fps: float = Field(..., description="Frames per second", gt=0) + + +class StateActionMetadata(BaseModel): + absolute: bool = Field(..., description="Whether the state or action is absolute") + rotation_type: Optional[RotationType] = Field(None, description="Type of rotation, if any") + shape: tuple[int, ...] = Field(..., description="Shape of the state or action") + continuous: bool = Field(..., description="Whether the state or action is continuous") + + +class DatasetModalities(BaseModel): + video: dict[str, VideoMetadata] = Field(..., description="Metadata of the video") + state: dict[str, StateActionMetadata] = Field(..., description="Metadata of the state") + action: dict[str, StateActionMetadata] = Field(..., description="Metadata of the action") + + +class DatasetMetadata(BaseModel): + """Metadata of the trainable dataset + + Changes: + - Update to use the new RawCommitHashMetadataMetadata_V1_2 + """ + + statistics: DatasetStatistics = Field(..., description="Statistics of the dataset") + modalities: DatasetModalities = Field(..., description="Metadata of the modalities") + embodiment_tag: EmbodimentTag = Field(..., description="Embodiment tag of the dataset") \ No newline at end of file diff --git a/starVLA/dataloader/gr00t_lerobot/transform/__init__.py b/starVLA/dataloader/gr00t_lerobot/transform/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bf22b5e4ca3d1c7937a25234cbf08e2644593587 --- /dev/null +++ b/starVLA/dataloader/gr00t_lerobot/transform/__init__.py @@ -0,0 +1,41 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .base import ( + ComposedModalityTransform, + InvertibleModalityTransform, + ModalityTransform, +) +from .concat import ConcatTransform +# from .state_action import ( +# StateActionDropout, +# StateActionPerturbation, +# StateActionSinCosTransform, +# StateActionToTensor, +# StateActionTransform, +# ) +from .video import ( + VideoColorJitter, + VideoCrop, + VideoGrayscale, + VideoHorizontalFlip, + VideoRandomGrayscale, + VideoRandomPosterize, + VideoRandomRotation, + VideoResize, + VideoToNumpy, + VideoToTensor, + VideoTransform, +) diff --git a/starVLA/dataloader/gr00t_lerobot/transform/base.py b/starVLA/dataloader/gr00t_lerobot/transform/base.py new file mode 100644 index 0000000000000000000000000000000000000000..aac88559af98fa23f34fbb9135775d0819c281ef --- /dev/null +++ b/starVLA/dataloader/gr00t_lerobot/transform/base.py @@ -0,0 +1,134 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from abc import ABC, abstractmethod +from typing import Any + +from pydantic import BaseModel, ConfigDict, Field, PrivateAttr + +from ..schema import DatasetMetadata + + +class ModalityTransform(BaseModel, ABC): + """ + Abstract class for transforming data modalities, e.g. video frame augmentation or action normalization. + """ + + apply_to: list[str] = Field(..., description="The keys to apply the transform to.") + training: bool = Field( + default=True, description="Whether to apply the transform in training mode." + ) + _dataset_metadata: DatasetMetadata | None = PrivateAttr(default=None) + + model_config = ConfigDict(arbitrary_types_allowed=True) + + @property + def dataset_metadata(self) -> DatasetMetadata: + assert ( + self._dataset_metadata is not None + ), "Dataset metadata is not set. Please call set_metadata() before calling apply()." + return self._dataset_metadata + + @dataset_metadata.setter + def dataset_metadata(self, value: DatasetMetadata): + self._dataset_metadata = value + + def set_metadata(self, dataset_metadata: DatasetMetadata): + """ + Set the dataset metadata. This is useful for transforms that need to know the dataset metadata, e.g. to normalize actions. + Subclasses can override this method if they need to do something more complex. + """ + self.dataset_metadata = dataset_metadata + + def __call__(self, data: dict[str, Any]) -> dict[str, Any]: + """Apply the transformation to the data corresponding to target_keys and return the processed data. + + Args: + data (dict[str, Any]): The data to transform. + example: data = { + "video.image_side_0": np.ndarray, + "action.eef_position": np.ndarray, + ... + } + + Returns: + dict[str, Any]: The transformed data. + example: transformed_data = { + "video.image_side_0": np.ndarray, + "action.eef_position": torch.Tensor, # Normalized and converted to tensor + ... + } + """ + return self.apply(data) + + @abstractmethod + def apply(self, data: dict[str, Any]) -> dict[str, Any]: + """Apply the transformation to the data corresponding to keys matching the `apply_to` regular expression and return the processed data.""" + + def train(self): + self.training = True + + def eval(self): + self.training = False + + +class InvertibleModalityTransform(ModalityTransform): + @abstractmethod + def unapply(self, data: dict[str, Any]) -> dict[str, Any]: + """Reverse the transformation to the data corresponding to keys matching the `apply_to` regular expression and return the processed data.""" + + +class ComposedModalityTransform(ModalityTransform): + """Compose multiple modality transforms.""" + + transforms: list[ModalityTransform] = Field(..., description="The transforms to compose.") + apply_to: list[str] = Field( + default_factory=list, description="Will be ignored for composed transforms." + ) + training: bool = Field( + default=True, description="Whether to apply the transform in training mode." + ) + + model_config = ConfigDict(arbitrary_types_allowed=True, from_attributes=True) + + def set_metadata(self, dataset_metadata: DatasetMetadata): + for transform in self.transforms: + transform.set_metadata(dataset_metadata) + + def apply(self, data: dict[str, Any]) -> dict[str, Any]: + for i, transform in enumerate(self.transforms): + try: + data = transform(data) + except Exception as e: + raise ValueError(f"Error applying transform {i} to data: {e}") from e + return data + + def unapply(self, data: dict[str, Any]) -> dict[str, Any]: + for i, transform in enumerate(reversed(self.transforms)): + if isinstance(transform, InvertibleModalityTransform): + try: + data = transform.unapply(data) + except Exception as e: + step = len(self.transforms) - i - 1 + raise ValueError(f"Error unapplying transform {step} to data: {e}") from e + return data + + def train(self): + for transform in self.transforms: + transform.train() + + def eval(self): + for transform in self.transforms: + transform.eval() diff --git a/starVLA/dataloader/gr00t_lerobot/transform/concat.py b/starVLA/dataloader/gr00t_lerobot/transform/concat.py new file mode 100644 index 0000000000000000000000000000000000000000..cf8eea4c77fc163ecdb0d25aeca26a2cde99f8c4 --- /dev/null +++ b/starVLA/dataloader/gr00t_lerobot/transform/concat.py @@ -0,0 +1,215 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Optional + +import numpy as np +import torch +from pydantic import Field + +from ..schema import DatasetMetadata, StateActionMetadata +from .base import InvertibleModalityTransform + + +class ConcatTransform(InvertibleModalityTransform): + """ + Concatenate the keys according to specified order. + """ + + # -- We inherit from ModalityTransform, so we keep apply_to as well -- + apply_to: list[str] = Field( + default_factory=list, description="Not used in this transform, kept for compatibility." + ) + + video_concat_order: list[str] = Field( + ..., + description="Concatenation order for each video modality. " + "Format: ['video.ego_view_pad_res224_freq20', ...]", + ) + + state_concat_order: Optional[list[str]] = Field( + default=None, + description="Concatenation order for each state modality. " + "Format: ['state.position', 'state.velocity', ...].", + ) + + action_concat_order: Optional[list[str]] = Field( + default=None, + description="Concatenation order for each action modality. " + "Format: ['action.position', 'action.velocity', ...].", + ) + + action_dims: dict[str, int] = Field( + default_factory=dict, + description="The dimensions of the action keys.", + ) + state_dims: dict[str, int] = Field( + default_factory=dict, + description="The dimensions of the state keys.", + ) + + def model_dump(self, *args, **kwargs): + if kwargs.get("mode", "python") == "json": + include = { + "apply_to", + "video_concat_order", + "state_concat_order", + "action_concat_order", + } + else: + include = kwargs.pop("include", None) + + return super().model_dump(*args, include=include, **kwargs) + + def apply(self, data: dict) -> dict: + grouped_keys = {} + for key in data.keys(): + try: + modality, _ = key.split(".") + except: # noqa: E722 + ### Handle language annotation special case + if "annotation" in key: + modality = "language" + else: + modality = "others" + if modality not in grouped_keys: + grouped_keys[modality] = [] + grouped_keys[modality].append(key) + + if "video" in grouped_keys: + # Check if keys in video_concat_order, state_concat_order, action_concat_order are + # ineed contained in the data. If not, then the keys are misspecified + video_keys = grouped_keys["video"] + assert self.video_concat_order is not None, f"{self.video_concat_order=}, {video_keys=}" + assert all( + item in video_keys for item in self.video_concat_order + ), f"keys in video_concat_order are misspecified, \n{video_keys=}, \n{self.video_concat_order=}" + + # Process each video view + unsqueezed_videos = [] + for video_key in self.video_concat_order: + video_data = data.pop(video_key) + unsqueezed_video = np.expand_dims( + video_data, axis=-4 + ) # [..., H, W, C] -> [..., 1, H, W, C] + unsqueezed_videos.append(unsqueezed_video) + # Concatenate along the new axis + unsqueezed_video = np.concatenate(unsqueezed_videos, axis=-4) # [..., V, H, W, C] + + # Video + data["video"] = unsqueezed_video + + # "state" + if "state" in grouped_keys: + state_keys = grouped_keys["state"] + assert self.state_concat_order is not None, f"{self.state_concat_order=}" + assert all( + item in state_keys for item in self.state_concat_order + ), f"keys in state_concat_order are misspecified, \n{state_keys=}, \n{self.state_concat_order=}" + # Check the state dims + for key in self.state_concat_order: + target_shapes = [self.state_dims[key]] + if self.is_rotation_key(key): + target_shapes.append(6) # Allow for rotation_6d + # if key in ["state.right_arm", "state.right_hand"]: + target_shapes.append(self.state_dims[key] * 2) # Allow for sin-cos transform + assert ( + data[key].shape[-1] in target_shapes + ), f"State dim mismatch for {key=}, {data[key].shape[-1]=}, {target_shapes=}" + # Concatenate the state keys + # We'll have StateActionToTensor before this transform, so here we use torch.cat + data["state"] = torch.cat( + [data.pop(key) for key in self.state_concat_order], dim=-1 + ) # [T, D_state] + + if "action" in grouped_keys: + action_keys = grouped_keys["action"] + assert self.action_concat_order is not None, f"{self.action_concat_order=}" + # Check if all keys in concat_order are present + assert set(self.action_concat_order) == set( + action_keys + ), f"{set(self.action_concat_order)=}, {set(action_keys)=}" + # Record the action dims + for key in self.action_concat_order: + target_shapes = [self.action_dims[key]] + if self.is_rotation_key(key): + target_shapes.append(3) # Allow for axis angle + assert ( + self.action_dims[key] == data[key].shape[-1] + ), f"Action dim mismatch for {key=}, {self.action_dims[key]=}, {data[key].shape[-1]=}" + # Concatenate the action keys + # We'll have StateActionToTensor before this transform, so here we use torch.cat + data["action"] = torch.cat( + [data.pop(key) for key in self.action_concat_order], dim=-1 + ) # [T, D_action] + + return data + + def unapply(self, data: dict) -> dict: + start_dim = 0 + assert "action" in data, f"{data.keys()=}" + # For those dataset without actions (LAPA), we'll never run unapply + assert self.action_concat_order is not None, f"{self.action_concat_order=}" + action_tensor = data.pop("action") + for key in self.action_concat_order: + if key not in self.action_dims: + raise ValueError(f"Action dim {key} not found in action_dims.") + end_dim = start_dim + self.action_dims[key] + data[key] = action_tensor[..., start_dim:end_dim] + start_dim = end_dim + if "state" in data: + assert self.state_concat_order is not None, f"{self.state_concat_order=}" + start_dim = 0 + state_tensor = data.pop("state") + for key in self.state_concat_order: + end_dim = start_dim + self.state_dims[key] + data[key] = state_tensor[..., start_dim:end_dim] + start_dim = end_dim + return data + + def __call__(self, data: dict) -> dict: + return self.apply(data) + + def get_modality_metadata(self, key: str) -> StateActionMetadata: + modality, subkey = key.split(".") + assert self.dataset_metadata is not None, "Metadata not set" + modality_config = getattr(self.dataset_metadata.modalities, modality) + assert subkey in modality_config, f"{subkey=} not found in {modality_config=}" + assert isinstance( + modality_config[subkey], StateActionMetadata + ), f"Expected {StateActionMetadata} for {subkey=}, got {type(modality_config[subkey])=}" + return modality_config[subkey] + + def get_state_action_dims(self, key: str) -> int: + """Get the dimension of a state or action key from the dataset metadata.""" + modality_config = self.get_modality_metadata(key) + shape = modality_config.shape + assert len(shape) == 1, f"{shape=}" + return shape[0] + + def is_rotation_key(self, key: str) -> bool: + modality_config = self.get_modality_metadata(key) + return modality_config.rotation_type is not None + + def set_metadata(self, dataset_metadata: DatasetMetadata): + """Set the metadata and compute the dimensions of the state and action keys.""" + super().set_metadata(dataset_metadata) + # Pre-compute the dimensions of the state and action keys + if self.action_concat_order is not None: + for key in self.action_concat_order: + self.action_dims[key] = self.get_state_action_dims(key) + if self.state_concat_order is not None: + for key in self.state_concat_order: + self.state_dims[key] = self.get_state_action_dims(key) diff --git a/starVLA/dataloader/gr00t_lerobot/transform/gr00ttransform.py b/starVLA/dataloader/gr00t_lerobot/transform/gr00ttransform.py new file mode 100644 index 0000000000000000000000000000000000000000..8a155c0d87cbc8d443b30b8518b94e53cbc88766 --- /dev/null +++ b/starVLA/dataloader/gr00t_lerobot/transform/gr00ttransform.py @@ -0,0 +1,459 @@ + +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import random +import re +from typing import Any, Dict, List, Optional + +import numpy as np +import torch +import tree +from einops import rearrange +from PIL import Image +from pydantic import Field, PrivateAttr +from transformers import AutoProcessor, ProcessorMixin +from transformers.data.data_collator import DataCollatorMixin +from transformers.feature_extraction_utils import BatchFeature + +from starVLA.dataloader.gr00t_lerobot.embodiment_tags import EMBODIMENT_TAG_MAPPING, EmbodimentTag +from starVLA.dataloader.gr00t_lerobot.schema import DatasetMetadata +from starVLA.dataloader.gr00t_lerobot.transform.base import InvertibleModalityTransform + +# from starVLA.dataloader.gr00t_lerobot.backbone.eagle_backbone import DEFAULT_EAGLE_PATH +# from starVLA.dataloader.gr00t_lerobot.backbone.qwen_vl_utils import process_vision_info + +# from starVLA.dataloader.gr00t_lerobot.fusevla.models.dinov3_vit.image_processing_dinov3_vit_fast import DINOv3ViTImageProcessorFast + +# def formalize_language(language: str) -> str: +# """ +# 1. Force lowercase +# 2. Remove all punctuations +# """ +# language = language.lower() +# language = re.sub(r"[^\w\s]", "", language) +# return language + + +# def build_eagle_processor(eagle_path: str) -> ProcessorMixin: +# eagle_processor = AutoProcessor.from_pretrained( +# eagle_path, trust_remote_code=True, use_fast=True +# ) +# eagle_processor.tokenizer.padding_side = "left" +# return eagle_processor + +# def build_dino_processor(pretrained_path: str): +# processor = DINOv3ViTImageProcessorFast.from_pretrained( +# pretrained_path, trust_remote_code=True, use_fast=True +# ) +# return processor + +def collate(features: List[dict]) -> dict: + batch = {} + keys = features[0].keys() + + for key in keys: + values = [elem[key] for elem in features] + + # if key == "eagle_content": + # text_list = [] + # image_inputs = [] + # for v in values: + # curr_text_list = v["text_list"] + # curr_image_inputs = v["image_inputs"] + # text_list += curr_text_list + # image_inputs += curr_image_inputs + # eagle_inputs = eagle_processor( + # text=text_list, images=image_inputs, return_tensors="pt", padding=True + # ) + + # if dino_processor is not None: + # vit_inputs = dino_processor(images=image_inputs, return_tensors="pt") + # #import pdb; pdb.set_trace() + # batch['vit_inputs'] = vit_inputs['pixel_values'] + + # for k, v in eagle_inputs.items(): + # k = "eagle_" + k + # batch[k] = v + # if 'future_image_inputs' in values[0]: + # # enable_latent_embedding + # future_image_inputs = [] + # for v in values: + # future_image = v["future_image_inputs"] + # future_image_inputs += future_image + # future_inputs = eagle_processor( + # text=text_list, images=future_image_inputs, return_tensors="pt", padding=True + # ) + # batch['future_pixel_values'] = future_inputs['pixel_values'] + if key in ("pixel_values", "image_grid_thw", "attention_mask", "input_ids"): + # Concat in existing batch dimension. + batch[key] = torch.cat(values) + else: + # state, state_mask, action and action_mask. + # Stack to form the batch dimension. + batch[key] = torch.from_numpy(np.stack(values)) + return batch + + +class DefaultDataCollator(DataCollatorMixin): + def __init__(self): + super().__init__() + # self.eagle_processor = build_eagle_processor(eagle_path) + # if dino_path is not None: + # self.dino_processor = build_dino_processor(dino_path) + # else: + # self.dino_processor = None + + def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]: + return collate(features) + + +class GR00TTransform(InvertibleModalityTransform): + + # -- We inherit from ModalityTransform, so we keep apply_to as well -- + apply_to: list[str] = Field( + default_factory=list, description="Not used in this transform, kept for compatibility." + ) + training: bool = Field( + default=True, description="Whether to apply the transform in training mode." + ) + # formalize_language: bool = Field(default=False, description="Formalize language if True.") + embodiment_tag_mapping: dict[str, int] = Field( + description="The projector index of each embodiment tag.", + default=EMBODIMENT_TAG_MAPPING, + ) + language_dropout_prob: float = Field( + default=0.0, + description="Dropout probability for language.", + ) + + # # Private attributes to keep track of shapes/dimensions across apply/unapply + # _language_key: Optional[list[str]] = PrivateAttr(default=None) + + # eagle_processor: ProcessorMixin = Field(default=build_eagle_processor(DEFAULT_EAGLE_PATH)) + # dino_processor: Optional[Any] = Field(default=None, description="DINO processor for LWA inference") + + # XEmbDiT arguments + default_instruction: str = Field(default="Perform the default behavior.") + max_state_dim: int + max_action_dim: int + state_horizon: int + action_horizon: int + + max_length: int = 512 + embodiment_tag: EmbodimentTag | None = None + + def set_metadata(self, dataset_metadata: DatasetMetadata): + """Set the metadata for the transform.""" + super().set_metadata(dataset_metadata) + self.embodiment_tag = dataset_metadata.embodiment_tag + + def get_embodiment_tag(self) -> int: + """Get the embodiment tag from the data.""" + assert ( + self.embodiment_tag is not None + ), "Embodiment tag not set. Please call set_metadata first." + return self.embodiment_tag_mapping[self.embodiment_tag.value] + + def check_keys_and_batch_size(self, data): + grouped_keys = {} + for key in data.keys(): + if "annotation" in key: + modality = "language" + else: + try: + modality, _ = key.split(".") + except: # noqa: E722 + modality = "others" # will contain the video, state, and action + if modality not in grouped_keys: + grouped_keys[modality] = [] + grouped_keys[modality].append(key) + # Use video key to determine batch size. + video_ndim = data["video"].ndim + if video_ndim == 5: # Interpret as [T, V, H, W, C] + is_batched = False + batch_size = 1 + elif video_ndim == 6: # Interpret as [B, T, V, H, W, C] + is_batched = True + batch_size = data["video"].shape[0] + else: + raise ValueError(f"Unsupported video number of dimensions: {video_ndim}") + + # Handle language + # if "language" in grouped_keys: + # language_keys = grouped_keys["language"] + # assert len(language_keys) == 1, f"{language_keys=}" + # self._language_key = language_keys[0] + return is_batched, batch_size + + # def _apply_vlm_processing(self, batch: dict) -> BatchFeature: + # """ + # Args: + # batch: + # video: [V, T, C, H, W] + # Returns: required input with the format `BatchFeature` + # """ + # # TODO(YL, FH): check if this is correct + # images = batch["images"] # [V, T, C, H, W] + # images.shape[0] + + # np_images = rearrange(images, "v t c h w -> (t v) c h w") + # text_content = [] + + # # handle language + # lang = batch["language"] + # if isinstance(lang, list): + # lang = lang[0] + # text_content.append({"type": "text", "text": lang}) + + # eagle_images = [Image.fromarray(np.transpose(v, (1, 2, 0))) for v in np_images] + # eagle_image = [{"type": "image", "image": img} for img in eagle_images] + # eagle_conversation = [ + # { + # "role": "user", + # "content": eagle_image + text_content, + # } + # ] + + # text_list = [ + # self.eagle_processor.apply_chat_template( + # eagle_conversation, tokenize=False, add_generation_prompt=True + # ) + # ] + # image_inputs, video_inputs = self._process_vision_info(eagle_conversation) + # eagle_content = { + # "image_inputs": image_inputs, + # "video_inputs": video_inputs, + # "text_list": text_list, + # } + # inputs = {} + # inputs["eagle_content"] = eagle_content + # return inputs + + # def _process_vision_info(self, eagle_conversation): + # # TODO + # if "eagle" in DEFAULT_EAGLE_PATH.lower(): + # # Use the eagle processor to process the vision info + # return self.eagle_processor.process_vision_info(eagle_conversation) + # return process_vision_info(eagle_conversation) + + # def _prepare_video(self, data: dict): + # """Process, stack, and pad images from data['video'].""" + # ## TODO(YL, FH): check if this is correct + # images = rearrange( + # data["video"], + # "t v h w c -> v t c h w", + # ) + # return images + + # def _prepare_language(self, data: dict): + # """Tokenize data['language'] (or default_instruction if missing).""" + # if self._language_key is not None: + # raw_language = data[self._language_key] + # if isinstance(raw_language, list): + # raw_language = raw_language[0] + + # # Language dropout + # if self.training and self.language_dropout_prob > 1e-9: + # if random.random() < self.language_dropout_prob: + # raw_language = self.default_instruction + # else: + # raw_language = self.default_instruction + # return raw_language + + def _prepare_state(self, data: dict): + """ + Gathers final state from data['state'], then pads to max_state_dim. + Return (state, state_mask, n_state_tokens). + """ + if "state" not in data: + state = np.zeros((self.state_horizon, self.max_state_dim)) + state_mask = np.zeros((self.state_horizon, self.max_state_dim), dtype=bool) + n_state_tokens = self.state_horizon + return state, state_mask, n_state_tokens + + state = data["state"] + assert state.shape[0] == self.state_horizon, f"{state.shape=}, {self.state_horizon=}" + + n_state_dims = state.shape[-1] + + # Instead of asserting, just take the first max_state_dim dimensions if needed + if n_state_dims > self.max_state_dim: + state = state[:, : self.max_state_dim] + n_state_dims = self.max_state_dim + else: + # Pad up to max_state_dim if smaller + state = np.pad(state, ((0, 0), (0, self.max_state_dim - n_state_dims)), "constant") + + # Create mask for real state dims + state_mask = np.zeros_like(state).astype(bool) + state_mask[:, :n_state_dims] = True + + # We only have 1 "proprio" token to represent the entire state + n_state_tokens = state.shape[0] + return state, state_mask, n_state_tokens + + + #action horizon padding + # def _prepare_action(self, data: dict): + # """ + # Pad/truncate to action_horizon and max_action_dim, return masks. + # Supports mixed datasets with different action horizons. + # """ + # if "action" not in data: + # actions = np.zeros((self.action_horizon, self.max_action_dim)) + # actions_mask = np.zeros((self.action_horizon, self.max_action_dim), dtype=bool) + # n_action_tokens = self.action_horizon + # return actions, actions_mask, n_action_tokens + + # actions = data["action"] + # actual_horizon = actions.shape[0] # T + # print('actual_horizon',actual_horizon) + # n_action_dims = actions.shape[1] # D + + # assert ( + # n_action_dims <= self.max_action_dim + # ), f"Action dim {n_action_dims} exceeds max allowed {self.max_action_dim}." + + # # Handle action horizon mismatch: pad or truncate + # if actual_horizon < self.action_horizon: + # # Pad temporal dimension with zeros + # pad_length = self.action_horizon - actual_horizon + # actions = np.pad(actions, ((0, pad_length), (0, 0)), mode='constant', constant_values=0) + # # Create temporal mask (True for real data, False for padding) + # temporal_mask = np.concatenate([ + # np.ones(actual_horizon, dtype=bool), + # np.zeros(pad_length, dtype=bool) + # ]) + # elif actual_horizon > self.action_horizon: + # # Truncate to target horizon (take first action_horizon steps) + # actions = actions[:self.action_horizon] + # temporal_mask = np.ones(self.action_horizon, dtype=bool) + # else: + # temporal_mask = np.ones(self.action_horizon, dtype=bool) + + # # Pad the action dimension + # actions = np.pad(actions, ((0, 0), (0, self.max_action_dim - n_action_dims)), mode='constant', constant_values=0) + + # # Create mask: [action_horizon, max_action_dim] + # # True only for valid (temporal, dimension) pairs + # actions_mask = np.zeros((self.action_horizon, self.max_action_dim), dtype=bool) + # actions_mask[:, :n_action_dims] = True + # # Apply temporal mask: set padded timesteps to False + # actions_mask = actions_mask & temporal_mask[:, np.newaxis] + # # print('actions masks',actions_mask.shape) + # n_action_tokens = self.action_horizon + # return actions, actions_mask, n_action_tokens + + def _prepare_action(self, data: dict): + """ + Pad to max_action_dim, return masks. + """ + if "action" not in data: + actions = np.zeros((self.action_horizon, self.max_action_dim)) + actions_mask = np.zeros((self.action_horizon, self.max_action_dim), dtype=bool) + n_action_tokens = self.action_horizon + return actions, actions_mask, n_action_tokens + + actions = data["action"] + + assert actions.shape[0] == self.action_horizon, f"{actions.shape=}, {self.action_horizon=}" + + n_action_tokens = actions.shape[0] # T + n_action_dims = actions.shape[1] + + assert ( + n_action_dims <= self.max_action_dim + ), f"Action dim {n_action_dims} exceeds max allowed {self.max_action_dim}." + + # Pad the channel dimension + actions = np.pad(actions, ((0, 0), (0, self.max_action_dim - n_action_dims)), "constant") + + # Create mask: [T, max_action_dim] + actions_mask = np.zeros((n_action_tokens, self.max_action_dim), dtype=bool) + actions_mask[:, :n_action_dims] = True + + return actions, actions_mask, n_action_tokens + + def apply_single(self, data: dict) -> dict: + # Keep all original data and only update/add new fields + transformed_data = data.copy() + + # # 1) Prepare video and language with vlm processing. + # images = self._prepare_video(data) + # images = images.astype(np.uint8) + # language = self._prepare_language(data) + # batch_data = {"images": images, "language": language} + # vlm_outputs = self._apply_vlm_processing(batch_data) + + # Initialize vlm_outputs as empty dict since VLM processing is commented out + vlm_outputs = {} + + # 2) Prepare state and update/add to transformed_data + state, state_mask, _ = self._prepare_state(data) + transformed_data["state"] = state + transformed_data["state_mask"] = state_mask + + if self.training: + # 3) Prepare actions and add to transformed_data + transformed_data["segmentation_target"] = np.zeros((2,)) + transformed_data["segmentation_target_mask"] = np.zeros((1,)) + transformed_data["has_real_action"] = np.ones((), dtype=bool) + actions, actions_mask, _ = self._prepare_action(data) + transformed_data["action"] = actions + transformed_data["action_mask"] = actions_mask + + # Add VLM outputs to transformed data (currently empty) + for k, v in vlm_outputs.items(): + assert k not in transformed_data, f"Key {k} already exists in transformed_data." + transformed_data[k] = v + + transformed_data["embodiment_id"] = self.get_embodiment_tag() + + if self.training: + action_and_mask_keys = ["action", "action_mask"] + assert all( + transformed_data[key].shape == transformed_data["action"].shape + for key in action_and_mask_keys + ), f"Shape mismatch: {[(key, transformed_data[key].shape) for key in action_and_mask_keys]}" + + return transformed_data + + #####训练的时候不会调用这个batch方法,只有在推理的时候会调用####### + + def apply_batch(self, data: dict, batch_size: int) -> dict: + # Split on batch dimension. + data_split = [tree.map_structure(lambda x: x[i], data) for i in range(batch_size)] + # Process each element. + data_split_processed = [self.apply_single(elem) for elem in data_split] + + #import pdb; pdb.set_trace() + return collate(data_split_processed) + + + def apply(self, data: dict) -> dict: + is_batched, batch_size = self.check_keys_and_batch_size(data) + if is_batched: + return self.apply_batch(data, batch_size) + else: + return self.apply_single(data) + + def unapply(self, data: dict) -> dict: + # Leave as is so that ConcatTransform can split the values + return data + + def __call__(self, data: dict) -> dict: + return self.apply(data) diff --git a/starVLA/dataloader/gr00t_lerobot/transform/gr00ttransform_1.py b/starVLA/dataloader/gr00t_lerobot/transform/gr00ttransform_1.py new file mode 100644 index 0000000000000000000000000000000000000000..21232d529122af1d93e57b9816e33de4e793b61e --- /dev/null +++ b/starVLA/dataloader/gr00t_lerobot/transform/gr00ttransform_1.py @@ -0,0 +1,301 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and limitations under the License. +import os +import random +import re +from typing import Any, Dict, List, Optional, Tuple +import numpy as np +import torch +import tree +from einops import rearrange +from PIL import Image +from pydantic import Field, PrivateAttr +from transformers import AutoProcessor, ProcessorMixin +from transformers.data.data_collator import DataCollatorMixin +from transformers.feature_extraction_utils import BatchFeature +from starVLA.dataloader.gr00t_lerobot.embodiment_tags import EMBODIMENT_TAG_MAPPING, EmbodimentTag +from starVLA.dataloader.gr00t_lerobot.schema import DatasetMetadata +from starVLA.dataloader.gr00t_lerobot.transform.base import InvertibleModalityTransform +# ============================================================ +# Unified schema definition +# ============================================================ +UNIFIED_STATE_SCHEMA: List[Tuple[str, int]] = [ + ("left_arm", 6), + ("right_arm", 6), + ("left_gripper", 1), + ("right_gripper", 1), + ("left_hand", 6), + ("right_hand", 6), + ("waist", 3), + ("head", 2), +] +UNIFIED_ACTION_SCHEMA: List[Tuple[str, int]] = [ + ("left_arm", 6), + ("right_arm", 6), + ("left_gripper", 1), + ("right_gripper", 1), + ("left_hand", 6), + ("right_hand", 6), + ("waist", 3), + ("head", 2), +] +# alias:支持不同数据集字段名映射到统一 canonical block +DEFAULT_SUFFIX_TO_CANONICAL: Dict[str, str] = { + "left_arm": "left_arm", + "right_arm": "right_arm", + "left_gripper": "left_gripper", + "right_gripper": "right_gripper", + "left_hand": "left_hand", + "right_hand": "right_hand", + "waist": "waist", + "head": "head", + "left_pose": "left_arm", + "right_pose": "right_arm", + "original_state_head_position": "head", + "original_state_waist_position": "waist", + "original_action_head_position": "head", + "original_action_waist_position": "waist", +} +# 反向:canonical -> 所有可接受的 suffix 候选 +CANONICAL_TO_SUFFIX_CANDIDATES: Dict[str, List[str]] = {} +for suffix, canonical in DEFAULT_SUFFIX_TO_CANONICAL.items(): + CANONICAL_TO_SUFFIX_CANDIDATES.setdefault(canonical, []).append(suffix) +def collate(features: List[dict]) -> dict: + batch = {} + keys = features[0].keys() + for key in keys: + values = [elem[key] for elem in features] + if key in ("pixel_values", "image_grid_thw", "attention_mask", "input_ids"): + batch[key] = torch.cat(values) + else: + # numpy / torch 都兼容 + if isinstance(values[0], torch.Tensor): + batch[key] = torch.stack(values, dim=0) + else: + batch[key] = torch.from_numpy(np.stack(values)) + return batch +class DefaultDataCollator(DataCollatorMixin): + def __init__(self): + super().__init__() + def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]: + return collate(features) +class GR00TTransform(InvertibleModalityTransform): + apply_to: list[str] = Field(default_factory=list) + training: bool = Field(default=True) + embodiment_tag_mapping: dict[str, int] = Field(default=EMBODIMENT_TAG_MAPPING) + language_dropout_prob: float = Field(default=0.0) + default_instruction: str = Field(default="Perform the default behavior.") + max_state_dim: int + max_action_dim: int + state_horizon: int + action_horizon: int + max_length: int = 512 + embodiment_tag: EmbodimentTag | None = None + # 可选:如果某些数据集字段名不标准,可以额外传 alias 覆盖 + # 例如 {"state.ee_pos": "left_arm"} + extra_suffix_to_canonical: Dict[str, str] = Field(default_factory=dict) + def set_metadata(self, dataset_metadata: DatasetMetadata): + super().set_metadata(dataset_metadata) + self.embodiment_tag = dataset_metadata.embodiment_tag + def get_embodiment_tag(self) -> int: + assert self.embodiment_tag is not None, "Embodiment tag not set. Please call set_metadata first." + return self.embodiment_tag_mapping[self.embodiment_tag.value] + def check_keys_and_batch_size(self, data): + # BUG + video_ndim = data["video"].ndim + if video_ndim == 5: # [T, V, H, W, C] + return False, 1 + elif video_ndim == 6: # [B, T, V, H, W, C] + return True, data["video"].shape[0] + else: + raise ValueError(f"Unsupported video number of dimensions: {video_ndim}") + # ============================================================ + # helpers + # ============================================================ + def _build_schema_slices(self, schema: List[Tuple[str, int]]): + slices = {} + start = 0 + for name, dim in schema: + slices[name] = slice(start, start + dim) + start += dim + return slices, start + def _to_tensor_2d(self, x, horizon: int, name: str) -> torch.Tensor: + """ + 把输入转成 [T, D] 的 torch.Tensor。 + 支持 list / np.ndarray / torch.Tensor。 + """ + if isinstance(x, torch.Tensor): + t = x + else: + t = torch.as_tensor(x) + if t.ndim == 1: + # [T] -> [T, 1] + if t.shape[0] != horizon: + raise ValueError( + f"{name} has shape {tuple(t.shape)}, expected first dim == horizon={horizon}" + ) + t = t.unsqueeze(-1) + elif t.ndim == 2: + if t.shape[0] != horizon: + raise ValueError( + f"{name} has shape {tuple(t.shape)}, expected first dim == horizon={horizon}" + ) + else: + raise ValueError( + f"{name} must be 1D or 2D ([T] or [T, D]), but got shape {tuple(t.shape)}" + ) + return t.float() + def _merged_suffix_to_canonical(self) -> Dict[str, str]: + merged = dict(DEFAULT_SUFFIX_TO_CANONICAL) + merged.update(self.extra_suffix_to_canonical) + return merged + def _merged_canonical_to_candidates(self) -> Dict[str, List[str]]: + suffix_to_canonical = self._merged_suffix_to_canonical() + canonical_to_candidates: Dict[str, List[str]] = {} + for suffix, canonical in suffix_to_canonical.items(): + canonical_to_candidates.setdefault(canonical, []).append(suffix) + return canonical_to_candidates + def _get_block_from_data( + self, + data: dict, + prefix: str, # "state" or "action" + canonical_name: str, # e.g. "left_arm" + horizon: int, + ) -> Optional[torch.Tensor]: + """ + 从 data 里找一个 block。 + 支持: + 1) data["state.left_arm"] + 2) data["state"]["left_arm"] + 3) alias, 例如 left_pose -> left_arm + """ + canonical_to_candidates = self._merged_canonical_to_candidates() + candidate_suffixes = canonical_to_candidates.get(canonical_name, [canonical_name]) + # 先查扁平 key:data["state.left_arm"] + for suffix in candidate_suffixes: + flat_key = f"{prefix}.{suffix}" + if flat_key in data: + return self._to_tensor_2d(data[flat_key], horizon=horizon, name=flat_key) + # 再查嵌套 key:data["state"]["left_arm"] + if prefix in data and isinstance(data[prefix], dict): + subdict = data[prefix] + for suffix in candidate_suffixes: + if suffix in subdict: + return self._to_tensor_2d(subdict[suffix], horizon=horizon, name=f"{prefix}.{suffix}") + return None + def _assemble_from_blocks( + self, + data: dict, + prefix: str, # "state" or "action" + schema: List[Tuple[str, int]], + horizon: int, + max_dim: int, + ): + schema_slices, schema_total_dim = self._build_schema_slices(schema) + if max_dim < schema_total_dim: + raise ValueError( + f"{prefix}: max_dim={max_dim} is smaller than schema_total_dim={schema_total_dim}" + ) + out = torch.zeros((horizon, max_dim), dtype=torch.float32) + mask = torch.zeros((horizon, max_dim), dtype=torch.bool) + for canonical_name, dst_dim in schema: + dst_slice = schema_slices[canonical_name] + block = self._get_block_from_data( + data=data, + prefix=prefix, + canonical_name=canonical_name, + horizon=horizon, + ) + if block is None: + continue + src_dim = block.shape[1] + copy_dim = min(src_dim, dst_dim) + out[:, dst_slice.start: dst_slice.start + copy_dim] = block[:, :copy_dim] + mask[:, dst_slice.start: dst_slice.start + copy_dim] = True + if canonical_name == "waist" and src_dim == 2 and dst_dim == 3: + continue + # 如果原始维度和 schema 不一致,给出提示 + if src_dim != dst_dim: + print( + f"[GR00TTransform][{prefix}] block '{canonical_name}' dim mismatch: " + f"input={src_dim}, schema={dst_dim}, copy_dim={copy_dim}" + ) + return out, mask + # ============================================================ + # prepare state / action + # ============================================================ + def _prepare_state(self, data: dict): + """ + 不再依赖 data["state"] 是预先 concat 好的矩阵。 + 直接从: + data["state.left_arm"], data["state.right_arm"], ... + 或: + data["state"]["left_arm"], ... + 中组装。 + """ + state, state_mask = self._assemble_from_blocks( + data=data, + prefix="state", + schema=UNIFIED_STATE_SCHEMA, + horizon=self.state_horizon, + max_dim=self.max_state_dim, + ) + return state, state_mask, self.state_horizon + def _prepare_action(self, data: dict): + """ + 不再依赖 data["action"] 是预先 concat 好的矩阵。 + """ + action, action_mask = self._assemble_from_blocks( + data=data, + prefix="action", + schema=UNIFIED_ACTION_SCHEMA, + horizon=self.action_horizon, + max_dim=self.max_action_dim, + ) + return action, action_mask, self.action_horizon + # ============================================================ + # main apply + # ============================================================ + def apply_single(self, data: dict) -> dict: + transformed_data = data.copy() + vlm_outputs = {} + state, state_mask, _ = self._prepare_state(data) + transformed_data["state"] = state.numpy() + transformed_data["state_mask"] = state_mask.numpy() + if self.training: + transformed_data["segmentation_target"] = np.zeros((2,), dtype=np.float32) + transformed_data["segmentation_target_mask"] = np.zeros((1,), dtype=bool) + transformed_data["has_real_action"] = np.ones((), dtype=bool) + action, action_mask, _ = self._prepare_action(data) + transformed_data["action"] = action.numpy() + transformed_data["action_mask"] = action_mask.numpy() + for k, v in vlm_outputs.items(): + assert k not in transformed_data, f"Key {k} already exists in transformed_data." + transformed_data[k] = v + transformed_data["embodiment_id"] = self.get_embodiment_tag() + if self.training: + assert transformed_data["action"].shape == transformed_data["action_mask"].shape, ( + transformed_data["action"].shape, + transformed_data["action_mask"].shape, + ) + return transformed_data + def apply_batch(self, data: dict, batch_size: int) -> dict: + data_split = [tree.map_structure(lambda x: x[i], data) for i in range(batch_size)] + data_split_processed = [self.apply_single(elem) for elem in data_split] + return collate(data_split_processed) + def apply(self, data: dict) -> dict: + return self.apply_single(data) + def unapply(self, data: dict) -> dict: + return data + def __call__(self, data: dict) -> dict: + return self.apply(data) diff --git a/starVLA/dataloader/gr00t_lerobot/transform/state_action.py b/starVLA/dataloader/gr00t_lerobot/transform/state_action.py new file mode 100644 index 0000000000000000000000000000000000000000..a356811b8da4048161db77bd8fbc4e77c4792e46 --- /dev/null +++ b/starVLA/dataloader/gr00t_lerobot/transform/state_action.py @@ -0,0 +1,606 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import functools +import random +from typing import Any, ClassVar + +import numpy as np +# import pytorch3d.transforms as pt +import torch +from pydantic import Field, PrivateAttr, field_validator, model_validator + +from ..schema import DatasetMetadata, RotationType, StateActionMetadata +from .base import InvertibleModalityTransform, ModalityTransform + + +class RotationTransform: + """Adapted from https://github.com/real-stanford/diffusion_policy/blob/548a52bbb105518058e27bf34dcf90bf6f73681a/diffusion_policy/model/common/rotation_transformer.py""" + + valid_reps = ["axis_angle", "euler_angles", "quaternion", "rotation_6d", "matrix"] + + def __init__(self, from_rep="axis_angle", to_rep="rotation_6d"): + """ + Valid representations + + Always use matrix as intermediate representation. + """ + if from_rep.startswith("euler_angles"): + from_convention = from_rep.split("_")[-1] + from_rep = "euler_angles" + from_convention = from_convention.replace("r", "X").replace("p", "Y").replace("y", "Z") + else: + from_convention = None + if to_rep.startswith("euler_angles"): + to_convention = to_rep.split("_")[-1] + to_rep = "euler_angles" + to_convention = to_convention.replace("r", "X").replace("p", "Y").replace("y", "Z") + else: + to_convention = None + assert from_rep != to_rep, f"from_rep and to_rep cannot be the same: {from_rep}" + assert from_rep in self.valid_reps, f"Invalid from_rep: {from_rep}" + assert to_rep in self.valid_reps, f"Invalid to_rep: {to_rep}" + + forward_funcs = list() + inverse_funcs = list() + + if from_rep != "matrix": + funcs = [getattr(pt, f"{from_rep}_to_matrix"), getattr(pt, f"matrix_to_{from_rep}")] + if from_convention is not None: + funcs = [functools.partial(func, convention=from_convention) for func in funcs] + forward_funcs.append(funcs[0]) + inverse_funcs.append(funcs[1]) + + if to_rep != "matrix": + funcs = [getattr(pt, f"matrix_to_{to_rep}"), getattr(pt, f"{to_rep}_to_matrix")] + if to_convention is not None: + funcs = [functools.partial(func, convention=to_convention) for func in funcs] + forward_funcs.append(funcs[0]) + inverse_funcs.append(funcs[1]) + + inverse_funcs = inverse_funcs[::-1] + + self.forward_funcs = forward_funcs + self.inverse_funcs = inverse_funcs + + @staticmethod + def _apply_funcs(x: torch.Tensor, funcs: list) -> torch.Tensor: + assert isinstance(x, torch.Tensor) + for func in funcs: + x = func(x) + return x + + def forward(self, x: torch.Tensor) -> torch.Tensor: + assert isinstance( + x, torch.Tensor + ), f"Unexpected input type: {type(x)}. Expected type: {torch.Tensor}" + return self._apply_funcs(x, self.forward_funcs) + + def inverse(self, x: torch.Tensor) -> torch.Tensor: + assert isinstance( + x, torch.Tensor + ), f"Unexpected input type: {type(x)}. Expected type: {torch.Tensor}" + return self._apply_funcs(x, self.inverse_funcs) + + +class Normalizer: + valid_modes = ["q99", "mean_std", "min_max", "binary"] + + def __init__(self, mode: str, statistics: dict): + self.mode = mode + self.statistics = statistics + for key, value in self.statistics.items(): + self.statistics[key] = torch.tensor(value) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + assert isinstance( + x, torch.Tensor + ), f"Unexpected input type: {type(x)}. Expected type: {torch.Tensor}" + + # Normalize the tensor + if self.mode == "q99": + # Range of q99 is [-1, 1] + q01 = self.statistics["q01"].to(x.dtype) + q99 = self.statistics["q99"].to(x.dtype) + + # In the case of q01 == q99, the normalization will be undefined + # So we set the normalized values to the original values + mask = q01 != q99 + normalized = torch.zeros_like(x) + + # Normalize the values where q01 != q99 + # Formula: 2 * (x - q01) / (q99 - q01) - 1 + normalized[..., mask] = (x[..., mask] - q01[..., mask]) / ( + q99[..., mask] - q01[..., mask] + ) + normalized[..., mask] = 2 * normalized[..., mask] - 1 + + # Set the normalized values to the original values where q01 == q99 + normalized[..., ~mask] = x[..., ~mask].to(x.dtype) + + # Clip the normalized values to be between -1 and 1 + normalized = torch.clamp(normalized, -1, 1) + + elif self.mode == "mean_std": + # Range of mean_std is not fixed, but can be positive or negative + mean = self.statistics["mean"].to(x.dtype) + std = self.statistics["std"].to(x.dtype) + + # In the case of std == 0, the normalization will be undefined + # So we set the normalized values to the original values + mask = std != 0 + normalized = torch.zeros_like(x) + + # Normalize the values where std != 0 + # Formula: (x - mean) / std + normalized[..., mask] = (x[..., mask] - mean[..., mask]) / std[..., mask] + + # Set the normalized values to the original values where std == 0 + normalized[..., ~mask] = x[..., ~mask].to(x.dtype) + + elif self.mode == "min_max": + # Range of min_max is [-1, 1] + min = self.statistics["min"].to(x.dtype) + max = self.statistics["max"].to(x.dtype) + + # In the case of min == max, the normalization will be undefined + # So we set the normalized values to the original values + mask = min != max + normalized = torch.zeros_like(x) + + # Normalize the values where min != max + # Formula: 2 * (x - min) / (max - min) - 1 + normalized[..., mask] = (x[..., mask] - min[..., mask]) / ( + max[..., mask] - min[..., mask] + ) + normalized[..., mask] = 2 * normalized[..., mask] - 1 + + # Set the normalized values to the original values where min == max + # normalized[..., ~mask] = x[..., ~mask].to(x.dtype) + # Set the normalized values to 0 where min == max + normalized[..., ~mask] = 0 + + elif self.mode == "scale": + # Range of scale is [0, 1] + min = self.statistics["min"].to(x.dtype) + max = self.statistics["max"].to(x.dtype) + abs_max = torch.max(torch.abs(min), torch.abs(max)) + mask = abs_max != 0 + normalized = torch.zeros_like(x) + normalized[..., mask] = x[..., mask] / abs_max[..., mask] + normalized[..., ~mask] = 0 + + elif self.mode == "binary": + # Range of binary is [0, 1] + normalized = (x > 0.5).to(x.dtype) + else: + raise ValueError(f"Invalid normalization mode: {self.mode}") + + return normalized + + def inverse(self, x: torch.Tensor) -> torch.Tensor: + assert isinstance( + x, torch.Tensor + ), f"Unexpected input type: {type(x)}. Expected type: {torch.Tensor}" + if self.mode == "q99": + q01 = self.statistics["q01"].to(x.dtype) + q99 = self.statistics["q99"].to(x.dtype) + return (x + 1) / 2 * (q99 - q01) + q01 + elif self.mode == "mean_std": + mean = self.statistics["mean"].to(x.dtype) + std = self.statistics["std"].to(x.dtype) + return x * std + mean + elif self.mode == "min_max": + min = self.statistics["min"].to(x.dtype) + max = self.statistics["max"].to(x.dtype) + return (x + 1) / 2 * (max - min) + min + elif self.mode == "binary": + return (x > 0.5).to(x.dtype) + else: + raise ValueError(f"Invalid normalization mode: {self.mode}") + + +class StateActionToTensor(InvertibleModalityTransform): + """ + Transforms states and actions to tensors. + """ + + input_dtypes: dict[str, np.dtype] = Field( + default_factory=dict, description="The input dtypes for each state key." + ) + output_dtypes: dict[str, torch.dtype] = Field( + default_factory=dict, description="The output dtypes for each state key." + ) + + def model_dump(self, *args, **kwargs): + if kwargs.get("mode", "python") == "json": + include = {"apply_to"} + else: + include = kwargs.pop("include", None) + + return super().model_dump(*args, include=include, **kwargs) + + @field_validator("input_dtypes", "output_dtypes", mode="before") + def validate_dtypes(cls, v): + for key, dtype in v.items(): + if isinstance(dtype, str): + if dtype.startswith("torch."): + dtype_split = dtype.split(".")[-1] + v[key] = getattr(torch, dtype_split) + elif dtype.startswith("np.") or dtype.startswith("numpy."): + dtype_split = dtype.split(".")[-1] + v[key] = np.dtype(dtype_split) + else: + raise ValueError(f"Invalid dtype: {dtype}") + return v + + def apply(self, data: dict[str, Any]) -> dict[str, Any]: + for key in self.apply_to: + if key not in data: + continue + value = data[key] + assert isinstance( + value, np.ndarray + ), f"Unexpected input type: {type(value)}. Expected type: {np.ndarray}" + data[key] = torch.from_numpy(value) + if key in self.output_dtypes: + data[key] = data[key].to(self.output_dtypes[key]) + return data + + def unapply(self, data: dict[str, Any]) -> dict[str, Any]: + for key in self.apply_to: + if key not in data: + continue + value = data[key] + assert isinstance( + value, torch.Tensor + ), f"Unexpected input type: {type(value)}. Expected type: {torch.Tensor}" + data[key] = value.numpy() + if key in self.input_dtypes: + data[key] = data[key].astype(self.input_dtypes[key]) + return data + + +class StateActionTransform(InvertibleModalityTransform): + """ + Class for state or action transform. + + Args: + apply_to (list[str]): The keys in the modality to load and transform. + normalization_modes (dict[str, str]): The normalization modes for each state key. + If a state key in apply_to is not present in the dictionary, it will not be normalized. + target_rotations (dict[str, str]): The target representations for each state key. + If a state key in apply_to is not present in the dictionary, it will not be rotated. + """ + + # Configurable attributes + apply_to: list[str] = Field(..., description="The keys in the modality to load and transform.") + normalization_modes: dict[str, str] = Field( + default_factory=dict, description="The normalization modes for each state key." + ) + target_rotations: dict[str, str] = Field( + default_factory=dict, description="The target representations for each state key." + ) + normalization_statistics: dict[str, dict] = Field( + default_factory=dict, description="The statistics for each state key." + ) + modality_metadata: dict[str, StateActionMetadata] = Field( + default_factory=dict, description="The modality metadata for each state key." + ) + + # Model variables + _rotation_transformers: dict[str, RotationTransform] = PrivateAttr(default_factory=dict) + _normalizers: dict[str, Normalizer] = PrivateAttr(default_factory=dict) + _input_dtypes: dict[str, np.dtype | torch.dtype] = PrivateAttr(default_factory=dict) + + # Model constants + _DEFAULT_MIN_MAX_STATISTICS: ClassVar[dict] = { + "rotation_6d": { + "min": [-1, -1, -1, -1, -1, -1], + "max": [1, 1, 1, 1, 1, 1], + }, + "euler_angles": { + "min": [-np.pi, -np.pi, -np.pi], + "max": [np.pi, np.pi, np.pi], + }, + "quaternion": { + "min": [-1, -1, -1, -1], + "max": [1, 1, 1, 1], + }, + "axis_angle": { + "min": [-np.pi, -np.pi, -np.pi], + "max": [np.pi, np.pi, np.pi], + }, + } + + def model_dump(self, *args, **kwargs): + if kwargs.get("mode", "python") == "json": + include = {"apply_to", "normalization_modes", "target_rotations"} + else: + include = kwargs.pop("include", None) + + return super().model_dump(*args, include=include, **kwargs) + + @field_validator("modality_metadata", mode="before") + def validate_modality_metadata(cls, v): + for modality_key, config in v.items(): + if isinstance(config, dict): + config = StateActionMetadata.model_validate(config) + else: + assert isinstance( + config, StateActionMetadata + ), f"Invalid source rotation config: {config}" + v[modality_key] = config + return v + + @model_validator(mode="after") + def validate_normalization_statistics(self): + for modality_key, normalization_statistics in self.normalization_statistics.items(): + if modality_key in self.normalization_modes: + normalization_mode = self.normalization_modes[modality_key] + if normalization_mode == "min_max": + assert ( + "min" in normalization_statistics and "max" in normalization_statistics + ), f"Min and max statistics are required for min_max normalization, but got {normalization_statistics}" + assert len(normalization_statistics["min"]) == len( + normalization_statistics["max"] + ), f"Min and max statistics must have the same length, but got {normalization_statistics['min']} and {normalization_statistics['max']}" + elif normalization_mode == "mean_std": + assert ( + "mean" in normalization_statistics and "std" in normalization_statistics + ), f"Mean and std statistics are required for mean_std normalization, but got {normalization_statistics}" + assert len(normalization_statistics["mean"]) == len( + normalization_statistics["std"] + ), f"Mean and std statistics must have the same length, but got {normalization_statistics['mean']} and {normalization_statistics['std']}" + elif normalization_mode == "q99": + assert ( + "q01" in normalization_statistics and "q99" in normalization_statistics + ), f"q01 and q99 statistics are required for q99 normalization, but got {normalization_statistics}" + assert len(normalization_statistics["q01"]) == len( + normalization_statistics["q99"] + ), f"q01 and q99 statistics must have the same length, but got {normalization_statistics['q01']} and {normalization_statistics['q99']}" + elif normalization_mode == "binary": + assert ( + len(normalization_statistics) == 1 + ), f"Binary normalization should only have one value, but got {normalization_statistics}" + assert normalization_statistics[0] in [ + 0, + 1, + ], f"Binary normalization should only have 0 or 1, but got {normalization_statistics[0]}" + else: + raise ValueError(f"Invalid normalization mode: {normalization_mode}") + return self + + def set_metadata(self, dataset_metadata: DatasetMetadata): + dataset_statistics = dataset_metadata.statistics + modality_metadata = dataset_metadata.modalities + + # Check that all state keys specified in apply_to have their modality_metadata + for key in self.apply_to: + split_key = key.split(".", 1) + assert len(split_key) == 2, "State keys should have two parts: 'modality.key'" + if key not in self.modality_metadata: + modality, state_key = split_key + assert hasattr(modality_metadata, modality), f"{modality} config not found" + assert state_key in getattr( + modality_metadata, modality + ), f"{state_key} config not found" + self.modality_metadata[key] = getattr(modality_metadata, modality)[state_key] + + # Check that all state keys specified in normalization_modes have their statistics in state_statistics + for key in self.normalization_modes: + split_key = key.split(".", 1) + assert len(split_key) == 2, "State keys should have two parts: 'modality.key'" + modality, state_key = split_key + assert hasattr(dataset_statistics, modality), f"{modality} statistics not found" + assert state_key in getattr( + dataset_statistics, modality + ), f"{state_key} statistics not found" + assert ( + len(getattr(modality_metadata, modality)[state_key].shape) == 1 + ), f"{getattr(modality_metadata, modality)[state_key].shape=}" + self.normalization_statistics[key] = getattr(dataset_statistics, modality)[ + state_key + ].model_dump() + + # Initialize the rotation transformers + for key in self.target_rotations: + # Get the original representation of the state + from_rep = self.modality_metadata[key].rotation_type + assert from_rep is not None, f"Source rotation type not found for {key}" + + # Get the target representation of the state, will raise an error if the target representation is not valid + to_rep = RotationType(self.target_rotations[key]) + + # If the original representation is not the same as the target representation, initialize the rotation transformer + if from_rep != to_rep: + self._rotation_transformers[key] = RotationTransform( + from_rep=from_rep.value, to_rep=to_rep.value + ) + + # Initialize the normalizers + for key in self.normalization_modes: + modality, state_key = key.split(".", 1) + # If the state has a nontrivial rotation, we need to handle it more carefully + # For absolute rotations, we need to convert them to the target representation and normalize them using min_max mode, + # since we can infer the bounds by the representation + # For relative rotations, we cannot normalize them as we don't know the bounds + if key in self._rotation_transformers: + # Case 1: Absolute rotation + if self.modality_metadata[key].absolute: + # Check that the normalization mode is valid + assert ( + self.normalization_modes[key] == "min_max" + ), "Absolute rotations that are converted to other formats must be normalized using `min_max` mode" + rotation_type = RotationType(self.target_rotations[key]).value + # If the target representation is euler angles, we need to parse the convention + if rotation_type.startswith("euler_angles"): + rotation_type = "euler_angles" + # Get the statistics for the target representation + statistics = self._DEFAULT_MIN_MAX_STATISTICS[rotation_type] + # Case 2: Relative rotation + else: + raise ValueError( + f"Cannot normalize relative rotations: {key} that's converted to {self.target_rotations[key]}" + ) + # If the state is not continuous, we should not use normalization modes other than binary + elif ( + not self.modality_metadata[key].continuous + and self.normalization_modes[key] != "binary" + ): + raise ValueError( + f"{key} is not continuous, so it should be normalized using `binary` mode" + ) + # Initialize the normalizer + else: + statistics = self.normalization_statistics[key] + self._normalizers[key] = Normalizer( + mode=self.normalization_modes[key], statistics=statistics + ) + + def apply(self, data: dict[str, Any]) -> dict[str, Any]: + for key in self.apply_to: + if key not in data: + # We allow some keys to be missing in the data, and only process the keys that are present + continue + if key not in self._input_dtypes: + input_dtype = data[key].dtype + assert isinstance( + input_dtype, torch.dtype + ), f"Unexpected input dtype: {input_dtype}. Expected type: {torch.dtype}" + self._input_dtypes[key] = input_dtype + else: + assert ( + data[key].dtype == self._input_dtypes[key] + ), 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]}" + # Rotate the state + state = data[key] + if key in self._rotation_transformers: + state = self._rotation_transformers[key].forward(state) + # Normalize the state + if key in self._normalizers: + state = self._normalizers[key].forward(state) + data[key] = state + return data + + def unapply(self, data: dict[str, Any]) -> dict[str, Any]: + for key in self.apply_to: + if key not in data: + continue + state = data[key] + assert isinstance( + state, torch.Tensor + ), f"Unexpected state type: {type(state)}. Expected type: {torch.Tensor}" + # Unnormalize the state + if key in self._normalizers: + state = self._normalizers[key].inverse(state) + # Change the state back to its original representation + if key in self._rotation_transformers: + state = self._rotation_transformers[key].inverse(state) + assert isinstance( + state, torch.Tensor + ), f"State should be tensor after unapplying transformations, but got {type(state)}" + # Only convert back to the original dtype if it's known, i.e. `apply` was called before + # If not, we don't know the original dtype, so we don't convert + if key in self._input_dtypes: + original_dtype = self._input_dtypes[key] + if isinstance(original_dtype, np.dtype): + state = state.numpy().astype(original_dtype) + elif isinstance(original_dtype, torch.dtype): + state = state.to(original_dtype) + else: + raise ValueError(f"Invalid input dtype: {original_dtype}") + data[key] = state + return data + + +class StateActionPerturbation(ModalityTransform): + """ + Class for state or action perturbation. + + Args: + apply_to (list[str]): The keys in the modality to load and transform. + std (float): Standard deviation of the noise to be added to the state or action. + """ + + # Configurable attributes + std: float = Field( + ..., description="Standard deviation of the noise to be added to the state or action." + ) + + def apply(self, data: dict[str, Any]) -> dict[str, Any]: + if not self.training: + # Don't perturb the data in eval mode + return data + if self.std < 0: + # If the std is negative, we don't add any noise + return data + for key in self.apply_to: + state = data[key] + assert isinstance(state, torch.Tensor) + transformed_data_min = torch.min(state) + transformed_data_max = torch.max(state) + noise = torch.randn_like(state) * self.std + state += noise + # Clip to the original range + state = torch.clamp(state, transformed_data_min, transformed_data_max) + data[key] = state + return data + + +class StateActionDropout(ModalityTransform): + """ + Class for state or action dropout. + + Args: + apply_to (list[str]): The keys in the modality to load and transform. + dropout_prob (float): Probability of dropping out a state or action. + """ + + # Configurable attributes + dropout_prob: float = Field(..., description="Probability of dropping out a state or action.") + + def apply(self, data: dict[str, Any]) -> dict[str, Any]: + if not self.training: + # Don't drop out the data in eval mode + return data + if self.dropout_prob < 0: + # If the dropout probability is negative, we don't drop out any states + return data + if self.dropout_prob > 1e-9 and random.random() < self.dropout_prob: + for key in self.apply_to: + state = data[key] + assert isinstance(state, torch.Tensor) + state = torch.zeros_like(state) + data[key] = state + return data + + +class StateActionSinCosTransform(ModalityTransform): + """ + Class for state or action sin-cos transform. + + Args: + apply_to (list[str]): The keys in the modality to load and transform. + """ + + def apply(self, data: dict[str, Any]) -> dict[str, Any]: + for key in self.apply_to: + state = data[key] + assert isinstance(state, torch.Tensor) + sin_state = torch.sin(state) + cos_state = torch.cos(state) + data[key] = torch.cat([sin_state, cos_state], dim=-1) + return data diff --git a/starVLA/dataloader/gr00t_lerobot/transform/video.py b/starVLA/dataloader/gr00t_lerobot/transform/video.py new file mode 100644 index 0000000000000000000000000000000000000000..0c31c194786ff5425a934dd561ce3eb8047f86b8 --- /dev/null +++ b/starVLA/dataloader/gr00t_lerobot/transform/video.py @@ -0,0 +1,683 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Any, Callable, ClassVar, Literal + +import albumentations as A +import cv2 +import numpy as np +import torch +import torchvision.transforms.v2 as T +from einops import rearrange +from pydantic import Field, PrivateAttr, field_validator +from PIL import Image + +from ..schema import DatasetMetadata +from .base import ModalityTransform + + +class VideoTransform(ModalityTransform): + # Configurable attributes + backend: str = Field( + default="torchvision", description="The backend to use for the transformations" + ) + + # Model variables + _train_transform: Callable | None = PrivateAttr(default=None) + _eval_transform: Callable | None = PrivateAttr(default=None) + _original_resolutions: dict[str, tuple[int, int]] = PrivateAttr(default_factory=dict) + + # Model constants + _INTERPOLATION_MAP: ClassVar[dict[str, dict[str, Any]]] = PrivateAttr( + { + "nearest": { + "albumentations": cv2.INTER_NEAREST, + "torchvision": T.InterpolationMode.NEAREST, + }, + "linear": { + "albumentations": cv2.INTER_LINEAR, + "torchvision": T.InterpolationMode.BILINEAR, + }, + "cubic": { + "albumentations": cv2.INTER_CUBIC, + "torchvision": T.InterpolationMode.BICUBIC, + }, + "area": { + "albumentations": cv2.INTER_AREA, + "torchvision": None, # Torchvision does not support this interpolation mode + }, + "lanczos4": { + "albumentations": cv2.INTER_LANCZOS4, # Lanczos with a 4x4 filter + "torchvision": T.InterpolationMode.LANCZOS, # Torchvision does not specify filter size, might be different from 4x4 + }, + "linear_exact": { + "albumentations": cv2.INTER_LINEAR_EXACT, + "torchvision": None, # Torchvision does not support this interpolation mode + }, + "nearest_exact": { + "albumentations": cv2.INTER_NEAREST_EXACT, + "torchvision": T.InterpolationMode.NEAREST_EXACT, + }, + "max": { + "albumentations": cv2.INTER_MAX, + "torchvision": None, + }, + } + ) + + @property + def train_transform(self) -> Callable: + assert ( + self._train_transform is not None + ), "Transform is not set. Please call set_metadata() before calling apply()." + return self._train_transform + + @train_transform.setter + def train_transform(self, value: Callable): + self._train_transform = value + + @property + def eval_transform(self) -> Callable | None: + return self._eval_transform + + @eval_transform.setter + def eval_transform(self, value: Callable | None): + self._eval_transform = value + + @property + def original_resolutions(self) -> dict[str, tuple[int, int]]: + assert ( + self._original_resolutions is not None + ), "Original resolutions are not set. Please call set_metadata() before calling apply()." + return self._original_resolutions + + @original_resolutions.setter + def original_resolutions(self, value: dict[str, tuple[int, int]]): + self._original_resolutions = value + + def check_input(self, data: dict[str, Any]): + if self.backend == "torchvision": + for key in self.apply_to: + assert isinstance(data[key], torch.Tensor), f"Video {key} is not a torch tensor" + assert data[key].ndim in [ + 4, + 5, + ], f"Expected video {key} to have 4 or 5 dimensions (T, C, H, W or T, B, C, H, W), got {data[key].ndim}" + elif self.backend == "albumentations": + for key in self.apply_to: + assert isinstance(data[key], np.ndarray), f"Video {key} is not a numpy array" + assert data[key].ndim in [ + 4, + 5, + ], f"Expected video {key} to have 4 or 5 dimensions (T, C, H, W or T, B, C, H, W), got {data[key].ndim}" + else: + raise ValueError(f"Backend {self.backend} not supported") + + def set_metadata(self, dataset_metadata: DatasetMetadata): + super().set_metadata(dataset_metadata) + self.original_resolutions = {} + for key in self.apply_to: + split_keys = key.split(".") + assert len(split_keys) == 2, f"Invalid key: {key}. Expected format: modality.key" + sub_key = split_keys[1] + if sub_key in dataset_metadata.modalities.video: + self.original_resolutions[key] = dataset_metadata.modalities.video[ + sub_key + ].resolution + else: + raise ValueError( + f"Video key {sub_key} not found in dataset metadata. Available keys: {dataset_metadata.modalities.video.keys()}" + ) + train_transform = self.get_transform(mode="train") + eval_transform = self.get_transform(mode="eval") + if self.backend == "albumentations": + self.train_transform = A.ReplayCompose(transforms=[train_transform]) # type: ignore + if eval_transform is not None: + self.eval_transform = A.ReplayCompose(transforms=[eval_transform]) # type: ignore + else: + assert train_transform is not None, "Train transform must be set" + self.train_transform = train_transform + self.eval_transform = eval_transform + + def apply(self, data: dict[str, Any]) -> dict[str, Any]: + if self.training: + transform = self.train_transform + else: + transform = self.eval_transform + if transform is None: + return data + assert ( + transform is not None + ), "Transform is not set. Please call set_metadata() before calling apply()." + try: + self.check_input(data) + except AssertionError as e: + raise ValueError( + f"Input data does not match the expected format for {self.__class__.__name__}: {e}" + ) from e + + # Concatenate views + views = [data[key] for key in self.apply_to] + num_views = len(views) + is_batched = views[0].ndim == 5 + bs = views[0].shape[0] if is_batched else 1 + if isinstance(views[0], torch.Tensor): + views = torch.cat(views, 0) + elif isinstance(views[0], np.ndarray): + views = np.concatenate(views, 0) + else: + raise ValueError(f"Unsupported view type: {type(views[0])}") + if is_batched: + views = rearrange(views, "(v b) t c h w -> (v b t) c h w", v=num_views, b=bs) + # Apply the transform + if self.backend == "torchvision": + views = transform(views) + elif self.backend == "albumentations": + assert isinstance(transform, A.ReplayCompose), "Transform must be a ReplayCompose" + first_frame = views[0] + transformed = transform(image=first_frame) + replay_data = transformed["replay"] + transformed_first_frame = transformed["image"] + + if len(views) > 1: + # Apply the same transformations to the rest of the frames + transformed_frames = [ + transform.replay(replay_data, image=frame)["image"] for frame in views[1:] + ] + # Add the first frame back + transformed_frames = [transformed_first_frame] + transformed_frames + else: + # If there is only one frame, just make a list with one frame + transformed_frames = [transformed_first_frame] + + # Delete the replay data to save memory + del replay_data + views = np.stack(transformed_frames, 0) + + else: + raise ValueError(f"Backend {self.backend} not supported") + # Split views + if is_batched: + views = rearrange(views, "(v b t) c h w -> v b t c h w", v=num_views, b=bs) + else: + views = rearrange(views, "(v t) c h w -> v t c h w", v=num_views) + for key, view in zip(self.apply_to, views): + data[key] = view + return data + + @classmethod + def _validate_interpolation(cls, interpolation: str): + if interpolation not in cls._INTERPOLATION_MAP: + raise ValueError(f"Interpolation mode {interpolation} not supported") + + def _get_interpolation(self, interpolation: str, backend: str = "torchvision"): + """ + Get the interpolation mode for the given backend. + + Args: + interpolation (str): The interpolation mode. + backend (str): The backend to use. + + Returns: + Any: The interpolation mode for the given backend. + """ + return self._INTERPOLATION_MAP[interpolation][backend] + + def get_transform(self, mode: Literal["train", "eval"] = "train") -> Callable | None: + raise NotImplementedError( + "set_transform is not implemented for VideoTransform. Please implement this function to set the transforms." + ) + + +class VideoCrop(VideoTransform): + height: int | None = Field(default=None, description="The height of the input image") + width: int | None = Field(default=None, description="The width of the input image") + scale: float = Field( + ..., + description="The scale of the crop. The crop size is (width * scale, height * scale)", + ) + + def get_transform(self, mode: Literal["train", "eval"] = "train") -> Callable: + """Get the transform for the given mode. + + Args: + mode (Literal["train", "eval"]): The mode to get the transform for. + + Returns: + Callable: If mode is "train", return a random crop transform. If mode is "eval", return a center crop transform. + """ + # 1. Check the input resolution + assert ( + len(set(self.original_resolutions.values())) == 1 + ), f"All video keys must have the same resolution, got: {self.original_resolutions}" + if self.height is None: + assert self.width is None, "Height and width must be either both provided or both None" + self.width, self.height = self.original_resolutions[self.apply_to[0]] + else: + assert ( + self.width is not None + ), "Height and width must be either both provided or both None" + # 2. Create the transform + size = (int(self.height * self.scale), int(self.width * self.scale)) + if self.backend == "torchvision": + if mode == "train": + return T.RandomCrop(size) + elif mode == "eval": + return T.CenterCrop(size) + else: + raise ValueError(f"Crop mode {mode} not supported") + elif self.backend == "albumentations": + if mode == "train": + return A.RandomCrop(height=size[0], width=size[1], p=1) + elif mode == "eval": + return A.CenterCrop(height=size[0], width=size[1], p=1) + else: + raise ValueError(f"Crop mode {mode} not supported") + else: + raise ValueError(f"Backend {self.backend} not supported") + + def check_input(self, data: dict[str, Any]): + super().check_input(data) + # Check the input resolution + for key in self.apply_to: + if self.backend == "torchvision": + height, width = data[key].shape[-2:] + elif self.backend == "albumentations": + height, width = data[key].shape[-3:-1] + else: + raise ValueError(f"Backend {self.backend} not supported") + assert ( + height == self.height and width == self.width + ), f"Video {key} has invalid shape {height, width}, expected {self.height, self.width}" + +class VideoResizePad(VideoTransform): + size: int = Field(..., description="The target size (both height and width will be this value)") + interpolation: str = Field(default="linear", description="The interpolation mode") + antialias: bool = Field(default=True, description="Whether to apply antialiasing") + fill_value: float = Field(default=0.0, description="The value to fill the padding (0.0 for black)") + + @field_validator("interpolation") + def validate_interpolation(cls, v): + cls._validate_interpolation(v) + return v + + def get_transform(self, mode: Literal["train", "eval"] = "train") -> Callable: + """Get the resize and pad transform that keeps aspect ratio. + + Args: + mode (Literal["train", "eval"]): The mode to get the transform for. + + Returns: + Callable: The resize and pad transform that resizes the longest edge to target size and pads the rest. + """ + if self.backend == "torchvision": + return self._torchvision_resize_pad + elif self.backend == "albumentations": + # For albumentations, use LongestMaxSize + PadIfNeeded + interpolation = self._get_interpolation(self.interpolation, self.backend) + return A.Compose([ + A.LongestMaxSize(max_size=self.size, interpolation=interpolation, p=1), + A.PadIfNeeded( + min_height=self.size, + min_width=self.size, + border_mode=cv2.BORDER_CONSTANT, + value=int(self.fill_value * 255), # Convert to uint8 range for numpy arrays + position=A.PadIfNeeded.PositionType.CENTER, # Center the image + p=1 + ) + ]) + else: + raise ValueError(f"Backend {self.backend} not supported") + + def _torchvision_resize_pad(self, frames: torch.Tensor) -> torch.Tensor: + """Resize and pad frames using torchvision. + + Args: + frames: tensor of shape [N, C, H, W] where N could be batch*time + + Returns: + tensor of shape [N, C, target_size, target_size] + """ + interpolation = self._get_interpolation(self.interpolation, self.backend) + N, C, H, W = frames.shape + + # Calculate scaling factor (scale longest edge to target size) + scale = self.size / max(H, W) + new_h = int(H * scale) + new_w = int(W * scale) + + # Resize + resized = T.Resize((new_h, new_w), interpolation=interpolation, antialias=self.antialias)(frames) + + # Calculate padding + pad_h = self.size - new_h + pad_w = self.size - new_w + pad_top = pad_h // 2 + pad_bottom = pad_h - pad_top + pad_left = pad_w // 2 + pad_right = pad_w - pad_left + + # Pad (pad order is: left, right, top, bottom) + padded = T.Pad([pad_left, pad_top, pad_right, pad_bottom], fill=self.fill_value)(resized) + + return padded + +class VideoResize(VideoTransform): + height: int = Field(..., description="The height of the resize") + width: int = Field(..., description="The width of the resize") + interpolation: str = Field(default="linear", description="The interpolation mode") + antialias: bool = Field(default=True, description="Whether to apply antialiasing") + + @field_validator("interpolation") + def validate_interpolation(cls, v): + cls._validate_interpolation(v) + return v + + def get_transform(self, mode: Literal["train", "eval"] = "train") -> Callable: + """Get the resize transform. Same transform for both train and eval. + + Args: + mode (Literal["train", "eval"]): The mode to get the transform for. + + Returns: + Callable: The resize transform. + """ + interpolation = self._get_interpolation(self.interpolation, self.backend) + if interpolation is None: + raise ValueError( + f"Interpolation mode {self.interpolation} not supported for torchvision" + ) + if self.backend == "torchvision": + size = (self.height, self.width) + return T.Resize(size, interpolation=interpolation, antialias=self.antialias) + elif self.backend == "albumentations": + return A.Resize( + height=self.height, + width=self.width, + interpolation=interpolation, + p=1, + ) + else: + raise ValueError(f"Backend {self.backend} not supported") + + +class VideoRandomRotation(VideoTransform): + degrees: float | tuple[float, float] = Field( + ..., description="The degrees of the random rotation" + ) + interpolation: str = Field("linear", description="The interpolation mode") + + @field_validator("interpolation") + def validate_interpolation(cls, v): + cls._validate_interpolation(v) + return v + + def get_transform(self, mode: Literal["train", "eval"] = "train") -> Callable | None: + """Get the random rotation transform, only used in train mode. + + Args: + mode (Literal["train", "eval"]): The mode to get the transform for. + + Returns: + Callable | None: The random rotation transform. None for eval mode. + """ + if mode == "eval": + return None + interpolation = self._get_interpolation(self.interpolation, self.backend) + if interpolation is None: + raise ValueError( + f"Interpolation mode {self.interpolation} not supported for torchvision" + ) + if self.backend == "torchvision": + return T.RandomRotation(self.degrees, interpolation=interpolation) # type: ignore + elif self.backend == "albumentations": + return A.Rotate(limit=self.degrees, interpolation=interpolation, p=1) + else: + raise ValueError(f"Backend {self.backend} not supported") + + +class VideoHorizontalFlip(VideoTransform): + p: float = Field(..., description="The probability of the horizontal flip") + + def get_transform(self, mode: Literal["train", "eval"] = "train") -> Callable | None: + """Get the horizontal flip transform, only used in train mode. + + Args: + mode (Literal["train", "eval"]): The mode to get the transform for. + + Returns: + Callable | None: If mode is "train", return a horizontal flip transform. If mode is "eval", return None. + """ + if mode == "eval": + return None + if self.backend == "torchvision": + return T.RandomHorizontalFlip(self.p) + elif self.backend == "albumentations": + return A.HorizontalFlip(p=self.p) + else: + raise ValueError(f"Backend {self.backend} not supported") + + +class VideoGrayscale(VideoTransform): + p: float = Field(..., description="The probability of the grayscale transformation") + + def get_transform(self, mode: Literal["train", "eval"] = "train") -> Callable | None: + """Get the grayscale transform, only used in train mode. + + Args: + mode (Literal["train", "eval"]): The mode to get the transform for. + + Returns: + Callable | None: If mode is "train", return a grayscale transform. If mode is "eval", return None. + """ + if mode == "eval": + return None + if self.backend == "torchvision": + return T.RandomGrayscale(self.p) + elif self.backend == "albumentations": + return A.ToGray(p=self.p) + else: + raise ValueError(f"Backend {self.backend} not supported") + + +class VideoColorJitter(VideoTransform): + brightness: float | tuple[float, float] = Field( + ..., description="The brightness of the color jitter" + ) + contrast: float | tuple[float, float] = Field( + ..., description="The contrast of the color jitter" + ) + saturation: float | tuple[float, float] = Field( + ..., description="The saturation of the color jitter" + ) + hue: float | tuple[float, float] = Field(..., description="The hue of the color jitter") + + def get_transform(self, mode: Literal["train", "eval"] = "train") -> Callable | None: + """Get the color jitter transform, only used in train mode. + + Args: + mode (Literal["train", "eval"]): The mode to get the transform for. + + Returns: + Callable | None: If mode is "train", return a color jitter transform. If mode is "eval", return None. + """ + if mode == "eval": + return None + if self.backend == "torchvision": + return T.ColorJitter( + brightness=self.brightness, + contrast=self.contrast, + saturation=self.saturation, + hue=self.hue, + ) + elif self.backend == "albumentations": + return A.ColorJitter( + brightness=self.brightness, + contrast=self.contrast, + saturation=self.saturation, + hue=self.hue, + p=1, + ) + else: + raise ValueError(f"Backend {self.backend} not supported") + + +class VideoRandomGrayscale(VideoTransform): + p: float = Field(..., description="The probability of the grayscale transformation") + + def get_transform(self, mode: Literal["train", "eval"] = "train") -> Callable | None: + """Get the grayscale transform, only used in train mode. + + Args: + mode (Literal["train", "eval"]): The mode to get the transform for. + + Returns: + Callable | None: If mode is "train", return a grayscale transform. If mode is "eval", return None. + """ + if mode == "eval": + return None + if self.backend == "torchvision": + return T.RandomGrayscale(self.p) + elif self.backend == "albumentations": + return A.ToGray(p=self.p) + else: + raise ValueError(f"Backend {self.backend} not supported") + + +class VideoRandomPosterize(VideoTransform): + bits: int = Field(..., description="The number of bits to posterize the image") + p: float = Field(..., description="The probability of the posterize transformation") + + def get_transform(self, mode: Literal["train", "eval"] = "train") -> Callable | None: + """Get the posterize transform, only used in train mode. + + Args: + mode (Literal["train", "eval"]): The mode to get the transform for. + + Returns: + Callable | None: If mode is "train", return a posterize transform. If mode is "eval", return None. + """ + if mode == "eval": + return None + if self.backend == "torchvision": + return T.RandomPosterize(bits=self.bits, p=self.p) + elif self.backend == "albumentations": + return A.Posterize(num_bits=self.bits, p=self.p) + else: + raise ValueError(f"Backend {self.backend} not supported") + + +class VideoToTensor(VideoTransform): + def get_transform(self, mode: Literal["train", "eval"] = "train") -> Callable: + """Get the to tensor transform. Same transform for both train and eval. + + Args: + mode (Literal["train", "eval"]): The mode to get the transform for. + + Returns: + Callable: The to tensor transform. + """ + if self.backend == "torchvision": + return self.__class__.to_tensor + else: + raise ValueError(f"Backend {self.backend} not supported") + + def check_input(self, data: dict): + """Check if the input data has the correct shape. + Expected video shape: [T, H, W, C], dtype np.uint8 + """ + for key in self.apply_to: + assert key in data, f"Key {key} not found in data. Available keys: {data.keys()}" + assert data[key].ndim in [ + 4, + 5, + ], f"Video {key} must have 4 or 5 dimensions, got {data[key].ndim}" + assert ( + data[key].dtype == np.uint8 + ), f"Video {key} must have dtype uint8, got {data[key].dtype}" + input_resolution = data[key].shape[-3:-1][::-1] + if key in self.original_resolutions: + expected_resolution = self.original_resolutions[key] + else: + expected_resolution = input_resolution + assert ( + input_resolution == expected_resolution + ), f"Video {key} has invalid resolution {input_resolution}, expected {expected_resolution}. Full shape: {data[key].shape}" + + @staticmethod + def to_tensor(frames: np.ndarray) -> torch.Tensor: + """Convert numpy array to tensor efficiently. + + Args: + frames: numpy array of shape [T, H, W, C] in uint8 format + Returns: + tensor of shape [T, C, H, W] in range [0, 1] + """ + frames_tensor = torch.from_numpy(frames).to(torch.float32) / 255.0 + return frames_tensor.permute(0, 3, 1, 2) # [T, C, H, W] + + +class VideoToNumpy(VideoTransform): + def get_transform(self, mode: Literal["train", "eval"] = "train") -> Callable: + """Get the to numpy transform. Same transform for both train and eval. + + Args: + mode (Literal["train", "eval"]): The mode to get the transform for. + + Returns: + Callable: The to numpy transform. + """ + if self.backend == "torchvision": + return self.__class__.to_numpy + else: + raise ValueError(f"Backend {self.backend} not supported") + + @staticmethod + def to_numpy(frames: torch.Tensor) -> np.ndarray: + """Convert tensor back to numpy array efficiently. + + Args: + frames: tensor of shape [T, C, H, W] in range [0, 1] + Returns: + numpy array of shape [T, H, W, C] in uint8 format + """ + return (frames.permute(0, 2, 3, 1) * 255).to(torch.uint8).cpu().numpy() + +class VideoToPIL(VideoTransform): + def get_transform(self, mode: Literal["train", "eval"] = "train") -> Callable: + """Get the to PIL transform. Same transform for both train and eval. + + Args: + mode (Literal["train", "eval"]): The mode to get the transform for. + + Returns: + Callable: The to PIL transform. + """ + if self.backend == "torchvision": + return self.__class__.to_pil + else: + raise ValueError(f"Backend {self.backend} not supported") + + @staticmethod + def to_pil(frames: torch.Tensor) -> Image.Image: + """Convert tensor back to PIL Image. + + Args: + frames: tensor of shape [T, C, H, W] in range [0, 1] + Returns: + PIL Image of shape [T, H, W, C] in uint8 format + """ + # video PIL format? + return Image.fromarray((frames.permute(0, 2, 3, 1) * 255).to(torch.uint8).cpu().numpy()) \ No newline at end of file diff --git a/starVLA/dataloader/gr00t_lerobot/video.py b/starVLA/dataloader/gr00t_lerobot/video.py new file mode 100644 index 0000000000000000000000000000000000000000..88efca820056eed8f474f3e6401677027eb2e152 --- /dev/null +++ b/starVLA/dataloader/gr00t_lerobot/video.py @@ -0,0 +1,338 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import av +import cv2 +import numpy as np +import warnings + +import torch # noqa: F401 # isort: skip +import torchvision # noqa: F401 # isort: skip + +# Suppress torchvision video deprecation warning +warnings.filterwarnings("ignore", category=UserWarning, module="torchvision.io._video_deprecation_warning") + +# Import decord with graceful fallback +try: + import decord # noqa: F401 + + DECORD_AVAILABLE = True +except ImportError: + DECORD_AVAILABLE = False + +try: + import torchcodec + + TORCHCODEC_AVAILABLE = True +except (ImportError, RuntimeError): + TORCHCODEC_AVAILABLE = False + + +def get_frames_by_indices( + video_path: str, + indices: list[int] | np.ndarray, + video_backend: str = "decord", + video_backend_kwargs: dict = {}, +) -> np.ndarray: + if video_backend == "decord": + if not DECORD_AVAILABLE: + raise ImportError("decord is not available.") + vr = decord.VideoReader(video_path, **video_backend_kwargs) + frames = vr.get_batch(indices) + return frames.asnumpy() + elif video_backend == "torchcodec": + if not TORCHCODEC_AVAILABLE: + raise ImportError("torchcodec is not available.") + decoder = torchcodec.decoders.VideoDecoder(video_path, device="cpu", dimension_order="NHWC", num_ffmpeg_threads=0) + return decoder.get_frames_at(indices=indices).data.numpy() + elif video_backend == "opencv": + frames = [] + cap = cv2.VideoCapture(video_path, **video_backend_kwargs) + for idx in indices: + cap.set(cv2.CAP_PROP_POS_FRAMES, idx) + ret, frame = cap.read() + if not ret: + raise ValueError(f"Unable to read frame at index {idx}") + frames.append(frame) + cap.release() + frames = np.array(frames) + return frames + elif video_backend == "torchvision_av": + # Optimized version using PyAV directly for better performance + container = av.open(video_path) + video_stream = container.streams.video[0] + fps = float(video_stream.average_rate) + + # Convert frame indices to timestamps + timestamps = np.array(indices) / fps + + # Sort indices to optimize seeking + sorted_order = np.argsort(timestamps) + sorted_timestamps = timestamps[sorted_order] + + loaded_frames = [None] * len(indices) + + try: + last_seek_pos = -1 + for i, target_ts in zip(sorted_order, sorted_timestamps): + # Only seek if we're going backwards or far ahead + if target_ts < last_seek_pos or target_ts - last_seek_pos > 2.0: + # Seek to slightly before target to ensure we don't miss it + seek_ts = max(0, target_ts - 0.5) + container.seek( + int(seek_ts / float(video_stream.time_base)), + stream=video_stream, + backward=True, + any_frame=False, + ) + + closest_frame = None + closest_ts_diff = float('inf') + + # Read frames until we pass the target timestamp + for frame in container.decode(video=0): + current_ts = frame.pts * video_stream.time_base + current_diff = abs(current_ts - target_ts) + + if current_diff < closest_ts_diff: + closest_ts_diff = current_diff + closest_frame = frame + else: + # Timestamps are increasing, we've passed the target + break + + # If we're very close, stop early + if current_diff < 0.001: + break + + if closest_frame is not None: + frame_array = closest_frame.to_ndarray(format="rgb24") + loaded_frames[i] = frame_array + last_seek_pos = target_ts + + finally: + container.close() + + # Filter out any None values (shouldn't happen, but safety check) + loaded_frames = [f for f in loaded_frames if f is not None] + + if len(loaded_frames) == 0: + raise ValueError(f"No frames could be loaded from {video_path}") + + return np.array(loaded_frames) + else: + raise NotImplementedError + + +def get_frames_by_timestamps( + video_path: str, + timestamps: list[float] | np.ndarray, + video_backend: str = "decord", + video_backend_kwargs: dict = {}, +) -> np.ndarray: + """Get frames from a video at specified timestamps. + Args: + video_path (str): Path to the video file. + timestamps (list[int] | np.ndarray): Timestamps to retrieve frames for, in seconds. + video_backend (str, optional): Video backend to use. Defaults to "decord". + Returns: + np.ndarray: Frames at the specified timestamps. + """ + if video_backend == "decord": + # For some GPUs, AV format data cannot be read + if not DECORD_AVAILABLE: + raise ImportError("decord is not available.") + vr = decord.VideoReader(video_path, **video_backend_kwargs) + num_frames = len(vr) + # Retrieve the timestamps for each frame in the video + frame_ts: np.ndarray = vr.get_frame_timestamp(range(num_frames)) + # Map each requested timestamp to the closest frame index + # Only take the first element of the frame_ts array which corresponds to start_seconds + indices = np.abs(frame_ts[:, :1] - timestamps).argmin(axis=0) + frames = vr.get_batch(indices) + return frames.asnumpy() + elif video_backend == "torchcodec": + if not TORCHCODEC_AVAILABLE: + raise ImportError("torchcodec is not available.") + decoder = torchcodec.decoders.VideoDecoder(video_path, device="cpu", dimension_order="NHWC", num_ffmpeg_threads=0) + return decoder.get_frames_played_at(seconds=timestamps).data.numpy() + elif video_backend == "opencv": + # Open the video file + cap = cv2.VideoCapture(video_path, **video_backend_kwargs) + if not cap.isOpened(): + raise ValueError(f"Unable to open video file: {video_path}") + # Retrieve the total number of frames + num_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + # Calculate timestamps for each frame + fps = cap.get(cv2.CAP_PROP_FPS) + frame_ts = np.arange(num_frames) / fps + frame_ts = frame_ts[:, np.newaxis] # Reshape to (num_frames, 1) for broadcasting + # Map each requested timestamp to the closest frame index + indices = np.abs(frame_ts - timestamps).argmin(axis=0) + frames = [] + for idx in indices: + cap.set(cv2.CAP_PROP_POS_FRAMES, idx) + ret, frame = cap.read() + if not ret: + raise ValueError(f"Unable to read frame at index {idx}") + frames.append(frame) + cap.release() + frames = np.array(frames) + return frames + elif video_backend == "torchvision_av": + # PyAV 单次 decode 版本:避免反复 decode 导致 dav1d-worker 线程暴涨 + ts = np.asarray(timestamps, dtype=np.float64) + if ts.ndim != 1: + ts = ts.reshape(-1) + + order = np.argsort(ts) + ts_sorted = ts[order] + + container = av.open(video_path, options={"threads": "1"}) + stream = container.streams.video[0] + + # 更强的“钉死线程”措施(不同版本可能有差异,try/except 保守) + try: + stream.thread_type = "NONE" + except Exception: + pass + try: + stream.codec_context.thread_count = 1 + except Exception: + pass + + out_sorted = [None] * len(ts_sorted) + + try: + # seek 到最早 timestamp 之前一点 + start_ts = max(0.0, float(ts_sorted[0]) - 0.5) + try: + container.seek( + int(start_ts / float(stream.time_base)), + stream=stream, + backward=True, + any_frame=False, + ) + except Exception: + # seek 不可靠就从头开始 + container.seek(0) + + j = 0 + last_frame_arr = None + + # 一次 decode 顺序扫过去 + for frame in container.decode(video=0): + if frame.pts is None: + continue + t = float(frame.pts * stream.time_base) + + # 如果还没到下一个目标,继续 decode + if t + 1e-6 < ts_sorted[j]: + last_frame_arr = frame.to_ndarray(format="rgb24") + continue + + # 到达/超过目标:把当前帧作为该目标的匹配帧 + frame_arr = frame.to_ndarray(format="rgb24") + last_frame_arr = frame_arr + + while j < len(ts_sorted) and t + 1e-6 >= ts_sorted[j]: + out_sorted[j] = frame_arr + j += 1 + if j >= len(ts_sorted): + break + + if j >= len(ts_sorted): + break + + # 如果尾部还有没填的,用最后一帧补(或你也可以 raise) + for k in range(len(out_sorted)): + if out_sorted[k] is None: + out_sorted[k] = last_frame_arr + + finally: + container.close() + + if out_sorted[0] is None: + raise ValueError(f"No frames could be loaded from {video_path}") + + frames_sorted = np.stack(out_sorted, axis=0) + + # 还原到原 timestamps 顺序 + inv = np.empty_like(order) + inv[order] = np.arange(len(order)) + return frames_sorted[inv] + + else: + raise NotImplementedError + + +def get_all_frames( + video_path: str, + video_backend: str = "decord", + video_backend_kwargs: dict = {}, + resize_size: tuple[int, int] | None = None, +) -> np.ndarray: + """Get all frames from a video. + Args: + video_path (str): Path to the video file. + video_backend (str, optional): Video backend to use. Defaults to "decord". + video_backend_kwargs (dict, optional): Keyword arguments for the video backend. + resize_size (tuple[int, int], optional): Resize size for the frames. Defaults to None. + """ + if video_backend == "decord": + if not DECORD_AVAILABLE: + raise ImportError("decord is not available.") + vr = decord.VideoReader(video_path, **video_backend_kwargs) + frames = vr.get_batch(range(len(vr))).asnumpy() + elif video_backend == "torchcodec": + if not TORCHCODEC_AVAILABLE: + raise ImportError("torchcodec is not available.") + decoder = torchcodec.decoders.VideoDecoder(video_path, device="cpu", dimension_order="NHWC", num_ffmpeg_threads=0) + frames = decoder.get_frames_at(indices=range(len(decoder))) + return frames.data.numpy(), frames.pts_seconds.numpy() + elif video_backend == "pyav": + container = av.open(video_path) + frames = [] + for frame in container.decode(video=0): + frame = frame.to_ndarray(format="rgb24") + frames.append(frame) + frames = np.array(frames) + elif video_backend == "torchvision_av": + # 全局 backend 只设一次(避免反复改全局状态) + if getattr(get_all_frames, "_tv_backend_set", False) is False: + torchvision.set_video_backend("pyav") + setattr(get_all_frames, "_tv_backend_set", True) + + reader = torchvision.io.VideoReader(video_path, "video") + try: + frames = [f["data"].numpy() for f in reader] + finally: + # 不同 torchvision 版本行为不同,尽量显式释放 + if hasattr(reader, "close"): + try: + reader.close() + except Exception: + pass + del reader + + frames = np.array(frames) + frames = frames.transpose(0, 2, 3, 1) + else: + raise NotImplementedError(f"Video backend {video_backend} not implemented") + # resize frames if specified + if resize_size is not None: + frames = [cv2.resize(frame, resize_size) for frame in frames] + frames = np.array(frames) + return frames diff --git a/starVLA/dataloader/lerobot_datasets.py b/starVLA/dataloader/lerobot_datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..04d6a154405e7abb89abda0dc3835a0bd9dea5aa --- /dev/null +++ b/starVLA/dataloader/lerobot_datasets.py @@ -0,0 +1,295 @@ +# Copyright 2025 NVIDIA Corp. and affiliates. All rights reserved. +# Modified by [Fangjing Wang/ SUST University] in [2025]. +# Modification: [return raw data and suport multi-dataset mixture]. +# Modified by [Jinhui YE/ HKUST University] in [2025]. +# Modification: [suport topdowm processing, suport param from config]. + +from pathlib import Path +from typing import Sequence +from omegaconf import OmegaConf + +from starVLA.dataloader.gr00t_lerobot.datasets import LeRobotSingleDataset, LeRobotMixtureDataset +from starVLA.dataloader.gr00t_lerobot.mixtures import DATASET_NAMED_MIXTURES +from starVLA.dataloader.gr00t_lerobot.data_config import ROBOT_TYPE_CONFIG_MAP +from starVLA.dataloader.gr00t_lerobot.embodiment_tags import ROBOT_TYPE_TO_EMBODIMENT_TAG, EmbodimentTag + +def collate_fn(batch): + return batch + +def make_LeRobotSingleDataset( + data_root_dir: Path | str, + data_name: str, + robot_type: str, + delete_pause_frame: bool = False, + data_cfg: dict | None = None, +) -> LeRobotSingleDataset: + """ + param data_root_dir 数据集的根目录。 + param data_name 数据集的名称。 + param robot_type 要使用的机器人类型配置。 + param delete_pause_frame 是否删除暂停帧。 + param data_cfg 数据配置, 包含可选的视频后端设置。 + """ + + # print("########### DATA.lerobot_datasets.make_LeRobotSingleDataset-1") + data_config = ROBOT_TYPE_CONFIG_MAP[robot_type] + modality_config = data_config.modality_config() + transforms = data_config.transform() + dataset_path = data_root_dir / data_name + # print(robot_type) # fourier_gr1_arms_waist + # print(data_config) + """ + + """ + # print(modality_config) + """ + { + 'video': ModalityConfig( + delta_indices=[0], + modality_keys=['video.ego_view'] + ), + 'state': ModalityConfig( + delta_indices=[0], + modality_keys=['state.left_arm', 'state.right_arm', 'state.left_hand', 'state.right_hand', 'state.waist'] + ), + 'action': ModalityConfig( + delta_indices=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], + modality_keys=['action.left_arm', 'action.right_arm', 'action.left_hand', 'action.right_hand', 'action.waist'] + ), + 'language': ModalityConfig( + delta_indices=[0], + modality_keys=['annotation.human.coarse_action'] + ) + } + """ + # print(transforms) + """ + apply_to=[] + training=True + transforms=[ + StateActionToTensor( + apply_to=['state.left_arm', 'state.right_arm', 'state.left_hand', 'state.right_hand', 'state.waist'], + training=True, + input_dtypes={}, + output_dtypes={} + ), + StateActionTransform( + apply_to=['state.left_arm', 'state.right_arm', 'state.left_hand', 'state.right_hand', 'state.waist'], + training=True, + normalization_modes={ + 'state.left_arm': 'min_max', + 'state.right_arm': 'min_max', + 'state.left_hand': 'min_max', + 'state.right_hand': 'min_max', + 'state.waist': 'min_max' + }, + target_rotations={}, + normalization_statistics={}, + modality_metadata={} + ), + StateActionToTensor( + apply_to=['action.left_arm', 'action.right_arm', 'action.left_hand', 'action.right_hand', 'action.waist'], + training=True, + input_dtypes={}, + output_dtypes={} + ), + StateActionTransform( + apply_to=['action.left_arm', 'action.right_arm', 'action.left_hand', 'action.right_hand', 'action.waist'], + training=True, + normalization_modes={ + 'action.left_arm': 'min_max', + 'action.right_arm': 'min_max', + 'action.left_hand': 'min_max', + 'action.right_hand': 'min_max', + 'action.waist': 'min_max' + }, + target_rotations={}, + normalization_statistics={}, + modality_metadata={} + ), + GR00TTransform( + apply_to=[], + training=True, + embodiment_tag_mapping={ + 'new_embodiment': 31, + 'oxe_droid': 17, + 'oxe_bridge': 18, + 'oxe_rt1': 19, + 'agibot_genie1': 26, + 'gr1': 24, + 'franka': 25, + 'action_net': 27, + 'agibot_beta': 28, + 'egodex': 29, + 'nvwa_f': 30, + 'robotwin': 32 + }, + language_dropout_prob=0.0, + default_instruction='Perform the default behavior.', + max_state_dim=64, + max_action_dim=32, + state_horizon=1, + action_horizon=16, + max_length=512, + embodiment_tag=None, + extra_suffix_to_canonical={} + ) + ] + """ + # print(dataset_path) + """ + /mnt/workspace/datasets/PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PnPBottleToCabinetClose_ee + """ + + if robot_type not in ROBOT_TYPE_TO_EMBODIMENT_TAG: + print(f"Warning: Robot type {robot_type} not found in ROBOT_TYPE_TO_EMBODIMENT_TAG, using {EmbodimentTag.NEW_EMBODIMENT} as default") + embodiment_tag = EmbodimentTag.NEW_EMBODIMENT + else: + embodiment_tag = ROBOT_TYPE_TO_EMBODIMENT_TAG[robot_type] + + video_backend = data_cfg.get("video_backend", "decord") if data_cfg else "decord" + dataset = LeRobotSingleDataset( + dataset_path=dataset_path, + modality_configs=modality_config, + transforms=transforms, + embodiment_tag=embodiment_tag, + video_backend=video_backend, # decord is more efficiency | torchvision_av for video.av1 + delete_pause_frame=delete_pause_frame, + data_cfg=data_cfg, + ) + # print("########### DATA.lerobot_datasets.make_LeRobotSingleDataset-2") + return dataset + +def get_vla_dataset( + data_cfg: dict, + mode: str = "train", + balance_dataset_weights: bool = True, + balance_trajectory_weights: bool = False, + seed: int = 42, + **kwargs: dict, +) -> LeRobotMixtureDataset: + # print("########### DATA.lerobot_datasets.get_vla_dataset-1") + data_root_dir = data_cfg.data_root_dir + data_mix = data_cfg.data_mix + delete_pause_frame = data_cfg.get("delete_pause_frame", False) + mixture_spec = DATASET_NAMED_MIXTURES[data_mix] + # print(data_cfg.data_root_dir) # /mnt/workspace/datasets/ + # print(data_cfg.data_mix) # robocasa_teleop_ee + # print(delete_pause_frame) # False + # print(data_mix) # robocasa_teleop_ee + # print(mixture_spec) + """ + [ + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PnPBottleToCabinetClose_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PnPCanToDrawerClose_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PnPCupToDrawerClose_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PnPMilkToMicrowaveClose_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PnPPotatoToMicrowaveClose_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PnPWineToCabinetClose_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromCuttingboardToBasketSplitA_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromCuttingboardToCardboardboxSplitA_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromCuttingboardToPanSplitA_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromCuttingboardToPotSplitA_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromCuttingboardToTieredbasketSplitA_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlacematToBasketSplitA_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlacematToBowlSplitA_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlacematToPlateSplitA_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlacematToTieredshelfSplitA_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlateToBowlSplitA_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlateToCardboardboxSplitA_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlateToPanSplitA_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromPlateToPlateSplitA_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromTrayToCardboardboxSplitA_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromTrayToPlateSplitA_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromTrayToPotSplitA_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromTrayToTieredbasketSplitA_ee', 1.0, 'fourier_gr1_arms_waist'), + ('PhysicalAI-Robotics-GR00T-Teleop-Sim/LeRobot_eepose/gr1_unified.PosttrainPnPNovelFromTrayToTieredshelfSplitA_ee', 1.0, 'fourier_gr1_arms_waist') + ] + """ + + included_datasets, filtered_mixture_spec = set(), [] + for d_name, d_weight, robot_type in mixture_spec: + dataset_key = (d_name, robot_type) + if dataset_key in included_datasets: + print(f"Skipping Duplicate Dataset: `{(d_name, d_weight, robot_type)}`") + continue + included_datasets.add(dataset_key) + filtered_mixture_spec.append((d_name, d_weight, robot_type)) + # print(len(included_datasets)) # 24 + # print(len(filtered_mixture_spec)) # 24 + + dataset_mixture = [] + for d_name, d_weight, robot_type in filtered_mixture_spec: + single_dataset = make_LeRobotSingleDataset( + Path(data_root_dir), + d_name, + robot_type, + delete_pause_frame=delete_pause_frame, + data_cfg=data_cfg + ) + # print(type(single_dataset)) # + dataset_mixture.append((single_dataset, d_weight)) + + dataset = LeRobotMixtureDataset( + dataset_mixture, + mode=mode, + balance_dataset_weights=balance_dataset_weights, + balance_trajectory_weights=balance_trajectory_weights, + seed=seed, + data_cfg=data_cfg, + **kwargs, + ) + # print(mode) # train + # print(balance_dataset_weights) # True + # print(balance_trajectory_weights) # False + # print("########### DATA.lerobot_datasets.get_vla_dataset-2") + return dataset + + + +if __name__ == "__main__": + + # import debugpy + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("--config_yaml", type=str, default="./examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml", help="Path to YAML config") + args, clipargs = parser.parse_known_args() + + # debugpy.listen(("0.0.0.0", 10092)) + # print("🔍 Rank 0 waiting for debugger attach on port 10092...") + # debugpy.wait_for_client() + # args.config_yaml = "./examples/Suqian_agibot/train_files/starvla_cotrain_robocasa_gr1.yaml" + cfg = OmegaConf.load(args.config_yaml) + cfg.datasets.vla_data.data_mix = "sq_egodex-f_agi_beta" + vla_dataset_cfg = cfg.datasets.vla_data + # cfg.datasets.vla_data.include_state = True + vla_dataset_cfg.task_id = 1 + for task_id in ["all"]: + vla_dataset_cfg.task_id = task_id + print(f"Testing Task ID: {task_id}") + dataset = get_vla_dataset(data_cfg=vla_dataset_cfg) + # dataset + from torch.utils.data import DataLoader + train_dataloader = DataLoader( + dataset, + batch_size=2, + num_workers=1, # For Debug + collate_fn=collate_fn, + ) + + cfg.output_dir = "./output/debug" + output_dir = Path(cfg.output_dir) + dataset.save_dataset_statistics(output_dir / "dataset_statistics.json") + + from tqdm import tqdm + count = 0 + for batch in tqdm(train_dataloader, desc="Processing Batches"): + # print(batch[0].keys()) + action = batch[0]['action'] + print('action', action[0]) + print('action_mask', batch[0]['action_mask'][0]) + # print(1) + if count > 100: + break + count += 1 + pass \ No newline at end of file diff --git a/starVLA/dataloader/qwenvl_llavajson/qwen_data_config.py b/starVLA/dataloader/qwenvl_llavajson/qwen_data_config.py new file mode 100644 index 0000000000000000000000000000000000000000..cec229f47d0bb07820b218b09f482058268c7fcf --- /dev/null +++ b/starVLA/dataloader/qwenvl_llavajson/qwen_data_config.py @@ -0,0 +1,121 @@ +import re + +from pathlib import Path + +# You can add multimodal datasets here and register a short nickname to ${data_dict}. +# The data format should follow the general multimodal VLM format, for example: +# https://github.com/QwenLM/Qwen2.5-VL/blob/main/qwen-vl-finetune/README.md + +json_root = f"/mnt/workspace/users/chidafeng/jsons" +# json_root = f"/mnt/workspace/datasets/Cambrian-10M/jsons" +image_root = f"/mnt/workspace/datasets" + +############# VLM Pretrain ############# +CAMBRAIN_300K = { + "annotation_path": f"/mnt/workspace/users/chidafeng/jsons/Cambrian300k_withsystemprompt.jsonl", + "data_path": f"{image_root}/Cambrian-10M/", +} + +REFSPATIAL_2D_100K = { + "annotation_path": f"/mnt/workspace/users/chidafeng/jsons/refspatial/refspatial_2d_100k.json", + "data_path": f"{image_root}/RefSpatial/2D/image/", +} + +REFSPATIAL_3D_150K = { + "annotation_path": f"/mnt/workspace/users/chidafeng/jsons/refspatial/refspatial_3d_150k.json", + "data_path": f"{image_root}/RefSpatial/3D/image/", +} + +REFSPATIAL_3D_VISUAL_50K = { + "annotation_path": f"/mnt/workspace/users/chidafeng/jsons/refspatial/refspatial_3d_visual_50k.json", + "data_path": f"{image_root}/RefSpatial/3D/image_visual_choice/", +} + +ROBOVQA_300K = { + "annotation_path": f"/mnt/workspace/users/chidafeng/jsons/robovqa_300k.json", + "data_path": f"/mnt/workspace/users/chidafeng/datasets/robovqa/", +} + +GAL_SUBTASK_110K = { + "annotation_path": f"/mnt/workspace/users/chidafeng/datasets/Galaxea_subtask/llava_jsons/galaxea_subtask_110k.json", + "data_path": f"/mnt/workspace/users/chidafeng/datasets/Galaxea_subtask", +} + +AGIBOT_SUBTASK = { + "annotation_path": "/mnt/workspace1/datasets/Agibot-Beta-Transformation/Subtask_QA/all_data.jsonl", + "data_path": "/mnt/workspace1/datasets/Agibot-Beta-Transformation/Subtask_QA/images" +} + +SQ_SUBTASK = { + "annotation_path": "/mnt/workspace1/Suqian_subtask_qa/all_data.jsonl", + "data_path": "/mnt/workspace1/Suqian_subtask_qa/images" +} + +############# VLA Pretrain ############# +CAMBRAIN_300K_VLAPT = { + "annotation_path": f"/mnt/workspace/users/chidafeng/jsons/Cambrian300k_withsystemprompt_vlapretrain.jsonl", + "data_path": f"{image_root}/Cambrian-10M/", +} + +REFSPATIAL_2D_100K_VLAPT = { + "annotation_path": f"/mnt/workspace/users/chidafeng/jsons/refspatial/refspatial_2d_100k_vlapretrain.json", + "data_path": f"{image_root}/RefSpatial/2D/image/", +} + +REFSPATIAL_3D_150K_VLAPT = { + "annotation_path": f"/mnt/workspace/users/chidafeng/jsons/refspatial/refspatial_3d_150k_vlapretrain.json", + "data_path": f"{image_root}/RefSpatial/3D/image/", +} + +REFSPATIAL_3D_VISUAL_50K_VLAPT = { + "annotation_path": f"/mnt/workspace/users/chidafeng/jsons/refspatial/refspatial_3d_visual_50k_vlapretrain.json", + "data_path": f"{image_root}/RefSpatial/3D/image_visual_choice/", +} + +ROBOVQA_300K_VLAPT = { + "annotation_path": f"/mnt/workspace/users/chidafeng/jsons/robovqa_300k_vlapretrain.json", + "data_path": f"/mnt/workspace/users/chidafeng/datasets/robovqa/", +} + +data_dict = { + "cambrain_300k": CAMBRAIN_300K, + "refspatial_2d_100k": REFSPATIAL_2D_100K, + "refspatial_3d_150k": REFSPATIAL_3D_150K, + "refspatial_3d_visual_50k": REFSPATIAL_3D_VISUAL_50K, + "robovqa_300k": ROBOVQA_300K, + "gal_subtask_110k": GAL_SUBTASK_110K, + "cambrain_300k_vlapt": CAMBRAIN_300K_VLAPT, + "refspatial_2d_100k_vlapt": REFSPATIAL_2D_100K_VLAPT, + "refspatial_3d_150k_vlapt": REFSPATIAL_3D_150K_VLAPT, + "refspatial_3d_visual_50k_vlapt": REFSPATIAL_3D_VISUAL_50K_VLAPT, + "robovqa_300k_vlapt": ROBOVQA_300K_VLAPT, + "agibot_subtask": AGIBOT_SUBTASK, + "sq_subtask": SQ_SUBTASK, +} + + +def parse_sampling_rate(dataset_name): + match = re.search(r"%(\d+)$", dataset_name) + if match: + return int(match.group(1)) / 100.0 + return 1.0 + + +def data_list(dataset_names): + if dataset_names == ["all"]: + dataset_names = list(data_dict.keys()) + config_list = [] + for dataset_name in dataset_names: + sampling_rate = parse_sampling_rate(dataset_name) + dataset_name = re.sub(r"%(\d+)$", "", dataset_name) + if dataset_name in data_dict.keys(): + config = data_dict[dataset_name].copy() + config["sampling_rate"] = sampling_rate + config_list.append(config) + else: + raise ValueError(f"do not find {dataset_name}") + return config_list + + +if __name__ == "__main__": + print(data_list) diff --git a/starVLA/dataloader/qwenvl_llavajson/rope2d.py b/starVLA/dataloader/qwenvl_llavajson/rope2d.py new file mode 100644 index 0000000000000000000000000000000000000000..ab4da85174dcc7da97bc27264858965628773296 --- /dev/null +++ b/starVLA/dataloader/qwenvl_llavajson/rope2d.py @@ -0,0 +1,351 @@ +import os +import copy +import json +import random +import logging +import re +import time +import math +import ast +from dataclasses import dataclass, field +from typing import Dict, Optional, Sequence, List, Tuple +from io import BytesIO +import base64 + +import numpy as np +import torch +from torch.utils.data import Dataset +from PIL import Image +from decord import VideoReader +import transformers + + +def get_rope_index_25( + spatial_merge_size: Optional[int] = 2, + input_ids: Optional[torch.LongTensor] = None, + image_grid_thw: Optional[torch.LongTensor] = None, + video_grid_thw: Optional[torch.LongTensor] = None, + second_per_grid_ts: Optional[torch.Tensor] = None, + attention_mask: Optional[torch.Tensor] = None, +) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Calculate the 3D rope index based on image and video's temporal, height and width in LLM. + + Explanation: + Each embedding sequence contains vision embedding and text embedding or just contains text embedding. + + For pure text embedding sequence, the rotary position embedding has no difference with modern LLMs. + Examples: + input_ids: [T T T T T], here T is for text. + temporal position_ids: [0, 1, 2, 3, 4] + height position_ids: [0, 1, 2, 3, 4] + width position_ids: [0, 1, 2, 3, 4] + + For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part + and 1D rotary position embedding for text part. + Examples: + Temporal (Time): 3 patches, representing different segments of the video in time. + Height: 2 patches, dividing each frame vertically. + Width: 2 patches, dividing each frame horizontally. + We also have some important parameters: + fps (Frames Per Second): The video's frame rate, set to 1. This means one frame is processed each second. + 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. + temporal_patch_size: The number of frames that compose one temporal patch. Here, it's 2 frames. + 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. + input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision. + vision temporal position_ids: [0, 0, 0, 0, 50, 50, 50, 50, 100, 100, 100, 100] + vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1] + vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1] + text temporal position_ids: [101, 102, 103, 104, 105] + text height position_ids: [101, 102, 103, 104, 105] + text width position_ids: [101, 102, 103, 104, 105] + Here we calculate the text start position_ids as the max vision position_ids plus 1. + + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide + it. + image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*): + The temporal, height and width of feature shape of each image in LLM. + video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*): + The temporal, height and width of feature shape of each video in LLM. + second_per_grid_ts (`torch.Tensor` of shape `(num_videos)`, *optional*): + The time interval (in seconds) for each grid along the temporal dimension in the 3D position IDs. + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + Returns: + position_ids (`torch.LongTensor` of shape `(3, batch_size, sequence_length)`) + mrope_position_deltas (`torch.Tensor` of shape `(batch_size)`) + """ + image_token_id = 151655 + video_token_id = 151656 + vision_start_token_id = 151652 + mrope_position_deltas = [] + if input_ids is not None and (image_grid_thw is not None or video_grid_thw is not None): + total_input_ids = input_ids + if attention_mask is None: + attention_mask = torch.ones_like(total_input_ids) + position_ids = torch.ones( + 3, + input_ids.shape[0], + input_ids.shape[1], + dtype=input_ids.dtype, + device=input_ids.device, + ) + image_index, video_index = 0, 0 + attention_mask = attention_mask.to(total_input_ids.device) + for i, input_ids in enumerate(total_input_ids): + input_ids = input_ids[attention_mask[i] == 1] + image_nums, video_nums = 0, 0 + vision_start_indices = torch.argwhere(input_ids == vision_start_token_id).squeeze(1) + vision_tokens = input_ids[vision_start_indices + 1] + image_nums = (vision_tokens == image_token_id).sum() + video_nums = (vision_tokens == video_token_id).sum() + input_tokens = input_ids.tolist() + llm_pos_ids_list: list = [] + st = 0 + remain_images, remain_videos = image_nums, video_nums + for _ in range(image_nums + video_nums): + if image_token_id in input_tokens and remain_images > 0: + ed_image = input_tokens.index(image_token_id, st) + else: + ed_image = len(input_tokens) + 1 + if video_token_id in input_tokens and remain_videos > 0: + ed_video = input_tokens.index(video_token_id, st) + else: + ed_video = len(input_tokens) + 1 + if ed_image < ed_video: + t, h, w = ( + image_grid_thw[image_index][0], + image_grid_thw[image_index][1], + image_grid_thw[image_index][2], + ) + second_per_grid_t = 0 + image_index += 1 + remain_images -= 1 + ed = ed_image + + else: + t, h, w = ( + video_grid_thw[video_index][0], + video_grid_thw[video_index][1], + video_grid_thw[video_index][2], + ) + if second_per_grid_ts is not None: + second_per_grid_t = second_per_grid_ts[video_index] + else: + second_per_grid_t = 1.0 + video_index += 1 + remain_videos -= 1 + ed = ed_video + llm_grid_t, llm_grid_h, llm_grid_w = ( + t.item(), + h.item() // spatial_merge_size, + w.item() // spatial_merge_size, + ) + text_len = ed - st + + st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0 + llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx) + + range_tensor = torch.arange(llm_grid_t).view(-1, 1) + expanded_range = range_tensor.expand(-1, llm_grid_h * llm_grid_w) + + time_tensor = expanded_range * second_per_grid_t * 2 + + time_tensor_long = time_tensor.long() + t_index = time_tensor_long.flatten() + + h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten() + w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten() + llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + text_len + st_idx) + st = ed + llm_grid_t * llm_grid_h * llm_grid_w + + if st < len(input_tokens): + st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0 + text_len = len(input_tokens) - st + llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx) + + llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1) + position_ids[..., i, attention_mask[i] == 1] = llm_positions.to(position_ids.device) + mrope_position_deltas.append(llm_positions.max() + 1 - len(total_input_ids[i])) + mrope_position_deltas = torch.tensor(mrope_position_deltas, device=input_ids.device).unsqueeze(1) + return position_ids, mrope_position_deltas + else: + if attention_mask is not None: + position_ids = attention_mask.long().cumsum(-1) - 1 + position_ids.masked_fill_(attention_mask == 0, 1) + position_ids = position_ids.unsqueeze(0).expand(3, -1, -1).to(attention_mask.device) + max_position_ids = position_ids.max(0, keepdim=False)[0].max(-1, keepdim=True)[0] + mrope_position_deltas = max_position_ids + 1 - attention_mask.shape[-1] + else: + position_ids = ( + torch.arange(input_ids.shape[1], device=input_ids.device) + .view(1, 1, -1) + .expand(3, input_ids.shape[0], -1) + ) + mrope_position_deltas = torch.zeros( + [input_ids.shape[0], 1], + device=input_ids.device, + dtype=input_ids.dtype, + ) + + return position_ids, mrope_position_deltas + + +def get_rope_index_2( + spatial_merge_size: Optional[int] = 2, + input_ids: Optional[torch.LongTensor] = None, + image_grid_thw: Optional[torch.LongTensor] = None, + video_grid_thw: Optional[torch.LongTensor] = None, + second_per_grid_ts: Optional[torch.Tensor] = None, + attention_mask: Optional[torch.Tensor] = None, +) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Calculate the 3D rope index based on image and video's temporal, height and width in LLM. + + Explanation: + Each embedding sequence contains vision embedding and text embedding or just contains text embedding. + + For pure text embedding sequence, the rotary position embedding has no difference with mordern LLMs. + Examples: + input_ids: [T T T T T], here T is for text. + temporal position_ids: [0, 1, 2, 3, 4] + height position_ids: [0, 1, 2, 3, 4] + width position_ids: [0, 1, 2, 3, 4] + + For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part + and 1D rotary position embeddin for text part. + Examples: + Assume we have a video input with 3 temporal patches, 2 height patches and 2 width patches. + input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision. + vision temporal position_ids: [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2] + vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1] + vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1] + text temporal position_ids: [3, 4, 5, 6, 7] + text height position_ids: [3, 4, 5, 6, 7] + text width position_ids: [3, 4, 5, 6, 7] + Here we calculate the text start position_ids as the max vision position_ids plus 1. + + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide + it. + image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*): + The temporal, height and width of feature shape of each image in LLM. + video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*): + The temporal, height and width of feature shape of each video in LLM. + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + Returns: + position_ids (`torch.LongTensor` of shape `(3, batch_size, sequence_length)`) + mrope_position_deltas (`torch.Tensor` of shape `(batch_size)`) + """ + image_token_id = 151655 + video_token_id = 151656 + vision_start_token_id = 151652 + mrope_position_deltas = [] + if input_ids is not None and (image_grid_thw is not None or video_grid_thw is not None): + total_input_ids = input_ids + if attention_mask is None: + attention_mask = torch.ones_like(total_input_ids) + position_ids = torch.ones( + 3, + input_ids.shape[0], + input_ids.shape[1], + dtype=input_ids.dtype, + device=input_ids.device, + ) + image_index, video_index = 0, 0 + for i, input_ids in enumerate(total_input_ids): + input_ids = input_ids[attention_mask[i] == 1] + image_nums, video_nums = 0, 0 + vision_start_indices = torch.argwhere(input_ids == vision_start_token_id).squeeze(1) + vision_tokens = input_ids[vision_start_indices + 1] + image_nums = (vision_tokens == image_token_id).sum() + video_nums = (vision_tokens == video_token_id).sum() + input_tokens = input_ids.tolist() + llm_pos_ids_list: list = [] + st = 0 + remain_images, remain_videos = image_nums, video_nums + for _ in range(image_nums + video_nums): + if image_token_id in input_tokens and remain_images > 0: + ed_image = input_tokens.index(image_token_id, st) + else: + ed_image = len(input_tokens) + 1 + if video_token_id in input_tokens and remain_videos > 0: + ed_video = input_tokens.index(video_token_id, st) + else: + ed_video = len(input_tokens) + 1 + if ed_image < ed_video: + t, h, w = ( + image_grid_thw[image_index][0], + image_grid_thw[image_index][1], + image_grid_thw[image_index][2], + ) + image_index += 1 + remain_images -= 1 + ed = ed_image + else: + t, h, w = ( + video_grid_thw[video_index][0], + video_grid_thw[video_index][1], + video_grid_thw[video_index][2], + ) + video_index += 1 + remain_videos -= 1 + ed = ed_video + llm_grid_t, llm_grid_h, llm_grid_w = ( + t.item(), + h.item() // spatial_merge_size, + w.item() // spatial_merge_size, + ) + text_len = ed - st + + st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0 + llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx) + + t_index = torch.arange(llm_grid_t).view(-1, 1).expand(-1, llm_grid_h * llm_grid_w).flatten() + h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten() + w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten() + llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + text_len + st_idx) + st = ed + llm_grid_t * llm_grid_h * llm_grid_w + + if st < len(input_tokens): + st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0 + text_len = len(input_tokens) - st + llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx) + + llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1) + position_ids[..., i, attention_mask[i] == 1] = llm_positions.to(position_ids.device) + mrope_position_deltas.append(llm_positions.max() + 1 - len(total_input_ids[i])) + mrope_position_deltas = torch.tensor(mrope_position_deltas, device=input_ids.device).unsqueeze(1) + return position_ids, mrope_position_deltas + else: + if attention_mask is not None: + position_ids = attention_mask.long().cumsum(-1) - 1 + position_ids.masked_fill_(attention_mask == 0, 1) + position_ids = position_ids.unsqueeze(0).expand(3, -1, -1).to(attention_mask.device) + max_position_ids = position_ids.max(0, keepdim=False)[0].max(-1, keepdim=True)[0] + mrope_position_deltas = max_position_ids + 1 - attention_mask.shape[-1] + else: + position_ids = ( + torch.arange(input_ids.shape[1], device=input_ids.device) + .view(1, 1, -1) + .expand(3, input_ids.shape[0], -1) + ) + mrope_position_deltas = torch.zeros( + [input_ids.shape[0], 1], + device=input_ids.device, + dtype=input_ids.dtype, + ) + + return position_ids, mrope_position_deltas diff --git a/starVLA/dataloader/vlm_datasets.py b/starVLA/dataloader/vlm_datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..652a27d0b18f1efceea0b90645caf2e08394d48e --- /dev/null +++ b/starVLA/dataloader/vlm_datasets.py @@ -0,0 +1,946 @@ +import os +import copy +import json +import random +import logging +import re +import time +import math +import itertools +import ast +from dataclasses import dataclass +from typing import Dict, Optional, Sequence, List, Tuple +from io import BytesIO +import base64 +from collections.abc import Sequence +from types import SimpleNamespace +import numpy as np +import torch +from torch.utils.data import Dataset +from PIL import Image +from PIL import ImageDraw +from PIL import ImageFont +from decord import VideoReader +import transformers +from omegaconf import OmegaConf +from starVLA.dataloader.qwenvl_llavajson.qwen_data_config import data_list +from starVLA.dataloader.qwenvl_llavajson.rope2d import get_rope_index_25, get_rope_index_2 + +IGNORE_INDEX = -100 +IMAGE_TOKEN_INDEX = 151655 +VIDEO_TOKEN_INDEX = 151656 +DEFAULT_IMAGE_TOKEN = "\n" +DEFAULT_VIDEO_TOKEN = "\n" + +local_rank = None + + +def rank0_print(*args): + if local_rank == 0: + print(*args) + + +def read_jsonl(path): + with open(path, "r") as f: + return [json.loads(line) for line in f] + + +def _extract_input_ids(encoded): + if isinstance(encoded, dict): + encoded = encoded["input_ids"] + elif hasattr(encoded, "input_ids"): + encoded = encoded.input_ids + + if isinstance(encoded, torch.Tensor): + encoded = encoded.tolist() + elif hasattr(encoded, "tolist") and not isinstance(encoded, list): + encoded = encoded.tolist() + + if len(encoded) > 0 and isinstance(encoded[0], list): + if len(encoded) != 1: + raise ValueError(f"Expected a single sequence from chat template, but got batch size {len(encoded)}.") + encoded = encoded[0] + + return list(encoded) + + +def preprocess_qwen_2_visual( + sources, + tokenizer: transformers.PreTrainedTokenizer, + grid_thw: Optional[List] = None, + visual_type: str = "image", +) -> Dict: + roles = {"human": "user", "gpt": "assistant"} + system_message = "You are a helpful assistant." + if visual_type not in ["image", "video"]: + raise ValueError("visual_type must be either 'image' or 'video'") + + tokenizer = copy.deepcopy(tokenizer) + 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 %}" + tokenizer.chat_template = chat_template + + visual_replicate_index = 0 + input_ids, targets = [], [] + + for i, source in enumerate(sources): + try: + if roles[source[0]["from"]] != roles["human"]: + source = source[1:] + except: + print(sources) + + input_id, target = [], [] + + system_ids = _extract_input_ids( + tokenizer.apply_chat_template( + [{"role": "system", "content": system_message}], + tokenize=True, + ) + ) + input_id += system_ids + target += [IGNORE_INDEX] * len(system_ids) + + for conv in source: + try: + role = conv["role"] + content = conv["content"] + except: + role = conv["from"] + content = conv["value"] + + role = roles.get(role, role) + if role == "user": + visual_tag = f"<{visual_type}>" + if visual_tag in content: + if grid_thw is None: + raise ValueError(f"Found {visual_tag} in conversation, but no {visual_type} input was provided.") + parts = content.split(visual_tag) + new_parts = [] + for i in range(len(parts) - 1): + if visual_replicate_index >= len(grid_thw): + raise ValueError( + f"Found more {visual_tag} placeholders than provided {visual_type} inputs." + ) + new_parts.append(parts[i]) + replacement = ("<|vision_start|>" + f"<|{visual_type}_pad|>" * grid_thw[visual_replicate_index] + "<|vision_end|>") + new_parts.append(replacement) + visual_replicate_index += 1 + new_parts.append(parts[-1]) + content = "".join(new_parts) + + conv = [{"role": role, "content": content}] + encode_id = _extract_input_ids(tokenizer.apply_chat_template(conv, tokenize=True)) + input_id += encode_id + if role in ["user", "system"]: + target += [IGNORE_INDEX] * len(encode_id) + else: + target_mask = encode_id.copy() + target_mask[:3] = [IGNORE_INDEX] * 3 + target += target_mask + + assert len(input_id) == len(target), f"{len(input_id)} != {len(target)}" + input_ids.append(input_id) + targets.append(target) + + input_ids = torch.tensor(input_ids, dtype=torch.long) + targets = torch.tensor(targets, dtype=torch.long) + + return dict( + input_ids=input_ids, + labels=targets, + ) + + +class LazySupervisedDataset(Dataset): + """Dataset for supervised fine-tuning.""" + + def __init__(self, tokenizer: transformers.PreTrainedTokenizer, data_args): + super(LazySupervisedDataset, self).__init__() + + dataset = data_args.dataset_use.split(",") + dataset_list = data_list(dataset) + rank0_print(f"Loading datasets: {dataset_list}") + self.video_max_total_pixels = getattr(data_args, "video_max_total_pixels", 1664 * 28 * 28) + self.video_min_total_pixels = getattr(data_args, "video_min_total_pixels", 256 * 28 * 28) + self.model_type = data_args.model_type + if data_args.model_type == "qwen2.5vl": + self.get_rope_index = get_rope_index_25 + else: + self.get_rope_index = get_rope_index_2 + + list_data_dict = [] + + for data in dataset_list: + file_format = data["annotation_path"].split(".")[-1] + if file_format == "jsonl": + annotations = read_jsonl(data["annotation_path"]) + else: + annotations = json.load(open(data["annotation_path"], "r")) + sampling_rate = data.get("sampling_rate", 1.0) + if sampling_rate < 1.0: + annotations = random.sample(annotations, int(len(annotations) * sampling_rate)) + print(f"sampling {len(annotations)} examples from dataset {data}") + else: + rank0_print(f"dataset name: {data}") + for ann in annotations: + if data["data_path"] != "": + ann["data_path"] = data["data_path"] + elif "raw_data" in ann.keys(): + ann["data_path"] = ann["raw_data"]["data_root"] + list_data_dict += annotations + + list_data_dict = self.pre_filter_long_case(list_data_dict, max_words=tokenizer.max_len_single_sentence) + random.shuffle(list_data_dict) # Randomly shuffle the data for training + + self.tokenizer = tokenizer + self.list_data_dict = list_data_dict + self.data_args = data_args + + rank0_print(f"Total training samples: {len(self.list_data_dict)}") + rank0_print("Formatting inputs...Skip in lazy mode") + + # self.data_args.image_processor.max_pixels = data_args.max_pixels + # self.data_args.image_processor.min_pixels = data_args.min_pixels + # self.data_args.image_processor.size["longest_edge"] = data_args.max_pixels + # self.data_args.image_processor.size["shortest_edge"] = data_args.min_pixels + + def __len__(self): + return len(self.list_data_dict) + + def pre_filter_long_case(self, list_data_dict, max_words=1024): + """filter out conversations with total words exceeding max_words""" + + def count_total_words(convs): + total = 0 + for entry in convs: + value = entry.get("value", "") + total += len(value.strip().split()) + return total + + return [item for item in list_data_dict if count_total_words(item.get("conversations", [])) <= max_words] + + @property + def lengths(self): + length_list = [] + for sample in self.list_data_dict: + img_tokens = 128 if "image" in sample else 0 + length_list.append(sum(len(conv["value"].split()) for conv in sample["conversations"]) + img_tokens) + return length_list + + @property + def modality_lengths(self): + length_list = [] + for sample in self.list_data_dict: + cur_len = sum(len(conv["value"].split()) for conv in sample["conversations"]) + cur_len = cur_len if ("image" in sample) or ("video" in sample) else -cur_len + length_list.append(cur_len) + return length_list + + @property + def pre_calculated_length(self): + if "num_tokens" in self.list_data_dict[0]: + length_list = [sample["num_tokens"] for sample in self.list_data_dict] + return np.array(length_list) + else: + print("No pre-calculated length available.") + return np.array([1] * len(self.list_data_dict)) + + def process_image_unified(self, image_file): + processor = copy.deepcopy(self.data_args.image_processor) + image = Image.open(image_file).convert("RGB") + # if fix image size? + if getattr(self.data_args, "fix_image_size", None) is not None: + image = image.resize( + self.data_args.fix_image_size, + resample=Image.BICUBIC, + ) + visual_processed = processor.preprocess(image, return_tensors="pt") + image_tensor = visual_processed["pixel_values"] + if isinstance(image_tensor, List): + image_tensor = image_tensor[0] + grid_thw = visual_processed["image_grid_thw"][0] + return image_tensor, grid_thw + + def process_video(self, video_file): + if not os.path.exists(video_file): + print(f"File not exist: {video_file}") + vr = VideoReader(video_file, num_threads=4) + total_frames = len(vr) + avg_fps = vr.get_avg_fps() + video_length = total_frames / avg_fps + interval = getattr(self.data_args, "base_interval", 4) + + num_frames_to_sample = round(video_length / interval) + video_min_frames = getattr(self.data_args, "video_min_frames", 4) + video_max_frames = getattr(self.data_args, "video_max_frames", 8) + + target_frames = min(max(num_frames_to_sample, video_min_frames), video_max_frames) + frame_idx = np.linspace(0, total_frames - 1, target_frames, dtype=int) + frame_idx = np.unique(frame_idx) + video = vr.get_batch(frame_idx).asnumpy() + fps = len(frame_idx) / video_length + processor = copy.deepcopy(self.data_args.image_processor) + self.data_args.video_max_frame_pixels = self.video_max_total_pixels + self.data_args.video_min_frame_pixels = self.video_min_total_pixels + processor.max_pixels = self.data_args.video_max_frame_pixels + processor.min_pixels = self.data_args.video_min_frame_pixels + processor.size["longest_edge"] = processor.max_pixels + processor.size["shortest_edge"] = processor.min_pixels + processor_valid_kwargs = getattr(processor, "valid_kwargs", None) + processor_valid_keys = None + if processor_valid_kwargs is not None: + if isinstance(processor_valid_kwargs, dict): + processor_valid_keys = set(processor_valid_kwargs.keys()) + elif hasattr(processor_valid_kwargs, "__annotations__"): + processor_valid_keys = set(processor_valid_kwargs.__annotations__.keys()) + else: + try: + processor_valid_keys = set(processor_valid_kwargs) + except TypeError: + processor_valid_keys = None + + supports_video_kwarg = processor_valid_keys is None or "video" in processor_valid_keys + supports_videos_kwarg = processor_valid_keys is None or "videos" in processor_valid_keys + + if supports_videos_kwarg: + video_processed = processor.preprocess(images=None, videos=video, return_tensors="pt") + video_tensor = video_processed["pixel_values_videos"] + grid_thw = video_processed["video_grid_thw"][0] + elif supports_video_kwarg: + video_processed = processor.preprocess(images=None, video=video, return_tensors="pt") + video_tensor = video_processed["pixel_values_videos"] + grid_thw = video_processed["video_grid_thw"][0] + else: + video_processed = processor.preprocess(list(video), return_tensors="pt") + video_tensor = video_processed["pixel_values"] + image_grid_thw = video_processed["image_grid_thw"] + if len(image_grid_thw) == 1: + grid_thw = image_grid_thw[0] + else: + grid_thw = image_grid_thw[0].clone() + grid_thw[0] = image_grid_thw[:, 0].sum() + second_per_grid_ts = [self.data_args.image_processor.temporal_patch_size / fps] + return video_tensor, grid_thw, second_per_grid_ts + + def __getitem__(self, i) -> Dict[str, torch.Tensor]: + num_base_retries = 3 + num_final_retries = 30 + + # try the current sample first + for attempt_idx in range(num_base_retries): + try: + sample = self._get_item(i) + sample["_debug_dataset_index"] = i + return sample + except Exception as e: + # sleep 1s in case it is a cloud disk issue + print(f"[Try #{attempt_idx}] Failed to fetch sample {i}. Exception:", e) + time.sleep(1) + + # try other samples, in case it is file corruption issue + for attempt_idx in range(num_base_retries): + try: + next_index = min(i + 1, len(self.list_data_dict) - 1) + # sample_idx = random.choice(range(len(self))) + sample = self._get_item(next_index) + sample["_debug_dataset_index"] = next_index + return sample + except Exception as e: + # no need to sleep + print( + f"[Try other #{attempt_idx}] Failed to fetch sample {next_index}. Exception:", + e, + ) + pass + + try: + sample = self._get_item(i) + sample["_debug_dataset_index"] = i + return sample + except Exception as e: + raise e + + def _get_item(self, i) -> Dict[str, torch.Tensor]: + sources = self.list_data_dict[i] + if isinstance(i, int): + sources = [sources] + assert len(sources) == 1, "Don't know why it is wrapped to a list" # FIXME + video = None + if "image" in sources[0] and len(sources[0]["image"]): + image_folder = self.list_data_dict[i]["data_path"] + image_file = self.list_data_dict[i]["image"] + if isinstance(image_file, List): + if len(image_file) > 1: + image_file = [os.path.join(image_folder, file) for file in image_file] + results = [self.process_image_unified(file) for file in image_file] + image, grid_thw = zip(*results) + else: + image_file = image_file[0] + image_file = os.path.join(image_folder, image_file) + image, grid_thw = self.process_image_unified(image_file) + image = [image] + else: + image_file = os.path.join(image_folder, image_file) + image, grid_thw = self.process_image_unified(image_file) + image = [image] + grid_thw_merged = copy.deepcopy(grid_thw) + if not isinstance(grid_thw, Sequence): + grid_thw_merged = [grid_thw_merged] + grid_thw = [grid_thw] + grid_thw_merged = [merged_thw.prod() // self.data_args.image_processor.merge_size**2 for merged_thw in grid_thw_merged] + sources = copy.deepcopy([e["conversations"] for e in sources]) + data_dict = preprocess_qwen_2_visual(sources, self.tokenizer, grid_thw=grid_thw_merged, visual_type="image") + position_ids, _ = self.get_rope_index( + self.data_args.image_processor.merge_size, + data_dict["input_ids"], + torch.stack(grid_thw, dim=0), # (1,16,16) + ) + elif "video" in sources[0] and len(sources[0]["video"]): + video_file = self.list_data_dict[i]["video"] + video_folder = self.list_data_dict[i]["data_path"] + if isinstance(video_file, List): + if len(video_file) > 1: + video_file = [os.path.join(video_folder, file) for file in video_file] + results = [self.process_video(file) for file in video_file] + video, grid_thw, second_per_grid_ts = zip(*results) + second_per_grid_ts = list(itertools.chain.from_iterable(second_per_grid_ts)) + else: + video_file = video_file[0] + video_file = os.path.join(video_folder, video_file) + video, grid_thw, second_per_grid_ts = self.process_video(video_file) + video = [video] + else: + video_file = os.path.join(video_folder, video_file) + video, grid_thw, second_per_grid_ts = self.process_video(video_file) + video = [video] + grid_thw_merged = copy.deepcopy(grid_thw) + if not isinstance(grid_thw, Sequence): + grid_thw_merged = [grid_thw_merged] + grid_thw = [grid_thw] + grid_thw_merged = [merged_thw.prod() // self.data_args.image_processor.merge_size**2 for merged_thw in grid_thw_merged] + sources = copy.deepcopy([e["conversations"] for e in sources]) + data_dict = preprocess_qwen_2_visual(sources, self.tokenizer, grid_thw=grid_thw_merged, visual_type="video") + position_ids, _ = self.get_rope_index( + self.data_args.image_processor.merge_size, + data_dict["input_ids"], + video_grid_thw=torch.stack(grid_thw, dim=0), + second_per_grid_ts=second_per_grid_ts, + ) + else: + grid_thw_merged = None + sources = copy.deepcopy([e["conversations"] for e in sources]) + data_dict = preprocess_qwen_2_visual(sources, self.tokenizer, grid_thw=grid_thw_merged) + position_ids = torch.arange(0, data_dict["input_ids"].size(1)).view(1, -1).unsqueeze(0).expand(3, -1, -1) + + if isinstance(i, int): + data_dict = dict( + input_ids=data_dict["input_ids"][0], + labels=data_dict["labels"][0], + position_ids=position_ids, + ) + if "image" in self.list_data_dict[i]: + data_dict["pixel_values"] = image + data_dict["image_grid_thw"] = grid_thw + # video exist in the data + elif "video" in self.list_data_dict[i]: + data_dict["pixel_values_videos"] = video + data_dict["video_grid_thw"] = grid_thw + + max_len = self.tokenizer.max_len_single_sentence + if data_dict["input_ids"].shape[0] > max_len: + truncated_input_ids = data_dict["input_ids"][:max_len] + image_tokens_before = int((data_dict["input_ids"] == IMAGE_TOKEN_INDEX).sum().item()) + image_tokens_after = int((truncated_input_ids == IMAGE_TOKEN_INDEX).sum().item()) + video_tokens_before = int((data_dict["input_ids"] == VIDEO_TOKEN_INDEX).sum().item()) + video_tokens_after = int((truncated_input_ids == VIDEO_TOKEN_INDEX).sum().item()) + + if image_tokens_before != image_tokens_after or video_tokens_before != video_tokens_after: + raw_sample = self.list_data_dict[i] + debug_message = _format_raw_sample_debug(raw_sample) + raise ValueError( + "Sequence truncation would drop visual placeholder tokens: " + f"image {image_tokens_before}->{image_tokens_after}, " + f"video {video_tokens_before}->{video_tokens_after}, " + f"max_len={max_len}.\n" + "Raw sample debug:\n" + f"{debug_message}" + ) + + data_dict["input_ids"] = data_dict["input_ids"][:max_len] + data_dict["labels"] = data_dict["labels"][:max_len] + data_dict["position_ids"] = position_ids[:, :, :max_len] + + return data_dict + + +def pad_and_cat(tensor_list): + max_length = max(tensor.shape[2] for tensor in tensor_list) + + padded_tensors = [] + for tensor in tensor_list: + pad_length = max_length - tensor.shape[2] + padded_tensor = torch.nn.functional.pad(tensor, (0, pad_length), "constant", 1) + padded_tensors.append(padded_tensor) + + stacked_tensor = torch.cat(padded_tensors, dim=1) + + return stacked_tensor + + +@dataclass +class DataCollatorForSupervisedDataset(object): + """Collate examples for supervised fine-tuning.""" + + tokenizer: transformers.PreTrainedTokenizer + + def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]: + input_ids, labels, position_ids = tuple( + [instance[key] for instance in instances] for key in ("input_ids", "labels", "position_ids")) + input_ids = torch.nn.utils.rnn.pad_sequence( + input_ids, + batch_first=True, + padding_value=self.tokenizer.pad_token_id, + padding_side=self.tokenizer.padding_side, + ) + labels = torch.nn.utils.rnn.pad_sequence(labels, + batch_first=True, + padding_value=IGNORE_INDEX, + padding_side=self.tokenizer.padding_side) + position_ids = pad_and_cat(position_ids) + + input_ids = input_ids[:, :self.tokenizer.model_max_length] + labels = labels[:, :self.tokenizer.model_max_length] + position_ids = position_ids[..., :self.tokenizer.model_max_length] # 3,bs,length + + batch = dict( + input_ids=input_ids, + labels=labels, + attention_mask=input_ids.ne(self.tokenizer.pad_token_id), + ) + images = list(itertools.chain(*(instance["pixel_values"] for instance in instances if "pixel_values" in instance))) + videos = list(itertools.chain(*(instance["pixel_values_videos"] for instance in instances if "pixel_values_videos" in instance))) + if len(images) != 0: + concat_images = torch.cat([image for image in images], dim=0) + grid_thw = list(itertools.chain(*(instance["image_grid_thw"] for instance in instances if "image_grid_thw" in instance))) + grid_thw = torch.stack(grid_thw, dim=0) + else: + concat_images = None + grid_thw = None + + if len(videos) != 0: + concat_videos = torch.cat([video for video in videos], dim=0) + video_grid_thw = list(itertools.chain(*(instance["video_grid_thw"] for instance in instances if "video_grid_thw" in instance))) + video_grid_thw = torch.stack(video_grid_thw, dim=0) + else: + concat_videos = None + video_grid_thw = None + + batch["pixel_values"] = concat_images + batch["image_grid_thw"] = grid_thw + batch["pixel_values_videos"] = concat_videos + batch["video_grid_thw"] = video_grid_thw + batch["position_ids"] = position_ids + batch["_debug_dataset_index"] = [instance.get("_debug_dataset_index") for instance in instances] + return batch + + +@dataclass +class FlattenedDataCollatorForSupervisedDataset(DataCollatorForSupervisedDataset): + """Collate examples into packed sequence with multi-modal support.""" + + tokenizer: transformers.PreTrainedTokenizer + + def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]: + input_ids, labels, position_ids = tuple( + [instance[key] for instance in instances] for key in ("input_ids", "labels", "position_ids")) + + seq_lens = torch.tensor([0] + [len(seq) for seq in input_ids], dtype=torch.int32) + cumsum_seq_lens = torch.cumsum(seq_lens, dim=0, dtype=torch.int32) + input_ids = torch.cat(input_ids, dim=0) + labels = torch.cat(labels, dim=0) + position_ids = torch.cat(position_ids, dim=2) + + batch = dict( + input_ids=input_ids.unsqueeze(0), + labels=labels.unsqueeze(0), + attention_mask=cumsum_seq_lens, + position_ids=position_ids, + ) + images = list(itertools.chain(*(instance["pixel_values"] for instance in instances if "pixel_values" in instance))) + videos = list(itertools.chain(*(instance["pixel_values_videos"] for instance in instances if "pixel_values_videos" in instance))) + if len(images) != 0: + concat_images = torch.cat([image for image in images], dim=0) + grid_thw = list(itertools.chain(*(instance["image_grid_thw"] for instance in instances if "image_grid_thw" in instance))) + grid_thw = torch.stack(grid_thw, dim=0) + else: + concat_images = None + grid_thw = None + + if len(videos) != 0: + concat_videos = torch.cat([video for video in videos], dim=0) + video_grid_thw = list(itertools.chain(*(instance["video_grid_thw"] for instance in instances if "video_grid_thw" in instance))) + video_grid_thw = torch.stack(video_grid_thw, dim=0) + else: + concat_videos = None + video_grid_thw = None + + batch["pixel_values"] = concat_images + batch["image_grid_thw"] = grid_thw + batch["pixel_values_videos"] = concat_videos + batch["video_grid_thw"] = video_grid_thw + batch["_debug_dataset_index"] = [instance.get("_debug_dataset_index") for instance in instances] + + return batch + + +def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer, data_args) -> Dict: + """Make dataset and collator for supervised fine-tuning.""" + # load training dataset + train_dataset = LazySupervisedDataset(tokenizer=tokenizer, data_args=data_args) + + # load evaluation dataset (if specified eval dataset path) + eval_dataset = None + if hasattr(data_args, "eval_dataset") and data_args.eval_dataset: + eval_data_args = copy.deepcopy(data_args) + eval_data_args.dataset_use = data_args.eval_dataset + eval_dataset = LazySupervisedDataset(tokenizer=tokenizer, data_args=eval_data_args) + + # select appropriate collator based on whether data needs to be flattened + if data_args.data_flatten: + data_collator = FlattenedDataCollatorForSupervisedDataset(tokenizer=tokenizer) + else: + data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer) + + return dict( + train_dataset=train_dataset, + eval_dataset=eval_dataset, + data_collator=data_collator, + ) + + +def make_vlm_dataloader(cfg): + data_args = cfg.datasets.vlm_data + image_processor = AutoProcessor.from_pretrained(cfg.framework.qwenvl.base_vlm,).image_processor + + tokenizer = transformers.AutoTokenizer.from_pretrained( + cfg.framework.qwenvl.base_vlm, + model_max_length=data_args.model_max_length, + padding_side= + "left", # flash Attention version of Qwen2.5_VL. Make sure to call `tokenizer.padding_side = 'left'` before tokenizing the input. + use_fast=False, + ) + + # avoid processing these in dataset + image_processor.max_pixels = int(data_args.max_pixels) + image_processor.min_pixels = int(data_args.min_pixels) + image_processor.size["longest_edge"] = int(data_args.max_pixels) + image_processor.size["shortest_edge"] = int(data_args.min_pixels) + data_args_ns = SimpleNamespace(**OmegaConf.to_container(data_args, resolve=True)) + data_args_ns.image_processor = image_processor # TODO later remove the logic bound to model + data_module = make_supervised_data_module(tokenizer=tokenizer, data_args=data_args_ns) + + # + train_dataset = data_module["train_dataset"] + data_collator = data_module["data_collator"] + from torch.utils.data import DataLoader + + train_dataloader = DataLoader( + train_dataset, + batch_size=cfg.datasets.vlm_data.per_device_batch_size, + collate_fn=data_collator, + num_workers=4, + ) + + eval_dataloader = None + eval_dataset = data_module["eval_dataset"] + if eval_dataset is not None: + eval_dataloader = DataLoader( + eval_dataset, + batch_size=cfg.datasets.vlm_data.per_device_batch_size, + collate_fn=data_collator, + num_workers=4, + ) + + return { + "train_dataloader": train_dataloader, + "eval_dataloader": eval_dataloader, + } + + +from transformers import AutoTokenizer, AutoProcessor + + +def _safe_shape(x): + if x is None: + return None + if hasattr(x, "shape"): + return tuple(x.shape) + if isinstance(x, (list, tuple)): + return f"len={len(x)}" + return type(x).__name__ + + +def _print_sample_debug(dataset, sample_index): + raw_sample = dataset.list_data_dict[sample_index] + print(f"=== Raw sample[{sample_index}] ===") + print(f"keys: {sorted(raw_sample.keys())}") + if "conversations" in raw_sample: + print(f"num_conversations: {len(raw_sample['conversations'])}") + for idx, conv in enumerate(raw_sample["conversations"][:4]): + role = conv.get("role", conv.get("from")) + text = conv.get("content", conv.get("value", "")) + text = text.replace("\n", "\\n") + print(f"conv[{idx}] role={role} text[:160]={text[:160]}") + image_files = raw_sample.get("image", raw_sample.get("images")) + video_files = raw_sample.get("video", raw_sample.get("videos")) + print(f"image field: {image_files}") + print(f"video field: {video_files}") + print(f"data_path: {raw_sample.get('data_path')}") + print() + + try: + sample = dataset[sample_index] + except Exception as e: + print(f"=== dataset[{sample_index}] failed ===") + print(repr(e)) + return + + print(f"=== Processed sample[{sample_index}] ===") + for key, value in sample.items(): + if isinstance(value, torch.Tensor): + print(f"{key}: shape={tuple(value.shape)} dtype={value.dtype}") + elif isinstance(value, list): + child_shapes = [_safe_shape(v) for v in value[:4]] + print(f"{key}: list_len={len(value)} first_items={child_shapes}") + else: + print(f"{key}: {value}") + + input_ids = sample["input_ids"] + print(f"num_image_tokens: {int((input_ids == IMAGE_TOKEN_INDEX).sum().item())}") + print(f"num_video_tokens: {int((input_ids == VIDEO_TOKEN_INDEX).sum().item())}") + if "video_grid_thw" in sample: + print(f"video_grid_thw: {sample['video_grid_thw']}") + if "image_grid_thw" in sample: + print(f"image_grid_thw: {sample['image_grid_thw']}") + + +def _format_raw_sample_debug(raw_sample): + lines = [] + lines.append(f"keys: {sorted(raw_sample.keys())}") + if "id" in raw_sample: + lines.append(f"id: {raw_sample['id']}") + lines.append(f"data_path: {raw_sample.get('data_path')}") + lines.append(f"image field: {raw_sample.get('image', raw_sample.get('images'))}") + lines.append(f"video field: {raw_sample.get('video', raw_sample.get('videos'))}") + conversations = raw_sample.get("conversations", []) + lines.append(f"num_conversations: {len(conversations)}") + for idx, conv in enumerate(conversations[:4]): + role = conv.get("role", conv.get("from")) + text = conv.get("content", conv.get("value", "")) + text = text.replace("\n", "\\n") + lines.append(f"conv[{idx}] role={role} text[:160]={text[:160]}") + return "\n".join(lines) + + +def _print_batch_debug(batch, batch_index): + print(f"=== Batch[{batch_index}] ===") + for key, value in batch.items(): + if isinstance(value, torch.Tensor): + print(f"{key}: shape={tuple(value.shape)} dtype={value.dtype}") + else: + print(f"{key}: {_safe_shape(value)}") + input_ids = batch["input_ids"] + print(f"batch_image_tokens: {int((input_ids == IMAGE_TOKEN_INDEX).sum().item())}") + print(f"batch_video_tokens: {int((input_ids == VIDEO_TOKEN_INDEX).sum().item())}") + print() + + +def _print_batch_qa_debug(dataset, batch, batch_index, batch_size): + sample_indices = batch.get("_debug_dataset_index") + if sample_indices is None: + start = batch_index * batch_size + end = min(start + batch_size, len(dataset.list_data_dict)) + sample_indices = list(range(start, end)) + print(f"=== Batch[{batch_index}] QA ===") + for sample_index in sample_indices: + if sample_index is None: + continue + raw_sample = dataset.list_data_dict[sample_index] + sample_id = raw_sample.get("id", "") + print(f"-- sample[{sample_index}] id={sample_id}") + conversations = raw_sample.get("conversations", []) + for conv_idx, conv in enumerate(conversations): + role = conv.get("role", conv.get("from")) + text = conv.get("content", conv.get("value", "")) + text = text.replace("\n", "\\n") + print(f" [{conv_idx}] {role}: {text[:300]}") + print() + + +def _sanitize_filename(name): + return re.sub(r"[^A-Za-z0-9._-]+", "_", str(name)) + + +def _wrap_text_for_width(draw, text, font, max_width): + words = text.split() + if not words: + return [""] + lines = [] + current = words[0] + for word in words[1:]: + candidate = f"{current} {word}" + if draw.textbbox((0, 0), candidate, font=font)[2] <= max_width: + current = candidate + else: + lines.append(current) + current = word + lines.append(current) + return lines + + +def _save_annotated_debug_image(image, conversations, save_path): + font = ImageFont.load_default() + image = image.convert("RGB") + panel_width = image.width + padding = 12 + line_gap = 6 + + dummy = Image.new("RGB", (panel_width, 10), "white") + draw = ImageDraw.Draw(dummy) + + wrapped_lines = [] + for conv_idx, conv in enumerate(conversations): + role = conv.get("role", conv.get("from", "unknown")) + text = conv.get("content", conv.get("value", "")) + text = text.replace("\n", " ") + prefix = f"[{conv_idx}] {role}: " + body_lines = _wrap_text_for_width(draw, text, font, panel_width - padding * 2) + if body_lines: + wrapped_lines.append(prefix + body_lines[0]) + wrapped_lines.extend(body_lines[1:]) + else: + wrapped_lines.append(prefix) + wrapped_lines.append("") + + line_height = draw.textbbox((0, 0), "Ag", font=font)[3] + line_gap + text_height = padding * 2 + max(1, len(wrapped_lines)) * line_height + canvas = Image.new("RGB", (panel_width, image.height + text_height), "white") + canvas.paste(image, (0, 0)) + + draw = ImageDraw.Draw(canvas) + y = image.height + padding + for line in wrapped_lines: + draw.text((padding, y), line, fill="black", font=font) + y += line_height + + canvas.save(save_path) + + +def _save_debug_media(dataset, batch, batch_index, batch_size, output_dir): + os.makedirs(output_dir, exist_ok=True) + sample_indices = batch.get("_debug_dataset_index") + if sample_indices is None: + start = batch_index * batch_size + end = min(start + batch_size, len(dataset.list_data_dict)) + sample_indices = list(range(start, end)) + print(f"=== Batch[{batch_index}] media saved to {output_dir} ===") + + for sample_index in sample_indices: + if sample_index is None: + continue + raw_sample = dataset.list_data_dict[sample_index] + sample_id = _sanitize_filename(raw_sample.get("id", f"sample_{sample_index}")) + data_path = raw_sample.get("data_path", "") + conversations = raw_sample.get("conversations", []) + + image_files = raw_sample.get("image", raw_sample.get("images")) + if image_files is not None: + if not isinstance(image_files, (list, tuple)): + image_files = [image_files] + for media_idx, image_file in enumerate(image_files): + image_path = os.path.join(data_path, image_file) + try: + image = Image.open(image_path).convert("RGB") + annotated_path = os.path.join(output_dir, f"batch{batch_index}_sample{sample_index}_{sample_id}_image{media_idx}_qa.jpg") + _save_annotated_debug_image(image, conversations, annotated_path) + print(f"saved image+qa: {annotated_path}") + except Exception as e: + print(f"failed to save image {image_path}: {e}") + + video_files = raw_sample.get("video", raw_sample.get("videos")) + if video_files is not None: + if not isinstance(video_files, (list, tuple)): + video_files = [video_files] + for media_idx, video_file in enumerate(video_files): + video_path = os.path.join(data_path, video_file) + try: + vr = VideoReader(video_path, num_threads=1) + frame = vr[0].asnumpy() + image = Image.fromarray(frame).convert("RGB") + annotated_path = os.path.join(output_dir, f"batch{batch_index}_sample{sample_index}_{sample_id}_video{media_idx}_frame0_qa.jpg") + _save_annotated_debug_image(image, conversations, annotated_path) + print(f"saved video preview+qa: {annotated_path}") + except Exception as e: + print(f"failed to save video preview {video_path}: {e}") + +if __name__ == "__main__": + # import debugpy + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("--config_yaml", + type=str, + default="./examples/Suqian_agibot/train_files/starvla_cotrain_robocasa_gr1.yaml", + help="Path to YAML config") + parser.add_argument("--sample_index", type=int, default=None, help="Inspect a single dataset sample by index") + parser.add_argument("--max_batches", type=int, default=100, help="Number of batches to iterate for debugging") + 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") + args, clipargs = parser.parse_known_args() + + # debugpy.listen(("0.0.0.0", 10092)) + # print("🔍 Rank 0 waiting for debugger attach on port 10092...") + # debugpy.wait_for_client() + + cfg = OmegaConf.load(args.config_yaml) + + data_args = cfg.datasets.vlm_data + image_processor = AutoProcessor.from_pretrained(cfg.framework.qwenvl.base_vlm,).image_processor + + tokenizer = transformers.AutoTokenizer.from_pretrained( + cfg.framework.qwenvl.base_vlm, + model_max_length=data_args.model_max_length, + padding_side="left", + use_fast=False, + ) + + # avoid processing these in dataset + image_processor.max_pixels = data_args.max_pixels + image_processor.min_pixels = data_args.min_pixels + image_processor.size["longest_edge"] = data_args.max_pixels + image_processor.size["shortest_edge"] = data_args.min_pixels + + data_args_ns = SimpleNamespace(**OmegaConf.to_container(data_args, resolve=True)) + data_args_ns.image_processor = image_processor + data_module = make_supervised_data_module(tokenizer=tokenizer, data_args=data_args_ns) + + # + train_dataset = data_module["train_dataset"] + data_collator = data_module["data_collator"] + from torch.utils.data import DataLoader + + train_dataloader = DataLoader( + train_dataset, + batch_size=cfg.datasets.vlm_data.per_device_batch_size, + collate_fn=data_collator, + ) + if args.sample_index is not None: + _print_sample_debug(train_dataset, args.sample_index) + else: + batchs = iter(train_dataloader) + count = 0 + while count < args.max_batches: + batch_samples = next(batchs) + _print_batch_debug(batch_samples, count) + _print_batch_qa_debug(train_dataset, batch_samples, count, cfg.datasets.vlm_data.per_device_batch_size) + if args.save_debug_media_dir is not None: + _save_debug_media(train_dataset, batch_samples, count, cfg.datasets.vlm_data.per_device_batch_size, args.save_debug_media_dir) + count += 1 diff --git a/starVLA/dinov3/.docstr.yaml b/starVLA/dinov3/.docstr.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8c822fbc0f2f84d90629a1f70502c7e3dfd5f7f4 --- /dev/null +++ b/starVLA/dinov3/.docstr.yaml @@ -0,0 +1,6 @@ +paths: + - dinov3 +exclude: dinov3/tests +skip_init: True +skip_private: True +fail_under: 0 diff --git a/starVLA/dinov3/.github/workflows/lint.yaml b/starVLA/dinov3/.github/workflows/lint.yaml new file mode 100644 index 0000000000000000000000000000000000000000..53a5de1f2d5b756354b2e7ed88cb3c0d7442a959 --- /dev/null +++ b/starVLA/dinov3/.github/workflows/lint.yaml @@ -0,0 +1,47 @@ +name: Lint + +on: + push: + branches: + - main + pull_request: + branches: + - main + +jobs: + run-linters: + name: Run linters + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: 3.11 + cache: 'pip' + cache-dependency-path: '**/requirements*.txt' + - name: Install Python (development) dependencies + run: | + pip install -r requirements-dev.txt + - name: Run ruff (linter) + run: | + ruff check dinov3 + - name: Run ruff (formatter) + if: always() + run: | + ruff format --diff dinov3 + - name: Report docstring coverage + if: always() + run: | + docstr-coverage dinov3 + - name: Run mypy + if: always() + run: | + mypy --txt-report . + [ -f index.txt ] && cat index.txt + - name: Run pylint + if: always() + run: | + pylint --exit-zero dinov3 diff --git a/starVLA/dinov3/.gitignore b/starVLA/dinov3/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..bc9665c2e6aae2080bccc03c3e7bf485b2a2c25a --- /dev/null +++ b/starVLA/dinov3/.gitignore @@ -0,0 +1,18 @@ +build/ +dist/ +*.egg-info/ +**/__pycache__/ + +**/.ipynb_checkpoints +**/.ipynb_checkpoints/** + +**/notebooks + +# Ignore shell scripts +*.sh + +# Ignore swap files +*.swp + +# Ignore vscode directory +.vscode/ diff --git a/starVLA/dinov3/CODE_OF_CONDUCT.md b/starVLA/dinov3/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..3232ed665566ec047ce55a929db1581dbda266a1 --- /dev/null +++ b/starVLA/dinov3/CODE_OF_CONDUCT.md @@ -0,0 +1,80 @@ +# Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to make participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or +advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic +address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a +professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies within all project spaces, and it also applies when +an individual is representing the project or its community in public spaces. +Examples of representing a project or community include using an official +project e-mail address, posting via an official social media account, or acting +as an appointed representative at an online or offline event. Representation of +a project may be further defined and clarified by project maintainers. + +This Code of Conduct also applies outside the project spaces when there is a +reasonable belief that an individual's behavior may have a negative impact on +the project or its community. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at . All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq diff --git a/starVLA/dinov3/CONTRIBUTING.md b/starVLA/dinov3/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..c5f0c3e75e4921e5aa706898b4f6eaccd8e7d009 --- /dev/null +++ b/starVLA/dinov3/CONTRIBUTING.md @@ -0,0 +1,31 @@ +# Contributing to DINOv3 +We want to make contributing to this project as easy and transparent as +possible. + +## Pull Requests +We actively welcome your pull requests. + +1. Fork the repo and create your branch from `main`. +2. If you've added code that should be tested, add tests. +3. If you've changed APIs, update the documentation. +4. Ensure the test suite passes. +5. Make sure your code lints. +6. If you haven't already, complete the Contributor License Agreement ("CLA"). + +## Contributor License Agreement ("CLA") +In order to accept your pull request, we need you to submit a CLA. You only need +to do this once to work on any of Meta's open source projects. + +Complete your CLA here: + +## Issues +We use GitHub issues to track public bugs. Please ensure your description is +clear and has sufficient instructions to be able to reproduce the issue. + +Meta has a [bounty program](https://www.facebook.com/whitehat/) for the safe +disclosure of security bugs. In those cases, please go through the process +outlined on that page and do not file a public issue. + +## License +By contributing to DINOv3, you agree that your contributions will be licensed +under the LICENSE.md file in the root directory of this source tree. diff --git a/starVLA/dinov3/DATASETS.md b/starVLA/dinov3/DATASETS.md new file mode 100644 index 0000000000000000000000000000000000000000..786dae2de72842288693befd08047cd932cdf7a7 --- /dev/null +++ b/starVLA/dinov3/DATASETS.md @@ -0,0 +1,43 @@ +# Dataset setups for DINOv3 + +## Evaluations + +### Depth Estimation on NYU + +Create a folder to host the [NYU dataset](https://cs.nyu.edu/~fergus/datasets/nyu_depth_v2.html) for example: + +``` +export DEPTH_DATASETS_ROOT=${HOME}/datasets +mkdir -p ${DEPTH_DATASETS_ROOT}/NYU +``` + +We use the NYU subset extracted by [BTS](https://github.com/cleinc/bts/blob/master/tensorflow/README.md) from the 120k samples of the original NYU raw dataset. + +#### Option 1 -- Follow BTS's instructions +Please follow BTS instructions to create the dataset: +- [train set](https://github.com/cleinc/bts/blob/master/tensorflow/README.md#nyu-depvh-v2) +- [test set](https://github.com/cleinc/bts/blob/master/README.md#prepare-nyu-depth-v2-test-set). + +Make sure you also download the train and test splits: +``` +wget https://github.com/cleinc/bts/blob/master/train_test_inputs/nyudepthv2_train_files_with_gt.txt -O ${DEPTH_DATASETS_ROOT}/NYU/nyu_train.txt +wget https://github.com/cleinc/bts/blob/master/train_test_inputs/nyudepthv2_test_files_with_gt.txt -O ${DEPTH_DATASETS_ROOT}/NYU/nyu_test.txt +``` + +#### Option 2 (preferred) -- Download the readily availble dataset from BinsFormer +Alternatively, one can download the dataset from the following Google Drive [link](https://drive.google.com/file/d/1xI9ksHzCC_kUz6Z4FL_b1ttgj3RVHGwW/view?usp=sharing). If the Google Drive link is not available anymore, try Option 1. + +Expected contents: +- `$DEPTH_DATASETS_ROOT/NYU/basement/[...]` +- `$DEPTH_DATASETS_ROOT/NYU/basement_0001a/[...]` +- `$DEPTH_DATASETS_ROOT/NYU/basement_0001b/[...]` +- `$DEPTH_DATASETS_ROOT/NYU/bathroom/[...]` +- `$DEPTH_DATASETS_ROOT/NYU/[...]` +- `$DEPTH_DATASETS_ROOT/NYU/study_room_0004/[...]` +- `$DEPTH_DATASETS_ROOT/NYU/study_room_0005a/[...]` +- `$DEPTH_DATASETS_ROOT/NYU/study_room_0005b/[...]` +- `$DEPTH_DATASETS_ROOT/NYU/nyu_test.txt` +- `$DEPTH_DATASETS_ROOT/NYU/nyu_train.txt` + +Note: if data is downloaded with Option 2 make sure to rename `nyu` into `NYU`. + diff --git a/starVLA/dinov3/LICENSE.md b/starVLA/dinov3/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..f531b1e6b5ab2318957bbf8ad1bda9f800a23e17 --- /dev/null +++ b/starVLA/dinov3/LICENSE.md @@ -0,0 +1,66 @@ +# DINOv3 License + +*Last Updated: August 19, 2025* + +**“Agreement”** means the terms and conditions for use, reproduction, distribution and modification of the DINO Materials set forth herein. + +**“DINO Materials”** means, collectively, Documentation and the models, software and algorithms, including machine-learning model code, trained model weights, inference-enabling code, training-enabling code, fine-tuning enabling code, and other elements of the foregoing distributed by Meta and made available under this Agreement. + +**“Documentation”** means the specifications, manuals and documentation accompanying +DINO Materials distributed by Meta. + +**“Licensee”** or **“you”** means you, or your employer or any other person or entity (if you are entering into this Agreement on such person or entity’s behalf), of the age required under applicable laws, rules or regulations to provide legal consent and that has legal authority to bind your employer or such other person or entity if you are entering in this Agreement on their behalf. + +**“Meta”** or **“we”** means Meta Platforms Ireland Limited (if you are located in or, if you are an entity, your principal place of business is in the EEA or Switzerland) or Meta Platforms, Inc. (if you are located outside of the EEA or Switzerland). + +**“Sanctions”** means any economic or trade sanctions or restrictions administered or enforced by the United States (including the Office of Foreign Assets Control of the U.S. Department of the Treasury (“OFAC”), the U.S. Department of State and the U.S. Department of Commerce), the United Nations, the European Union, or the United Kingdom. + +**“Trade Controls”** means any of the following: Sanctions and applicable export and import controls. + +By clicking “I Accept” below or by using or distributing any portion or element of the DINO Materials, you agree to be bound by this Agreement. + +## 1. License Rights and Redistribution. + +a. Grant of Rights. You are granted a non-exclusive, worldwide, non-transferable and royalty-free limited license under Meta’s intellectual property or other rights owned by Meta embodied in the DINO Materials to use, reproduce, distribute, copy, create derivative works of, and make modifications to the DINO Materials. + +b. Redistribution and Use. + +i. Distribution of DINO Materials, and any derivative works thereof, are subject to the terms of this Agreement. If you distribute or make the DINO Materials, or any derivative works thereof, available to a third party, you may only do so under the terms of this Agreement and you shall provide a copy of this Agreement with any such DINO Materials. + +ii. If you submit for publication the results of research you perform on, using, or otherwise in connection with DINO Materials, you must acknowledge the use of DINO Materials in your publication. + +iii. Your use of the DINO Materials must comply with applicable laws and regulations, including Trade Control Laws and applicable privacy and data protection laws. + +iv. Your use of the DINO Materials will not involve or encourage others to reverse engineer, decompile or discover the underlying components of the DINO Materials. + +v. You are not the target of Trade Controls and your use of DINO Materials must comply with Trade Controls. You agree not to use, or permit others to use, DINO Materials for any activities subject to the International Traffic in Arms Regulations (ITAR) or end uses prohibited by Trade Controls, including those related to military or warfare purposes, nuclear industries or applications, espionage, or the development or use of guns or illegal weapons. + +## 2. User Support. + +Your use of the DINO Materials is done at your own discretion; Meta does not process any information nor provide any service in relation to such use. Meta is under no obligation to provide any support services for the DINO Materials. Any support provided is “as is”, “with all faults”, and without warranty of any kind. + +## 3. Disclaimer of Warranty. + +UNLESS REQUIRED BY APPLICABLE LAW, THE DINO MATERIALS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED ON AN “AS IS” BASIS, WITHOUT WARRANTIES OF ANY KIND, AND META DISCLAIMS ALL WARRANTIES OF ANY KIND, BOTH EXPRESS AND IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING THE DINO MATERIALS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE DINO MATERIALS AND ANY OUTPUT AND RESULTS. + +## 4. Limitation of Liability. + +IN NO EVENT WILL META OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT, FOR ANY LOST PROFITS OR ANY DIRECT OR INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN IF META OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING. + +## 5. Intellectual Property. + +a. Subject to Meta’s ownership of DINO Materials and derivatives made by or for Meta, with respect to any derivative works and modifications of the DINO Materials that are made by you, as between you and Meta, you are and will be the owner of such derivative works and modifications. + +b. If you institute litigation or other proceedings against Meta or any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the DINO Materials, outputs or results, or any portion of any of the foregoing, constitutes infringement of intellectual property or other rights owned or licensable by you, then any licenses granted to you under this Agreement shall terminate as of the date such litigation or claim is filed or instituted. You will indemnify and hold harmless Meta from and against any claim by any third party arising out of or related to your use or distribution of the DINO Materials. + +## 6. Term and Termination. + +The term of this Agreement will commence upon your acceptance of this Agreement or access to the DINO Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein. Meta may terminate this Agreement if you are in breach of any term or condition of this Agreement. Upon termination of this Agreement, you shall delete and cease use of the DINO Materials. Sections 3, 4 and 7 shall survive the termination of this Agreement. + +## 7. Governing Law and Jurisdiction. + +This Agreement will be governed and construed under the laws of the State of California without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. The courts of California shall have exclusive jurisdiction of any dispute arising out of this Agreement. + +## 8. Modifications and Amendments. + +Meta may modify this Agreement from time to time; provided that they are similar in spirit to the current version of the Agreement, but may differ in detail to address new problems or concerns. All such changes will be effective immediately. Your continued use of the DINO Materials after any modification to this Agreement constitutes your agreement to such modification. Except as provided in this Agreement, no modification or addition to any provision of this Agreement will be binding unless it is in writing and signed by an authorized representative of both you and Meta. diff --git a/starVLA/dinov3/MODEL_CARD.md b/starVLA/dinov3/MODEL_CARD.md new file mode 100644 index 0000000000000000000000000000000000000000..2bd45fb07beab1ad5f7a734608e79d5fd8899b42 --- /dev/null +++ b/starVLA/dinov3/MODEL_CARD.md @@ -0,0 +1,432 @@ +# Model Card for DINOv3 + +DINOv3 is a family of versatile vision foundation models that outperforms the specialized state of the art across a broad range of settings, without fine-tuning. DINOv3 produces high-quality dense features that achieve outstanding performance on various vision tasks, significantly surpassing previous self- and weakly-supervised foundation models. + +## Model Details + +These are Vision Transformer and ConvNeXt models trained following the method described in the DINOv3 paper. 12 models are provided: + +- 10 models pretrained on web data (LVD-1689M dataset) + - 1 ViT-7B trained from scratch, + - 5 ViT-S/S+/B/L/H+ models distilled from the ViT-7B, + - 4 ConvNeXt-{T/S/B/L} models distilled from the ViT-7B, +- 2 models pretrained on satellite data (SAT-493M dataset) + - 1 ViT-7B trained from scratch + - 1 ViT-L distilled from the ViT-7B + + +Each Transformer-based model takes an image as input and returns a class token, patch tokens (and register tokens). These models follow a ViT architecture, with a patch size of 16. For a 224x224 image, this results in 1 class token + 4 register tokens + 196 patch tokens = 201 tokens (for DINOv2 with registers this resulted in 1 + 4 + 256 = 261 tokens). + +The models can accept larger images provided the image shapes are multiples of the patch size (16). If this condition is not verified, the model will crop to the closest smaller multiple of the patch size. + +### Model Description + +- **Developed by:** Meta AI +- **Model type:** Vision Transformer, ConvNeXt +- **License:** [DINOv3 License](https://ai.meta.com/resources/models-and-libraries/dinov3-license/) + +### Model Sources + +- **Repository:** [https://github.com/facebookresearch/dinov3](https://github.com/facebookresearch/dinov3) +- **Paper:** [https://arxiv.org/abs/2508.10104](https://arxiv.org/abs/2508.10104) + +## Uses + +The models are vision backbones providing multi-purpose features for downstream tasks. + +### Direct Use + +The models can be used without fine-tuning, with downstream classifiers as simple as linear layers, to obtain competitive results: + +- on image classification, using k-NN classifiers on the class token +- on image classification, with logistic regression classifiers applied on the class token +- on image classification, with a linear layer applied on the class token and the average of the patch tokens +- on image retrieval using nearest neighbors +- on geometric and semantic 3D keypoint correspondances +- on depth estimation, semantic segmentation, using linear layers +- on unsupervised object discovery +- on video segmentation tracking +- on video classification, using a small 4-layer attentive probe + +### Downstream Use + +While fine-tuning the models can yield some gains, it is recommended to keep this option as a last resort: the frozen features are expected to provide good performance out-of-the-box. + +## Bias, Risks, and Limitations + +Compared to DINOv2 and SEERv2, DINOv3 delivers somewhat consistent performance across income categories on geographical fairness and diversity, although with a notable performance drop in the low-income bucket compared to the highest-income bucket. + +DINOv3 also achieves relatively good scores across different regions, improving over its predecessor DINOv2. However, a relative difference is still observed between Europe and Africa. + +### Recommendations + +Fine-tuning is expected to increase the biases in the features produced by the model as they will be tuned to the fine-tuning labels. + +## How to Get Started with the Model + +Use the code below to get started with the model. + +```python +import torch + +model = torch.hub.load( + repo_or_dir='facebookresearch/dinov3', + model='', + weights='', +) + +# where MODEL_NAME can be one of: +# - dinov3_vits16 +# - dinov3_vits16plus +# - dinov3_vitb16 +# - dinov3_vitl16 +# - dinov3_vith16plus +# - dinov3_vit7b16 +# - dinov3_convnext_tiny +# - dinov3_convnext_small +# - dinov3_convnext_base +# - dinov3_convnext_large + +# For instance +dinov3_vits16 = torch.hub.load( + repo_or_dir='facebookresearch/dinov3', + model='dinov3_vits16', + weights='', +) +``` + +## Training Details + +### Training Data + +- Web dataset (LVD-1689M): a curated dataset of 1,689 millions of images extracted from a large data +pool of 17 billions web images collected from public posts on Instagram + +- Satellite dataset (SAT-493M): a dataset of 493 millions of 512x512 images sampled randomly from Maxar RGB ortho-rectified imagery at 0.6 meter resolution + +### Training Procedure + +**Training objective:** + +- DINO self-distillation loss with multi-crop +- iBOT masked-image modeling loss +- KoLeo regularization on [CLS] tokens +- Gram anchoring + +- **Training regime:** PyTorch FSDP2 (with bf16 and fp8 matrix multiplications) + +**Distillation:** + +- Distillation follows the standard DINOv3 pretraining procedure, except the teacher is a frozen pretrained ViT-7B. + +## Evaluation + +**Results** + +The reader is referred to the associated paper for details on the evaluation protocols + +*Results for ViT backbones pretrained (or distilled) on web (LVD-1689M)* + + + + + + Global Tasks + Dense Tasks + + + Model + + IN-ReaL + IN-R + Obj.Net + Ox.-H + ADE20k + NYU↓ + DAVIS + NAVI + SPair + + + DINOv3 ViT-S/16 + + 87.0 + 60.4 + 50.9 + 49.5 + 47.0 + 0.403 + 72.7 + 56.3 + 50.4 + + + DINOv3 ViT-S+/16 + + 88.0 + 68.8 + 54.6 + 50.0 + 48.8 + 0.399 + 75.5 + 57.1 + 55.2 + + + DINOv3 ViT-B/16 + + 89.3 + 76.7 + 64.1 + 58.5 + 51.8 + 0.373 + 77.2 + 58.8 + 57.2 + + + DINOv3 ViT-L/16 + + 90.2 + 88.1 + 74.8 + 63.1 + 54.9 + 0.352 + 79.9 + 62.3 + 61.3 + + + DINOv3 ViT-H+/16 + + 90.3 + 90.0 + 78.6 + 64.5 + 54.8 + 0.352 + 79.3 + 63.3 + 56.3 + + + DINOv3 ViT-7B/16 + + 90.4 + 91.1 + 91.1 + 72.8 + 55.9 + 0.309 + 79.7 + 64.4 + 58.7 + + + +*Results for ConvNeXt backbones distilled on web (LVD-1689M)* + + + + + Global Tasks + Dense Tasks + + + Model + IN-ReaL + IN-R + Obj.Net + ADE20k + NYU↓ + + + + @256px + @512px + @256px + @512px + @256px + @512px + + + + DINOv3 ConvNeXt Tiny + 86.6 + 87.7 + 73.7 + 74.1 + 52.6 + 58.7 + 42.7 + 0.448 + + + DINOv3 ConvNeXt Small + 87.9 + 88.7 + 73.7 + 74.1 + 52.6 + 58.7 + 44.8 + 0.432 + + + DINOv3 ConvNeXt Base + 88.5 + 89.2 + 77.2 + 78.2 + 56.2 + 61.3 + 46.3 + 0.420 + + + DINOv3 ConvNeXt Large + 88.9 + 89.4 + 81.3 + 82.4 + 59.3 + 65.2 + 47.8 + 0.403 + + + +*Results for ViT backbones pretrained (or distilled) on satellite (SAT-493M)* + + + + + (GEO-Bench) Classification + + + Model + m-BEnet + m-brick-kiln + m-eurosat + m-forestnet + m-pv4ger + m-so2sat + mean + + + DINOv3 ViT-L/16 + 73.0 + 96.5 + 94.1 + 60.6 + 96.0 + 57.4 + 79.6 + + + DINOv3 ViT-7B/16 + 74.0 + 97.2 + 94.8 + 62.3 + 96.1 + 62.1 + 81.1 + + + + (GEO-Bench) Segmentation + + + Model + m-cashew + m-chesapeake + m-NeonTree + m-nz-cattle + m-pv4ger-seg + m-SA-crop + mean + + + DINOv3 ViT-L/16 + 94.2 + 75.6 + 61.8 + 83.7 + 95.2 + 36.8 + 74.5 + + + DINOv3 ViT-7B/16 + 94.1 + 76.6 + 62.6 + 83.4 + 95.5 + 37.6 + 75.0 + + + + +## Environmental Impact + +- **Hardware Type:** Nvidia H100 +- **Hours used:** 61,440 hours for ViT-7B model training +- **Cloud Provider:** Private infrastructure +- **Compute Region:** USA +- **Carbon Emitted:** 18t CO2eq + +## Technical Specifications + +### Model Architecture and Objective + +Vision Transformer models: + +- ViT-S (21M parameters): patch size 16, embedding dimension 384, 4 register tokens, 6 heads, MLP FFN, RoPE +- ViT-S+ (29M parameters): patch size 16, embedding dimension 384, 4 register tokens, 6 heads, SwiGLU FFN, RoPE +- ViT-B (86M parameters): patch size 16, embedding dimension 768, 4 register tokens, 12 heads, MLP FFN, RoPE +- ViT-L (300M parameters): patch size 16, embedding dimension 1024, 4 register tokens, 16 heads, MLP FFN, RoPE +- ViT-H+ (840M parameters): patch size 16, embedding dimension 1280, 4 register tokens, 20 heads, SwiGLU FFN, RoPE +- ViT-7B (6716M parameters): patch size 16, embedding dimension 4096, 4 register tokens, 32 heads, SwiGLU FFN, RoPE + +ConvNeXt models: + +- ConvNeXt Tiny (29M parameters) +- ConvNeXt Small (50M parameters) +- ConvNeXt Base (89M parameters) +- ConvNeXt Large (198M parameters) + +### Compute Infrastructure + +#### Hardware + +Nvidia H100 GPUs + +#### Software + +PyTorch 2.7 + +## More Information + +See the [blog post](https://ai.meta.com/blog/dinov3-self-supervised-vision-model/) and the associated [website](https://ai.meta.com/dinov3/). + +## Citation + +**BibTeX** + +``` +@misc{simeoni2025dinov3, + title={{DINOv3}}, + author={Sim{\'e}oni, Oriane and Vo, Huy V. and Seitzer, Maximilian and Baldassarre, Federico and Oquab, Maxime and Jose, Cijo and Khalidov, Vasil and Szafraniec, Marc and Yi, Seungeun and Ramamonjisoa, Micha{\"e}l and Massa, Francisco and Haziza, Daniel and Wehrstedt, Luca and Wang, Jianyuan and Darcet, Timoth{\'e}e and Moutakanni, Th{\'e}o and Sentana, Leonel and Roberts, Claire and Vedaldi, Andrea and Tolan, Jamie and Brandt, John and Couprie, Camille and Mairal, Julien and J{\'e}gou, Herv{\'e} and Labatut, Patrick and Bojanowski, Piotr}, + year={2025}, + eprint={2508.10104}, + archivePrefix={arXiv}, + primaryClass={cs.CV}, + url={https://arxiv.org/abs/2508.10104}, +} +``` diff --git a/starVLA/dinov3/README.md b/starVLA/dinov3/README.md new file mode 100644 index 0000000000000000000000000000000000000000..317f71034cd615b36b9b7b741779750ba3bd55bd --- /dev/null +++ b/starVLA/dinov3/README.md @@ -0,0 +1,882 @@ +:new: [2026-03-10] :fire: The [Canopy Height Maps v2 (CHMv2) model](https://arxiv.org/abs/2603.06382) and inference code are now available (more details on downloading the model weights and using the code [here](#canopy-height-maps-v2-chmv2)). The model weights are also available in [Hugging Face Hub](https://huggingface.co/facebook/dinov3-vitl16-chmv2-dpt-head) and [supported](https://github.com/huggingface/transformers/blob/main/docs/source/en/model_doc/chmv2.md) by the Hugging Face [Transformers](https://huggingface.co/docs/transformers/index) library. Building on our original high-resolution canopy height maps released in 2024, CHMv2 delivers substantial improvements in accuracy, detail, and global consistency by leveraging DINOv3. + +[2025-11-20] Distillation code and configurations for ConvNeXt backbones are now released! + +[2025-10-13] [Semantic segmentation](https://github.com/facebookresearch/dinov3?tab=readme-ov-file#linear-segmentation-with-data-augmentation-on-ade20k) (ADE20K) and [monocular depth estimation](https://github.com/facebookresearch/dinov3?tab=readme-ov-file#linear-depth-estimation-on-nyuv2-depth) (NYUv2-Depth) linear probing code are now released! + +[2025-09-17] DINOv3 backbones are now supported by the [PyTorch Image Models / timm](https://github.com/huggingface/pytorch-image-models/) library starting with version [1.0.20](https://github.com/huggingface/pytorch-image-models/releases/tag/v1.0.20) + +[2025-08-29] DINOv3 backbones are [supported](https://huggingface.co/docs/transformers/model_doc/dinov3) by released versions of the Hugging Face [Transformers](https://huggingface.co/docs/transformers/index) library starting with version [4.56.0](https://github.com/huggingface/transformers/releases/tag/v4.56.0) + +[2025-08-14] DINOv3 backbones are now available in [Hugging Face Hub](https://huggingface.co/collections/facebook/dinov3-68924841bd6b561778e31009) and [supported](https://huggingface.co/docs/transformers/model_doc/dinov3) by the [development](https://github.com/huggingface/transformers/) version of the Hugging Face [Transformers](https://huggingface.co/docs/transformers/index) library + +# DINOv3 🦖🦖🦖 + +**[Meta AI Research, FAIR](https://ai.meta.com/research/)** + +Oriane Siméoni, Huy V. Vo, Maximilian Seitzer, Federico Baldassarre, Maxime Oquab, +Cijo Jose, Vasil Khalidov, Marc Szafraniec, Seungeun Yi, Michaël Ramamonjisoa, +Francisco Massa, Daniel Haziza, Luca Wehrstedt, Jianyuan Wang, +Timothée Darcet, Théo Moutakanni, Leonel Sentana, Claire Roberts, +Andrea Vedaldi, Jamie Tolan, John Brandt, Camille Couprie, +Julien Mairal, Hervé Jégou, Patrick Labatut, Piotr Bojanowski + +[ :scroll: [`Paper`](https://arxiv.org/abs/2508.10104)] [ :newspaper: [`Blog`](https://ai.meta.com/blog/dinov3-self-supervised-vision-model/)] [ :globe_with_meridians: [`Website`](https://ai.meta.com/dinov3/)] [ :book: [`BibTeX`](#citing-dinov3)] + +Reference PyTorch implementation and models for DINOv3. For details, see the **[DINOv3](https://arxiv.org/abs/2508.10104)** paper. + +## Overview + + + + + High-resolution dense features.We visualize the cosine similarity maps obtained with DINOv3 output features between the patches marked with a red cross and all other patches. + + + + +An extended family of versatile vision foundation models producing high-quality dense features and achieving outstanding performance on various vision tasks including outperforming the specialized state of the art across a broad range of settings, without fine-tuning + +## Pretrained models + +:information_source: Please follow the link provided below to get access to all the model weights: once accepted, an e-mail will be sent with the complete list of URLs pointing to all the available model weights (both backbones and adapters). These URLs can then be used to either: +- download the model or adapter weights to a local filesystem and point `torch.hub.load()` to these local weights via the `weights` or `backbone_weights` parameters, or +- directly invoke `torch.hub.load()` to download and load a backbone or an adapter from its URL via also the `weights` or `backbone_weights` parameters. + +See the example code snippets below. + +:warning: Please use `wget` instead of a web browser to download the weights. + +ViT models pretrained on web dataset (LVD-1689M): + + + + Model + Parameters + PretrainingDataset + Download + + + + + ViT-S/16 distilled + 21M + LVD-1689M + [link] + + + ViT-S+/16 distilled + 29M + LVD-1689M + [link] + + + ViT-B/16 distilled + 86M + LVD-1689M + [link] + + + ViT-L/16 distilled + 300M + LVD-1689M + [link] + + + ViT-H+/16 distilled + 840M + LVD-1689M + [link] + + + ViT-7B/16 + 6,716M + LVD-1689M + [link] + + + + +ConvNeXt models pretrained on web dataset (LVD-1689M): + + + + Model + Parameters + PretrainingDataset + Download + + + + + ConvNeXt Tiny + 29M + LVD-1689M + [link] + + + ConvNeXt Small + 50M + LVD-1689M + [link] + + + ConvNeXt Base + 89M + LVD-1689M + [link] + + + ConvNeXt Large + 198M + LVD-1689M + [link] + + + + +ViT models pretrained on satellite dataset (SAT-493M): + + + + Model + Parameters + PretrainingDataset + Download + + + + + ViT-L/16 distilled + 300M + SAT-493M + [link] + + + ViT-7B/16 + 6,716M + SAT-493M + [link] + + + + + +### Pretrained backbones (via PyTorch [Hub](https://docs.pytorch.org/docs/stable/hub.html)) + +Please follow the instructions [here](https://pytorch.org/get-started/locally/) to install PyTorch (the only required dependency for loading the model). Installing PyTorch with CUDA support is strongly recommended. + +```python +import torch + +REPO_DIR = + +# DINOv3 ViT models pretrained on web images +dinov3_vits16 = torch.hub.load(REPO_DIR, 'dinov3_vits16', source='local', weights=) +dinov3_vits16plus = torch.hub.load(REPO_DIR, 'dinov3_vits16plus', source='local', weights=) +dinov3_vitb16 = torch.hub.load(REPO_DIR, 'dinov3_vitb16', source='local', weights=) +dinov3_vitl16 = torch.hub.load(REPO_DIR, 'dinov3_vitl16', source='local', weights=) +dinov3_vith16plus = torch.hub.load(REPO_DIR, 'dinov3_vith16plus', source='local', weights=) +dinov3_vit7b16 = torch.hub.load(REPO_DIR, 'dinov3_vit7b16', source='local', weights=) + +# DINOv3 ConvNeXt models pretrained on web images +dinov3_convnext_tiny = torch.hub.load(REPO_DIR, 'dinov3_convnext_tiny', source='local', weights=) +dinov3_convnext_small = torch.hub.load(REPO_DIR, 'dinov3_convnext_small', source='local', weights=) +dinov3_convnext_base = torch.hub.load(REPO_DIR, 'dinov3_convnext_base', source='local', weights=) +dinov3_convnext_large = torch.hub.load(REPO_DIR, 'dinov3_convnext_large', source='local', weights=) + +# DINOv3 ViT models pretrained on satellite imagery +dinov3_vitl16 = torch.hub.load(REPO_DIR, 'dinov3_vitl16', source='local', weights=) +dinov3_vit7b16 = torch.hub.load(REPO_DIR, 'dinov3_vit7b16', source='local', weights=) +``` + +### Pretrained backbones (via Hugging Face [Transformers](https://huggingface.co/docs/transformers/)) + +All the backbones are available in the [DINOv3](https://huggingface.co/collections/facebook/dinov3-68924841bd6b561778e31009) collection on Hugging Face Hub and supported via the Hugging Face [Transformers](https://huggingface.co/docs/transformers/index) library (with released packages from version 4.56.0). Please refer to the corresponding documentation for usage, but below is a short example that demonstrates how to obtain an image embedding with either [Pipeline] or the [AutoModel] class. + +```python +from transformers import pipeline +from transformers.image_utils import load_image + +url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg" +image = load_image(url) + +feature_extractor = pipeline( + model="facebook/dinov3-convnext-tiny-pretrain-lvd1689m", + task="image-feature-extraction", +) +features = feature_extractor(image) +``` + +```python +import torch +from transformers import AutoImageProcessor, AutoModel +from transformers.image_utils import load_image + +url = "http://images.cocodataset.org/val2017/000000039769.jpg" +image = load_image(url) + +pretrained_model_name = "facebook/dinov3-convnext-tiny-pretrain-lvd1689m" +processor = AutoImageProcessor.from_pretrained(pretrained_model_name) +model = AutoModel.from_pretrained( + pretrained_model_name, + device_map="auto", +) + +inputs = processor(images=image, return_tensors="pt").to(model.device) +with torch.inference_mode(): + outputs = model(**inputs) + +pooled_output = outputs.pooler_output +print("Pooled output shape:", pooled_output.shape) +``` + +where `model` and `pretrained_model_name` above can be one of: +- `facebook/dinov3-vits16-pretrain-lvd1689m` +- `facebook/dinov3-vits16plus-pretrain-lvd1689m` +- `facebook/dinov3-vitb16-pretrain-lvd1689m` +- `facebook/dinov3-vitl16-pretrain-lvd1689m` +- `facebook/dinov3-vith16plus-pretrain-lvd1689m` +- `facebook/dinov3-vit7b16-pretrain-lvd1689m` +- `facebook/dinov3-convnext-base-pretrain-lvd1689m` +- `facebook/dinov3-convnext-large-pretrain-lvd1689m` +- `facebook/dinov3-convnext-small-pretrain-lvd1689m` +- `facebook/dinov3-convnext-tiny-pretrain-lvd1689m` +- `facebook/dinov3-vitl16-pretrain-sat493m` +- `facebook/dinov3-vit7b16-pretrain-sat493m` + +### Image transforms + +For models using the LVD-1689M weights (pretrained on web images), please use the following transform (standard ImageNet evaluation transform): + +```python +import torchvision +from torchvision.transforms import v2 + +def make_transform(resize_size: int = 256): + to_tensor = v2.ToImage() + resize = v2.Resize((resize_size, resize_size), antialias=True) + to_float = v2.ToDtype(torch.float32, scale=True) + normalize = v2.Normalize( + mean=(0.485, 0.456, 0.406), + std=(0.229, 0.224, 0.225), + ) + return v2.Compose([to_tensor, resize, to_float, normalize]) +``` + + +For models using the SAT-493M weights (pretrained on satellite imagery), please use the following transform: + + +```python +import torchvision +from torchvision.transforms import v2 + +def make_transform(resize_size: int = 256): + to_tensor = v2.ToImage() + resize = v2.Resize((resize_size, resize_size), antialias=True) + to_float = v2.ToDtype(torch.float32, scale=True) + normalize = v2.Normalize( + mean=(0.430, 0.411, 0.296), + std=(0.213, 0.156, 0.143), + ) + return v2.Compose([to_tensor, resize, to_float, normalize]) +``` + +### Pretrained heads - Image classification + + + + + Backbone + PretrainingDataset + HeadDataset + Download + + + + + ViT-7B/16 + LVD-1689M + ImageNet + [link] + + + + + +The (full) classifier models can be loaded via PyTorch Hub: + +```python +import torch + +# DINOv3 +dinov3_vit7b16_lc = torch.hub.load(REPO_DIR, 'dinov3_vit7b16_lc', source="local", weights=, backbone_weights=) + +``` + +### Pretrained heads - Depther trained on SYNTHMIX dataset + + + + + Backbone + PretrainingDataset + HeadDataset + Download + + + + + ViT-7B/16 + LVD-1689M + SYNTHMIX + [link] + + + + + +```python +depther = torch.hub.load(REPO_DIR, 'dinov3_vit7b16_dd', source="local", weights=, backbone_weights=) +``` + +Full example code of depther on an image + +```python +from PIL import Image +import torch +from torchvision.transforms import v2 +import matplotlib.pyplot as plt +from matplotlib import colormaps + +def get_img(): + import requests + url = "http://images.cocodataset.org/val2017/000000039769.jpg" + image = Image.open(requests.get(url, stream=True).raw).convert("RGB") + return image + +def make_transform(resize_size: int | list[int] = 768): + to_tensor = v2.ToImage() + resize = v2.Resize((resize_size, resize_size), antialias=True) + to_float = v2.ToDtype(torch.float32, scale=True) + normalize = v2.Normalize( + mean=(0.485, 0.456, 0.406), + std=(0.229, 0.224, 0.225), + ) + return v2.Compose([to_tensor, resize, to_float, normalize]) + +depther = torch.hub.load(REPO_DIR, 'dinov3_vit7b16_dd', source="local", weights=, backbone_weights=) + +img_size = 1024 +img = get_img() +transform = make_transform(img_size) +with torch.inference_mode(): + with torch.autocast('cuda', dtype=torch.bfloat16): + batch_img = transform(img)[None] + batch_img = batch_img + depths = depther(batch_img) + +plt.figure(figsize=(12, 6)) +plt.subplot(121) +plt.imshow(img) +plt.axis("off") +plt.subplot(122) +plt.imshow(depths[0,0].cpu(), cmap=colormaps["Spectral"]) +plt.axis("off") + +``` + +#### Reproduce paper results + +Make sure the NYU dataset is setup following [this](DATASETS.md#depth-estimation-on-nyu). + +Launch the following to reproduce our paper's depth estimation results on NYUv2 with the pretrained Depther trained on SYNTHMIX: + +```shell +PYTHONPATH=. python -m dinov3.run.submit dinov3/eval/depth/run.py \ +config=dinov3/eval/depth/configs/config-nyu-synthmix-dpt-inference.yaml \ +datasets.root= \ +load_from=dinov3_vit7b16_dd \ +--output-dir +``` + +Notes: +- if you want to launch the code without dinov3.run.submit, you can do so using python directly or torchrun: + +```shell +PYTHONPATH=. python dinov3/eval/depth/run.py \ +config=dinov3/eval/depth/configs/config-nyu-synthmix-dpt-inference.yaml \ +datasets.root= \ +load_from=dinov3_vit7b16_dd \ +output_dir= +``` + +- One can also save prediction results using `result_config.save_results=true`. + + +### Pretrained heads - Detector trained on COCO2017 dataset + + + + + Backbone + PretrainingDataset + HeadDataset + Download + + + + + ViT-7B/16 + LVD-1689M + COCO2017 + [link] + + + + + +```python +detector = torch.hub.load(REPO_DIR, 'dinov3_vit7b16_de', source="local", weights=, backbone_weights=) +``` + +### Pretrained heads - Segmentor trained on ADE20K dataset + + + + + Backbone + PretrainingDataset + HeadDataset + Download + + + + + ViT-7B/16 + LVD-1689M + ADE20K + [link] + + + + +```python +segmentor = torch.hub.load(REPO_DIR, 'dinov3_vit7b16_ms', source="local", weights=, backbone_weights=) +``` + +Example command to run a full inference on ADE20K with the provided segmentor (ViT-7B + M2F): + +```shell +PYTHONPATH=. python -m dinov3.run.submit dinov3/eval/segmentation/run.py \ +config=dinov3/eval/segmentation/configs/config-ade20k-m2f-inference.yaml \ +datasets.root= \ +load_from=dinov3_vit7b16_ms \ +--output-dir +``` + +Full example code of segmentator on an image + +```python +import sys +sys.path.append(REPO_DIR) + +from PIL import Image +import torch +from torchvision import transforms +import matplotlib.pyplot as plt +from matplotlib import colormaps +from functools import partial +from dinov3.eval.segmentation.inference import make_inference + + +def get_img(): + import requests + url = "http://images.cocodataset.org/val2017/000000039769.jpg" + image = Image.open(requests.get(url, stream=True).raw).convert("RGB") + return image + +def make_transform(resize_size: int | list[int] = 768): + to_tensor = v2.ToImage() + resize = v2.Resize((resize_size, resize_size), antialias=True) + to_float = v2.ToDtype(torch.float32, scale=True) + normalize = v2.Normalize( + mean=(0.485, 0.456, 0.406), + std=(0.229, 0.224, 0.225), + ) + return v2.Compose([to_tensor, resize, to_float, normalize]) + +segmentor = torch.hub.load(REPO_DIR, 'dinov3_vit7b16_ms', source="local", weights=, backbone_weights=) + +img_size = 896 +img = get_img() +transform = make_transform(img_size) +with torch.inference_mode(): + with torch.autocast('cuda', dtype=torch.bfloat16): + batch_img = transform(img)[None] + pred_vit7b = segmentor(batch_img) # raw predictions + # actual segmentation map + segmentation_map_vit7b = make_inference( + batch_img, + segmentor, + inference_mode="slide", + decoder_head_type="m2f", + rescale_to=(img.size[-1], img.size[-2]), + n_output_channels=150, + crop_size=(img_size, img_size), + stride=(img_size, img_size), + output_activation=partial(torch.nn.functional.softmax, dim=1), + ).argmax(dim=1, keepdim=True) +plt.figure(figsize=(12, 6)) +plt.subplot(121) +plt.imshow(img) +plt.axis("off") +plt.subplot(122) +plt.imshow(segmentation_map_vit7b[0,0].cpu(), cmap=colormaps["Spectral"]) +plt.axis("off") +``` + + + + +### Pretrained heads - Zero-shot tasks with `dino.txt` + + + + + Backbone + Download + + + + + ViT-L/16 distilled + + [link], + vocabulary, + vocabulary license + + + + + +The (full) dino.txt model can be loaded via PyTorch Hub: + +```python +import torch +# DINOv3 +dinov3_vitl16_dinotxt_tet1280d20h24l, tokenizer = torch.hub.load(REPO_DIR, 'dinov3_vitl16_dinotxt_tet1280d20h24l', weights=, backbone_weights=) +``` + + +## Installation + +The training and evaluation code requires PyTorch version >= 2.7.1 as well as a few other 3rd party packages. Note that the code has only been tested with the specified versions and also expects a Linux environment. To setup all the required dependencies for training and evaluation, please follow the instructions below: + +*[micromamba](https://mamba.readthedocs.io/en/latest/user_guide/micromamba.html)* **(Recommended)** - Clone the repository and then create and activate a `dinov3` conda environment using the provided environment definition: + +```shell +micromamba env create -f conda.yaml +micromamba activate dinov3 +``` + +## Getting started + +Several notebooks are provided to get started applying DINOv3: +- [PCA of patch features](notebooks/pca.ipynb): display the PCA of DINOv3 patch features on a foreground object (rainbow visualizations from the paper) [[Run in Google Colab]](https://colab.research.google.com/github/facebookresearch/dinov3/blob/main/notebooks/pca.ipynb) +- [Foreground segmentation](notebooks/foreground_segmentation.ipynb): train a linear foreground segmentation model based on DINOv3 features [[Run in Google Colab]](https://colab.research.google.com/github/facebookresearch/dinov3/blob/main/notebooks/foreground_segmentation.ipynb) +- [Dense and sparse matching](notebooks/dense_sparse_matching.ipynb): match patches from objects on two different images based on DINOv3 features [[Run in Google Colab]](https://colab.research.google.com/github/facebookresearch/dinov3/blob/main/notebooks/dense_sparse_matching.ipynb) +- [Segmentation tracking](notebooks/segmentation_tracking.ipynb): video segmentation tracking using a non-parametric method based on DINOv3 features [[Run in Google Colab]](https://colab.research.google.com/github/facebookresearch/dinov3/blob/main/notebooks/segmentation_tracking.ipynb) +- [Zero-shot segmentation with DINOv3-based dino.txt](notebooks/dinotxt_segmentation_inference.ipynb): compute the open-vocabulary segmentation results with dino.txt strategy. + +## Data preparation + +### ImageNet-1k + +The root directory of the dataset should hold the following contents: + +- `/test/ILSVRC2012_test_00000001.JPEG` +- `/test/[..]` +- `/test/ILSVRC2012_test_00100000.JPEG` +- `/train/n01440764/n01440764_10026.JPEG` +- `/train/[...]` +- `/train/n15075141/n15075141_9993.JPEG` +- `/val/n01440764/ILSVRC2012_val_00000293.JPEG` +- `/val/[...]` +- `/val/n15075141/ILSVRC2012_val_00049174.JPEG` +- `/labels.txt` + +The provided dataset implementation expects a few additional metadata files to be present under the extra directory: + +- `/class-ids-TRAIN.npy` +- `/class-ids-VAL.npy` +- `/class-names-TRAIN.npy` +- `/class-names-VAL.npy` +- `/entries-TEST.npy` +- `/entries-TRAIN.npy` +- `/entries-VAL.npy` + +These metadata files can be generated (once) with the following lines of Python code: + +```python +from dinov3.data.datasets import ImageNet + +for split in ImageNet.Split: + dataset = ImageNet(split=split, root="", extra="") + dataset.dump_extra() +``` + +Note that the root and extra directories do not have to be distinct directories. + +### ImageNet-22k + +Please adapt the [dataset class](dinov3/data/datasets/image_net_22k.py) to match your local setup. + + + +:warning: To execute the commands provided in the next sections for training and evaluation, the `dinov3` package should be included in the Python module search path, i.e. simply prefix the command to run with `PYTHONPATH=.`. + +## Training + +### Fast setup: training DINOv3 ViT-L/16 on ImageNet-1k + +Run DINOv3 pre-training on 4 H100-80GB nodes (32 GPUs) in a SLURM cluster environment with submitit: + +```shell + PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/train/train.py \ + --nodes 4 \ + --config-file dinov3/configs/train/vitl_im1k_lin834.yaml \ + --output-dir \ + train.dataset_path=ImageNet22k:root=:extra= +``` +Training time is approximately 14 hours and the resulting checkpoint should reach 82.0% on k-NN eval and 83.5% on linear eval. + +The training code saves the weights of the teacher in the eval folder every 12500 iterations for evaluation. + +### Exact DINOv3 setup: training DINOv3 ViT-7B/16 + +DINOv3 ViT-7B/16 is trained on a private dataset. The training involves 3 stages: +- Pretraining +- Gram anchoring +- High resolution adaptation + +#### Pretraining + +Launch DINOV3 ViT-7B/16 pretraining on 32 nodes (256 GPUs) in a SLURM cluster environment with submitit. + +```shell +PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/train/train.py \ + --nodes 32 \ + --config-file dinov3/configs/train/dinov3_vit7b16_pretrain.yaml \ + --output-dir \ + train.dataset_path=:root=:extra= +``` + +#### Gram anchoring + +```shell +PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/train/train.py \ + --nodes 32 \ + --config-file dinov3/configs/train/dinov3_vit7b16_gram_anchor.yaml \ + --output-dir \ + train.dataset_path=:root=:extra= \ + gram.ckpt= +``` + +#### High-resolution adaptation + + +```shell +PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/train/train.py \ + --nodes 32 \ + --config-file dinov3/configs/train/dinov3_vit7b16_high_res_adapt.yaml \ + --output-dir \ + train.dataset_path=:root=:extra= \ + gram.ckpt= \ + student.resume_from_teacher_chkpt= +``` + +## Multi-distillation + +### Test setup: + +```shell +PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/train/train.py \ + --nodes 1 \ + --config-file dinov3/configs/train/multi_distillation_test.yaml \ + --output-dir \ + --multi-distillation \ + train.dataset_path=:root=:extra= +``` + +## Evaluation + +The training code regularly saves the teacher weights. In order to evaluate the model, run the following evaluation on a single node: + + +### Logistic regression classification on ImageNet-1k + +```shell +PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/eval/log_regression.py \ + model.config_file=/config.yaml \ + model.pretrained_weights=/teacher_checkpoint.pth \ + output_dir= \ + train.dataset=ImageNet:split=TRAIN:root=:extra= \ + eval.test_dataset=ImageNet:split=VAL:root=:extra= +``` + +### k-NN classification on ImageNet-1k + +```shell +PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/eval/knn.py \ + model.config_file=/config.yaml \ + model.pretrained_weights=/teacher_checkpoint.pth \ + output_dir= \ + train.dataset=ImageNet:split=TRAIN:root=:extra= \ + eval.test_dataset=ImageNet:split=VAL:root=:extra= +``` + +### Linear classification with data augmentation on ImageNet-1k + +```shell +PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/eval/linear.py \ + model.config_file=/config.yaml \ + model.pretrained_weights=/teacher_checkpoint.pth \ + output_dir= \ + train.dataset=ImageNet:split=TRAIN:root=:extra= \ + train.val_dataset=ImageNet:split=VAL:root=:extra= +``` + +### Linear segmentation with data augmentation on ADE20K + +```shell +PYTHONPATH=. python -m dinov3.run.submit dinov3/eval/segmentation/run.py \ +model.dino_hub=dinov3_vit7b16 \ +config=dinov3/eval/segmentation/configs/config-ade20k-linear-training.yaml \ +datasets.root= \ +--output-dir +``` + +After the job completes, you will find in the output path directory you specified +- `segmentation_config.yaml` that contains the config you trained the model with; +- `model_final.pth`, the final linear head checkpoint at the end of training; and +- `results-semantic-segmentation.csv` with the final metrics. + + +#### Linear depth estimation on NYUv2 Depth +```shell +PYTHONPATH=. python -m dinov3.run.submit dinov3/eval/depth/run.py \ + model.dino_hub=dinov3_vit7b16 \ + config=dinov3/eval/depth/configs/config-nyu.yaml \ + datasets.root= \ + --output-dir +``` + +After the job completes, you will find in the output path directory you specified +- `depth_config.yaml` that contains the config you trained the model with; +- `model_final.pth`, the final linear head checkpoint at the end of training; and +- `results-depth.csv` with the final metrics. + +### Text alignment on DINOv3 using dino.txt + +Text alignment can be done following the method from `dino.txt` aka [DINOv2 Meets Text](https://arxiv.org/abs/2412.16334). + +```shell +PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/eval/text/train_dinotxt.py \ + --nodes 4 \ + # An example config for text alignment is here: dinov3/eval/text/configs/dinov3_vitl_text.yaml \ + trainer_config_file="" \ + output-dir= +``` +Launching the above trains text alignment on 4 nodes with 8 gpus each (32 gpus in total). +Please note that the text alignment model in the DINOv3 paper was trained on a private dataset and here we have given an example config in ```dinov3/eval/text/configs/dinov3_vitl_text.yaml``` using ```CocoCaptions``` dataset for illustration purposes. +Please adapt the provided ```CocoCaptions``` dataset class, the dataset can be found [here](https://www.kaggle.com/datasets/nikhil7280/coco-image-caption) + + +## Canopy Height Maps v2 (CHMv2) + +John Brandt, Seungeun Yi, Jamie Tolan, Xinyuan Li, Peter Potapov, +Jessica Ertel, Justine Spore, Huy V. Vo, Michaël Ramamonjisoa, Patrick Labatut, +Piotr Bojanowski, Camille Couprie + +[ :scroll: [`Paper`](https://arxiv.org/abs/2603.06382)] [ :newspaper: [`Blog`](http://ai.meta.com/blog/world-resources-institute-dino-canopy-height-maps-v2)] + +### CHMv2 model loading (via PyTorch [Hub](https://docs.pytorch.org/docs/stable/hub.html)) + +:information_source: Please follow the link provided below to get access to the CHMv2 model weights: once accepted, an e-mail will be sent with the URL pointing to the available model weights. The URL can then be used to either: +- download the model weights to a local filesystem and point `torch.hub.load()` to these local weights via the `weights` parameters, or +- directly invoke `torch.hub.load()` to download and load a backbone from its URL. + +CHMv2 uses the DINOv3 ViT-L/16 satellite as the backbone, available after requesting access [here](https://ai.meta.com/resources/models-and-libraries/dinov3-downloads/). + +:warning: Please use `wget` instead of a web browser to download the weights. + +Download link: https://ai.meta.com/resources/models-and-libraries/chmv2-downloads/ + +```python +import torch +from dinov3.hub.backbones import Weights + +REPO_DIR = + +chmv2_model = torch.hub.load( + REPO_DIR, + 'dinov3_vitl16_chmv2', + source="local", + weights="", + backbone_weights=Weights.SAT493M, # or +) +``` + +Refer to this [notebook](notebooks/chmv2_inference.ipynb) for an example of how to use the DINOv3 + CHMv2 model. + +This [notebook](notebooks/chmv2_dataset_exploration.ipynb) can be used to download inference data from the existing global dataset stored on aws. + +### CHMv2 model loading (via Hugging Face [Transformers](https://huggingface.co/docs/transformers/)) + +The CHMv2 model is also available on [Hugging Face Hub](https://huggingface.co/facebook/dinov3-vitl16-chmv2-dpt-head) and supported via the Hugging Face [Transformers](https://huggingface.co/docs/transformers/index) library. Please refer to the corresponding documentation for usage, but below is a short example that demonstrates how to obtain canopy height predictions on a sample image. + +```python +from PIL import Image +import torch + +from transformers import AutoModelForDepthEstimation, AutoImageProcessor + +processor = AutoImageProcessor.from_pretrained("facebook/dinov3-vitl16-chmv2-dpt-head") +model = AutoModelForDepthEstimation.from_pretrained("facebook/dinov3-vitl16-chmv2-dpt-head") + +image = Image.open("image.tif") +inputs = processor(images=image, return_tensors="pt") + +with torch.no_grad(): + outputs = model(**inputs) + +depth = processor.post_process_depth_estimation( + outputs, target_sizes=[(image.height, image.width)] +)[0]["predicted_depth"] +``` + +## License + +DINOv3 code and model weights are released under the DINOv3 License. See [LICENSE.md](LICENSE.md) for additional details. + +## Contributing + +See [contributing](CONTRIBUTING.md) and the [code of conduct](CODE_OF_CONDUCT.md). + +## Citing DINOv3 + +If you find this repository useful, please consider giving a star :star: and citation :t-rex:: + +``` +@misc{simeoni2025dinov3, + title={{DINOv3}}, + author={Sim{\'e}oni, Oriane and Vo, Huy V. and Seitzer, Maximilian and Baldassarre, Federico and Oquab, Maxime and Jose, Cijo and Khalidov, Vasil and Szafraniec, Marc and Yi, Seungeun and Ramamonjisoa, Micha{\"e}l and Massa, Francisco and Haziza, Daniel and Wehrstedt, Luca and Wang, Jianyuan and Darcet, Timoth{\'e}e and Moutakanni, Th{\'e}o and Sentana, Leonel and Roberts, Claire and Vedaldi, Andrea and Tolan, Jamie and Brandt, John and Couprie, Camille and Mairal, Julien and J{\'e}gou, Herv{\'e} and Labatut, Patrick and Bojanowski, Piotr}, + year={2025}, + eprint={2508.10104}, + archivePrefix={arXiv}, + primaryClass={cs.CV}, + url={https://arxiv.org/abs/2508.10104}, +} +``` diff --git a/starVLA/dinov3/README_dinov3.md b/starVLA/dinov3/README_dinov3.md new file mode 100644 index 0000000000000000000000000000000000000000..317f71034cd615b36b9b7b741779750ba3bd55bd --- /dev/null +++ b/starVLA/dinov3/README_dinov3.md @@ -0,0 +1,882 @@ +:new: [2026-03-10] :fire: The [Canopy Height Maps v2 (CHMv2) model](https://arxiv.org/abs/2603.06382) and inference code are now available (more details on downloading the model weights and using the code [here](#canopy-height-maps-v2-chmv2)). The model weights are also available in [Hugging Face Hub](https://huggingface.co/facebook/dinov3-vitl16-chmv2-dpt-head) and [supported](https://github.com/huggingface/transformers/blob/main/docs/source/en/model_doc/chmv2.md) by the Hugging Face [Transformers](https://huggingface.co/docs/transformers/index) library. Building on our original high-resolution canopy height maps released in 2024, CHMv2 delivers substantial improvements in accuracy, detail, and global consistency by leveraging DINOv3. + +[2025-11-20] Distillation code and configurations for ConvNeXt backbones are now released! + +[2025-10-13] [Semantic segmentation](https://github.com/facebookresearch/dinov3?tab=readme-ov-file#linear-segmentation-with-data-augmentation-on-ade20k) (ADE20K) and [monocular depth estimation](https://github.com/facebookresearch/dinov3?tab=readme-ov-file#linear-depth-estimation-on-nyuv2-depth) (NYUv2-Depth) linear probing code are now released! + +[2025-09-17] DINOv3 backbones are now supported by the [PyTorch Image Models / timm](https://github.com/huggingface/pytorch-image-models/) library starting with version [1.0.20](https://github.com/huggingface/pytorch-image-models/releases/tag/v1.0.20) + +[2025-08-29] DINOv3 backbones are [supported](https://huggingface.co/docs/transformers/model_doc/dinov3) by released versions of the Hugging Face [Transformers](https://huggingface.co/docs/transformers/index) library starting with version [4.56.0](https://github.com/huggingface/transformers/releases/tag/v4.56.0) + +[2025-08-14] DINOv3 backbones are now available in [Hugging Face Hub](https://huggingface.co/collections/facebook/dinov3-68924841bd6b561778e31009) and [supported](https://huggingface.co/docs/transformers/model_doc/dinov3) by the [development](https://github.com/huggingface/transformers/) version of the Hugging Face [Transformers](https://huggingface.co/docs/transformers/index) library + +# DINOv3 🦖🦖🦖 + +**[Meta AI Research, FAIR](https://ai.meta.com/research/)** + +Oriane Siméoni, Huy V. Vo, Maximilian Seitzer, Federico Baldassarre, Maxime Oquab, +Cijo Jose, Vasil Khalidov, Marc Szafraniec, Seungeun Yi, Michaël Ramamonjisoa, +Francisco Massa, Daniel Haziza, Luca Wehrstedt, Jianyuan Wang, +Timothée Darcet, Théo Moutakanni, Leonel Sentana, Claire Roberts, +Andrea Vedaldi, Jamie Tolan, John Brandt, Camille Couprie, +Julien Mairal, Hervé Jégou, Patrick Labatut, Piotr Bojanowski + +[ :scroll: [`Paper`](https://arxiv.org/abs/2508.10104)] [ :newspaper: [`Blog`](https://ai.meta.com/blog/dinov3-self-supervised-vision-model/)] [ :globe_with_meridians: [`Website`](https://ai.meta.com/dinov3/)] [ :book: [`BibTeX`](#citing-dinov3)] + +Reference PyTorch implementation and models for DINOv3. For details, see the **[DINOv3](https://arxiv.org/abs/2508.10104)** paper. + +## Overview + + + + + High-resolution dense features.We visualize the cosine similarity maps obtained with DINOv3 output features between the patches marked with a red cross and all other patches. + + + + +An extended family of versatile vision foundation models producing high-quality dense features and achieving outstanding performance on various vision tasks including outperforming the specialized state of the art across a broad range of settings, without fine-tuning + +## Pretrained models + +:information_source: Please follow the link provided below to get access to all the model weights: once accepted, an e-mail will be sent with the complete list of URLs pointing to all the available model weights (both backbones and adapters). These URLs can then be used to either: +- download the model or adapter weights to a local filesystem and point `torch.hub.load()` to these local weights via the `weights` or `backbone_weights` parameters, or +- directly invoke `torch.hub.load()` to download and load a backbone or an adapter from its URL via also the `weights` or `backbone_weights` parameters. + +See the example code snippets below. + +:warning: Please use `wget` instead of a web browser to download the weights. + +ViT models pretrained on web dataset (LVD-1689M): + + + + Model + Parameters + PretrainingDataset + Download + + + + + ViT-S/16 distilled + 21M + LVD-1689M + [link] + + + ViT-S+/16 distilled + 29M + LVD-1689M + [link] + + + ViT-B/16 distilled + 86M + LVD-1689M + [link] + + + ViT-L/16 distilled + 300M + LVD-1689M + [link] + + + ViT-H+/16 distilled + 840M + LVD-1689M + [link] + + + ViT-7B/16 + 6,716M + LVD-1689M + [link] + + + + +ConvNeXt models pretrained on web dataset (LVD-1689M): + + + + Model + Parameters + PretrainingDataset + Download + + + + + ConvNeXt Tiny + 29M + LVD-1689M + [link] + + + ConvNeXt Small + 50M + LVD-1689M + [link] + + + ConvNeXt Base + 89M + LVD-1689M + [link] + + + ConvNeXt Large + 198M + LVD-1689M + [link] + + + + +ViT models pretrained on satellite dataset (SAT-493M): + + + + Model + Parameters + PretrainingDataset + Download + + + + + ViT-L/16 distilled + 300M + SAT-493M + [link] + + + ViT-7B/16 + 6,716M + SAT-493M + [link] + + + + + +### Pretrained backbones (via PyTorch [Hub](https://docs.pytorch.org/docs/stable/hub.html)) + +Please follow the instructions [here](https://pytorch.org/get-started/locally/) to install PyTorch (the only required dependency for loading the model). Installing PyTorch with CUDA support is strongly recommended. + +```python +import torch + +REPO_DIR = + +# DINOv3 ViT models pretrained on web images +dinov3_vits16 = torch.hub.load(REPO_DIR, 'dinov3_vits16', source='local', weights=) +dinov3_vits16plus = torch.hub.load(REPO_DIR, 'dinov3_vits16plus', source='local', weights=) +dinov3_vitb16 = torch.hub.load(REPO_DIR, 'dinov3_vitb16', source='local', weights=) +dinov3_vitl16 = torch.hub.load(REPO_DIR, 'dinov3_vitl16', source='local', weights=) +dinov3_vith16plus = torch.hub.load(REPO_DIR, 'dinov3_vith16plus', source='local', weights=) +dinov3_vit7b16 = torch.hub.load(REPO_DIR, 'dinov3_vit7b16', source='local', weights=) + +# DINOv3 ConvNeXt models pretrained on web images +dinov3_convnext_tiny = torch.hub.load(REPO_DIR, 'dinov3_convnext_tiny', source='local', weights=) +dinov3_convnext_small = torch.hub.load(REPO_DIR, 'dinov3_convnext_small', source='local', weights=) +dinov3_convnext_base = torch.hub.load(REPO_DIR, 'dinov3_convnext_base', source='local', weights=) +dinov3_convnext_large = torch.hub.load(REPO_DIR, 'dinov3_convnext_large', source='local', weights=) + +# DINOv3 ViT models pretrained on satellite imagery +dinov3_vitl16 = torch.hub.load(REPO_DIR, 'dinov3_vitl16', source='local', weights=) +dinov3_vit7b16 = torch.hub.load(REPO_DIR, 'dinov3_vit7b16', source='local', weights=) +``` + +### Pretrained backbones (via Hugging Face [Transformers](https://huggingface.co/docs/transformers/)) + +All the backbones are available in the [DINOv3](https://huggingface.co/collections/facebook/dinov3-68924841bd6b561778e31009) collection on Hugging Face Hub and supported via the Hugging Face [Transformers](https://huggingface.co/docs/transformers/index) library (with released packages from version 4.56.0). Please refer to the corresponding documentation for usage, but below is a short example that demonstrates how to obtain an image embedding with either [Pipeline] or the [AutoModel] class. + +```python +from transformers import pipeline +from transformers.image_utils import load_image + +url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg" +image = load_image(url) + +feature_extractor = pipeline( + model="facebook/dinov3-convnext-tiny-pretrain-lvd1689m", + task="image-feature-extraction", +) +features = feature_extractor(image) +``` + +```python +import torch +from transformers import AutoImageProcessor, AutoModel +from transformers.image_utils import load_image + +url = "http://images.cocodataset.org/val2017/000000039769.jpg" +image = load_image(url) + +pretrained_model_name = "facebook/dinov3-convnext-tiny-pretrain-lvd1689m" +processor = AutoImageProcessor.from_pretrained(pretrained_model_name) +model = AutoModel.from_pretrained( + pretrained_model_name, + device_map="auto", +) + +inputs = processor(images=image, return_tensors="pt").to(model.device) +with torch.inference_mode(): + outputs = model(**inputs) + +pooled_output = outputs.pooler_output +print("Pooled output shape:", pooled_output.shape) +``` + +where `model` and `pretrained_model_name` above can be one of: +- `facebook/dinov3-vits16-pretrain-lvd1689m` +- `facebook/dinov3-vits16plus-pretrain-lvd1689m` +- `facebook/dinov3-vitb16-pretrain-lvd1689m` +- `facebook/dinov3-vitl16-pretrain-lvd1689m` +- `facebook/dinov3-vith16plus-pretrain-lvd1689m` +- `facebook/dinov3-vit7b16-pretrain-lvd1689m` +- `facebook/dinov3-convnext-base-pretrain-lvd1689m` +- `facebook/dinov3-convnext-large-pretrain-lvd1689m` +- `facebook/dinov3-convnext-small-pretrain-lvd1689m` +- `facebook/dinov3-convnext-tiny-pretrain-lvd1689m` +- `facebook/dinov3-vitl16-pretrain-sat493m` +- `facebook/dinov3-vit7b16-pretrain-sat493m` + +### Image transforms + +For models using the LVD-1689M weights (pretrained on web images), please use the following transform (standard ImageNet evaluation transform): + +```python +import torchvision +from torchvision.transforms import v2 + +def make_transform(resize_size: int = 256): + to_tensor = v2.ToImage() + resize = v2.Resize((resize_size, resize_size), antialias=True) + to_float = v2.ToDtype(torch.float32, scale=True) + normalize = v2.Normalize( + mean=(0.485, 0.456, 0.406), + std=(0.229, 0.224, 0.225), + ) + return v2.Compose([to_tensor, resize, to_float, normalize]) +``` + + +For models using the SAT-493M weights (pretrained on satellite imagery), please use the following transform: + + +```python +import torchvision +from torchvision.transforms import v2 + +def make_transform(resize_size: int = 256): + to_tensor = v2.ToImage() + resize = v2.Resize((resize_size, resize_size), antialias=True) + to_float = v2.ToDtype(torch.float32, scale=True) + normalize = v2.Normalize( + mean=(0.430, 0.411, 0.296), + std=(0.213, 0.156, 0.143), + ) + return v2.Compose([to_tensor, resize, to_float, normalize]) +``` + +### Pretrained heads - Image classification + + + + + Backbone + PretrainingDataset + HeadDataset + Download + + + + + ViT-7B/16 + LVD-1689M + ImageNet + [link] + + + + + +The (full) classifier models can be loaded via PyTorch Hub: + +```python +import torch + +# DINOv3 +dinov3_vit7b16_lc = torch.hub.load(REPO_DIR, 'dinov3_vit7b16_lc', source="local", weights=, backbone_weights=) + +``` + +### Pretrained heads - Depther trained on SYNTHMIX dataset + + + + + Backbone + PretrainingDataset + HeadDataset + Download + + + + + ViT-7B/16 + LVD-1689M + SYNTHMIX + [link] + + + + + +```python +depther = torch.hub.load(REPO_DIR, 'dinov3_vit7b16_dd', source="local", weights=, backbone_weights=) +``` + +Full example code of depther on an image + +```python +from PIL import Image +import torch +from torchvision.transforms import v2 +import matplotlib.pyplot as plt +from matplotlib import colormaps + +def get_img(): + import requests + url = "http://images.cocodataset.org/val2017/000000039769.jpg" + image = Image.open(requests.get(url, stream=True).raw).convert("RGB") + return image + +def make_transform(resize_size: int | list[int] = 768): + to_tensor = v2.ToImage() + resize = v2.Resize((resize_size, resize_size), antialias=True) + to_float = v2.ToDtype(torch.float32, scale=True) + normalize = v2.Normalize( + mean=(0.485, 0.456, 0.406), + std=(0.229, 0.224, 0.225), + ) + return v2.Compose([to_tensor, resize, to_float, normalize]) + +depther = torch.hub.load(REPO_DIR, 'dinov3_vit7b16_dd', source="local", weights=, backbone_weights=) + +img_size = 1024 +img = get_img() +transform = make_transform(img_size) +with torch.inference_mode(): + with torch.autocast('cuda', dtype=torch.bfloat16): + batch_img = transform(img)[None] + batch_img = batch_img + depths = depther(batch_img) + +plt.figure(figsize=(12, 6)) +plt.subplot(121) +plt.imshow(img) +plt.axis("off") +plt.subplot(122) +plt.imshow(depths[0,0].cpu(), cmap=colormaps["Spectral"]) +plt.axis("off") + +``` + +#### Reproduce paper results + +Make sure the NYU dataset is setup following [this](DATASETS.md#depth-estimation-on-nyu). + +Launch the following to reproduce our paper's depth estimation results on NYUv2 with the pretrained Depther trained on SYNTHMIX: + +```shell +PYTHONPATH=. python -m dinov3.run.submit dinov3/eval/depth/run.py \ +config=dinov3/eval/depth/configs/config-nyu-synthmix-dpt-inference.yaml \ +datasets.root= \ +load_from=dinov3_vit7b16_dd \ +--output-dir +``` + +Notes: +- if you want to launch the code without dinov3.run.submit, you can do so using python directly or torchrun: + +```shell +PYTHONPATH=. python dinov3/eval/depth/run.py \ +config=dinov3/eval/depth/configs/config-nyu-synthmix-dpt-inference.yaml \ +datasets.root= \ +load_from=dinov3_vit7b16_dd \ +output_dir= +``` + +- One can also save prediction results using `result_config.save_results=true`. + + +### Pretrained heads - Detector trained on COCO2017 dataset + + + + + Backbone + PretrainingDataset + HeadDataset + Download + + + + + ViT-7B/16 + LVD-1689M + COCO2017 + [link] + + + + + +```python +detector = torch.hub.load(REPO_DIR, 'dinov3_vit7b16_de', source="local", weights=, backbone_weights=) +``` + +### Pretrained heads - Segmentor trained on ADE20K dataset + + + + + Backbone + PretrainingDataset + HeadDataset + Download + + + + + ViT-7B/16 + LVD-1689M + ADE20K + [link] + + + + +```python +segmentor = torch.hub.load(REPO_DIR, 'dinov3_vit7b16_ms', source="local", weights=, backbone_weights=) +``` + +Example command to run a full inference on ADE20K with the provided segmentor (ViT-7B + M2F): + +```shell +PYTHONPATH=. python -m dinov3.run.submit dinov3/eval/segmentation/run.py \ +config=dinov3/eval/segmentation/configs/config-ade20k-m2f-inference.yaml \ +datasets.root= \ +load_from=dinov3_vit7b16_ms \ +--output-dir +``` + +Full example code of segmentator on an image + +```python +import sys +sys.path.append(REPO_DIR) + +from PIL import Image +import torch +from torchvision import transforms +import matplotlib.pyplot as plt +from matplotlib import colormaps +from functools import partial +from dinov3.eval.segmentation.inference import make_inference + + +def get_img(): + import requests + url = "http://images.cocodataset.org/val2017/000000039769.jpg" + image = Image.open(requests.get(url, stream=True).raw).convert("RGB") + return image + +def make_transform(resize_size: int | list[int] = 768): + to_tensor = v2.ToImage() + resize = v2.Resize((resize_size, resize_size), antialias=True) + to_float = v2.ToDtype(torch.float32, scale=True) + normalize = v2.Normalize( + mean=(0.485, 0.456, 0.406), + std=(0.229, 0.224, 0.225), + ) + return v2.Compose([to_tensor, resize, to_float, normalize]) + +segmentor = torch.hub.load(REPO_DIR, 'dinov3_vit7b16_ms', source="local", weights=, backbone_weights=) + +img_size = 896 +img = get_img() +transform = make_transform(img_size) +with torch.inference_mode(): + with torch.autocast('cuda', dtype=torch.bfloat16): + batch_img = transform(img)[None] + pred_vit7b = segmentor(batch_img) # raw predictions + # actual segmentation map + segmentation_map_vit7b = make_inference( + batch_img, + segmentor, + inference_mode="slide", + decoder_head_type="m2f", + rescale_to=(img.size[-1], img.size[-2]), + n_output_channels=150, + crop_size=(img_size, img_size), + stride=(img_size, img_size), + output_activation=partial(torch.nn.functional.softmax, dim=1), + ).argmax(dim=1, keepdim=True) +plt.figure(figsize=(12, 6)) +plt.subplot(121) +plt.imshow(img) +plt.axis("off") +plt.subplot(122) +plt.imshow(segmentation_map_vit7b[0,0].cpu(), cmap=colormaps["Spectral"]) +plt.axis("off") +``` + + + + +### Pretrained heads - Zero-shot tasks with `dino.txt` + + + + + Backbone + Download + + + + + ViT-L/16 distilled + + [link], + vocabulary, + vocabulary license + + + + + +The (full) dino.txt model can be loaded via PyTorch Hub: + +```python +import torch +# DINOv3 +dinov3_vitl16_dinotxt_tet1280d20h24l, tokenizer = torch.hub.load(REPO_DIR, 'dinov3_vitl16_dinotxt_tet1280d20h24l', weights=, backbone_weights=) +``` + + +## Installation + +The training and evaluation code requires PyTorch version >= 2.7.1 as well as a few other 3rd party packages. Note that the code has only been tested with the specified versions and also expects a Linux environment. To setup all the required dependencies for training and evaluation, please follow the instructions below: + +*[micromamba](https://mamba.readthedocs.io/en/latest/user_guide/micromamba.html)* **(Recommended)** - Clone the repository and then create and activate a `dinov3` conda environment using the provided environment definition: + +```shell +micromamba env create -f conda.yaml +micromamba activate dinov3 +``` + +## Getting started + +Several notebooks are provided to get started applying DINOv3: +- [PCA of patch features](notebooks/pca.ipynb): display the PCA of DINOv3 patch features on a foreground object (rainbow visualizations from the paper) [[Run in Google Colab]](https://colab.research.google.com/github/facebookresearch/dinov3/blob/main/notebooks/pca.ipynb) +- [Foreground segmentation](notebooks/foreground_segmentation.ipynb): train a linear foreground segmentation model based on DINOv3 features [[Run in Google Colab]](https://colab.research.google.com/github/facebookresearch/dinov3/blob/main/notebooks/foreground_segmentation.ipynb) +- [Dense and sparse matching](notebooks/dense_sparse_matching.ipynb): match patches from objects on two different images based on DINOv3 features [[Run in Google Colab]](https://colab.research.google.com/github/facebookresearch/dinov3/blob/main/notebooks/dense_sparse_matching.ipynb) +- [Segmentation tracking](notebooks/segmentation_tracking.ipynb): video segmentation tracking using a non-parametric method based on DINOv3 features [[Run in Google Colab]](https://colab.research.google.com/github/facebookresearch/dinov3/blob/main/notebooks/segmentation_tracking.ipynb) +- [Zero-shot segmentation with DINOv3-based dino.txt](notebooks/dinotxt_segmentation_inference.ipynb): compute the open-vocabulary segmentation results with dino.txt strategy. + +## Data preparation + +### ImageNet-1k + +The root directory of the dataset should hold the following contents: + +- `/test/ILSVRC2012_test_00000001.JPEG` +- `/test/[..]` +- `/test/ILSVRC2012_test_00100000.JPEG` +- `/train/n01440764/n01440764_10026.JPEG` +- `/train/[...]` +- `/train/n15075141/n15075141_9993.JPEG` +- `/val/n01440764/ILSVRC2012_val_00000293.JPEG` +- `/val/[...]` +- `/val/n15075141/ILSVRC2012_val_00049174.JPEG` +- `/labels.txt` + +The provided dataset implementation expects a few additional metadata files to be present under the extra directory: + +- `/class-ids-TRAIN.npy` +- `/class-ids-VAL.npy` +- `/class-names-TRAIN.npy` +- `/class-names-VAL.npy` +- `/entries-TEST.npy` +- `/entries-TRAIN.npy` +- `/entries-VAL.npy` + +These metadata files can be generated (once) with the following lines of Python code: + +```python +from dinov3.data.datasets import ImageNet + +for split in ImageNet.Split: + dataset = ImageNet(split=split, root="", extra="") + dataset.dump_extra() +``` + +Note that the root and extra directories do not have to be distinct directories. + +### ImageNet-22k + +Please adapt the [dataset class](dinov3/data/datasets/image_net_22k.py) to match your local setup. + + + +:warning: To execute the commands provided in the next sections for training and evaluation, the `dinov3` package should be included in the Python module search path, i.e. simply prefix the command to run with `PYTHONPATH=.`. + +## Training + +### Fast setup: training DINOv3 ViT-L/16 on ImageNet-1k + +Run DINOv3 pre-training on 4 H100-80GB nodes (32 GPUs) in a SLURM cluster environment with submitit: + +```shell + PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/train/train.py \ + --nodes 4 \ + --config-file dinov3/configs/train/vitl_im1k_lin834.yaml \ + --output-dir \ + train.dataset_path=ImageNet22k:root=:extra= +``` +Training time is approximately 14 hours and the resulting checkpoint should reach 82.0% on k-NN eval and 83.5% on linear eval. + +The training code saves the weights of the teacher in the eval folder every 12500 iterations for evaluation. + +### Exact DINOv3 setup: training DINOv3 ViT-7B/16 + +DINOv3 ViT-7B/16 is trained on a private dataset. The training involves 3 stages: +- Pretraining +- Gram anchoring +- High resolution adaptation + +#### Pretraining + +Launch DINOV3 ViT-7B/16 pretraining on 32 nodes (256 GPUs) in a SLURM cluster environment with submitit. + +```shell +PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/train/train.py \ + --nodes 32 \ + --config-file dinov3/configs/train/dinov3_vit7b16_pretrain.yaml \ + --output-dir \ + train.dataset_path=:root=:extra= +``` + +#### Gram anchoring + +```shell +PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/train/train.py \ + --nodes 32 \ + --config-file dinov3/configs/train/dinov3_vit7b16_gram_anchor.yaml \ + --output-dir \ + train.dataset_path=:root=:extra= \ + gram.ckpt= +``` + +#### High-resolution adaptation + + +```shell +PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/train/train.py \ + --nodes 32 \ + --config-file dinov3/configs/train/dinov3_vit7b16_high_res_adapt.yaml \ + --output-dir \ + train.dataset_path=:root=:extra= \ + gram.ckpt= \ + student.resume_from_teacher_chkpt= +``` + +## Multi-distillation + +### Test setup: + +```shell +PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/train/train.py \ + --nodes 1 \ + --config-file dinov3/configs/train/multi_distillation_test.yaml \ + --output-dir \ + --multi-distillation \ + train.dataset_path=:root=:extra= +``` + +## Evaluation + +The training code regularly saves the teacher weights. In order to evaluate the model, run the following evaluation on a single node: + + +### Logistic regression classification on ImageNet-1k + +```shell +PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/eval/log_regression.py \ + model.config_file=/config.yaml \ + model.pretrained_weights=/teacher_checkpoint.pth \ + output_dir= \ + train.dataset=ImageNet:split=TRAIN:root=:extra= \ + eval.test_dataset=ImageNet:split=VAL:root=:extra= +``` + +### k-NN classification on ImageNet-1k + +```shell +PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/eval/knn.py \ + model.config_file=/config.yaml \ + model.pretrained_weights=/teacher_checkpoint.pth \ + output_dir= \ + train.dataset=ImageNet:split=TRAIN:root=:extra= \ + eval.test_dataset=ImageNet:split=VAL:root=:extra= +``` + +### Linear classification with data augmentation on ImageNet-1k + +```shell +PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/eval/linear.py \ + model.config_file=/config.yaml \ + model.pretrained_weights=/teacher_checkpoint.pth \ + output_dir= \ + train.dataset=ImageNet:split=TRAIN:root=:extra= \ + train.val_dataset=ImageNet:split=VAL:root=:extra= +``` + +### Linear segmentation with data augmentation on ADE20K + +```shell +PYTHONPATH=. python -m dinov3.run.submit dinov3/eval/segmentation/run.py \ +model.dino_hub=dinov3_vit7b16 \ +config=dinov3/eval/segmentation/configs/config-ade20k-linear-training.yaml \ +datasets.root= \ +--output-dir +``` + +After the job completes, you will find in the output path directory you specified +- `segmentation_config.yaml` that contains the config you trained the model with; +- `model_final.pth`, the final linear head checkpoint at the end of training; and +- `results-semantic-segmentation.csv` with the final metrics. + + +#### Linear depth estimation on NYUv2 Depth +```shell +PYTHONPATH=. python -m dinov3.run.submit dinov3/eval/depth/run.py \ + model.dino_hub=dinov3_vit7b16 \ + config=dinov3/eval/depth/configs/config-nyu.yaml \ + datasets.root= \ + --output-dir +``` + +After the job completes, you will find in the output path directory you specified +- `depth_config.yaml` that contains the config you trained the model with; +- `model_final.pth`, the final linear head checkpoint at the end of training; and +- `results-depth.csv` with the final metrics. + +### Text alignment on DINOv3 using dino.txt + +Text alignment can be done following the method from `dino.txt` aka [DINOv2 Meets Text](https://arxiv.org/abs/2412.16334). + +```shell +PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/eval/text/train_dinotxt.py \ + --nodes 4 \ + # An example config for text alignment is here: dinov3/eval/text/configs/dinov3_vitl_text.yaml \ + trainer_config_file="" \ + output-dir= +``` +Launching the above trains text alignment on 4 nodes with 8 gpus each (32 gpus in total). +Please note that the text alignment model in the DINOv3 paper was trained on a private dataset and here we have given an example config in ```dinov3/eval/text/configs/dinov3_vitl_text.yaml``` using ```CocoCaptions``` dataset for illustration purposes. +Please adapt the provided ```CocoCaptions``` dataset class, the dataset can be found [here](https://www.kaggle.com/datasets/nikhil7280/coco-image-caption) + + +## Canopy Height Maps v2 (CHMv2) + +John Brandt, Seungeun Yi, Jamie Tolan, Xinyuan Li, Peter Potapov, +Jessica Ertel, Justine Spore, Huy V. Vo, Michaël Ramamonjisoa, Patrick Labatut, +Piotr Bojanowski, Camille Couprie + +[ :scroll: [`Paper`](https://arxiv.org/abs/2603.06382)] [ :newspaper: [`Blog`](http://ai.meta.com/blog/world-resources-institute-dino-canopy-height-maps-v2)] + +### CHMv2 model loading (via PyTorch [Hub](https://docs.pytorch.org/docs/stable/hub.html)) + +:information_source: Please follow the link provided below to get access to the CHMv2 model weights: once accepted, an e-mail will be sent with the URL pointing to the available model weights. The URL can then be used to either: +- download the model weights to a local filesystem and point `torch.hub.load()` to these local weights via the `weights` parameters, or +- directly invoke `torch.hub.load()` to download and load a backbone from its URL. + +CHMv2 uses the DINOv3 ViT-L/16 satellite as the backbone, available after requesting access [here](https://ai.meta.com/resources/models-and-libraries/dinov3-downloads/). + +:warning: Please use `wget` instead of a web browser to download the weights. + +Download link: https://ai.meta.com/resources/models-and-libraries/chmv2-downloads/ + +```python +import torch +from dinov3.hub.backbones import Weights + +REPO_DIR = + +chmv2_model = torch.hub.load( + REPO_DIR, + 'dinov3_vitl16_chmv2', + source="local", + weights="", + backbone_weights=Weights.SAT493M, # or +) +``` + +Refer to this [notebook](notebooks/chmv2_inference.ipynb) for an example of how to use the DINOv3 + CHMv2 model. + +This [notebook](notebooks/chmv2_dataset_exploration.ipynb) can be used to download inference data from the existing global dataset stored on aws. + +### CHMv2 model loading (via Hugging Face [Transformers](https://huggingface.co/docs/transformers/)) + +The CHMv2 model is also available on [Hugging Face Hub](https://huggingface.co/facebook/dinov3-vitl16-chmv2-dpt-head) and supported via the Hugging Face [Transformers](https://huggingface.co/docs/transformers/index) library. Please refer to the corresponding documentation for usage, but below is a short example that demonstrates how to obtain canopy height predictions on a sample image. + +```python +from PIL import Image +import torch + +from transformers import AutoModelForDepthEstimation, AutoImageProcessor + +processor = AutoImageProcessor.from_pretrained("facebook/dinov3-vitl16-chmv2-dpt-head") +model = AutoModelForDepthEstimation.from_pretrained("facebook/dinov3-vitl16-chmv2-dpt-head") + +image = Image.open("image.tif") +inputs = processor(images=image, return_tensors="pt") + +with torch.no_grad(): + outputs = model(**inputs) + +depth = processor.post_process_depth_estimation( + outputs, target_sizes=[(image.height, image.width)] +)[0]["predicted_depth"] +``` + +## License + +DINOv3 code and model weights are released under the DINOv3 License. See [LICENSE.md](LICENSE.md) for additional details. + +## Contributing + +See [contributing](CONTRIBUTING.md) and the [code of conduct](CODE_OF_CONDUCT.md). + +## Citing DINOv3 + +If you find this repository useful, please consider giving a star :star: and citation :t-rex:: + +``` +@misc{simeoni2025dinov3, + title={{DINOv3}}, + author={Sim{\'e}oni, Oriane and Vo, Huy V. and Seitzer, Maximilian and Baldassarre, Federico and Oquab, Maxime and Jose, Cijo and Khalidov, Vasil and Szafraniec, Marc and Yi, Seungeun and Ramamonjisoa, Micha{\"e}l and Massa, Francisco and Haziza, Daniel and Wehrstedt, Luca and Wang, Jianyuan and Darcet, Timoth{\'e}e and Moutakanni, Th{\'e}o and Sentana, Leonel and Roberts, Claire and Vedaldi, Andrea and Tolan, Jamie and Brandt, John and Couprie, Camille and Mairal, Julien and J{\'e}gou, Herv{\'e} and Labatut, Patrick and Bojanowski, Piotr}, + year={2025}, + eprint={2508.10104}, + archivePrefix={arXiv}, + primaryClass={cs.CV}, + url={https://arxiv.org/abs/2508.10104}, +} +``` diff --git a/starVLA/dinov3/conda.yaml b/starVLA/dinov3/conda.yaml new file mode 100644 index 0000000000000000000000000000000000000000..db4c17be5c918075002b11c48abbef4a9d3043cd --- /dev/null +++ b/starVLA/dinov3/conda.yaml @@ -0,0 +1,23 @@ +name: dinov3 +channels: + - defaults + - conda-forge +dependencies: + - python=3.11 + - omegaconf + - pip + - pip: + - ftfy # needed for dino.txt + - iopath + - omegaconf + - pandas + - regex # needed for dino.txt + - pandas + - scikit-learn + - scikit-learn-intelex + - submitit + - termcolor + - torch + - torchvision + - torchmetrics + diff --git a/starVLA/dinov3/dinov3/__init__.py b/starVLA/dinov3/dinov3/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b70f615df55246ea150f0c76e02b0b8b98d16b2b --- /dev/null +++ b/starVLA/dinov3/dinov3/__init__.py @@ -0,0 +1,6 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +__version__ = "0.0.1" diff --git a/starVLA/dinov3/dinov3/checkpointer/__init__.py b/starVLA/dinov3/dinov3/checkpointer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..120712ccd2ec68848a027ca2a54b662f4e109205 --- /dev/null +++ b/starVLA/dinov3/dinov3/checkpointer/__init__.py @@ -0,0 +1,18 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +from .checkpointer import ( + CheckpointRetentionPolicy, + cleanup_checkpoint, + find_all_checkpoints, + find_latest_checkpoint, + init_fsdp_model_from_checkpoint, + init_model_from_checkpoint_for_evals, + keep_checkpoint_copy, + keep_last_n_checkpoints, + load_checkpoint, + register_dont_save_hooks, + save_checkpoint, +) diff --git a/starVLA/dinov3/dinov3/checkpointer/checkpointer.py b/starVLA/dinov3/dinov3/checkpointer/checkpointer.py new file mode 100644 index 0000000000000000000000000000000000000000..7a984110c68be859f5612be5d290bf27d5a77a55 --- /dev/null +++ b/starVLA/dinov3/dinov3/checkpointer/checkpointer.py @@ -0,0 +1,352 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +""" +Suggested file structure: + +output_dir/ +|-- ckpt/ +| |-- 0/ +| |-- 99/ +| |-- 199/ +| |-- 199_keep/ +| |-- 299/ +| `-- ... +`-- eval/ + `-- 0/ + `-- 99/ + `-- ckpt/ + +Distributed checkpointer docs: +- https://pytorch.org/tutorials/recipes/distributed_checkpoint_recipe.html +- https://pytorch.org/docs/stable/distributed.checkpoint.html +""" + +import logging +import shutil +import subprocess +import tempfile +from enum import Enum +from pathlib import Path +from typing import List, Sequence, Set + +import torch +import torch.distributed as dist +import torch.distributed.checkpoint as dcp +import torch.distributed.checkpoint.filesystem as dcpfs +import torch.distributed.checkpoint.state_dict as dcpsd +from torch.distributed.checkpoint.stateful import Stateful + +logger = logging.getLogger("dinov3") + + +class CheckpointRetentionPolicy(Enum): + ALL = "all" # keep all checkpoints + BEST = "best" + LAST = "last" + LAST_AND_BEST = "last_and_best" + NONE = "none" # do not keep any checkpoints + + @property + def keep_filters(self) -> Set[str]: + """Files that match these patterns are not deleted by cleanup""" + if self == CheckpointRetentionPolicy.LAST: + return set(["final"]) + if self == CheckpointRetentionPolicy.BEST: + return set(["best"]) + if self == CheckpointRetentionPolicy.LAST_AND_BEST: + return set(["final", "best"]) + if self == CheckpointRetentionPolicy.ALL: + return set() + return set() + + @property + def max_to_keep(self) -> int | None: + """ + maximum "periodic" checkpoints to keep concurrently, ie. saved with `step` and not `save`. `None` for keep all + """ + if self == CheckpointRetentionPolicy.ALL: + return None + return 1 + + +def save_checkpoint( + ckpt_dir: str | Path, # output_dir/ckpt/199 + *, + iteration: int | str, + model: torch.nn.Module, + optimizer: torch.optim.Optimizer | None = None, + overwrite: bool = True, + process_group: dist.ProcessGroup = None, + **others: Stateful, +): + """Save a plain/DDP/FSDP/FSDP2 model, its optimizer, an integer iteration and other stateful objects.""" + rank = torch.distributed.get_rank(group=process_group) + + # Rank 0 checks if the checkpoint directory exists, but all ranks need to know if if exists, + # so they can raise an error when overwrite is False. If overwrite is True, rank 0 will delete it + # and other ranks wait for the deletion to finish. + ckpt_dir = Path(ckpt_dir) + ckpt_dir_exists = [ckpt_dir.exists() if rank == 0 else None] + src_rank = 0 + if process_group is not None: + src_rank = torch.distributed.get_global_rank(group=process_group, group_rank=0) + torch.distributed.broadcast_object_list(ckpt_dir_exists, src=src_rank, group=process_group) + ckpt_dir_exists = ckpt_dir_exists[0] + if ckpt_dir_exists: + if overwrite: + if rank == 0: + if ckpt_dir.is_dir(): + shutil.rmtree(ckpt_dir) + else: + ckpt_dir.unlink() + logger.info(f"Deleted: {ckpt_dir}") + torch.distributed.barrier(group=process_group) + else: + raise RuntimeError(f"Checkpoint already exists: {ckpt_dir}") + + # Rank 0 creates a temporary directory for the checkpoint and broadcasts the name to all ranks. + ckpt_dir.parent.mkdir(parents=True, exist_ok=True) + ckpt_dir_tmp = [tempfile.mkdtemp(dir=ckpt_dir.parent, prefix=ckpt_dir.name) if rank == 0 else None] + torch.distributed.broadcast_object_list(ckpt_dir_tmp, src=src_rank, group=process_group) + ckpt_dir_tmp = Path(ckpt_dir_tmp[0]) + + to_save = {"iteration": iteration} + to_save["model"] = dcpsd.get_model_state_dict(model) + if optimizer is not None: + to_save["optimizer"] = dcpsd.get_optimizer_state_dict(model, optimizer) + to_save.update(others) + dcp.save( + to_save, + storage_writer=dcpfs.FileSystemWriter(ckpt_dir_tmp), + process_group=process_group, + ) + + # Rank 0 renames the temporary directory to the final checkpoint directory. All ranks wait for the rename. + if rank == 0: + ckpt_dir_tmp.rename(ckpt_dir) + torch.distributed.barrier() + + logger.info(f"Saved: {ckpt_dir}") + + +def load_checkpoint( + ckpt_dir: str | Path, # output_dir/ckpt/199 + *, + model: torch.nn.Module, + optimizer: torch.optim.Optimizer | None = None, + strict_loading: bool = True, + process_group: dist.ProcessGroup = None, + **others: Stateful, +) -> int | None: + """ + Load a plain/DDP/FSDP/FSDP2 model, its optimizer, an integer iteration and other stateful objects. + Can you take a checkpoint saved on N ranks and load it on M ranks? Sure you can! + Activation checkpointing and torch-compile can also be different between save and load, no problem. + """ + ckpt_dir = Path(ckpt_dir) + to_load = {"iteration": None} + to_load["model"] = dcpsd.get_model_state_dict(model) + if optimizer is not None: + to_load["optimizer"] = dcpsd.get_optimizer_state_dict(model, optimizer) + to_load.update(others) + dcp.load( + to_load, + storage_reader=dcpfs.FileSystemReader(ckpt_dir), + planner=dcp.default_planner.DefaultLoadPlanner(allow_partial_load=not strict_loading), + process_group=process_group, + ) + iteration = to_load["iteration"] + dcpsd.set_model_state_dict(model, to_load["model"]) + if optimizer is not None: + dcpsd.set_optimizer_state_dict(model, optimizer, to_load["optimizer"]) + logger.info(f"Loaded: {ckpt_dir}") + return iteration + + +def register_dont_save_hooks(module: torch.nn.Module, dont_save: Sequence[str]): + """ + Registers save/load state dict hooks such that the weights in `dont_save` are not persisted in the checkpoint. + + Typical use case: a classification model composed of a frozen backbone and a trainable head. + If the frozen backbone is loaded from torch hub, it does't make sense to save a copy of it in each checkpoint. + """ + + def state_dict_post_hook(module, state_dict, prefix, local_metadata): + # Remove frozen weights so they won't get saved. + # If this module is not the top-level module, its weights will have a prefix in the state dict. + nonlocal _dont_save + for k in _dont_save: + del state_dict[prefix + k] + + def load_state_dict_pre_hook( + module, + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ): + # This pre hook exists only to pass the prefix to the post hook when loading the state dict. + nonlocal _prefix + assert _prefix is None + _prefix = prefix + + def load_state_dict_post_hook(module, incompatible_keys): + # Remove the frozen weights from the missing keys so they don't raise an error. + nonlocal _prefix + assert _prefix is not None + to_remove = [] + for missing_key in incompatible_keys.missing_keys: + k = missing_key.removeprefix(_prefix) + k = k.replace("_checkpoint_wrapped_module.", "") # Added by activation checkpointing + if k in _dont_save: + to_remove.append(missing_key) + for r in to_remove: + incompatible_keys.missing_keys.remove(r) + _prefix = None + + _dont_save = set(name.replace("_checkpoint_wrapped_module.", "") for name in dont_save) + _prefix = None + module.register_state_dict_post_hook(state_dict_post_hook) + module.register_load_state_dict_pre_hook(load_state_dict_pre_hook) + module.register_load_state_dict_post_hook(load_state_dict_post_hook) + + +def find_all_checkpoints(ckpt_dir: Path | str) -> list[Path]: + """Find all checkpoints in a directory, i.e. subdirs with integer name. Sorted from first to last.""" + ckpt_dir = Path(ckpt_dir) + if not ckpt_dir.is_dir(): + return [] + checkpoints = [p for p in ckpt_dir.iterdir() if p.is_dir() and _is_int(p.name)] + checkpoints.sort(key=lambda p: int(p.name)) + return checkpoints + + +def find_latest_checkpoint(ckpt_dir: Path | str) -> Path | None: + """Find the latest checkpoint in a directory, i.e. the subdir with the highest integer name.""" + checkpoints = find_all_checkpoints(ckpt_dir) + if len(checkpoints) == 0: + return None + return checkpoints[-1] + + +def keep_last_n_checkpoints(ckpt_dir: Path | str, n: int | None): + """In a directory with integer-named subdirs, keep only the n subdirs with the highest number.""" + if n is None: + return + checkpoints = find_all_checkpoints(ckpt_dir) + for ckpt_dir in checkpoints[:-n]: + try: + shutil.rmtree(ckpt_dir) + logger.info(f"Deleted: {ckpt_dir}") + except Exception: + logger.exception(f"Failed to delete: {ckpt_dir}") + + +def keep_checkpoint_copy(src: Path | str): + """Copy a file/directory next to itself with a _keep suffix. Files are hardlinked.""" + src = Path(src) + dst = src.parent / f"{src.name}_keep" + subprocess.check_output(["cp", "--recursive", "--link", src, dst]) + logger.info(f"Copied: {src} -> {dst}") + + +def _is_int(s: str) -> bool: + try: + int(s) + return True + except ValueError: + return False + + +# Initialize a FSDP2 model from DCP or PyTorch standard checkpoint +def init_fsdp_model_from_checkpoint( + model: torch.nn.Module, + checkpoint_path: str, + skip_load_keys: List[str] | None = None, + keys_not_sharded: List[str] | None = None, + process_group: dist.ProcessGroup = None, +): + if not Path(checkpoint_path).is_dir(): # PyTorch standard checkpoint + logger.info(f"Loading pretrained weights from {checkpoint_path}") + chkpt = torch.load(checkpoint_path, map_location="cpu")["teacher"] + from torch.distributed.device_mesh import DeviceMesh, init_device_mesh + + if process_group is None: + world_mesh = init_device_mesh( + "cuda", + mesh_shape=(dist.get_world_size(),), + mesh_dim_names=("dp",), + ) + else: + world_mesh = DeviceMesh.from_group(process_group, "cuda") + chkpt = { + key: ( + torch.distributed.tensor.distribute_tensor(tensor, world_mesh, src_data_rank=None) + if not any(key_not_sharded in key for key_not_sharded in keys_not_sharded) + else tensor + ) + for key, tensor in chkpt.items() + } + model.load_state_dict( + { + key: tensor + for key, tensor in chkpt.items() + if not any(skip_load_key in key for skip_load_key in skip_load_keys) + } + ) + else: # DCP checkpoint + load_checkpoint(ckpt_dir=checkpoint_path, model=model, process_group=process_group) + + +# Initialize a standard non distributed PyTorch model from PyTorch standard checkpoint for evals +def init_model_from_checkpoint_for_evals( + model: torch.nn.Module, pretrained_weights: str | Path, checkpoint_key: str = None +): + state_dict = torch.load(pretrained_weights, map_location="cpu") + if checkpoint_key is not None and checkpoint_key in state_dict: + logger.info(f"Take key {checkpoint_key} in provided checkpoint dict") + state_dict = state_dict[checkpoint_key] + # remove `module.` prefix + state_dict = {k.replace("module.", ""): v for k, v in state_dict.items()} + # remove `backbone.` prefix induced by multicrop wrapper + state_dict = {k.replace("backbone.", ""): v for k, v in state_dict.items()} + msg = model.load_state_dict(state_dict, strict=False) + logger.info("Pretrained weights found at {} and loaded with msg: {}".format(pretrained_weights, msg)) + + +def cleanup_checkpoint(ckpt_dir: str, checkpoint_retention_policy: CheckpointRetentionPolicy): + """ + ckpt_dir is the directory containing each individual checkpoint directories (either at iteration, best (validation performance) or final) + |-- ckpt_dir/ + | |-- 0/ + | |--checkpoint.pth or dcp_sharded_checkpoint_dir + | |-- 99/ + |--checkpoint.pth or dcp_sharded_checkpoint_dir + | |-- 199/ + |--checkpoint.pth or dcp_sharded_checkpoint_dir + | |-- best/ + |--checkpoint.pth or dcp_sharded_checkpoint_dir + | |-- 299/ + |--checkpoint.pth or dcp_sharded_checkpoint_dir + | |-- final/ + |--checkpoint.pth or dcp_sharded_checkpoint_dir + """ + ckpt_dir = Path(ckpt_dir) + if not ckpt_dir.is_dir(): + return [] + checkpoint_filters = checkpoint_retention_policy.keep_filters + checkpoints = [p for p in ckpt_dir.iterdir() if p.is_dir()] + for checkpoint in checkpoints: + if checkpoint in checkpoint_filters: + continue + try: + shutil.rmtree(checkpoint) + logger.info(f"Deleted: {checkpoint}") + except Exception: + logger.exception(f"Failed to delete: {checkpoint}") diff --git a/starVLA/dinov3/dinov3/configs/__init__.py b/starVLA/dinov3/dinov3/configs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3719887dfb7c33ad67c2546e33e2f1c9f426760c --- /dev/null +++ b/starVLA/dinov3/dinov3/configs/__init__.py @@ -0,0 +1,16 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +from .config import ( + DinoV3SetupArgs, + apply_scaling_rules_to_cfg, + exit_job, + get_cfg_from_args, + get_default_config, + setup_config, + setup_job, + setup_multidistillation, + write_config, +) diff --git a/starVLA/dinov3/dinov3/configs/config.py b/starVLA/dinov3/dinov3/configs/config.py new file mode 100644 index 0000000000000000000000000000000000000000..6aceaa86f9b952cc554cb6ae80ed16a242d67d0e --- /dev/null +++ b/starVLA/dinov3/dinov3/configs/config.py @@ -0,0 +1,222 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import logging +import math +import os +import pathlib +import sys +from dataclasses import dataclass, field +from datetime import timedelta +from typing import Any, List, Optional, Sequence, Tuple + +from omegaconf import DictConfig, OmegaConf + +import dinov3.distributed as distributed +from dinov3.logging import cleanup_logging, setup_logging +from dinov3.utils import fix_random_seeds, get_conda_env, get_sha + +logger = logging.getLogger("dinov3") + + +@dataclass +class DinoV3SetupArgs: + config_file: str + pretrained_weights: str | None = None + shard_unsharded_model: bool = False + output_dir: str = "" + opts: List[Any] = field(default_factory=lambda: []) + + def __post_init__(self): + # When loaded from benchmark.yaml, self.opts is a frozen omegaconf.ListConfig, + # which works everywhere except when we want to modify it or when + # we try to json-serialize it. So we convert it to a regular list here. + if OmegaConf.is_config(self.opts): + self.opts = OmegaConf.to_object(self.opts) + + +def apply_scaling_rules_to_cfg(cfg): # to fix + assert distributed.is_enabled(), "Setup distributed to get global size !" + if "schedules" in cfg: + # For schedules v2, the scaling rules are applied when building the schedules, the config is not modified + return cfg + + if cfg.optim.scaling_rule == "linear_wrt_256": + old_lr = cfg.optim.lr + cfg.optim.lr *= cfg.train.batch_size_per_gpu * distributed.get_world_size() / 256.0 + logger.info(f"linear scaling learning rate; old: {old_lr}, new: {cfg.optim.lr}") + elif cfg.optim.scaling_rule == "sqrt_wrt_1024": + old_lr = cfg.optim.lr + cfg.optim.lr *= 4 * math.sqrt(cfg.train.batch_size_per_gpu * distributed.get_world_size() / 1024.0) + logger.info(f"sqrt scaling learning rate; old: {old_lr}, new: {cfg.optim.lr}") + return cfg + + +def write_config(cfg, output_dir, name="config.yaml"): + logger.info(OmegaConf.to_yaml(cfg)) + output_dir = os.path.abspath(output_dir) + saved_cfg_path = os.path.join(output_dir, name) + with open(saved_cfg_path, "w") as f: + OmegaConf.save(config=cfg, f=f) + return saved_cfg_path + + +def get_default_config() -> DictConfig: + p = pathlib.Path(__file__).parent / "ssl_default_config.yaml" + return OmegaConf.load(p) + + +def get_cfg_from_args(args: DinoV3SetupArgs, multidistillation=False, strict=True): + overrides = [*args.opts] + if args.output_dir is not None: + overrides.append(f"train.output_dir={os.path.realpath(args.output_dir)}") + + # Config file + cfg = OmegaConf.load(args.config_file) + + # Command line overrides + opts_cfg = OmegaConf.from_cli(overrides) + + if multidistillation: + cfg = OmegaConf.merge(cfg, opts_cfg) + else: + # Default config + default_cfg = get_default_config() + if strict: + OmegaConf.set_struct(default_cfg, True) + cfg = OmegaConf.merge(default_cfg, cfg, opts_cfg) + return cfg + + +def setup_config(args: DinoV3SetupArgs, strict_cfg=True): + """ + Create configs and perform basic setups. + """ + # Create the cfg with OmegaConf + cfg = get_cfg_from_args(args, strict=strict_cfg) + # setup distributed, logging, and random seeds + logger.info("\n".join("%s: %s" % (k, str(v)) for k, v in sorted(dict(vars(args)).items()))) + # dump config before modifying so it can be reloaded + if args.output_dir is not None: + write_config(cfg, args.output_dir) + # modify the config inplace by applying scaling rules + apply_scaling_rules_to_cfg(cfg) + return cfg + + +def _enumerate_all_subgroup_ranks(all_subgroup_rank_spans: Sequence[Tuple[int, int]]): + """Expands a specification of process subgroups from spans to enumerated ranks. + + Args: + all_group_rank_spans: a sequence of rank spans (first rank, last rank), + one for each process group. Example: ((0, 1), (2, 3), (4, 7)). + """ + for first, last in all_subgroup_rank_spans: + assert first <= last + return tuple(tuple(range(first, last + 1)) for first, last in all_subgroup_rank_spans) + + +def setup_multidistillation(args: DinoV3SetupArgs): + base_output_dir = args.output_dir + os.makedirs(args.output_dir, exist_ok=True) + # get config file for this rank + base_cfg = OmegaConf.load(args.config_file) + assert base_cfg.multidistillation.enabled + + global_batch_size = base_cfg.multidistillation.global_batch_size + + distributed.enable(overwrite=True) + seed = getattr(args, "seed", 0) + rank = distributed.get_rank() + + # build process subgroups + all_subgroup_rank_spans = tuple( + (student.ranks_range[0], student.ranks_range[1] - 1) for student in base_cfg.multidistillation.students + ) + all_subgroup_ranks = _enumerate_all_subgroup_ranks(all_subgroup_rank_spans) + distributed.new_subgroups(all_subgroup_ranks) + + found = False + for student in base_cfg.multidistillation.students: + if rank in range(*student.ranks_range): + found = True + break + assert found, "rank of worker not in defined range" + + name = student.name + config_path = student.config_path + n_gpus = student.ranks_range[1] - student.ranks_range[0] + assert global_batch_size % n_gpus == 0 + total_n_gpus = distributed.get_world_size() + + args.output_dir = os.path.join(base_output_dir, name) + args.opts += [f"train.output_dir={args.output_dir}"] + args.opts += [f"train.batch_size_per_gpu={global_batch_size // total_n_gpus}"] + args.config_file = os.path.abspath(config_path) + default_cfg = get_default_config() + cfg = OmegaConf.load(args.config_file) + cfg = OmegaConf.merge(default_cfg, cfg, base_cfg, OmegaConf.from_cli(args.opts)) + + global logger + setup_logging(output=args.output_dir, level=logging.INFO) + + fix_random_seeds(seed + rank) + + write_config(cfg, args.output_dir) + apply_scaling_rules_to_cfg(cfg) + + return cfg + + +def setup_job( + output_dir: Optional[str] = None, + distributed_enabled: bool = True, + logging_enabled: bool = True, + seed: Optional[int] = 0, + restrict_print_to_main_process: bool = True, + distributed_timeout: timedelta | None = None, +): + """ + Setup methods that should be done in every fairvit job + Initializes logging, distributed, random seeds and other utilities. + """ + if output_dir is not None: + output_dir = os.path.realpath(output_dir) + os.makedirs(output_dir, exist_ok=True) + + if logging_enabled: + setup_logging( + output=output_dir, + level=logging.INFO, + log_to_stdout_only_in_main_process=restrict_print_to_main_process, + ) + + if distributed_enabled: + distributed.enable( + overwrite=True, + nccl_async_error_handling=True, + restrict_print_to_main_process=restrict_print_to_main_process, + timeout=distributed_timeout, + ) + + if seed is not None: + rank = distributed.get_rank() + fix_random_seeds(seed + rank) + + logger = logging.getLogger("dinov3") + logger.info("git:\n {}\n".format(get_sha())) + + # Log some python info + conda_env_name, conda_env_path = get_conda_env() + logger.info(f"conda env name: {conda_env_name}") + logger.info(f"conda env path: {conda_env_path}") + logger.info(f"python path: {sys.path}") + + +def exit_job(distributed_enabled: bool = True, logging_enabled: bool = True): + if distributed_enabled: + distributed.disable() + if logging_enabled: + cleanup_logging() diff --git a/starVLA/dinov3/dinov3/configs/ssl_default_config.yaml b/starVLA/dinov3/dinov3/configs/ssl_default_config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8002aacc45f81829c9ffa030eaa4e89fde09b10b --- /dev/null +++ b/starVLA/dinov3/dinov3/configs/ssl_default_config.yaml @@ -0,0 +1,206 @@ +MODEL: + META_ARCHITECTURE: SSLMetaArch + DEVICE: cuda + WEIGHTS: '' + DTYPE: float32 +compute_precision: + param_dtype: bf16 + reduce_dtype: fp32 + sharding_strategy: SHARD_GRAD_OP +dino: + loss_weight: 1.0 + global_ignore_diagonal: true # Whether to ignore A-A and B-B global pairs, default as in DINOv2, ignored by SSLMetaArch + head_n_prototypes: 65536 + head_bottleneck_dim: 256 + head_norm_last_layer: false + head_nlayers: 3 + head_hidden_dim: 2048 + koleo_loss_weight: 0.1 + koleo_loss_distributed: false + koleo_topk: 1 + koleo_distributed_replicas: 0 + koleo_distributed_loss_group_size: null # Size of the nearest neighbor set for distributed Koleo. If None, uses global batch size. + koleo_distributed_loss_group_data: true # group data from adjacent ranks to make sure koleo is applied on the same data distribution + force_weight_norm: false + reweight_dino_local_loss: false # If true, reweighting of DINO loss + local_loss_weight_schedule: # Schedule for local loss weight, enabled if reweight_dino_local_loss is true + start: 0.5 + peak: 0.5 + end: 0.5 + warmup_epochs: 0 +ibot: + loss_weight: 1.0 + mask_sample_probability: 0.5 + mask_ratio_min_max: + - 0.1 + - 0.5 + mask_random_circular_shift: false + force_masking_even_with_zero_weight: False + separate_head: true + head_n_prototypes: 65536 + head_bottleneck_dim: 256 + head_norm_last_layer: false + head_nlayers: 3 + head_hidden_dim: 2048 +gram: + use_loss: false # (bool) if true gram is used, else not + compute_stats: false # (bool): if true compute auxilliary stats + loss_weight: 1.0 # (float): weight of the loss + ema_teacher: false # (bool): using the EMA teacher as GRAM teacher + ckpt: null #(str): Checkpoint to the teacher + it_load_ema_teacher: -1 # (int): iteration at which the ema teacher is loaded into the gram teacher + rep_update: true # (bool): if true GRAM teacher updated every gram.update_frequency after iter gram.it_first_update steps + update_frequency: 50000 # (int): update frequency + it_first_update: 0 # (int): iteration of the first update + max_updates: null # (int): maximum number of updates to gram teacher. If None, it is unlimited + normalized: true # (bool): normalization of the features + img_level: false # (bool): if true GRAM computation at the image else, otherwise at the local batch level + remove_neg: false # (bool): if true remove the negative similarities before applying the loss + remove_only_teacher_neg: false # (bool): remove negative similarities of the teacher + tokens_used: all # (str): In [all, masked, unmasked] + global_teacher_resize_method: bicubic # Method for resizing the outputs of the gram teacher + global_teacher_resize_antialias: false # Whether to use antialiasing when resizing the outputs of the gram teacher + loss_weight_schedule: null # (dict): If not None, use a schedule for the loss weight instead of `loss_weight` +train: + batch_size_per_gpu: 64 + dataset_path: ImageNet:split=TRAIN + data_config: null + output_dir: . + saveckp_freq: 20 + seed: 0 + num_workers: 10 + OFFICIAL_EPOCH_LENGTH: 1250 + monitor_gradient_norm: false + chunk_schedule: [] + use_teacher_head: true + learn_from_teacher_tokens: false + centering: "sinkhorn_knopp" # or "sinkhorn_knopp" + checkpointing: false + checkpointing_full: false # aggressive checkpointing + compile: true + cudagraphs: false + sharded_eval_checkpoint: false + cache_dataset: false +student: + arch: vit_large + patch_size: 16 + drop_path_rate: 0.3 + layerscale: 1.0e-05 + pretrained_weights: '' + ffn_layer: "mlp" + ffn_ratio: 4.0 + resume_from_teacher_chkpt: "" + qkv_bias: true + proj_bias: true + ffn_bias: true + norm_layer: "layernorm" + n_storage_tokens: 0 + mask_k_bias: false + untie_cls_and_patch_norms: false # If true, use separate norms for CLS/reg and patch/mask tokens + untie_global_and_local_cls_norm: false # If true, use separate norms for local and global crop CLS token during training + in_chans: 3 + pos_embed_type: rope + pos_embed_rope_base: 100.0 + pos_embed_rope_min_period: null + pos_embed_rope_max_period: null + pos_embed_rope_normalize_coords: separate # min, max, separate + pos_embed_rope_shift_coords: null + pos_embed_rope_jitter_coords: null + pos_embed_rope_rescale_coords: null + pos_embed_rope_dtype: bf16 + fp8_enabled: False # Convert Linear layers to operate in fp8 precision + fp8_filter: "blocks" # Regex that must appear in module path; empty means everything +teacher: + momentum_teacher: 0.992 + final_momentum_teacher: 1 + warmup_teacher_temp: 0.04 + teacher_temp: 0.07 + warmup_teacher_temp_epochs: 30 + in_chans: 3 +distillation: # teacher + enabled: false + full_cfg_path: "" + checkpoint_path: "" +multidistillation: + enabled: false +hrft: # non-hrft'd student + enabled: false + checkpoint_path: "" # teacher_checkpoint path +optim: + epochs: 100 + optimizer: adamw + weight_decay: 0.04 + weight_decay_end: 0.4 + lr: 0.001 + warmup_epochs: 10 + min_lr: 1.0e-06 + schedule_trunc_extra: 0.0 # Compute the schedule for (1 + schedule_trunc_extra) steps and truncate, .25 is a good choice + clip_grad: 3.0 + freeze_last_layer_epochs: 1 + scaling_rule: sqrt_wrt_1024 + patch_embed_lr_mult: 0.2 + dino_head_wd_multiplier: 1.0 + layerwise_decay: 0.9 + multi_tensor_optim: true + dump_fsdp_weights_path: "" + adamw_beta1: 0.9 + adamw_beta2: 0.999 +crops: + global_crops_scale: + - 0.32 + - 1.0 + local_crops_number: 8 + local_crops_scale: + - 0.05 + - 0.32 + global_crops_size: 224 + local_crops_size: 96 + global_local_crop_pairs_ratios: 1.0 + gram_teacher_crops_size: null # If not None, return crops for gram teacher + localcrops_subset_of_globalcrops: false + share_color_jitter: false + horizontal_flips: true + gram_teacher_no_distortions: false # If True, no distortions are applied to gram teacher crops + rgb_mean: + - 0.485 + - 0.456 + - 0.406 + rgb_std: + - 0.229 + - 0.224 + - 0.225 + teacher_to_student_resolution_scale: 1.0 +evaluation: + eval_period_iterations: 12500 + low_freq_every: 5 + config_files: # Must be in fairvit/eval/configs + high_freq: benchmark_high_frequency.yaml # More often + low_freq: benchmark_low_frequency.yaml # Less often +checkpointing: + period: 3750 + max_to_keep: 3 + keep_every: 99999999999999999 # Save a checkpoint every N iterations, regardless of max_to_keep and period + +# Example of constant schedules with schedules v2 +# # schedules: +# # lr: +# # start: 0.0 +# # peak: 1e-3 +# # end: 1e-6 +# # warmup_epochs: 10 +# # freeze_last_layer_epochs: 1 +# # weight_decay: +# # start: 0.04 +# # peak: 0.04 +# # end: 0.04 +# # warmup_epochs: 0 +# # momentum: +# # start: 0.992 +# # peak: 0.992 +# # end: 0.992 +# # warmup_epochs: 0 +# # teacher_temp: +# # start: 0.04 +# # peak: 0.07 +# # end: 0.07 +# # warmup_epochs: 30 diff --git a/starVLA/dinov3/dinov3/configs/train/__init__.py b/starVLA/dinov3/dinov3/configs/train/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/starVLA/dinov3/dinov3/configs/train/dinov3_vit7b16_gram_anchor.yaml b/starVLA/dinov3/dinov3/configs/train/dinov3_vit7b16_gram_anchor.yaml new file mode 100644 index 0000000000000000000000000000000000000000..05cf7dfef6fda0199e10b45a761f14201a3db6b5 --- /dev/null +++ b/starVLA/dinov3/dinov3/configs/train/dinov3_vit7b16_gram_anchor.yaml @@ -0,0 +1,203 @@ +MODEL: + META_ARCHITECTURE: SSLMetaArch + DEVICE: cuda + WEIGHTS: '' + DTYPE: float32 +compute_precision: + param_dtype: bf16 + reduce_dtype: fp32 + sharding_strategy: SHARD_GRAD_OP +dino: + loss_weight: 1.0 + global_ignore_diagonal: true + head_n_prototypes: 262144 + head_bottleneck_dim: 512 + head_norm_last_layer: false + head_nlayers: 3 + head_hidden_dim: 8192 + koleo_loss_weight: 0.1 + koleo_loss_distributed: false + koleo_topk: 1 + koleo_distributed_replicas: 0 + koleo_distributed_loss_group_size: null + koleo_distributed_loss_group_data: true + force_weight_norm: false + reweight_dino_local_loss: true + local_loss_weight_schedule: + start: 1 + peak: 1 + end: 0.5 + warmup_epochs: 1000 + cosine_epochs: 1 +ibot: + loss_weight: 1.0 + mask_sample_probability: 0.5 + mask_ratio_min_max: + - 0.1 + - 0.5 + mask_random_circular_shift: false + force_masking_even_with_zero_weight: false + separate_head: true + head_n_prototypes: 98304 + head_bottleneck_dim: 384 + head_norm_last_layer: false + head_nlayers: 3 + head_hidden_dim: 4096 +gram: + use_loss: true + compute_stats: false + loss_weight: 1.0 + ema_teacher: false + ckpt: ignore + it_load_ema_teacher: -1 + rep_update: true + update_frequency: 10000 + it_first_update: 1010000 + max_updates: 3 + normalized: true + img_level: true + remove_neg: false + remove_only_teacher_neg: false + tokens_used: all + global_teacher_resize_method: bicubic + global_teacher_resize_antialias: false + loss_weight_schedule: + start: 0 + peak: 0 + end: 2.0 + warmup_epochs: 1000 + cosine_epochs: 1 +train: + batch_size_per_gpu: 16 + dataset_path: null + saveckp_freq: 20 + seed: 0 + num_workers: 10 + OFFICIAL_EPOCH_LENGTH: 1000 + monitor_gradient_norm: false + chunk_schedule: [] + cache_dataset: true + use_teacher_head: true + learn_from_teacher_tokens: false + centering: sinkhorn_knopp + checkpointing: true + checkpointing_full: true + compile: true + cudagraphs: false + cell_augmentation: false + cell_augmentation_type: hpa + sharded_eval_checkpoint: true +student: + arch: vit_7b + patch_size: 16 + drop_path_rate: 0.4 + layerscale: 1.0e-05 + patch_drop: 0.0 + pretrained_weights: '' + ffn_layer: swiglu64 + ffn_ratio: 3 + resume_from_teacher_chkpt: '' + qkv_bias: false + proj_bias: true + ffn_bias: true + norm_layer: layernormbf16 + n_storage_tokens: 4 + untie_cls_and_patch_norms: false + untie_global_and_local_cls_norm: true + mask_k_bias: true + in_chans: 3 + pos_embed_type: rope + pos_embed_rope_base: 100 + pos_embed_rope_min_period: null + pos_embed_rope_max_period: null + pos_embed_rope_normalize_coords: separate + pos_embed_rope_shift_coords: null + pos_embed_rope_jitter_coords: null + pos_embed_rope_rescale_coords: 2 + pos_embed_rope_dtype: fp32 + fp8_enabled: true + fp8_filter: blocks +teacher: + momentum_teacher: null + final_momentum_teacher: null + warmup_teacher_temp: null + teacher_temp: null + warmup_teacher_temp_epochs: null + in_chans: 3 +distillation: + enabled: false + full_cfg_path: '' + checkpoint_path: '' +multidistillation: + enabled: false +hrft: + enabled: false + checkpoint_path: '' +optim: + epochs: 1200 + optimizer: adamw + weight_decay: null + weight_decay_end: null + lr: null + warmup_epochs: null + min_lr: null + schedule_trunc_extra: null + clip_grad: 30.0 + freeze_last_layer_epochs: null + scaling_rule: sqrt_wrt_1024 + patch_embed_lr_mult: 0.2 + dino_head_wd_multiplier: 1.0 + layerwise_decay: 0.98 + multi_tensor_optim: true + dump_fsdp_weights_path: '' + adamw_beta1: 0.9 + adamw_beta2: 0.99 +crops: + global_crops_scale: + - 0.32 + - 1.0 + local_crops_number: 8 + local_crops_scale: + - 0.05 + - 0.32 + global_crops_size: 256 + local_crops_size: 112 + gram_teacher_crops_size: 512 + localcrops_subset_of_globalcrops: false + share_color_jitter: false + horizontal_flips: false + gram_teacher_no_distortions: true + rgb_mean: + - 0.485 + - 0.456 + - 0.406 + rgb_std: + - 0.229 + - 0.224 + - 0.225 +checkpointing: + period: 1000 + max_to_keep: 3 + keep_every: 50000 +schedules: + lr: + start: 0 + peak: 3.0e-05 + end: 3.0e-05 + warmup_epochs: 100 + freeze_last_layer_epochs: 5 + weight_decay: + start: 0.04 + peak: 0.04 + end: 0.04 + warmup_epochs: 0 + teacher_temp: + start: 0.04 + peak: 0.07 + end: 0.07 + warmup_epochs: 100 + momentum: + start: 0.999 + peak: 0.999 + end: 0.999 + warmup_epochs: 0 diff --git a/starVLA/dinov3/dinov3/configs/train/dinov3_vit7b16_high_res_adapt.yaml b/starVLA/dinov3/dinov3/configs/train/dinov3_vit7b16_high_res_adapt.yaml new file mode 100644 index 0000000000000000000000000000000000000000..313a104a7cbf757cc0288f10d8d22eb960bfe644 --- /dev/null +++ b/starVLA/dinov3/dinov3/configs/train/dinov3_vit7b16_high_res_adapt.yaml @@ -0,0 +1,224 @@ +MODEL: + META_ARCHITECTURE: SSLMetaArch + DEVICE: cuda + WEIGHTS: '' + DTYPE: float32 +compute_precision: + param_dtype: bf16 + reduce_dtype: fp32 + sharding_strategy: SHARD_GRAD_OP +dino: + loss_weight: 1.0 + global_ignore_diagonal: true + head_n_prototypes: 262144 + head_bottleneck_dim: 512 + head_norm_last_layer: false + head_nlayers: 3 + head_hidden_dim: 8192 + koleo_loss_weight: 0.1 + koleo_loss_distributed: true + koleo_topk: 1 + koleo_distributed_replicas: 0 + koleo_distributed_loss_group_size: 16 + force_weight_norm: false + reweight_dino_local_loss: true + local_loss_weight_schedule: + start: 0.5 + peak: 0.5 + end: 0.5 + warmup_epochs: 0 + cosine_epochs: 0 + koleo_distributed_loss_group_data: true +ibot: + loss_weight: 1.0 + mask_sample_probability: 0.5 + mask_ratio_min_max: + - 0.1 + - 0.5 + mask_random_circular_shift: false + force_masking_even_with_zero_weight: false + separate_head: true + head_n_prototypes: 98304 + head_bottleneck_dim: 384 + head_norm_last_layer: false + head_nlayers: 3 + head_hidden_dim: 4096 +gram: + use_loss: true + compute_stats: false + loss_weight: 1.0 + ema_teacher: false + it_load_ema_teacher: -1 + rep_update: false + update_frequency: 10000 + it_first_update: 1010000 + max_updates: 3 + normalized: true + img_level: true + remove_neg: false + remove_only_teacher_neg: false + tokens_used: all + global_teacher_resize_method: bicubic + global_teacher_resize_antialias: false + loss_weight_schedule: + start: 1.5 + peak: 1.5 + end: 1.5 + warmup_epochs: 0 + cosine_epochs: 0 +train: + batch_size_per_gpu: 8 + dataset_path: null + saveckp_freq: 20 + seed: 0 + num_workers: 2 + OFFICIAL_EPOCH_LENGTH: 1000 + monitor_gradient_norm: false + chunk_schedule: [] + cache_dataset: true + use_teacher_head: true + learn_from_teacher_tokens: false + centering: sinkhorn_knopp + checkpointing: true + checkpointing_full: true + compile: true + cudagraphs: false + cell_augmentation: false + cell_augmentation_type: hpa + sharded_eval_checkpoint: true +student: + arch: vit_7b + patch_size: 16 + drop_path_rate: 0.4 + layerscale: 1.0e-05 + patch_drop: 0.0 + pretrained_weights: '' + ffn_layer: swiglu64 + ffn_ratio: 3 + resume_from_teacher_chkpt: '' + qkv_bias: false + proj_bias: true + ffn_bias: true + norm_layer: layernormbf16 + n_storage_tokens: 4 + untie_cls_and_patch_norms: false + untie_global_and_local_cls_norm: true + mask_k_bias: true + in_chans: 3 + pos_embed_type: rope + pos_embed_rope_base: 100 + pos_embed_rope_min_period: null + pos_embed_rope_max_period: null + pos_embed_rope_normalize_coords: separate + pos_embed_rope_shift_coords: null + pos_embed_rope_jitter_coords: null + pos_embed_rope_rescale_coords: 2 + pos_embed_rope_dtype: fp32 + fp8_enabled: true + fp8_filter: blocks +teacher: + momentum_teacher: null + final_momentum_teacher: null + warmup_teacher_temp: null + teacher_temp: null + warmup_teacher_temp_epochs: null + in_chans: 3 +distillation: + enabled: false + full_cfg_path: '' + checkpoint_path: '' +multidistillation: + enabled: false +hrft: + enabled: false + checkpoint_path: '' +optim: + epochs: 30 + optimizer: adamw + weight_decay: null + weight_decay_end: null + lr: null + warmup_epochs: null + min_lr: null + schedule_trunc_extra: null + clip_grad: 30.0 + freeze_last_layer_epochs: null + scaling_rule: sqrt_wrt_1024 + patch_embed_lr_mult: 0.2 + dino_head_wd_multiplier: 1.0 + layerwise_decay: 0.98 + multi_tensor_optim: true + dump_fsdp_weights_path: '' + adamw_beta1: 0.9 + adamw_beta2: 0.99 +crops: + global_crops_scale: + - 0.32 + - 1.0 + local_crops_number: 8 + local_crops_scale: + - 0.05 + - 0.32 + global_crops_size: + - 512 + - 768 + - 768 + - 768 + - 768 + local_crops_size: + - 112 + - 112 + - 168 + - 224 + - 336 + global_local_crop_pairs_ratios: + - 0.3 + - 0.3 + - 0.3 + - 0.05 + - 0.05 + gram_teacher_crops_size: + - 768 + - 1152 + - 1152 + - 1152 + - 1152 + localcrops_subset_of_globalcrops: false + share_color_jitter: false + horizontal_flips: false + gram_teacher_no_distortions: true + rgb_mean: + - 0.485 + - 0.456 + - 0.406 + rgb_std: + - 0.229 + - 0.224 + - 0.225 +checkpointing: + period: 250 + max_to_keep: 3 + keep_every: 50000 +schedules: + lr: + start: 0 + peak: 0 + end: 1.25e-05 + warmup_epochs: 0 + freeze_last_layer_epochs: 0 + cosine_epochs: 10 + weight_decay: + start: 0.04 + peak: 0.04 + end: 0.04 + warmup_epochs: 0 + teacher_temp: + start: 0.07 + peak: 0.07 + end: 0.07 + warmup_epochs: 0 + momentum: + start: 0.999 + peak: 0.999 + end: 0.999 + warmup_epochs: 0 diff --git a/starVLA/dinov3/dinov3/configs/train/dinov3_vit7b16_pretrain.yaml b/starVLA/dinov3/dinov3/configs/train/dinov3_vit7b16_pretrain.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7b93be46ecedb582befb9d4fcb7ed185410f2517 --- /dev/null +++ b/starVLA/dinov3/dinov3/configs/train/dinov3_vit7b16_pretrain.yaml @@ -0,0 +1,172 @@ +MODEL: + META_ARCHITECTURE: SSLMetaArch + DEVICE: cuda + WEIGHTS: '' + DTYPE: float32 +compute_precision: + param_dtype: bf16 + reduce_dtype: fp32 + sharding_strategy: SHARD_GRAD_OP +dino: + loss_weight: 1.0 + global_ignore_diagonal: true + head_n_prototypes: 262144 + head_bottleneck_dim: 512 + head_norm_last_layer: false + head_nlayers: 3 + head_hidden_dim: 8192 + koleo_loss_weight: 0.1 + koleo_loss_distributed: false + koleo_topk: 1 + koleo_distributed_replicas: 0 + koleo_distributed_loss_group_size: null + force_weight_norm: false +ibot: + loss_weight: 1.0 + mask_sample_probability: 0.5 + mask_ratio_min_max: + - 0.1 + - 0.5 + mask_random_circular_shift: false + force_masking_even_with_zero_weight: false + separate_head: true + head_n_prototypes: 98304 + head_bottleneck_dim: 384 + head_norm_last_layer: false + head_nlayers: 3 + head_hidden_dim: 4096 +gram: + use_loss: false + compute_stats: false +train: + batch_size_per_gpu: 16 + dataset_path: null + saveckp_freq: 20 + seed: 0 + num_workers: 10 + OFFICIAL_EPOCH_LENGTH: 1000 + monitor_gradient_norm: false + chunk_schedule: [] + cache_dataset: true + use_teacher_head: true + learn_from_teacher_tokens: false + centering: sinkhorn_knopp + checkpointing: true + checkpointing_full: false + compile: true + cudagraphs: false + cell_augmentation: false + cell_augmentation_type: hpa + sharded_eval_checkpoint: true +student: + arch: vit_7b + patch_size: 16 + drop_path_rate: 0.4 + layerscale: 1.0e-05 + patch_drop: 0.0 + pretrained_weights: '' + ffn_layer: swiglu64 + ffn_ratio: 3 + resume_from_teacher_chkpt: '' + qkv_bias: false + proj_bias: true + ffn_bias: true + norm_layer: layernormbf16 + n_storage_tokens: 4 + untie_cls_and_patch_norms: false + untie_global_and_local_cls_norm: true + mask_k_bias: true + in_chans: 3 + pos_embed_type: rope + pos_embed_rope_base: 100 + pos_embed_rope_min_period: null + pos_embed_rope_max_period: null + pos_embed_rope_normalize_coords: separate + pos_embed_rope_shift_coords: null + pos_embed_rope_jitter_coords: null + pos_embed_rope_rescale_coords: 2 + pos_embed_rope_dtype: fp32 + fp8_enabled: true + fp8_filter: blocks +teacher: + momentum_teacher: null + final_momentum_teacher: null + warmup_teacher_temp: null + teacher_temp: null + warmup_teacher_temp_epochs: null + in_chans: 3 +distillation: + enabled: false + full_cfg_path: '' + checkpoint_path: '' +multidistillation: + enabled: false +hrft: + enabled: false + checkpoint_path: '' +optim: + epochs: 1000 + optimizer: adamw + weight_decay: null + weight_decay_end: null + lr: null + warmup_epochs: null + min_lr: null + schedule_trunc_extra: null + clip_grad: 30.0 + freeze_last_layer_epochs: null + scaling_rule: sqrt_wrt_1024 + patch_embed_lr_mult: 0.2 + dino_head_wd_multiplier: 1.0 + layerwise_decay: 0.98 + multi_tensor_optim: true + dump_fsdp_weights_path: '' + adamw_beta1: 0.9 + adamw_beta2: 0.99 +crops: + global_crops_scale: + - 0.32 + - 1.0 + local_crops_number: 8 + local_crops_scale: + - 0.05 + - 0.32 + global_crops_size: 256 + local_crops_size: 112 + localcrops_subset_of_globalcrops: false + share_color_jitter: false + horizontal_flips: false + rgb_mean: + - 0.485 + - 0.456 + - 0.406 + rgb_std: + - 0.229 + - 0.224 + - 0.225 +checkpointing: + period: 1000 + max_to_keep: 3 + keep_every: 50000 +schedules: + lr: + start: 0 + peak: 5.0e-05 + end: 5.0e-05 + warmup_epochs: 100 + freeze_last_layer_epochs: 5 + weight_decay: + start: 0.04 + peak: 0.04 + end: 0.04 + warmup_epochs: 0 + teacher_temp: + start: 0.04 + peak: 0.07 + end: 0.07 + warmup_epochs: 100 + momentum: + start: 0.994 + peak: 0.994 + end: 0.994 + warmup_epochs: 0 diff --git a/starVLA/dinov3/dinov3/configs/train/dinov3_vitl16_lvd1689m_distilled.yaml b/starVLA/dinov3/dinov3/configs/train/dinov3_vitl16_lvd1689m_distilled.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5d81e605593401de00ea6ac68630714a2c707fcc --- /dev/null +++ b/starVLA/dinov3/dinov3/configs/train/dinov3_vitl16_lvd1689m_distilled.yaml @@ -0,0 +1,251 @@ +MODEL: + META_ARCHITECTURE: MultiDistillationMetaArch + DEVICE: cuda + WEIGHTS: '' + DTYPE: float32 +compute_precision: + param_dtype: bf16 + reduce_dtype: fp32 + sharding_strategy: SHARD_GRAD_OP +dino: + loss_weight: 1.0 + global_ignore_diagonal: true + head_n_prototypes: 262144 + head_bottleneck_dim: 512 + head_norm_last_layer: false + head_nlayers: 3 + head_hidden_dim: 8192 + koleo_loss_weight: 0.1 + koleo_loss_distributed: false + koleo_topk: 1 + koleo_distributed_replicas: 0 + koleo_distributed_loss_group_size: null + koleo_distributed_loss_group_data: true + force_weight_norm: false + reweight_dino_local_loss: false + local_loss_weight_schedule: + start: 0.5 + peak: 0.5 + end: 0.5 + warmup_epochs: 0 +ibot: + loss_weight: 1.0 + mask_sample_probability: 0.5 + mask_ratio_min_max: + - 0.1 + - 0.5 + mask_random_circular_shift: false + force_masking_even_with_zero_weight: false + separate_head: true + head_n_prototypes: 98304 + head_bottleneck_dim: 384 + head_norm_last_layer: false + head_nlayers: 3 + head_hidden_dim: 4096 +coding_rate_loss: + use_cls_loss: false + cls_loss_weight: 0.2 + use_masked_patches_loss: false + masked_patches_loss_weight: 0.1 + epsilon: 8 +gram: + use_loss: false + compute_stats: false + loss_weight: 1.0 + ema_teacher: false + ckpt: null + it_load_ema_teacher: -1 + rep_update: true + update_frequency: 50000 + it_first_update: 0 + max_updates: null + normalized: true + img_level: false + remove_neg: false + remove_only_teacher_neg: false + tokens_used: all + global_teacher_resize_method: bicubic + global_teacher_resize_antialias: false + loss_weight_schedule: null +train: + batch_size_per_gpu: 3 + dataset_path: + output_dir: + saveckp_freq: 20 + seed: 0 + num_workers: 2 + OFFICIAL_EPOCH_LENGTH: 1250 + monitor_gradient_norm: false + chunk_schedule: [] + cache_dataset: true + use_teacher_head: true + learn_from_teacher_tokens: false + centering: sinkhorn_knopp + checkpointing: true + checkpointing_full: true + compile: true + cudagraphs: false + cell_augmentation: false + cell_augmentation_type: hpa + sharded_eval_checkpoint: false +student: + arch: vit_large + patch_size: 16 + drop_path_rate: 0.0 + layerscale: 1.0e-05 + drop_path_uniform: true + drop_path_shape: uniform + patch_drop: 0.0 + pretrained_weights: '' + sin_cos_embeddings: false + fourier_embeddings: false + fourier_encoding_dim: 64 + multiple_pos_embeddings: false + cls_pos_embedding: false + reg_pos_embedding: false + ffn_layer: mlp + ffn_ratio: 4.0 + resume_from_teacher_chkpt: + block_chunks: 0 + qkv_bias: true + proj_bias: true + ffn_bias: true + norm_layer: layernormbf16 + n_storage_tokens: 4 + mask_attention: false + mask_register_attention: false + untie_cls_and_patch_norms: false + untie_global_and_local_cls_norm: false + interpolate_offset: 0.0 + interpolate_antialias: true + mask_k_bias: true + init_std_cls: 0.02 + init_std_reg: 0.02 + rescale_weights_by_layer_id: false + in_chans: 3 + pos_embed_grid_size: 48 + pos_embed_type: ropenew + pos_embed_rope_gamma: 1.0 + pos_embed_rope_init_multi_frequencies: false + pos_embed_rope_base: 100 + pos_embed_rope_min_period: null + pos_embed_rope_max_period: null + pos_embed_rope_normalize_coords: separate + pos_embed_rope_shift_coords: null + pos_embed_rope_jitter_coords: null + pos_embed_rope_rescale_coords: 2 + pos_embed_rope_dtype: bf16 + sparse24_ranges: [] + sparse24_filter: + - mlp + sparse24_default: false + fp8_enabled: false + fp8_filter: blocks +teacher: + momentum_teacher: 0.994 + final_momentum_teacher: 1 + warmup_teacher_temp: 0.04 + teacher_temp: 0.07 + warmup_teacher_temp_epochs: 120 + in_chans: 3 +distillation: + enabled: true + full_cfg_path: + checkpoint_path: +multidistillation: + enabled: true + global_batch_size: 1920 + students: + - name: vits_mlp4_4 + config_path: + ranks_range: + - 0 + - 48 + - name: vitsp_swiglu6_1 + config_path: + ranks_range: + - 48 + - 96 + - name: vitb_mlp4_3 + config_path: