"""Vision-language verification and target selection.
Each candidate region M_i is embedded with a dual encoder (CLIP, SigLIP 2, ...) after masking out
its background, and compared with the label set {d_j}:
S_ij = cos(V_i, t_j)
p(d_j|M_i) = softmax_j(tau * S_ij)
E(M_i) = -log sum_j exp(tau * S_ij) (energy; reject if > tau_e)
Theta_i = exp(-beta * ||Omega_i||)
o* = argmax_i Theta_i * c_i * max_j p(d_j|M_i) * sim(d_j, c)
with c_i the detector's own score and sim(d_j, c) the text similarity between a label and the user's
reference. Theta_i depends only on the region, so it acts as a per-region confidence factor in Eq. 9
(renormalising p * Theta over the labels would cancel it): degraded regions rank below clean ones.
"""
from __future__ import annotations
import logging
from collections.abc import Sequence
import numpy as np
from ..config import VerifierConfig
log = logging.getLogger(__name__)
def softmax(logits: np.ndarray) -> np.ndarray:
z = logits - logits.max(axis=-1, keepdims=True)
e = np.exp(z)
return e / e.sum(axis=-1, keepdims=True)
[docs]
def energy(logits: np.ndarray) -> np.ndarray:
"""E_i = -log sum_j exp(logit_ij), numerically stable."""
m = logits.max(axis=-1)
return -(m + np.log(np.exp(logits - m[..., None]).sum(axis=-1)))
[docs]
def select_scores(
probs: np.ndarray, label_sim: np.ndarray, theta: np.ndarray, det_scores: np.ndarray
) -> np.ndarray:
"""Per-region selection score of Eq. (9): Theta_i * c_i * max_j p_ij * sim_j."""
return theta * det_scores * (probs * label_sim[None, :]).max(axis=1)
class DualEncoderVerifier:
"""Hugging Face dual encoder (``AutoModel`` exposing image/text embeddings)."""
def __init__(self, cfg: VerifierConfig, device: str):
import torch
from transformers import AutoModel, AutoProcessor
assert cfg.model is not None
self.cfg = cfg
self.device = device
self.torch = torch
self.processor = AutoProcessor.from_pretrained(cfg.model)
self.model = AutoModel.from_pretrained(cfg.model).to(device).eval()
model_type = getattr(self.model.config, "model_type", "")
self._padding: str | bool = "max_length" if "siglip" in model_type else True
log.info("Verifier %s loaded on %s", cfg.model, device)
def embed(
self, crops: Sequence[np.ndarray], texts: Sequence[str]
) -> tuple[np.ndarray, np.ndarray, float, float]:
"""L2-normalised image and text embeddings plus the model's logit scale/bias."""
from PIL import Image
images = [Image.fromarray(c[:, :, ::-1]) for c in crops] # BGR -> RGB
inputs = self.processor(
text=list(texts), images=images, padding=self._padding, return_tensors="pt"
).to(self.device)
with self.torch.no_grad():
out = self.model(**inputs)
scale = (
self.model.logit_scale.exp().item() if hasattr(self.model, "logit_scale") else 1.0
)
bias = self.model.logit_bias.item() if hasattr(self.model, "logit_bias") else 0.0
img = out.image_embeds.float().cpu().numpy()
txt = out.text_embeds.float().cpu().numpy()
img /= np.linalg.norm(img, axis=1, keepdims=True) + 1e-12
txt /= np.linalg.norm(txt, axis=1, keepdims=True) + 1e-12
return img, txt, scale, bias
def score(
self, crops: Sequence[np.ndarray], labels: Sequence[str], query: str
) -> dict[str, np.ndarray]:
"""Return probs (N x M), energy (N), label_sim (M) for regions vs labels."""
img, txt, scale, bias = self.embed(crops, [*labels, query])
label_emb, query_emb = txt[:-1], txt[-1]
cos = img @ label_emb.T
if self.cfg.temperature is not None:
logits = cos / self.cfg.temperature
else:
logits = scale * cos + bias
label_sim = np.clip(label_emb @ query_emb, 0.0, 1.0)
return {
"probs": softmax(logits),
"energy": energy(logits),
"label_sim": label_sim,
"cos": cos,
}
def masked_crop(
image_bgr: np.ndarray,
box: tuple[float, float, float, float],
mask: np.ndarray | None,
margin: float,
) -> np.ndarray:
"""Crop the region with a margin; pixels outside the mask are set to the mean colour."""
h, w = image_bgr.shape[:2]
x1, y1, x2, y2 = box
mx, my = (x2 - x1) * margin, (y2 - y1) * margin
xa, ya = max(0, int(x1 - mx)), max(0, int(y1 - my))
xb, yb = min(w, int(np.ceil(x2 + mx))), min(h, int(np.ceil(y2 + my)))
crop = image_bgr[ya:yb, xa:xb].copy()
if mask is not None and crop.size:
sub = mask[ya:yb, xa:xb]
if sub.any():
crop[~sub] = crop[sub].mean(axis=0).astype(crop.dtype)
if crop.size == 0:
crop = np.zeros((2, 2, 3), dtype=image_bgr.dtype)
return crop