File size: 11,707 Bytes
9c890d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
"""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,
        )