""" Precompute task condition vectors (DINOv3 difference features). Pipeline: For each episode: - Take the first / last frame images -> resize to (W,H)=image_size -> ImageNet normalization - Frozen DINOv3 forward, take the last-layer CLS token (last_hidden_state[:, 0]) - diff = cls_last - cls_first # (D,) For each task (all episodes of clean + randomized together): - task_cond = mean(diff over episodes) # (D,) Output (mirrors the dataset task structure into a new directory; the original dataset directory is not written to): {output_dir}/{task_name}/task_cond.npy # shape (D,), float32 {output_dir}/meta.json # metadata Usage: python precompute_task_cond.py \ --config ./configs/robotwin.yaml \ --output_dir /home/yf/Desktop/Code/VLA/RoboTwin/RoboTwin/data-200-10-taskcond """ import os import json import argparse import logging from pathlib import Path from collections import defaultdict import cv2 import h5py import numpy as np import torch from tqdm import tqdm from omegaconf import OmegaConf from transformers import AutoModel, AutoConfig logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32) IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=np.float32) def decode_img(buf): arr = np.frombuffer(buf, dtype=np.uint8) img = cv2.imdecode(arr, cv2.IMREAD_COLOR) return img def preprocess_image(img_np, image_size): """HxWx3 uint8 RGB → (1,3,H,W) float32 ImageNet normalized. image_size=(W,H)""" if (img_np.shape[1], img_np.shape[0]) != tuple(image_size): img_np = cv2.resize(img_np, tuple(image_size), interpolation=cv2.INTER_LINEAR) img = img_np.astype(np.float32) / 255.0 img = (img - IMAGENET_MEAN) / IMAGENET_STD img = np.transpose(img, (2, 0, 1))[None] # (1,3,H,W) return img def scan_episodes(dataset_dir, data_mode, camera_name): """Return [{task_name, hdf5_path}]; clean+randomized share the same task_name""" root = Path(dataset_dir) splits = ["demo_clean", "demo_randomized"] if data_mode == "both" else [f"demo_{data_mode}"] episodes = [] for task_dir in sorted([d for d in root.iterdir() if d.is_dir()]): for split in splits: data_dir = task_dir / split / "data" if not data_dir.exists(): continue for hdf5_path in sorted(data_dir.glob("*.hdf5")): episodes.append({ 'task_name': task_dir.name, 'hdf5_path': str(hdf5_path), }) return episodes @torch.no_grad() def compute_episode_diff(model, hdf5_path, camera_name, image_size, device, dtype): """Return the difference feature (D,) of a single episode as numpy float32, or None on failure""" with h5py.File(hdf5_path, 'r') as f: if camera_name not in f['observation']: return None rgb_ds = f['observation'][camera_name]['rgb'] n = rgb_ds.shape[0] if n < 2: return None first_buf = rgb_ds[0] last_buf = rgb_ds[n - 1] first_img = decode_img(first_buf) last_img = decode_img(last_buf) if first_img is None or last_img is None: return None batch = np.concatenate([ preprocess_image(first_img, image_size), preprocess_image(last_img, image_size), ], axis=0) # (2,3,H,W) px = torch.from_numpy(batch).to(device, dtype) out = model(pixel_values=px, return_dict=True) cls = out.last_hidden_state[:, 0, :] # (2, D) — last-layer CLS cls = cls.float().cpu().numpy() diff = cls[1] - cls[0] # last - first return diff.astype(np.float32) def main(): parser = argparse.ArgumentParser(description="Precompute DINOv3 diff-feature task condition vectors") parser.add_argument("--config", type=str, default="./configs/robotwin_task_cond_fewshot.yaml") parser.add_argument("--output_dir", type=str, default='/home/yf/Desktop/Code/VLA/RoboTwin/RoboTwin/data-200-10-taskcond-clean', help="new directory that mirrors the dataset task structure for saving task condition vectors") parser.add_argument("--device", type=str, default="cuda") args = parser.parse_args() cfg = OmegaConf.load(args.config) dataset_dir = cfg.dataset.dataset_dir data_mode = cfg.dataset.data_mode camera_name = list(cfg.dataset.camera_names)[0] image_size = tuple(OmegaConf.to_container(cfg.dataset.image_size, resolve=True)) # (W,H) ckpt_path = cfg.model.vision_encoder.checkpoint_path device = args.device if torch.cuda.is_available() else "cpu" dtype = torch.bfloat16 if (device != "cpu" and torch.cuda.is_bf16_supported()) else torch.float32 output_dir = Path(args.output_dir) if str(output_dir.resolve()) == str(Path(dataset_dir).resolve()): raise ValueError("output_dir must not be the same as the original dataset directory!") output_dir.mkdir(parents=True, exist_ok=True) logger.info(f"Loading frozen DINOv3 from {ckpt_path} ...") dino_cfg = AutoConfig.from_pretrained(ckpt_path, local_files_only=True) model = AutoModel.from_pretrained(ckpt_path, torch_dtype=dtype, local_files_only=True).to(device) model.eval() for p in model.parameters(): p.requires_grad = False hidden_size = getattr(dino_cfg, "hidden_size", None) logger.info(f"Scanning episodes under {dataset_dir} (mode={data_mode}) ...") episodes = scan_episodes(dataset_dir, data_mode, camera_name) if not episodes: raise ValueError(f"No episodes found under {dataset_dir}") logger.info(f"Found {len(episodes)} episodes.") task_diffs = defaultdict(list) # task_name -> [diff, ...] skipped = 0 for ep in tqdm(episodes, desc="Computing diff features"): diff = compute_episode_diff(model, ep['hdf5_path'], camera_name, image_size, device, dtype) if diff is None: skipped += 1 continue task_diffs[ep['task_name']].append(diff) logger.info(f"Computed diffs for {len(task_diffs)} tasks (skipped {skipped} episodes).") meta = { "dino_checkpoint": str(ckpt_path), "hidden_size": int(hidden_size) if hidden_size is not None else None, "image_size": list(image_size), "data_mode": data_mode, "camera_name": camera_name, "feature": "last_layer_cls_diff (last_frame - first_frame), averaged per task", "tasks": {}, } for task_name, diffs in sorted(task_diffs.items()): diffs_np = np.stack(diffs, axis=0) # (num_ep, D) task_cond = diffs_np.mean(axis=0).astype(np.float32) # (D,) task_out_dir = output_dir / task_name task_out_dir.mkdir(parents=True, exist_ok=True) np.save(task_out_dir / "task_cond.npy", task_cond) meta["tasks"][task_name] = { "num_episodes": int(diffs_np.shape[0]), "dim": int(task_cond.shape[0]), "norm": float(np.linalg.norm(task_cond)), } logger.info(f" {task_name}: {diffs_np.shape[0]} eps, dim={task_cond.shape[0]}, " f"|cond|={np.linalg.norm(task_cond):.3f}") with open(output_dir / "meta.json", "w") as f: json.dump(meta, f, indent=2, ensure_ascii=False) logger.info(f"Done. Saved task condition vectors to {output_dir}") logger.info(f"Meta saved to {output_dir / 'meta.json'}") if __name__ == "__main__": main()