Lyndow's picture
Add verified ExoWrist test assets (201-300)
e302b11 verified
Raw History Blame Contribute Delete
3.01 kB
"""Shared frozen DINOv2 encoder utilities for offline and live inference."""
from __future__ import annotations
import warnings
from pathlib import Path
import cv2
import numpy as np
import torch
import torch.nn.functional as F
def load_local_dinov2(torch_home: Path, device: torch.device) -> torch.nn.Module:
"""Load the project-local DINOv2-B/14 source and weights without network access."""
repo = torch_home / "hub" / "facebookresearch_dinov2_main"
weights = torch_home / "hub" / "checkpoints" / "dinov2_vitb14_pretrain.pth"
if not repo.is_dir() or not weights.is_file():
raise FileNotFoundError(
"DINOv2-B/14 source or weights are missing from the project .cache/torch directory"
)
with warnings.catch_warnings():
warnings.filterwarnings("ignore", message="xFormers is not available")
model = torch.hub.load(str(repo), "dinov2_vitb14", source="local", pretrained=False)
state = torch.load(weights, map_location="cpu", weights_only=True)
model.load_state_dict(state)
return model.requires_grad_(False).eval().to(device)
def preprocess_frame(frame: np.ndarray, size: int) -> torch.Tensor:
"""Apply the exact letterbox and ImageNet normalization used for training."""
if frame is None or frame.ndim != 3 or frame.shape[2] != 3:
raise ValueError("expected a non-empty BGR image shaped [height, width, 3]")
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
height, width = rgb.shape[:2]
scale = min(size / width, size / height)
resized_width = max(1, round(width * scale))
resized_height = max(1, round(height * scale))
resized = cv2.resize(rgb, (resized_width, resized_height), interpolation=cv2.INTER_AREA)
canvas = np.empty((size, size, 3), dtype=np.uint8)
canvas[:] = np.array([124, 116, 104], dtype=np.uint8)
left = (size - resized_width) // 2
top = (size - resized_height) // 2
canvas[top:top + resized_height, left:left + resized_width] = resized
tensor = torch.from_numpy(canvas).permute(2, 0, 1).float().div_(255.0)
mean = torch.tensor([0.485, 0.456, 0.406])[:, None, None]
std = torch.tensor([0.229, 0.224, 0.225])[:, None, None]
return (tensor - mean) / std
def encode_batch(
model: torch.nn.Module,
batch: list[torch.Tensor],
device: torch.device,
) -> torch.Tensor:
"""Return normalized CLS+mean-patch features on CPU as float32."""
if not batch:
raise ValueError("cannot encode an empty image batch")
images = torch.stack(batch).to(device, non_blocking=True)
amp_enabled = device.type == "cuda"
with torch.inference_mode(), torch.autocast(
device_type=device.type,
dtype=torch.float16,
enabled=amp_enabled,
):
output = model.forward_features(images)
cls = output["x_norm_clstoken"]
patches = output["x_norm_patchtokens"].mean(dim=1)
embeddings = F.normalize(torch.cat((cls, patches), dim=1), dim=1)
return embeddings.float().cpu()