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 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
"""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