"""Frozen vision encoders (DINOv2, SigLIP) for classification probe baselines.""" from __future__ import annotations import os import shutil import time from dataclasses import dataclass from pathlib import Path from typing import Iterable import h5py import numpy as np from PIL import Image from probe_common import ( CLASSIFICATION_OUTPUT_ROOT, concept_steps, concept_timesteps_to_video_frames, ensure_dir, episode_label_stem, iter_video_frames, natural_key, resolve_episode_paths, ) FEATURE_SOURCE_CONCEPT = "concept" FEATURE_SOURCE_DINOV2 = "dinov2" FEATURE_SOURCE_SIGLIP = "siglip" FEATURE_SOURCE_LATENT_ACTION = "latent_action" FEATURE_SOURCE_UNIVLA = "univla" VISION_FEATURE_SOURCES = ( FEATURE_SOURCE_DINOV2, FEATURE_SOURCE_SIGLIP, FEATURE_SOURCE_LATENT_ACTION, FEATURE_SOURCE_UNIVLA, ) ALL_FEATURE_SOURCES = (FEATURE_SOURCE_CONCEPT, *VISION_FEATURE_SOURCES) MODEL_CONFIGS: dict[str, dict] = { FEATURE_SOURCE_DINOV2: { "hf_id": "facebook/dinov2-base", "embedding_dim": 768, }, FEATURE_SOURCE_SIGLIP: { "hf_id": "google/siglip-base-patch16-224", "embedding_dim": 768, }, } def hf_cache_root() -> Path: """Hub cache directory (HF_HOME/hub or legacy HF_HOME root).""" hf_home = Path(os.environ.get("HF_HOME", Path.home() / ".cache" / "huggingface")) hub = hf_home / "hub" return hub if hub.is_dir() else hf_home def hf_model_cache_dir(hf_id: str) -> Path: return hf_cache_root() / f"models--{hf_id.replace('/', '--')}" def clear_hf_model_cache(hf_id: str) -> None: target = hf_model_cache_dir(hf_id) if target.exists(): print(f"clearing corrupted HF cache: {target}", flush=True) shutil.rmtree(target, ignore_errors=True) # Legacy layout: blobs directly under HF_HOME legacy = Path(os.environ.get("HF_HOME", "")) / f"models--{hf_id.replace('/', '--')}" if legacy.is_dir() and legacy != target: print(f"clearing legacy HF cache: {legacy}", flush=True) shutil.rmtree(legacy, ignore_errors=True) def download_hf_snapshot(hf_id: str, max_retries: int = 2) -> str: """Download full model snapshot to local cache; retry after clearing corrupt cache.""" from huggingface_hub import snapshot_download cache_dir = str(hf_cache_root()) last_err: Exception | None = None for attempt in range(max_retries): try: local_dir = snapshot_download( repo_id=hf_id, cache_dir=cache_dir, resume_download=True, local_files_only=False, ) print(f"HF snapshot ready: {hf_id} -> {local_dir}", flush=True) return local_dir except Exception as exc: last_err = exc print(f"HF download failed ({attempt + 1}/{max_retries}) {hf_id}: {exc}", flush=True) clear_hf_model_cache(hf_id) time.sleep(2) raise RuntimeError(f"Failed to download {hf_id} after {max_retries} attempts: {last_err}") def prefetch_vision_models(feature_sources: Iterable[str]) -> None: """Pre-download all vision encoders once (avoids mid-batch cache races).""" for source in feature_sources: if source not in MODEL_CONFIGS: continue hf_id = MODEL_CONFIGS[source]["hf_id"] download_hf_snapshot(hf_id) def default_feature_root() -> Path: return CLASSIFICATION_OUTPUT_ROOT / "features" def feature_episode_path( feature_root: Path, feature_source: str, task: str, demo: str, episode_id: int, ) -> Path: return feature_root / feature_source / task / demo / f"{episode_label_stem(episode_id)}.h5" def load_precomputed_features( path: Path, feature_start: int = 0, feature_end: int | None = None, ) -> np.ndarray: if path.suffix == ".npz": data = np.load(path) key = "features" if "features" in data else "arr_0" if "arr_0" in data else list(data.files)[0] arr = data[key] else: with h5py.File(path, "r") as handle: if "features" in handle: arr = handle["features"][:] elif "concept" in handle: arr = handle["concept"][:] else: raise KeyError(f"{path} must contain dataset 'features' or 'concept'") if arr.ndim != 2: raise ValueError(f"{path} features must be 2D, got {arr.shape}") return arr[:, feature_start:feature_end].astype(np.float32, copy=False) @dataclass class VisionEncoder: feature_source: str model_name: str device: str def __post_init__(self) -> None: self._model = None self._processor = None @property def embedding_dim(self) -> int: cfg = MODEL_CONFIGS.get(self.feature_source, {}) return int(cfg.get("embedding_dim", 768)) def _lazy_load(self) -> None: if self._model is not None: return import torch from transformers import AutoImageProcessor, AutoModel cfg = MODEL_CONFIGS[self.feature_source] hf_id = self.model_name or cfg["hf_id"] local_dir = download_hf_snapshot(hf_id) self._processor = AutoImageProcessor.from_pretrained(local_dir, local_files_only=True) self._model = AutoModel.from_pretrained(local_dir, local_files_only=True) self._model.eval() try: self._model.to(self.device) except RuntimeError as exc: if self.device == "cpu": raise print(f"WARN: model.to({self.device}) failed: {exc}", flush=True) print("WARN: falling back to CPU for vision encoding (slower but works)", flush=True) self.device = "cpu" self._model.to("cpu") print(f"loaded {self.feature_source} model={hf_id} device={self.device}", flush=True) def encode_images(self, images: list[Image.Image], batch_size: int = 32) -> np.ndarray: import torch self._lazy_load() assert self._model is not None and self._processor is not None outputs: list[np.ndarray] = [] for start in range(0, len(images), batch_size): batch = images[start : start + batch_size] inputs = self._processor(images=batch, return_tensors="pt") inputs = {k: v.to(self.device) for k, v in inputs.items()} with torch.no_grad(): if self.feature_source == FEATURE_SOURCE_SIGLIP: feats = self._model.get_image_features(**inputs) else: out = self._model(**inputs) feats = out.last_hidden_state[:, 0] outputs.append(feats.detach().cpu().numpy().astype(np.float32)) return np.concatenate(outputs, axis=0) def probe_cuda_works() -> bool: """True only if PyTorch can allocate on GPU (nvidia-smi alone is not enough).""" try: import torch if not torch.cuda.is_available(): return False x = torch.zeros(1, device="cuda") del x torch.cuda.synchronize() return True except Exception as exc: print(f"CUDA probe failed ({exc}); will use CPU", flush=True) return False def resolve_device(requested: str | None = None) -> str: """Pick compute device. ``auto`` / None → cuda if usable, else cpu.""" req = (requested or "auto").lower() if req == "cpu": return "cpu" if req == "mps": import torch if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available(): return "mps" print("MPS requested but unavailable; using CPU", flush=True) return "cpu" if req == "cuda": if probe_cuda_works(): return "cuda" raise RuntimeError( "DEVICE=cuda requested but PyTorch cannot use GPU " "(common on RTX 5090: driver/CUDA vs torch build mismatch, Error 803). " "Try DEVICE=cpu or upgrade torch: pip install torch --index-url https://download.pytorch.org/whl/cu124" ) # auto if probe_cuda_works(): return "cuda" return "cpu" def print_torch_device_info() -> None: try: import torch print( f"torch={torch.__version__} cuda_build={torch.version.cuda} " f"cuda_available={torch.cuda.is_available()}", flush=True, ) if torch.cuda.is_available(): print(f"cuda_device={torch.cuda.get_device_name(0)}", flush=True) except Exception as exc: print(f"torch device info skipped: {exc}", flush=True) def pool_frame_indices(center: int, video_frames: int, radius: int) -> list[int]: if radius <= 0: return [max(0, min(center, video_frames - 1))] lo = max(0, center - radius) hi = min(video_frames - 1, center + radius) return list(range(lo, hi + 1)) def frames_needed_for_pooling( frame_map: np.ndarray, video_frames: int, pool_radius: int, ) -> set[int]: """All video frame indices required for center frames ± pool_radius.""" needed: set[int] = set() for center in frame_map: for f in pool_frame_indices(int(center), video_frames, pool_radius): needed.add(int(f)) return needed def extract_concept_aligned_features( encoder: VisionEncoder, video_path: Path, concept_count: int, video_frames: int, pool_radius: int = 1, batch_size: int = 32, ) -> tuple[np.ndarray, np.ndarray]: """Map each concept timestep to pooled vision embeddings.""" frame_map = concept_timesteps_to_video_frames(concept_count, video_frames) needed_frames = frames_needed_for_pooling(frame_map, video_frames, pool_radius) frame_to_image: dict[int, Image.Image] = {} max_frame = max(needed_frames) + 1 if needed_frames else 0 for f_idx, image in iter_video_frames(video_path, step=1, max_frame=max_frame, progress_every=100): if f_idx in needed_frames: frame_to_image[f_idx] = image if len(frame_to_image) == len(needed_frames): break missing = [f for f in sorted(needed_frames) if f not in frame_to_image] if missing: raise RuntimeError(f"Missing video frames {missing[:5]} from {video_path}") sorted_frames = sorted(needed_frames) unique_images = [frame_to_image[f] for f in sorted_frames] unique_emb = encoder.encode_images(unique_images, batch_size=batch_size) frame_to_emb = {f: unique_emb[i] for i, f in enumerate(sorted_frames)} feats = np.zeros((concept_count, encoder.embedding_dim), dtype=np.float32) mapped_frames = np.zeros(concept_count, dtype=np.int32) for t in range(concept_count): center = int(frame_map[t]) idxs = pool_frame_indices(center, video_frames, pool_radius) pooled = np.mean([frame_to_emb[int(i)] for i in idxs], axis=0) feats[t] = pooled mapped_frames[t] = center return feats, mapped_frames def write_feature_h5( out_path: Path, features: np.ndarray, *, feature_source: str, model_name: str, task: str, demo: str, episode_id: int, concept_count: int, video_frames: int, pool_radius: int, mapped_frames: np.ndarray, label_path: Path, video_path: Path, ) -> None: ensure_dir(out_path.parent) with h5py.File(out_path, "w") as handle: handle.create_dataset("features", data=features, compression="gzip") handle.create_dataset("video_frame", data=mapped_frames.astype(np.int32)) handle.attrs["feature_source"] = feature_source handle.attrs["model_name"] = model_name handle.attrs["task"] = task handle.attrs["demo"] = demo handle.attrs["episode_id"] = int(episode_id) handle.attrs["concept_count"] = int(concept_count) handle.attrs["video_frames"] = int(video_frames) handle.attrs["pool_radius"] = int(pool_radius) handle.attrs["alignment"] = "concept" handle.attrs["label_path"] = str(label_path) handle.attrs["video_path"] = str(video_path) def extract_episode_features( task: str, demo: str, episode_id: int, feature_source: str, label_root: Path, video_root: Path, feature_root: Path, label_kind: str = "full_label", validation_index: int = 0, pool_radius: int = 1, batch_size: int = 32, device: str | None = None, model_name: str | None = None, overwrite: bool = False, ) -> Path: if feature_source not in VISION_FEATURE_SOURCES: raise ValueError(f"Unsupported vision feature source: {feature_source}") out_path = feature_episode_path(feature_root, feature_source, task, demo, episode_id) if out_path.exists() and not overwrite: return out_path label_path, video_path, _ = resolve_episode_paths( task, demo, episode_id, label_root, video_root, label_kind, validation_index, ) T = concept_steps(label_path) from probe_common import ffprobe_video video_meta = ffprobe_video(video_path) V = int(video_meta["video_frames"]) cfg = MODEL_CONFIGS[feature_source] encoder = VisionEncoder( feature_source=feature_source, model_name=model_name or cfg["hf_id"], device=resolve_device(device), ) features, mapped_frames = extract_concept_aligned_features( encoder, video_path, T, V, pool_radius=pool_radius, batch_size=batch_size, ) write_feature_h5( out_path, features, feature_source=feature_source, model_name=encoder.model_name, task=task, demo=demo, episode_id=episode_id, concept_count=T, video_frames=V, pool_radius=pool_radius, mapped_frames=mapped_frames, label_path=label_path, video_path=video_path, ) print(f"wrote {out_path} shape={features.shape}", flush=True) return out_path def batch_extract_features( task: str, demos: Iterable[str], feature_sources: Iterable[str], episode_ids_by_demo: dict[str, list[int]], label_root: Path, video_root: Path, feature_root: Path, label_kind: str = "full_label", validation_index: int = 0, pool_radius: int = 1, batch_size: int = 32, device: str | None = None, overwrite: bool = False, ) -> list[Path]: written: list[Path] = [] encoders: dict[str, VisionEncoder] = {} valid_sources = [s for s in feature_sources if s in MODEL_CONFIGS] if valid_sources: prefetch_vision_models(valid_sources) for demo in demos: episode_ids = episode_ids_by_demo.get(demo, []) for feature_source in feature_sources: if feature_source not in VISION_FEATURE_SOURCES: continue if feature_source not in encoders: cfg = MODEL_CONFIGS[feature_source] encoders[feature_source] = VisionEncoder( feature_source=feature_source, model_name=cfg["hf_id"], device=resolve_device(device), ) encoder = encoders[feature_source] for episode_id in episode_ids: out_path = feature_episode_path(feature_root, feature_source, task, demo, episode_id) if out_path.exists() and not overwrite: print(f"skip existing {out_path}", flush=True) written.append(out_path) continue label_path, video_path, _ = resolve_episode_paths( task, demo, episode_id, label_root, video_root, label_kind, validation_index, ) T = concept_steps(label_path) from probe_common import ffprobe_video video_meta = ffprobe_video(video_path) V = int(video_meta["video_frames"]) features, mapped_frames = extract_concept_aligned_features( encoder, video_path, T, V, pool_radius=pool_radius, batch_size=batch_size, ) write_feature_h5( out_path, features, feature_source=feature_source, model_name=encoder.model_name, task=task, demo=demo, episode_id=episode_id, concept_count=T, video_frames=V, pool_radius=pool_radius, mapped_frames=mapped_frames, label_path=label_path, video_path=video_path, ) print(f"wrote {out_path} shape={features.shape}", flush=True) written.append(out_path) return written def import_external_features( src_path: Path, feature_root: Path, feature_source: str, task: str, demo: str, episode_id: int, *, label_path: Path | None = None, video_path: Path | None = None, ) -> Path: """Copy user-provided latent_action / univla arrays into the standard layout.""" arr = load_precomputed_features(src_path) out_path = feature_episode_path(feature_root, feature_source, task, demo, episode_id) mapped = np.arange(arr.shape[0], dtype=np.int32) write_feature_h5( out_path, arr, feature_source=feature_source, model_name=str(src_path), task=task, demo=demo, episode_id=episode_id, concept_count=int(arr.shape[0]), video_frames=int(arr.shape[0]), pool_radius=0, mapped_frames=mapped, label_path=label_path or Path(""), video_path=video_path or Path(""), ) return out_path