""" EgoDex Ultimate Speed Preprocessing Worker (Distributed & OOM-Safe) """ import sys import os import time import queue import threading import numpy as np import torch import cv2 import h5py import argparse from pathlib import Path from tqdm import tqdm import gc # [FIX] 优化显存分配策略 os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True" # ============================================================================= # 1. Configuration # ============================================================================= TARGET_SHORTER_SIDE = 224 ENABLE_TORCH_COMPILE = False def get_sparse_hand_keynames(side='right'): prefix = side return [ f'{prefix}Hand', # Wrist f'{prefix}ThumbTip', # Thumb f'{prefix}IndexFingerTip', # Index f'{prefix}MiddleFingerTip', # Middle f'{prefix}RingFingerTip', # Ring f'{prefix}LittleFingerTip', # Little f'{prefix}IndexFingerKnuckle' # Knuckle ] KEYPOINT_NAMES = get_sparse_hand_keynames('right') + get_sparse_hand_keynames('left') # ============================================================================= # 2. Optimized Utils # ============================================================================= def load_cotracker_optimized(device=None): # 假设 cotracker 已安装在环境中 from cotracker.predictor import CoTrackerPredictor if device is None: device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') checkpoint_paths = [ './scaled_offline.pth', '/mnt/kevin/vlm_models/cotracker/scaled_offline.pth', os.path.expanduser('~/.cache/cotracker/scaled_offline.pth') ] ckpt = "scaled_offline.pth" for p in checkpoint_paths: if os.path.exists(p): ckpt = p break print(f"Loading CoTracker from: {ckpt}") model = CoTrackerPredictor(checkpoint=ckpt) model = model.to(device) model.eval() if ENABLE_TORCH_COMPILE and hasattr(torch, 'compile'): try: print("Compiling CoTracker model...") model = torch.compile(model, mode="reduce-overhead") except Exception as e: print(f"Compilation failed, using eager mode: {e}") return model def sample_single_grid(n=5, img_h=1080, img_w=1920): u = np.linspace(0.05 * img_w, 0.95 * img_w, n) v = np.linspace(0.05 * img_h, 0.95 * img_h, n) u_grid, v_grid = np.meshgrid(u, v) return np.stack([u_grid.flatten(), v_grid.flatten()], axis=-1).astype(np.float32) def create_temporal_queries(points_2d, T, num_fixed): N = len(points_2d) queries = np.zeros((N, 3), dtype=np.float32) queries[:num_fixed, 0] = 0 queries[:num_fixed, 1:] = points_2d[:num_fixed] if T > 1: queries[num_fixed:, 0] = np.random.randint(0, T, size=N - num_fixed) queries[num_fixed:, 1:] = points_2d[num_fixed:] else: queries[num_fixed:, 1:] = points_2d[num_fixed:] return queries def project_points_vectorized(tfs_world, cam_ext_world, K, img_h, img_w): w2c = np.linalg.inv(cam_ext_world) p_world = tfs_world[..., :3, 3] ones = np.ones_like(p_world[..., :1]) p_world_homo = np.concatenate([p_world, ones], axis=-1) p_cam_homo = np.einsum('tij, tnj -> tni', w2c, p_world_homo) p_cam = p_cam_homo[..., :3] fx, fy = K[0, 0], K[1, 1] cx, cy = K[0, 2], K[1, 2] x, y, z = p_cam[..., 0], p_cam[..., 1], p_cam[..., 2] z_safe = np.where(z > 0.01, z, 1e-6) u = (fx * x / z_safe) + cx v = (fy * y / z_safe) + cy points_2d = np.stack([u, v], axis=-1).astype(np.float32) in_front = z > 0.01 in_bounds = (u >= 0) & (u < img_w) & (v >= 0) & (v < img_h) visibility = in_front & in_bounds points_2d[~visibility] = 0.0 return points_2d, visibility # ============================================================================= # 3. Pipeline Stages # ============================================================================= def loader_thread(file_queue, data_queue): while True: task = file_queue.get() if task is None: data_queue.put(None) break global_idx, h5_path, mp4_path = task try: cap = cv2.VideoCapture(str(mp4_path)) w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) scale_w = TARGET_SHORTER_SIDE / w scale_h = TARGET_SHORTER_SIDE / h new_w, new_h = int(w * scale_w), int(h * scale_h) frames = [] while True: ret, frame = cap.read() if not ret: break frame = cv2.resize(frame, (new_w, new_h), interpolation=cv2.INTER_LINEAR) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frames.append(frame) cap.release() frames = np.array(frames) if len(frames) < 10: raise ValueError("Video too short") T, H, W, _ = frames.shape with h5py.File(h5_path, 'r') as f: h5_len = f['transforms']['camera'].shape[0] min_len = min(T, h5_len) frames = frames[:min_len] T = min_len cam_ext = f['transforms']['camera'][:min_len] K = f['camera']['intrinsic'][:] K_scaled = K.copy() K_scaled[0, :] *= scale_w K_scaled[1, :] *= scale_h tfs_list, conf_list = [], [] has_conf = 'confidences' in f for kp in KEYPOINT_NAMES: tfs_list.append(f['transforms'][kp][:min_len] if kp in f['transforms'] else np.eye(4)[None].repeat(T,0)) conf_list.append(f['confidences'][kp][:min_len] if has_conf and kp in f['confidences'] else np.ones(T)) tfs_world = np.stack(tfs_list, axis=1) confidences = np.stack(conf_list, axis=1) mesh_2d_gt, mesh_vis_gt = project_points_vectorized(tfs_world, cam_ext, K_scaled, H, W) mesh_vis_gt[confidences < 0.1] = False # Sampling mesh_2d_0 = mesh_2d_gt[0] grid_points = sample_single_grid(n=5, img_h=H, img_w=W) num_random = 249 random_points = (np.random.rand(num_random, 2) * [W, H]).astype(np.float32) query_points = np.vstack([mesh_2d_0, grid_points, random_points]) num_fixed = 14 + 25 queries = create_temporal_queries(query_points, T, num_fixed) batch_data = { 'frames': frames, 'queries': queries, 'mesh_2d_gt': mesh_2d_gt, 'mesh_vis_gt': mesh_vis_gt, 'K_scaled': K_scaled, 'cam_ext': cam_ext, 'tfs_world': tfs_world, 'global_idx': global_idx, 'num_fixed': num_fixed } data_queue.put(batch_data) except Exception as e: pass def saver_thread(save_queue, output_dir): while True: item = save_queue.get() if item is None: break save_path, data_dict = item try: np.savez_compressed(save_path, **data_dict) except Exception as e: print(f"Save error: {e}") def main(): torch.set_float32_matmul_precision('high') parser = argparse.ArgumentParser() parser.add_argument('--data_root', type=str, required=True) parser.add_argument('--output_dir', type=str, required=True) parser.add_argument('--gpu_id', type=int, default=0, help="Local GPU ID") parser.add_argument('--world_size', type=int, default=1, help="Total workers across all nodes") parser.add_argument('--global_rank', type=int, default=0, help="Unique global rank") args = parser.parse_args() data_root = Path(args.data_root) output_dir = Path(args.output_dir) output_dir.mkdir(parents=True, exist_ok=True) device = torch.device(f'cuda:{args.gpu_id}') model = load_cotracker_optimized(device) all_files = sorted(list(data_root.rglob("*.hdf5"))) indexed_files = list(enumerate(all_files)) # [CRITICAL] 跨节点切分数据 my_tasks = indexed_files[args.global_rank::args.world_size] print(f"[Global Rank {args.global_rank}] GPU {args.gpu_id}: Processing {len(my_tasks)} files.") file_queue = queue.Queue() data_queue = queue.Queue(maxsize=3) save_queue = queue.Queue(maxsize=10) for task in my_tasks: idx, h5_f = task mp4_f = h5_f.with_suffix('.mp4') if mp4_f.exists(): file_queue.put((idx, h5_f, mp4_f)) file_queue.put(None) t_load = threading.Thread(target=loader_thread, args=(file_queue, data_queue)) t_save = threading.Thread(target=saver_thread, args=(save_queue, output_dir)) t_load.daemon = True t_save.daemon = True t_load.start() t_save.start() pbar = tqdm(total=len(my_tasks), position=args.gpu_id, desc=f"GPU {args.gpu_id}") while True: batch = data_queue.get() if batch is None: break frames = batch['frames'] queries = batch['queries'] num_fixed = batch['num_fixed'] video_tensor = torch.from_numpy(frames).permute(0, 3, 1, 2)[None].to(device).float() / 255.0 queries_tensor = torch.from_numpy(queries)[None].to(device).float() try: with torch.no_grad(): with torch.autocast(device_type='cuda', dtype=torch.float16): tracks, vis = model(video_tensor, queries=queries_tensor, backward_tracking=False) tracks_b, vis_b = model(video_tensor, queries=queries_tensor, backward_tracking=True) tracks = (tracks + tracks_b) / 2.0 vis = (vis + vis_b) / 2.0 variance = torch.var(tracks[0], dim=0).sum(dim=-1) variance[:num_fixed] = float('inf') valid_idx = torch.where(variance > 10.0)[0] tracks_cpu = tracks[0, :, valid_idx].float().cpu().numpy() vis_cpu = vis[0, :, valid_idx].float().cpu().numpy() save_path = output_dir / f"episode_{batch['global_idx']:06d}.npz" final_data = { 'episode_idx': batch['global_idx'], 'images': frames, 'mesh_vertices_2d_exterior': batch['mesh_2d_gt'], 'mesh_vertices_vis_exterior': batch['mesh_vis_gt'], 'tracks_exterior': tracks_cpu, 'tracks_vis_exterior': vis_cpu, 'cam_intrinsics': batch['K_scaled'], 'cam_extrinsics': batch['cam_ext'], 'actions': batch['tfs_world'], 'keypoint_names': KEYPOINT_NAMES } save_queue.put((save_path, final_data)) except torch.cuda.OutOfMemoryError: print(f"[Rank {args.global_rank}] OOM on {batch['global_idx']}. Skipping.") del video_tensor, queries_tensor torch.cuda.empty_cache() except Exception as e: print(f"[Rank {args.global_rank}] Error on {batch['global_idx']}: {e}") pbar.update(1) save_queue.put(None) t_save.join() t_load.join() if __name__ == "__main__": main()