Spaces:
Running on Zero

File size: 5,308 Bytes
a863b67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from typing import Dict, Tuple

import torch
import torch.nn as nn

from .dpt_head import DPTHead
from .geometry import geotrf, solve_transfm
from .geometry_blocks import GeometryBlocks
from .motion_blocks import MotionBlocks


class Flow4RT(nn.Module):
    """Flow4RT.

    Geometry blocks (a ViT-g) process all views jointly. At each of four read-out layers, motion
    blocks map the tokens of a source view toward its target view (viewpoint and time). A shared
    DPT head decodes the geometry branch into a local point map P with confidence C, and the
    motion branch into a displaced point map P_vt with rigidity W. The rigidity-weighted rigid
    alignment of P to P_vt gives the relative camera pose T, which separates scene flow into
    camera motion and object motion.
    """

    PATCH_SIZE = 14

    def __init__(self, motion_depth: int = 8):
        super().__init__()
        self.geometry_blocks = GeometryBlocks()
        self.motion_blocks = MotionBlocks(dim=1536, depth=motion_depth)
        self.head = DPTHead(dim_in=1536, output_dim=4)

    @classmethod
    def from_pretrained(cls, path: str, device="cpu", **kwargs) -> "Flow4RT":
        """Loads weights from a `.safetensors` file or a training checkpoint (`.pth`)."""
        model = cls(**kwargs)
        if path.endswith(".safetensors"):
            from safetensors.torch import load_file
            state_dict = load_file(path)
        else:
            state_dict = torch.load(path, map_location="cpu", weights_only=False, mmap=True)
            state_dict = state_dict.get("model", state_dict)
        model.load_state_dict(state_dict, strict=True)
        return model.to(device).eval()

    def forward(self, views: Dict[str, torch.Tensor]) -> Tuple[Dict[str, torch.Tensor], Dict[str, torch.Tensor]]:
        """
        Args:
            views: dict with
                img:        (B, V, 3, H, W) images in [-1, 1]; H and W multiples of 14.
                target_idx: (B, V) long, the target view of each view.
        Returns:
            (pred_src, pred_tgt), dicts of (B, V, ...) tensors. For view i with target j:
              pred_src: view i as the source, toward j;  pred_tgt: view j as the source, toward i.
              Names follow the paper's notation (P, C, P_vt, W, T, P_v, P_t).
              pts3d        P     local point map: source viewpoint, source time
              conf         C     confidence of P
              pts3d_vt     P_vt  displaced point map: target viewpoint, target time
              rigidity     W     rigidity map, sums to 1 over the pixels of each view
              camera_pose  T     (B, V, 4, 4) relative pose (source -> target camera), solved
                                 from P, P_vt and W by weighted rigid alignment
              pts3d_v      P_v   target viewpoint, source time (T P)
              pts3d_t      P_t   source viewpoint, target time (T^-1 P_vt)
        """
        images = views["img"]
        target_idx = views["target_idx"]
        B, V, _, H, W = images.shape
        x = (images + 1) / 2  # the geometry blocks take images in [0, 1]

        geometry_tokens, motion_tokens = [], []
        for level, (patches, cls_token, time_token) in enumerate(self.geometry_blocks(x)):
            geometry_tokens.append(patches.flatten(0, 1))  # (B*V, P, C)
            tokens = torch.cat([cls_token.unsqueeze(2), time_token.unsqueeze(2), patches], dim=2)
            motion_tokens.append(self.motion_blocks(tokens, target_idx, level))  # (B*2V, P, C)

        with torch.autocast(device_type=images.device.type, dtype=torch.float32):
            pts3d, conf = self.head(geometry_tokens, (H, W))  # geometry branch, per view
            pts3d_vt, rigidity = self.head(motion_tokens, (H, W))  # motion branch, per (source, target)

            def with_target(t):  # (B*V, ...) -> (B*2V, ...): views followed by their targets
                t = t.reshape(B, V, *t.shape[1:])
                idx = target_idx.reshape(B, V, *([1] * (t.ndim - 2))).expand_as(t)
                return torch.cat([t, torch.gather(t, dim=1, index=idx)], dim=1).flatten(0, 1)

            out = {
                "pts3d": with_target(pts3d),
                "conf": with_target(1 + torch.exp(conf)),
                "pts3d_vt": pts3d_vt,
                "rigidity": rigidity.flatten(1).softmax(dim=1).view_as(rigidity),  # sums to 1 over pixels
            }
            pred_src, pred_tgt = {}, {}
            for k, v in out.items():
                pred_src[k], pred_tgt[k] = v.reshape(B, 2, V, *v.shape[1:]).unbind(dim=1)
            return self._postprocess(pred_src), self._postprocess(pred_tgt)

    @staticmethod
    def _postprocess(pred: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
        pts = pred["pts3d"].detach()
        pts_vt = pred["pts3d_vt"]
        rigidity = pred["rigidity"]

        # relative camera pose: rigidity-weighted alignment of the two pointmaps of the same pixels
        trf_cam = solve_transfm(pts.flatten(-3, -2), pts_vt.flatten(-3, -2).detach(), rigidity.flatten(-2, -1))
        pts_v = geotrf(trf_cam, pts)
        pts_t = geotrf(trf_cam.inverse(), pts_vt)
        pred["camera_pose"] = trf_cam  # (B, V, 4, 4): source camera -> target camera
        pred["pts3d_v"] = pts_v
        pred["pts3d_t"] = pts_t
        return pred