| """ |
| Multi-GPU DROID Preprocessing Script |
| |
| Processes full DROID dataset in parallel across multiple GPUs. |
| Usage: |
| # Machine 1 (GPUs 0-7): |
| bash scripts/run_multigpu_machine1.sh |
| |
| # Machine 2 (GPUs 0-7): |
| bash scripts/run_multigpu_machine2.sh |
| |
| Each GPU processes a subset of episodes based on GPU_ID % NUM_GPUS. |
| """ |
|
|
| import sys |
| from pathlib import Path |
| sys.path.append(str(Path(__file__).parent.parent)) |
|
|
| import os |
| import numpy as np |
| import torch |
| import mediapy as media |
| import tensorflow as tf |
| tf.config.set_visible_devices([], 'GPU') |
| import tensorflow_datasets as tfds |
| import cv2 |
| import datetime |
| import re |
| import json |
| from tqdm import tqdm |
| from scipy.spatial.transform import Rotation as R |
|
|
| from utils.load_camera_calibration import CameraCalibrationLoader |
| from utils.franka_mesh_projection import FrankaMeshProjector |
|
|
|
|
| |
| GRIPPER_OFFSETS = np.array([ |
| [0.0, 0.0, 0.0], |
| [0.0, 0.045, 0.161], |
| [0.0, -0.045, 0.161], |
| [0.0, 0.045, 0.13], |
| [0.0, -0.045, 0.13], |
| [0.0, 0.0, 0.13], |
| [0.0, 0.0, 0.065], |
| ]) |
|
|
|
|
| def euler_xyz_to_rotation_matrix(euler_xyz): |
| """Convert Euler XYZ angles to rotation matrix.""" |
| return R.from_euler('xyz', euler_xyz).as_matrix() |
|
|
|
|
| def transform_gripper_offsets(action): |
| """Transform gripper offsets using action position and rotation.""" |
| pos = action[:3] |
| rot_euler = action[3:6] |
| rot_matrix = euler_xyz_to_rotation_matrix(rot_euler) |
| gripper_points_3d = (rot_matrix @ GRIPPER_OFFSETS.T).T + pos |
| return gripper_points_3d |
|
|
|
|
| def sample_arm_shaped_points(mesh_2d_visible, img_h, img_w, num_points=993, seed=None): |
| """Sample points in arm shape around visible mesh vertices.""" |
| if seed is not None: |
| np.random.seed(seed) |
|
|
| points = [] |
| num_visible = len(mesh_2d_visible) |
|
|
| if num_visible == 0: |
| return np.random.rand(num_points, 2) * [img_w, img_h] |
|
|
| |
| points_per_mesh = min(50, num_points // max(num_visible, 1)) |
| gaussian_sigma = 15.0 |
|
|
| for mesh_pt in mesh_2d_visible: |
| gaussian_pts = np.random.randn(points_per_mesh, 2) * gaussian_sigma + mesh_pt |
| gaussian_pts[:, 0] = np.clip(gaussian_pts[:, 0], 0, img_w - 1) |
| gaussian_pts[:, 1] = np.clip(gaussian_pts[:, 1], 0, img_h - 1) |
| points.append(gaussian_pts) |
|
|
| |
| if num_visible >= 2: |
| points_per_line = 10 |
| for i in range(num_visible - 1): |
| line_pts = np.linspace(mesh_2d_visible[i], mesh_2d_visible[i+1], points_per_line + 2) |
| points.append(line_pts[1:-1]) |
|
|
| |
| current_count = sum(len(p) for p in points) |
| remaining = num_points - current_count |
|
|
| if remaining > 0: |
| uniform_pts = np.random.rand(remaining, 2) * [img_w, img_h] |
| points.append(uniform_pts) |
|
|
| all_points = np.vstack(points) if points else np.empty((0, 2)) |
|
|
| if len(all_points) < num_points: |
| extra = np.random.rand(num_points - len(all_points), 2) * [img_w, img_h] |
| all_points = np.vstack([all_points, extra]) |
| elif len(all_points) > num_points: |
| all_points = all_points[:num_points] |
|
|
| return all_points |
|
|
|
|
| def sample_wrist_points(img_h, img_w, num_sparse=300, num_dense=700, seed=None): |
| """Sample wrist points: sparse uniform + dense in bottom 60%-100%.""" |
| if seed is not None: |
| np.random.seed(seed) |
|
|
| sparse = np.random.rand(num_sparse, 2) * [img_w, img_h] |
|
|
| |
| y_min = int(img_h * 0.60) |
| y_max = img_h |
| y_range = y_max - y_min |
|
|
| dense_x = np.random.rand(num_dense) * img_w |
| dense_y = np.random.rand(num_dense) * y_range + y_min |
| dense = np.column_stack([dense_x, dense_y]) |
|
|
| return np.vstack([sparse, dense]) |
|
|
|
|
| def find_closest_calibration(episode, uuid_list): |
| """Find closest calibration UUID for episode.""" |
| try: |
| recording_path = episode['episode_metadata']['recording_folderpath'].numpy().decode('utf-8') |
| match = re.search(r'/([A-Z]+)/success/(\d{4}-\d{2}-\d{2})/\w+_\w+_+\d+_(\d{2}):(\d{2}):(\d{2})_\d{4}/', recording_path) |
| if not match: |
| return None |
| lab, date, hour, minute, second = match.groups() |
| episode_time = datetime.datetime.strptime(f"{date} {hour}:{minute}:{second}", "%Y-%m-%d %H:%M:%S") |
| matching_calibs = [uuid for uuid in uuid_list if uuid.startswith(f"{lab}+") and f"+{date}-" in uuid] |
| if len(matching_calibs) == 0: |
| return None |
| best_uuid = None |
| min_time_diff = float('inf') |
| for calib_uuid in matching_calibs: |
| parts = calib_uuid.split('+') |
| if len(parts) >= 3: |
| time_str = parts[2].replace('_cameras', '') |
| match_time = re.search(r'(\d{2})h-(\d{2})m-(\d{2})s', time_str) |
| if match_time: |
| calib_hour = int(match_time.group(1)) |
| calib_min = int(match_time.group(2)) |
| calib_sec = int(match_time.group(3)) |
| calib_time = datetime.datetime.strptime( |
| f"{date} {calib_hour}:{calib_min}:{calib_sec}", |
| "%Y-%m-%d %H:%M:%S" |
| ) |
| time_diff = abs((episode_time - calib_time).total_seconds()) |
| if time_diff < min_time_diff: |
| min_time_diff = time_diff |
| best_uuid = calib_uuid |
| return best_uuid |
| except: |
| return None |
|
|
|
|
| def process_episode(episode, episode_idx, projector, calib_loader, uuid, cotracker, device, |
| max_frames=400, save_video=False, output_dir=None): |
| """Process a single episode.""" |
|
|
| |
| dual_params = calib_loader.get_dual_view_params(uuid, param_type='refined', require_refined=True) |
| K_ext, E_ext = dual_params['exterior_1'] |
| K_wrist, E_wrist = dual_params['wrist'] |
|
|
| |
| valid_frame_count = 0 |
| for step in episode['steps']: |
| img_ext = step['observation']['exterior_image_1_left'].numpy() |
| img_wrist = step['observation']['wrist_image_left'].numpy() |
| if img_ext is not None and img_wrist is not None: |
| valid_frame_count += 1 |
| if valid_frame_count > max_frames: |
| |
| return None |
|
|
| |
| if valid_frame_count < 10: |
| return None |
|
|
| |
| frames_ext = [] |
| frames_wrist = [] |
| actions = [] |
|
|
| for step_idx, step in enumerate(episode['steps']): |
| img_ext = step['observation']['exterior_image_1_left'].numpy() |
| img_wrist = step['observation']['wrist_image_left'].numpy() |
| action = step['action'].numpy() |
|
|
| if img_ext is not None and img_wrist is not None: |
| frames_ext.append(img_ext) |
| frames_wrist.append(img_wrist) |
| actions.append(action) |
|
|
| T = len(frames_ext) |
| img_h, img_w = frames_ext[0].shape[:2] |
|
|
| |
| all_mesh_2d_ext = [] |
| all_mesh_vis_ext = [] |
|
|
| for t in range(T): |
| gripper_3d = transform_gripper_offsets(actions[t]) |
| mesh_2d, mesh_vis = projector._project_3d_to_2d( |
| gripper_3d, K_ext, E_ext, img_h=img_h, img_w=img_w |
| ) |
| all_mesh_2d_ext.append(mesh_2d) |
| all_mesh_vis_ext.append(mesh_vis) |
|
|
| all_mesh_2d_ext = np.array(all_mesh_2d_ext) |
| all_mesh_vis_ext = np.array(all_mesh_vis_ext) |
|
|
| |
| if np.sum(all_mesh_vis_ext[0]) < 2: |
| return None |
|
|
| |
| mesh_2d_0 = all_mesh_2d_ext[0] |
| mesh_2d_visible_0 = mesh_2d_0[all_mesh_vis_ext[0]] |
|
|
| additional_points_ext = sample_arm_shaped_points( |
| mesh_2d_visible_0, img_h, img_w, num_points=993, seed=episode_idx |
| ) |
| query_points_ext = np.vstack([mesh_2d_0, additional_points_ext]) |
|
|
| query_points_wrist = sample_wrist_points( |
| img_h, img_w, num_sparse=300, num_dense=700, seed=episode_idx |
| ) |
|
|
| |
| video_ext_np = np.array(frames_ext).transpose(0, 3, 1, 2) |
| video_ext_tensor = torch.from_numpy(video_ext_np).float() / 255.0 |
| video_ext_tensor = video_ext_tensor.unsqueeze(0).to(device) |
|
|
| queries_ext = np.zeros((len(query_points_ext), 3)) |
| queries_ext[:, 0] = 0 |
| queries_ext[:, 1:] = query_points_ext |
| queries_ext_tensor = torch.from_numpy(queries_ext).float().unsqueeze(0).to(device) |
|
|
| with torch.no_grad(): |
| tracks_ext, vis_ext = cotracker( |
| video_ext_tensor, |
| queries=queries_ext_tensor, |
| backward_tracking=False |
| ) |
|
|
| tracks_ext = tracks_ext[0].cpu().numpy() |
| vis_ext = vis_ext[0].cpu().numpy() |
|
|
| |
| video_wrist_np = np.array(frames_wrist).transpose(0, 3, 1, 2) |
| video_wrist_tensor = torch.from_numpy(video_wrist_np).float() / 255.0 |
| video_wrist_tensor = video_wrist_tensor.unsqueeze(0).to(device) |
|
|
| queries_wrist = np.zeros((len(query_points_wrist), 3)) |
| queries_wrist[:, 0] = 0 |
| queries_wrist[:, 1:] = query_points_wrist |
| queries_wrist_tensor = torch.from_numpy(queries_wrist).float().unsqueeze(0).to(device) |
|
|
| with torch.no_grad(): |
| tracks_wrist, vis_wrist = cotracker( |
| video_wrist_tensor, |
| queries=queries_wrist_tensor, |
| backward_tracking=False |
| ) |
|
|
| tracks_wrist = tracks_wrist[0].cpu().numpy() |
| vis_wrist = vis_wrist[0].cpu().numpy() |
|
|
| |
| if save_video and output_dir is not None: |
| video_frames = [] |
| for t in range(T): |
| |
| viz_ext = frames_ext[t].copy() |
|
|
| |
| for i in range(7): |
| if all_mesh_vis_ext[t, i]: |
| pt = tuple(all_mesh_2d_ext[t, i].astype(int)) |
| cv2.circle(viz_ext, pt, 5, (255, 0, 0), 2) |
| cv2.putText(viz_ext, str(i), (pt[0]+6, pt[1]-6), |
| cv2.FONT_HERSHEY_SIMPLEX, 0.3, (255, 0, 0), 1) |
|
|
| |
| for i in range(7): |
| if vis_ext[t, i]: |
| pt = tuple(tracks_ext[t, i].astype(int)) |
| cv2.circle(viz_ext, pt, 3, (0, 0, 255), -1) |
|
|
| |
| for i in range(7, len(tracks_ext[t])): |
| if vis_ext[t, i]: |
| pt = tuple(tracks_ext[t, i].astype(int)) |
| cv2.circle(viz_ext, pt, 1, (0, 255, 0), -1) |
|
|
| cv2.putText(viz_ext, f"Ext: GT mesh (blue) | Tracked mesh (red) | Others (green)", |
| (5, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (255, 255, 255), 1) |
|
|
| |
| viz_wrist = frames_wrist[t].copy() |
|
|
| for i in range(len(tracks_wrist[t])): |
| if vis_wrist[t, i]: |
| pt = tuple(tracks_wrist[t, i].astype(int)) |
| color = (255, 255, 0) if i < 300 else (0, 255, 255) |
| cv2.circle(viz_wrist, pt, 1, color, -1) |
|
|
| cv2.putText(viz_wrist, f"Wrist: 300 sparse (cyan) + 700 dense bottom (yellow)", |
| (5, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (255, 255, 255), 1) |
|
|
| combined = np.concatenate([viz_ext, viz_wrist], axis=1) |
| cv2.putText(combined, f"Episode {episode_idx} | Frame {t}/{T}", |
| (5, img_h - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 255), 1) |
| video_frames.append(combined) |
|
|
| video_path = output_dir / f"preview_episode_{episode_idx:06d}.mp4" |
| media.write_video(str(video_path), video_frames, fps=10) |
|
|
| return { |
| 'episode_idx': episode_idx, |
| 'uuid': uuid, |
| 'frames_exterior': np.array(frames_ext), |
| 'frames_wrist': np.array(frames_wrist), |
| 'actions': np.array(actions), |
| 'mesh_vertices_2d_exterior': all_mesh_2d_ext, |
| 'mesh_vertices_vis_exterior': all_mesh_vis_ext, |
| 'tracks_exterior': tracks_ext, |
| 'tracks_vis_exterior': vis_ext, |
| 'tracks_wrist': tracks_wrist, |
| 'tracks_vis_wrist': vis_wrist, |
| } |
|
|
|
|
| def main(): |
| import argparse |
| parser = argparse.ArgumentParser() |
| parser.add_argument('--gpu-id', type=int, required=True, help='GPU ID (0-15 for 2 machines)') |
| parser.add_argument('--num-gpus', type=int, default=16, help='Total number of GPUs') |
| parser.add_argument('--machine-id', type=int, required=True, help='Machine ID (0 or 1)') |
| parser.add_argument('--output-dir', type=str, required=True, help='Output directory') |
| parser.add_argument('--max-frames', type=int, default=400, help='Max frames per episode') |
| parser.add_argument('--preview-total', type=int, default=20, help='Total preview videos across all GPUs') |
| args = parser.parse_args() |
|
|
| |
| os.environ['CUDA_VISIBLE_DEVICES'] = str(args.gpu_id) |
| device = torch.device('cuda:0') |
|
|
| output_dir = Path(args.output_dir) |
| output_dir.mkdir(parents=True, exist_ok=True) |
| data_dir = output_dir / 'data' |
| data_dir.mkdir(exist_ok=True) |
| preview_dir = output_dir / 'preview_videos' |
| preview_dir.mkdir(exist_ok=True) |
|
|
| global_gpu_id = args.machine_id * 8 + args.gpu_id |
|
|
| print("=" * 80) |
| print(f"Multi-GPU DROID Preprocessing") |
| print("=" * 80) |
| print(f" Machine ID: {args.machine_id}") |
| print(f" Local GPU ID: {args.gpu_id}") |
| print(f" Global GPU ID: {global_gpu_id}/{args.num_gpus}") |
| print(f" Output: {output_dir}") |
| print(f" Max frames: {args.max_frames}") |
| print(f" Preview videos: {args.preview_total} total (distributed)") |
| print("=" * 80) |
|
|
| |
| calib_dir = '/root/workspace/code/wmrl/Dual-Dynamics-Models/DROID-main/vision/u/wenlongh/datasets/droid_v4/cameras' |
| calib_loader = CameraCalibrationLoader(calib_dir) |
| projector = FrankaMeshProjector(use_gui=False) |
|
|
| calib_path = Path(calib_dir) |
| uuid_list = [f.stem.replace('_cameras', '') for f in sorted(calib_path.glob("*_cameras.json"))] |
| print(f"Loaded {len(uuid_list)} camera calibrations") |
|
|
| |
| print("Loading CoTracker...") |
| from cotracker.predictor import CoTrackerOnlinePredictor, CoTrackerPredictor |
|
|
| |
| cotracker_paths = [ |
| '/mnt/kevin/vlm_models/cotracker/scaled_offline.pth', |
| '/mnt/kevin/vlm_models/hub/checkpoints/scaled_offline.pth', |
| '/root/workspace/code/wmrl/Dual-Dynamics-Models/DROID-main/co-tracker/checkpoints/scaled_offline.pth', |
| ] |
|
|
| cotracker_checkpoint = None |
| for path in cotracker_paths: |
| if Path(path).exists(): |
| cotracker_checkpoint = path |
| print(f"Found CoTracker checkpoint: {cotracker_checkpoint}") |
| break |
|
|
| if cotracker_checkpoint is None: |
| raise FileNotFoundError(f"CoTracker checkpoint not found. Tried:\n" + "\n".join(cotracker_paths)) |
|
|
| cotracker = CoTrackerPredictor(checkpoint=cotracker_checkpoint) |
| cotracker = cotracker.to(device) |
| cotracker.eval() |
|
|
| |
| print("Loading DROID dataset...") |
| droid_path = '/mnt/kevin/data/droid/droid/1.0.0' |
| builder = tfds.builder_from_directory(droid_path) |
| dataset = builder.as_dataset(split='train') |
|
|
| |
| print("Counting total episodes...") |
| total_episodes = sum(1 for _ in dataset) |
| print(f"Total episodes in dataset: {total_episodes}") |
|
|
| |
| episodes_per_gpu = total_episodes // args.num_gpus |
| start_idx = global_gpu_id * episodes_per_gpu |
| end_idx = start_idx + episodes_per_gpu if global_gpu_id < args.num_gpus - 1 else total_episodes |
|
|
| print(f"This GPU will process episodes {start_idx} to {end_idx-1} ({end_idx - start_idx} episodes)") |
|
|
| |
| preview_interval = max(1, (end_idx - start_idx) // max(1, args.preview_total // args.num_gpus)) |
|
|
| processed_count = 0 |
| skipped_count = 0 |
| preview_count = 0 |
|
|
| pbar = tqdm(total=end_idx - start_idx, desc=f"GPU {global_gpu_id}") |
|
|
| for episode_idx, episode in enumerate(dataset): |
| |
| if episode_idx < start_idx: |
| continue |
| if episode_idx >= end_idx: |
| break |
|
|
| local_idx = episode_idx - start_idx |
|
|
| |
| uuid = find_closest_calibration(episode, uuid_list) |
| if uuid is None or not calib_loader.has_refined_extrinsics(uuid): |
| skipped_count += 1 |
| pbar.update(1) |
| continue |
|
|
| |
| save_video = (local_idx % preview_interval == 0) and (preview_count < args.preview_total // args.num_gpus) |
|
|
| try: |
| result = process_episode( |
| episode, episode_idx, projector, calib_loader, uuid, |
| cotracker, device, max_frames=args.max_frames, |
| save_video=save_video, output_dir=preview_dir |
| ) |
|
|
| if result is None: |
| skipped_count += 1 |
| pbar.update(1) |
| continue |
|
|
| |
| npz_path = data_dir / f"episode_{episode_idx:06d}.npz" |
| np.savez_compressed( |
| npz_path, |
| episode_idx=result['episode_idx'], |
| uuid=result['uuid'], |
| images_exterior=result['frames_exterior'], |
| images_wrist=result['frames_wrist'], |
| actions=result['actions'], |
| mesh_vertices_2d_exterior=result['mesh_vertices_2d_exterior'], |
| mesh_vertices_vis_exterior=result['mesh_vertices_vis_exterior'], |
| tracks_exterior=result['tracks_exterior'], |
| tracks_vis_exterior=result['tracks_vis_exterior'], |
| tracks_wrist=result['tracks_wrist'], |
| tracks_vis_wrist=result['tracks_vis_wrist'], |
| mesh_indices=np.array([0, 1, 2, 3, 4, 5, 6], dtype=np.int32), |
| ) |
|
|
| processed_count += 1 |
| if save_video: |
| preview_count += 1 |
| pbar.update(1) |
|
|
| except Exception as e: |
| print(f"\nError processing episode {episode_idx}: {e}") |
| skipped_count += 1 |
| pbar.update(1) |
| continue |
|
|
| pbar.close() |
|
|
| |
| metadata = { |
| 'gpu_id': global_gpu_id, |
| 'machine_id': args.machine_id, |
| 'local_gpu_id': args.gpu_id, |
| 'processed_episodes': processed_count, |
| 'skipped_episodes': skipped_count, |
| 'preview_videos': preview_count, |
| 'episode_range': [start_idx, end_idx], |
| 'split': 'train', |
| 'camera_params': { |
| 'exterior': { |
| 'extrinsics': 'refined', |
| 'intrinsics': 'measured', |
| 'inversion': False |
| }, |
| 'wrist': { |
| 'sampling': 'random', |
| 'dense_region': 'bottom_60_100_pct' |
| } |
| }, |
| 'point_distribution': { |
| 'exterior': { |
| 'total_tracked_points': 1000, |
| 'mesh_vertices_tracked': 7, |
| 'additional_points': 993, |
| 'arm_shaped_strategy': 'gaussian_15px_per_mesh + lines_between', |
| }, |
| 'wrist': { |
| 'total_tracked_points': 1000, |
| 'sparse_uniform': 300, |
| 'dense_bottom': 700 |
| } |
| }, |
| 'image_resolution': [180, 320], |
| 'max_frames_per_episode': args.max_frames, |
| 'cotracker_model': 'scaled_offline.pth', |
| 'cotracker_chunking': 'automatic_internal_only' |
| } |
|
|
| metadata_path = output_dir / f'metadata_gpu{global_gpu_id:02d}.json' |
| with open(metadata_path, 'w') as f: |
| json.dump(metadata, f, indent=2) |
|
|
| print("\n" + "=" * 80) |
| print(f"GPU {global_gpu_id} Complete") |
| print("=" * 80) |
| print(f" Processed: {processed_count} episodes") |
| print(f" Skipped: {skipped_count} episodes") |
| print(f" Preview videos: {preview_count}") |
| print(f" Metadata: {metadata_path}") |
| print("=" * 80) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|