Spaces:
Sleeping

photo-culling / embed.py
Jayasurya23's picture
Scale GPU duration to input size (fixes illegal duration)
c20dd2c verified
Raw History Blame Contribute Delete
8.36 kB
"""Step 2 - two embedding models, both cached on disk.
DINOv3 -> clustering. Instance-level visual similarity; near-duplicates stay separable.
SigLIP -> context-prompt matching only. Loaded lazily, so no cost when no prompt is set.
DINOv3 is under Meta's DINOv3 licence, not Apache-2.0 - see NOTICE.md before redistributing.
"""
import json, logging, time
import runtime # noqa: F401 - MUST precede torch (see runtime.py)
import numpy as np
import torch
from PIL import Image
from config import (CACHE_DIR, DINO_CACHE, DINO_IDS_CACHE, DINO_MODEL, EMBED_BATCH,
HOSTED, SIGLIP_CACHE, SIGLIP_IDS_CACHE, SIGLIP_MODEL)
log = logging.getLogger(__name__)
runtime.pin_threads()
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
_dino = _siglip = None # (processor, model) tuples, built on first use
# Derived from the configured id rather than hard-coded, so log lines and progress labels
# cannot drift out of date the next time the backbone is swapped.
DINO_LABEL = DINO_MODEL.split("/")[-1].split("-pretrain")[0]
def _load_dino():
global _dino
if _dino is None:
from transformers import AutoImageProcessor, AutoModel
log.info("Loading %s on %s", DINO_MODEL, DEVICE)
proc = AutoImageProcessor.from_pretrained(DINO_MODEL)
model = AutoModel.from_pretrained(DINO_MODEL).to(DEVICE).eval()
_dino = (proc, model)
return _dino
def _load_siglip():
global _siglip
if _siglip is None:
from transformers import AutoProcessor, AutoModel
log.info("Loading %s on %s", SIGLIP_MODEL, DEVICE)
proc = AutoProcessor.from_pretrained(SIGLIP_MODEL)
model = AutoModel.from_pretrained(SIGLIP_MODEL).to(DEVICE).eval()
_siglip = (proc, model)
return _siglip
def _l2(a: np.ndarray) -> np.ndarray:
return a / np.clip(np.linalg.norm(a, axis=-1, keepdims=True), 1e-8, None)
def _tensor(out):
"""transformers <5 returns a tensor from get_*_features; >=5 returns an output object."""
if torch.is_tensor(out):
return out
for attr in ("pooler_output", "image_embeds", "text_embeds"):
if getattr(out, attr, None) is not None:
return getattr(out, attr)
return out.last_hidden_state[:, 0]
def _cached(npy, ids_path, ids):
"""Reuse only when the id list matches exactly."""
if not (npy.exists() and ids_path.exists()):
return None
try:
if json.loads(ids_path.read_text()) != ids:
return None
return np.load(npy)
except Exception:
return None
def _store(npy, ids_path, ids, emb):
CACHE_DIR.mkdir(parents=True, exist_ok=True)
np.save(npy, emb)
ids_path.write_text(json.dumps(ids))
def _batched(paths, progress, label, encode):
# Logged so the GPU_* constants above can be re-derived from real numbers instead of
# padding: the recommended setting is measured_max * 1.4, and this is the measurement.
t0 = time.perf_counter()
chunks = []
for start in range(0, len(paths), EMBED_BATCH):
batch = paths[start:start + EMBED_BATCH]
if progress:
progress(start / max(len(paths), 1), desc=f"{label} {start + 1}-{start + len(batch)}")
imgs = []
for p in batch:
try:
imgs.append(Image.open(p).convert("RGB"))
except Exception as exc:
log.warning("Embed failed for %s: %s - using grey", p, exc)
imgs.append(Image.new("RGB", (224, 224), (128, 128, 128)))
with torch.no_grad():
chunks.append(encode(imgs))
dt = time.perf_counter() - t0
n = max(len(paths), 1)
log.info("GPU %s: %d images in %.1fs (%.3f s/image) - declared %ds",
label, len(paths), dt, dt / n, _gpu_seconds(paths))
return _l2(np.concatenate(chunks).astype(np.float32))
# Measured on the Space's card: DINOv3-vitb16 at batch 16 runs well under 0.1 s/image once
# the weights are resident, and SigLIP is comparable. The constants below are deliberately
# padded past that - GPU_WARMUP covers the first-call weight stream into VRAM, and the
# per-image figure carries roughly 3x headroom over the measured rate - while still landing
# far under the old flat 180 s. A hosted visitor is capped at MAX_UPLOAD_FILES images, so
# the realistic worst case is ~40 s, not three minutes.
GPU_WARMUP = 25 # seconds: cold weight streaming + processor setup
GPU_PER_IMAGE = 0.25 # seconds per image, padded
GPU_CEILING = 90 # never request more than this, whatever the count
def _gpu_seconds(paths, *_args, **_kw) -> int:
n = len(paths) if paths is not None else 0
return int(min(GPU_WARMUP + GPU_PER_IMAGE * n, GPU_CEILING))
@runtime.GPU(duration=_gpu_seconds)
def _run_dino(paths, progress):
proc, model = _load_dino()
def encode(imgs):
px = proc(images=imgs, return_tensors="pt").to(DEVICE)
# Token 0 is the CLS token for both DINOv2 and DINOv3. DINOv3 also carries 4
# REGISTER tokens, but they sit at indices 1-4, after the CLS and before the patch
# tokens, so slicing index 0 is unaffected by them. (Verified on the v3 config:
# 201 tokens = 1 CLS + 4 registers + 196 patches at 224px/16.) Its pooler_output
# is the same vector once L2-normalised, so there is nothing to gain by switching.
return model(**px).last_hidden_state[:, 0].float().cpu().numpy()
return _batched(paths, progress, DINO_LABEL, encode)
def embed_visual(df, progress=None) -> np.ndarray:
"""DINOv3 CLS token per image. This is what clustering consumes.
The GPU decorator wraps the WHOLE pass rather than each batch: spaces.GPU runs the
decorated function in a forked worker, so gr.Progress callbacks from inside it never
reach the browser, and each entry/exit is a separate GPU attach. One attach for the
whole set is both faster and cheaper against the visitor's quota.
"""
ids = df["id"].tolist()
hit = _cached(DINO_CACHE, DINO_IDS_CACHE, ids)
if hit is not None:
log.info("Reusing cached %s embeddings for %d images", DINO_LABEL, len(ids))
return hit
emb = _run_dino(df["proxy_path"].tolist(), progress)
_store(DINO_CACHE, DINO_IDS_CACHE, ids, emb)
return emb
@runtime.GPU(duration=_gpu_seconds)
def _run_siglip(paths, progress):
proc, model = _load_siglip()
def encode(imgs):
px = proc(images=imgs, return_tensors="pt").to(DEVICE)
return _tensor(model.get_image_features(**px)).cpu().numpy()
return _batched(paths, progress, "SigLIP", encode)
def embed_image_siglip(df, progress=None) -> np.ndarray:
"""SigLIP image tower. Only called when a context prompt is present."""
ids = df["id"].tolist()
hit = _cached(SIGLIP_CACHE, SIGLIP_IDS_CACHE, ids)
if hit is not None:
log.info("Reusing cached SigLIP embeddings for %d images", len(ids))
return hit
emb = _run_siglip(df["proxy_path"].tolist(), progress)
_store(SIGLIP_CACHE, SIGLIP_IDS_CACHE, ids, emb)
return emb
if HOSTED:
# ZeroGPU requires models to reach `cuda` at ROOT MODULE LEVEL, not inside a
# @spaces.GPU function: outside the decorator a CUDA emulation layer accepts the
# placement, and the real transfer is done once at startup where it is optimised.
# Loading lazily inside the decorator still works but re-pays that cost on every GPU
# attach - the docs call it "significantly less efficient".
#
# Only the two models every session uses are warmed. OWLv2 (611 MB) stays lazy because
# detection is an opt-in mode, and warming it would add ~10 s to every cold start for a
# feature most visitors never touch.
log.info("HOSTED: warming %s + SigLIP onto %s at import", DINO_LABEL, DEVICE)
_load_dino()
_load_siglip()
@runtime.GPU(duration=15)
def embed_text(prompt: str) -> np.ndarray:
"""Decorated individually because score.compose() calls it from inside an otherwise
CPU-only function - hoisting it out would mean threading a tensor through the scorer."""
proc, model = _load_siglip()
tok = proc(text=[prompt], padding="max_length", truncation=True, return_tensors="pt").to(DEVICE)
with torch.no_grad():
feats = _tensor(model.get_text_features(**tok)).cpu().numpy()
return _l2(feats.astype(np.float32))[0]