#!/usr/bin/env python3 """ Reprocessing script for existing DROID .npz files. This script updates old preprocessed files to match the new structure: - Track counts: 1000 → 1105 (7 mesh + 98 grid + 1000 random) - Recalculates wrist mesh with correct hardcoded interpolation - Ensures both views have consistent structure Usage: # Test run on first 10 files python reprocess_existing_npz.py --start-idx 0 --end-idx 10 --dry-run # Process range with GPU 0 python reprocess_existing_npz.py --start-idx 0 --end-idx 622 --gpu-id 0 # Full reprocessing (use run_reprocessing_8gpu.sh) python reprocess_existing_npz.py --start-idx 0 --end-idx 4976 --gpu-id 0 """ import argparse import sys import numpy as np from pathlib import Path from tqdm import tqdm import tensorflow_datasets as tfds import tensorflow as tf # Disable TensorFlow GPU to avoid conflicts with PyTorch tf.config.set_visible_devices([], 'GPU') # Import preprocessing functions from main script sys.path.insert(0, str(Path(__file__).parent.parent)) from scripts.preprocess_droid_rlds_final import ( process_episode, load_cotracker, find_closest_calibration ) from utils.load_camera_calibration import CameraCalibrationLoader from utils.franka_mesh_projection import FrankaMeshProjector def load_existing_npz_files(data_dir): """Load all existing .npz files and extract episode indices.""" data_dir = Path(data_dir) / "data" npz_files = sorted(data_dir.glob("episode_*.npz")) episode_files = [] for npz_path in npz_files: # Extract episode index from filename filename = npz_path.stem # "episode_000123" episode_idx = int(filename.split('_')[1]) episode_files.append((episode_idx, npz_path)) return sorted(episode_files) def check_if_needs_reprocessing(npz_path): """Check if .npz file needs reprocessing based on track count.""" try: data = np.load(npz_path, allow_pickle=True) tracks_ext_shape = data['tracks_exterior'].shape tracks_wrist_shape = data['tracks_wrist'].shape # Check if tracks have old count (1000) instead of new (1105) if tracks_ext_shape[1] != 1105 or tracks_wrist_shape[1] != 1105: return True, f"tracks={tracks_ext_shape[1]} (need 1105)" # Check if wrist fixed mesh exists if 'mesh_vertices_2d_wrist_fixed' not in data: return True, "missing wrist mesh" return False, "already correct" except Exception as e: return True, f"error: {e}" def reprocess_episode(episode_idx, rlds_dataset, uuid_list, calib_loader, projector, cotracker, device, output_dir, dry_run=False, use_batching=False, batch_size=500): """ Reprocess a single episode with new 1105-point logic. Args: episode_idx: RLDS episode index rlds_dataset: RLDS dataset object uuid_list: List of calibration UUIDs calib_loader: Camera calibration loader projector: Franka mesh projector cotracker: CoTracker model device: torch device output_dir: Output directory path dry_run: If True, don't save files use_batching: If True, use batched tracking to reduce memory batch_size: Number of points per batch when use_batching=True Returns: success (bool), message (str) """ try: # Get episode from RLDS episodes = rlds_dataset.take(episode_idx + 1).skip(episode_idx) episode = next(iter(episodes)) # Find calibration uuid = find_closest_calibration(episode, uuid_list) if uuid is None or not calib_loader.has_refined_extrinsics(uuid): return False, "no valid calibration found" # Run preprocessing (same logic as original) result = process_episode( episode=episode, episode_idx=episode_idx, uuid=uuid, calib_loader=calib_loader, projector=projector, cotracker=cotracker, device=device, output_dir=None, # Don't save preview video save_video=False, max_frames=400, use_batching=use_batching, batch_size=batch_size ) if result is None: return False, "preprocessing returned None (invalid episode)" # Verify track counts tracks_ext_shape = result['tracks_exterior'].shape tracks_wrist_shape = result['tracks_wrist'].shape if tracks_ext_shape[1] != 1105 or tracks_wrist_shape[1] != 1105: return False, f"wrong track count: ext={tracks_ext_shape[1]}, wrist={tracks_wrist_shape[1]}" # Save to .npz (if not dry run) if not dry_run: output_file = Path(output_dir) / "data" / f"episode_{episode_idx:06d}.npz" output_file.parent.mkdir(parents=True, exist_ok=True) np.savez_compressed( str(output_file), 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'], mesh_vertices_2d_wrist_fixed=result['mesh_vertices_2d_wrist_fixed'], mesh_vertices_vis_wrist_fixed=result['mesh_vertices_vis_wrist_fixed'], 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.arange(7, dtype=np.int32), ) return True, f"ext={tracks_ext_shape}, wrist={tracks_wrist_shape}" except Exception as e: return False, f"error: {str(e)[:100]}" def main(): parser = argparse.ArgumentParser(description="Reprocess existing DROID .npz files") parser.add_argument('--data-dir', type=str, default='/mnt/kevin/data/droid_processed_1000pts', help='Directory containing existing .npz files') parser.add_argument('--start-idx', type=int, default=0, help='Start index in file list (not episode index)') parser.add_argument('--end-idx', type=int, default=None, help='End index in file list (exclusive)') parser.add_argument('--gpu-id', type=int, default=0, help='GPU ID to use') parser.add_argument('--dry-run', action='store_true', help='Check what needs reprocessing without saving') parser.add_argument('--force', action='store_true', help='Reprocess all files, even if already correct') args = parser.parse_args() # Setup import torch # Create device (important for multi-GPU parallelization) if args.gpu_id is not None: device = torch.device(f'cuda:{args.gpu_id}' if torch.cuda.is_available() else 'cpu') else: device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print("=" * 80) print("DROID Reprocessing: Updating Existing .npz Files") print("=" * 80) print(f" Data directory: {args.data_dir}") print(f" GPU: {device}") print(f" Dry run: {args.dry_run}") print(f" Force reprocess: {args.force}") print("=" * 80) # Load existing files print("\nScanning existing .npz files...") episode_files = load_existing_npz_files(args.data_dir) print(f"Found {len(episode_files)} existing files") # Filter by index range if args.end_idx is None: args.end_idx = len(episode_files) episode_files = episode_files[args.start_idx:args.end_idx] print(f"Processing files {args.start_idx} to {args.end_idx} ({len(episode_files)} files)") # Check which files need reprocessing print("\nChecking which files need reprocessing...") files_to_process = [] for episode_idx, npz_path in tqdm(episode_files, desc="Checking"): if args.force: files_to_process.append((episode_idx, npz_path, "forced")) else: needs_reprocessing, reason = check_if_needs_reprocessing(npz_path) if needs_reprocessing: files_to_process.append((episode_idx, npz_path, reason)) print(f"\n{len(files_to_process)} / {len(episode_files)} files need reprocessing") if args.dry_run: print("\nDRY RUN - Files that would be reprocessed:") for episode_idx, npz_path, reason in files_to_process[:20]: # Show first 20 print(f" Episode {episode_idx:6d}: {reason}") if len(files_to_process) > 20: print(f" ... and {len(files_to_process) - 20} more") print("\nRun without --dry-run to actually reprocess") return if len(files_to_process) == 0: print("All files already have correct structure. Nothing to do!") return # Load RLDS dataset and CoTracker print("\nLoading calibration, projector, and CoTracker...") 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) # Load CoTracker with correct device (critical for multi-GPU distribution!) cotracker, device = load_cotracker(device=device) print(f"CoTracker loaded on: {device}") # Load UUID list 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") # Load RLDS dataset print("Loading DROID dataset...") droid_path = '/mnt/kevin/data/droid/droid/1.0.0' builder = tfds.builder_from_directory(droid_path) rlds_dataset = builder.as_dataset(split='train') # Reprocess files print(f"\nReprocessing {len(files_to_process)} files...") success_count = 0 skip_count = 0 error_count = 0 oom_retry_count = 0 for episode_idx, npz_path, reason in tqdm(files_to_process, desc="Reprocessing"): # OOM retry logic: try unbatched first, retry with batching on OOM try: success, message = reprocess_episode( episode_idx, rlds_dataset, uuid_list, calib_loader, projector, cotracker, device, args.data_dir, dry_run=False, use_batching=False ) except Exception as e: # Check if it's an OOM error import torch if isinstance(e, torch.cuda.OutOfMemoryError): tqdm.write(f" OOM on episode {episode_idx}, retrying with batching...") torch.cuda.empty_cache() oom_retry_count += 1 try: success, message = reprocess_episode( episode_idx, rlds_dataset, uuid_list, calib_loader, projector, cotracker, device, args.data_dir, dry_run=False, use_batching=True, batch_size=500 ) except Exception as retry_e: success = False message = f"OOM retry failed: {str(retry_e)[:50]}" else: success = False message = f"error: {str(e)[:100]}" if success: success_count += 1 else: error_count += 1 if error_count <= 10: # Show first 10 errors tqdm.write(f" ERROR episode {episode_idx}: {message}") # Summary print("\n" + "=" * 80) print("Reprocessing Complete") print("=" * 80) print(f" Success: {success_count}") print(f" Errors: {error_count}") print(f" OOM retries: {oom_retry_count}") print(f" Total processed: {success_count + error_count}") print("=" * 80) if __name__ == '__main__': main()