import numpy as np import torch from PIL import Image _DINOV2_MODEL = None _RAFT_MODEL = None def _resolve_device(device=None): if device is not None: return device return "cuda" if torch.cuda.is_available() else "cpu" def _load_dinov2(device="cpu"): global _DINOV2_MODEL if _DINOV2_MODEL is None: import timm model = timm.create_model("vit_small_patch14_dinov2.lvd142m", pretrained=True, num_classes=0, img_size=224) model = model.eval().to(device) _DINOV2_MODEL = model return _DINOV2_MODEL def _resize_frames(frames: list, height: int, width: int = None, keep_aspect_width_multiple_of: int = None): resized = [] for frame in frames: w, h = frame.size if width is None and keep_aspect_width_multiple_of is not None: scale = height / h new_w = max(keep_aspect_width_multiple_of, int(round(w * scale / keep_aspect_width_multiple_of)) * keep_aspect_width_multiple_of) else: new_w = width resized.append(frame.resize((new_w, height), Image.BILINEAR)) return resized def compute_dinov2_csim(frames: list, device=None) -> float: """Mean adjacent-frame cosine similarity of DINOv2 patch-token embeddings. Args: frames: list of PIL.Image frames. device: torch device override; defaults to cuda if available else cpu. Returns: scalar float in [-1, 1]; higher means more consistent frames. """ if len(frames) < 2: return 1.0 device = _resolve_device(device) model = _load_dinov2(device) frames224 = _resize_frames(frames, 224, 224) x = torch.stack([torch.from_numpy(np.asarray(f.convert("RGB"), dtype=np.float32) / 255.0).permute(2, 0, 1) for f in frames224]) mean = torch.tensor([0.485, 0.456, 0.406], dtype=torch.float32).view(1, 3, 1, 1) std = torch.tensor([0.229, 0.224, 0.225], dtype=torch.float32).view(1, 3, 1, 1) x = (x - mean) / std with torch.no_grad(): x = x.to(device=device, dtype=torch.float32) tokens = model.forward_features(x) # (B, 1+num_patches, dim), CLS first tokens = tokens[:, 1:] if tokens.shape[1] > 1 else tokens x_norm = torch.nn.functional.normalize(tokens.float(), p=2, dim=-1) sims = (x_norm[:-1] * x_norm[1:]).sum(dim=-1).mean(dim=-1) # (B-1,) csim = sims.mean().item() return float(csim) def _download_raft_small_weights(): """Download raft-small.pth from a HF mirror of the princeton-vl/RAFT weights.""" from huggingface_hub import hf_hub_download repo_candidates = [ ("ddrfan/RAFT", "raft-small.pth"), ] last_err = None for repo_id, filename in repo_candidates: try: return hf_hub_download(repo_id=repo_id, filename=filename) except Exception as e: last_err = e raise RuntimeError(f"Failed to download RAFT-small weights from HF mirrors: {last_err}") def _norm(c): return torch.nn.InstanceNorm2d(c, affine=False) class _RAFTLocal: """Self-contained RAFT-small implementation (hidden=96, iters=12, corr levels=4, radius=3) matching the princeton-vl/RAFT small checkpoint layout (bottleneck feature/context encoder + sep-conv update block), used when torch.hub cannot reach GitHub.""" class BottleneckBlock(torch.nn.Module): def __init__(self, in_planes, planes, stride=1): super().__init__() self.conv1 = torch.nn.Conv2d(in_planes, planes, 1) self.norm1 = _norm(planes) self.conv2 = torch.nn.Conv2d(planes, planes, 3, stride, 1) self.norm2 = _norm(planes) self.conv3 = torch.nn.Conv2d(planes, planes * 4, 1) self.norm3 = _norm(planes * 4) self.relu = torch.nn.ReLU(inplace=True) if stride != 1 or in_planes != planes * 4: self.downsample = torch.nn.Sequential( torch.nn.Conv2d(in_planes, planes * 4, 1, stride), _norm(planes * 4), ) else: self.downsample = None def forward(self, x): identity = x out = self.relu(self.norm1(self.conv1(x))) out = self.relu(self.norm2(self.conv2(out))) out = self.norm3(self.conv3(out)) if self.downsample is not None: identity = self.downsample(x) return self.relu(out + identity) class SmallEncoder(torch.nn.Module): def __init__(self, output_dim=128): super().__init__() self.conv1 = torch.nn.Conv2d(3, 32, 7, 2, 3) self.norm1 = _norm(32) self.relu1 = torch.nn.ReLU(inplace=True) self.layer1 = torch.nn.Sequential( _RAFTLocal.BottleneckBlock(32, 8, 1), _RAFTLocal.BottleneckBlock(32, 8, 1) ) self.layer2 = torch.nn.Sequential( _RAFTLocal.BottleneckBlock(32, 16, 2), _RAFTLocal.BottleneckBlock(64, 16, 1) ) self.layer3 = torch.nn.Sequential( _RAFTLocal.BottleneckBlock(64, 24, 2), _RAFTLocal.BottleneckBlock(96, 24, 1) ) self.conv2 = torch.nn.Conv2d(96, output_dim, 1) def forward(self, x): x = self.relu1(self.norm1(self.conv1(x))) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) return self.conv2(x) class CorrBlock: def __init__(self, fmap1, fmap2, num_levels=4, radius=3): self.num_levels = num_levels self.radius = radius self.corr_pyramid = [] corr = self._correlation(fmap1, fmap2) batch, h1, w1, h2, w2 = corr.shape corr = corr.reshape(batch * h1 * w1, 1, h2, w2) self.corr_pyramid.append(corr) for _ in range(num_levels - 1): corr = torch.nn.functional.avg_pool2d(corr, 2, stride=2) self.corr_pyramid.append(corr) def _correlation(self, fmap1, fmap2): batch, dim, ht, wd = fmap1.shape fmap1 = fmap1.view(batch, dim, ht * wd) fmap2 = fmap2.view(batch, dim, ht * wd) corr = torch.matmul(fmap1.transpose(1, 2), fmap2) corr = corr.view(batch, ht, wd, ht, wd) / torch.sqrt(torch.tensor(dim).float()) return corr def __call__(self, coords): r = self.radius b, _, h1, w1 = coords.shape out_pyramid = [] for i in range(self.num_levels): corr = self.corr_pyramid[i] dx = torch.linspace(-r, r, 2 * r + 1, device=coords.device) dy = torch.linspace(-r, r, 2 * r + 1, device=coords.device) delta = torch.stack(torch.meshgrid(dy, dx, indexing="ij"), axis=-1).to(coords.dtype) centroid_lvl = coords.reshape(b * h1 * w1, 1, 1, 2) / 2 ** i delta_lvl = delta.view(1, 2 * r + 1, 2 * r + 1, 2) coords_lvl = centroid_lvl + delta_lvl corr = self._bilinear_sampler(corr, coords_lvl) corr = corr.view(b, h1, w1, -1) out_pyramid.append(corr) out = torch.cat(out_pyramid, dim=-1) return out.permute(0, 3, 1, 2).contiguous().float() @staticmethod def _bilinear_sampler(img, coords, mode="bilinear", mask=False): h, w = img.shape[-2:] grid = coords.clone() grid[..., 0] = 2 * grid[..., 0] / (w - 1) - 1 grid[..., 1] = 2 * grid[..., 1] / (h - 1) - 1 img = torch.nn.functional.grid_sample(img, grid, align_corners=True) if mask: valid = ((grid[..., 0] > -1) & (grid[..., 0] < 1) & (grid[..., 1] > -1) & (grid[..., 1] < 1)).float() img = torch.cat([img, valid.unsqueeze(1)], dim=1) return img class SmallMotionEncoder(torch.nn.Module): def __init__(self, corr_planes): super().__init__() self.convc1 = torch.nn.Conv2d(corr_planes, 96, 1, padding=0) self.normc1 = _norm(96) self.convf1 = torch.nn.Conv2d(2, 64, 7, padding=3) self.normf1 = _norm(64) self.convf2 = torch.nn.Conv2d(64, 32, 3, padding=1) self.normf2 = _norm(32) self.conv = torch.nn.Conv2d(96 + 32, 80, 3, padding=1) self.norm = _norm(80) self.relu = torch.nn.ReLU(inplace=True) def forward(self, flow, corr): cor = self.relu(self.normc1(self.convc1(corr))) flo = self.relu(self.normf1(self.convf1(flow))) flo = self.relu(self.normf2(self.convf2(flo))) return self.relu(self.norm(self.conv(torch.cat([cor, flo], dim=1)))) class ConvGRU(torch.nn.Module): def __init__(self, hidden_dim, input_dim): super().__init__() self.convz = torch.nn.Conv2d(hidden_dim + input_dim, hidden_dim, 3, padding=1) self.convr = torch.nn.Conv2d(hidden_dim + input_dim, hidden_dim, 3, padding=1) self.convq = torch.nn.Conv2d(hidden_dim + input_dim, hidden_dim, 3, padding=1) def forward(self, h, x): hx = torch.cat([h, x], dim=1) z = torch.sigmoid(self.convz(hx)) r = torch.sigmoid(self.convr(hx)) q = torch.relu(self.convq(torch.cat([r * h, x], dim=1))) return (1 - z) * h + z * q class FlowHead(torch.nn.Module): def __init__(self, input_dim=128, hidden_dim=256): super().__init__() self.conv1 = torch.nn.Conv2d(input_dim, hidden_dim, 3, padding=1) self.conv2 = torch.nn.Conv2d(hidden_dim, 2, 3, padding=1) self.relu = torch.nn.ReLU(inplace=True) def forward(self, x): return self.conv2(self.relu(self.conv1(x))) class SmallUpdateBlock(torch.nn.Module): def __init__(self, hidden_dim=96, context_dim=64, corr_planes=196): super().__init__() self.encoder = _RAFTLocal.SmallMotionEncoder(corr_planes) self.gru = _RAFTLocal.ConvGRU(hidden_dim=hidden_dim, input_dim=context_dim + 80 + 2) self.flow_head = _RAFTLocal.FlowHead(hidden_dim, 128) def forward(self, net, inp, corr, flow): motion_features = self.encoder(flow, corr) x = torch.cat([inp, motion_features, flow], dim=1) net = self.gru(net, x) return net, self.flow_head(net) class RAFTSmall(torch.nn.Module): def __init__(self): super().__init__() self.hidden_dim = 96 self.context_dim = 64 self.corr_levels = 4 self.corr_radius = 3 self.iters = 12 corr_planes = self.corr_levels * (2 * self.corr_radius + 1) ** 2 self.fnet = _RAFTLocal.SmallEncoder(output_dim=128) self.cnet = _RAFTLocal.SmallEncoder(output_dim=self.hidden_dim + self.context_dim) self.update_block = _RAFTLocal.SmallUpdateBlock(self.hidden_dim, self.context_dim, corr_planes) def forward(self, image1, image2, iters=None, flow_init=None): iters = iters or self.iters image1 = image1.contiguous() image2 = image2.contiguous() hdim, cdim = self.hidden_dim, self.context_dim fmap1, fmap2 = self.fnet(image1), self.fnet(image2) corr_block = _RAFTLocal.CorrBlock(fmap1, fmap2, num_levels=self.corr_levels, radius=self.corr_radius) cnet = self.cnet(image1) net, inp = torch.split(cnet, [hdim, cdim], dim=1) net = torch.tanh(net) inp = torch.relu(inp) coords0, coords1 = self._coords_grid(fmap1.shape[0], fmap1.shape[2], fmap1.shape[3], image1.device) if flow_init is not None: coords1 = coords1 + flow_init flow_predictions = [] for _ in range(iters): coords1 = coords1.detach() corr = corr_block(coords1) flow = coords1 - coords0 net, delta_flow = self.update_block(net, inp, corr, flow) coords1 = coords1 + delta_flow flow_predictions.append(coords1 - coords0) return flow_predictions @staticmethod def _coords_grid(batch, ht, wd, device): coords = torch.meshgrid(torch.arange(ht, device=device), torch.arange(wd, device=device), indexing="ij") coords = torch.stack(coords[::-1], dim=0).float() return coords[None].repeat(batch, 1, 1, 1), coords[None].repeat(batch, 1, 1, 1) @staticmethod def load(device): weights_path = _download_raft_small_weights() model = _RAFTLocal.RAFTSmall() state_dict = torch.load(weights_path, map_location=device) state_dict = {k.replace("module.", "", 1) if k.startswith("module.") else k: v for k, v in state_dict.items()} model.load_state_dict(state_dict) return model.eval().to(device) def _load_raft(device="cpu"): global _RAFT_MODEL if _RAFT_MODEL is None: model = None try: model = torch.hub.load("princeton-vl/RAFT", "small", pretrained=True, trust_repo=True) model = model.eval().to(device) except Exception as e: print(f"[RAFT] torch.hub load failed ({e}); falling back to local RAFT-small implementation.") model = _RAFTLocal.load(device) _RAFT_MODEL = model return _RAFT_MODEL def compute_raft_flow(frames: list, device=None, max_pairs: int = None) -> dict: """Optical-flow statistics between adjacent frames using RAFT-small. Args: frames: list of PIL.Image frames. device: torch device override; defaults to cuda if available else cpu. max_pairs: cap on adjacent pairs evaluated (pairs are evenly subsampled). Returns: dict with "flow_mean" (global mean flow magnitude) and "flow_std" (std of flow magnitudes, a proxy for temporal smoothness). """ if len(frames) < 2: return {"flow_mean": 0.0, "flow_std": 0.0} device = _resolve_device(device) model = _load_raft(device) frames_r = _resize_frames(frames, 256, keep_aspect_width_multiple_of=8) x = torch.stack([torch.from_numpy(np.asarray(f.convert("RGB"), dtype=np.float32)).permute(2, 0, 1) for f in frames_r]) x = x.unsqueeze(0) # (1, T, 3, H, W) num_pairs = x.shape[1] - 1 pair_ids = list(range(num_pairs)) if max_pairs is not None and num_pairs > max_pairs: stride = num_pairs / max_pairs pair_ids = sorted(set(int(i * stride) for i in range(max_pairs))) mags = [] with torch.no_grad(): x = x.to(device=device, dtype=torch.float32) for i in pair_ids: image1 = x[:, i] * 2 - 1 image2 = x[:, i + 1] * 2 - 1 flow_preds = model(image1, image2, iters=12) flow = flow_preds[-1][0] # (2, H, W) mag = torch.sqrt((flow ** 2).sum(dim=0) + 1e-12) mags.append(mag.flatten()) mags = torch.cat(mags) return { "flow_mean": float(mags.mean().item()), "flow_std": float(mags.std().item()), } class DINOv2FrameConsistency: """Wrapper class with a Metric-like callable interface.""" def __call__(self, frames: list) -> float: return compute_dinov2_csim(frames) class RAFTFlowMetric: """Wrapper class with a Metric-like callable interface.""" def __call__(self, frames: list) -> dict: return compute_raft_flow(frames)