"""The WDM stable-UCPE query path without fbsource or training dependencies.""" from __future__ import annotations import json from dataclasses import dataclass, field from pathlib import Path import cv2 import numpy as np import torch import torch.nn.functional as F from evaluation.ucpe_inputs import ClipInput from nets.ucpe_cd50_stable.geometry import camera_diameter from nets.ucpe_cd50_stable.model import UCPECD50StableModel def normalize_images(images: torch.Tensor) -> torch.Tensor: mean = images.new_tensor([0.485, 0.456, 0.406]).reshape(1, 1, 3, 1, 1) std = images.new_tensor([0.229, 0.224, 0.225]).reshape(1, 1, 3, 1, 1) return (images / 255.0 - mean) / std def sample_patches(rgbs, uv, times, views, patch_size): height, width = rgbs.shape[-2:] half = patch_size // 2 dy, dx = torch.meshgrid( torch.arange(-half, half + 1, device=uv.device, dtype=uv.dtype), torch.arange(-half, half + 1, device=uv.device, dtype=uv.dtype), indexing="ij", ) grid = uv[:, None, None] + torch.stack([dx, dy], dim=-1) grid[..., 0] = 2.0 * grid[..., 0] / max(width - 1, 1) - 1.0 grid[..., 1] = 2.0 * grid[..., 1] / max(height - 1, 1) - 1.0 return F.grid_sample( rgbs[views.long(), times.long()], grid, mode="bilinear", padding_mode="border", align_corners=True, ) def camera_xyz_from_uv_depth(uv, depth, intrinsics): if uv.ndim != 3 or uv.shape[-1] != 2 or depth.shape != uv.shape[:2]: raise ValueError("Expected UV (T, N, 2) and depth (T, N)") if intrinsics.shape not in ((3, 3), (uv.shape[0], 3, 3)): raise ValueError("Expected intrinsics (3, 3) or (T, 3, 3)") uv = uv.float() depth = depth.to(uv) intrinsics = intrinsics.to(uv) homogeneous = torch.cat([uv, torch.ones_like(uv[..., :1])], dim=-1) if not all(bool(torch.isfinite(value).all()) for value in (uv, depth, intrinsics)): raise ValueError("UV-depth needs finite predictions and intrinsics") rays = torch.linalg.solve(intrinsics, homogeneous.transpose(-1, -2)).transpose( -1, -2 ) if bool((rays[..., 2] == 0).any()): raise ValueError("Intrinsics produced a ray parallel to the camera plane") xy = rays[..., :2] * (depth / rays[..., 2])[..., None] return torch.cat([xy, depth[..., None]], dim=-1) @dataclass(frozen=True) class Prediction: xyz: torch.Tensor uv_depth: torch.Tensor uv: torch.Tensor visibility: torch.Tensor confidence: torch.Tensor camera_ids: list metadata: dict = field(default_factory=dict) query_uv: torch.Tensor | None = None query_times: torch.Tensor | None = None query_views: torch.Tensor | None = None def save(self, path: str | Path) -> Path: path = Path(path).expanduser() path.parent.mkdir(parents=True, exist_ok=True) arrays = { name: getattr(self, name).detach().cpu().numpy() for name in ("xyz", "uv_depth", "uv", "visibility", "confidence") } for name in ("query_uv", "query_times", "query_views"): value = getattr(self, name) if value is not None: arrays[name] = value.detach().cpu().numpy() with path.open("xb") as handle: np.savez_compressed( handle, **arrays, metadata_json=json.dumps(self.metadata) ) return path class UCPEEvaluator: def __init__( self, model: UCPECD50StableModel, device: str | torch.device, *, decoder_chunk: int = 512, camera_gate_m: float | None = None, max_input_views: int = 3, ): if decoder_chunk <= 0: raise ValueError("decoder_chunk must be positive") if not 1 <= max_input_views <= getattr(model.decoder, "max_view_num", 3): raise ValueError("max_input_views exceeds decoder capacity") self.device = torch.device(device) self.model = model.to(self.device).eval() self.decoder_chunk = decoder_chunk self.camera_gate_m = camera_gate_m self.max_input_views = max_input_views @torch.inference_mode() def predict( self, clip: ClipInput, *, views: int = 1, camera: str = "on" ) -> Prediction: clip.validate() if camera not in ("on", "off") or not 1 <= views <= self.max_input_views: raise ValueError( f"Expected 1–{self.max_input_views} views and camera on/off" ) if clip.rgbs.shape[0] < views: raise ValueError("The clip does not contain enough configured views") size = self.model.encoder.model.patch_embed.img_size[0] native_frames = clip.rgbs.shape[1] frames = self.model.encoder.num_frames source = clip.rgbs[:views] poses = clip.cameras_to_world[:views].to(self.device).float() intrinsics = clip.intrinsics[:views].to(self.device).float() anchor = poses[0, 0] rotation = anchor[:3, :3].T world_to_anchor = torch.eye(4, device=self.device) world_to_anchor[:3, :3] = rotation world_to_anchor[:3, 3] = -(rotation @ anchor[:3, 3]) poses = world_to_anchor[None, None] @ poses up = ( None if clip.world_up is None else (rotation @ clip.world_up.to(self.device).float())[None] ) if camera == "on" and up is None: raise ValueError("Camera ON requires verified world up") if native_frames != frames: if ( clip.metadata["dataset_type"] != "dexycb_mv" or native_frames not in (24, 25) or frames != 48 ): raise ValueError( "Only native 24/25-frame DexYCB clips may repeat-pad to 48" ) def pad(value): return torch.cat( [ value, value[:, -1:].expand( -1, frames - native_frames, *value.shape[2:] ), ], dim=1, ) source, poses, intrinsics = pad(source), pad(poses), pad(intrinsics) height, width = source.shape[-2:] images = source.permute(0, 1, 3, 4, 2).cpu().numpy() resized = np.stack( [ np.stack( [ cv2.resize(frame, (size, size), interpolation=cv2.INTER_LINEAR) for frame in view ] ) for view in images ] ) rgbs = torch.as_tensor( resized, device=self.device, dtype=torch.float32 ).permute(0, 1, 4, 2, 3) pixel_cameras = ( torch.eye(4, device=self.device).expand(views, frames, 4, 4).clone() ) pixel_cameras[..., :3, :3] = intrinsics pixel_cameras[..., 0, 0] *= size / float(width) pixel_cameras[..., 1, 1] *= size / float(height) pixel_cameras[..., 0, 2] = (pixel_cameras[..., 0, 2] + 0.5) * ( size / float(width) ) - 0.5 pixel_cameras[..., 1, 2] = (pixel_cameras[..., 1, 2] + 0.5) * ( size / float(height) ) - 0.5 mask = torch.tensor([camera == "on"], device=self.device) if self.camera_gate_m is not None: diameter = camera_diameter(poses[None]) mask = mask & torch.isfinite(diameter) & (diameter <= self.camera_gate_m) with torch.autocast( self.device.type, dtype=torch.bfloat16, enabled=self.device.type == "cuda" ): features = self.model.encode( normalize_images(rgbs).permute(0, 2, 1, 3, 4)[None], poses[None], pixel_cameras[None], camera_condition_mask=mask, world_up=up, world_up_valid=None if up is None else torch.ones_like(up[:, 0], dtype=torch.bool), ) count = len(clip.query_times) padded_count = max(count, 512) uv = clip.query_uv.to(self.device).float() source_times = clip.query_times.to(self.device) source_views = clip.query_views.to(self.device) padding = padded_count - count if padding: uv = torch.cat([uv, uv.new_zeros(padding, 2)]) source_times = torch.cat( [source_times, source_times.new_full((padding,), int(source_times[0]))] ) source_views = torch.cat([source_views, source_views.new_zeros(padding)]) uv = uv[:, None].expand(-1, frames, -1).reshape(-1, 2).clone() uv[..., 0] += 0.5 - 0.5 * float(width) / size uv[..., 1] += 0.5 - 0.5 * float(height) / size uv[..., 0] *= size / float(width) uv[..., 1] *= size / float(height) source_times = source_times[:, None].expand(-1, frames).reshape(-1) source_views = source_views[:, None].expand(-1, frames).reshape(-1) target_times = ( torch.arange(frames, device=self.device)[None] .expand(padded_count, -1) .reshape(-1) ) xyz, uv_pred, visibility, confidence = [], [], [], [] for begin in range(0, count * frames, self.decoder_chunk): end = min(begin + self.decoder_chunk, padded_count * frames) patch_size = int( (self.model.decoder.image_patch_embed.in_features / 3) ** 0.5 ) patches = sample_patches( rgbs, uv[begin:end], source_times[begin:end], source_views[begin:end], patch_size, ) t_tgt = target_times[None, begin:end, None].float() with torch.autocast( self.device.type, dtype=torch.bfloat16, enabled=self.device.type == "cuda", ): outputs = self.model.decoder( uv=uv[None, begin:end], t_src=source_times[None, begin:end, None].float(), t_tgt=t_tgt, t_cam=t_tgt, image_patch=normalize_images(patches[:, None]).squeeze(1)[None], y=features, num_views=views, v_src=source_views[None, begin:end, None], ) xyz.append(outputs[0][0].float()) uv_pred.append(outputs[1][0].float()) visibility.append(outputs[2][0, :, 0].sigmoid().float()) confidence.append(outputs[5][0, :, 0].sigmoid().float()) def tracks(parts, dimensions=()): return ( torch.cat(parts)[: count * frames] .reshape(count, frames, *dimensions) .transpose(0, 1)[:native_frames] .cpu() ) xyz = tracks(xyz, (3,)) uv_pred = tracks(uv_pred, (2,)) uv_pred[..., 0] *= width - 1 uv_pred[..., 1] *= height - 1 return Prediction( xyz, camera_xyz_from_uv_depth(uv_pred, xyz[..., 2], clip.intrinsics[0]), uv_pred, tracks(visibility), tracks(confidence), clip.metadata["camera_ids"][:views], { **clip.metadata, "camera": camera, "encoded_camera_ids": clip.metadata["camera_ids"][:views], "coordinate_frame": "target_camera", }, clip.query_uv, clip.query_times, clip.query_views, )