#!/usr/bin/env python3 """Frozen-encoder image features of every train/val/test pair of a training revision (resumable cache). The final model uses SigLIP 2 giant (pooled embedding + mean of last-layer tokens, 3,072-d) and Perception Encoder PE-Core bigG/14 448 px (image embedding, 1,280-d). Features are cached per backbone in /features_.npz (keys = view paths), which the CV, comparison and inference scripts read. python scripts/model/features/extract_backbone_features.py --manifest /metadata_manifest.csv \ --models siglip2_giant_384 pe_core_bigg14_448 """ from __future__ import annotations import sys as _sys from pathlib import Path as _Path _SCRIPTS = next(_p for _p in _Path(__file__).resolve().parents if _p.name == "scripts") _sys.path[:0] = [str(_SCRIPTS.parent), str(_SCRIPTS.parent / "models")] + [str(_d) for _d in sorted(_SCRIPTS.rglob("*")) if _d.is_dir() and _d.name != "__pycache__"] import argparse import time from concurrent.futures import ThreadPoolExecutor from pathlib import Path import numpy as np import pandas as pd from dataset_labels import DEFAULT_EXCLUDED BACKBONES = { # name: (family, model id, pretrained tag for open_clip) "dinov3_vits16": ("dinov3", "facebook/dinov3-vits16-pretrain-lvd1689m", None), # 21M "dinov3_vitb16": ("dinov3", "facebook/dinov3-vitb16-pretrain-lvd1689m", None), # 86M "dinov3_vitl16": ("dinov3", "facebook/dinov3-vitl16-pretrain-lvd1689m", None), # 300M "dinov3_vith16plus": ("dinov3", "facebook/dinov3-vith16plus-pretrain-lvd1689m", None), # 840M "dinov3_vit7b16": ("dinov3", "facebook/dinov3-vit7b16-pretrain-lvd1689m", None), # 6.7B (opt-in) "siglip2_so400m_384": ("siglip2", "google/siglip2-so400m-patch14-384", None), # 400M "siglip2_giant_384": ("siglip2", "google/siglip2-giant-opt-patch16-384", None), # 1B "openclip_vith14": ("openclip", "ViT-H-14", "laion2b_s32b_b79k"), # 630M "openclip_bigg14": ("openclip", "ViT-bigG-14", "laion2b_s39b_b160k"), # 1.8B # Meta Perception Encoder (2025), contrastive core model, 448 px; open_clip >= 2.32 loads it from the HF hub "pe_core_bigg14_448": ("openclip", "hf-hub:timm/PE-Core-bigG-14-448", None), # ~2B } DEFAULT = ["siglip2_giant_384", "pe_core_bigg14_448"] class Extractor: def __init__(self, name, device): import torch self.torch, self.device = torch, device self.family, model_id, tag = BACKBONES[name] dtype = torch.bfloat16 if device == "cuda" and torch.cuda.is_bf16_supported() else (torch.float16 if device == "cuda" else torch.float32) self.dtype = dtype if self.family == "openclip": import open_clip model, _, self.preprocess = open_clip.create_model_and_transforms(model_id, pretrained=tag) self.model = model.eval().to(device=device, dtype=dtype) else: from transformers import AutoImageProcessor, AutoModel try: self.processor = AutoImageProcessor.from_pretrained(model_id) model = AutoModel.from_pretrained(model_id, torch_dtype=dtype) except Exception as error: hint = ("DINOv3 is gated: accept the licence on https://huggingface.co/" + model_id + " and run 'huggingface-cli login'. If the architecture is unknown, update transformers " "(pip install -U transformers; DINOv3 needs >= 4.56)." if self.family == "dinov3" else "SigLIP 2 needs transformers >= 4.49 (pip install -U transformers).") raise RuntimeError(f"Could not load {model_id}: {error}\n{hint}") from error self.model = (model.vision_model if self.family == "siglip2" else model).eval().to(device) self.registers = int(getattr(self.model.config, "num_register_tokens", 0) or 0) def __call__(self, images): torch = self.torch with torch.inference_mode(): if self.family == "openclip": x = torch.stack([self.preprocess(im) for im in images]).to(self.device, self.dtype) return self.model.encode_image(x).float().cpu().numpy() pix = self.processor(images=images, return_tensors="pt")["pixel_values"].to(self.device, self.dtype) out = self.model(pixel_values=pix) h = out.last_hidden_state.float() if self.family == "dinov3": return torch.cat([h[:, 0], h[:, 1 + self.registers:].mean(1)], 1).cpu().numpy() return torch.cat([out.pooler_output.float(), h.mean(1)], 1).cpu().numpy() def load_image(path): from PIL import Image with Image.open(path) as im: return im.convert("RGB") def extract(name, paths, out_dir, batch, device): cache = out_dir / f"features_{name}.npz" done = {} for source in (cache.with_name(cache.stem + ".partial.npz"), cache): # a finished partial file wins if source.exists(): with np.load(source, allow_pickle=True) as z: # closed again: Windows cannot done = dict(zip(z["keys"], z["features"])) # replace a file that is open break todo = [p for p in paths if p not in done] partial = cache.with_name(cache.stem + ".partial.npz") if not todo and partial.exists(): # finished features left in a partial file: promote it for attempt in range(10): try: partial.replace(cache); break except PermissionError: if attempt == 9: raise time.sleep(1.0) if not todo: return done print(f"\n=== {name}: extracting {len(todo)} images ({len(done)} cached) ===", flush=True) ex, begun, last_save = Extractor(name, device), time.time(), time.time() def save(): tmp = cache.with_name(cache.stem + ".partial.npz") np.savez(tmp, keys=np.array(list(done), dtype=object), features=np.stack(list(done.values())).astype(np.float16)) for attempt in range(10): # Windows: scanners can hold the file briefly try: tmp.replace(cache); break except PermissionError: if attempt == 9: raise time.sleep(1.0) batches = [todo[i:i + batch] for i in range(0, len(todo), batch)] with ThreadPoolExecutor(8) as pool: load = lambda b: [load_image(p) for p in b] queue = [pool.submit(load, b) for b in batches[:4]] # bounded prefetch for n, b in enumerate(batches, 1): images = queue.pop(0).result() if n + 3 < len(batches): queue.append(pool.submit(load, batches[n + 3])) for p, f in zip(b, ex(images)): done[p] = f if n % 20 == 0: rate = n * batch / (time.time() - begun) print(f" {min(n * batch, len(todo))}/{len(todo)} {rate:.1f} img/s", flush=True) if time.time() - last_save > 300: save(); last_save = time.time() save() del ex import torch if torch.cuda.is_available(): torch.cuda.empty_cache() return done def main(): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--manifest", type=Path, required=True) p.add_argument("--output-dir", type=Path, default=Path("runs_main_all_datasets/backbone_compare")) p.add_argument("--models", nargs="+", default=DEFAULT, choices=sorted(BACKBONES)) p.add_argument("--batch-size", type=int, default=32) p.add_argument("--device", default="cuda") a = p.parse_args() f = pd.read_csv(a.manifest, low_memory=False) f = f[f.direct_aq_target_status.eq("ok") & ~f.training_dataset.astype(str).str.casefold().isin(DEFAULT_EXCLUDED) & f.split.isin(["train", "val", "test"])] paths = sorted(set(f.view_path.astype(str))) print(f"{len(f)} pairs, {len(paths)} images") a.output_dir.mkdir(parents=True, exist_ok=True) for name in a.models: extract(name, paths, a.output_dir, a.batch_size, a.device) print(f"{name}: {a.output_dir / f'features_{name}.npz'}") if __name__ == "__main__": main()